lua-cli 0.0.10

Lua 5.4 runtime port in Rust with an AI-assisted C-to-Rust porting harness.
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
//! Faithful Rust port of `reference/lua-5.4.7/src/lua.c` — the standalone
//! interpreter's option handling and chunk-running logic.
//!
//! The read-eval-print loop (`doREPL` and friends) lives in [`crate::repl`].
//! Platform hooks (file/io/dynlib/popen) and the `main` entry point live in
//! `main.rs`; this module owns everything between argument collection and the
//! decision to enter the REPL.
//!
//! Structure mirrors `lua.c` section-for-section: `collectargs`, `runargs`,
//! `createargtable`, `handle_script`, `dolibrary`, `handle_luainit`, the
//! `docall`/`msghandler`/`report` error path, and the `pmain` orchestrator
//! ([`run`]).

use std::io::{IsTerminal, Read, Write};

use lua_stdlib::auxlib::{self, load_buffer};
use lua_stdlib::init::open_libs;
use lua_types::error::LuaError;
use lua_types::value::LuaValue;
use lua_types::LuaType;
use lua_vm::api;
use lua_vm::state::LuaState;

/// `LUA_MULTRET`.
const MULTRET: i32 = -1;

/// `luaconf.h`: `LUA_PROGNAME`.
const PROGNAME_DEFAULT: &[u8] = b"lua";

/// `lua.c`: `LUA_COPYRIGHT`, printed by `-v` and on entry to an interactive
/// session. The language level implemented is Lua 5.4.7, so the banner names
/// that release.
//
// PORT NOTE: lua-rs is not C-Lua, but the REPL/`-v` banner mirrors the
// upstream copyright line so tooling that greps `lua -v` behaves unchanged.
const LUA_COPYRIGHT: &[u8] = b"Lua 5.4.7  Copyright (C) 1994-2024 Lua.org, PUC-Rio";

/// `LUA_REGISTRYINDEX` pseudo-index. Used to plant `LUA_NOENV` for `-E`.
const LUA_REGISTRYINDEX: i32 = -1_001_000;

/// `lua.c`: bits returned by `collectargs`.
const HAS_ERROR: i32 = 1;
const HAS_I: i32 = 2;
const HAS_V: i32 = 4;
const HAS_E: i32 = 8;
const HAS_BIG_E: i32 = 16;

/// Carries the program name across the option/chunk helpers, mirroring the
/// file-scope `progname` in `lua.c`. The REPL clears it (`None`) so errors at
/// the prompt are printed without a `lua:` prefix.
pub(crate) struct Cli {
    pub progname: Option<Vec<u8>>,
}

/// `lua.c`: `l_message` — print a message to stderr, prefixed with the program
/// name when one is set.
pub(crate) fn l_message(progname: Option<&[u8]>, msg: &[u8]) {
    let mut err = std::io::stderr();
    if let Some(p) = progname {
        let _ = err.write_all(p);
        let _ = err.write_all(b": ");
    }
    let _ = err.write_all(msg);
    let _ = err.write_all(b"\n");
    let _ = err.flush();
}

/// Extract the printable bytes from an error object. After `docall`, the
/// message handler has already replaced the error with a traceback string, so
/// the common case is `LuaError::Runtime(LuaValue::Str)`.
pub(crate) fn error_bytes(e: &LuaError) -> Vec<u8> {
    match e {
        LuaError::Runtime(v) | LuaError::Syntax(v) => match v {
            LuaValue::Str(s) => s.as_bytes().to_vec(),
            _ => b"(error object is not a string)".to_vec(),
        },
        _ => b"(error message not a string)".to_vec(),
    }
}

/// `lua.c`: `lua_remove` — drop the stack slot at `idx`, shifting the elements
/// above it down. Expressed via the public `rotate` + `set_top` primitives.
fn lua_remove(state: &mut LuaState, idx: i32) -> Result<(), LuaError> {
    api::rotate(state, idx, -1);
    api::set_top(state, -2)
}

/// `lua.c`: `msghandler` — the error-message handler installed by `docall`.
/// Turns the error object into a string (directly, via `__tostring`, or a
/// typed placeholder) and appends a standard traceback.
fn msghandler(state: &mut LuaState) -> Result<usize, LuaError> {
    let direct = match api::to_lua_string(state, 1) {
        Ok(Some(s)) => Some(s.as_bytes().to_vec()),
        _ => None,
    };
    let msg = match direct {
        Some(m) => m,
        None => {
            if auxlib::call_meta(state, 1, b"__tostring")?
                && api::lua_type_at(state, -1) == LuaType::String
            {
                return Ok(1);
            }
            let tn = api::type_name(state, api::lua_type_at(state, 1));
            format!(
                "(error object is a {} value)",
                String::from_utf8_lossy(tn)
            )
            .into_bytes()
        }
    };
    auxlib::traceback(state, None, Some(&msg), 1)?;
    Ok(1)
}

