1/*
2** $Id: lua.c $
3** Lua stand-alone interpreter
4** See Copyright Notice in lua.h
5*/
6
7#define lua_c
8
9#include "lprefix.h"
10
11
12#include <stdio.h>
13#include <stdlib.h>
14#include <string.h>
15
16#include <signal.h>
17
18#include "lua.h"
19
20#include "lauxlib.h"
21#include "lualib.h"
22
23
24#if !defined(LUA_PROGNAME)
25#define LUA_PROGNAME "lua"
26#endif
27
28#if !defined(LUA_INIT_VAR)
29#define LUA_INIT_VAR "LUA_INIT"
30#endif
31
32#define LUA_INITVARVERSION LUA_INIT_VAR LUA_VERSUFFIX
33
34
35static lua_State *globalL = NULL;
36
37static const char *progname = LUA_PROGNAME;
38
39
40#if defined(LUA_USE_POSIX) /* { */
41
42/*
43** Use 'sigaction' when available.
44*/
45static void setsignal (int sig, void (*handler)(int)) {
46 struct sigaction sa;
47 sa.sa_handler = handler;
48 sa.sa_flags = 0;
49 sigemptyset(&sa.sa_mask); /* do not mask any signal */
50 sigaction(sig, &sa, NULL);
51}
52
53#else /* }{ */
54
55#define setsignal signal
56
57#endif /* } */
58
59
60/*
61** Hook set by signal function to stop the interpreter.
62*/
63static void lstop (lua_State *L, lua_Debug *ar) {
64 (void)ar; /* unused arg. */
65 lua_sethook(L, NULL, 0, 0); /* reset hook */
66 luaL_error(L, "interrupted!");
67}
68
69
70/*
71** Function to be called at a C signal. Because a C signal cannot
72** just change a Lua state (as there is no proper synchronization),
73** this function only sets a hook that, when called, will stop the
74** interpreter.
75*/
76static void laction (int i) {
77 int flag = LUA_MASKCALL | LUA_MASKRET | LUA_MASKLINE | LUA_MASKCOUNT;
78 setsignal(i, SIG_DFL); /* if another SIGINT happens, terminate process */
79 lua_sethook(globalL, lstop, flag, 1);
80}
81
82
83static void print_usage (const char *badoption) {
84 lua_writestringerror("%s: ", progname);
85 if (badoption[1] == 'e' || badoption[1] == 'l')
86 lua_writestringerror("'%s' needs argument\n", badoption);
87 else
88 lua_writestringerror("unrecognized option '%s'\n", badoption);
89 lua_writestringerror(
90 "usage: %s [options] [script [args]]\n"
91 "Available options are:\n"
92 " -e stat execute string 'stat'\n"
93 " -i enter interactive mode after executing 'script'\n"
94 " -l mod require library 'mod' into global 'mod'\n"
95 " -l g=mod require library 'mod' into global 'g'\n"
96 " -v show version information\n"
97 " -E ignore environment variables\n"
98 " -W turn warnings on\n"
99 " -- stop handling options\n"
100 " - stop handling options and execute stdin\n"
101 ,
102 progname);
103}
104
105
106/*
107** Prints an error message, adding the program name in front of it
108** (if present)
109*/
110static void l_message (const char *pname, const char *msg) {
111 if (pname) lua_writestringerror("%s: ", pname);
112 lua_writestringerror("%s\n", msg);
113}
114
115
116/*
117** Check whether 'status' is not OK and, if so, prints the error
118** message on the top of the stack.
119*/
120static int report (lua_State *L, int status) {
121 if (status != LUA_OK) {
122 const char *msg = lua_tostring(L, -1);
123 if (msg == NULL)
124 msg = "(error message not a string)";
125 l_message(progname, msg);
126 lua_pop(L, 1); /* remove message */
127 }
128 return status;
129}
130
131
132/*
133** Message handler used to run all chunks
134*/
135static int msghandler (lua_State *L) {
136 const char *msg = lua_tostring(L, 1);
137 if (msg == NULL) { /* is error object not a string? */
138 if (luaL_callmeta(L, 1, "__tostring") && /* does it have a metamethod */
139 lua_type(L, -1) == LUA_TSTRING) /* that produces a string? */
140 return 1; /* that is the message */
141 else
142 msg = lua_pushfstring(L, "(error object is a %s value)",
143 luaL_typename(L, 1));
144 }
145 luaL_traceback(L, L, msg, 1); /* append a standard traceback */
146 return 1; /* return the traceback */
147}
148
149
150/*
151** Interface to 'lua_pcall', which sets appropriate message function
152** and C-signal handler. Used to run all chunks.
153*/
154static int docall (lua_State *L, int narg, int nres) {
155 int status;
156 int base = lua_gettop(L) - narg; /* function index */
157 lua_pushcfunction(L, msghandler); /* push message handler */
158 lua_insert(L, base); /* put it under function and args */
159 globalL = L; /* to be available to 'laction' */
160 setsignal(SIGINT, laction); /* set C-signal handler */
161 status = lua_pcall(L, narg, nres, base);
162 setsignal(SIGINT, SIG_DFL); /* reset C-signal handler */
163 lua_remove(L, base); /* remove message handler from the stack */
164 return status;
165}
166
167
168static void print_version (void) {
169 lua_writestring(LUA_COPYRIGHT, strlen(LUA_COPYRIGHT));
170 lua_writeline();
171}
172
173
174/*
175** Create the 'arg' table, which stores all arguments from the
176** command line ('argv'). It should be aligned so that, at index 0,
177** it has 'argv[script]', which is the script name. The arguments
178** to the script (everything after 'script') go to positive indices;
179** other arguments (before the script name) go to negative indices.
180** If there is no script name, assume interpreter's name as base.
181** (If there is no interpreter's name either, 'script' is -1, so
182** table sizes are zero.)
183*/
184static void createargtable (lua_State *L, char **argv, int argc, int script) {
185 int i, narg;
186 narg = argc - (script + 1); /* number of positive indices */
187 lua_createtable(L, narg, script + 1);
188 for (i = 0; i < argc; i++) {
189 lua_pushstring(L, argv[i]);
190 lua_rawseti(L, -2, i - script);
191 }
192 lua_setglobal(L, "arg");
193}
194
195
196static int dochunk (lua_State *L, int status) {
197 if (status == LUA_OK) status = docall(L, 0, 0);
198 return report(L, status);
199}
200
201
202static int dofile (lua_State *L, const char *name) {
203 return dochunk(L, luaL_loadfile(L, name));
204}
205
206
207static int dostring (lua_State *L, const char *s, const char *name) {
208 return dochunk(L, luaL_loadbuffer(L, s, strlen(s), name));
209}
210
211
212/*
213** Receives 'globname[=modname]' and runs 'globname = require(modname)'.
214** If there is no explicit modname and globname contains a '-', cut
215** the suffix after '-' (the "version") to make the global name.
216*/
217static int dolibrary (lua_State *L, char *globname) {
218 int status;
219 char *suffix = NULL;
220 char *modname = strchr(globname, '=');
221 if (modname == NULL) { /* no explicit name? */
222 modname = globname; /* module name is equal to global name */
223 suffix = strchr(modname, *LUA_IGMARK); /* look for a suffix mark */
224 }
225 else {
226 *modname = '\0'; /* global name ends here */
227 modname++; /* module name starts after the '=' */
228 }
229 lua_getglobal(L, "require");
230 lua_pushstring(L, modname);
231 status = docall(L, 1, 1); /* call 'require(modname)' */
232 if (status == LUA_OK) {
233 if (suffix != NULL) /* is there a suffix mark? */
234 *suffix = '\0'; /* remove suffix from global name */
235 lua_setglobal(L, globname); /* globname = require(modname) */
236 }
237 return report(L, status);
238}
239
240
241/*
242** Push on the stack the contents of table 'arg' from 1 to #arg
243*/
244static int pushargs (lua_State *L) {
245 int i, n;
246 if (lua_getglobal(L, "arg") != LUA_TTABLE)
247 luaL_error(L, "'arg' is not a table");
248 n = (int)luaL_len(L, -1);
249 luaL_checkstack(L, n + 3, "too many arguments to script");
250 for (i = 1; i <= n; i++)
251 lua_rawgeti(L, -i, i);
252 lua_remove(L, -i); /* remove table from the stack */
253 return n;
254}
255
256
257static int handle_script (lua_State *L, char **argv) {
258 int status;
259 const char *fname = argv[0];
260 if (strcmp(fname, "-") == 0 && strcmp(argv[-1], "--") != 0)
261 fname = NULL; /* stdin */
262 status = luaL_loadfile(L, fname);
263 if (status == LUA_OK) {
264 int n = pushargs(L); /* push arguments to script */
265 status = docall(L, n, LUA_MULTRET);
266 }
267 return report(L, status);
268}
269
270
271/* bits of various argument indicators in 'args' */
272#define has_error 1 /* bad option */
273#define has_i 2 /* -i */
274#define has_v 4 /* -v */
275#define has_e 8 /* -e */
276#define has_E 16 /* -E */
277
278
279/*
280** Traverses all arguments from 'argv', returning a mask with those
281** needed before running any Lua code or an error code if it finds any
282** invalid argument. In case of error, 'first' is the index of the bad
283** argument. Otherwise, 'first' is -1 if there is no program name,
284** 0 if there is no script name, or the index of the script name.
285*/
286static int collectargs (char **argv, int *first) {
287 int args = 0;
288 int i;
289 if (argv[0] != NULL) { /* is there a program name? */
290 if (argv[0][0]) /* not empty? */
291 progname = argv[0]; /* save it */
292 }
293 else { /* no program name */
294 *first = -1;
295 return 0;
296 }
297 for (i = 1; argv[i] != NULL; i++) { /* handle arguments */
298 *first = i;
299 if (argv[i][0] != '-') /* not an option? */
300 return args; /* stop handling options */
301 switch (argv[i][1]) { /* else check option */
302 case '-': /* '--' */
303 if (argv[i][2] != '\0') /* extra characters after '--'? */
304 return has_error; /* invalid option */
305 *first = i + 1;
306 return args;
307 case '\0': /* '-' */
308 return args; /* script "name" is '-' */
309 case 'E':
310 if (argv[i][2] != '\0') /* extra characters? */
311 return has_error; /* invalid option */
312 args |= has_E;
313 break;
314 case 'W':
315 if (argv[i][2] != '\0') /* extra characters? */
316 return has_error; /* invalid option */
317 break;
318 case 'i':
319 args |= has_i; /* (-i implies -v) *//* FALLTHROUGH */
320 case 'v':
321 if (argv[i][2] != '\0') /* extra characters? */
322 return has_error; /* invalid option */
323 args |= has_v;
324 break;
325 case 'e':
326 args |= has_e; /* FALLTHROUGH */
327 case 'l': /* both options need an argument */
328 if (argv[i][2] == '\0') { /* no concatenated argument? */
329 i++; /* try next 'argv' */
330 if (argv[i] == NULL || argv[i][0] == '-')
331 return has_error; /* no next argument or it is another option */
332 }
333 break;
334 default: /* invalid option */
335 return has_error;
336 }
337 }
338 *first = 0; /* no script name */
339 return args;
340}
341
342
343/*
344** Processes options 'e' and 'l', which involve running Lua code, and
345** 'W', which also affects the state.
346** Returns 0 if some code raises an error.
347*/
348static int runargs (lua_State *L, char **argv, int n) {
349 int i;
350 for (i = 1; i < n; i++) {
351 int option = argv[i][1];
352 lua_assert(argv[i][0] == '-'); /* already checked */
353 switch (option) {
354 case 'e': case 'l': {
355 int status;
356 char *extra = argv[i] + 2; /* both options need an argument */
357 if (*extra == '\0') extra = argv[++i];
358 lua_assert(extra != NULL);
359 status = (option == 'e')
360 ? dostring(L, extra, "=(command line)")
361 : dolibrary(L, extra);
362 if (status != LUA_OK) return 0;
363 break;
364 }
365 case 'W':
366 lua_warning(L, "@on", 0); /* warnings on */
367 break;
368 }
369 }
370 return 1;
371}
372
373
374static int handle_luainit (lua_State *L) {
375 const char *name = "=" LUA_INITVARVERSION;
376 const char *init = getenv(name + 1);
377 if (init == NULL) {
378 name = "=" LUA_INIT_VAR;
379 init = getenv(name + 1); /* try alternative name */
380 }
381 if (init == NULL) return LUA_OK;
382 else if (init[0] == '@')
383 return dofile(L, init+1);
384 else
385 return dostring(L, init, name);
386}
387
388
389/*
390** {==================================================================
391** Read-Eval-Print Loop (REPL)
392** ===================================================================
393*/
394
395#if !defined(LUA_PROMPT)
396#define LUA_PROMPT "> "
397#define LUA_PROMPT2 ">> "
398#endif
399
400#if !defined(LUA_MAXINPUT)
401#define LUA_MAXINPUT 512
402#endif
403
404
405/*
406** lua_stdin_is_tty detects whether the standard input is a 'tty' (that
407** is, whether we're running lua interactively).
408*/
409#if !defined(lua_stdin_is_tty) /* { */
410
411#if defined(LUA_USE_POSIX) /* { */
412
413#include <unistd.h>
414#define lua_stdin_is_tty() isatty(0)
415
416#elif defined(LUA_USE_WINDOWS) /* }{ */
417
418#include <io.h>
419#include <windows.h>
420
421#define lua_stdin_is_tty() _isatty(_fileno(stdin))
422
423#else /* }{ */
424
425/* ISO C definition */
426#define lua_stdin_is_tty() 1 /* assume stdin is a tty */
427
428#endif /* } */
429
430#endif /* } */
431
432
433/*
434** lua_readline defines how to show a prompt and then read a line from
435** the standard input.
436** lua_saveline defines how to "save" a read line in a "history".
437** lua_freeline defines how to free a line read by lua_readline.
438*/
439#if !defined(lua_readline) /* { */
440
441#if defined(LUA_USE_READLINE) /* { */
442
443#include <readline/readline.h>
444#include <readline/history.h>
445#define lua_initreadline(L) ((void)L, rl_readline_name="lua")
446#define lua_readline(L,b,p) ((void)L, ((b)=readline(p)) != NULL)
447#define lua_saveline(L,line) ((void)L, add_history(line))
448#define lua_freeline(L,b) ((void)L, free(b))
449
450#else /* }{ */
451
452#define lua_initreadline(L) ((void)L)
453#define lua_readline(L,b,p) \
454 ((void)L, fputs(p, stdout), fflush(stdout), /* show prompt */ \
455 fgets(b, LUA_MAXINPUT, stdin) != NULL) /* get line */
456#define lua_saveline(L,line) { (void)L; (void)line; }
457#define lua_freeline(L,b) { (void)L; (void)b; }
458
459#endif /* } */
460
461#endif /* } */
462
463
464/*
465** Return the string to be used as a prompt by the interpreter. Leave
466** the string (or nil, if using the default value) on the stack, to keep
467** it anchored.
468*/
469static const char *get_prompt (lua_State *L, int firstline) {
470 if (lua_getglobal(L, firstline ? "_PROMPT" : "_PROMPT2") == LUA_TNIL)
471 return (firstline ? LUA_PROMPT : LUA_PROMPT2); /* use the default */
472 else { /* apply 'tostring' over the value */
473 const char *p = luaL_tolstring(L, -1, NULL);
474 lua_remove(L, -2); /* remove original value */
475 return p;
476 }
477}
478
479/* mark in error messages for incomplete statements */
480#define EOFMARK "<eof>"
481#define marklen (sizeof(EOFMARK)/sizeof(char) - 1)
482
483
484/*
485** Check whether 'status' signals a syntax error and the error
486** message at the top of the stack ends with the above mark for
487** incomplete statements.
488*/
489static int incomplete (lua_State *L, int status) {
490 if (status == LUA_ERRSYNTAX) {
491 size_t lmsg;
492 const char *msg = lua_tolstring(L, -1, &lmsg);
493 if (lmsg >= marklen && strcmp(msg + lmsg - marklen, EOFMARK) == 0) {
494 lua_pop(L, 1);
495 return 1;
496 }
497 }
498 return 0; /* else... */
499}
500
501
502/*
503** Prompt the user, read a line, and push it into the Lua stack.
504*/
505static int pushline (lua_State *L, int firstline) {
506 char buffer[LUA_MAXINPUT];
507 char *b = buffer;
508 size_t l;
509 const char *prmt = get_prompt(L, firstline);
510 int readstatus = lua_readline(L, b, prmt);
511 if (readstatus == 0)
512 return 0; /* no input (prompt will be popped by caller) */
513 lua_pop(L, 1); /* remove prompt */
514 l = strlen(b);
515 if (l > 0 && b[l-1] == '\n') /* line ends with newline? */
516 b[--l] = '\0'; /* remove it */
517 if (firstline && b[0] == '=') /* for compatibility with 5.2, ... */
518 lua_pushfstring(L, "return %s", b + 1); /* change '=' to 'return' */
519 else
520 lua_pushlstring(L, b, l);
521 lua_freeline(L, b);
522 return 1;
523}
524
525
526/*
527** Try to compile line on the stack as 'return <line>;'; on return, stack
528** has either compiled chunk or original line (if compilation failed).
529*/
530static int addreturn (lua_State *L) {
531 const char *line = lua_tostring(L, -1); /* original line */
532 const char *retline = lua_pushfstring(L, "return %s;", line);
533 int status = luaL_loadbuffer(L, retline, strlen(retline), "=stdin");
534 if (status == LUA_OK) {
535 lua_remove(L, -2); /* remove modified line */
536 if (line[0] != '\0') /* non empty? */
537 lua_saveline(L, line); /* keep history */
538 }
539 else
540 lua_pop(L, 2); /* pop result from 'luaL_loadbuffer' and modified line */
541 return status;
542}
543
544
545/*
546** Read multiple lines until a complete Lua statement
547*/
548static int multiline (lua_State *L) {
549 for (;;) { /* repeat until gets a complete statement */
550 size_t len;
551 const char *line = lua_tolstring(L, 1, &len); /* get what it has */
552 int status = luaL_loadbuffer(L, line, len, "=stdin"); /* try it */
553 if (!incomplete(L, status) || !pushline(L, 0)) {
554 lua_saveline(L, line); /* keep history */
555 return status; /* cannot or should not try to add continuation line */
556 }
557 lua_pushliteral(L, "\n"); /* add newline... */
558 lua_insert(L, -2); /* ...between the two lines */
559 lua_concat(L, 3); /* join them */
560 }
561}
562
563
564/*
565** Read a line and try to load (compile) it first as an expression (by
566** adding "return " in front of it) and second as a statement. Return
567** the final status of load/call with the resulting function (if any)
568** in the top of the stack.
569*/
570static int loadline (lua_State *L) {
571 int status;
572 lua_settop(L, 0);
573 if (!pushline(L, 1))
574 return -1; /* no input */
575 if ((status = addreturn(L)) != LUA_OK) /* 'return ...' did not work? */
576 status = multiline(L); /* try as command, maybe with continuation lines */
577 lua_remove(L, 1); /* remove line from the stack */
578 lua_assert(lua_gettop(L) == 1);
579 return status;
580}
581
582
583/*
584** Prints (calling the Lua 'print' function) any values on the stack
585*/
586static void l_print (lua_State *L) {
587 int n = lua_gettop(L);
588 if (n > 0) { /* any result to be printed? */
589 luaL_checkstack(L, LUA_MINSTACK, "too many results to print");
590 lua_getglobal(L, "print");
591 lua_insert(L, 1);
592 if (lua_pcall(L, n, 0, 0) != LUA_OK)
593 l_message(progname, lua_pushfstring(L, "error calling 'print' (%s)",
594 lua_tostring(L, -1)));
595 }
596}
597
598
599/*
600** Do the REPL: repeatedly read (load) a line, evaluate (call) it, and
601** print any results.
602*/
603static void doREPL (lua_State *L) {
604 int status;
605 const char *oldprogname = progname;
606 progname = NULL; /* no 'progname' on errors in interactive mode */
607 lua_initreadline(L);
608 while ((status = loadline(L)) != -1) {
609 if (status == LUA_OK)
610 status = docall(L, 0, LUA_MULTRET);
611 if (status == LUA_OK) l_print(L);
612 else report(L, status);
613 }
614 lua_settop(L, 0); /* clear stack */
615 lua_writeline();
616 progname = oldprogname;
617}
618
619/* }================================================================== */
620
621
622/*
623** Main body of stand-alone interpreter (to be called in protected mode).
624** Reads the options and handles them all.
625*/
626static int pmain (lua_State *L) {
627 int argc = (int)lua_tointeger(L, 1);
628 char **argv = (char **)lua_touserdata(L, 2);
629 int script;
630 int args = collectargs(argv, &script);
631 int optlim = (script > 0) ? script : argc; /* first argv not an option */
632 luaL_checkversion(L); /* check that interpreter has correct version */
633 if (args == has_error) { /* bad arg? */
634 print_usage(argv[script]); /* 'script' has index of bad arg. */
635 return 0;
636 }
637 if (args & has_v) /* option '-v'? */
638 print_version();
639 if (args & has_E) { /* option '-E'? */
640 lua_pushboolean(L, 1); /* signal for libraries to ignore env. vars. */
641 lua_setfield(L, LUA_REGISTRYINDEX, "LUA_NOENV");
642 }
643 luaL_openlibs(L); /* open standard libraries */
644 createargtable(L, argv, argc, script); /* create table 'arg' */
645 lua_gc(L, LUA_GCRESTART); /* start GC... */
646 lua_gc(L, LUA_GCGEN, 0, 0); /* ...in generational mode */
647 if (!(args & has_E)) { /* no option '-E'? */
648 if (handle_luainit(L) != LUA_OK) /* run LUA_INIT */
649 return 0; /* error running LUA_INIT */
650 }
651 if (!runargs(L, argv, optlim)) /* execute arguments -e and -l */
652 return 0; /* something failed */
653 if (script > 0) { /* execute main script (if there is one) */
654 if (handle_script(L, argv + script) != LUA_OK)
655 return 0; /* interrupt in case of error */
656 }
657 if (args & has_i) /* -i option? */
658 doREPL(L); /* do read-eval-print loop */
659 else if (script < 1 && !(args & (has_e | has_v))) { /* no active option? */
660 if (lua_stdin_is_tty()) { /* running in interactive mode? */
661 print_version();
662 doREPL(L); /* do read-eval-print loop */
663 }
664 else dofile(L, NULL); /* executes stdin as a file */
665 }
666 lua_pushboolean(L, 1); /* signal no errors */
667 return 1;
668}
669
670
671int main (int argc, char **argv) {
672 int status, result;
673 lua_State *L = luaL_newstate(); /* create state */
674 if (L == NULL) {
675 l_message(argv[0], "cannot create state: not enough memory");
676 return EXIT_FAILURE;
677 }
678 lua_gc(L, LUA_GCSTOP); /* stop GC while building state */
679 lua_pushcfunction(L, &pmain); /* to call 'pmain' in protected mode */
680 lua_pushinteger(L, argc); /* 1st argument */
681 lua_pushlightuserdata(L, argv); /* 2nd argument */
682 status = lua_pcall(L, 2, 1, 0); /* do the call */
683 result = lua_toboolean(L, -1); /* get result */
684 report(L, status);
685 lua_close(L);
686 return (result && status == LUA_OK) ? EXIT_SUCCESS : EXIT_FAILURE;
687}
688