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