/// `lua.c`: `print_version` — write the copyright banner to stdout.
fn print_version() {
    let mut out = std::io::stdout();
    let _ = out.write_all(LUA_COPYRIGHT);
    let _ = out.write_all(b"\n");
    let _ = out.flush();
}

/// `lua.c`: `lua_stdin_is_tty` — whether we are attached to an interactive
/// terminal.
fn stdin_is_tty() -> bool {
    std::io::stdin().is_terminal()
}

/// `lua_readline`'s loader counterpart from `lauxlib.c`: skip a UTF-8 BOM and a
/// leading `#...` line so executable scripts with a shebang load. A newline is
/// preserved in place of the stripped line to keep reported line numbers
/// aligned with the source file.
//
// PORT NOTE: C's luaL_loadfilex skips the shebang char-by-char in the reader;
// we strip it from the buffer before `load_buffer`, keeping the terminating
// newline so line counts match.
fn strip_shebang(mut data: Vec<u8>) -> Vec<u8> {
    if data.starts_with(b"\xEF\xBB\xBF") {
        data.drain(0..3);
    }
    if data.first() == Some(&b'#') {
        match data.iter().position(|&b| b == b'\n') {
            Some(pos) => {
                data.drain(0..pos);
            }
            None => data.clear(),
        }
    }
    data
}

/// Render an I/O error the way C's `strerror` does — Rust's `Display` appends
/// a ` (os error N)` suffix that C-Lua never prints, so strip it.
fn io_error_message(e: &std::io::Error) -> String {
    let s = e.to_string();
    match s.rfind(" (os error ") {
        Some(idx) => s[..idx].to_string(),
        None => s,
    }
}

#[cfg(unix)]
fn path_from_bytes(b: &[u8]) -> std::path::PathBuf {
    use std::os::unix::ffi::OsStrExt;
    std::path::PathBuf::from(std::ffi::OsStr::from_bytes(b))
}
#[cfg(not(unix))]
fn path_from_bytes(b: &[u8]) -> std::path::PathBuf {
    std::path::PathBuf::from(String::from_utf8_lossy(b).into_owned())
}

#[cfg(unix)]
fn env_bytes(key: &str) -> Option<Vec<u8>> {
    use std::os::unix::ffi::OsStrExt;
    std::env::var_os(key).map(|v| v.as_bytes().to_vec())
}
#[cfg(not(unix))]
fn env_bytes(key: &str) -> Option<Vec<u8>> {
    std::env::var_os(key).map(|v| v.to_string_lossy().into_owned().into_bytes())
}

/// `lua.c`: `createargtable` — build the global `arg` table. `argv[script]`
/// lands at index 0; arguments after the script take positive indices; options
/// before it take negative indices.
fn createargtable(state: &mut LuaState, argv: &[Vec<u8>], script: i32) -> Result<(), LuaError> {
    let argc = argv.len() as i32;
    let narg = argc - (script + 1);
    api::create_table(state, narg.max(0), script + 1)?;
    for i in 0..argc {
        api::push_lstring(state, &argv[i as usize])?;
        api::raw_set_i(state, -2, (i - script) as i64)?;
    }
    api::set_global(state, b"arg")
}

/// `lua.c`: `pushargs` — push `arg[1..#arg]` for the script call and return the
/// count.
fn pushargs(state: &mut LuaState) -> Result<i32, LuaError> {
    if api::get_global(state, b"arg")? != LuaType::Table {
        return Err(LuaError::runtime(format_args!("'arg' is not a table")));
    }
    let n = auxlib::lua_len(state, -1)? as i32;
    if !api::check_stack(state, n + 3) {
        return Err(LuaError::runtime(format_args!(
            "too many arguments to script"
        )));
    }
    for i in 1..=n {
        api::raw_get_i(state, -i, i as i64);
    }
    lua_remove(state, -(n + 1))?;
    Ok(n)
}

