lua-cli 0.0.13

The lua-rs command-line interpreter: Lua 5.4 in safe Rust.
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
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
//! Standalone `lua-rs` interpreter — minimal entry point that exercises the
//! full pipeline: `new_state` → `open_libs` → `load_string` → `pcall_k`.
//!
//! This is intentionally minimal — its job is to surface which `todo!()`
//! stubs block real execution, NOT to be a complete Lua interpreter.
//!
//! Usage:
//!   lua-rs '<lua source>'
//! Examples:
//!   lua-rs 'print("hello")'
//!   lua-rs '1+1'

use std::io::{self, BufReader, BufWriter, Read, Seek, SeekFrom, Write};
use std::panic::{catch_unwind, AssertUnwindSafe};
use std::process::ExitCode;

use lua_types::closure::LuaLClosure;
use lua_types::error::{LuaError, LuaExit};
use lua_types::filehandle::LuaFileHandle;
use lua_types::gc::GcRef;
use lua_types::upval::UpVal;
use lua_types::value::LuaValue;
use lua_vm::state::{
    new_state, DynLibId, DynamicSymbol, LuaState, OsExecuteReason, OsExecuteResult,
};

mod interp;
mod repl;

fn file_loader_hook(filename: &[u8]) -> Result<Vec<u8>, LuaError> {
    #[cfg(unix)]
    let path: std::path::PathBuf = {
        use std::os::unix::ffi::OsStrExt;
        std::path::PathBuf::from(std::ffi::OsStr::from_bytes(filename))
    };
    #[cfg(not(unix))]
    let path: std::path::PathBuf = {
        let s = std::str::from_utf8(filename).map_err(|_| {
            LuaError::runtime(format_args!("filename is not valid UTF-8"))
        })?;
        std::path::PathBuf::from(s)
    };
    std::fs::read(&path).map_err(|err| {
        LuaError::runtime(format_args!(
            "cannot open '{}': {}",
            String::from_utf8_lossy(filename),
            err
        ))
    })
}

/// `std::fs::File`-backed implementation of [`LuaFileHandle`].
///
/// Wraps a `BufReader` for read paths and a `BufWriter` for write paths,
/// sharing the same underlying `std::fs::File` via cloning the handle.
/// The write wrapper is flushed on `Drop` (implicit close) so data is not
/// lost when `io.close()` drops the `Box<dyn LuaFileHandle>`.
enum FsFile {
    Read(BufReader<std::fs::File>, Option<(i32, String)>),
    Write(BufWriter<std::fs::File>, bool, FsBufMode),
    ReadWrite(std::fs::File, Option<u8>, Option<(i32, String)>),
}

#[derive(Clone, Copy)]
enum FsBufMode {
    No,
    Full,
    Line,
}

impl FsFile {
    fn open(filename: &[u8], mode: &[u8]) -> io::Result<Self> {
        #[cfg(unix)]
        let path: std::path::PathBuf = {
            use std::os::unix::ffi::OsStrExt;
            std::path::PathBuf::from(std::ffi::OsStr::from_bytes(filename))
        };
        #[cfg(not(unix))]
        let path: std::path::PathBuf = {
            let s = std::str::from_utf8(filename)
                .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "filename not valid UTF-8"))?;
            std::path::PathBuf::from(s)
        };

        let first = mode.first().copied().unwrap_or(b'r');
        let update = mode.get(1).copied() == Some(b'+');

        if first != b'r' {
            if let Some(parent) = path.parent() {
                if !parent.as_os_str().is_empty() {
                    let _ = std::fs::create_dir_all(parent);
                }
            }
        }

        match (first, update) {
            (b'r', false) => {
                let f = std::fs::File::open(&path)?;
                Ok(FsFile::Read(BufReader::new(f), None))
            }
            (b'w', false) => {
                let f = std::fs::File::create(&path)?;
                Ok(FsFile::Write(BufWriter::new(f), false, FsBufMode::Full))
            }
            (b'a', false) => {
                let mut f = std::fs::OpenOptions::new().append(true).create(true).open(&path)?;
                f.seek(SeekFrom::End(0))?;
                Ok(FsFile::Write(BufWriter::new(f), false, FsBufMode::Full))
            }
            _ => {
                let f = std::fs::OpenOptions::new()
                    .read(true)
                    .write(true)
                    .create(first == b'w' || first == b'a')
                    .truncate(first == b'w')
                    .append(first == b'a')
                    .open(&path)?;
                Ok(FsFile::ReadWrite(f, None, None))
            }
        }
    }
}

