slew 0.2.0

A suspendable Lua interpreter with strict, embedder-controlled execution budgets
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
//! The `io` library, backed entirely by the embedder-installed [`Host`].
//!
//! Nothing here touches the operating system directly: file handles are
//! host-owned ids inside userdata, and standard streams go through the host's
//! `stdin`/`stdout`/`stderr` methods. When no host is installed these
//! functions do not exist at all.

use crate::host::{HostError, HostObject, SeekWhence, Userdata};
use crate::value::UserdataId;
use crate::value::Value;
use crate::vm::Lua;

use super::{arg, check_bytes, set_field};

/// Builds the shared file userdata metatable and its method table. `lines` is
/// added later by the Lua prelude (it needs to close over the format list).
pub(super) fn build_file_metatable<C>(lua: &mut Lua<C>) -> crate::value::TableId {
    let methods = lua.new_table();
    let natives: [(&str, crate::vm::NativeFn<C>); 7] = [
        ("read", n_read),
        ("write", n_write),
        ("seek", n_seek),
        ("close", n_close),
        ("flush", n_flush),
        ("setvbuf", n_setvbuf),
        ("lines", n_lines_stub),
    ];
    for (name, f) in natives {
        let v = lua.add_native(name, f);
        set_field(lua, methods, name, v);
    }

    let meta = lua.new_table();
    let Value::Table(meta_id) = meta else {
        unreachable!()
    };
    let name = lua.new_string(b"FILE*");
    set_field(lua, meta, "__name", name);
    set_field(lua, meta, "__index", methods);
    let tostring = lua.add_native("__tostring", n_tostring);
    set_field(lua, meta, "__tostring", tostring);
    let gc = lua.add_native("__gc", n_gc);
    set_field(lua, meta, "__gc", gc);
    let close = lua.add_native("__close", n_gc);
    set_field(lua, meta, "__close", close);
    // Hand the methods table to the Lua prelude, which adds `lines`.
    lua.set_global("__slew_file_methods", methods);
    meta_id
}

pub(super) fn install<C>(lua: &mut Lua<C>) {
    let file_meta = lua.file_meta.expect("file metatable installed first");
    let io = lua.new_table();
    lua.set_global("io", io);

    let stdin = new_file(lua, HostObject::Stdin, file_meta);
    let stdout = new_file(lua, HostObject::Stdout, file_meta);
    let stderr = new_file(lua, HostObject::Stderr, file_meta);
    set_field(lua, io, "stdin", stdin);
    set_field(lua, io, "stdout", stdout);
    set_field(lua, io, "stderr", stderr);
    let Value::Userdata(stdin_id) = stdin else {
        unreachable!()
    };
    let Value::Userdata(stdout_id) = stdout else {
        unreachable!()
    };
    lua.io_input = Some(stdin_id);
    lua.io_output = Some(stdout_id);

    let entries: [(&str, crate::vm::NativeFn<C>); 8] = [
        ("open", n_open),
        ("close", n_io_close),
        ("read", n_io_read),
        ("write", n_io_write),
        ("input", n_io_input),
        ("output", n_io_output),
        ("type", n_type),
        ("tmpfile", n_tmpfile),
    ];
    for (name, f) in entries {
        let v = lua.add_native(name, f);
        set_field(lua, io, name, v);
    }
}

/// Runs the small Lua prelude that defines `io.lines` and `file:lines` in
/// terms of the native `read` (so their iterator closures are real Lua
/// functions, suspendable like everything else).
pub(super) fn run_prelude<C>(lua: &mut Lua<C>) {
    let chunk = match lua.load_named("=io", include_str!("io_prelude.lua")) {
        Ok(c) => c,
        Err(e) => panic!("io prelude must compile: {e}"),
    };
    if let Err(e) = lua.run_chunk(&chunk) {
        panic!("io prelude failed: {e}");
    }
}