/// `lua.c`: `collectargs` — scan options, returning `(mask, first)`. `first` is
/// the index of the script name, `0` for no script, or the index of the bad
/// option when `mask == HAS_ERROR`.
fn collectargs(argv: &[Vec<u8>]) -> (i32, i32) {
    let mut args = 0;
    let mut first;
    let mut i = 1usize;
    while i < argv.len() {
        first = i as i32;
        let a = &argv[i];
        if a.is_empty() || a[0] != b'-' {
            return (args, first);
        }
        match a.get(1).copied() {
            None => return (args, first),
            Some(b'-') => {
                if a.len() > 2 {
                    return (HAS_ERROR, first);
                }
                return (args, (i + 1) as i32);
            }
            Some(b'E') => {
                if a.len() > 2 {
                    return (HAS_ERROR, first);
                }
                args |= HAS_BIG_E;
            }
            Some(b'W') => {
                if a.len() > 2 {
                    return (HAS_ERROR, first);
                }
            }
            Some(b'i') => {
                if a.len() > 2 {
                    return (HAS_ERROR, first);
                }
                args |= HAS_I | HAS_V;
            }
            Some(b'v') => {
                if a.len() > 2 {
                    return (HAS_ERROR, first);
                }
                args |= HAS_V;
            }
            Some(b'e') => {
                args |= HAS_E;
                if a.len() == 2 {
                    i += 1;
                    if i >= argv.len() || argv[i].first() == Some(&b'-') {
                        return (HAS_ERROR, first);
                    }
                }
            }
            Some(b'l') => {
                if a.len() == 2 {
                    i += 1;
                    if i >= argv.len() || argv[i].first() == Some(&b'-') {
                        return (HAS_ERROR, first);
                    }
                }
            }
            _ => return (HAS_ERROR, first),
        }
        i += 1;
    }
    (args, 0)
}

impl Cli {
    pub(crate) fn report(&self, r: Result<(), LuaError>) -> bool {
        match r {
            Ok(()) => true,
            Err(e) => {
                l_message(self.progname.as_deref(), &error_bytes(&e));
                false
            }
        }
    }

    /// Report the error string a failed `load` left on the stack, then pop it.
    pub(crate) fn report_stack_error(&self, state: &mut LuaState) {
        let bytes = match api::to_lua_string(state, -1) {
            Ok(Some(s)) => s.as_bytes().to_vec(),
            _ => b"(error message not a string)".to_vec(),
        };
        state.pop_n(1);
        l_message(self.progname.as_deref(), &bytes);
    }

    /// `lua.c`: `docall` — call the function on the stack under a freshly
    /// installed `msghandler`, so any error comes back as a traceback string.
    /// C-Lua's SIGINT-driven interrupt of a running chunk (`laction`/`lstop`)
    /// is not yet ported; see the `repl.rs` PORT STATUS for why.
    pub(crate) fn docall(&self, state: &mut LuaState, nargs: i32, nres: i32) -> Result<(), LuaError> {
        let base = api::get_top(state) - nargs;
        api::push_cclosure(state, msghandler, 0)?;
        state.insert(base)?;
        let r = api::pcall_k(state, nargs, nres, base, 0, None);
        let _ = lua_remove(state, base);
        r.map(|_| ())
    }

    /// `lua.c`: `dostring` — load a string and run it, reporting any failure.
    fn dostring(&self, state: &mut LuaState, s: &[u8], name: &[u8]) -> bool {
        match load_buffer(state, s, name) {
            Ok(0) => self.report(self.docall(state, 0, 0)),
            Ok(_) => {
                self.report_stack_error(state);
                false
            }
            Err(e) => self.report(Err(e)),
        }
    }

    /// `lua.c`: `dofile` — load a file (or stdin when `name` is `None`) and run
    /// it.
    fn dofile(&self, state: &mut LuaState, name: Option<&[u8]>) -> bool {
        match self.load_file(state, name) {
            Ok(0) => self.report(self.docall(state, 0, 0)),
            Ok(_) => {
                self.report_stack_error(state);
                false
            }
            Err(e) => self.report(Err(e)),
        }
    }

    /// `lauxlib.c`: `luaL_loadfile` — read a file (or stdin) and compile it.
    /// Returns the loader status (`0` = ok, chunk on stack; non-zero = error
    /// message on stack).
    fn load_file(&self, state: &mut LuaState, name: Option<&[u8]>) -> Result<i32, LuaError> {
        let (data, chunkname) = match name {
            Some(path) => {
                let raw = std::fs::read(path_from_bytes(path)).map_err(|e| {
                    LuaError::runtime(format_args!(
                        "cannot open {}: {}",
                        String::from_utf8_lossy(path),
                        io_error_message(&e)
                    ))
                })?;
                let mut cn = vec![b'@'];
                cn.extend_from_slice(path);
                (strip_shebang(raw), cn)
            }
            None => {
                let mut raw = Vec::new();
                std::io::stdin()
                    .lock()
                    .read_to_end(&mut raw)
                    .map_err(|e| LuaError::runtime(format_args!("stdin read error: {}", e)))?;
                (strip_shebang(raw), b"=stdin".to_vec())
            }
        };
        load_buffer(state, &data, &chunkname)
    }