fn io_error_info(err: &io::Error) -> (i32, String) {
    (err.raw_os_error().unwrap_or(0), err.to_string())
}

impl LuaFileHandle for FsFile {
    fn read_byte(&mut self) -> i32 {
        match self {
            FsFile::Read(r, err) => {
                let mut buf = [0u8; 1];
                match r.read(&mut buf) {
                    Ok(1) => buf[0] as i32,
                    Ok(_) => -1,
                    Err(e) => {
                        *err = Some(io_error_info(&e));
                        -1
                    }
                }
            }
            FsFile::ReadWrite(f, pushback, err) => {
                if let Some(b) = pushback.take() {
                    return b as i32;
                }
                let mut buf = [0u8; 1];
                match f.read(&mut buf) {
                    Ok(1) => buf[0] as i32,
                    Ok(_) => -1,
                    Err(e) => {
                        *err = Some(io_error_info(&e));
                        -1
                    }
                }
            }
            FsFile::Write(_, errored, _) => {
                *errored = true;
                -1
            }
        }
    }

    fn unread_byte(&mut self, byte: i32) {
        match self {
            FsFile::Read(r, _) => {
                if byte >= 0 {
                    let _ = r.seek_relative(-1);
                }
            }
            FsFile::ReadWrite(_, pushback, _) => {
                if byte >= 0 {
                    *pushback = Some(byte as u8);
                }
            }
            FsFile::Write(_, _, _) => {}
        }
    }

    fn write_bytes(&mut self, data: &[u8]) -> io::Result<usize> {
        match self {
            FsFile::Write(w, _, mode) => {
                let n = w.write(data)?;
                match mode {
                    FsBufMode::No => w.flush()?,
                    FsBufMode::Line if data[..n].contains(&b'\n') => w.flush()?,
                    FsBufMode::Line | FsBufMode::Full => {}
                }
                Ok(n)
            }
            FsFile::ReadWrite(f, _, _) => f.write(data),
            FsFile::Read(_, _) => Err(io::Error::new(io::ErrorKind::PermissionDenied, "file not open for writing")),
        }
    }

    fn flush(&mut self) -> io::Result<()> {
        match self {
            FsFile::Write(w, _, _) => w.flush(),
            FsFile::ReadWrite(f, _, _) => f.flush(),
            FsFile::Read(_, _) => Ok(()),
        }
    }

    fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
        match self {
            FsFile::Read(r, _) => r.seek(pos),
            FsFile::Write(w, _, _) => w.seek(pos),
            FsFile::ReadWrite(f, _, _) => f.seek(pos),
        }
    }

    fn tell(&mut self) -> io::Result<u64> {
        self.seek(SeekFrom::Current(0))
    }

    fn clear_error(&mut self) {
        match self {
            FsFile::Read(_, err) => *err = None,
            FsFile::Write(_, errored, _) => *errored = false,
            FsFile::ReadWrite(_, _, err) => *err = None,
        }
    }

    fn has_error(&self) -> bool {
        match self {
            FsFile::Read(_, err) => err.is_some(),
            FsFile::Write(_, errored, _) => *errored,
            FsFile::ReadWrite(_, _, err) => err.is_some(),
        }
    }

    fn last_error_info(&self) -> Option<(i32, String)> {
        match self {
            FsFile::Read(_, err) => err.clone(),
            FsFile::ReadWrite(_, _, err) => err.clone(),
            FsFile::Write(_, true, _) => Some((0, "file write error".to_string())),
            FsFile::Write(_, false, _) => None,
        }
    }

    fn set_buf_mode(&mut self, mode: i32, _size: usize) -> io::Result<()> {
        if let FsFile::Write(w, _, current) = self {
            w.flush()?;
            *current = match mode {
                0 => FsBufMode::No,
                1 => FsBufMode::Full,
                2 => FsBufMode::Line,
                _ => FsBufMode::Full,
            };
        }
        Ok(())
    }
}

