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