    /// `lua.c`: `dolibrary` — run `globname = require(modname)` for `-l`,
    /// handling the `g=mod` and version-suffix forms.
    fn dolibrary(&self, state: &mut LuaState, globname: &[u8]) -> bool {
        let eq = globname.iter().position(|&b| b == b'=');
        let (glob_full, modname): (&[u8], &[u8]) = match eq {
            Some(p) => (&globname[..p], &globname[p + 1..]),
            None => (globname, globname),
        };
        let effective_glob: &[u8] = if eq.is_none() {
            match glob_full.iter().position(|&b| b == b'-') {
                Some(p) => &glob_full[..p],
                None => glob_full,
            }
        } else {
            glob_full
        };

        let load = (|| {
            if api::get_global(state, b"require")? != LuaType::Function {
                return Err(LuaError::runtime(format_args!("'require' is not a function")));
            }
            api::push_lstring(state, modname)?;
            Ok(())
        })();
        if let Err(e) = load {
            return self.report(Err(e));
        }
        match self.docall(state, 1, 1) {
            Ok(()) => match api::set_global(state, effective_glob) {
                Ok(()) => true,
                Err(e) => self.report(Err(e)),
            },
            Err(e) => self.report(Err(e)),
        }
    }

    /// `lua.c`: `handle_luainit` — run `$LUA_INIT_5_4` or `$LUA_INIT` (a file
    /// when it starts with `@`, otherwise a chunk).
    fn handle_luainit(&self, state: &mut LuaState) -> bool {
        let (init, name): (Vec<u8>, &[u8]) = match env_bytes("LUA_INIT_5_4") {
            Some(v) => (v, b"=LUA_INIT_5_4" as &[u8]),
            None => match env_bytes("LUA_INIT") {
                Some(v) => (v, b"=LUA_INIT" as &[u8]),
                None => return true,
            },
        };
        if init.first() == Some(&b'@') {
            self.dofile(state, Some(&init[1..]))
        } else {
            self.dostring(state, &init, name)
        }
    }

    /// `lua.c`: `handle_script` — load and run the main script, passing the
    /// positive entries of `arg`. `argv` is sliced so index 0 is the script.
    fn handle_script(&self, state: &mut LuaState, argv: &[Vec<u8>], script: i32) -> bool {
        let fname = &argv[script as usize];
        let prev = argv.get((script - 1) as usize).map(|v| v.as_slice());
        let use_stdin = fname.as_slice() == b"-" && prev != Some(b"--");
        let loaded = if use_stdin {
            self.load_file(state, None)
        } else {
            self.load_file(state, Some(fname))
        };
        match loaded {
            Ok(0) => {
                let n = match pushargs(state) {
                    Ok(n) => n,
                    Err(e) => return self.report(Err(e)),
                };
                self.report(self.docall(state, n, MULTRET))
            }
            Ok(_) => {
                self.report_stack_error(state);
                false
            }
            Err(e) => self.report(Err(e)),
        }
    }

    /// `lua.c`: `runargs` — execute the `-e`, `-l`, and `-W` options in order,
    /// up to `optlim`. Returns `false` if any chunk failed.
    fn runargs(&self, state: &mut LuaState, argv: &[Vec<u8>], n: i32) -> bool {
        let mut i = 1usize;
        while (i as i32) < n {
            let a = &argv[i];
            let option = a.get(1).copied();
            match option {
                Some(opt @ b'e') | Some(opt @ b'l') => {
                    let extra: Vec<u8> = if a.len() > 2 {
                        a[2..].to_vec()
                    } else {
                        i += 1;
                        argv[i].clone()
                    };
                    let ok = if opt == b'e' {
                        self.dostring(state, &extra, b"=(command line)")
                    } else {
                        self.dolibrary(state, &extra)
                    };
                    if !ok {
                        return false;
                    }
                }
                Some(b'W') => api::warning(state, b"@on", false),
                _ => {}
            }
            i += 1;
        }
        true
    }