impl Drop for FsFile {
    fn drop(&mut self) {
        if let FsFile::Write(w, _, _) = self {
            let _ = w.flush();
        }
    }
}

fn file_remove_hook(filename: &[u8]) -> Result<(), LuaError> {
    #[cfg(unix)]
    let path: std::path::PathBuf = {
        use std::os::unix::ffi::OsStrExt;
        std::path::PathBuf::from(std::ffi::OsStr::from_bytes(filename))
    };
    #[cfg(not(unix))]
    let path: std::path::PathBuf = {
        let s = std::str::from_utf8(filename).map_err(|_| {
            LuaError::runtime(format_args!("filename is not valid UTF-8"))
        })?;
        std::path::PathBuf::from(s)
    };
    std::fs::remove_file(&path)
        .or_else(|_| std::fs::remove_dir(&path))
        .map_err(|err| {
            LuaError::runtime(format_args!(
                "cannot remove '{}': {}",
                String::from_utf8_lossy(filename),
                err
            ))
        })
}

fn file_rename_hook(from: &[u8], to: &[u8]) -> Result<(), LuaError> {
    fn to_path(bytes: &[u8]) -> Result<std::path::PathBuf, LuaError> {
        #[cfg(unix)]
        {
            use std::os::unix::ffi::OsStrExt;
            Ok(std::path::PathBuf::from(std::ffi::OsStr::from_bytes(bytes)))
        }
        #[cfg(not(unix))]
        {
            let s = std::str::from_utf8(bytes).map_err(|_| {
                LuaError::runtime(format_args!("filename is not valid UTF-8"))
            })?;
            Ok(std::path::PathBuf::from(s))
        }
    }
    let from_path = to_path(from)?;
    let to_path_buf = to_path(to)?;
    std::fs::rename(&from_path, &to_path_buf).map_err(|err| {
        LuaError::runtime(format_args!(
            "cannot rename '{}' to '{}': {}",
            String::from_utf8_lossy(from),
            String::from_utf8_lossy(to),
            err
        ))
    })
}

fn file_open_hook(filename: &[u8], mode: &[u8]) -> Result<Box<dyn LuaFileHandle>, LuaError> {
    FsFile::open(filename, mode).map(|f| Box::new(f) as Box<dyn LuaFileHandle>).map_err(|err| {
        LuaError::runtime(format_args!(
            "cannot open '{}': {}",
            String::from_utf8_lossy(filename),
            err
        ))
    })
}

fn stdout_hook(bytes: &[u8]) -> io::Result<()> {
    let stdout = std::io::stdout();
    let mut handle = stdout.lock();
    handle.write_all(bytes)?;
    handle.flush()
}

fn stderr_hook(bytes: &[u8]) -> io::Result<()> {
    let stderr = std::io::stderr();
    let mut handle = stderr.lock();
    handle.write_all(bytes)?;
    handle.flush()
}

fn stdin_hook(buf: &mut [u8]) -> io::Result<usize> {
    std::io::stdin().lock().read(buf)
}

fn env_hook(name: &[u8]) -> Option<Vec<u8>> {
    #[cfg(unix)]
    {
        use std::ffi::OsStr;
        use std::os::unix::ffi::{OsStrExt, OsStringExt};
        std::env::var_os(OsStr::from_bytes(name)).map(|v| v.into_vec())
    }

    #[cfg(not(unix))]
    {
        let name = std::str::from_utf8(name).ok()?;
        std::env::var(name).ok().map(|v| v.into_bytes())
    }
}

fn unix_time_hook() -> i64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs() as i64)
        .unwrap_or(0)
}

/// Monotonic baseline for `os.clock`, captured at process start by `main`.
static CLI_START: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();

/// Program CPU time for `os.clock`, reported as monotonic wall time elapsed since
/// process start. `std` exposes no `CLOCK_PROCESS_CPUTIME_ID` equivalent, so this
/// matches the emulation wasi-libc and Emscripten use for C's `clock()`: faithful
/// for elapsed-time benchmarking, but it counts idle wall time (e.g. at an
/// interactive prompt) that true CPU time would not.
fn cpu_clock_hook() -> f64 {
    CLI_START
        .get_or_init(std::time::Instant::now)
        .elapsed()
        .as_secs_f64()
}

