lua-rs 0.0.11

Lua port written in 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
897
898
// Copyright (C) 1994-2017 Lua.org, PUC-Rio.
// Copyright (C) 2018-2020 Ahmed Charles - acharles@outlook.com
// Distributed under the MIT License.
//    (See accompanying file LICENSE.txt or copy at
//          http://opensource.org/licenses/MIT)

//! Lua stand-alone interpreter

#![deny(warnings)]
#![deny(absolute_paths_not_starting_with_crate)]
#![deny(anonymous_parameters)]
#![deny(deprecated_in_future)]
#![deny(elided_lifetimes_in_paths)]
#![deny(explicit_outlives_requirements)]
#![deny(indirect_structural_match)]
#![deny(keyword_idents)]
#![deny(macro_use_extern_crate)]
#![deny(meta_variable_misuse)]
#![deny(missing_copy_implementations)]
#![deny(missing_debug_implementations)]
#![deny(missing_docs)]
#![deny(missing_doc_code_examples)]
#![deny(non_ascii_idents)]
#![deny(private_doc_tests)]
#![deny(single_use_lifetimes)]
#![deny(trivial_casts)]
#![deny(trivial_numeric_casts)]
#![deny(unreachable_pub)]
#![deny(unused_extern_crates)]
#![deny(unused_import_braces)]
#![deny(unused_labels)]
#![deny(unused_lifetimes)]
#![deny(unused_qualifications)]
#![deny(unused_results)]
#![deny(variant_size_differences)]

use lua_rs::ffi;

const LUA_PROMPT: &str = "> ";
const LUA_PROMPT2: &str = ">> ";

const INITVAR_NAME: &str = "=LUA_INIT";
const INITVAR_VERSION_NAME: &str = "=LUA_INIT_5_3";

/*
** stdin_is_tty detects whether the standard input is a 'tty' (that
** is, whether we're running lua interactively).
*/
#[cfg(unix)]
fn stdin_is_tty() -> bool {
    unsafe { libc::isatty(0) != 0 }
}

#[cfg(not(unix))]
fn stdin_is_tty() -> bool {
    true /* assume stdin is a tty */
}

/*
** readline defines how to show a prompt and then read a line from
** the standard input.
** saveline defines how to "save" a read line in a "history".
*/
fn readline(prompt: &str) -> Option<String> {
    use std::io::{self, Write};
    print!("{}", prompt);
    io::stdout().flush().unwrap(); /* show prompt */
    let mut input = String::new();
    /* get line */
    match io::stdin().read_line(&mut input) {
        Ok(_) => Some(input),
        Err(_) => None,
    }
}
fn saveline(_: &str) {}

#[allow(non_upper_case_globals)]
static mut global_l: *mut ffi::lua_State = 0 as *mut _;

/*
** Hook set by signal function to stop the interpreter.
*/
#[cfg(unix)]
extern "C" fn stop(l: *mut ffi::lua_State, _: *mut ffi::lua_Debug) {
    unsafe { ffi::lua_sethook(l, None, 0, 0) }; /* reset hook */
    unsafe { ffi::luaL_error(l, b"interrupted!\0".as_ptr() as _) };
}

/*
** Function to be called at a C signal. Because a C signal cannot
** just change a Lua state (as there is no proper synchronization),
** this function only sets a hook that, when called, will stop the
** interpreter.
*/
#[cfg(unix)]
extern "C" fn laction(i: i32) {
    /* if another SIGINT happens, terminate process */
    let _ = unsafe { libc::signal(i, libc::SIG_DFL) };
    unsafe {
        ffi::lua_sethook(
            global_l,
            Some(stop),
            ffi::LUA_MASKCALL | ffi::LUA_MASKRET | ffi::LUA_MASKCOUNT,
            1,
        )
    };
}

