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