fn entropy_hook() -> u64 {
    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_nanos() as u64)
        .unwrap_or(0);
    nanos ^ ((std::process::id() as u64) << 32)
}

fn temp_name_hook() -> Result<Vec<u8>, LuaError> {
    use std::sync::atomic::{AtomicU64, Ordering};

    static COUNTER: AtomicU64 = AtomicU64::new(0);

    let mut path: Vec<u8> = {
        let tmp = std::env::temp_dir();
        #[cfg(unix)]
        {
            use std::os::unix::ffi::OsStrExt;
            tmp.as_os_str().as_bytes().to_vec()
        }
        #[cfg(not(unix))]
        {
            tmp.to_string_lossy().as_bytes().to_vec()
        }
    };
    if path.last().copied() != Some(b'/') && path.last().copied() != Some(b'\\') {
        path.push(b'/');
    }

    let unique = format!(
        "lua_rs_{:x}_{:x}_{:x}",
        std::process::id(),
        entropy_hook(),
        COUNTER.fetch_add(1, Ordering::Relaxed)
    );
    path.extend_from_slice(unique.as_bytes());
    Ok(path)
}

fn os_execute_hook(cmd: &[u8]) -> Result<OsExecuteResult, LuaError> {
    let cmd_str = std::str::from_utf8(cmd)
        .map_err(|_| LuaError::runtime(format_args!("os.execute command not valid UTF-8")))?;
    let status = std::process::Command::new("/bin/sh")
        .arg("-c")
        .arg(cmd_str)
        .status()
        .map_err(|err| LuaError::runtime(format_args!("os.execute failed: {}", err)))?;

    if let Some(code) = status.code() {
        return Ok(OsExecuteResult {
            success: status.success(),
            reason: OsExecuteReason::Exit,
            code,
        });
    }

    #[cfg(unix)]
    {
        use std::os::unix::process::ExitStatusExt;
        if let Some(signal) = status.signal() {
            return Ok(OsExecuteResult {
                success: false,
                reason: OsExecuteReason::Signal,
                code: signal,
            });
        }
    }

    Ok(OsExecuteResult {
        success: false,
        reason: OsExecuteReason::Exit,
        code: -1,
    })
}

/// `LuaFileHandle` backed by a `std::process::Child` and one of its pipes.
///
/// Mirrors POSIX `popen(3)` semantics: mode `"r"` exposes the child's stdout
/// as a readable stream, mode `"w"` exposes the child's stdin as a writable
/// stream. The pipe is stored as `Option<_>` so the closing path can take()
/// it before calling `wait()`, ensuring the child sees EOF and exits — if
/// the BufWriter/BufReader were left in place across `wait()`, write-mode
/// children like `cat` or `wc` would block indefinitely.
enum PopenFile {
    Read(Option<BufReader<std::process::ChildStdout>>, std::process::Child),
    Write(Option<BufWriter<std::process::ChildStdin>>, std::process::Child),
}

impl PopenFile {
    fn spawn(cmd: &[u8], mode: &[u8]) -> io::Result<Self> {
        let cmd_str = std::str::from_utf8(cmd).map_err(|_| {
            io::Error::new(io::ErrorKind::InvalidInput, "popen command not valid UTF-8")
        })?;
        let read_mode = match mode {
            b"r" => true,
            b"w" => false,
            _ => {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidInput,
                    "popen mode must be \"r\" or \"w\"",
                ));
            }
        };
        let mut command = std::process::Command::new("/bin/sh");
        command.arg("-c").arg(cmd_str);
        if read_mode {
            command.stdout(std::process::Stdio::piped());
        } else {
            command.stdin(std::process::Stdio::piped());
        }
        let mut child = command.spawn()?;
        if read_mode {
            let out = child.stdout.take().ok_or_else(|| {
                io::Error::new(io::ErrorKind::Other, "popen: child stdout was None")
            })?;
            Ok(PopenFile::Read(Some(BufReader::new(out)), child))
        } else {
            let inp = child.stdin.take().ok_or_else(|| {
                io::Error::new(io::ErrorKind::Other, "popen: child stdin was None")
            })?;
            Ok(PopenFile::Write(Some(BufWriter::new(inp)), child))
        }
    }
}