fn print_usage(badoption: &str) {
    let progname = std::env::args().next().unwrap();
    eprint!("{}: ", progname);
    let ch = badoption.chars().nth(1).unwrap();
    if ch == 'e' || ch == 'l' {
        eprintln!("'{}' needs argument", badoption);
    } else {
        eprintln!("unrecognized option '{}'", badoption);
    }
    eprintln!(
        r#"usage: {} [options] [script [args]]
Available options are:
  -e stat  execute string 'stat'
  -i       enter interactive mode after executing 'script'
  -l name  require library 'name' into global 'name'
  -v       show version information
  -E       ignore environment variables
  --       stop handling options
  -        stop handling options and execute stdin"#,
        progname
    );
}

/*
** Prints an error message, adding the program name in front of it
** (if include_name is true).
*/
fn message(msg: &str, include_name: bool) {
    if include_name {
        eprint!("{}: ", std::env::args().next().unwrap());
    }
    eprintln!("{}", msg);
}

/*
** Check whether 'status' is not OK and, if so, prints the error
** message on the top of the stack. It assumes that the error object
** is a string, as it was either generated by Lua or by 'msghandler'.
*/
fn report(l: *mut ffi::lua_State, status: i32, include_name: bool) -> i32 {
    if status != ffi::LUA_OK {
        let mut len: usize = 0;
        let msg = unsafe { ffi::lua_tolstring(l, -1, &mut len) };
        let msg_slice = unsafe { std::slice::from_raw_parts(msg as _, len) };
        message(std::str::from_utf8(msg_slice).unwrap(), include_name);
        unsafe { ffi::lua_pop(l, 1) }; /* remove message */
    }
    status
}

/*
** Message handler used to run all chunks
*/
fn msghandler_(l: *mut ffi::lua_State) -> i32 {
    let mut msg = unsafe { ffi::lua_tostring(l, 1) };
    /* is error object not a string? */
    if msg.is_null() {
        let meta = unsafe { ffi::luaL_callmeta(l, 1, b"__tostring\0".as_ptr() as _) };
        /* does it have a metamethod that produces a string? */
        if meta != 0 && unsafe { ffi::lua_type(l, -1) } == ffi::LUA_TSTRING {
            return 1; /* that is the message */
        } else {
            msg = unsafe {
                ffi::lua_pushfstring(
                    l,
                    b"(error object is a %s value)\0".as_ptr() as _,
                    ffi::luaL_typename(l, 1),
                )
            };
        }
    }
    unsafe { ffi::luaL_traceback(l, l, msg, 1) }; /* append a standard traceback */
    1 /* return the traceback */
}

unsafe extern "C" fn msghandler(l: *mut ffi::lua_State) -> i32 {
    msghandler_(l)
}

/*
** Interface to 'lua_pcall', which sets appropriate message function
** and C-signal handler. Used to run all chunks.
*/
fn docall(l: *mut ffi::lua_State, narg: i32, nres: i32) -> i32 {
    let base = unsafe { ffi::lua_gettop(l) } - narg; /* function index */
    unsafe { ffi::lua_pushcfunction(l, Some(msghandler)) }; /* push message handler */
    unsafe { ffi::lua_insert(l, base) }; /* put it under function and args */
    unsafe { global_l = l }; /* to be available to 'laction' */
    #[cfg(unix)]
    let _ = unsafe { libc::signal(libc::SIGINT, laction as _) }; /* set C-signal handler */
    let status = unsafe { ffi::lua_pcall(l, narg, nres, base) };
    #[cfg(unix)]
    let _ = unsafe { libc::signal(libc::SIGINT, libc::SIG_DFL) }; /* reset C-signal handler */
    unsafe { ffi::lua_remove(l, base) }; /* remove message handler from the stack */
    status
}

fn print_version() {
    println!("Lua 5.3.5  Copyright (C) 1994-2018 Lua.org, PUC-Rio");
}

