Skip to main content

lua_stdlib/
io_lib.rs

1//! Standard I/O library — `io.*` functions and `file:*` methods.
2//!
3//! C source: `reference/lua-5.4.7/src/liolib.c`.
4//!
5//! **Impurity is host-provided and load-bearing.** Filesystem and process
6//! access reach the host only through hooks: regular files via
7//! `GlobalState::file_open_hook`, `io.popen` via `GlobalState::popen_hook`,
8//! stdout/stderr via output hooks. The native CLI installs hooks backed by
9//! `std::fs`/`std::process`/`std::io`; sandboxed and `wasm32` hosts leave those
10//! capabilities absent, and the functions then return a clean `(nil, msg,
11//! errno)` failure tuple (or, for the standard streams, an `Unsupported` error)
12//! instead of touching ambient OS state. That hook plumbing and the `wasm32`
13//! cfg gates are deliberately kept intact.
14//!
15//! **The side-table indirection** is the one structural divergence from C: C
16//! stores the `LStream` inside the userdata payload, but `LStream` carries heap
17//! pointers (a `Box<dyn LuaFileHandle>` and a fn pointer) that cannot be safely
18//! reinterpreted from a raw byte buffer in safe Rust, so the stream lives in a
19//! per-VM side table (`GlobalState::io_streams`) keyed by userdata identity,
20//! dropped with the VM (issue #317). Each I/O step
21//! borrows the file through its `Rc<RefCell<LStream>>` briefly, releases the
22//! borrow, then touches `LuaState` — resolving C's single `LStream *` aliasing
23//! into two scoped borrows.
24//!
25//! Graduation: the deterministic format-parsing/validation and error-shaping
26//! surface (read formats, the `*`-prefix version seam, the closed-file error,
27//! `io.type`) is pinned by `tests/io_strengthen.rs` against the reference
28//! binaries; host-specific I/O *results* are not reproducible and stay
29//! oracle-checked only through the official `files.lua` suite. See
30//! `crates/lua-stdlib/GRADUATED.md`.
31
32use std::cell::RefCell;
33use std::collections::HashMap;
34use std::io::{self, SeekFrom};
35use std::rc::Rc;
36
37use crate::state_stub::{LuaState, LuaStateStubExt as _};
38use lua_types::{LuaError, LuaFileHandle, LuaType, LuaValue};
39use lua_vm::state::{InputHook, OutputHook};
40
41/// Side-table mapping userdata identity (the `Rc` pointer address from
42/// `GcRef::identity()`) to its associated `LStream` (see the module header
43/// for why the stream lives here rather than inside the userdata payload).
44/// Entries are inserted by `new_pre_file` and never removed individually —
45/// a leak bounded by the owning VM's lifetime per `PORTING.md` §2 #4.
46type LStreamMap = RefCell<HashMap<usize, Rc<RefCell<LStream>>>>;
47
48/// Fetch this VM's `LStream` side table from [`GlobalState::io_streams`],
49/// lazily installing an empty map on first use. The table is per-VM state
50/// (issue #317): a process-wide `thread_local!` outlived the VMs that filled
51/// it, retaining one dead `LStream` per file userdata whose identity address
52/// was never reused — the leak canary's per-iteration VM-churn growth.
53///
54/// [`GlobalState::io_streams`]: lua_vm::state::GlobalState::io_streams
55fn lstream_registry(state: &LuaState) -> Rc<LStreamMap> {
56    let installed = state.global().io_streams.clone();
57    match installed {
58        Some(any) => any
59            .downcast::<LStreamMap>()
60            .expect("GlobalState::io_streams holds the io LStream side table"),
61        None => {
62            let fresh: Rc<LStreamMap> = Rc::new(RefCell::new(HashMap::new()));
63            state.global_mut().io_streams = Some(fresh.clone());
64            fresh
65        }
66    }
67}
68
69fn register_lstream(state: &LuaState, ud_id: usize, lstream: LStream) -> Rc<RefCell<LStream>> {
70    let cell = Rc::new(RefCell::new(lstream));
71    lstream_registry(state)
72        .borrow_mut()
73        .insert(ud_id, cell.clone());
74    cell
75}
76
77fn lookup_lstream(state: &LuaState, ud_id: usize) -> Option<Rc<RefCell<LStream>>> {
78    lstream_registry(state).borrow().get(&ud_id).cloned()
79}
80
81// ── Constants ────────────────────────────────────────────────────────────────
82
83/// Name of the file-handle metatable in the Lua registry. C: `LUA_FILEHANDLE`.
84pub const LUA_FILE_HANDLE: &[u8] = b"FILE*";
85
86/// Registry key for the default input file. C: `IO_INPUT` = `"_IO_input"`.
87const IO_INPUT_KEY: &[u8] = b"_IO_input";
88
89/// Registry key for the default output file. C: `IO_OUTPUT` = `"_IO_output"`.
90const IO_OUTPUT_KEY: &[u8] = b"_IO_output";
91
92/// Number of bytes in the `"_IO_"` prefix, used to strip it in error messages.
93const IO_PREFIX_LEN: usize = 4;
94
95/// Maximum number of format-arguments passed to `file:lines`. C: `MAXARGLINE`.
96const MAX_ARG_LINE: usize = 250;
97
98/// Maximum byte-length of a numeric literal read from a file. C: `L_MAXLENNUM`.
99const L_MAX_LEN_NUM: usize = 200;
100
101/// End-of-file sentinel returned by `LuaFileHandle::read_byte`. C: `EOF` == -1.
102const EOF_SENTINEL: i32 = -1;
103
104/// Bulk-read chunk size, mirroring C's `LUAL_BUFFERSIZE`.
105const LUAL_BUFFER_SIZE: usize = 8192;
106
107// ── Traits ───────────────────────────────────────────────────────────────────
108
109/// Capabilities required by the io library from an OS file handle.
110///
111/// This trait extends [`LuaFileHandle`] (defined in `lua-types`) with the
112/// additional `set_buf_mode` operation. Concrete implementations backed by
113/// `std::fs::File` live in `lua-cli`; standard-stream implementations live in
114/// this module. The split keeps `std::fs` out of `lua-stdlib` per PORTING.md §1.
115pub trait LuaFileOps: LuaFileHandle {
116    /// Control stream buffering. C: `setvbuf`.
117    fn set_buf_mode(&mut self, mode: BufMode, size: usize) -> io::Result<()>;
118}
119
120// ── Enums ────────────────────────────────────────────────────────────────────
121
122/// Seek anchor for `file:seek`. C: `{SEEK_SET, SEEK_CUR, SEEK_END}`.
123#[derive(Debug, Clone, Copy, PartialEq, Eq)]
124pub enum SeekWhence {
125    Set,
126    Cur,
127    End,
128}
129
130/// Buffering mode for `file:setvbuf`. C: `{_IONBF, _IOFBF, _IOLBF}`.
131#[derive(Debug, Clone, Copy, PartialEq, Eq)]
132pub enum BufMode {
133    No,
134    Full,
135    Line,
136}
137
138/// Which standard stream to wrap in `create_std_file`.
139pub enum StdFileKind {
140    Stdin,
141    Stdout,
142    Stderr,
143}
144
145// ── Structs ──────────────────────────────────────────────────────────────────
146
147/// A Lua file handle. C equivalent: `typedef luaL_Stream LStream`.
148///
149/// The instance lives in `LSTREAM_REGISTRY` (keyed by its userdata's identity),
150/// wrapped in `Rc<RefCell<…>>` so a brief file borrow and a `LuaState` borrow
151/// never overlap — the safe-Rust resolution of C's single `LStream *` pointer.
152pub struct LStream {
153    /// OS file handle. `None` = incompletely opened (the pre-file pattern).
154    /// Concrete implementations are installed via `GlobalState::file_open_hook`
155    /// (registered by `lua-cli`) to keep `std::fs` out of `lua-stdlib`.
156    pub file: Option<Box<dyn LuaFileHandle>>,
157    /// Close callback. `None` means the stream is closed. C: `p->closef == NULL`.
158    pub close_fn: Option<fn(&mut LuaState) -> Result<usize, LuaError>>,
159}
160
161impl LStream {
162    /// `isclosed(p)` in C: true when `closef` is NULL.
163    pub fn is_closed(&self) -> bool {
164        self.close_fn.is_none()
165    }
166}
167
168/// Standard stream handle for stdin/stdout/stderr.
169///
170/// Output goes through host hooks when installed. Native builds keep a direct
171/// stdio fallback for compatibility; bare `wasm32-unknown-unknown` reports
172/// unsupported instead of touching stubbed stdio.
173struct StdStreamHandle {
174    kind: StdFileKind,
175    input_hook: Option<InputHook>,
176    output_hook: Option<OutputHook>,
177    unread: Option<u8>,
178}
179
180impl LuaFileHandle for StdStreamHandle {
181    fn read_byte(&mut self) -> i32 {
182        if let Some(byte) = self.unread.take() {
183            return byte as i32;
184        }
185        match self.kind {
186            StdFileKind::Stdin => {
187                if let Some(read_fn) = self.input_hook {
188                    let mut buf = [0u8; 1];
189                    return match read_fn(&mut buf) {
190                        Ok(1) => buf[0] as i32,
191                        _ => EOF_SENTINEL,
192                    };
193                }
194
195                #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
196                {
197                    EOF_SENTINEL
198                }
199
200                #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
201                {
202                    use std::io::Read;
203                    let mut buf = [0u8; 1];
204                    match std::io::stdin().read(&mut buf) {
205                        Ok(1) => buf[0] as i32,
206                        _ => EOF_SENTINEL,
207                    }
208                }
209            }
210            _ => EOF_SENTINEL,
211        }
212    }
213    fn unread_byte(&mut self, byte: i32) {
214        if (0..=u8::MAX as i32).contains(&byte) {
215            self.unread = Some(byte as u8);
216        }
217    }
218    fn write_bytes(&mut self, data: &[u8]) -> io::Result<usize> {
219        if let Some(write_fn) = self.output_hook {
220            write_fn(data)?;
221            return Ok(data.len());
222        }
223
224        #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
225        {
226            let _ = data;
227            return Err(io::Error::new(
228                io::ErrorKind::Unsupported,
229                "standard output not available in this host",
230            ));
231        }
232
233        #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
234        {
235            use std::io::Write;
236            match self.kind {
237                StdFileKind::Stderr => {
238                    std::io::stderr().write_all(data)?;
239                    Ok(data.len())
240                }
241                _ => {
242                    std::io::stdout().write_all(data)?;
243                    Ok(data.len())
244                }
245            }
246        }
247    }
248    fn flush(&mut self) -> io::Result<()> {
249        if self.output_hook.is_some() {
250            return Ok(());
251        }
252
253        #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
254        {
255            return Err(io::Error::new(
256                io::ErrorKind::Unsupported,
257                "standard output not available in this host",
258            ));
259        }
260
261        #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
262        {
263            use std::io::Write;
264            match self.kind {
265                StdFileKind::Stderr => std::io::stderr().flush(),
266                _ => std::io::stdout().flush(),
267            }
268        }
269    }
270    fn seek(&mut self, _pos: SeekFrom) -> io::Result<u64> {
271        Err(io::Error::new(io::ErrorKind::Unsupported, "stdio seek"))
272    }
273    fn tell(&mut self) -> io::Result<u64> {
274        Err(io::Error::new(io::ErrorKind::Unsupported, "stdio tell"))
275    }
276    fn clear_error(&mut self) {}
277    fn has_error(&self) -> bool {
278        false
279    }
280}
281
282impl LuaFileOps for StdStreamHandle {
283    fn set_buf_mode(&mut self, _mode: BufMode, _size: usize) -> io::Result<()> {
284        Ok(())
285    }
286}
287
288impl StdStreamHandle {
289    fn new(
290        kind: StdFileKind,
291        input_hook: Option<InputHook>,
292        output_hook: Option<OutputHook>,
293    ) -> Self {
294        StdStreamHandle {
295            kind,
296            input_hook,
297            output_hook,
298            unread: None,
299        }
300    }
301}
302
303/// State machine for reading a numeric literal byte-by-byte from a file.
304struct ReadNumState {
305    /// Current look-ahead byte, or `EOF_SENTINEL`.
306    current: i32,
307    /// Number of bytes accumulated in `buf`.
308    count: usize,
309    /// Accumulated characters of the numeral (NUL-terminated on finalise).
310    buf: [u8; L_MAX_LEN_NUM + 1],
311}
312
313impl ReadNumState {
314    fn new(first_byte: i32) -> Self {
315        ReadNumState {
316            current: first_byte,
317            count: 0,
318            buf: [0u8; L_MAX_LEN_NUM + 1],
319        }
320    }
321
322    /// Save current char to `buf` and read the next byte from `file`.
323    /// Returns `false` if the buffer is full (numeral too long). C: `nextc`.
324    fn advance(&mut self, file: &mut dyn LuaFileHandle) -> bool {
325        if self.count >= L_MAX_LEN_NUM {
326            self.buf[0] = 0;
327            return false;
328        }
329        self.buf[self.count] = self.current as u8;
330        self.count += 1;
331        self.current = file.read_byte();
332        true
333    }
334
335    /// Accept current char if it equals either byte in `set`. C: `test2`.
336    fn try2(&mut self, file: &mut dyn LuaFileHandle, set: [u8; 2]) -> bool {
337        if self.current == set[0] as i32 || self.current == set[1] as i32 {
338            self.advance(file)
339        } else {
340            false
341        }
342    }
343
344    /// Consume a run of (hex)digits; return the count. C: `readdigits`.
345    fn read_digits(&mut self, file: &mut dyn LuaFileHandle, hex: bool) -> usize {
346        let mut count = 0usize;
347        loop {
348            let is_digit = if hex {
349                (self.current as u8).is_ascii_hexdigit()
350            } else {
351                (self.current as u8).is_ascii_digit()
352            };
353            if !is_digit || self.current == EOF_SENTINEL {
354                break;
355            }
356            if !self.advance(file) {
357                break;
358            }
359            count += 1;
360        }
361        count
362    }
363
364    /// Return the accumulated bytes (without the NUL terminator).
365    fn as_bytes(&self) -> &[u8] {
366        &self.buf[..self.count]
367    }
368}
369
370// ── Function registration tables ─────────────────────────────────────────────
371
372/// `io.*` module functions. C: `static const luaL_Reg iolib[]`.
373pub const IO_LIB: &[(&[u8], fn(&mut LuaState) -> Result<usize, LuaError>)] = &[
374    (b"close", io_close),
375    (b"flush", io_flush),
376    (b"input", io_input),
377    (b"lines", io_lines),
378    (b"open", io_open),
379    (b"output", io_output),
380    (b"popen", io_popen),
381    (b"read", io_read),
382    (b"tmpfile", io_tmpfile),
383    (b"type", io_type),
384    (b"write", io_write),
385];
386
387/// `file:*` instance methods. C: `static const luaL_Reg meth[]`.
388pub const FILE_METHODS: &[(&[u8], fn(&mut LuaState) -> Result<usize, LuaError>)] = &[
389    (b"read", f_read),
390    (b"write", f_write),
391    (b"lines", f_lines),
392    (b"flush", f_flush),
393    (b"seek", f_seek),
394    (b"close", f_close),
395    (b"setvbuf", f_setvbuf),
396];
397
398/// File-handle metamethods. C: `static const luaL_Reg metameth[]`.
399pub const FILE_METAMETHODS: &[(&[u8], fn(&mut LuaState) -> Result<usize, LuaError>)] = &[
400    (b"__gc", f_gc),
401    (b"__close", f_gc),
402    (b"__tostring", f_tostring),
403];
404
405// ── Helpers ──────────────────────────────────────────────────────────────────
406
407/// Validate an `fopen` mode string: must match `[rwa]\+?b*`. C: `l_checkmode`.
408///
409/// (*mode != '+' || ...) && strspn(mode, "b") == strlen(mode));`
410fn check_mode(mode: &[u8]) -> bool {
411    if mode.is_empty() {
412        return false;
413    }
414    let mut idx = 0usize;
415    if !matches!(mode[idx], b'r' | b'w' | b'a') {
416        return false;
417    }
418    idx += 1;
419    if idx < mode.len() && mode[idx] == b'+' {
420        idx += 1;
421    }
422    mode[idx..].iter().all(|&b| b == b'b')
423}
424
425/// Validate a `popen` mode string: only `"r"` or `"w"`. C: `l_checkmodep`.
426fn check_mode_popen(mode: &[u8]) -> bool {
427    matches!(mode, b"r" | b"w")
428}
429
430/// Canonical POSIX `strerror` text for common errnos, target-independent.
431///
432/// `wasm32-unknown-unknown`'s `std` ships no libc `strerror` table, so
433/// `io::Error::from_raw_os_error(n).to_string()` renders a useless
434/// "operation successful" there (#301). Resolving the message from this static
435/// map instead makes the wasm build report the SAME text a native build does
436/// for the same errno. The strings are the standard POSIX texts that Darwin and
437/// glibc `strerror` both emit — verified against the reference binary for the
438/// file errnos the oracle exercises (2, 9, 13, 20, 28, 1) — so using the table
439/// on every target is deterministic and keeps wasm and native identical.
440/// The table is also consulted on Windows after Win32→CRT-errno normalization
441/// ([`win32_to_crt_errno`]): MSVC CRT errno integers 1–32 are numerically
442/// identical to their POSIX counterparts, so the same table serves both. Known
443/// text divergence pending a Windows runner: errno 12 (ENOMEM) — the MSVC CRT
444/// `strerror` says "Not enough space" where this table says "Cannot allocate
445/// memory". Errnos absent here (rare, platform-specific values whose text
446/// diverges between platforms, e.g. macOS `ENOTEMPTY` = 66, Windows CRT
447/// `ENOTEMPTY` = 41) return `None` and are resolved from the OS `Display`,
448/// which is correct on a native host and does not arise on wasm.
449fn posix_strerror(code: i32) -> Option<&'static str> {
450    Some(match code {
451        1 => "Operation not permitted",
452        2 => "No such file or directory",
453        3 => "No such process",
454        4 => "Interrupted system call",
455        5 => "Input/output error",
456        7 => "Argument list too long",
457        8 => "Exec format error",
458        9 => "Bad file descriptor",
459        10 => "No child processes",
460        12 => "Cannot allocate memory",
461        13 => "Permission denied",
462        14 => "Bad address",
463        17 => "File exists",
464        20 => "Not a directory",
465        21 => "Is a directory",
466        22 => "Invalid argument",
467        24 => "Too many open files",
468        27 => "File too large",
469        28 => "No space left on device",
470        29 => "Illegal seek",
471        30 => "Read-only file system",
472        32 => "Broken pipe",
473        _ => return None,
474    })
475}
476
477/// Win32 error code to MSVC CRT errno, mirroring the `_dosmaperr` table.
478///
479/// The MSVC CRT's `_dosmaperr` runs after every failing Win32 system call and
480/// maps a fixed set of codes to CRT errno values; every other code yields
481/// `EINVAL` (22). That table is stable public CRT ABI (unchanged since at
482/// least VS 2005), and it is what C Lua on Windows observes through `errno`
483/// after a failed `fopen`/`remove`/`rename` — so `file_result`'s pushed
484/// integer must pass through the same mapping (#305). There is no
485/// range-passthrough rule in modern `_dosmaperr`; that logic existed only in
486/// 16-bit DOS-era code.
487///
488/// Named-constant reference (Win32 code → CRT errno name → CRT value):
489/// ```text
490/// 1   ERROR_INVALID_FUNCTION       → EINVAL       22
491/// 2   ERROR_FILE_NOT_FOUND         → ENOENT        2
492/// 3   ERROR_PATH_NOT_FOUND         → ENOENT        2
493/// 4   ERROR_TOO_MANY_OPEN_FILES    → EMFILE       24
494/// 5   ERROR_ACCESS_DENIED          → EACCES       13
495/// 6   ERROR_INVALID_HANDLE         → EBADF         9
496/// 7   ERROR_ARENA_TRASHED          → ENOMEM       12
497/// 8   ERROR_NOT_ENOUGH_MEMORY      → ENOMEM       12
498/// 9   ERROR_INVALID_BLOCK          → ENOMEM       12
499/// 10  ERROR_BAD_ENVIRONMENT        → E2BIG         7
500/// 11  ERROR_BAD_FORMAT             → ENOEXEC       8
501/// 12  ERROR_INVALID_ACCESS         → EINVAL       22
502/// 13  ERROR_INVALID_DATA           → EINVAL       22
503/// 15  ERROR_INVALID_DRIVE          → ENOENT        2
504/// 16  ERROR_CURRENT_DIRECTORY      → EACCES       13
505/// 17  ERROR_NOT_SAME_DEVICE        → EXDEV        18
506/// 18  ERROR_NO_MORE_FILES          → ENOENT        2
507/// 32  ERROR_SHARING_VIOLATION      → EACCES       13
508/// 33  ERROR_LOCK_VIOLATION         → EACCES       13
509/// 53  ERROR_BAD_NETPATH            → ENOENT        2
510/// 65  ERROR_NETWORK_ACCESS_DENIED  → EACCES       13
511/// 67  ERROR_BAD_NET_NAME           → ENOENT        2
512/// 80  ERROR_FILE_EXISTS            → EEXIST       17
513/// 82  ERROR_CANNOT_MAKE            → EACCES       13
514/// 83  ERROR_FAIL_I24               → EACCES       13
515/// 87  ERROR_INVALID_PARAMETER      → EINVAL       22
516/// 89  ERROR_NO_PROC_SLOTS          → EAGAIN       11
517/// 108 ERROR_DRIVE_LOCKED           → EACCES       13
518/// 109 ERROR_BROKEN_PIPE            → EPIPE        32
519/// 112 ERROR_DISK_FULL              → ENOSPC       28
520/// 114 ERROR_INVALID_TARGET_HANDLE  → EBADF         9
521/// 128 ERROR_WAIT_NO_CHILDREN       → ECHILD       10
522/// 129 ERROR_CHILD_NOT_COMPLETE     → ECHILD       10
523/// 130 ERROR_DIRECT_ACCESS_HANDLE   → EBADF         9
524/// 131 ERROR_NEGATIVE_SEEK          → EINVAL       22
525/// 132 ERROR_SEEK_ON_DEVICE         → EACCES       13
526/// 133 ERROR_IS_JOIN_TARGET         → EACCES       13
527/// 134 ERROR_IS_JOINED              → EACCES       13
528/// 135 ERROR_IS_SUBSTED             → EACCES       13
529/// 136 ERROR_NOT_JOINED             → EACCES       13
530/// 137 ERROR_NOT_SUBSTED            → EACCES       13
531/// 138 ERROR_JOIN_TO_JOIN           → EACCES       13
532/// 139 ERROR_SUBST_TO_SUBST         → EACCES       13
533/// 140 ERROR_JOIN_TO_SUBST          → EACCES       13
534/// 141 ERROR_SUBST_TO_JOIN          → EACCES       13
535/// 145 ERROR_DIR_NOT_EMPTY          → ENOTEMPTY    41  (Windows CRT value; POSIX is 39)
536/// 158 ERROR_NOT_LOCKED             → EACCES       13
537/// 161 ERROR_BAD_PATHNAME           → ENOENT        2
538/// 164 ERROR_MAX_THRDS_REACHED      → EAGAIN       11
539/// 167 ERROR_LOCK_FAILED            → EACCES       13
540/// 183 ERROR_ALREADY_EXISTS         → EEXIST       17
541/// 206 ERROR_FILENAME_EXCED_RANGE   → ENOENT        2
542/// 215 ERROR_NESTING_NOT_ALLOWED    → EAGAIN       11
543/// 1816 ERROR_NOT_ENOUGH_QUOTA      → ENOMEM       12
544/// _   (all others)                 → EINVAL       22
545/// ```
546///
547/// This function carries no `cfg` gate so its unit tests run on every
548/// platform; only the call sites are `#[cfg(windows)]`-gated, hence the
549/// dead-code allowance for non-Windows non-test builds.
550#[cfg_attr(not(windows), allow(dead_code))]
551fn win32_to_crt_errno(win32_code: u32) -> i32 {
552    match win32_code {
553        1 => 22,
554        2 => 2,
555        3 => 2,
556        4 => 24,
557        5 => 13,
558        6 => 9,
559        7 => 12,
560        8 => 12,
561        9 => 12,
562        10 => 7,
563        11 => 8,
564        12 => 22,
565        13 => 22,
566        15 => 2,
567        16 => 13,
568        17 => 18,
569        18 => 2,
570        32 => 13,
571        33 => 13,
572        53 => 2,
573        65 => 13,
574        67 => 2,
575        80 => 17,
576        82 => 13,
577        83 => 13,
578        87 => 22,
579        89 => 11,
580        108 => 13,
581        109 => 32,
582        112 => 28,
583        114 => 9,
584        128 => 10,
585        129 => 10,
586        130 => 9,
587        131 => 22,
588        132 => 13,
589        133 => 13,
590        134 => 13,
591        135 => 13,
592        136 => 13,
593        137 => 13,
594        138 => 13,
595        139 => 13,
596        140 => 13,
597        141 => 13,
598        145 => 41,
599        158 => 13,
600        161 => 2,
601        164 => 11,
602        167 => 13,
603        183 => 17,
604        206 => 2,
605        215 => 11,
606        1816 => 12,
607        _ => 22,
608    }
609}
610
611/// Normalize a raw-OS code for the integer pushed in Lua's failure triple.
612///
613/// On Windows `raw_os_error()` returns a Win32 code; the MSVC CRT's
614/// `_dosmaperr` converts it to a CRT errno before C Lua ever sees it through
615/// `errno`. This performs the same conversion so the integer pushed by
616/// [`file_result`] matches what C Lua pushes (#305). On all other targets the
617/// raw OS code is already a POSIX errno and passes through unchanged.
618#[cfg(windows)]
619fn os_errno_for_lua(raw: i32) -> i32 {
620    win32_to_crt_errno(raw as u32)
621}
622
623#[cfg(not(windows))]
624fn os_errno_for_lua(raw: i32) -> i32 {
625    raw
626}
627
628/// On Unix and wasm the raw OS code is already a POSIX errno; look it up in
629/// [`posix_strerror`] directly. On Windows the raw code is a Win32 code
630/// (code 5 is `ERROR_ACCESS_DENIED`, not `EIO`); normalize it to a CRT errno
631/// first so the returned text matches C's `strerror(errno)` for the same
632/// failure (#305). On other targets no translation is known; callers fall
633/// through to the OS `Display`.
634#[cfg(any(unix, target_arch = "wasm32"))]
635fn target_posix_strerror(code: i32) -> Option<&'static str> {
636    posix_strerror(code)
637}
638
639#[cfg(windows)]
640fn target_posix_strerror(code: i32) -> Option<&'static str> {
641    posix_strerror(win32_to_crt_errno(code as u32))
642}
643
644#[cfg(not(any(unix, target_arch = "wasm32", windows)))]
645fn target_posix_strerror(_code: i32) -> Option<&'static str> {
646    None
647}
648
649/// Render an `io::Error` the way C's `strerror(errno)` would: the plain
650/// platform message, with no trailing `" (os error N)"`.
651///
652/// For an OS-backed error the message comes from [`posix_strerror`] (a
653/// target-independent table, so the wasm build matches native — #301), falling
654/// back to the OS `Display` minus its `" (os error N)"` suffix for errnos the
655/// table does not cover. `std::io::Error`'s `Display` appends that suffix for
656/// the `Repr::Os` case in a stable format, so stripping it is a deterministic
657/// un-format. Errors with no raw OS code (e.g. "no filesystem hook registered")
658/// carry their own message and pass through unchanged.
659fn strerror_text(err: &io::Error) -> String {
660    match err.raw_os_error() {
661        Some(code) => match target_posix_strerror(code) {
662            Some(msg) => msg.to_string(),
663            None => {
664                let full = err.to_string();
665                let suffix = format!(" (os error {code})");
666                full.strip_suffix(&suffix).unwrap_or(&full).to_string()
667            }
668        },
669        None => err.to_string(),
670    }
671}
672
673/// Push success (`true`) or failure (`fail`, msg[, errno]) per `luaL_fileresult`.
674///
675/// On success: `lua_pushboolean(L, 1); return 1`. On failure C runs
676/// `luaL_pushfail(L); lua_pushfstring(...); lua_pushinteger(errno); return 3`,
677/// and `luaL_pushfail` resolves to `lua_pushnil` on every supported version
678/// (5.1-5.5), so the first failure value is `nil`, never `false`. Tests that
679/// compare the failure handle to `nil` (e.g. `io.open(missing) == nil`) rely on
680/// this exact value.
681///
682/// The message and errno come straight off `os_err` via [`strerror_text`] and
683/// `raw_os_error()` — callers must pass through the original `io::Error` from
684/// the host hook unmodified, never re-wrap it as `ErrorKind::Other` (#301:
685/// re-wrapping drops `raw_os_error()`, surfacing as errno 0 downstream).
686///
687/// The errno is pushed **only when `os_err` actually carries one**
688/// (`raw_os_error().is_some()` — every real OS failure does). C always has a
689/// live `errno`, so real filesystem failures produce the faithful 3-value
690/// triple. When the error is a non-OS failure with no errno — an omniLua-only
691/// case C cannot reach, e.g. a sandbox capability failure ("no filesystem hook
692/// registered") or a host hook that returned a `raw_os_error`-less
693/// `io::Error` — there is genuinely no errno to report, so the result is the
694/// honest 2-value `(nil, msg)`. Coercing that to `0` (the removed
695/// `unwrap_or(0)`) was the #301 fallback: a fabricated errno that no `errno`
696/// value ever legitimately equals here.
697pub(crate) fn file_result(
698    state: &mut LuaState,
699    success: bool,
700    fname: Option<&[u8]>,
701    os_err: io::Error,
702) -> Result<usize, LuaError> {
703    if success {
704        state.push(LuaValue::Bool(true));
705        return Ok(1);
706    }
707    state.push(LuaValue::Nil);
708    let msg = strerror_text(&os_err);
709    match fname {
710        Some(name) => {
711            let mut s = Vec::with_capacity(name.len() + 2 + msg.len());
712            s.extend_from_slice(name);
713            s.extend_from_slice(b": ");
714            s.extend_from_slice(msg.as_bytes());
715            state.push_string(&s)?;
716        }
717        None => {
718            state.push_string(msg.as_bytes())?;
719        }
720    }
721    match os_err.raw_os_error() {
722        Some(code) => {
723            state.push(LuaValue::Int(os_errno_for_lua(code) as i64));
724            Ok(3)
725        }
726        None => Ok(2),
727    }
728}
729
730/// Push popen/system exit-status results per `luaL_execresult`: `true` on a
731/// zero status, else `(nil, "exit"|"signal", stat)`.
732///
733/// Deferred: `WIFEXITED`/`WTERMSIG` are not portable across all hosts, so this
734/// always reports a non-zero status as an `"exit"` code and never distinguishes
735/// a signal — faithful enough for the clients that probe an exit status.
736fn exec_result(state: &mut LuaState, stat: i32) -> Result<usize, LuaError> {
737    if stat == 0 {
738        state.push(LuaValue::Bool(true));
739        Ok(1)
740    } else {
741        state.push(LuaValue::Bool(false));
742        state.push_string(b"exit")?;
743        state.push(LuaValue::Int(stat as i64));
744        Ok(3)
745    }
746}
747
748/// Retrieve `LStream` from argument 1 via a userdata type-check.
749///
750/// Returns an `Rc<RefCell<LStream>>` from the side-table registry. The C port
751/// returns a raw `LStream *` pointing into the userdata payload; Rust uses a
752/// side table because `LStream` contains heap pointers that cannot be safely
753/// reinterpreted from a raw byte buffer in safe Rust.
754fn get_lstream(state: &mut LuaState) -> Result<Rc<RefCell<LStream>>, LuaError> {
755    let ud = state.check_arg_userdata(1, LUA_FILE_HANDLE)?;
756    lookup_lstream(state, ud.identity())
757        .ok_or_else(|| LuaError::runtime(format_args!("invalid file handle")))
758}
759
760/// Look up the `LStream` registered for the userdata sitting at upvalue `idx`.
761///
762/// `aux_lines` stores the file-handle userdata as upvalue 1 of `io_readline`;
763/// this helper performs the same registry round-trip that `get_lstream` does
764/// for argument 1, but reads the value from the closure's upvalue slot instead
765/// of the call stack.
766fn lstream_from_upvalue(state: &mut LuaState, idx: i32) -> Result<Rc<RefCell<LStream>>, LuaError> {
767    let v = state.value_at(crate::state_stub::upvalue_index(idx));
768    let ud_id = match v {
769        LuaValue::UserData(ud) => ud.identity(),
770        _ => {
771            return Err(LuaError::runtime(format_args!(
772                "invalid file handle in upvalue {}",
773                idx
774            )));
775        }
776    };
777    lookup_lstream(state, ud_id)
778        .ok_or_else(|| LuaError::runtime(format_args!("invalid file handle in upvalue {}", idx)))
779}
780
781/// Validate that argument 1 is an open file handle; error if closed.
782///
783/// The closed-file error is raised through `c_api_runtime` (the `luaL_error`
784/// analogue) so it carries the calling source-location prefix
785/// (`<source>:<line>:`), matching the reference `tofile` in `liolib.c`.
786fn tofile(state: &mut LuaState) -> Result<Rc<RefCell<LStream>>, LuaError> {
787    let p_rc = get_lstream(state)?;
788    let closed = {
789        let p = p_rc.borrow();
790        debug_assert!(p.is_closed() || p.file.is_some());
791        p.is_closed()
792    };
793    if closed {
794        return Err(lua_vm::debug::c_api_runtime(
795            state,
796            b"attempt to use a closed file".to_vec(),
797        ));
798    }
799    Ok(p_rc)
800}
801
802// ── File creation helpers ────────────────────────────────────────────────────
803
804/// Allocate a "closed" file-handle userdata and push it; set its metatable.
805/// Also registers an empty `LStream` in the side table keyed by the userdata
806/// identity, and returns the `Rc<RefCell<LStream>>` so the caller may finish
807/// initialising it (set `file`, set `close_fn`). C: `newprefile(L)`.
808fn new_pre_file(state: &mut LuaState) -> Result<Rc<RefCell<LStream>>, LuaError> {
809    let ud = state.new_userdata_typed(LUA_FILE_HANDLE, std::mem::size_of::<LStream>(), 0)?;
810    state.set_metatable_by_name(LUA_FILE_HANDLE)?;
811    let cell = register_lstream(
812        state,
813        ud.identity(),
814        LStream {
815            file: None,
816            close_fn: None,
817        },
818    );
819    Ok(cell)
820}
821
822/// Allocate a new regular-file handle with `io_fclose` as the close function.
823fn new_file(state: &mut LuaState) -> Result<Rc<RefCell<LStream>>, LuaError> {
824    let cell = new_pre_file(state)?;
825    cell.borrow_mut().close_fn = Some(io_fclose);
826    Ok(cell)
827}
828
829/// Build the `io.input`/`io.output`/`io.lines` open-failure error, version-gated.
830///
831/// C splits here by version. 5.2+ `opencheck` raises
832/// `luaL_error(L, "cannot open file '%s' (%s)", fname, strerror(errno))`. 5.1's
833/// `g_iofile`/`io_lines` instead call `fileerror`, which does
834/// `luaL_argerror(L, 1, "<fname>: <strerror>")` — rendered as
835/// `bad argument #1 to '<caller>' (<fname>: <strerror>)`, with `<caller>`
836/// resolved from the call stack ('?' under `pcall(io.input, x)`, `'lines'` when
837/// called from a Lua frame). [`lua_vm::debug::arg_error_impl`] reproduces that
838/// exact stack walk, so routing the 5.1 case through it matches the reference
839/// funcname and location prefix without special-casing either.
840fn open_failure_error(state: &mut LuaState, fname: &[u8], detail: &[u8]) -> LuaError {
841    if matches!(state.global().lua_version, lua_types::LuaVersion::V51) {
842        let mut extramsg = Vec::with_capacity(fname.len() + 2 + detail.len());
843        extramsg.extend_from_slice(fname);
844        extramsg.extend_from_slice(b": ");
845        extramsg.extend_from_slice(detail);
846        lua_vm::debug::arg_error_impl(state, 1, &extramsg)
847    } else {
848        let mut msg = Vec::with_capacity(fname.len() + detail.len() + 20);
849        msg.extend_from_slice(b"cannot open file '");
850        msg.extend_from_slice(fname);
851        msg.extend_from_slice(b"' (");
852        msg.extend_from_slice(detail);
853        msg.push(b')');
854        lua_vm::debug::c_api_runtime(state, msg)
855    }
856}
857
858/// Open `fname` and push its handle; raise a runtime error on failure.
859///
860/// The file system is reached via `GlobalState::file_open_hook` (registered by
861/// `lua-cli`) since `std::fs` is banned in `lua-stdlib` per PORTING.md §1.
862fn opencheck(state: &mut LuaState, fname: &[u8], mode: &[u8]) -> Result<(), LuaError> {
863    let hook = state.global().file_open_hook;
864    let fh = match hook {
865        Some(open_fn) => match open_fn(fname, mode) {
866            Ok(fh) => fh,
867            Err(e) => {
868                let detail = strerror_text(&e);
869                return Err(open_failure_error(state, fname, detail.as_bytes()));
870            }
871        },
872        None => {
873            return Err(open_failure_error(
874                state,
875                fname,
876                b"no filesystem hook registered",
877            ));
878        }
879    };
880    let cell = new_file(state)?;
881    cell.borrow_mut().file = Some(fh);
882    Ok(())
883}
884
885// ── Close functions ──────────────────────────────────────────────────────────
886
887/// Close a regular file via `fclose`. C: `io_fclose`.
888///
889/// Dropping the `Box<dyn LuaFileHandle>` flushes through the host handle's own
890/// `Drop` (the CLI's writer flushes on drop). Deferred: surfacing a close-time
891/// I/O error as a `file_result` failure tuple — close currently always reports
892/// success.
893fn io_fclose(state: &mut LuaState) -> Result<usize, LuaError> {
894    let p_rc = get_lstream(state)?;
895    let _closed = p_rc.borrow_mut().file.take();
896    state.push(LuaValue::Bool(true));
897    Ok(1)
898}
899
900/// Close a popen process pipe. C: `io_pclose`.
901///
902/// Deferred: waiting on the child and forwarding its real exit status. Dropping
903/// the handle closes the pipe; the status reported here is a fixed success.
904fn io_pclose(state: &mut LuaState) -> Result<usize, LuaError> {
905    let p_rc = get_lstream(state)?;
906    let _closed = p_rc.borrow_mut().file.take();
907    exec_result(state, 0)
908}
909
910/// Refuse to close a standard-stream handle. C: `io_noclose`.
911///
912/// The close function is reinstalled before returning so the handle stays alive
913/// and remains closeable-but-inert on a later attempt, matching C's `io_noclose`.
914fn io_noclose(state: &mut LuaState) -> Result<usize, LuaError> {
915    let p_rc = get_lstream(state)?;
916    p_rc.borrow_mut().close_fn = Some(io_noclose);
917    state.push(LuaValue::Bool(false));
918    state.push_string(b"cannot close standard file")?;
919    Ok(2)
920}
921
922/// Invoke the stream's close function and mark it closed. C: `aux_close`.
923fn aux_close(state: &mut LuaState) -> Result<usize, LuaError> {
924    let p_rc = get_lstream(state)?;
925    let cf = p_rc.borrow_mut().close_fn.take().ok_or_else(|| {
926        LuaError::runtime(format_args!("attempt to close an already-closed file"))
927    })?;
928    cf(state)
929}
930
931// ── io.type ──────────────────────────────────────────────────────────────────
932
933/// `io.type(x)` — return `"file"`, `"closed file"`, or the fail value for a
934/// non-handle. C: `io_type`.
935///
936/// A non-handle pushes the `fail` value (`nil`) via the reference's
937/// `luaL_pushfail`, NOT `false`; `fail` is `nil` on every supported version.
938/// An unknown userdata still carrying the `FILE*` metatable but absent from the
939/// `LStream` side table is treated as closed (it cannot be an open stream).
940pub fn io_type(state: &mut LuaState) -> Result<usize, LuaError> {
941    state.check_arg_any(1)?;
942    let maybe_userdata = state.test_arg_userdata(1, LUA_FILE_HANDLE);
943    match maybe_userdata {
944        None => {
945            state.push(LuaValue::Nil);
946        }
947        Some(ud) => {
948            let is_closed = match lookup_lstream(state, ud.identity()) {
949                Some(rc) => rc.borrow().is_closed(),
950                None => true,
951            };
952            if is_closed {
953                state.push_string(b"closed file")?;
954            } else {
955                state.push_string(b"file")?;
956            }
957        }
958    }
959    Ok(1)
960}
961
962// ── __tostring metamethod ────────────────────────────────────────────────────
963
964/// `tostring(file)` metamethod. C: `f_tostring`.
965///
966/// An open handle renders `file (0x?)`. The reference prints the handle's real
967/// pointer address (`file (0x<addr>)`); that address is non-deterministic, so
968/// reproducing it is deferred and intentionally not pinned by the behavioral
969/// net. A closed handle renders `file (closed)`, matching the reference exactly.
970fn f_tostring(state: &mut LuaState) -> Result<usize, LuaError> {
971    let p_rc = get_lstream(state)?;
972    let closed = p_rc.borrow().is_closed();
973    if closed {
974        state.push_string(b"file (closed)")?;
975    } else {
976        state.push_string(b"file (0x?)")?;
977    }
978    Ok(1)
979}
980
981// ── close / gc ───────────────────────────────────────────────────────────────
982
983/// `file:close()`. C: `f_close`.
984fn f_close(state: &mut LuaState) -> Result<usize, LuaError> {
985    let _ = tofile(state)?; // validates stream is open before closing
986    aux_close(state)
987}
988
989/// `io.close([file])`. C: `io_close`.
990pub fn io_close(state: &mut LuaState) -> Result<usize, LuaError> {
991    // The pushed value naturally lands at position 1 (top advances by one from
992    // func+1 to func+2). The C source does NOT call lua_replace here; adding one
993    // would pop the value back out, since position 1 equals top-1 in this case.
994    if state.type_at(1) == LuaType::None {
995        state.registry_get(IO_OUTPUT_KEY)?;
996    }
997    f_close(state)
998}
999
1000/// `__gc` / `__close` metamethod — silently close if still open. C: `f_gc`.
1001fn f_gc(state: &mut LuaState) -> Result<usize, LuaError> {
1002    let p_rc = get_lstream(state)?;
1003    let needs_close = {
1004        let p = p_rc.borrow();
1005        !p.is_closed() && p.file.is_some()
1006    };
1007    if needs_close {
1008        // ignore any error from aux_close during GC finalisation
1009        let _ = aux_close(state);
1010    }
1011    Ok(0)
1012}
1013
1014// ── io.open / io.popen / io.tmpfile ─────────────────────────────────────────
1015
1016/// `io.open(filename [, mode])`. C: `io_open`.
1017///
1018/// The file system is reached via `GlobalState::file_open_hook` (registered by
1019/// `lua-cli`) since `std::fs` is banned in `lua-stdlib` per PORTING.md §1.
1020pub fn io_open(state: &mut LuaState) -> Result<usize, LuaError> {
1021    let filename: Vec<u8> = state.check_arg_string(1)?;
1022    let mode: Vec<u8> = state.opt_arg_string(2, b"r")?;
1023    if !check_mode(&mode) {
1024        return Err(lua_vm::debug::arg_error_impl(state, 2, b"invalid mode"));
1025    }
1026    let hook = state.global().file_open_hook;
1027    match hook {
1028        Some(open_fn) => match open_fn(&filename, &mode) {
1029            Ok(fh) => {
1030                let cell = new_file(state)?;
1031                cell.borrow_mut().file = Some(fh);
1032                Ok(1)
1033            }
1034            Err(os_err) => file_result(state, false, Some(&filename), os_err),
1035        },
1036        None => {
1037            let os_err =
1038                io::Error::new(io::ErrorKind::Unsupported, "no filesystem hook registered");
1039            file_result(state, false, Some(&filename), os_err)
1040        }
1041    }
1042}
1043
1044/// `io.popen(filename [, mode])`. C: `io_popen`.
1045///
1046/// `std::process::Command` is banned in `lua-stdlib`; the child process is
1047/// spawned via `GlobalState::popen_hook`, which `lua-cli` installs. When the
1048/// hook is absent (sandboxed embeddings), this returns a clean Lua failure
1049/// shape (`nil, errmsg, errno`) rather than panicking, so clients such as
1050/// LuaRocks that probe `io.popen` fall back gracefully instead of crashing
1051/// the host.
1052pub fn io_popen(state: &mut LuaState) -> Result<usize, LuaError> {
1053    let filename: Vec<u8> = state.check_arg_string(1)?;
1054    let mode: Vec<u8> = state.opt_arg_string(2, b"r")?;
1055    if !check_mode_popen(&mode) {
1056        return Err(lua_vm::debug::arg_error_impl(state, 2, b"invalid mode"));
1057    }
1058    let hook = state.global().popen_hook;
1059    match hook {
1060        Some(spawn_fn) => match spawn_fn(&filename, &mode) {
1061            Ok(fh) => {
1062                let cell = new_pre_file(state)?;
1063                let mut p = cell.borrow_mut();
1064                p.file = Some(fh);
1065                p.close_fn = Some(io_pclose);
1066                drop(p);
1067                Ok(1)
1068            }
1069            Err(e) => {
1070                let os_err = io::Error::new(
1071                    io::ErrorKind::Other,
1072                    match e.message_bytes() {
1073                        Some(b) => String::from_utf8_lossy(b).into_owned(),
1074                        None => format!("{:?}", &e),
1075                    },
1076                );
1077                file_result(state, false, Some(&filename), os_err)
1078            }
1079        },
1080        None => {
1081            let os_err = io::Error::new(
1082                io::ErrorKind::Unsupported,
1083                "popen not enabled in this build",
1084            );
1085            file_result(state, false, Some(&filename), os_err)
1086        }
1087    }
1088}
1089
1090fn native_temp_name() -> io::Result<Vec<u8>> {
1091    #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
1092    {
1093        return Err(io::Error::new(
1094            io::ErrorKind::Unsupported,
1095            "temporary files not available in this host",
1096        ));
1097    }
1098
1099    #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
1100    {
1101        let mut path = std::env::temp_dir().to_string_lossy().as_bytes().to_vec();
1102        if path.last().copied() != Some(b'/') && path.last().copied() != Some(b'\\') {
1103            path.push(b'/');
1104        }
1105        let unique = format!(
1106            "lua_tmpfile_{}_{}",
1107            std::process::id(),
1108            std::time::SystemTime::now()
1109                .duration_since(std::time::UNIX_EPOCH)
1110                .map(|d| d.as_nanos())
1111                .unwrap_or(0)
1112        );
1113        path.extend_from_slice(unique.as_bytes());
1114        Ok(path)
1115    }
1116}
1117
1118/// `io.tmpfile()`. C: `io_tmpfile`.
1119pub fn io_tmpfile(state: &mut LuaState) -> Result<usize, LuaError> {
1120    let hook = state.global().file_open_hook;
1121    let Some(open_fn) = hook else {
1122        let os_err = io::Error::new(io::ErrorKind::Unsupported, "no filesystem hook registered");
1123        return file_result(state, false, None, os_err);
1124    };
1125
1126    let temp_name_hook = state.global().temp_name_hook;
1127    let path = match temp_name_hook {
1128        Some(temp_fn) => match temp_fn() {
1129            Ok(path) => path,
1130            Err(e) => {
1131                let msg = match e.message_bytes() {
1132                    Some(b) => String::from_utf8_lossy(b).into_owned(),
1133                    None => format!("{:?}", &e),
1134                };
1135                return file_result(
1136                    state,
1137                    false,
1138                    None,
1139                    io::Error::new(io::ErrorKind::Unsupported, msg),
1140                );
1141            }
1142        },
1143        None => match native_temp_name() {
1144            Ok(path) => path,
1145            Err(e) => return file_result(state, false, None, e),
1146        },
1147    };
1148
1149    match open_fn(&path, b"w+b") {
1150        Ok(fh) => {
1151            let cell = new_file(state)?;
1152            cell.borrow_mut().file = Some(fh);
1153            Ok(1)
1154        }
1155        Err(os_err) => file_result(state, false, None, os_err),
1156    }
1157}
1158
1159// ── io.input / io.output ─────────────────────────────────────────────────────
1160
1161/// Generic setter/getter for `io.input` and `io.output`. C: `g_iofile`.
1162fn g_iofile(state: &mut LuaState, key: &[u8], mode: &[u8]) -> Result<usize, LuaError> {
1163    if !matches!(state.type_at(1), LuaType::None | LuaType::Nil) {
1164        if state.type_at(1) == LuaType::String {
1165            let filename = state.check_arg_string(1)?;
1166            opencheck(state, &filename, mode)?;
1167        } else {
1168            let _ = tofile(state)?;
1169            state.push_value_at(1)?;
1170        }
1171        state.registry_set(key)?;
1172    }
1173    state.registry_get(key)?;
1174    Ok(1)
1175}
1176
1177/// `io.input([file])`. C: `io_input`.
1178pub fn io_input(state: &mut LuaState) -> Result<usize, LuaError> {
1179    g_iofile(state, IO_INPUT_KEY, b"r")
1180}
1181
1182/// `io.output([file])`. C: `io_output`.
1183pub fn io_output(state: &mut LuaState) -> Result<usize, LuaError> {
1184    g_iofile(state, IO_OUTPUT_KEY, b"w")
1185}
1186
1187// ── Read helpers ─────────────────────────────────────────────────────────────
1188
1189/// Read a numeric literal from `file` into an owned byte buffer.
1190///
1191/// The decimal point is always `.`: the reference reads the locale's
1192/// `decimal_point`, but omnilua is locale-independent, so `.` is the single
1193/// source of truth (the same simplification the rest of the number path makes).
1194fn read_number_bytes(file: &mut dyn LuaFileHandle) -> Vec<u8> {
1195    let first = loop {
1196        let b = file.read_byte();
1197        if b == EOF_SENTINEL || !(b as u8).is_ascii_whitespace() {
1198            break b;
1199        }
1200    };
1201
1202    let mut rn = ReadNumState::new(first);
1203
1204    rn.try2(file, [b'-', b'+']);
1205
1206    let mut count: usize = 0;
1207    let hex = if rn.try2(file, [b'0', b'0']) {
1208        if rn.try2(file, [b'x', b'X']) {
1209            true
1210        } else {
1211            count = 1;
1212            false
1213        }
1214    } else {
1215        false
1216    };
1217
1218    count += rn.read_digits(file, hex);
1219
1220    let dec_point = b'.';
1221    if rn.try2(file, [dec_point, b'.']) {
1222        count += rn.read_digits(file, hex);
1223    }
1224
1225    if count > 0 {
1226        let exp_chars = if hex { [b'p', b'P'] } else { [b'e', b'E'] };
1227        if rn.try2(file, exp_chars) {
1228            rn.try2(file, [b'-', b'+']);
1229            rn.read_digits(file, false);
1230        }
1231    }
1232
1233    file.unread_byte(rn.current);
1234    rn.as_bytes().to_vec()
1235}
1236
1237/// Peek for EOF: returns `true` if more input is available. C: `test_eof`
1238/// (the file-only half — caller still pushes `""` regardless).
1239fn test_eof(file: &mut dyn LuaFileHandle) -> bool {
1240    let c = file.read_byte();
1241    if c != EOF_SENTINEL {
1242        file.unread_byte(c);
1243    }
1244    c != EOF_SENTINEL
1245}
1246
1247/// Read one line from `file` into an owned buffer. Returns `(bytes, had_content)`.
1248/// If `chop` is true the trailing `\n` is stripped. C: `read_line(L, f, chop)`.
1249///
1250/// The bytes are accumulated in `LUAL_BUFFER_SIZE`-sized passes and the outer
1251/// loop continues while a pass fills without hitting a newline or EOF — the
1252/// chunked structure mirrors C's `luaL_prepbuffer` loop, though a growable `Vec`
1253/// stands in for the fixed stack buffer.
1254fn read_line(file: &mut dyn LuaFileHandle, chop: bool) -> (Vec<u8>, bool) {
1255    let mut buf: Vec<u8> = Vec::new();
1256    let mut c: i32;
1257
1258    'outer: loop {
1259        for _ in 0..LUAL_BUFFER_SIZE {
1260            c = file.read_byte();
1261            if c == EOF_SENTINEL || c == b'\n' as i32 {
1262                break 'outer;
1263            }
1264            buf.push(c as u8);
1265        }
1266    }
1267
1268    if !chop && c == b'\n' as i32 {
1269        buf.push(b'\n');
1270    }
1271
1272    let had_content = c == b'\n' as i32 || !buf.is_empty();
1273    (buf, had_content)
1274}
1275
1276/// Read the entire file into an owned buffer. C: `read_all(L, f)` (file-only half).
1277///
1278/// Perf: C `fread`s in bulk; this reads one byte at a time via
1279/// `LuaFileHandle::read_byte`. A future `read_chunk(&mut [u8])` on the trait
1280/// would let the host fill a buffer directly.
1281fn read_all(file: &mut dyn LuaFileHandle) -> Vec<u8> {
1282    let mut buf: Vec<u8> = Vec::new();
1283    loop {
1284        let mut chunk_read = 0usize;
1285        for _ in 0..LUAL_BUFFER_SIZE {
1286            let b = file.read_byte();
1287            if b == EOF_SENTINEL {
1288                break;
1289            }
1290            buf.push(b as u8);
1291            chunk_read += 1;
1292        }
1293        if chunk_read < LUAL_BUFFER_SIZE {
1294            break;
1295        }
1296    }
1297    buf
1298}
1299
1300/// Read at most `n` bytes from `file`. Returns `(bytes, had_content)`.
1301fn read_chars(file: &mut dyn LuaFileHandle, n: usize) -> (Vec<u8>, bool) {
1302    let mut buf = Vec::with_capacity(n);
1303    for _ in 0..n {
1304        let b = file.read_byte();
1305        if b == EOF_SENTINEL {
1306            break;
1307        }
1308        buf.push(b as u8);
1309    }
1310    let nr = buf.len();
1311    (buf, nr > 0)
1312}
1313
1314/// A validated `file:read`/`io.read` string format: the canonical option byte
1315/// (`b'n'`/`b'l'`/`b'L'`/`b'a'`) after the leading `*` has been resolved.
1316#[derive(Clone, Copy, PartialEq, Eq)]
1317enum ReadFormat {
1318    Number,
1319    Line,
1320    LineWithEol,
1321    All,
1322}
1323
1324/// Whether the leading `*` on a read format is REQUIRED (5.1/5.2) or OPTIONAL
1325/// (5.3+). The `*` was a mandatory marker in 5.1/5.2; 5.3 kept it accepted for
1326/// compatibility but made it optional (`if (*p == '*') p++;` in `liolib.c`'s
1327/// `g_read`). Single source of truth for that seam — verified empirically
1328/// against the 5.1.5/5.2.4 vs 5.3.6/5.4.7/5.5.0 reference binaries.
1329fn read_format_requires_star(version: lua_types::LuaVersion) -> bool {
1330    matches!(
1331        version,
1332        lua_types::LuaVersion::V51 | lua_types::LuaVersion::V52
1333    )
1334}
1335
1336/// Whether the `L` (line-with-end-of-line) format exists. `L` was added in 5.2;
1337/// 5.1 has only `n`/`l`/`a`, so `*L` there is an invalid format. Single source of
1338/// truth — verified against the 5.1.5 reference (`*L` → "invalid format") vs
1339/// 5.2.4+ (`*L` reads the line including its newline).
1340fn read_format_has_line_with_eol(version: lua_types::LuaVersion) -> bool {
1341    version != lua_types::LuaVersion::V51
1342}
1343
1344/// Resolve a read-format string against the version seam, returning the
1345/// canonical [`ReadFormat`] or the exact `extramsg` the reference passes to
1346/// `luaL_argerror`.
1347///
1348/// The two reference wordings encode the seam: a leading char that is not a
1349/// valid format marker yields `"invalid option"`, while a recognised marker
1350/// followed by an unknown option yields `"invalid format"`.
1351///   * 5.1/5.2: the `*` is the required marker. No `*` ⇒ `"invalid option"`.
1352///     After `*`, an unknown/absent option char ⇒ `"invalid format"`; on 5.1
1353///     the `L` option does not exist, so `*L` ⇒ `"invalid format"`.
1354///   * 5.3+: the `*` is optional. The option char is read directly (with or
1355///     without a leading `*`); an unknown one ⇒ `"invalid format"`.
1356fn resolve_read_format(
1357    version: lua_types::LuaVersion,
1358    fmt: &[u8],
1359) -> Result<ReadFormat, &'static [u8]> {
1360    let option = if read_format_requires_star(version) {
1361        if fmt.first() != Some(&b'*') {
1362            return Err(b"invalid option");
1363        }
1364        fmt.get(1).copied()
1365    } else if fmt.first() == Some(&b'*') {
1366        fmt.get(1).copied()
1367    } else {
1368        fmt.first().copied()
1369    };
1370    match option {
1371        Some(b'n') => Ok(ReadFormat::Number),
1372        Some(b'l') => Ok(ReadFormat::Line),
1373        Some(b'L') if read_format_has_line_with_eol(version) => Ok(ReadFormat::LineWithEol),
1374        Some(b'a') => Ok(ReadFormat::All),
1375        _ => Err(b"invalid format"),
1376    }
1377}
1378
1379/// Dispatch one or more read formats; push results. C: `g_read(L, f, first)`.
1380///
1381/// Takes an `Rc<RefCell<LStream>>` so each I/O step can borrow the file briefly,
1382/// release the borrow, then push the result to `state`. This is the "collect
1383/// then borrow" pattern that resolves the `&mut state` vs `&mut file` conflict.
1384fn g_read(
1385    state: &mut LuaState,
1386    p_rc: &Rc<RefCell<LStream>>,
1387    first: i32,
1388) -> Result<usize, LuaError> {
1389    //
1390    // In C, `getiofile` leaves the default stream on the stack, so subtracting
1391    // one skips that extra value. This Rust port resolves registry streams into
1392    // an Rc and pops the registry value before reaching `g_read`, so count the
1393    // read formats directly from `first`.
1394    let nargs = (state.top() - first + 1).max(0);
1395    let mut n = first;
1396    let mut success = true;
1397
1398    {
1399        let mut p = p_rc.borrow_mut();
1400        let fh = p.file.as_mut().expect("open stream has no file handle");
1401        fh.clear_error();
1402    }
1403
1404    if nargs == 0 {
1405        let (bytes, had) = {
1406            let mut p = p_rc.borrow_mut();
1407            let fh = p
1408                .file
1409                .as_deref_mut()
1410                .expect("open stream has no file handle");
1411            read_line(fh, true)
1412        };
1413        state.push_string(&bytes)?;
1414        success = had;
1415        n = first + 1;
1416    } else {
1417        state.ensure_stack((nargs as i32) + 20, "too many arguments")?;
1418        let mut remaining = nargs;
1419        while remaining > 0 && success {
1420            if state.type_at(n) == LuaType::Number {
1421                let l = state.check_arg_integer(n)? as usize;
1422                if l == 0 {
1423                    let not_eof = {
1424                        let mut p = p_rc.borrow_mut();
1425                        let fh = p
1426                            .file
1427                            .as_deref_mut()
1428                            .expect("open stream has no file handle");
1429                        test_eof(fh)
1430                    };
1431                    state.push_string(b"")?;
1432                    success = not_eof;
1433                } else {
1434                    let (bytes, had) = {
1435                        let mut p = p_rc.borrow_mut();
1436                        let fh = p
1437                            .file
1438                            .as_deref_mut()
1439                            .expect("open stream has no file handle");
1440                        read_chars(fh, l)
1441                    };
1442                    state.push_string(&bytes)?;
1443                    success = had;
1444                }
1445            } else {
1446                let s: Vec<u8> = state.check_arg_string(n)?;
1447                let version = state.global().lua_version;
1448                let format = match resolve_read_format(version, &s) {
1449                    Ok(format) => format,
1450                    Err(extramsg) => {
1451                        return Err(lua_vm::debug::arg_error_impl(state, n, extramsg));
1452                    }
1453                };
1454                match format {
1455                    ReadFormat::Number => {
1456                        let bytes = {
1457                            let mut p = p_rc.borrow_mut();
1458                            let fh = p
1459                                .file
1460                                .as_deref_mut()
1461                                .expect("open stream has no file handle");
1462                            read_number_bytes(fh)
1463                        };
1464                        let pushed = state.string_to_number_push(&bytes)?;
1465                        if pushed != 0 {
1466                            success = true;
1467                        } else {
1468                            state.push(LuaValue::Nil);
1469                            success = false;
1470                        }
1471                    }
1472                    ReadFormat::Line => {
1473                        let (bytes, had) = {
1474                            let mut p = p_rc.borrow_mut();
1475                            let fh = p
1476                                .file
1477                                .as_deref_mut()
1478                                .expect("open stream has no file handle");
1479                            read_line(fh, true)
1480                        };
1481                        state.push_string(&bytes)?;
1482                        success = had;
1483                    }
1484                    ReadFormat::LineWithEol => {
1485                        let (bytes, had) = {
1486                            let mut p = p_rc.borrow_mut();
1487                            let fh = p
1488                                .file
1489                                .as_deref_mut()
1490                                .expect("open stream has no file handle");
1491                            read_line(fh, false)
1492                        };
1493                        state.push_string(&bytes)?;
1494                        success = had;
1495                    }
1496                    ReadFormat::All => {
1497                        let bytes = {
1498                            let mut p = p_rc.borrow_mut();
1499                            let fh = p
1500                                .file
1501                                .as_deref_mut()
1502                                .expect("open stream has no file handle");
1503                            read_all(fh)
1504                        };
1505                        state.push_string(&bytes)?;
1506                        success = true;
1507                    }
1508                }
1509            }
1510            n += 1;
1511            remaining -= 1;
1512        }
1513    }
1514
1515    let has_err = {
1516        let p = p_rc.borrow();
1517        match p.file.as_deref() {
1518            Some(fh) => fh.has_error(),
1519            None => false,
1520        }
1521    };
1522    if has_err {
1523        let err = {
1524            let p = p_rc.borrow();
1525            match p.file.as_deref().and_then(|fh| fh.last_error_info()) {
1526                Some((code, _msg)) if code != 0 => io::Error::from_raw_os_error(code),
1527                Some((_code, msg)) => io::Error::new(io::ErrorKind::Other, msg),
1528                None => io::Error::new(io::ErrorKind::Other, "file read error"),
1529            }
1530        };
1531        return file_result(state, false, None, err);
1532    }
1533
1534    if !success {
1535        state.pop_n(1);
1536        state.push(LuaValue::Nil);
1537    }
1538
1539    Ok((n - first) as usize)
1540}
1541
1542/// Resolve the registry-default I/O file (IO_INPUT / IO_OUTPUT) into its
1543/// backing `Rc<RefCell<LStream>>`. Errors if the slot holds a closed handle
1544/// or a value that is not a registered file userdata.
1545///
1546fn get_io_file_rc(state: &mut LuaState, key: &[u8]) -> Result<Rc<RefCell<LStream>>, LuaError> {
1547    state.registry_get(key)?;
1548    let ud_id = state
1549        .test_arg_userdata(-1, LUA_FILE_HANDLE)
1550        .map(|ud| ud.identity());
1551    state.pop_n(1);
1552    let label = &key[IO_PREFIX_LEN..];
1553    let id = ud_id.ok_or_else(|| {
1554        LuaError::runtime(format_args!(
1555            "default {} file is invalid",
1556            label.escape_ascii()
1557        ))
1558    })?;
1559    let rc = lookup_lstream(state, id).ok_or_else(|| {
1560        LuaError::runtime(format_args!(
1561            "default {} file is invalid",
1562            label.escape_ascii()
1563        ))
1564    })?;
1565    if rc.borrow().is_closed() {
1566        return Err(LuaError::runtime(format_args!(
1567            "default {} file is closed",
1568            label.escape_ascii()
1569        )));
1570    }
1571    Ok(rc)
1572}
1573
1574/// `io.read(...)`. C: `io_read`.
1575pub fn io_read(state: &mut LuaState) -> Result<usize, LuaError> {
1576    let p_rc = get_io_file_rc(state, IO_INPUT_KEY)?;
1577    g_read(state, &p_rc, 1)
1578}
1579
1580/// `file:read(...)`. C: `f_read`.
1581pub fn f_read(state: &mut LuaState) -> Result<usize, LuaError> {
1582    let p_rc = tofile(state)?;
1583    g_read(state, &p_rc, 2)
1584}
1585
1586// ── Write helpers ────────────────────────────────────────────────────────────
1587
1588/// Render a numeric `LuaValue` to its `io.write` byte form.
1589///
1590/// Reference `g_write` writes numbers with `lua_tostring` — the same
1591/// `tostringbuff` path as `print`/`tostring` — so this routes through the
1592/// shared, version-aware [`lua_vm::object::num_to_string`] to keep
1593/// `io.write(1.0)` byte-identical to `print(1.0)` on every version: `%.14g` on
1594/// 5.1-5.4 (no `.0` suffix under the float-only 5.1/5.2), shortest-round-trip
1595/// on 5.5.
1596fn num_to_write_bytes(state: &mut LuaState, val: &LuaValue) -> Result<Vec<u8>, LuaError> {
1597    let s = lua_vm::object::num_to_string(state, val)?;
1598    Ok(s.as_bytes().to_vec())
1599}
1600
1601/// Collect the write arguments `arg..=top` as owned byte chunks. Numbers are
1602/// stringified with `num_to_write_bytes`; everything else is arg-checked to a
1603/// string. Done before borrowing the file handle to keep `&mut LuaState`
1604/// available for the coercions.
1605fn collect_write_chunks(state: &mut LuaState, first_arg: i32) -> Result<Vec<Vec<u8>>, LuaError> {
1606    let n = state.top() as i32;
1607    let mut chunks: Vec<Vec<u8>> = Vec::with_capacity((n - first_arg + 1).max(0) as usize);
1608    for i in first_arg..=n {
1609        if state.type_at(i) == LuaType::Number {
1610            let val = state.value_at(i);
1611            chunks.push(num_to_write_bytes(state, &val)?);
1612        } else {
1613            let bytes: Vec<u8> = state.check_arg_string(i)?;
1614            chunks.push(bytes);
1615        }
1616    }
1617    Ok(chunks)
1618}
1619
1620/// Write every chunk to `p_rc`'s handle, accumulating total bytes written, and
1621/// shape the result exactly like C's `g_write` (shared by `io.write` and
1622/// `file:write`).
1623///
1624/// A chunk is written the way C's `fwrite` writes it (#305): loop over the
1625/// unwritten remainder, so a short `Ok(n)` from a single `write_bytes` call —
1626/// partial progress, not an error — continues until the chunk completes or the
1627/// handle returns a real `Err`. That first `Err` is passed to [`file_result`]
1628/// **unmodified** so its `raw_os_error()` becomes the faithful third value of
1629/// the `luaL_fileresult` tuple `(nil, strerror(errno), errno)`; fabricating a
1630/// `raw_os_error`-less "short write" error here collapsed the tuple to 2
1631/// values and lost the errno. `fwrite` does not retry `EINTR` (glibc surfaces
1632/// it as a short count with `errno` set), so `ErrorKind::Interrupted` is a
1633/// failure like any other. A zero-progress `Ok(0)` cannot make progress and
1634/// would loop forever; it carries no OS errno, so it is reported as the honest
1635/// errno-less 2-value result (the #301 rule: never fabricate an errno).
1636///
1637/// On full success returns `Ok(None)`; the caller pushes its own success value
1638/// (the output file for `io.write`, the handle for `file:write`). On the first
1639/// failed chunk returns `Ok(Some(nres))` with the failure result already on
1640/// the stack and, **on Lua 5.5 only**, an appended total-bytes-written counter
1641/// covering every completed chunk plus the failing chunk's partial progress
1642/// (5.5's `g_write` accumulates `totalbytes += numbytes` per `fwrite` and
1643/// pushes `cast_st2S(totalbytes)`, returning `n + 1`; 5.1-5.4's `g_write` does
1644/// not).
1645fn g_write(
1646    state: &mut LuaState,
1647    p_rc: &Rc<RefCell<LStream>>,
1648    chunks: &[Vec<u8>],
1649) -> Result<Option<usize>, LuaError> {
1650    let mut total: usize = 0;
1651    let write_err: Option<io::Error> = {
1652        let mut p = p_rc.borrow_mut();
1653        let fh = p.file.as_mut().expect("open stream has no file handle");
1654        let mut err = None;
1655        'chunks: for chunk in chunks {
1656            let mut done: usize = 0;
1657            while done < chunk.len() {
1658                match fh.write_bytes(&chunk[done..]) {
1659                    Ok(0) => {
1660                        err = Some(io::Error::new(io::ErrorKind::WriteZero, "write error"));
1661                        break 'chunks;
1662                    }
1663                    Ok(n) => {
1664                        done += n;
1665                        total += n;
1666                    }
1667                    Err(e) => {
1668                        err = Some(e);
1669                        break 'chunks;
1670                    }
1671                }
1672            }
1673        }
1674        err
1675    };
1676
1677    match write_err {
1678        None => Ok(None),
1679        Some(e) => {
1680            let mut nres = file_result(state, false, None, e)?;
1681            if matches!(state.global().lua_version, lua_types::LuaVersion::V55) {
1682                state.push(LuaValue::Int(total as i64));
1683                nres += 1;
1684            }
1685            Ok(Some(nres))
1686        }
1687    }
1688}
1689
1690/// `io.write(...)`. C: `io_write` → `g_write(L, getiofile(IO_OUTPUT), 1)`.
1691///
1692/// Writes all arguments to the current default output file (`IO_OUTPUT`). A
1693/// write failure returns the `luaL_fileresult` tuple (like the reference), not
1694/// a raised error.
1695pub fn io_write(state: &mut LuaState) -> Result<usize, LuaError> {
1696    let chunks = collect_write_chunks(state, 1)?;
1697    let p_rc = get_io_file_rc(state, IO_OUTPUT_KEY)?;
1698    match g_write(state, &p_rc, &chunks)? {
1699        None => {
1700            state.registry_get(IO_OUTPUT_KEY)?;
1701            Ok(1)
1702        }
1703        Some(nres) => Ok(nres),
1704    }
1705}
1706
1707/// `file:write(...)`. C: `f_write` → `g_write(L, tofile(L), 2)`.
1708pub fn f_write(state: &mut LuaState) -> Result<usize, LuaError> {
1709    let p_rc = tofile(state)?;
1710    let chunks = collect_write_chunks(state, 2)?;
1711    match g_write(state, &p_rc, &chunks)? {
1712        None => {
1713            state.push_value_at(1)?;
1714            Ok(1)
1715        }
1716        Some(nres) => Ok(nres),
1717    }
1718}
1719
1720// ── Seek / setvbuf / flush ───────────────────────────────────────────────────
1721
1722/// `file:seek([whence [, offset]])`. C: `f_seek`.
1723pub fn f_seek(state: &mut LuaState) -> Result<usize, LuaError> {
1724    static MODE_NAMES: &[&[u8]] = &[b"set", b"cur", b"end"];
1725
1726    let p_rc = tofile(state)?;
1727    let op = state.check_arg_option(2, Some(b"cur"), MODE_NAMES)?;
1728    let p3: i64 = state.opt_arg_integer(3, 0)?;
1729
1730    let seek_pos = match op {
1731        0 => SeekFrom::Start(p3 as u64),
1732        1 => SeekFrom::Current(p3),
1733        2 => SeekFrom::End(p3),
1734        _ => unreachable!(),
1735    };
1736
1737    let result = {
1738        let mut p = p_rc.borrow_mut();
1739        let fh = p.file.as_mut().expect("open stream has no file handle");
1740        fh.seek(seek_pos)
1741    };
1742    match result {
1743        Ok(pos) => {
1744            state.push(LuaValue::Int(pos as i64));
1745            Ok(1)
1746        }
1747        Err(e) => file_result(state, false, None, e),
1748    }
1749}
1750
1751/// `file:setvbuf(mode [, size])`. C: `f_setvbuf`.
1752pub fn f_setvbuf(state: &mut LuaState) -> Result<usize, LuaError> {
1753    static MODE_NAMES: &[&[u8]] = &[b"no", b"full", b"line"];
1754
1755    let p_rc = tofile(state)?;
1756    let op = state.check_arg_option(2, None, MODE_NAMES)?;
1757    let sz: i64 = state.opt_arg_integer(3, LUAL_BUFFER_SIZE as i64)?;
1758    let mode = match op {
1759        0 => BufMode::No,
1760        1 => BufMode::Full,
1761        2 => BufMode::Line,
1762        _ => unreachable!(),
1763    };
1764    let result = {
1765        let mut p = p_rc.borrow_mut();
1766        let fh = p.file.as_mut().expect("open stream has no file handle");
1767        let mode_index = match mode {
1768            BufMode::No => 0,
1769            BufMode::Full => 1,
1770            BufMode::Line => 2,
1771        };
1772        fh.set_buf_mode(mode_index, sz.max(0) as usize)
1773    };
1774    match result {
1775        Ok(()) => file_result(state, true, None, io::Error::last_os_error()),
1776        Err(e) => file_result(state, false, None, e),
1777    }
1778}
1779
1780/// `io.flush()`. C: `io_flush`.
1781pub fn io_flush(state: &mut LuaState) -> Result<usize, LuaError> {
1782    let ud_id: Option<usize> = {
1783        state.registry_get(IO_OUTPUT_KEY)?;
1784        let id = state
1785            .test_arg_userdata(-1, LUA_FILE_HANDLE)
1786            .map(|ud| ud.identity());
1787        state.pop_n(1);
1788        id
1789    };
1790    if let Some(id) = ud_id {
1791        if let Some(rc) = lookup_lstream(state, id) {
1792            let result = {
1793                let mut p = rc.borrow_mut();
1794                if p.is_closed() {
1795                    return Err(LuaError::runtime(format_args!(
1796                        "default output file is closed"
1797                    )));
1798                }
1799                let fh = p
1800                    .file
1801                    .as_deref_mut()
1802                    .expect("open stream has no file handle");
1803                fh.flush()
1804            };
1805            return match result {
1806                Ok(()) => {
1807                    state.push(LuaValue::Bool(true));
1808                    Ok(1)
1809                }
1810                Err(e) => file_result(state, false, None, e),
1811            };
1812        }
1813    }
1814    // No live default output file: behave like a successful no-op flush of stdout.
1815    state.push(LuaValue::Bool(true));
1816    Ok(1)
1817}
1818
1819/// `file:flush()`. C: `f_flush`.
1820pub fn f_flush(state: &mut LuaState) -> Result<usize, LuaError> {
1821    let p_rc = tofile(state)?;
1822    let result = {
1823        let mut p = p_rc.borrow_mut();
1824        let fh = p.file.as_mut().expect("open stream has no file handle");
1825        fh.flush()
1826    };
1827    match result {
1828        Ok(()) => {
1829            state.push(LuaValue::Bool(true));
1830            Ok(1)
1831        }
1832        Err(e) => file_result(state, false, None, e),
1833    }
1834}
1835
1836// ── Lines iterator ───────────────────────────────────────────────────────────
1837
1838/// Build the `io_readline` closure with its upvalues and push it.
1839///
1840/// Upvalue layout (C comment):
1841///   1) file handle (first stack value)
1842///   2) number of read-format arguments
1843///   3) toclose flag (bool)
1844///   4..n+3) format arguments
1845fn aux_lines(state: &mut LuaState, toclose: bool) -> Result<(), LuaError> {
1846    // `lua_gettop` is the stack count RELATIVE to the current frame, not the
1847    // absolute `top_idx`; using `state.top()` mirrors that.
1848    let n = state.top() - 1;
1849    if n > MAX_ARG_LINE as i32 {
1850        return Err(lua_vm::debug::arg_error_impl(
1851            state,
1852            MAX_ARG_LINE as i32 + 2,
1853            b"too many arguments",
1854        ));
1855    }
1856    state.push_value_at(1)?;
1857    state.push(LuaValue::Int(n as i64));
1858    state.push(LuaValue::Bool(toclose));
1859    state.rotate(2, 3)?;
1860    state.push_c_closure(io_readline, (3 + n) as i32)?;
1861    Ok(())
1862}
1863
1864/// `file:lines(...)`. C: `f_lines`.
1865pub fn f_lines(state: &mut LuaState) -> Result<usize, LuaError> {
1866    let _ = tofile(state)?; // validates file is open
1867    aux_lines(state, false)?;
1868    Ok(1)
1869}
1870
1871/// `io.lines([filename, ...])`. C: `io_lines`.
1872pub fn io_lines(state: &mut LuaState) -> Result<usize, LuaError> {
1873    if state.type_at(1) == LuaType::None {
1874        state.push(LuaValue::Nil);
1875    }
1876    let toclose = if state.type_at(1) == LuaType::Nil {
1877        state.registry_get(IO_INPUT_KEY)?;
1878        state.replace(1)?;
1879        let _ = tofile(state)?;
1880        false
1881    } else {
1882        let filename = state.check_arg_string(1)?;
1883        opencheck(state, &filename, b"r")?;
1884        state.replace(1)?;
1885        true
1886    };
1887
1888    aux_lines(state, toclose)?;
1889
1890    if toclose && state.global().lua_version.lines_returns_to_be_closed() {
1891        state.push(LuaValue::Nil); // state
1892        state.push(LuaValue::Nil); // control
1893        state.push_value_at(1)?; // file as to-be-closed variable (4th result)
1894        Ok(4)
1895    } else {
1896        Ok(1)
1897    }
1898}
1899
1900/// Iteration function created by `aux_lines`. C: `io_readline`.
1901///
1902/// Upvalue layout matches what `aux_lines` creates:
1903///   upvalue 1: file handle (userdata)
1904///   upvalue 2: n (number of read-format args)
1905///   upvalue 3: toclose flag
1906///   upvalue 4..n+3: format arguments
1907fn io_readline(state: &mut LuaState) -> Result<usize, LuaError> {
1908    let n = match state.value_at(crate::state_stub::upvalue_index(2)) {
1909        LuaValue::Int(i) => i as usize,
1910        _ => 0,
1911    };
1912
1913    let p_rc = lstream_from_upvalue(state, 1)?;
1914
1915    if p_rc.borrow().is_closed() {
1916        return Err(LuaError::runtime(format_args!("file is already closed")));
1917    }
1918
1919    lua_vm::api::set_top(state, 1)?;
1920    state.ensure_stack(n as i32, "too many arguments")?;
1921
1922    for i in 1..=n {
1923        let uv = state.value_at(crate::state_stub::upvalue_index(3 + i as i32));
1924        state.push(uv);
1925    }
1926
1927    let result_n: usize = g_read(state, &p_rc, 2)?;
1928
1929    debug_assert!(result_n > 0, "g_read should return at least one value");
1930
1931    let top = state.top_idx().get() as i32;
1932    let first_result_idx = top - result_n as i32;
1933    let first_truthy = !matches!(
1934        state.stack_at(first_result_idx),
1935        LuaValue::Nil | LuaValue::Bool(false)
1936    );
1937    if first_truthy {
1938        return Ok(result_n);
1939    }
1940
1941    if result_n > 1 {
1942        let err_val = state.stack_at(first_result_idx + 1).clone();
1943        return Err(LuaError::from_value(err_val));
1944    }
1945
1946    let toclose = !matches!(
1947        state.value_at(crate::state_stub::upvalue_index(3)),
1948        LuaValue::Nil | LuaValue::Bool(false)
1949    );
1950    if toclose {
1951        lua_vm::api::set_top(state, 0)?;
1952        state.push_upvalue(1)?;
1953        aux_close(state)?;
1954    }
1955
1956    Ok(0)
1957}
1958
1959// ── Module registration ──────────────────────────────────────────────────────
1960
1961/// Create the file-handle metatable in the registry. C: `createmeta(L)`.
1962fn create_meta(state: &mut LuaState) -> Result<(), LuaError> {
1963    state.new_metatable(LUA_FILE_HANDLE)?;
1964    state.set_funcs(FILE_METAMETHODS, 0)?;
1965    state.new_lib_table(FILE_METHODS)?;
1966    state.set_funcs(FILE_METHODS, 0)?;
1967    state.set_field(-2, b"__index")?;
1968    state.pop_n(1);
1969    Ok(())
1970}
1971
1972/// Register stdin, stdout, or stderr as a Lua file handle. C: `createstdfile`.
1973fn create_std_file(
1974    state: &mut LuaState,
1975    std_kind: StdFileKind,
1976    registry_key: Option<&[u8]>,
1977    field_name: &[u8],
1978) -> Result<(), LuaError> {
1979    let cell = new_pre_file(state)?;
1980    let output_hook = match std_kind {
1981        StdFileKind::Stdout => state.global().stdout_hook,
1982        StdFileKind::Stderr => state.global().stderr_hook,
1983        StdFileKind::Stdin => None,
1984    };
1985    let input_hook = match std_kind {
1986        StdFileKind::Stdin => state.global().stdin_hook,
1987        StdFileKind::Stdout | StdFileKind::Stderr => None,
1988    };
1989    {
1990        let mut p = cell.borrow_mut();
1991        p.file = Some(Box::new(StdStreamHandle::new(
1992            std_kind,
1993            input_hook,
1994            output_hook,
1995        )));
1996        p.close_fn = Some(io_noclose);
1997    }
1998    if let Some(key) = registry_key {
1999        state.push_value_at(-1)?;
2000        state.registry_set(key)?;
2001    }
2002    state.set_field(-2, field_name)?;
2003    Ok(())
2004}
2005
2006/// Open the `io` library and return 1 (the library table). C: `luaopen_io`.
2007pub fn luaopen_io(state: &mut LuaState) -> Result<usize, LuaError> {
2008    state.new_lib(IO_LIB)?;
2009    create_meta(state)?;
2010    create_std_file(state, StdFileKind::Stdin, Some(IO_INPUT_KEY), b"stdin")?;
2011    create_std_file(state, StdFileKind::Stdout, Some(IO_OUTPUT_KEY), b"stdout")?;
2012    create_std_file(state, StdFileKind::Stderr, None, b"stderr")?;
2013    Ok(1)
2014}
2015
2016#[cfg(test)]
2017mod win32_errno_map_tests {
2018    use super::win32_to_crt_errno;
2019
2020    #[test]
2021    fn file_not_found_yields_enoent() {
2022        assert_eq!(win32_to_crt_errno(2), 2, "ERROR_FILE_NOT_FOUND → ENOENT");
2023    }
2024
2025    #[test]
2026    fn path_not_found_yields_enoent() {
2027        assert_eq!(win32_to_crt_errno(3), 2, "ERROR_PATH_NOT_FOUND → ENOENT");
2028    }
2029
2030    #[test]
2031    fn access_denied_yields_eacces() {
2032        assert_eq!(win32_to_crt_errno(5), 13, "ERROR_ACCESS_DENIED → EACCES");
2033    }
2034
2035    #[test]
2036    fn invalid_handle_yields_ebadf() {
2037        assert_eq!(win32_to_crt_errno(6), 9, "ERROR_INVALID_HANDLE → EBADF");
2038    }
2039
2040    #[test]
2041    fn not_enough_memory_yields_enomem() {
2042        assert_eq!(win32_to_crt_errno(8), 12, "ERROR_NOT_ENOUGH_MEMORY → ENOMEM");
2043    }
2044
2045    #[test]
2046    fn arena_trashed_yields_enomem() {
2047        assert_eq!(win32_to_crt_errno(7), 12, "ERROR_ARENA_TRASHED → ENOMEM");
2048    }
2049
2050    #[test]
2051    fn invalid_block_yields_enomem() {
2052        assert_eq!(win32_to_crt_errno(9), 12, "ERROR_INVALID_BLOCK → ENOMEM");
2053    }
2054
2055    #[test]
2056    fn too_many_open_files_yields_emfile() {
2057        assert_eq!(win32_to_crt_errno(4), 24, "ERROR_TOO_MANY_OPEN_FILES → EMFILE");
2058    }
2059
2060    #[test]
2061    fn bad_environment_yields_e2big() {
2062        assert_eq!(win32_to_crt_errno(10), 7, "ERROR_BAD_ENVIRONMENT → E2BIG");
2063    }
2064
2065    #[test]
2066    fn bad_format_yields_enoexec() {
2067        assert_eq!(win32_to_crt_errno(11), 8, "ERROR_BAD_FORMAT → ENOEXEC");
2068    }
2069
2070    #[test]
2071    fn sharing_violation_yields_eacces() {
2072        assert_eq!(win32_to_crt_errno(32), 13, "ERROR_SHARING_VIOLATION → EACCES");
2073    }
2074
2075    #[test]
2076    fn lock_violation_yields_eacces() {
2077        assert_eq!(win32_to_crt_errno(33), 13, "ERROR_LOCK_VIOLATION → EACCES");
2078    }
2079
2080    #[test]
2081    fn file_exists_yields_eexist() {
2082        assert_eq!(win32_to_crt_errno(80), 17, "ERROR_FILE_EXISTS → EEXIST");
2083    }
2084
2085    #[test]
2086    fn already_exists_yields_eexist() {
2087        assert_eq!(win32_to_crt_errno(183), 17, "ERROR_ALREADY_EXISTS → EEXIST");
2088    }
2089
2090    #[test]
2091    fn broken_pipe_yields_epipe() {
2092        assert_eq!(win32_to_crt_errno(109), 32, "ERROR_BROKEN_PIPE → EPIPE");
2093    }
2094
2095    #[test]
2096    fn disk_full_yields_enospc() {
2097        assert_eq!(win32_to_crt_errno(112), 28, "ERROR_DISK_FULL → ENOSPC");
2098    }
2099
2100    #[test]
2101    fn not_same_device_yields_exdev() {
2102        assert_eq!(win32_to_crt_errno(17), 18, "ERROR_NOT_SAME_DEVICE → EXDEV");
2103    }
2104
2105    #[test]
2106    fn invalid_parameter_yields_einval() {
2107        assert_eq!(win32_to_crt_errno(87), 22, "ERROR_INVALID_PARAMETER → EINVAL");
2108    }
2109
2110    #[test]
2111    fn invalid_function_yields_einval() {
2112        assert_eq!(win32_to_crt_errno(1), 22, "ERROR_INVALID_FUNCTION → EINVAL");
2113    }
2114
2115    #[test]
2116    fn bad_pathname_yields_enoent() {
2117        assert_eq!(win32_to_crt_errno(161), 2, "ERROR_BAD_PATHNAME → ENOENT");
2118    }
2119
2120    #[test]
2121    fn filename_exced_range_yields_enoent() {
2122        assert_eq!(win32_to_crt_errno(206), 2, "ERROR_FILENAME_EXCED_RANGE → ENOENT");
2123    }
2124
2125    #[test]
2126    fn network_access_denied_yields_eacces() {
2127        assert_eq!(win32_to_crt_errno(65), 13, "ERROR_NETWORK_ACCESS_DENIED → EACCES");
2128    }
2129
2130    #[test]
2131    fn drive_locked_yields_eacces() {
2132        assert_eq!(win32_to_crt_errno(108), 13, "ERROR_DRIVE_LOCKED → EACCES");
2133    }
2134
2135    #[test]
2136    fn not_enough_quota_yields_enomem() {
2137        assert_eq!(win32_to_crt_errno(1816), 12, "ERROR_NOT_ENOUGH_QUOTA → ENOMEM");
2138    }
2139
2140    #[test]
2141    fn dir_not_empty_yields_windows_crt_enotempty() {
2142        assert_eq!(
2143            win32_to_crt_errno(145),
2144            41,
2145            "ERROR_DIR_NOT_EMPTY → ENOTEMPTY=41 (Windows CRT)"
2146        );
2147    }
2148
2149    #[test]
2150    fn join_and_subst_family_yields_eacces() {
2151        for code in 133u32..=141 {
2152            assert_eq!(win32_to_crt_errno(code), 13, "join/subst error {code} → EACCES");
2153        }
2154    }
2155
2156    #[test]
2157    fn unmapped_codes_yield_einval() {
2158        for code in [0u32, 14, 19, 20, 21, 22, 23, 100, 999, 65535, u32::MAX] {
2159            assert_eq!(
2160                win32_to_crt_errno(code),
2161                22,
2162                "unmapped Win32 code {code} must yield EINVAL=22 (_dosmaperr default)"
2163            );
2164        }
2165    }
2166
2167    #[test]
2168    fn all_table_codes_map_to_positive_errno() {
2169        let mapped_codes: &[u32] = &[
2170            1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 32, 33, 53, 65, 67, 80,
2171            82, 83, 87, 89, 108, 109, 112, 114, 128, 129, 130, 131, 132, 133, 134, 135, 136,
2172            137, 138, 139, 140, 141, 145, 158, 161, 164, 167, 183, 206, 215, 1816,
2173        ];
2174        for &code in mapped_codes {
2175            let errno = win32_to_crt_errno(code);
2176            assert!(
2177                errno > 0,
2178                "Win32 code {code} must map to a positive CRT errno, got {errno}"
2179            );
2180        }
2181    }
2182
2183    #[test]
2184    fn mapped_common_file_errnos_have_posix_strerror_text() {
2185        for win32 in [2u32, 3, 5, 6, 80, 109, 112, 183] {
2186            let errno = win32_to_crt_errno(win32);
2187            assert!(
2188                super::posix_strerror(errno).is_some(),
2189                "Win32 code {win32} maps to errno {errno} which must have strerror text"
2190            );
2191        }
2192    }
2193}