impl LuaFileHandle for PopenFile {
    fn read_byte(&mut self) -> i32 {
        match self {
            PopenFile::Read(Some(r), _) => {
                let mut buf = [0u8; 1];
                match r.read(&mut buf) {
                    Ok(1) => buf[0] as i32,
                    _ => -1,
                }
            }
            _ => -1,
        }
    }

    fn unread_byte(&mut self, _byte: i32) {}

    fn write_bytes(&mut self, data: &[u8]) -> io::Result<usize> {
        match self {
            PopenFile::Write(Some(w), _) => w.write(data),
            _ => Err(io::Error::new(
                io::ErrorKind::PermissionDenied,
                "popen pipe not open for writing",
            )),
        }
    }

    fn flush(&mut self) -> io::Result<()> {
        match self {
            PopenFile::Write(Some(w), _) => w.flush(),
            _ => Ok(()),
        }
    }

    fn seek(&mut self, _pos: SeekFrom) -> io::Result<u64> {
        Err(io::Error::new(io::ErrorKind::Unsupported, "popen pipe is not seekable"))
    }

    fn tell(&mut self) -> io::Result<u64> {
        Err(io::Error::new(io::ErrorKind::Unsupported, "popen pipe is not seekable"))
    }

    fn clear_error(&mut self) {}

    fn has_error(&self) -> bool { false }
}

impl Drop for PopenFile {
    fn drop(&mut self) {
        match self {
            PopenFile::Read(reader, child) => {
                drop(reader.take());
                let _ = child.wait();
            }
            PopenFile::Write(writer, child) => {
                if let Some(mut w) = writer.take() {
                    let _ = w.flush();
                }
                let _ = child.wait();
            }
        }
    }
}

fn popen_hook(cmd: &[u8], mode: &[u8]) -> Result<Box<dyn LuaFileHandle>, LuaError> {
    PopenFile::spawn(cmd, mode)
        .map(|p| Box::new(p) as Box<dyn LuaFileHandle>)
        .map_err(|err| {
            LuaError::runtime(format_args!(
                "cannot popen '{}': {}",
                String::from_utf8_lossy(cmd),
                err
            ))
        })
}

// ─── Dynamic library backend (Phase D-3.5) ────────────────────────────────────
//
// `lua-stdlib` cannot use `libloading` because it forbids `unsafe`. The CLI
// owns a per-process registry of loaded libraries and exposes it to
// `package.loadlib` via three function-pointer hooks on `GlobalState`. The
// registry is a `thread_local!` because `lua-rs` is single-threaded by
// construction; `libloading::Library` is not `Sync`. Libraries are leaked
// for the lifetime of the process so any function pointer resolved from
// them stays valid — that's `libloading`'s safety model.

thread_local! {
    static DYNLIB_REGISTRY: std::cell::RefCell<Vec<libloading::Library>> =
        const { std::cell::RefCell::new(Vec::new()) };
}

fn path_from_bytes(path: &[u8]) -> Result<std::path::PathBuf, LuaError> {
    #[cfg(unix)]
    {
        use std::os::unix::ffi::OsStrExt;
        Ok(std::path::PathBuf::from(std::ffi::OsStr::from_bytes(path)))
    }
    #[cfg(not(unix))]
    {
        let s = std::str::from_utf8(path).map_err(|_| {
            LuaError::runtime(format_args!("library path is not valid UTF-8"))
        })?;
        Ok(std::path::PathBuf::from(s))
    }
}