pub(super) fn new_file<C>(
    lua: &mut Lua<C>,
    object: HostObject,
    meta: crate::value::TableId,
) -> Value {
    let ud = Userdata {
        metatable: Some(meta),
        object,
        closed: false,
        finalized: false,
        read_buf: Vec::new(),
        read_pos: 0,
    };
    Value::Userdata(lua.alloc_userdata(ud))
}

/// `nil, "message", errno` return shape used by `io.open` etc.
fn open_failure<C>(lua: &mut Lua<C>, e: &HostError) -> Vec<Value> {
    let msg = lua.new_string(e.message.as_bytes());
    vec![Value::Nil, msg, Value::Int(e.errno as i64)]
}

fn want_file<C>(lua: &Lua<C>, args: &[Value], i: usize, who: &str) -> Result<UserdataId, String> {
    match arg(args, i) {
        Value::Userdata(u) => {
            if lua.userdata[u.0 as usize].closed {
                Err("attempt to use a closed file".into())
            } else {
                Ok(u)
            }
        }
        v => Err(format!(
            "bad argument #{} to '{who}' (FILE* expected, got {})",
            i + 1,
            v.type_name()
        )),
    }
}

// ---- low-level byte access on a file userdata --------------------------

/// Reads more bytes from the host, compacting any consumed prefix first.
/// Returns the number of new bytes (0 at end of file).
fn fill_more<C>(lua: &mut Lua<C>, uid: UserdataId) -> Result<usize, String> {
    let obj = {
        let ud = &mut lua.userdata[uid.0 as usize];
        if ud.read_pos > 0 {
            ud.read_buf.drain(..ud.read_pos);
            ud.read_pos = 0;
        }
        ud.object
    };
    let mut tmp = [0u8; 8192];
    let n = {
        let Some(h) = lua.host.as_mut() else {
            return Err("io library has no host".into());
        };
        match obj {
            HostObject::Stdin => h.stdin_read(&mut tmp),
            HostObject::File(handle) => h.read(handle, &mut tmp),
            _ => return Ok(0),
        }
        .map_err(|e| e.message)?
    };
    lua.userdata[uid.0 as usize]
        .read_buf
        .extend_from_slice(&tmp[..n]);
    Ok(n)
}

/// Ensures at least one buffered byte is available. Returns `true` when bytes
/// are available, `false` at end of file.
fn refill<C>(lua: &mut Lua<C>, uid: UserdataId) -> Result<bool, String> {
    {
        let ud = &lua.userdata[uid.0 as usize];
        if ud.read_pos < ud.read_buf.len() {
            return Ok(true);
        }
    }
    fill_more(lua, uid).map(|n| n > 0)
}

fn peek<C>(lua: &mut Lua<C>, uid: UserdataId) -> Result<Option<u8>, String> {
    if !refill(lua, uid)? {
        return Ok(None);
    }
    let ud = &lua.userdata[uid.0 as usize];
    Ok(Some(ud.read_buf[ud.read_pos]))
}

fn advance<C>(lua: &mut Lua<C>, uid: UserdataId) {
    lua.userdata[uid.0 as usize].read_pos += 1;
}

fn read_line<C>(
    lua: &mut Lua<C>,
    uid: UserdataId,
    keep_newline: bool,
) -> Result<Option<Vec<u8>>, String> {
    loop {
        {
            let ud = &lua.userdata[uid.0 as usize];
            if let Some(rel) = ud.read_buf[ud.read_pos..].iter().position(|&b| b == b'\n') {
                let start = ud.read_pos;
                let nl = start + rel;
                let line = if keep_newline {
                    ud.read_buf[start..=nl].to_vec()
                } else {
                    ud.read_buf[start..nl].to_vec()
                };
                lua.userdata[uid.0 as usize].read_pos = nl + 1;
                return Ok(Some(line));
            }
        }
        // No newline in the buffer yet: append more. `fill_more` compacts the
        // consumed prefix, so a partial line spanning reads is preserved.
        if fill_more(lua, uid)? == 0 {
            let ud = &mut lua.userdata[uid.0 as usize];
            if ud.read_pos < ud.read_buf.len() {
                let line = ud.read_buf[ud.read_pos..].to_vec();
                ud.read_pos = ud.read_buf.len();
                return Ok(Some(line));
            }
            return Ok(None);
        }
    }
}