/*
** Create the 'arg' table, which stores all arguments from the
** command line ('options'). It should be aligned so that, at index 0,
** it has 'script_args[0]', which is the script name. The arguments
** to the script (everything after 'script_args[0]') go to positive indices;
** other arguments (pre_script_args) go to negative indices.
** If there is no script name, assume interpreter's name as base.
*/
fn createargtable(l: *mut ffi::lua_State, options: &ProgramOptions<'_>) {
    /* no script name? */
    let (pre, post) = if options.script_args.is_empty() {
        (options.script_args, options.pre_script_args)
    } else {
        (options.pre_script_args, options.script_args)
    };
    unsafe { ffi::lua_createtable(l, post.len() as _, (pre.len() + 1) as _) };
    for (i, arg) in pre.iter().enumerate() {
        let _ = unsafe { ffi::lua_pushlstring(l, arg.as_ptr() as _, arg.as_bytes().len()) };
        unsafe { ffi::lua_rawseti(l, -2, i as i64 - pre.len() as i64) };
    }
    for (i, arg) in post.iter().enumerate() {
        let _ = unsafe { ffi::lua_pushlstring(l, arg.as_ptr() as _, arg.as_bytes().len()) };
        unsafe { ffi::lua_rawseti(l, -2, i as _) };
    }
    unsafe { ffi::lua_setglobal(l, b"arg\0".as_ptr() as _) };
}

fn dochunk(l: *mut ffi::lua_State, status: i32) -> i32 {
    let stat = if status == ffi::LUA_OK {
        docall(l, 0, 0)
    } else {
        status
    };
    report(l, stat, true)
}

fn dofile(l: *mut ffi::lua_State, name: Option<&str>) -> i32 {
    let status = match name {
        Some(n) => {
            let s = std::ffi::CString::new(n).unwrap();
            unsafe { ffi::luaL_loadfile(l, s.as_ptr()) }
        }
        None => unsafe { ffi::luaL_loadfile(l, std::ptr::null()) },
    };
    dochunk(l, status)
}

fn dostring(l: *mut ffi::lua_State, s: &str, name: &str) -> i32 {
    let name = std::ffi::CString::new(name).unwrap();
    dochunk(l, unsafe {
        ffi::luaL_loadbuffer(l, s.as_ptr() as _, s.as_bytes().len(), name.as_ptr())
    })
}

/*
** Calls 'require(name)' and stores the result in a global variable
** with the given name.
*/
fn dolibrary(l: *mut ffi::lua_State, name: &str) -> i32 {
    let _ = unsafe { ffi::lua_getglobal(l, b"require\0".as_ptr() as _) };
    let name = std::ffi::CString::new(name).unwrap();
    let _ = unsafe { ffi::lua_pushlstring(l, name.as_ptr(), name.as_bytes().len()) };
    let status = docall(l, 1, 1); /* call 'require(name)' */
    if status == ffi::LUA_OK {
        unsafe { ffi::lua_setglobal(l, name.as_ptr()) }; /* global[name] = require return */
    }
    report(l, status, true)
}

/*
** Returns the string to be used as a prompt by the interpreter.
*/
fn get_prompt(l: *mut ffi::lua_State, firstline: bool) -> String {
    let s = if firstline {
        b"_PROMPT\0".as_ref()
    } else {
        b"_PROMPT2\0".as_ref()
    };
    let _ = unsafe { ffi::lua_getglobal(l, s.as_ptr() as _) };
    let p = unsafe { ffi::lua_tostring(l, -1) };
    if p.is_null() {
        if firstline { LUA_PROMPT } else { LUA_PROMPT2 }.to_string()
    } else {
        unsafe { std::ffi::CStr::from_ptr(p) }
            .to_str()
            .unwrap()
            .to_string()
    }
}

/* mark in error messages for incomplete statements */
const EOFMARK: &str = "<eof>";

/*
** Check whether 'status' signals a syntax error and the error
** message at the top of the stack ends with the above mark for
** incomplete statements.
*/
fn incomplete(l: *mut ffi::lua_State, status: i32) -> bool {
    if status == ffi::LUA_ERRSYNTAX {
        let msg = unsafe { ffi::lua_tostring(l, -1) };
        let s = unsafe { std::ffi::CStr::from_ptr(msg) };
        if s.to_str().unwrap().ends_with(EOFMARK) {
            unsafe { ffi::lua_pop(l, 1) };
            return true;
        }
    }
    false
}