/// `dynlib_load_hook` backend. Loads the library via `libloading` and stashes
/// it in the per-thread registry; the returned [`DynLibId`] is the
/// registry-vector index, which keeps the library alive until process exit.
///
/// PORT NOTE: a missing path is reported as `LuaError::File`, which
/// `lua-stdlib`'s `package.loadlib` maps to the `"absent"` failure tag (the
/// `lua-rs` build behaves like C-Lua's no-dlfcn fallback for plain file-not-
/// found, and like POSIX/Windows dlopen for every other open failure).
fn dynlib_load(
    _state: &mut LuaState,
    path: &[u8],
    _see_global: bool,
) -> Result<DynLibId, LuaError> {
    let p = path_from_bytes(path)?;
    if !p.exists() {
        return Err(LuaError::File);
    }
    // SAFETY: `libloading::Library::new` executes the dynamic linker, which
    // may run arbitrary initializer code in the loaded library. We trust the
    // operator-supplied path; this is the same trust model as stock Lua's
    // `package.loadlib`. We never call any symbol from the library through
    // an unchecked ABI: only `DynamicSymbol::RustNative` is invoked, and
    // those must match our Rust function-pointer ABI exactly. Libraries are
    // stored in `DYNLIB_REGISTRY` and never unloaded mid-state, so symbol
    // pointers resolved later stay valid for as long as the state can call
    // them.
    let lib = unsafe { libloading::Library::new(&p) }.map_err(|err| {
        LuaError::runtime(format_args!(
            "cannot load '{}': {}",
            String::from_utf8_lossy(path),
            err
        ))
    })?;
    let id = DYNLIB_REGISTRY.with(|reg| {
        let mut v = reg.borrow_mut();
        let idx = v.len() as u64;
        v.push(lib);
        idx
    });
    Ok(DynLibId(id))
}

/// Conservative heuristic: stock Lua C ABI module entry points are named
/// `luaopen_<name>` and take a `lua_State *` followed by a single return.
/// Without a way to inspect the symbol's signature at run time, we treat any
/// symbol whose name starts with `luaopen_` as a C-ABI symbol and refuse it
/// with the "ABI not supported" message; everything else is treated as a
/// Rust-native entry compatible with `fn(&mut LuaState) -> Result<usize,
/// LuaError>`.
fn looks_like_c_abi(sym: &[u8]) -> bool {
    sym.starts_with(b"luaopen_")
}

/// `dynlib_symbol_hook` backend. Resolves `symbol` in the library identified
/// by `handle`; returns `RustNative` for non-`luaopen_*` symbols and
/// `LuaCAbi` (a null pointer placeholder) for `luaopen_*` symbols so
/// `package.loadlib` can refuse them with a clear `"init"` error.
fn dynlib_symbol(
    _state: &mut LuaState,
    handle: DynLibId,
    symbol: &[u8],
) -> Result<DynamicSymbol, LuaError> {
    let idx = handle.0 as usize;
    DYNLIB_REGISTRY.with(|reg| {
        let v = reg.borrow();
        let lib = v.get(idx).ok_or_else(|| {
            LuaError::runtime(format_args!("invalid dynlib handle {}", idx))
        })?;

        if looks_like_c_abi(symbol) {
            // SAFETY: We only resolve the symbol address; we never call
            // through this pointer. The `DynamicSymbol::LuaCAbi` variant is
            // a placeholder so `package.loadlib` can report an "init"
            // failure with the unsupported-ABI message. The library outlives
            // the pointer because `DYNLIB_REGISTRY` retains it for the
            // process lifetime.
            let resolved: Result<libloading::Symbol<unsafe extern "C" fn()>, _> =
                unsafe { lib.get(symbol) };
            return match resolved {
                Ok(_) => Ok(DynamicSymbol::LuaCAbi(std::ptr::null())),
                Err(err) => Err(LuaError::runtime(format_args!(
                    "cannot find symbol '{}': {}",
                    String::from_utf8_lossy(symbol),
                    err
                ))),
            };
        }

        type RustNativeFn = fn(&mut LuaState) -> Result<usize, LuaError>;
        // SAFETY: We assume the loaded library was built against this build's
        // Rust-native module ABI: it exports `symbol` as a function pointer
        // with signature `fn(&mut LuaState) -> Result<usize, LuaError>`.
        // Verified by convention (operator-supplied path + opt-in `_rs`
        // suffix); calling a symbol with the wrong signature is undefined
        // behaviour and the operator's responsibility. The library outlives
        // the function pointer (kept alive in `DYNLIB_REGISTRY` until
        // process exit).
        let resolved: Result<libloading::Symbol<RustNativeFn>, _> =
            unsafe { lib.get(symbol) };
        match resolved {
            Ok(sym) => Ok(DynamicSymbol::RustNative(*sym)),
            Err(err) => Err(LuaError::runtime(format_args!(
                "cannot find symbol '{}': {}",
                String::from_utf8_lossy(symbol),
                err
            ))),
        }
    })
}

