1use std::io::SeekFrom;
10
11use super::R;
12use crate::value::Value;
13use crate::vm::{Args, Lua, LuaError};
14
15#[derive(Clone, Debug, PartialEq, Eq)]
18pub struct IoError {
19 pub message: String,
21 pub code: i64,
23}
24
25impl IoError {
26 pub fn new(message: impl Into<String>, code: i64) -> IoError {
28 IoError { message: message.into(), code }
29 }
30}
31
32fn not_found() -> IoError {
33 IoError::new("No such file or directory", 2)
34}
35
36fn bad_descriptor() -> IoError {
37 IoError::new("Bad file descriptor", 9)
38}
39
40fn illegal_seek() -> IoError {
41 IoError::new("Illegal seek", 29)
42}
43
44pub trait Stream: Send {
48 fn read(&mut self, _buf: &mut [u8]) -> Result<usize, IoError> {
50 Err(bad_descriptor())
51 }
52 fn write(&mut self, _data: &[u8]) -> Result<(), IoError> {
54 Err(bad_descriptor())
55 }
56 fn flush(&mut self) -> Result<(), IoError> {
58 Ok(())
59 }
60 fn seek(&mut self, _pos: SeekFrom) -> Result<u64, IoError> {
62 Err(illegal_seek())
63 }
64 fn close(&mut self) -> Result<(), IoError> {
66 Ok(())
67 }
68}
69
70const BUF: usize = 4096;
72const MAXLENNUM: usize = 200;
74const MAXARGLINE: usize = 250;
76
77pub(crate) enum Backing {
78 Output,
80 Stream(Box<dyn Stream>),
81 Empty,
83}
84
85pub(crate) struct FileState {
87 backing: Backing,
88 buf: Vec<u8>,
89 pos: usize,
90 error: Option<IoError>,
92}
93
94impl FileState {
95 pub(crate) fn new(backing: Backing) -> FileState {
96 FileState { backing, buf: Vec::new(), pos: 0, error: None }
97 }
98
99 fn fill(&mut self, lua: &mut Lua) -> Result<bool, LuaError> {
102 if self.pos < self.buf.len() {
103 return Ok(true);
104 }
105 self.pos = 0;
106 self.buf.resize(BUF, 0);
107 let r = match &mut self.backing {
108 Backing::Stream(s) => s.read(&mut self.buf),
109 Backing::Empty => Ok(0),
110 Backing::Output => Err(bad_descriptor()),
111 };
112 let n = r.unwrap_or_else(|e| {
113 self.error = Some(e);
114 0
115 });
116 self.buf.truncate(n.min(BUF));
117 lua.charge(1 + n as u64 / 32)?;
118 Ok(n > 0)
119 }
120
121 fn getc(&mut self, lua: &mut Lua) -> Result<Option<u8>, LuaError> {
122 if !self.fill(lua)? {
123 return Ok(None);
124 }
125 self.pos += 1;
126 Ok(self.buf.get(self.pos - 1).copied())
127 }
128
129 fn unread(&mut self) -> i64 {
132 let n = self.buf.len().saturating_sub(self.pos) as i64;
133 self.buf.clear();
134 self.pos = 0;
135 n
136 }
137
138 fn write(&mut self, lua: &mut Lua, b: &[u8]) -> Result<Result<(), IoError>, LuaError> {
139 lua.charge(1 + b.len() as u64 / 32)?;
140 let n = self.unread();
141 Ok(match &mut self.backing {
142 Backing::Output => super::base::emit_output(lua, b).map(|()| Ok(()))?,
143 Backing::Stream(s) => {
144 if n > 0 {
145 let _ = s.seek(SeekFrom::Current(-n));
146 }
147 s.write(b)
148 }
149 Backing::Empty => Err(bad_descriptor()),
150 })
151 }
152}
153
154pub(crate) struct LFile {
156 std: Option<usize>,
157 closed: bool,
158 state: Option<FileState>,
159}
160
161pub(super) fn open(lua: &mut Lua) {
162 let t = lua.lib_table("io");
163 let fns: [(&str, &'static str, crate::vm::NativeFn); 9] = [
164 ("close", "io.close", io_close),
165 ("flush", "io.flush", |l, _| {
166 let f = default_file(l, "_IO_output", true)?;
167 flush(l, f)
168 }),
169 ("input", "io.input", |l, a| g_iofile(l, a, "_IO_input", b"r")),
170 ("lines", "io.lines", io_lines),
171 ("open", "io.open", io_open),
172 ("output", "io.output", |l, a| g_iofile(l, a, "_IO_output", b"w")),
173 ("read", "io.read", |l, a| {
174 let f = default_file(l, "_IO_input", true)?;
175 g_read(l, f, &args_from(l, a, 0), 1)
176 }),
177 ("type", "io.type", io_type),
178 ("write", "io.write", |l, a| {
179 let f = default_file(l, "_IO_output", true)?;
180 g_write(l, f, a, 0)
181 }),
182 ];
183 for (n, q, f) in fns {
184 lua.set_fn(t, n, q, f);
185 }
186 let (Ok(meta), Ok(methods)) = (lua.new_table(0, 8), lua.new_table(0, 8)) else { return };
189 let ms: [(&str, &'static str, crate::vm::NativeFn); 7] = [
190 ("read", "read_aux", |l, a| {
191 let f = to_file(l, a)?;
192 g_read(l, f, &args_from(l, a, 1), 2)
193 }),
194 ("write", "write_aux", |l, a| g_write(l, to_file(l, a)?, a, 1)),
195 ("lines", "lines_aux", |l, a| {
196 let f = aux_lines(l, to_file(l, a)?, a, false)?;
197 l.ret1(f)
198 }),
199 ("flush", "flush_aux", |l, a| flush(l, to_file(l, a)?)),
200 ("seek", "seek_aux", f_seek),
201 ("close", "close_aux", |l, a| aux_close(l, to_file(l, a)?)),
202 ("setvbuf", "setvbuf_aux", |l, a| {
203 to_file(l, a)?;
204 l.check_option(a, 1, None, &["no", "full", "line"])?;
205 l.opt_int(a, 2, 0)?;
206 l.ret1(Value::Bool(true))
207 }),
208 ];
209 for (n, q, f) in ms {
210 lua.set_fn(methods, n, q, f);
211 }
212 lua.set_field(meta, "__index", Value::Table(methods));
213 lua.set_fn(meta, "__close", "__close_aux", f_gc);
214 lua.set_fn(meta, "__tostring", "__tostring_aux", f_tostring);
215 let name = lua.new_str(b"FILE*").unwrap_or_default();
216 lua.set_field(meta, "__name", name);
217 let reg = lua.registry;
218 let _ = lua.raw_set(reg, name, Value::Table(meta));
219 lua.io_meta = Some(meta);
220 for (i, field, key) in [(0, "stdin", "_IO_input"), (1, "stdout", "_IO_output"), (2, "stderr", "")] {
221 let Ok(f) = new_file(lua, LFile { std: Some(i), closed: false, state: None }) else { return };
222 if !key.is_empty() {
223 lua.set_field(reg, key, f);
224 }
225 lua.set_field(t, field, f);
226 }
227}
228
229fn new_file(lua: &mut Lua, f: LFile) -> Result<Value, LuaError> {
230 let size = std::mem::size_of::<LFile>() + if f.std.is_some() { 0 } else { BUF };
231 let v = Value::UserData(lua.alloc_ud(Box::new(f), size, lua.io_meta)?);
232 lua.hold(v);
233 Ok(v)
234}
235
236fn lfile(lua: &Lua, v: Value) -> Option<&LFile> {
237 let Value::UserData(u) = v else { return None };
238 lua.heap.uds.get(u.idx)?.data.as_ref()?.downcast_ref::<LFile>()
239}
240
241fn lfile_mut(lua: &mut Lua, v: Value) -> Option<&mut LFile> {
242 let Value::UserData(u) = v else { return None };
243 lua.heap.uds.get_mut(u.idx)?.data.as_mut()?.downcast_mut::<LFile>()
244}
245
246fn check_file(lua: &Lua, a: Args) -> Result<Value, LuaError> {
248 let v = lua.arg(a, 0);
249 if lfile(lua, v).is_some() { Ok(v) } else { Err(lua.type_error(a, 0, "FILE*")) }
250}
251
252fn open_file(lua: &Lua, v: Value) -> Result<Value, LuaError> {
254 if lfile(lua, v).is_some_and(|f| f.closed) { Err(LuaError::msg("attempt to use a closed file")) } else { Ok(v) }
255}
256
257fn to_file(lua: &Lua, a: Args) -> Result<Value, LuaError> {
258 let v = check_file(lua, a)?;
259 open_file(lua, v)
260}
261
262fn default_file(lua: &mut Lua, key: &str, strict: bool) -> Result<Value, LuaError> {
265 let k = lua.new_str(key.as_bytes())?;
266 let v = lua.raw_get(lua.registry, k);
267 if strict && lfile(lua, v).is_none_or(|f| f.closed) {
268 return Err(LuaError::msg(format!("default {} file is closed", key.get(4..).unwrap_or_default())));
269 }
270 open_file(lua, v)
271}
272
273fn with_state<T>(lua: &mut Lua, v: Value, op: impl FnOnce(&mut Lua, &mut FileState) -> Result<T, LuaError>) -> Result<T, LuaError> {
275 let std = lfile(lua, v).and_then(|f| f.std);
276 let taken = match std {
277 Some(i) => lua.io_std.get_mut(i).and_then(Option::take),
278 None => lfile_mut(lua, v).and_then(|f| f.state.take()),
279 };
280 let mut st = taken.unwrap_or_else(|| FileState::new(if std.is_some_and(|i| i > 0) { Backing::Output } else { Backing::Empty }));
281 let r = op(lua, &mut st);
282 match std {
283 Some(i) => {
284 if let Some(s) = lua.io_std.get_mut(i) {
285 *s = Some(st);
286 }
287 }
288 None => {
289 if let Some(f) = lfile_mut(lua, v) {
290 f.state = Some(st);
291 }
292 }
293 }
294 r
295}
296
297fn file_result(lua: &mut Lua, r: Result<(), IoError>, fname: Option<&[u8]>) -> R {
299 let Err(e) = r else { return lua.ret1(Value::Bool(true)) };
300 let mut msg = fname.map(|n| [n, b": "].concat()).unwrap_or_default();
301 msg.extend_from_slice(e.message.as_bytes());
302 let m = lua.new_str(&msg)?;
303 lua.ret(&[Value::Nil, m, Value::Int(e.code)])
304}
305
306fn host_open(lua: &mut Lua, name: &[u8], mode: &[u8]) -> Result<Result<Value, IoError>, LuaError> {
308 lua.charge(16 + name.len() as u64 / 32)?;
309 let opened = match (lua.io_opener.clone(), std::str::from_utf8(name), std::str::from_utf8(mode)) {
310 (Some(o), Ok(n), Ok(m)) => o(n, m),
311 _ => Err(not_found()),
312 };
313 Ok(match opened {
314 Ok(s) => Ok(new_file(lua, LFile { std: None, closed: false, state: Some(FileState::new(Backing::Stream(s))) })?),
315 Err(e) => Err(e),
316 })
317}
318
319fn c_str(lua: &mut Lua, a: Args, i: usize) -> Result<Vec<u8>, LuaError> {
321 let s = lua.check_str(a, i)?;
322 Ok(lua.bytes(s).split(|&c| c == 0).next().unwrap_or_default().to_vec())
323}
324
325fn open_check(lua: &mut Lua, a: Args, mode: &[u8]) -> Result<Value, LuaError> {
327 let name = c_str(lua, a, 0)?;
328 host_open(lua, &name, mode)?.map_err(|e| LuaError::msg(format!("cannot open file '{}' ({})", String::from_utf8_lossy(&name), e.message)))
329}
330
331fn io_open(lua: &mut Lua, a: Args) -> R {
332 let name = c_str(lua, a, 0)?;
333 let mode = if lua.arg(a, 1).is_nil() { b"r".to_vec() } else { c_str(lua, a, 1)? };
334 let rest = mode.get(1..).unwrap_or_default();
336 let rest = rest.strip_prefix(b"+").unwrap_or(rest);
337 if !matches!(mode.first(), Some(b'r' | b'w' | b'a')) || rest.iter().any(|&c| c != b'b') {
338 return Err(LuaError::Arg(2, "invalid mode".into()));
339 }
340 match host_open(lua, &name, &mode)? {
341 Ok(f) => lua.ret1(f),
342 Err(e) => file_result(lua, Err(e), Some(&name)),
343 }
344}
345
346fn io_type(lua: &mut Lua, a: Args) -> R {
347 let v = lua.check_any(a, 0)?;
348 match lfile(lua, v) {
349 None => lua.ret1(Value::Nil),
350 Some(f) => lua.ret_str(if f.closed { b"closed file" } else { b"file" }),
351 }
352}
353
354fn f_tostring(lua: &mut Lua, a: Args) -> R {
355 let v = check_file(lua, a)?;
356 if lfile(lua, v).is_some_and(|f| f.closed) {
357 return lua.ret_str(b"file (closed)");
358 }
359 lua.ret_str(format!("file (0x{:08x})", crate::vm::address_of(v)).as_bytes())
360}
361
362fn aux_close(lua: &mut Lua, v: Value) -> R {
364 lua.charge(4)?;
365 if lfile(lua, v).is_some_and(|f| f.std.is_some()) {
366 let m = lua.new_str(b"cannot close standard file")?;
367 return lua.ret(&[Value::Nil, m]);
368 }
369 let st = lfile_mut(lua, v).and_then(|f| {
370 f.closed = true;
371 f.state.take()
372 });
373 let r = match st {
374 Some(FileState { backing: Backing::Stream(mut s), .. }) => s.flush().and(s.close()),
375 _ => Ok(()),
376 };
377 file_result(lua, r, None)
378}
379
380fn io_close(lua: &mut Lua, a: Args) -> R {
381 let v = if a.n == 0 { default_file(lua, "_IO_output", false)? } else { to_file(lua, a)? };
382 aux_close(lua, v)
383}
384
385fn f_gc(lua: &mut Lua, a: Args) -> R {
387 let v = check_file(lua, a)?;
388 if lfile(lua, v).is_some_and(|f| !f.closed) {
389 aux_close(lua, v)?;
390 }
391 lua.ret(&[])
392}
393
394fn g_iofile(lua: &mut Lua, a: Args, key: &str, mode: &[u8]) -> R {
396 let k = lua.new_str(key.as_bytes())?;
397 let f = match lua.arg(a, 0) {
398 Value::Nil => lua.raw_get(lua.registry, k),
399 Value::Str(_) | Value::Int(_) | Value::Num(_) => open_check(lua, a, mode)?,
400 _ => to_file(lua, a)?,
401 };
402 let reg = lua.registry;
403 lua.raw_set(reg, k, f)?;
404 lua.ret1(f)
405}
406
407fn read_bytes(lua: &mut Lua, st: &mut FileState, n: u64, line: bool) -> Result<(Vec<u8>, bool), LuaError> {
412 let mut out = Vec::new();
413 let mut hold = super::MemHold::default();
414 while (out.len() as u64) < n && st.fill(lua)? {
415 let rest = st.buf.get(st.pos..).unwrap_or_default();
416 let room = usize::try_from(n - out.len() as u64).unwrap_or(usize::MAX).min(rest.len());
417 let nl = if line { rest.get(..room).and_then(|r| r.iter().position(|&c| c == b'\n')) } else { None };
418 let take = nl.unwrap_or(room);
419 if out.len() + take > lua.limits.string_len {
420 return Err(LuaError::Limit(crate::LimitKind::Memory));
421 }
422 out.extend_from_slice(rest.get(..take).unwrap_or_default());
423 hold.cover(lua, out.capacity())?;
424 st.pos += take;
425 if nl.is_some() {
426 st.pos += 1;
427 return Ok((out, true));
428 }
429 }
430 Ok((out, false))
431}
432
433fn read_number(lua: &mut Lua, st: &mut FileState) -> Result<Option<Value>, LuaError> {
435 let mut buf = Vec::new();
436 let mut c = st.getc(lua)?;
437 while c.is_some_and(|c| matches!(c, b' ' | b'\t' | b'\n' | b'\x0b' | b'\x0c' | b'\r')) {
438 c = st.getc(lua)?;
439 }
440 let mut bad = false;
443 let mut accept = |lua: &mut Lua, st: &mut FileState, c: &mut Option<u8>, ok: &dyn Fn(u8) -> bool| -> Result<bool, LuaError> {
444 match *c {
445 Some(x) if ok(x) && !bad => {
446 bad = buf.len() >= MAXLENNUM;
447 if !bad {
448 buf.push(x);
449 *c = st.getc(lua)?;
450 }
451 Ok(!bad)
452 }
453 _ => Ok(false),
454 }
455 };
456 let mut count = 0;
457 accept(lua, st, &mut c, &|x| x == b'-' || x == b'+')?;
458 let hex = if accept(lua, st, &mut c, &|x| x == b'0')? {
459 let hex = accept(lua, st, &mut c, &|x| x == b'x' || x == b'X')?;
460 count = usize::from(!hex);
461 hex
462 } else {
463 false
464 };
465 let digit = move |x: u8| if hex { x.is_ascii_hexdigit() } else { x.is_ascii_digit() };
466 while accept(lua, st, &mut c, &digit)? {
467 count += 1;
468 }
469 if accept(lua, st, &mut c, &|x| x == b'.')? {
470 while accept(lua, st, &mut c, &digit)? {
471 count += 1;
472 }
473 }
474 if count > 0 && accept(lua, st, &mut c, &|x| if hex { x == b'p' || x == b'P' } else { x == b'e' || x == b'E' })? {
475 accept(lua, st, &mut c, &|x| x == b'-' || x == b'+')?;
476 while accept(lua, st, &mut c, &|x: u8| x.is_ascii_digit())? {}
477 }
478 if c.is_some() {
479 st.pos -= 1; }
481 Ok(if bad { None } else { crate::number::str_to_number(&buf) })
482}
483
484fn g_read(lua: &mut Lua, v: Value, formats: &[Value], argn0: usize) -> R {
486 lua.charge(4)?;
487 let mut results = Vec::with_capacity(formats.len().max(1));
488 let line = [Value::Nil];
489 let fmts = if formats.is_empty() { &line[..] } else { formats };
490 let err = with_state(lua, v, |lua, st| {
491 st.error = None;
492 for (k, &f) in fmts.iter().enumerate() {
493 let argn = argn0 + k;
494 let kind = match f {
495 Value::Nil => b'l',
496 Value::Int(_) | Value::Num(_) => b'#',
497 Value::Str(s) => {
498 let b = lua.bytes(s);
499 b.strip_prefix(b"*").unwrap_or(b).first().copied().unwrap_or(0)
500 }
501 other => return Err(LuaError::Arg(argn, format!("string expected, got {}", lua.arg_type_name(other)))),
502 };
503 let read: Option<Result<Vec<u8>, Value>> = match kind {
505 b'#' => match lua.tointeger(f) {
506 Some(0) => st.fill(lua)?.then(|| Ok(Vec::new())), Some(n) => Some(read_bytes(lua, st, n as u64, false)?.0).filter(|b| !b.is_empty()).map(Ok),
508 None => return Err(LuaError::Arg(argn, "number has no integer representation".into())),
509 },
510 b'n' => read_number(lua, st)?.map(Err),
511 b'l' | b'L' => {
512 let (mut b, nl) = read_bytes(lua, st, u64::MAX, true)?;
513 if nl && kind == b'L' {
514 b.push(b'\n');
515 }
516 (nl || !b.is_empty()).then_some(Ok(b))
517 }
518 b'a' => Some(Ok(read_bytes(lua, st, u64::MAX, false)?.0)),
519 _ => return Err(LuaError::Arg(argn, "invalid format".into())),
520 };
521 let val = match read {
522 Some(Ok(b)) => lua.new_str(&b)?,
523 Some(Err(n)) => n,
524 None => {
525 results.push(Value::Nil);
526 break;
527 }
528 };
529 lua.hold(val);
530 results.push(val);
531 }
532 Ok(st.error.take())
533 })?;
534 if let Some(e) = err {
535 return file_result(lua, Err(e), None);
536 }
537 lua.ret(&results)
538}
539
540fn args_from(lua: &Lua, a: Args, from: usize) -> Vec<Value> {
541 (from..a.n).map(|i| lua.arg(a, i)).collect()
542}
543
544fn aux_lines(lua: &mut Lua, v: Value, a: Args, close: bool) -> Result<Value, LuaError> {
546 if a.n > MAXARGLINE + 1 {
547 return Err(LuaError::Arg(MAXARGLINE + 2, "too many arguments".into()));
548 }
549 let mut up = vec![v, Value::Bool(close)];
550 up.extend(args_from(lua, a, 1));
551 lua.new_native(io_readline, "io_readline_aux", up)
552}
553
554fn io_lines(lua: &mut Lua, a: Args) -> R {
555 if lua.arg(a, 0).is_nil() {
556 let f = default_file(lua, "_IO_input", false)?;
557 let it = aux_lines(lua, f, a, false)?;
558 return lua.ret1(it);
559 }
560 let file = open_check(lua, a, b"r")?;
561 let it = aux_lines(lua, file, a, true)?;
562 lua.ret(&[it, Value::Nil, Value::Nil, file])
563}
564
565fn io_readline(lua: &mut Lua, a: Args) -> R {
567 let v = lua.native_upval(a, 0);
568 if lfile(lua, v).is_none_or(|f| f.closed) {
569 return Err(LuaError::msg("file is already closed"));
570 }
571 let fmts: Vec<Value> = (2..lua.native_upvals_len(a)).map(|i| lua.native_upval(a, i)).collect();
572 g_read(lua, v, &fmts, 2)?; let results = lua.rets.clone();
574 match results.as_slice() {
575 [first, ..] if first.truthy() => lua.ret(&results),
576 [_, Value::Str(m), ..] => Err(LuaError::msg(String::from_utf8_lossy(lua.bytes(*m)).into_owned())),
577 _ => {
578 if lua.native_upval(a, 1).truthy() {
579 aux_close(lua, v)?;
580 }
581 lua.ret(&[])
582 }
583 }
584}
585
586fn g_write(lua: &mut Lua, v: Value, a: Args, first: usize) -> R {
590 lua.charge(4)?;
591 let mut status = Ok(());
592 for i in first..a.n {
593 let bytes = match lua.arg(a, i) {
594 Value::Int(n) => n.to_string().into_bytes(),
595 Value::Num(f) => {
596 lua.charge(crate::vm::FLOAT_TEXT_FUEL)?;
597 crate::number::fmt_g(f, 14, false, false).into_bytes()
598 }
599 _ => {
600 let s = lua.check_str(a, i)?;
601 lua.bytes(s).to_vec()
602 }
603 };
604 if status.is_ok() {
605 status = with_state(lua, v, |lua, st| st.write(lua, &bytes))?;
606 }
607 }
608 if status.is_ok() { lua.ret1(v) } else { file_result(lua, status, None) }
609}
610
611fn f_seek(lua: &mut Lua, a: Args) -> R {
612 let v = to_file(lua, a)?;
613 let op = lua.check_option(a, 1, Some("cur"), &["set", "cur", "end"])?;
614 let off = lua.opt_int(a, 2, 0)?;
615 lua.charge(4)?;
616 let r = with_state(lua, v, |_, st| {
617 let unread = st.unread();
619 let to = match op {
620 0 => match u64::try_from(off) {
621 Ok(o) => SeekFrom::Start(o),
622 Err(_) => return Ok(Err(IoError::new("Invalid argument", 22))),
623 },
624 1 => SeekFrom::Current(off.saturating_sub(unread)),
625 _ => SeekFrom::End(off),
626 };
627 Ok(if let Backing::Stream(s) = &mut st.backing { s.seek(to) } else { Err(illegal_seek()) })
628 })?;
629 match r {
630 Ok(p) => lua.ret1(Value::Int(i64::try_from(p).unwrap_or(i64::MAX))),
631 Err(e) => file_result(lua, Err(e), None),
632 }
633}
634
635fn flush(lua: &mut Lua, v: Value) -> R {
636 lua.charge(4)?;
637 let r = with_state(lua, v, |_, st| Ok(if let Backing::Stream(s) = &mut st.backing { s.flush() } else { Ok(()) }))?;
638 file_result(lua, r, None)
639}