fn read_count<C>(lua: &mut Lua<C>, uid: UserdataId, n: usize) -> Result<Option<Vec<u8>>, String> {
    if n == 0 {
        return Ok(peek(lua, uid)?.map(|_| Vec::new()));
    }
    let mut out: Vec<u8> = Vec::new();
    // PUC pre-sizes the destination buffer and raises a catchable "not enough
    // memory" error when the reservation fails (`luaL_prepbuffsize`). Do the
    // same via `try_reserve` so a huge numeric format cannot abort the process
    // on an infallible allocation.
    out.try_reserve(n)
        .map_err(|_| "not enough memory".to_string())?;
    while out.len() < n {
        let take_from_buf = {
            let ud = &lua.userdata[uid.0 as usize];
            let avail = ud.read_buf.len() - ud.read_pos;
            if avail > 0 {
                Some(avail.min(n - out.len()))
            } else {
                None
            }
        };
        match take_from_buf {
            Some(take) => {
                let ud = &mut lua.userdata[uid.0 as usize];
                out.extend_from_slice(&ud.read_buf[ud.read_pos..ud.read_pos + take]);
                ud.read_pos += take;
            }
            None => {
                if !refill(lua, uid)? {
                    break;
                }
            }
        }
    }
    if out.is_empty() {
        Ok(None)
    } else {
        Ok(Some(out))
    }
}

fn read_all<C>(lua: &mut Lua<C>, uid: UserdataId) -> Result<Vec<u8>, String> {
    let mut out = Vec::new();
    loop {
        {
            let ud = &lua.userdata[uid.0 as usize];
            if ud.read_pos < ud.read_buf.len() {
                out.extend_from_slice(&ud.read_buf[ud.read_pos..]);
                lua.userdata[uid.0 as usize].read_pos = ud.read_buf.len();
            }
        }
        if !refill(lua, uid)? {
            break;
        }
    }
    Ok(out)
}

/// PUC's `L_MAXLENNUM`: the longest numeral prefix `read("*n")` will buffer.
const MAX_NUMERAL_LEN: usize = 200;

/// Consumes the current byte into `token` when `pred` accepts it, mirroring
/// PUC's `nextc`: once the buffer is full the byte is left unread and `overflow`
/// is set, so an over-long numeral fails instead of growing without bound.
fn accept_byte<C>(
    lua: &mut Lua<C>,
    uid: UserdataId,
    token: &mut Vec<u8>,
    overflow: &mut bool,
    pred: impl Fn(u8) -> bool,
) -> Result<bool, String> {
    let Some(b) = peek(lua, uid)? else {
        return Ok(false);
    };
    if !pred(b) {
        return Ok(false);
    }
    if token.len() >= MAX_NUMERAL_LEN {
        *overflow = true;
        return Ok(false);
    }
    token.push(b);
    advance(lua, uid);
    Ok(true)
}

/// Consumes a run of (hex)digits, returning how many were accepted.
fn accept_digits<C>(
    lua: &mut Lua<C>,
    uid: UserdataId,
    token: &mut Vec<u8>,
    overflow: &mut bool,
    hex: bool,
) -> Result<usize, String> {
    let mut n = 0;
    loop {
        let ok = accept_byte(lua, uid, token, overflow, |b| {
            if hex {
                b.is_ascii_hexdigit()
            } else {
                b.is_ascii_digit()
            }
        })?;
        if !ok {
            return Ok(n);
        }
        n += 1;
    }
}