/// `dynlib_unload_hook` backend. No-op: libraries are kept alive for the
/// lifetime of the process to honour `libloading`'s safety model (symbol
/// pointers must not outlive the library). Closing libraries at state
/// shutdown is platform-dependent and best deferred to OS-level cleanup.
fn dynlib_unload(_handle: DynLibId) {}

fn parser_hook(
    state: &mut LuaState,
    source: &[u8],
    name: &[u8],
    firstchar: i32,
) -> Result<GcRef<LuaLClosure>, LuaError> {
    let proto = lua_parse::parse(
        state,
        lua_parse::DynData::default(),
        source,
        name,
        firstchar,
    )?;
    let nupvals = proto.upvalues.len();
    let mut upvals = Vec::with_capacity(nupvals);
    for _ in 0..nupvals {
        upvals.push(std::cell::Cell::new(GcRef::new(UpVal::closed(LuaValue::Nil))));
    }
    Ok(GcRef::new(LuaLClosure {
        proto: GcRef::new(*proto),
        upvals,
    }))
}

/// Install Rust-native modules that ship with `lua-cli` into
/// `package.preload`. After `open_libs` has populated the `package` library,
/// each entry written to `package.preload[name]` becomes a loader that
/// `require(name)` will invoke through the preload searcher.
///
/// Phase G-1 ships a single preloaded module — `lfs`, the Rust-native
/// LuaFileSystem port from the `lua-rs-lfs` crate.
fn register_preloaded_modules(state: &mut LuaState) -> Result<(), LuaError> {
    lua_vm::api::get_global(state, b"package")?;
    lua_vm::api::get_field(state, -1, b"preload")?;
    lua_vm::api::push_cclosure(state, lua_rs_lfs::luaopen_lfs, 0)?;
    lua_vm::api::set_field(state, -2, b"lfs")?;
    state.pop_n(2);
    Ok(())
}

#[cfg(unix)]
fn os_str_bytes(s: &std::ffi::OsString) -> Vec<u8> {
    use std::os::unix::ffi::OsStrExt;
    s.as_bytes().to_vec()
}
#[cfg(not(unix))]
fn os_str_bytes(s: &std::ffi::OsString) -> Vec<u8> {
    s.to_string_lossy().into_owned().into_bytes()
}

/// Prepend `dir/?.lua;dir/?/init.lua` to `LUA_PATH` so that `require` can
/// find modules that live next to the running script.
///
/// When `LUA_PATH` is already set the script-dir entries are prepended so the
/// existing value is preserved.  When `LUA_PATH` is not set we write
/// `dir/?.lua;dir/?/init.lua;;` — the trailing `;;` causes `setpath` to
/// splice in the compiled-in default at that position, matching C-Lua's
/// behaviour when `LUA_PATH` is absent.
pub(crate) fn prepend_lua_path(dir: &std::path::Path) {
    let prefix = format!(
        "{dir}/?.lua;{dir}/?/init.lua",
        dir = dir.display(),
    );
    let new_val = match std::env::var("LUA_PATH") {
        Ok(existing) if !existing.is_empty() => format!("{};{}", prefix, existing),
        _ => format!("{};;", prefix),
    };
    std::env::set_var("LUA_PATH", new_val);
}