    /// `lua.c`: `print_usage` — emit the usage block, tailored to the offending
    /// option.
    fn print_usage(&self, badoption: &[u8]) {
        let mut err = std::io::stderr();
        let prog = self.progname.as_deref().unwrap_or(PROGNAME_DEFAULT);
        let _ = err.write_all(prog);
        let _ = err.write_all(b": ");
        if badoption.get(1) == Some(&b'e') || badoption.get(1) == Some(&b'l') {
            let _ = writeln!(err, "'{}' needs argument", String::from_utf8_lossy(badoption));
        } else {
            let _ = writeln!(
                err,
                "unrecognized option '{}'",
                String::from_utf8_lossy(badoption)
            );
        }
        let _ = err.write_all(b"usage: ");
        let _ = err.write_all(prog);
        let _ = err.write_all(
            b" [options] [script [args]]\n\
              Available options are:\n\
              \x20 -e stat   execute string 'stat'\n\
              \x20 -i        enter interactive mode after executing 'script'\n\
              \x20 -l mod    require library 'mod' into global 'mod'\n\
              \x20 -l g=mod  require library 'mod' into global 'g'\n\
              \x20 -v        show version information\n\
              \x20 -E        ignore environment variables\n\
              \x20 -W        turn warnings on\n\
              \x20 --        stop handling options\n\
              \x20 -         stop handling options and execute stdin\n",
        );
        let _ = err.flush();
    }
}

/// `lua.c`: `pmain` — the body of the interpreter. Assumes `state` already has
/// its platform hooks installed; opens the standard libraries, installs
/// `preload`-registered native modules, builds `arg`, runs `LUA_INIT`, then the
/// `-e`/`-l` options, then the script, and finally enters the REPL when
/// appropriate. Returns the process exit code.
pub(crate) fn run(
    state: &mut LuaState,
    argv: &[Vec<u8>],
    preload: fn(&mut LuaState) -> Result<(), LuaError>,
) -> i32 {
    let (args, script) = collectargs(argv);

    let mut cli = Cli {
        progname: argv
            .first()
            .filter(|p| !p.is_empty())
            .map(|p| p.to_vec()),
    };

    if args == HAS_ERROR {
        let bad = argv.get(script as usize).map(|v| v.as_slice()).unwrap_or(b"");
        cli.print_usage(bad);
        return 1;
    }

    if args & HAS_V != 0 {
        print_version();
    }

    if args & HAS_BIG_E != 0 {
        api::push_boolean(state, true);
        if let Err(e) = api::set_field(state, LUA_REGISTRYINDEX, b"LUA_NOENV") {
            return if cli.report(Err(e)) { 0 } else { 1 };
        }
    }

    if script > 0 {
        if let Some(dir) = path_from_bytes(&argv[script as usize])
            .parent()
            .filter(|d| !d.as_os_str().is_empty())
        {
            crate::prepend_lua_path(dir);
        }
    }

    if let Err(e) = open_libs(state) {
        cli.report(Err(e));
        return 1;
    }
    if let Err(e) = preload(state) {
        cli.report(Err(e));
        return 1;
    }

    if let Err(e) = createargtable(state, argv, script) {
        cli.report(Err(e));
        return 1;
    }

    if args & HAS_BIG_E == 0 && !cli.handle_luainit(state) {
        return 1;
    }

    let optlim = if script > 0 { script } else { argv.len() as i32 };
    if !cli.runargs(state, argv, optlim) {
        return 1;
    }

    if script > 0 && !cli.handle_script(state, argv, script) {
        return 1;
    }

    if args & HAS_I != 0 {
        crate::repl::do_repl(state, &mut cli);
    } else if script < 1 && args & (HAS_E | HAS_V) == 0 {
        if stdin_is_tty() {
            print_version();
            crate::repl::do_repl(state, &mut cli);
        } else {
            cli.dofile(state, None);
        }
    }

    0
}

// ──────────────────────────────────────────────────────────────────────────
// PORT STATUS
//   source:        reference/lua-5.4.7/src/lua.c (option handling + pmain)
//   target_crate:  lua-cli
//   confidence:    medium
//   todos:         1  (os.exit exit-code propagation is a pre-existing
//                      lua-stdlib gap: os_lib.rs returns a placeholder
//                      with_status error; a LuaError::Exit(i32) variant is
//                      needed for faithful behaviour — out of scope here)
//   port_notes:    3  (LUA_COPYRIGHT banner reused; shebang stripped in
//                      buffer not reader; script-dir prepended to LUA_PATH —
//                      a lua-rs extension preserved from the prior CLI)
//   unsafe_blocks: 0
//   notes:         docall installs msghandler as the pcall errfunc; the VM
//                  invokes it during error synthesis (do_.rs pcall), so the
//                  returned LuaError carries the traceback string. SIGINT
//                  interruption of a running chunk is wired in repl.rs.
// ──────────────────────────────────────────────────────────────────────────