Skip to main content

lua_rs_lfs/
lib.rs

1//! Rust-native implementation of the LuaFileSystem (lfs) module.
2//!
3//! Provides the lfs functions LuaRocks actually uses:
4//!
5//! | function                         | std::fs / std::env equivalent      |
6//! |----------------------------------|------------------------------------|
7//! | `lfs.attributes(path [, req])`   | `std::fs::metadata(path)`          |
8//! | `lfs.dir(path)`                  | `std::fs::read_dir(path)`          |
9//! | `lfs.mkdir(path)`                | `std::fs::create_dir(path)`        |
10//! | `lfs.rmdir(path)`                | `std::fs::remove_dir(path)`        |
11//! | `lfs.chdir(path)`                | `std::env::set_current_dir(path)`  |
12//! | `lfs.currentdir()`               | `std::env::current_dir()`          |
13//! | `lfs.touch(path [,a [,m]])`      | `filetime::set_file_times`         |
14//! | `lfs.link(old, new [, sym])`     | `std::fs::hard_link` / `symlink`   |
15//! | `lfs.lock_dir(path)`             | atomic `lockfile.lfs` creation     |
16//!
17//! Out of scope (LuaRocks does not exercise these): `lfs.lock`, `lfs.unlock`,
18//! `lfs.symlinkattributes`, `lfs.setmode`.
19//!
20//! Registration: the entry point [`luaopen_lfs`] builds and returns the lfs
21//! table. `lua-cli` installs that function in `package.preload.lfs` after
22//! `open_libs` and before user code runs, so `require('lfs')` resolves via
23//! the preload searcher and the rest of the lfs API ends up where stock lfs
24//! users expect to find it.
25
26use std::cell::RefCell;
27use std::collections::HashMap;
28use std::io::Write;
29use std::path::{Path, PathBuf};
30use std::time::{SystemTime, UNIX_EPOCH};
31
32use lua_types::error::LuaError;
33use lua_types::value::LuaValue;
34use lua_vm::state::LuaState;
35
36/// Each `lfs.dir` call allocates one zero-sized userdata to act as the
37/// iterator handle; the real iterator state lives in this side-table keyed by
38/// the userdata's identity. The same pattern is used by `lua-stdlib`'s
39/// `io_lib` because Lua's userdata payload is `Box<[u8]>` and cannot hold
40/// arbitrary Rust types directly.
41///
42/// Entries are inserted by `lfs_dir` and cleaned up either when the iterator
43/// is exhausted or when the userdata's metatable `__gc` handler runs.
44struct DirIterState {
45    iter: Option<std::fs::ReadDir>,
46}
47
48thread_local! {
49    static DIR_ITER_REGISTRY: RefCell<HashMap<usize, DirIterState>> =
50        RefCell::new(HashMap::new());
51}
52
53/// Convert a byte-string path argument (as Lua sees it) to a `PathBuf`. On
54/// Unix this is the zero-copy path that preserves non-UTF-8 byte sequences;
55/// on non-Unix targets we fall back to UTF-8 and surface a runtime error if
56/// the bytes are not valid UTF-8.
57fn path_from_bytes(bytes: &[u8]) -> Result<PathBuf, LuaError> {
58    #[cfg(unix)]
59    {
60        use std::os::unix::ffi::OsStrExt;
61        Ok(PathBuf::from(std::ffi::OsStr::from_bytes(bytes)))
62    }
63    #[cfg(not(unix))]
64    {
65        let s = std::str::from_utf8(bytes)
66            .map_err(|_| LuaError::runtime(format_args!("path is not valid UTF-8")))?;
67        Ok(PathBuf::from(s))
68    }
69}
70
71/// Returns the byte representation of a `Path` suitable for handing back to
72/// Lua. Unix preserves raw bytes; other platforms lossy-convert through
73/// UTF-8.
74fn path_to_bytes(p: &Path) -> Vec<u8> {
75    #[cfg(unix)]
76    {
77        use std::os::unix::ffi::OsStrExt;
78        p.as_os_str().as_bytes().to_vec()
79    }
80    #[cfg(not(unix))]
81    {
82        p.to_string_lossy().into_owned().into_bytes()
83    }
84}
85
86/// Push a failure result of the form `(nil, errmsg)` and return `2`, matching
87/// the convention every lfs function uses when an underlying syscall fails.
88fn push_fail(state: &mut LuaState, msg: &str) -> Result<usize, LuaError> {
89    state.push(LuaValue::Nil);
90    state.push_string(msg.as_bytes())?;
91    Ok(2)
92}
93
94// ─── lfs.currentdir ────────────────────────────────────────────────────────
95
96/// Push the absolute path of the current working directory, or
97/// `(nil, errmsg)` on failure. C-lfs: `lfs_currentdir`.
98fn lfs_currentdir(state: &mut LuaState) -> Result<usize, LuaError> {
99    match std::env::current_dir() {
100        Ok(p) => {
101            let bytes = path_to_bytes(&p);
102            state.push_string(&bytes)?;
103            Ok(1)
104        }
105        Err(e) => push_fail(state, &e.to_string()),
106    }
107}
108
109// ─── lfs.chdir ─────────────────────────────────────────────────────────────
110
111/// Change the current working directory. Returns `true` on success, or
112/// `(nil, errmsg)` on failure. C-lfs: `lfs_chdir`.
113fn lfs_chdir(state: &mut LuaState) -> Result<usize, LuaError> {
114    let path = path_from_bytes(&state.check_arg_string(1)?)?;
115    match std::env::set_current_dir(&path) {
116        Ok(()) => {
117            state.push(LuaValue::Bool(true));
118            Ok(1)
119        }
120        Err(e) => push_fail(
121            state,
122            &format!(
123                "Unable to change working directory to '{}': {}",
124                path.display(),
125                e
126            ),
127        ),
128    }
129}
130
131// ─── lfs.mkdir ─────────────────────────────────────────────────────────────
132
133/// Create a directory at `path`. Returns `true` on success, or
134/// `(nil, errmsg)` on failure. C-lfs: `make_dir`.
135fn lfs_mkdir(state: &mut LuaState) -> Result<usize, LuaError> {
136    let path = path_from_bytes(&state.check_arg_string(1)?)?;
137    match std::fs::create_dir(&path) {
138        Ok(()) => {
139            state.push(LuaValue::Bool(true));
140            Ok(1)
141        }
142        Err(e) => push_fail(state, &e.to_string()),
143    }
144}
145
146// ─── lfs.rmdir ─────────────────────────────────────────────────────────────
147
148/// Remove an empty directory at `path`. Returns `true` on success, or
149/// `(nil, errmsg)` on failure. C-lfs: `remove_dir`.
150fn lfs_rmdir(state: &mut LuaState) -> Result<usize, LuaError> {
151    let path = path_from_bytes(&state.check_arg_string(1)?)?;
152    match std::fs::remove_dir(&path) {
153        Ok(()) => {
154            state.push(LuaValue::Bool(true));
155            Ok(1)
156        }
157        Err(e) => push_fail(state, &e.to_string()),
158    }
159}
160
161// ─── lfs.link ──────────────────────────────────────────────────────────────
162
163/// Create either a hard link or a symbolic link from `new` to `old` depending
164/// on the optional third argument. Returns `true` on success or
165/// `(nil, errmsg)` on failure. C-lfs: `make_link`.
166///
167/// Argument order matches stock lfs: `lfs.link(old, new [, symlink])` —
168/// `old` is the existing target, `new` is the path of the link being created.
169fn lfs_link(state: &mut LuaState) -> Result<usize, LuaError> {
170    let old_path = path_from_bytes(&state.check_arg_string(1)?)?;
171    let new_path = path_from_bytes(&state.check_arg_string(2)?)?;
172    let symlink = lua_vm::api::to_boolean(state, 3);
173
174    let result = if symlink {
175        #[cfg(unix)]
176        {
177            std::os::unix::fs::symlink(&old_path, &new_path)
178        }
179        #[cfg(windows)]
180        {
181            if old_path.is_dir() {
182                std::os::windows::fs::symlink_dir(&old_path, &new_path)
183            } else {
184                std::os::windows::fs::symlink_file(&old_path, &new_path)
185            }
186        }
187        #[cfg(not(any(unix, windows)))]
188        {
189            Err(std::io::Error::new(
190                std::io::ErrorKind::Other,
191                "symlinks not supported on this platform",
192            ))
193        }
194    } else {
195        std::fs::hard_link(&old_path, &new_path)
196    };
197
198    match result {
199        Ok(()) => {
200            state.push(LuaValue::Bool(true));
201            Ok(1)
202        }
203        Err(e) => push_fail(state, &e.to_string()),
204    }
205}
206
207// ─── lfs.touch ─────────────────────────────────────────────────────────────
208
209/// Update the access and modification times of `path`. Both times default to
210/// the current wall-clock time if absent; if only the access time is given
211/// it is used for the modification time as well, matching stock lfs.
212/// C-lfs: `file_utime`.
213fn lfs_touch(state: &mut LuaState) -> Result<usize, LuaError> {
214    let path = path_from_bytes(&state.check_arg_string(1)?)?;
215
216    let now_secs: f64 = SystemTime::now()
217        .duration_since(UNIX_EPOCH)
218        .map(|d| d.as_secs_f64())
219        .unwrap_or(0.0);
220
221    let arg2_type = lua_vm::api::lua_type_at(state, 2);
222    let atime: f64 = match arg2_type {
223        lua_types::LuaType::None | lua_types::LuaType::Nil => now_secs,
224        _ => state.check_number(2)?,
225    };
226    let arg3_type = lua_vm::api::lua_type_at(state, 3);
227    let mtime: f64 = match arg3_type {
228        lua_types::LuaType::None | lua_types::LuaType::Nil => atime,
229        _ => state.check_number(3)?,
230    };
231
232    let atime_ft = filetime::FileTime::from_unix_time(
233        atime.trunc() as i64,
234        ((atime.fract().abs()) * 1_000_000_000.0) as u32,
235    );
236    let mtime_ft = filetime::FileTime::from_unix_time(
237        mtime.trunc() as i64,
238        ((mtime.fract().abs()) * 1_000_000_000.0) as u32,
239    );
240
241    match filetime::set_file_times(&path, atime_ft, mtime_ft) {
242        Ok(()) => {
243            state.push(LuaValue::Bool(true));
244            Ok(1)
245        }
246        Err(e) => push_fail(state, &e.to_string()),
247    }
248}
249
250// ─── lfs.lock_dir ─────────────────────────────────────────────────────────
251
252fn lfs_lock_free(state: &mut LuaState) -> Result<usize, LuaError> {
253    lua_vm::api::push_value(state, upvalue_index(1));
254    let lockfile = match state.pop() {
255        LuaValue::Str(s) => path_from_bytes(s.as_bytes())?,
256        _ => {
257            return Err(LuaError::runtime(format_args!(
258                "lfs.lock_dir: missing lockfile upvalue"
259            )));
260        }
261    };
262
263    match std::fs::remove_file(&lockfile) {
264        Ok(()) => {
265            state.push(LuaValue::Bool(true));
266            Ok(1)
267        }
268        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
269            state.push(LuaValue::Bool(true));
270            Ok(1)
271        }
272        Err(e) => push_fail(state, &e.to_string()),
273    }
274}
275
276/// `lfs.lock_dir(path)` — acquire a coarse directory lock.
277///
278/// LuaRocks uses LuaFileSystem's `lock_dir` by creating `path/lockfile.lfs`
279/// and later calling `lock:free()`.  We implement just that stock contract
280/// with `create_new(true)` so acquisition is atomic on the host filesystem.
281fn lfs_lock_dir(state: &mut LuaState) -> Result<usize, LuaError> {
282    let dir = path_from_bytes(&state.check_arg_string(1)?)?;
283    if let Err(e) = std::fs::create_dir_all(&dir) {
284        return push_fail(state, &e.to_string());
285    }
286
287    let lockfile = dir.join("lockfile.lfs");
288    match std::fs::OpenOptions::new()
289        .write(true)
290        .create_new(true)
291        .open(&lockfile)
292    {
293        Ok(mut file) => {
294            let _ = file.write_all(b"lock");
295        }
296        Err(e) => return push_fail(state, &e.to_string()),
297    }
298
299    state.create_table(0, 1)?;
300    let lockfile_bytes = path_to_bytes(&lockfile);
301    state.push_string(&lockfile_bytes)?;
302    lua_vm::api::push_cclosure(state, lfs_lock_free, 1)?;
303    lua_vm::api::set_field(state, -2, b"free")?;
304    Ok(1)
305}
306
307// ─── lfs.attributes ────────────────────────────────────────────────────────
308
309/// Translate `std::fs::FileType` to one of stock lfs's mode strings. The
310/// returned value is the byte form expected by the existing lfs ecosystem
311/// (`"file"`, `"directory"`, `"link"`, …).
312fn mode_string(ft: std::fs::FileType) -> &'static [u8] {
313    if ft.is_file() {
314        b"file"
315    } else if ft.is_dir() {
316        b"directory"
317    } else if ft.is_symlink() {
318        b"link"
319    } else {
320        #[cfg(unix)]
321        {
322            use std::os::unix::fs::FileTypeExt;
323            if ft.is_socket() {
324                return b"socket";
325            }
326            if ft.is_fifo() {
327                return b"named pipe";
328            }
329            if ft.is_char_device() {
330                return b"char device";
331            }
332            if ft.is_block_device() {
333                return b"block device";
334            }
335        }
336        b"other"
337    }
338}
339
340/// Convert a `SystemTime` to seconds-since-epoch as an integer, matching
341/// stock lfs's `time_t`-shaped fields. Negative durations (pre-epoch) become
342/// negative integers, exactly like C's `time_t`.
343fn system_time_to_secs(t: std::io::Result<SystemTime>) -> i64 {
344    match t {
345        Ok(st) => match st.duration_since(UNIX_EPOCH) {
346            Ok(d) => d.as_secs() as i64,
347            Err(e) => -(e.duration().as_secs() as i64),
348        },
349        Err(_) => 0,
350    }
351}
352
353/// Catalog of `attributes` field names → emitter. The emitter pushes the
354/// field's value onto the stack. Centralising the table avoids duplication
355/// between the full-table mode and the single-field request mode.
356fn push_attr_field(
357    state: &mut LuaState,
358    field: &[u8],
359    md: &std::fs::Metadata,
360) -> Result<bool, LuaError> {
361    match field {
362        b"mode" => {
363            state.push_string(mode_string(md.file_type()))?;
364        }
365        b"size" => {
366            state.push(LuaValue::Int(md.len() as i64));
367        }
368        b"modification" => {
369            state.push(LuaValue::Int(system_time_to_secs(md.modified())));
370        }
371        b"access" => {
372            state.push(LuaValue::Int(system_time_to_secs(md.accessed())));
373        }
374        b"change" => {
375            #[cfg(unix)]
376            {
377                use std::os::unix::fs::MetadataExt;
378                state.push(LuaValue::Int(md.ctime()));
379            }
380            #[cfg(not(unix))]
381            {
382                state.push(LuaValue::Int(system_time_to_secs(md.modified())));
383            }
384        }
385        b"permissions" => {
386            #[cfg(unix)]
387            {
388                use std::os::unix::fs::PermissionsExt;
389                let m = md.permissions().mode() & 0o777;
390                let mut buf = [b'-'; 9];
391                let bits = [
392                    (0o400, 0, b'r'),
393                    (0o200, 1, b'w'),
394                    (0o100, 2, b'x'),
395                    (0o040, 3, b'r'),
396                    (0o020, 4, b'w'),
397                    (0o010, 5, b'x'),
398                    (0o004, 6, b'r'),
399                    (0o002, 7, b'w'),
400                    (0o001, 8, b'x'),
401                ];
402                for (mask, idx, ch) in bits {
403                    if m & mask != 0 {
404                        buf[idx] = ch;
405                    }
406                }
407                state.push_string(&buf)?;
408            }
409            #[cfg(not(unix))]
410            {
411                let s = if md.permissions().readonly() {
412                    b"r--r--r--"
413                } else {
414                    b"rw-rw-rw-"
415                };
416                state.push_string(s)?;
417            }
418        }
419        b"nlink" => {
420            #[cfg(unix)]
421            {
422                use std::os::unix::fs::MetadataExt;
423                state.push(LuaValue::Int(md.nlink() as i64));
424            }
425            #[cfg(not(unix))]
426            {
427                state.push(LuaValue::Int(1));
428            }
429        }
430        b"uid" => {
431            #[cfg(unix)]
432            {
433                use std::os::unix::fs::MetadataExt;
434                state.push(LuaValue::Int(md.uid() as i64));
435            }
436            #[cfg(not(unix))]
437            {
438                state.push(LuaValue::Int(0));
439            }
440        }
441        b"gid" => {
442            #[cfg(unix)]
443            {
444                use std::os::unix::fs::MetadataExt;
445                state.push(LuaValue::Int(md.gid() as i64));
446            }
447            #[cfg(not(unix))]
448            {
449                state.push(LuaValue::Int(0));
450            }
451        }
452        b"dev" => {
453            #[cfg(unix)]
454            {
455                use std::os::unix::fs::MetadataExt;
456                state.push(LuaValue::Int(md.dev() as i64));
457            }
458            #[cfg(not(unix))]
459            {
460                state.push(LuaValue::Int(0));
461            }
462        }
463        b"rdev" => {
464            #[cfg(unix)]
465            {
466                use std::os::unix::fs::MetadataExt;
467                state.push(LuaValue::Int(md.rdev() as i64));
468            }
469            #[cfg(not(unix))]
470            {
471                state.push(LuaValue::Int(0));
472            }
473        }
474        b"ino" => {
475            #[cfg(unix)]
476            {
477                use std::os::unix::fs::MetadataExt;
478                state.push(LuaValue::Int(md.ino() as i64));
479            }
480            #[cfg(not(unix))]
481            {
482                state.push(LuaValue::Int(0));
483            }
484        }
485        b"blocks" => {
486            #[cfg(unix)]
487            {
488                use std::os::unix::fs::MetadataExt;
489                state.push(LuaValue::Int(md.blocks() as i64));
490            }
491            #[cfg(not(unix))]
492            {
493                state.push(LuaValue::Int(0));
494            }
495        }
496        b"blksize" => {
497            #[cfg(unix)]
498            {
499                use std::os::unix::fs::MetadataExt;
500                state.push(LuaValue::Int(md.blksize() as i64));
501            }
502            #[cfg(not(unix))]
503            {
504                state.push(LuaValue::Int(0));
505            }
506        }
507        _ => return Ok(false),
508    }
509    Ok(true)
510}
511
512/// `lfs.attributes(path [, request])` — `stat`-like introspection.
513///
514/// Three calling shapes match stock lfs:
515///   * one-arg: return a fresh table whose keys are every attribute name.
516///   * two-arg with a string request: return just that field.
517///   * two-arg with a table: populate the given table in place and return it.
518fn lfs_attributes(state: &mut LuaState) -> Result<usize, LuaError> {
519    let path = path_from_bytes(&state.check_arg_string(1)?)?;
520    let md = match std::fs::metadata(&path) {
521        Ok(m) => m,
522        Err(e) => {
523            return push_fail(
524                state,
525                &format!(
526                    "cannot obtain information from file '{}': {}",
527                    path.display(),
528                    e
529                ),
530            );
531        }
532    };
533
534    let arg2_type = lua_vm::api::lua_type_at(state, 2);
535    match arg2_type {
536        lua_types::LuaType::String => {
537            let req = state.check_arg_string(2)?;
538            if !push_attr_field(state, &req, &md)? {
539                return Err(LuaError::runtime(format_args!(
540                    "invalid attribute name '{}'",
541                    String::from_utf8_lossy(&req)
542                )));
543            }
544            Ok(1)
545        }
546        lua_types::LuaType::Table => {
547            lua_vm::api::push_value(state, 2);
548            populate_attr_table(state, &md)?;
549            Ok(1)
550        }
551        _ => {
552            state.create_table(0, 14)?;
553            populate_attr_table(state, &md)?;
554            Ok(1)
555        }
556    }
557}
558
559/// Fill the table on top of the stack with every attribute field. Used by the
560/// no-request and table-request branches of [`lfs_attributes`].
561fn populate_attr_table(state: &mut LuaState, md: &std::fs::Metadata) -> Result<(), LuaError> {
562    const FIELDS: &[&[u8]] = &[
563        b"mode",
564        b"size",
565        b"modification",
566        b"access",
567        b"change",
568        b"permissions",
569        b"nlink",
570        b"uid",
571        b"gid",
572        b"dev",
573        b"rdev",
574        b"ino",
575        b"blocks",
576        b"blksize",
577    ];
578    for field in FIELDS {
579        if !push_attr_field(state, field, md)? {
580            continue;
581        }
582        lua_vm::api::set_field(state, -2, field)?;
583    }
584    Ok(())
585}
586
587// ─── lfs.dir ───────────────────────────────────────────────────────────────
588
589/// Iterator step function — installed as a C closure with one upvalue
590/// (the userdata that owns the `ReadDir`). Each call returns the next
591/// directory entry's name as a string, or `nil` when exhausted.
592fn lfs_dir_next(state: &mut LuaState) -> Result<usize, LuaError> {
593    let ud_idx = upvalue_index(1);
594    lua_vm::api::push_value(state, ud_idx);
595    let v = state.pop();
596    let id = match v {
597        LuaValue::UserData(u) => u.identity(),
598        _ => {
599            return Err(LuaError::runtime(format_args!(
600                "lfs.dir iterator: missing handle upvalue"
601            )));
602        }
603    };
604
605    let next = DIR_ITER_REGISTRY.with(|reg| {
606        let mut map = reg.borrow_mut();
607        let entry = match map.get_mut(&id) {
608            Some(e) => e,
609            None => return None,
610        };
611        let iter = match entry.iter.as_mut() {
612            Some(i) => i,
613            None => return None,
614        };
615        loop {
616            match iter.next() {
617                Some(Ok(de)) => {
618                    let name = de.file_name();
619                    let bytes = {
620                        #[cfg(unix)]
621                        {
622                            use std::os::unix::ffi::OsStrExt;
623                            name.as_bytes().to_vec()
624                        }
625                        #[cfg(not(unix))]
626                        {
627                            name.to_string_lossy().into_owned().into_bytes()
628                        }
629                    };
630                    return Some(Some(bytes));
631                }
632                Some(Err(_)) => continue,
633                None => {
634                    entry.iter = None;
635                    return Some(None);
636                }
637            }
638        }
639    });
640
641    match next {
642        Some(Some(bytes)) => {
643            state.push_string(&bytes)?;
644            Ok(1)
645        }
646        _ => {
647            state.push(LuaValue::Nil);
648            Ok(1)
649        }
650    }
651}
652
653/// `lfs.dir(path)` — open the directory and return `(iterator, handle)`.
654///
655/// The iterator is a closure over a zero-byte userdata; the userdata's
656/// identity (a `usize` from `GcRef::identity`) is the side-table key holding
657/// the live `std::fs::ReadDir`. When the iterator function is later called,
658/// it re-reads the userdata via its upvalue and looks the iterator up.
659///
660/// Returning the handle as the second value matches stock lfs's signature —
661/// callers commonly write `for name in lfs.dir(path) do ... end` and never
662/// observe it, but a few rare scripts do.
663fn lfs_dir(state: &mut LuaState) -> Result<usize, LuaError> {
664    let path = path_from_bytes(&state.check_arg_string(1)?)?;
665    let iter = std::fs::read_dir(&path).map_err(|e| {
666        LuaError::runtime(format_args!(
667            "cannot open directory '{}': {}",
668            path.display(),
669            e
670        ))
671    })?;
672
673    let ud = state.new_userdata_typed(b"lfs.dir.handle", 0, 0)?;
674    let id = ud.identity();
675    DIR_ITER_REGISTRY.with(|reg| {
676        reg.borrow_mut()
677            .insert(id, DirIterState { iter: Some(iter) });
678    });
679
680    lua_vm::api::push_cclosure(state, lfs_dir_next, 1)?;
681    Ok(1)
682}
683
684// ─── Module entry point ────────────────────────────────────────────────────
685
686/// `lua_upvalueindex(i)` macro from `lua.h`. The duplicate in `lua-stdlib`'s
687/// state stub is module-private, so this crate keeps its own copy; a
688/// future cleanup could de-duplicate by exposing one canonical constant
689/// from `lua-vm`.
690fn upvalue_index(i: i32) -> i32 {
691    -1_001_000 - i
692}
693
694const LFS_FUNCS: &[(&[u8], fn(&mut LuaState) -> Result<usize, LuaError>)] = &[
695    (b"attributes", lfs_attributes),
696    (b"chdir", lfs_chdir),
697    (b"currentdir", lfs_currentdir),
698    (b"dir", lfs_dir),
699    (b"link", lfs_link),
700    (b"lock_dir", lfs_lock_dir),
701    (b"mkdir", lfs_mkdir),
702    (b"rmdir", lfs_rmdir),
703    (b"touch", lfs_touch),
704];
705
706/// Module entry point. Mirrors the stock lfs C signature
707/// `int luaopen_lfs(lua_State *L)` but at the Rust-native ABI used inside
708/// this workspace: builds the `lfs` table, populates it with the 8 functions
709/// above, and returns `1` to signal "one return value on the stack".
710///
711/// Installed in `package.preload.lfs` by `lua-cli`'s `main.rs`, so
712/// `require('lfs')` resolves the preload searcher and pushes this table.
713pub fn luaopen_lfs(state: &mut LuaState) -> Result<usize, LuaError> {
714    state.create_table(0, LFS_FUNCS.len() as i32)?;
715    for (name, func) in LFS_FUNCS {
716        lua_vm::api::push_cclosure(state, *func, 0)?;
717        lua_vm::api::set_field(state, -2, name)?;
718    }
719    Ok(1)
720}