fn main() -> ExitCode {
    CLI_START.get_or_init(std::time::Instant::now);

    let previous_hook = std::panic::take_hook();
    std::panic::set_hook(Box::new(move |info| {
        if info.payload().downcast_ref::<LuaExit>().is_none() {
            previous_hook(info);
        }
    }));

    let args_os: Vec<std::ffi::OsString> = std::env::args_os().collect();
    let argv: Vec<Vec<u8>> = args_os.iter().map(os_str_bytes).collect();

    let result = catch_unwind(AssertUnwindSafe(|| -> Result<i32, String> {
        let mut state = new_state().ok_or("new_state returned None")?;
        state.global_mut().parser_hook = Some(parser_hook);
        state.global_mut().file_loader_hook = Some(file_loader_hook);
        state.global_mut().file_open_hook = Some(file_open_hook);
        state.global_mut().stdout_hook = Some(stdout_hook);
        state.global_mut().stderr_hook = Some(stderr_hook);
        state.global_mut().stdin_hook = Some(stdin_hook);
        state.global_mut().env_hook = Some(env_hook);
        state.global_mut().unix_time_hook = Some(unix_time_hook);
        state.global_mut().cpu_clock_hook = Some(cpu_clock_hook);
        state.global_mut().entropy_hook = Some(entropy_hook);
        state.global_mut().temp_name_hook = Some(temp_name_hook);
        state.global_mut().popen_hook = Some(popen_hook);
        state.global_mut().file_remove_hook = Some(file_remove_hook);
        state.global_mut().file_rename_hook = Some(file_rename_hook);
        state.global_mut().os_execute_hook = Some(os_execute_hook);
        state.global_mut().dynlib_load_hook = Some(dynlib_load);
        state.global_mut().dynlib_symbol_hook = Some(dynlib_symbol);
        state.global_mut().dynlib_unload_hook = Some(dynlib_unload);

        let code = interp::run(&mut state, &argv, register_preloaded_modules);

        if std::env::var("LUA_RS_GC_DIAG").is_ok() {
            let tracked = state.global().heap.bytes_used();
            let allgc = state.global().heap.allgc_count();
            let threshold = state.global().heap.threshold_bytes();
            let collections = state.global().heap.collections();
            let paused = state.global().heap.is_paused();
            let gc_state = state.global().heap.gc_state();
            eprintln!(
                "[gc-diag] tracked={:.1}MB  allgc={}  threshold={:.1}MB  collections={}  paused={}  state={:?}",
                tracked as f64 / (1024.0 * 1024.0),
                allgc,
                threshold as f64 / (1024.0 * 1024.0),
                collections,
                paused,
                gc_state,
            );
        }

        Ok(code)
    }));

    match result {
        Ok(Ok(code)) => ExitCode::from(code as u8),
        Ok(Err(msg)) => {
            eprintln!("lua: {}", msg);
            ExitCode::from(1)
        }
        Err(panic) => {
            if let Some(exit) = panic.downcast_ref::<LuaExit>() {
                return ExitCode::from(exit.0 as u8);
            }
            let msg = if let Some(s) = panic.downcast_ref::<String>() {
                s.clone()
            } else if let Some(s) = panic.downcast_ref::<&str>() {
                s.to_string()
            } else {
                "(non-string panic payload)".to_string()
            };
            eprintln!("[panic] {}", msg);
            ExitCode::from(101)
        }
    }
}

// ──────────────────────────────────────────────────────────────────────────
// PORT STATUS
//   source:        (minimal entrypoint; not a port of lua.c — that's Phase F)
//   target_crate:  lua-cli
//   confidence:    high
//   todos:         0
//   port_notes:    0
//   unsafe_blocks: 3  (libloading-backed dynlib backend, Phase D-3.5;
//                      budget counts 4 due to one `unsafe extern "C" fn()`
//                      type parameter on `Symbol<...>`).
//   notes:         drives new_state → open_libs → load_string → pcall_k.
//                  Designed to surface the first todo!() panic on a hello-
//                  world program, not to be a complete interpreter. Hosts the
//                  libloading-backed implementation of the three
//                  dynlib_*_hook hooks on GlobalState (Phase D-3.5); ceiling
//                  in harness/unsafe-budgets.toml = 3. Also installs
//                  popen_hook (Phase F): spawns /bin/sh -c <cmd> via
//                  std::process::Command, wraps the resulting pipe in
//                  PopenFile (a LuaFileHandle) so io.popen and the LStream
//                  read/write/close path Just Work for clients like
//                  LuaRocks. No new unsafe — std::process is permitted in
//                  lua-cli.
// ──────────────────────────────────────────────────────────────────────────