/// Reads a `"*n"` format. Mirrors PUC's `read_number`: scan only characters
/// that can belong to a numeral (sign, hex prefix, digits, fraction, exponent),
/// leaving every other byte — including a long non-numeric run — unread, then
/// let [`super::parse_number`] validate the scanned prefix. This never rewinds
/// `read_pos`, so a token spanning the read buffer cannot underflow.
fn read_number<C>(lua: &mut Lua<C>, uid: UserdataId) -> Result<Option<Value>, String> {
    // skip leading whitespace
    while let Some(b) = peek(lua, uid)? {
        if b.is_ascii_whitespace() {
            advance(lua, uid);
        } else {
            break;
        }
    }
    let mut token: Vec<u8> = Vec::new();
    let mut overflow = false;
    // optional sign
    accept_byte(lua, uid, &mut token, &mut overflow, |b| {
        matches!(b, b'+' | b'-')
    })?;
    // leading '0', possibly introducing a hexadecimal numeral
    let mut hex = false;
    let mut count = 0usize;
    if accept_byte(lua, uid, &mut token, &mut overflow, |b| b == b'0')? {
        if accept_byte(lua, uid, &mut token, &mut overflow, |b| {
            matches!(b, b'x' | b'X')
        })? {
            hex = true;
        } else {
            count = 1;
        }
    }
    count += accept_digits(lua, uid, &mut token, &mut overflow, hex)?;
    // fractional part
    if accept_byte(lua, uid, &mut token, &mut overflow, |b| b == b'.')? {
        count += accept_digits(lua, uid, &mut token, &mut overflow, hex)?;
    }
    // exponent marker (only if there was a mantissa digit)
    if count > 0 {
        let (mark, mark2) = if hex { (b'p', b'P') } else { (b'e', b'E') };
        if accept_byte(lua, uid, &mut token, &mut overflow, |b| {
            b == mark || b == mark2
        })? {
            accept_byte(lua, uid, &mut token, &mut overflow, |b| {
                matches!(b, b'+' | b'-')
            })?;
            accept_digits(lua, uid, &mut token, &mut overflow, false)?;
        }
    }
    if overflow || token.is_empty() {
        return Ok(None);
    }
    Ok(super::parse_number(&token))
}

/// One `read` format: `Value` result or `None` on failure (EOF).
fn read_one<C>(lua: &mut Lua<C>, uid: UserdataId, fmt: Value) -> Result<Option<Value>, String> {
    match fmt {
        Value::Int(n) => {
            if n < 0 {
                return Err("bad argument to 'read' (invalid format)".into());
            }
            Ok(read_count(lua, uid, n as usize)?.map(|b| lua.new_string(&b)))
        }
        Value::Float(f) => {
            let n = crate::value::float_to_exact_int(f).ok_or_else(|| {
                "bad argument to 'read' (number has no integer representation)".to_string()
            })?;
            if n < 0 {
                return Err("bad argument to 'read' (invalid format)".into());
            }
            Ok(read_count(lua, uid, n as usize)?.map(|b| lua.new_string(&b)))
        }
        Value::Str(id) => {
            let bytes = lua.strings.get(id).to_vec();
            let bytes = bytes.strip_prefix(b"*").unwrap_or(&bytes);
            match bytes.first().copied() {
                Some(b'n') => read_number(lua, uid),
                Some(b'l') => {
                    let line = read_line(lua, uid, false)?;
                    Ok(line.map(|b| lua.new_string(&b)))
                }
                Some(b'L') => {
                    let line = read_line(lua, uid, true)?;
                    Ok(line.map(|b| lua.new_string(&b)))
                }
                Some(b'a') => {
                    let all = read_all(lua, uid)?;
                    Ok(Some(lua.new_string(&all)))
                }
                _ => Err("bad argument to 'read' (invalid format)".into()),
            }
        }
        _ => Err("bad argument to 'read' (invalid format)".into()),
    }
}