/*
** Prompt the user, read a line, and push it into the Lua stack.
*/
fn pushline(l: *mut ffi::lua_State, firstline: bool) -> bool {
    let prompt = get_prompt(l, firstline);
    let mut line = match readline(&prompt) {
        Some(l) => l,
        None => return false,
    };
    if line.is_empty() {
        return false; /* no input (prompt will be popped by caller) */
    }
    unsafe { ffi::lua_pop(l, 1) }; /* remove prompt */
    /* line ends with newline? */
    if line.ends_with('\n') {
        let _ = line.pop(); /* remove it */
    }
    let _ = unsafe { ffi::lua_pushlstring(l, line.as_ptr() as _, line.as_bytes().len()) };
    true
}

/*
** Try to compile line on the stack as 'return <line>;'; on return, stack
** has either compiled chunk or original line (if compilation failed).
*/
fn addreturn(l: *mut ffi::lua_State) -> i32 {
    let line = unsafe { ffi::lua_tostring(l, -1) }; /* original line */
    let retline = unsafe { ffi::lua_pushfstring(l, b"return %s;\0".as_ptr() as _, line) };
    let status = unsafe {
        ffi::luaL_loadbuffer(l, retline, libc::strlen(retline), b"=stdin\0".as_ptr() as _)
    };
    if status == ffi::LUA_OK {
        unsafe { ffi::lua_remove(l, -2) }; /* remove modified line */
        let s = unsafe { std::ffi::CStr::from_ptr(line) };
        /* non empty? */
        if !s.to_bytes().is_empty() {
            saveline(s.to_str().unwrap()); /* keep history */
        }
    } else {
        unsafe { ffi::lua_pop(l, 2) }; /* pop result from 'luaL_loadbuffer' and modified line */
    }
    status
}

/*
** Read multiple lines until a complete Lua statement
*/
fn multiline(l: *mut ffi::lua_State) -> i32 {
    /* repeat until gets a complete statement */
    loop {
        let mut len: usize = 0;
        let line = unsafe { ffi::lua_tolstring(l, 1, &mut len) }; /* get what it has */
        /* try it */
        let status = unsafe { ffi::luaL_loadbuffer(l, line, len, b"=stdin\0".as_ptr() as _) };
        if !incomplete(l, status) || !pushline(l, false) {
            let s = unsafe { std::ffi::CStr::from_ptr(line) };
            saveline(s.to_str().unwrap()); /* keep history */
            return status; /* cannot or should not try to add continuation line */
        }
        let _ = unsafe { ffi::lua_pushliteral(l, b"\n") }; /* add newline... */
        unsafe { ffi::lua_insert(l, -2) }; /* ...between the two lines */
        unsafe { ffi::lua_concat(l, 3) }; /* join them */
    }
}

/*
** Read a line and try to load (compile) it first as an expression (by
** adding "return " in front of it) and second as a statement. Return
** the final status of load/call with the resulting function (if any)
** in the top of the stack.
*/
fn loadline(l: *mut ffi::lua_State) -> i32 {
    unsafe { ffi::lua_settop(l, 0) };
    if !pushline(l, true) {
        return -1; /* no input */
    }
    let mut status = addreturn(l);
    /* 'return ...' did not work? */
    if status != ffi::LUA_OK {
        status = multiline(l); /* try as command, maybe with continuation lines */
    }
    unsafe { ffi::lua_remove(l, 1) }; /* remove line from the stack */
    assert!(unsafe { ffi::lua_gettop(l) } == 1);
    status
}

