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