fn do_read<C>(lua: &mut Lua<C>, uid: UserdataId, fmts: &[Value]) -> Result<Vec<Value>, String> {
    let mut results = Vec::new();
    if fmts.is_empty() {
        let lfmt = lua.new_string(b"l");
        match read_one(lua, uid, lfmt)? {
            Some(v) => results.push(v),
            None => results.push(Value::Nil),
        }
        return Ok(results);
    }
    for &fmt in fmts {
        if let Some(v) = read_one(lua, uid, fmt)? {
            results.push(v);
        } else {
            results.push(Value::Nil);
            break;
        }
    }
    Ok(results)
}

// ---- natives -----------------------------------------------------------

fn n_read<C>(lua: &mut Lua<C>, args: &[Value]) -> Result<Vec<Value>, String> {
    let uid = want_file(lua, args, 0, "read")?;
    let fmts = args.get(1..).unwrap_or(&[]).to_vec();
    do_read(lua, uid, &fmts)
}

fn n_write<C>(lua: &mut Lua<C>, args: &[Value]) -> Result<Vec<Value>, String> {
    let uid = want_file(lua, args, 0, "write")?;
    let mut bytes = Vec::new();
    for (i, &v) in args.iter().enumerate().skip(1) {
        match v {
            Value::Str(id) => bytes.extend_from_slice(lua.strings.get(id)),
            Value::Int(_) | Value::Float(_) => {
                bytes.extend_from_slice(crate::value::fmt_number(v).as_bytes());
            }
            other => {
                return Err(format!(
                    "bad argument #{} to 'write' (string expected, got {})",
                    i + 1,
                    other.type_name()
                ));
            }
        }
    }
    if let Err(e) = write_handle(lua, uid, &bytes) {
        return Ok(open_failure(lua, &e));
    }
    Ok(vec![args[0]])
}

fn write_handle<C>(lua: &mut Lua<C>, uid: UserdataId, bytes: &[u8]) -> Result<(), HostError> {
    let obj = lua.userdata[uid.0 as usize].object;
    let Some(h) = lua.host.as_mut() else {
        return Err(HostError::new("io library has no host"));
    };
    match obj {
        HostObject::Stdout => h.stdout_write(bytes),
        HostObject::Stderr => h.stderr_write(bytes),
        HostObject::File(handle) => h.write(handle, bytes).map(|_| ()),
        HostObject::Stdin => Err(HostError::new("cannot write to stdin")),
    }
}

fn seek_whence(bytes: &[u8]) -> Option<SeekWhence> {
    match bytes {
        b"set" => Some(SeekWhence::Set),
        b"cur" => Some(SeekWhence::Cur),
        b"end" => Some(SeekWhence::End),
        _ => None,
    }
}

fn n_seek<C>(lua: &mut Lua<C>, args: &[Value]) -> Result<Vec<Value>, String> {
    let uid = want_file(lua, args, 0, "seek")?;
    let whence_bytes = match arg(args, 1) {
        Value::Nil => None,
        v => Some(check_bytes(lua, &[v], 0, "seek")?),
    };
    let offset = match arg(args, 2) {
        Value::Nil => 0,
        Value::Int(i) => i,
        Value::Float(f) => crate::value::float_to_exact_int(f).ok_or_else(|| {
            "bad argument #3 to 'seek' (number has no integer representation)".to_string()
        })?,
        v => {
            return Err(format!(
                "bad argument #3 to 'seek' (number expected, got {})",
                v.type_name()
            ));
        }
    };
    let whence = match &whence_bytes {
        None => SeekWhence::Cur,
        Some(b) => seek_whence(b)
            .ok_or_else(|| "bad argument #2 to 'seek' (invalid option)".to_string())?,
    };
    // Discard buffered read-ahead and translate a `cur` offset accordingly.
    let unread = {
        let ud = &mut lua.userdata[uid.0 as usize];
        let unread = ud.read_buf.len() - ud.read_pos;
        ud.read_buf.clear();
        ud.read_pos = 0;
        unread as i64
    };
    let offset = if whence == SeekWhence::Cur {
        offset - unread
    } else {
        offset
    };
    let obj = lua.userdata[uid.0 as usize].object;
    let result = match obj {
        HostObject::File(handle) => match lua.host.as_mut() {
            Some(h) => h.seek(handle, whence, offset),
            None => return Ok(open_failure(lua, &HostError::new("io library has no host"))),
        },
        _ => {
            return Ok(open_failure(
                lua,
                &HostError::new("cannot seek this stream"),
            ));
        }
    };
    match result {
        Ok(pos) => Ok(vec![Value::Int(pos as i64)]),
        Err(e) => Ok(open_failure(lua, &e)),
    }
}