/*
** Prints (calling the Lua 'print' function) any values on the stack
*/
fn print(l: *mut ffi::lua_State) {
    let n = unsafe { ffi::lua_gettop(l) };
    /* any result to be printed? */
    if n > 0 {
        unsafe {
            ffi::luaL_checkstack(
                l,
                ffi::LUA_MINSTACK,
                b"too many results to print\0".as_ptr() as _,
            )
        };
        let _ = unsafe { ffi::lua_getglobal(l, b"print\0".as_ptr() as _) };
        unsafe { ffi::lua_insert(l, 1) };
        if unsafe { ffi::lua_pcall(l, n, 0, 0) } != ffi::LUA_OK {
            let msg = unsafe {
                ffi::lua_pushfstring(
                    l,
                    b"error calling 'print' (%s)\0".as_ptr() as _,
                    ffi::lua_tostring(l, -1),
                )
            };
            message(
                unsafe { std::ffi::CStr::from_ptr(msg) }.to_str().unwrap(),
                false,
            );
        }
    }
}

/*
** Do the REPL: repeatedly read (load) a line, evaluate (call) it, and
** print any results.
*/
fn dorepl(l: *mut ffi::lua_State) {
    loop {
        let mut status = loadline(l);
        if status == -1 {
            break;
        }
        if status == ffi::LUA_OK {
            status = docall(l, 0, ffi::LUA_MULTRET);
        }
        if status == ffi::LUA_OK {
            print(l);
        } else {
            /* no 'progname' on errors in interactive mode */
            let _ = report(l, status, false);
        }
    }
    unsafe { ffi::lua_settop(l, 0) }; /* clear stack */
    println!();
}

/*
** Push on the stack the contents of table 'arg' from 1 to #arg
*/
fn pushargs(l: *mut ffi::lua_State) -> i32 {
    let ty = unsafe { ffi::lua_getglobal(l, b"arg\0".as_ptr() as _) };
    if ty != ffi::LUA_TTABLE {
        unsafe { ffi::luaL_error(l, b"'arg' is not a table\0".as_ptr() as _) };
    }
    let n = unsafe { ffi::luaL_len(l, -1) } as i32;
    unsafe { ffi::luaL_checkstack(l, n + 3, b"too many arguments to script\0".as_ptr() as _) };
    for i in 1..=n {
        let _ = unsafe { ffi::lua_rawgeti(l, -i, i64::from(i)) };
    }
    unsafe { ffi::lua_remove(l, -(n + 1)) }; /* remove table from the stack */
    n
}

fn handle_script(l: *mut ffi::lua_State, args: &[&str], stop_options: bool) -> i32 {
    let s = std::ffi::CString::new(args[0]).unwrap();
    let fname = if args[0] == "-" && !stop_options {
        std::ptr::null() /* stdin */
    } else {
        s.as_ptr()
    };
    let mut status = unsafe { ffi::luaL_loadfile(l, fname) };
    if status == ffi::LUA_OK {
        let n = pushargs(l); /* push arguments to script */
        status = docall(l, n, ffi::LUA_MULTRET);
    }
    report(l, status, true)
}

#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
#[allow(single_use_lifetimes)]
enum RunnableArg<'a> {
    Library(&'a str), /* -l */
    Execute(&'a str), /* -e */
}

/* represents the various argument indicators in 'args' */
#[derive(Default, PartialEq, Eq, PartialOrd, Ord, Debug)]
#[allow(single_use_lifetimes)]
struct ProgramOptions<'a> {
    interactive: bool,                   /* -i */
    version: bool,                       /* -v */
    ignore_env: bool,                    /* -E */
    execute: bool,                       /* -e */
    stop_options: bool,                  /* -- */
    runnable_args: Vec<RunnableArg<'a>>, /* -l or -e */
    pre_script_args: &'a [&'a str],      /* before script name */
    script_args: &'a [&'a str],          /* script name and args */
}

