source: trunk/src/lua/lua.c @ 2541

Last change on this file since 2541 was 2541, checked in by sam, 10 years ago

lua: disable Lua signal handling: PS3, X360 or NaCl don't have signal().

File size: 13.8 KB
Line 
1/*
2** $Id: lua.c,v 1.205 2012/05/23 15:37:09 roberto Exp $
3** Lua stand-alone interpreter
4** See Copyright Notice in lua.h
5*/
6
7
8#if 0 // LOL BEGIN
9#include <signal.h>
10#endif // LOL END
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)
37#define LUA_INIT                "LUA_INIT"
38#endif
39
40#define LUA_INITVERSION  \
41        LUA_INIT "_" 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_USE_ISATTY)
49#include <unistd.h>
50#define lua_stdin_is_tty()      isatty(0)
51#elif defined(LUA_WIN)
52#include <io.h>
53#include <stdio.h>
54#define lua_stdin_is_tty()      _isatty(_fileno(stdin))
55#else
56#define lua_stdin_is_tty()      1  /* assume stdin is a tty */
57#endif
58
59
60/*
61** lua_readline defines how to show a prompt and then read a line from
62** the standard input.
63** lua_saveline defines how to "save" a read line in a "history".
64** lua_freeline defines how to free a line read by lua_readline.
65*/
66#if defined(LUA_USE_READLINE)
67
68#include <stdio.h>
69#include <readline/readline.h>
70#include <readline/history.h>
71#define lua_readline(L,b,p)     ((void)L, ((b)=readline(p)) != NULL)
72#define lua_saveline(L,idx) \
73        if (lua_rawlen(L,idx) > 0)  /* non-empty line? */ \
74          add_history(lua_tostring(L, idx));  /* add it to history */
75#define lua_freeline(L,b)       ((void)L, free(b))
76
77#elif !defined(lua_readline)
78
79#define lua_readline(L,b,p) \
80        ((void)L, fputs(p, stdout), fflush(stdout),  /* show prompt */ \
81        fgets(b, LUA_MAXINPUT, stdin) != NULL)  /* get line */
82#define lua_saveline(L,idx)     { (void)L; (void)idx; }
83#define lua_freeline(L,b)       { (void)L; (void)b; }
84
85#endif
86
87
88
89
90#if 0 // LOL BEGIN
91static lua_State *globalL = NULL;
92#endif // LOL END
93
94static const char *progname = LUA_PROGNAME;
95
96
97
98static void lstop (lua_State *L, lua_Debug *ar) {
99  (void)ar;  /* unused arg. */
100  lua_sethook(L, NULL, 0, 0);
101  luaL_error(L, "interrupted!");
102}
103
104
105#if 0 // LOL BEGIN
106static void laction (int i) {
107  signal(i, SIG_DFL); /* if another SIGINT happens before lstop,
108                              terminate process (default action) */
109  lua_sethook(globalL, lstop, LUA_MASKCALL | LUA_MASKRET | LUA_MASKCOUNT, 1);
110}
111#endif // LOL END
112
113
114static void print_usage (const char *badoption) {
115  luai_writestringerror("%s: ", progname);
116  if (badoption[1] == 'e' || badoption[1] == 'l')
117    luai_writestringerror("'%s' needs argument\n", badoption);
118  else
119    luai_writestringerror("unrecognized option '%s'\n", badoption);
120  luai_writestringerror(
121  "usage: %s [options] [script [args]]\n"
122  "Available options are:\n"
123  "  -e stat  execute string " LUA_QL("stat") "\n"
124  "  -i       enter interactive mode after executing " LUA_QL("script") "\n"
125  "  -l name  require library " LUA_QL("name") "\n"
126  "  -v       show version information\n"
127  "  -E       ignore environment variables\n"
128  "  --       stop handling options\n"
129  "  -        stop handling options and execute stdin\n"
130  ,
131  progname);
132}
133
134
135static void l_message (const char *pname, const char *msg) {
136  if (pname) luai_writestringerror("%s: ", pname);
137  luai_writestringerror("%s\n", msg);
138}
139
140
141static int report (lua_State *L, int status) {
142  if (status != LUA_OK && !lua_isnil(L, -1)) {
143    const char *msg = lua_tostring(L, -1);
144    if (msg == NULL) msg = "(error object is not a string)";
145    l_message(progname, msg);
146    lua_pop(L, 1);
147    /* force a complete garbage collection in case of errors */
148    lua_gc(L, LUA_GCCOLLECT, 0);
149  }
150  return status;
151}
152
153
154/* the next function is called unprotected, so it must avoid errors */
155static void finalreport (lua_State *L, int status) {
156  if (status != LUA_OK) {
157    const char *msg = (lua_type(L, -1) == LUA_TSTRING) ? lua_tostring(L, -1)
158                                                       : NULL;
159    if (msg == NULL) msg = "(error object is not a string)";
160    l_message(progname, msg);
161    lua_pop(L, 1);
162  }
163}
164
165
166static int traceback (lua_State *L) {
167  const char *msg = lua_tostring(L, 1);
168  if (msg)
169    luaL_traceback(L, L, msg, 1);
170  else if (!lua_isnoneornil(L, 1)) {  /* is there an error object? */
171    if (!luaL_callmeta(L, 1, "__tostring"))  /* try its 'tostring' metamethod */
172      lua_pushliteral(L, "(no error message)");
173  }
174  return 1;
175}
176
177
178static int docall (lua_State *L, int narg, int nres) {
179  int status;
180  int base = lua_gettop(L) - narg;  /* function index */
181  lua_pushcfunction(L, traceback);  /* push traceback function */
182  lua_insert(L, base);  /* put it under chunk and args */
183#if 0 // LOL BEGIN
184  globalL = L;  /* to be available to 'laction' */
185  signal(SIGINT, laction);
186#endif // LOL END
187  status = lua_pcall(L, narg, nres, base);
188#if 0 // LOL BEGIN
189  signal(SIGINT, SIG_DFL);
190#endif // LOL END
191  lua_remove(L, base);  /* remove traceback function */
192  return status;
193}
194
195
196static void print_version (void) {
197  luai_writestring(LUA_COPYRIGHT, strlen(LUA_COPYRIGHT));
198  luai_writeline();
199}
200
201
202static int getargs (lua_State *L, char **argv, int n) {
203  int narg;
204  int i;
205  int argc = 0;
206  while (argv[argc]) argc++;  /* count total number of arguments */
207  narg = argc - (n + 1);  /* number of arguments to the script */
208  luaL_checkstack(L, narg + 3, "too many arguments to script");
209  for (i=n+1; i < argc; i++)
210    lua_pushstring(L, argv[i]);
211  lua_createtable(L, narg, n + 1);
212  for (i=0; i < argc; i++) {
213    lua_pushstring(L, argv[i]);
214    lua_rawseti(L, -2, i - n);
215  }
216  return narg;
217}
218
219
220static int dofile (lua_State *L, const char *name) {
221  int status = luaL_loadfile(L, name);
222  if (status == LUA_OK) status = docall(L, 0, 0);
223  return report(L, status);
224}
225
226
227static int dostring (lua_State *L, const char *s, const char *name) {
228  int status = luaL_loadbuffer(L, s, strlen(s), name);
229  if (status == LUA_OK) status = docall(L, 0, 0);
230  return report(L, status);
231}
232
233
234static int dolibrary (lua_State *L, const char *name) {
235  int status;
236  lua_getglobal(L, "require");
237  lua_pushstring(L, name);
238  status = docall(L, 1, 1);  /* call 'require(name)' */
239  if (status == LUA_OK)
240    lua_setglobal(L, name);  /* global[name] = require return */
241  return report(L, status);
242}
243
244
245static const char *get_prompt (lua_State *L, int firstline) {
246  const char *p;
247  lua_getglobal(L, firstline ? "_PROMPT" : "_PROMPT2");
248  p = lua_tostring(L, -1);
249  if (p == NULL) p = (firstline ? LUA_PROMPT : LUA_PROMPT2);
250  lua_pop(L, 1);  /* remove global */
251  return p;
252}
253
254/* mark in error messages for incomplete statements */
255#define EOFMARK         "<eof>"
256#define marklen         (sizeof(EOFMARK)/sizeof(char) - 1)
257
258static int incomplete (lua_State *L, int status) {
259  if (status == LUA_ERRSYNTAX) {
260    size_t lmsg;
261    const char *msg = lua_tolstring(L, -1, &lmsg);
262    if (lmsg >= marklen && strcmp(msg + lmsg - marklen, EOFMARK) == 0) {
263      lua_pop(L, 1);
264      return 1;
265    }
266  }
267  return 0;  /* else... */
268}
269
270
271static int pushline (lua_State *L, int firstline) {
272  char buffer[LUA_MAXINPUT];
273  char *b = buffer;
274  size_t l;
275  const char *prmt = get_prompt(L, firstline);
276  if (lua_readline(L, b, prmt) == 0)
277    return 0;  /* no input */
278  l = strlen(b);
279  if (l > 0 && b[l-1] == '\n')  /* line ends with newline? */
280    b[l-1] = '\0';  /* remove it */
281  if (firstline && b[0] == '=')  /* first line starts with `=' ? */
282    lua_pushfstring(L, "return %s", b+1);  /* change it to `return' */
283  else
284    lua_pushstring(L, b);
285  lua_freeline(L, b);
286  return 1;
287}
288
289
290static int loadline (lua_State *L) {
291  int status;
292  lua_settop(L, 0);
293  if (!pushline(L, 1))
294    return -1;  /* no input */
295  for (;;) {  /* repeat until gets a complete line */
296    size_t l;
297    const char *line = lua_tolstring(L, 1, &l);
298    status = luaL_loadbuffer(L, line, l, "=stdin");
299    if (!incomplete(L, status)) break;  /* cannot try to add lines? */
300    if (!pushline(L, 0))  /* no more input? */
301      return -1;
302    lua_pushliteral(L, "\n");  /* add a new line... */
303    lua_insert(L, -2);  /* ...between the two lines */
304    lua_concat(L, 3);  /* join them */
305  }
306  lua_saveline(L, 1);
307  lua_remove(L, 1);  /* remove line */
308  return status;
309}
310
311
312static void dotty (lua_State *L) {
313  int status;
314  const char *oldprogname = progname;
315  progname = NULL;
316  while ((status = loadline(L)) != -1) {
317    if (status == LUA_OK) status = docall(L, 0, LUA_MULTRET);
318    report(L, status);
319    if (status == LUA_OK && lua_gettop(L) > 0) {  /* any result to print? */
320      luaL_checkstack(L, LUA_MINSTACK, "too many results to print");
321      lua_getglobal(L, "print");
322      lua_insert(L, 1);
323      if (lua_pcall(L, lua_gettop(L)-1, 0, 0) != LUA_OK)
324        l_message(progname, lua_pushfstring(L,
325                               "error calling " LUA_QL("print") " (%s)",
326                               lua_tostring(L, -1)));
327    }
328  }
329  lua_settop(L, 0);  /* clear stack */
330  luai_writeline();
331  progname = oldprogname;
332}
333
334
335static int handle_script (lua_State *L, char **argv, int n) {
336  int status;
337  const char *fname;
338  int narg = getargs(L, argv, n);  /* collect arguments */
339  lua_setglobal(L, "arg");
340  fname = argv[n];
341  if (strcmp(fname, "-") == 0 && strcmp(argv[n-1], "--") != 0)
342    fname = NULL;  /* stdin */
343  status = luaL_loadfile(L, fname);
344  lua_insert(L, -(narg+1));
345  if (status == LUA_OK)
346    status = docall(L, narg, LUA_MULTRET);
347  else
348    lua_pop(L, narg);
349  return report(L, status);
350}
351
352
353/* check that argument has no extra characters at the end */
354#define noextrachars(x)         {if ((x)[2] != '\0') return -1;}
355
356
357/* indices of various argument indicators in array args */
358#define has_i           0       /* -i */
359#define has_v           1       /* -v */
360#define has_e           2       /* -e */
361#define has_E           3       /* -E */
362
363#define num_has         4       /* number of 'has_*' */
364
365
366static int collectargs (char **argv, int *args) {
367  int i;
368  for (i = 1; argv[i] != NULL; i++) {
369    if (argv[i][0] != '-')  /* not an option? */
370        return i;
371    switch (argv[i][1]) {  /* option */
372      case '-':
373        noextrachars(argv[i]);
374        return (argv[i+1] != NULL ? i+1 : 0);
375      case '\0':
376        return i;
377      case 'E':
378        args[has_E] = 1;
379        break;
380      case 'i':
381        noextrachars(argv[i]);
382        args[has_i] = 1;  /* go through */
383      case 'v':
384        noextrachars(argv[i]);
385        args[has_v] = 1;
386        break;
387      case 'e':
388        args[has_e] = 1;  /* go through */
389      case 'l':  /* both options need an argument */
390        if (argv[i][2] == '\0') {  /* no concatenated argument? */
391          i++;  /* try next 'argv' */
392          if (argv[i] == NULL || argv[i][0] == '-')
393            return -(i - 1);  /* no next argument or it is another option */
394        }
395        break;
396      default:  /* invalid option; return its index... */
397        return -i;  /* ...as a negative value */
398    }
399  }
400  return 0;
401}
402
403
404static int runargs (lua_State *L, char **argv, int n) {
405  int i;
406  for (i = 1; i < n; i++) {
407    lua_assert(argv[i][0] == '-');
408    switch (argv[i][1]) {  /* option */
409      case 'e': {
410        const char *chunk = argv[i] + 2;
411        if (*chunk == '\0') chunk = argv[++i];
412        lua_assert(chunk != NULL);
413        if (dostring(L, chunk, "=(command line)") != LUA_OK)
414          return 0;
415        break;
416      }
417      case 'l': {
418        const char *filename = argv[i] + 2;
419        if (*filename == '\0') filename = argv[++i];
420        lua_assert(filename != NULL);
421        if (dolibrary(L, filename) != LUA_OK)
422          return 0;  /* stop if file fails */
423        break;
424      }
425      default: break;
426    }
427  }
428  return 1;
429}
430
431
432static int handle_luainit (lua_State *L) {
433  const char *name = "=" LUA_INITVERSION;
434  const char *init = getenv(name + 1);
435  if (init == NULL) {
436    name = "=" LUA_INIT;
437    init = getenv(name + 1);  /* try alternative name */
438  }
439  if (init == NULL) return LUA_OK;
440  else if (init[0] == '@')
441    return dofile(L, init+1);
442  else
443    return dostring(L, init, name);
444}
445
446
447static int pmain (lua_State *L) {
448  int argc = (int)lua_tointeger(L, 1);
449  char **argv = (char **)lua_touserdata(L, 2);
450  int script;
451  int args[num_has];
452  args[has_i] = args[has_v] = args[has_e] = args[has_E] = 0;
453  if (argv[0] && argv[0][0]) progname = argv[0];
454  script = collectargs(argv, args);
455  if (script < 0) {  /* invalid arg? */
456    print_usage(argv[-script]);
457    return 0;
458  }
459  if (args[has_v]) print_version();
460  if (args[has_E]) {  /* option '-E'? */
461    lua_pushboolean(L, 1);  /* signal for libraries to ignore env. vars. */
462    lua_setfield(L, LUA_REGISTRYINDEX, "LUA_NOENV");
463  }
464  /* open standard libraries */
465  luaL_checkversion(L);
466  lua_gc(L, LUA_GCSTOP, 0);  /* stop collector during initialization */
467  luaL_openlibs(L);  /* open libraries */
468  lua_gc(L, LUA_GCRESTART, 0);
469  if (!args[has_E] && handle_luainit(L) != LUA_OK)
470    return 0;  /* error running LUA_INIT */
471  /* execute arguments -e and -l */
472  if (!runargs(L, argv, (script > 0) ? script : argc)) return 0;
473  /* execute main script (if there is one) */
474  if (script && handle_script(L, argv, script) != LUA_OK) return 0;
475  if (args[has_i])  /* -i option? */
476    dotty(L);
477  else if (script == 0 && !args[has_e] && !args[has_v]) {  /* no arguments? */
478    if (lua_stdin_is_tty()) {
479      print_version();
480      dotty(L);
481    }
482    else dofile(L, NULL);  /* executes stdin as a file */
483  }
484  lua_pushboolean(L, 1);  /* signal no errors */
485  return 1;
486}
487
488
489int main (int argc, char **argv) {
490  int status, result;
491  lua_State *L = luaL_newstate();  /* create state */
492  if (L == NULL) {
493    l_message(argv[0], "cannot create state: not enough memory");
494    return EXIT_FAILURE;
495  }
496  /* call 'pmain' in protected mode */
497  lua_pushcfunction(L, &pmain);
498  lua_pushinteger(L, argc);  /* 1st argument */
499  lua_pushlightuserdata(L, argv); /* 2nd argument */
500  status = lua_pcall(L, 2, 1, 0);
501  result = lua_toboolean(L, -1);  /* get result */
502  finalreport(L, status);
503  lua_close(L);
504  return (result && status == LUA_OK) ? EXIT_SUCCESS : EXIT_FAILURE;
505}
506
Note: See TracBrowser for help on using the repository browser.