fn n_close<C>(lua: &mut Lua<C>, args: &[Value]) -> Result<Vec<Value>, String> {
    let uid = want_file(lua, args, 0, "close")?;
    close_handle(lua, uid)?;
    Ok(vec![Value::Bool(true)])
}

fn close_handle<C>(lua: &mut Lua<C>, uid: UserdataId) -> Result<(), String> {
    if lua.userdata[uid.0 as usize].closed {
        return Err("attempt to use a closed file".into());
    }
    let obj = lua.userdata[uid.0 as usize].object;
    lua.userdata[uid.0 as usize].closed = true;
    lua.userdata[uid.0 as usize].read_buf.clear();
    lua.userdata[uid.0 as usize].read_pos = 0;
    if let HostObject::File(handle) = obj
        && let Some(h) = lua.host.as_mut()
    {
        let _ = h.close(handle);
    }
    Ok(())
}

fn n_flush<C>(lua: &mut Lua<C>, args: &[Value]) -> Result<Vec<Value>, String> {
    let uid = want_file(lua, args, 0, "flush")?;
    let obj = lua.userdata[uid.0 as usize].object;
    if let HostObject::File(handle) = obj
        && let Some(h) = lua.host.as_mut()
        && let Err(e) = h.flush(handle)
    {
        return Ok(open_failure(lua, &e));
    }
    Ok(vec![args[0]])
}

fn n_setvbuf<C>(lua: &mut Lua<C>, args: &[Value]) -> Result<Vec<Value>, String> {
    let uid = want_file(lua, args, 0, "setvbuf")?;
    let mode = check_bytes(lua, args, 1, "setvbuf")?;
    if !matches!(&mode[..], b"no" | b"full" | b"line") {
        return Err("bad argument #2 to 'setvbuf' (invalid option)".into());
    }
    let size = match arg(args, 2) {
        Value::Nil => 0usize,
        Value::Int(i) if i >= 0 => i as usize,
        _ => return Err("bad argument #3 to 'setvbuf' (number expected)".into()),
    };
    let obj = lua.userdata[uid.0 as usize].object;
    if let HostObject::File(handle) = obj
        && let Some(h) = lua.host.as_mut()
        && let Err(e) = h.setvbuf(handle, &mode, size)
    {
        return Ok(open_failure(lua, &e));
    }
    Ok(vec![args[0]])
}

fn n_lines_stub<C>(_lua: &mut Lua<C>, _args: &[Value]) -> Result<Vec<Value>, String> {
    // Replaced by the Lua prelude's `methods:lines`.
    Err("bad argument #1 to 'lines' (FILE* expected)".into())
}

fn n_tostring<C>(lua: &mut Lua<C>, args: &[Value]) -> Result<Vec<Value>, String> {
    let uid = want_file(lua, args, 0, "tostring")?;
    let s = if lua.userdata[uid.0 as usize].closed {
        "file (closed)".to_string()
    } else {
        format!("file (0x{:08x})", uid.0)
    };
    Ok(vec![lua.new_string(s.as_bytes())])
}