/*
** Traverses all arguments from 'args', returning a ProgramOptions with those
** needed before running any Lua code (or an error code if it finds
** any invalid argument). It returns the first not-handled argument as
** either the script name or a bad argument in case of error.
*/
fn collectargs<'a>(args: &'a [&str]) -> Result<ProgramOptions<'a>, &'a str> {
    fn add_script_args<'b>(
        mut options: ProgramOptions<'b>,
        args: &'b [&str],
        script: usize,
    ) -> Result<ProgramOptions<'b>, &'b str> {
        let (pre_script_args, script_args) = args.split_at(script);
        options.pre_script_args = pre_script_args;
        options.script_args = script_args;
        Ok(options)
    }
    let mut options: ProgramOptions<'_> = Default::default();
    let mut first = 0usize;
    let mut skip = 0;
    for (i, arg) in args.iter().enumerate().skip(1) {
        first = i;
        if skip != 0 {
            /* another option instead of an argument */
            if arg.starts_with('-') {
                return Err(args[first]);
            }
            options.runnable_args.push(if skip == 1 {
                RunnableArg::Library(arg)
            } else {
                RunnableArg::Execute(arg)
            });
            skip = 0;
            continue;
        }
        /* not an option? */
        if !arg.starts_with('-') {
            return add_script_args(options, args, first); /* stop handling options */
        }
        /* '-' */
        if arg.len() == 1 {
            return add_script_args(options, args, first); /* script "name" is '-' */
        }
        /* else check option */
        match arg.chars().nth(1).unwrap() {
            /* '--' */
            '-' => {
                /* extra characters after '--'? */
                if arg.len() != 2 {
                    return Err(args[first]); /* invalid option */
                }
                options.stop_options = true;
                return add_script_args(options, args, first + 1);
            }
            'E' => {
                /* extra characters after 1st? */
                if arg.len() != 2 {
                    return Err(args[first]); /* invalid option */
                }
                options.ignore_env = true;
            }
            'i' => {
                /* extra characters after 1st? */
                if arg.len() != 2 {
                    return Err(args[first]); /* invalid option */
                }
                options.interactive = true;
                options.version = true; /* (-i implies -v) */
            }
            'v' => {
                /* extra characters after 1st? */
                if arg.len() != 2 {
                    return Err(args[first]); /* invalid option */
                }
                options.version = true;
            }
            'e' => {
                options.execute = true;
                /* no concatenated argument? */
                if arg.len() == 2 {
                    skip = 2; /* try next 'arg' */
                } else {
                    let (_, a) = arg.split_at(2);
                    options.runnable_args.push(RunnableArg::Execute(a));
                }
            }
            'l' => {
                /* no concatenated argument? */
                if arg.len() == 2 {
                    skip = 1; /* try next 'arg' */
                } else {
                    let (_, a) = arg.split_at(2);
                    options.runnable_args.push(RunnableArg::Library(a));
                }
            }
            _ => return Err(args[first]), /* invalid option */
        }
    }
    /* no argument to option */
    if skip != 0 {
        return Err(args[first]);
    }
    add_script_args(options, args, first + 1) /* no script name */
}