fn n_gc<C>(lua: &mut Lua<C>, args: &[Value]) -> Result<Vec<Value>, String> {
    if let Value::Userdata(u) = arg(args, 0)
        && !lua.userdata[u.0 as usize].closed
    {
        let _ = close_handle(lua, u);
    }
    Ok(vec![])
}

// ---- io.* --------------------------------------------------------------

fn valid_mode(mode: &[u8]) -> bool {
    if !matches!(mode.first(), Some(b'r' | b'w' | b'a')) {
        return false;
    }
    let mut plus = false;
    for &b in &mode[1..] {
        match b {
            b'b' => {}
            b'+' if !plus => plus = true,
            _ => return false,
        }
    }
    true
}

fn n_open<C>(lua: &mut Lua<C>, args: &[Value]) -> Result<Vec<Value>, String> {
    let path = check_bytes(lua, args, 0, "open")?;
    let mode = match arg(args, 1) {
        Value::Nil => b"r".to_vec(),
        v => check_bytes(lua, &[v], 0, "open")?,
    };
    if !valid_mode(&mode) {
        return Err("bad argument #2 to 'open' (invalid mode)".into());
    }
    let path_str = String::from_utf8_lossy(&path).into_owned();
    let mode_str = String::from_utf8_lossy(&mode).into_owned();
    let file_meta = lua.file_meta.expect("file metatable");
    let Some(h) = lua.host.as_mut() else {
        return Ok(open_failure(lua, &HostError::new("io library has no host")));
    };
    match h.open(&path_str, &mode_str) {
        Ok(handle) => Ok(vec![new_file(lua, HostObject::File(handle), file_meta)]),
        Err(mut e) => {
            e.message = format!("{path_str}: {}", e.message);
            Ok(open_failure(lua, &e))
        }
    }
}

fn default_input<C>(lua: &mut Lua<C>, who: &str) -> Result<UserdataId, String> {
    lua.io_input
        .ok_or_else(|| format!("bad argument #1 to '{who}' (no default input)"))
}

fn default_output<C>(lua: &mut Lua<C>, who: &str) -> Result<UserdataId, String> {
    lua.io_output
        .ok_or_else(|| format!("bad argument #1 to '{who}' (no default output)"))
}

fn n_io_read<C>(lua: &mut Lua<C>, args: &[Value]) -> Result<Vec<Value>, String> {
    let uid = default_input(lua, "read")?;
    let fmts = args.to_vec();
    do_read(lua, uid, &fmts)
}

fn n_io_write<C>(lua: &mut Lua<C>, args: &[Value]) -> Result<Vec<Value>, String> {
    let uid = default_output(lua, "write")?;
    let mut bytes = Vec::new();
    for (i, &v) in args.iter().enumerate() {
        match v {
            Value::Str(id) => bytes.extend_from_slice(lua.strings.get(id)),
            Value::Int(_) | Value::Float(_) => {
                bytes.extend_from_slice(crate::value::fmt_number(v).as_bytes());
            }
            other => {
                return Err(format!(
                    "bad argument #{} to 'write' (string expected, got {})",
                    i + 1,
                    other.type_name()
                ));
            }
        }
    }
    if let Err(e) = write_handle(lua, uid, &bytes) {
        return Ok(open_failure(lua, &e));
    }
    Ok(vec![Value::Userdata(uid)])
}

fn n_io_close<C>(lua: &mut Lua<C>, args: &[Value]) -> Result<Vec<Value>, String> {
    let uid = match arg(args, 0) {
        Value::Nil => default_output(lua, "close")?,
        v => match v {
            Value::Userdata(u) => u,
            other => {
                return Err(format!(
                    "bad argument #1 to 'close' (FILE* expected, got {})",
                    other.type_name()
                ));
            }
        },
    };
    if lua.userdata[uid.0 as usize].closed {
        return Err("attempt to use a closed file".into());
    }
    close_handle(lua, uid)?;
    Ok(vec![Value::Bool(true)])
}

/// Opens a named file for `io.input`/`io.output`: `Ok(file)` or `Err(message)`
/// so the wrapper can raise with a PUC-shaped message.
fn open_named<C>(lua: &mut Lua<C>, name: &[u8], mode: &[u8]) -> Result<Value, String> {
    let file_meta = lua.file_meta.expect("file metatable");
    let path = String::from_utf8_lossy(name).into_owned();
    let mode_str = String::from_utf8_lossy(mode).into_owned();
    let opened = {
        let Some(h) = lua.host.as_mut() else {
            return Err(format!("cannot open file '{path}' (no host)"));
        };
        h.open(&path, &mode_str)
    };
    match opened {
        Ok(handle) => Ok(new_file(lua, HostObject::File(handle), file_meta)),
        Err(e) => Err(format!("cannot open file '{path}' ({})", e.message)),
    }
}

fn n_io_input<C>(lua: &mut Lua<C>, args: &[Value]) -> Result<Vec<Value>, String> {
    set_default_stream(lua, args, true)
}

fn n_io_output<C>(lua: &mut Lua<C>, args: &[Value]) -> Result<Vec<Value>, String> {
    set_default_stream(lua, args, false)
}

fn set_default_stream<C>(
    lua: &mut Lua<C>,
    args: &[Value],
    input: bool,
) -> Result<Vec<Value>, String> {
    match arg(args, 0) {
        Value::Nil => {
            let uid = if input {
                default_input(lua, "input")?
            } else {
                default_output(lua, "output")?
            };
            Ok(vec![Value::Userdata(uid)])
        }
        Value::Str(id) => {
            let name = lua.strings.get(id).to_vec();
            let mode: &[u8] = if input { b"r" } else { b"w" };
            let f = open_named(lua, &name, mode)?;
            let Value::Userdata(uid) = f else {
                unreachable!()
            };
            if input {
                lua.io_input = Some(uid);
            } else {
                lua.io_output = Some(uid);
            }
            Ok(vec![f])
        }
        Value::Userdata(uid) => {
            if input {
                lua.io_input = Some(uid);
            } else {
                lua.io_output = Some(uid);
            }
            Ok(vec![Value::Userdata(uid)])
        }
        other => Err(format!(
            "bad argument #1 to '{}' (string expected, got {})",
            if input { "input" } else { "output" },
            other.type_name()
        )),
    }
}

fn n_type<C>(lua: &mut Lua<C>, args: &[Value]) -> Result<Vec<Value>, String> {
    let file_meta = lua.file_meta;
    match arg(args, 0) {
        Value::Userdata(u) if lua.userdata[u.0 as usize].metatable == file_meta => {
            let s = if lua.userdata[u.0 as usize].closed {
                "closed file"
            } else {
                "file"
            };
            Ok(vec![lua.new_string(s.as_bytes())])
        }
        _ => Ok(vec![Value::Nil]),
    }
}

fn n_tmpfile<C>(lua: &mut Lua<C>, _args: &[Value]) -> Result<Vec<Value>, String> {
    let file_meta = lua.file_meta.expect("file metatable");
    let name = {
        let Some(h) = lua.host.as_mut() else {
            return Ok(open_failure(lua, &HostError::new("io library has no host")));
        };
        h.tmpname()
    };
    let name = match name {
        Ok(n) => n,
        Err(e) => return Ok(open_failure(lua, &e)),
    };
    let opened = {
        let Some(h) = lua.host.as_mut() else {
            return Ok(open_failure(lua, &HostError::new("io library has no host")));
        };
        h.open(&name, "w+")
    };
    match opened {
        Ok(handle) => Ok(vec![new_file(lua, HostObject::File(handle), file_meta)]),
        Err(e) => Ok(open_failure(lua, &e)),
    }
}