/*
** Processes options 'e' and 'l', which involve running Lua code.
** Returns 0 if some code raises an error.
*/
fn runargs(l: *mut ffi::lua_State, runnable_args: &[RunnableArg<'_>]) -> bool {
    for arg in runnable_args {
        let status = match *arg {
            RunnableArg::Library(s) => dolibrary(l, s),
            RunnableArg::Execute(s) => dostring(l, s, "=(command line)"),
        };
        if status != ffi::LUA_OK {
            return false;
        }
    }
    true
}

fn handle_luainit(l: *mut ffi::lua_State) -> i32 {
    fn get_var(name: &str) -> Option<(String, &str)> {
        let mut chars = name.chars();
        let _ = chars.next(); /* skip the '=' to get the key */
        match std::env::var(chars.as_str()) {
            Ok(val) => Some((val, name)),
            Err(_) => None,
        }
    }
    let (init, name) = match get_var(INITVAR_VERSION_NAME).or_else(|| get_var(INITVAR_NAME)) {
        Some((i, n)) => (i, n),
        None => return ffi::LUA_OK,
    };
    if init.starts_with('@') {
        let mut chars = init.chars();
        let _ = chars.next(); /* skip the '@' to get the key */
        dofile(l, Some(chars.as_str()))
    } else {
        dostring(l, &init, &name)
    }
}

#[cfg(debug_assertions)]
fn openlibs(l: *mut ffi::lua_State) {
    unsafe { ffi::luaL_openlibs(l) };
    extern "C" {
        fn luaB_opentests(l: *mut ffi::lua_State) -> i32;
    }
    unsafe { ffi::luaL_requiref(l, b"T\0".as_ptr() as _, Some(luaB_opentests), 1) };
}
#[cfg(not(debug_assertions))]
fn openlibs(l: *mut ffi::lua_State) {
    unsafe { ffi::luaL_openlibs(l) };
}

/*
** Main body of stand-alone interpreter (to be called in protected mode).
** Reads the options and handles them all.
*/
fn pmain_(l: *mut ffi::lua_State) -> i32 {
    let args: Vec<_> = std::env::args().collect();
    let arg_strs: Vec<_> = args.iter().map(AsRef::as_ref).collect();
    let options = match collectargs(&arg_strs) {
        Ok(o) => o,
        Err(bad_arg) => {
            print_usage(bad_arg);
            return 0;
        }
    };
    /* option '-v'? */
    if options.version {
        print_version();
    }
    /* option '-E'? */
    if options.ignore_env {
        unsafe { ffi::lua_pushboolean(l, 1) }; /* signal for libraries to ignore env. vars. */
        unsafe { ffi::lua_setfield(l, ffi::LUA_REGISTRYINDEX, "LUA_NOENV\0".as_ptr() as _) };
    }
    openlibs(l); /* open standard libraries */
    createargtable(l, &options); /* create table 'arg' */
    /* no option '-E'? run LUA_INIT */
    if !options.ignore_env && handle_luainit(l) != ffi::LUA_OK {
        return 0; /* error running LUA_INIT */
    }
    /* execute arguments -e and -l */
    if !runargs(l, &options.runnable_args) {
        return 0; /* something failed */
    }
    /* execute main script (if there is one) */
    if !options.script_args.is_empty()
        && handle_script(l, options.script_args, options.stop_options) != ffi::LUA_OK
    {
        return 0;
    }
    /* -i option? */
    if options.interactive {
        dorepl(l); /* do read-eval-print loop */
    }
    /* no arguments? */
    else if options.script_args.is_empty() && !(options.execute || options.version) {
        /* running in interactive mode? */
        if stdin_is_tty() {
            print_version();
            dorepl(l); /* do read-eval-print loop */
        } else {
            let _ = dofile(l, None); /* executes stdin as a file */
        }
    }
    unsafe { ffi::lua_pushboolean(l, 1) }; /* signal no errors */
    1
}

unsafe extern "C" fn pmain(l: *mut ffi::lua_State) -> i32 {
    pmain_(l)
}

#[cfg(debug_assertions)]
fn newstate() -> *mut ffi::lua_State {
    #[repr(C)]
    struct Memcontrol {
        numblocks: u64,
        total: u64,
        maxmem: u64,
        memlimit: u64,
        objcount: [u64; ffi::LUA_NUMTAGS as usize],
    }

    extern "C" {
        static mut l_memcontrol: Memcontrol;
    }

    extern "C" {
        fn debug_realloc(
            ud: *mut std::ffi::c_void,
            ptr: *mut std::ffi::c_void,
            osize: usize,
            osize: usize,
        ) -> *mut std::ffi::c_void;
    }
    #[allow(trivial_casts)]
    unsafe {
        ffi::lua_newstate(
            Some(debug_realloc),
            &mut l_memcontrol as *mut Memcontrol as *mut _,
        )
    }
}
#[cfg(not(debug_assertions))]
fn newstate() -> *mut ffi::lua_State {
    unsafe { ffi::luaL_newstate() }
}

fn main() {
    let l = newstate(); /* create state */
    if l.is_null() {
        message("cannot create state: not enough memory", true);
        std::process::exit(1);
    }
    unsafe { ffi::lua_pushcfunction(l, Some(pmain)) }; /* to call 'pmain' in protected mode */
    let status = unsafe { ffi::lua_pcall(l, 0, 1, 0) }; /* do the call */
    let result = unsafe { ffi::lua_toboolean(l, -1) }; /* get result */
    let _ = report(l, status, true);
    unsafe { ffi::lua_close(l) };
    std::process::exit(if result != 0 && status == ffi::LUA_OK {
        0
    } else {
        1
    });
}

#[cfg(test)]
mod tests {
    use super::collectargs;
    use super::ProgramOptions;
    use super::RunnableArg::{Execute, Library};

    #[test]
    fn test_collectargs() {
        assert_eq!(
            collectargs(vec!["lua"].as_slice()),
            Ok(ProgramOptions {
                pre_script_args: &["lua"],
                ..Default::default()
            })
        );
        assert_eq!(
            collectargs(vec!["lua", "name"].as_slice()),
            Ok(ProgramOptions {
                pre_script_args: &["lua"],
                script_args: &["name"],
                ..Default::default()
            })
        );
        assert_eq!(
            collectargs(vec!["lua", "-"].as_slice()),
            Ok(ProgramOptions {
                pre_script_args: &["lua"],
                script_args: &["-"],
                ..Default::default()
            })
        );
        assert_eq!(
            collectargs(vec!["lua", "--"].as_slice()),
            Ok(ProgramOptions {
                stop_options: true,
                pre_script_args: &["lua", "--"],
                ..Default::default()
            })
        );
        assert_eq!(
            collectargs(vec!["lua", "-i"].as_slice()),
            Ok(ProgramOptions {
                interactive: true,
                version: true,
                pre_script_args: &["lua", "-i"],
                ..Default::default()
            })
        );
        assert_eq!(
            collectargs(vec!["lua", "-v"].as_slice()),
            Ok(ProgramOptions {
                version: true,
                pre_script_args: &["lua", "-v"],
                ..Default::default()
            })
        );
        assert_eq!(
            collectargs(vec!["lua", "-v", "name"].as_slice()),
            Ok(ProgramOptions {
                version: true,
                pre_script_args: &["lua", "-v"],
                script_args: &["name"],
                ..Default::default()
            })
        );
        assert_eq!(collectargs(vec!["lua", "-e"].as_slice()), Err("-e"));
        assert_eq!(
            collectargs(vec!["lua", "-escript"].as_slice()),
            Ok(ProgramOptions {
                execute: true,
                runnable_args: vec![Execute("script")],
                pre_script_args: &["lua", "-escript"],
                ..Default::default()
            })
        );
        assert_eq!(
            collectargs(vec!["lua", "-e", "script"].as_slice()),
            Ok(ProgramOptions {
                execute: true,
                runnable_args: vec![Execute("script")],
                pre_script_args: &["lua", "-e", "script"],
                ..Default::default()
            })
        );
        assert_eq!(
            collectargs(vec!["lua", "-E"].as_slice()),
            Ok(ProgramOptions {
                ignore_env: true,
                pre_script_args: &["lua", "-E"],
                ..Default::default()
            })
        );
        assert_eq!(collectargs(vec!["lua", "-l"].as_slice()), Err("-l"));
        assert_eq!(
            collectargs(vec!["lua", "-llib"].as_slice()),
            Ok(ProgramOptions {
                runnable_args: vec![Library("lib")],
                pre_script_args: &["lua", "-llib"],
                ..Default::default()
            })
        );
        assert_eq!(
            collectargs(vec!["lua", "-l", "lib"].as_slice()),
            Ok(ProgramOptions {
                runnable_args: vec![Library("lib")],
                pre_script_args: &["lua", "-l", "lib"],
                ..Default::default()
            })
        );
        assert_eq!(collectargs(vec!["lua", "-x"].as_slice()), Err("-x"));
    }
}