From Lua 5.2: Add -E command line option (ignore env vars).
[luajit-2.0.git] / src / luajit.c
blob22628aaf6a06459368bad3fdae37cb259d8ffd4b
1 /*
2 ** LuaJIT frontend. Runs commands, scripts, read-eval-print (REPL) etc.
3 ** Copyright (C) 2005-2012 Mike Pall. See Copyright Notice in luajit.h
4 **
5 ** Major portions taken verbatim or adapted from the Lua interpreter.
6 ** Copyright (C) 1994-2008 Lua.org, PUC-Rio. See Copyright Notice in lua.h
7 */
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <string.h>
13 #define luajit_c
15 #include "lua.h"
16 #include "lauxlib.h"
17 #include "lualib.h"
18 #include "luajit.h"
20 #include "lj_arch.h"
22 #if LJ_TARGET_POSIX
23 #include <unistd.h>
24 #define lua_stdin_is_tty() isatty(0)
25 #elif LJ_TARGET_WINDOWS
26 #include <io.h>
27 #ifdef __BORLANDC__
28 #define lua_stdin_is_tty() isatty(_fileno(stdin))
29 #else
30 #define lua_stdin_is_tty() _isatty(_fileno(stdin))
31 #endif
32 #else
33 #define lua_stdin_is_tty() 1
34 #endif
36 #if !LJ_TARGET_CONSOLE
37 #include <signal.h>
38 #endif
40 static lua_State *globalL = NULL;
41 static const char *progname = LUA_PROGNAME;
43 #if !LJ_TARGET_CONSOLE
44 static void lstop(lua_State *L, lua_Debug *ar)
46 (void)ar; /* unused arg. */
47 lua_sethook(L, NULL, 0, 0);
48 /* Avoid luaL_error -- a C hook doesn't add an extra frame. */
49 luaL_where(L, 0);
50 lua_pushfstring(L, "%sinterrupted!", lua_tostring(L, -1));
51 lua_error(L);
54 static void laction(int i)
56 signal(i, SIG_DFL); /* if another SIGINT happens before lstop,
57 terminate process (default action) */
58 lua_sethook(globalL, lstop, LUA_MASKCALL | LUA_MASKRET | LUA_MASKCOUNT, 1);
60 #endif
62 static void print_usage(void)
64 fprintf(stderr,
65 "usage: %s [options]... [script [args]...].\n"
66 "Available options are:\n"
67 " -e chunk Execute string " LUA_QL("chunk") ".\n"
68 " -l name Require library " LUA_QL("name") ".\n"
69 " -b ... Save or list bytecode.\n"
70 " -j cmd Perform LuaJIT control command.\n"
71 " -O[opt] Control LuaJIT optimizations.\n"
72 " -i Enter interactive mode after executing " LUA_QL("script") ".\n"
73 " -v Show version information.\n"
74 " -E Ignore environment variables.\n"
75 " -- Stop handling options.\n"
76 " - Execute stdin and stop handling options.\n"
78 progname);
79 fflush(stderr);
82 static void l_message(const char *pname, const char *msg)
84 if (pname) fprintf(stderr, "%s: ", pname);
85 fprintf(stderr, "%s\n", msg);
86 fflush(stderr);
89 static int report(lua_State *L, int status)
91 if (status && !lua_isnil(L, -1)) {
92 const char *msg = lua_tostring(L, -1);
93 if (msg == NULL) msg = "(error object is not a string)";
94 l_message(progname, msg);
95 lua_pop(L, 1);
97 return status;
100 static int traceback(lua_State *L)
102 if (!lua_isstring(L, 1)) { /* Non-string error object? Try metamethod. */
103 if (lua_isnoneornil(L, 1) ||
104 !luaL_callmeta(L, 1, "__tostring") ||
105 !lua_isstring(L, -1))
106 return 1; /* Return non-string error object. */
107 lua_remove(L, 1); /* Replace object by result of __tostring metamethod. */
109 lua_getfield(L, LUA_GLOBALSINDEX, "debug");
110 if (!lua_istable(L, -1)) {
111 lua_pop(L, 1);
112 return 1;
114 lua_getfield(L, -1, "traceback");
115 if (!lua_isfunction(L, -1)) {
116 lua_pop(L, 2);
117 return 1;
119 lua_pushvalue(L, 1); /* Push error message. */
120 lua_pushinteger(L, 2); /* Skip this function and debug.traceback(). */
121 lua_call(L, 2, 1); /* Call debug.traceback(). */
122 return 1;
125 static int docall(lua_State *L, int narg, int clear)
127 int status;
128 int base = lua_gettop(L) - narg; /* function index */
129 lua_pushcfunction(L, traceback); /* push traceback function */
130 lua_insert(L, base); /* put it under chunk and args */
131 #if !LJ_TARGET_CONSOLE
132 signal(SIGINT, laction);
133 #endif
134 status = lua_pcall(L, narg, (clear ? 0 : LUA_MULTRET), base);
135 #if !LJ_TARGET_CONSOLE
136 signal(SIGINT, SIG_DFL);
137 #endif
138 lua_remove(L, base); /* remove traceback function */
139 /* force a complete garbage collection in case of errors */
140 if (status != 0) lua_gc(L, LUA_GCCOLLECT, 0);
141 return status;
144 static void print_version(void)
146 fputs(LUAJIT_VERSION " -- " LUAJIT_COPYRIGHT ". " LUAJIT_URL "\n", stdout);
149 static void print_jit_status(lua_State *L)
151 int n;
152 const char *s;
153 lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
154 lua_getfield(L, -1, "jit"); /* Get jit.* module table. */
155 lua_remove(L, -2);
156 lua_getfield(L, -1, "status");
157 lua_remove(L, -2);
158 n = lua_gettop(L);
159 lua_call(L, 0, LUA_MULTRET);
160 fputs(lua_toboolean(L, n) ? "JIT: ON" : "JIT: OFF", stdout);
161 for (n++; (s = lua_tostring(L, n)); n++) {
162 putc(' ', stdout);
163 fputs(s, stdout);
165 putc('\n', stdout);
168 static int getargs(lua_State *L, char **argv, int n)
170 int narg;
171 int i;
172 int argc = 0;
173 while (argv[argc]) argc++; /* count total number of arguments */
174 narg = argc - (n + 1); /* number of arguments to the script */
175 luaL_checkstack(L, narg + 3, "too many arguments to script");
176 for (i = n+1; i < argc; i++)
177 lua_pushstring(L, argv[i]);
178 lua_createtable(L, narg, n + 1);
179 for (i = 0; i < argc; i++) {
180 lua_pushstring(L, argv[i]);
181 lua_rawseti(L, -2, i - n);
183 return narg;
186 static int dofile(lua_State *L, const char *name)
188 int status = luaL_loadfile(L, name) || docall(L, 0, 1);
189 return report(L, status);
192 static int dostring(lua_State *L, const char *s, const char *name)
194 int status = luaL_loadbuffer(L, s, strlen(s), name) || docall(L, 0, 1);
195 return report(L, status);
198 static int dolibrary(lua_State *L, const char *name)
200 lua_getglobal(L, "require");
201 lua_pushstring(L, name);
202 return report(L, docall(L, 1, 1));
205 static void write_prompt(lua_State *L, int firstline)
207 const char *p;
208 lua_getfield(L, LUA_GLOBALSINDEX, firstline ? "_PROMPT" : "_PROMPT2");
209 p = lua_tostring(L, -1);
210 if (p == NULL) p = firstline ? LUA_PROMPT : LUA_PROMPT2;
211 fputs(p, stdout);
212 fflush(stdout);
213 lua_pop(L, 1); /* remove global */
216 static int incomplete(lua_State *L, int status)
218 if (status == LUA_ERRSYNTAX) {
219 size_t lmsg;
220 const char *msg = lua_tolstring(L, -1, &lmsg);
221 const char *tp = msg + lmsg - (sizeof(LUA_QL("<eof>")) - 1);
222 if (strstr(msg, LUA_QL("<eof>")) == tp) {
223 lua_pop(L, 1);
224 return 1;
227 return 0; /* else... */
230 static int pushline(lua_State *L, int firstline)
232 char buf[LUA_MAXINPUT];
233 write_prompt(L, firstline);
234 if (fgets(buf, LUA_MAXINPUT, stdin)) {
235 size_t len = strlen(buf);
236 if (len > 0 && buf[len-1] == '\n')
237 buf[len-1] = '\0';
238 if (firstline && buf[0] == '=')
239 lua_pushfstring(L, "return %s", buf+1);
240 else
241 lua_pushstring(L, buf);
242 return 1;
244 return 0;
247 static int loadline(lua_State *L)
249 int status;
250 lua_settop(L, 0);
251 if (!pushline(L, 1))
252 return -1; /* no input */
253 for (;;) { /* repeat until gets a complete line */
254 status = luaL_loadbuffer(L, lua_tostring(L, 1), lua_strlen(L, 1), "=stdin");
255 if (!incomplete(L, status)) break; /* cannot try to add lines? */
256 if (!pushline(L, 0)) /* no more input? */
257 return -1;
258 lua_pushliteral(L, "\n"); /* add a new line... */
259 lua_insert(L, -2); /* ...between the two lines */
260 lua_concat(L, 3); /* join them */
262 lua_remove(L, 1); /* remove line */
263 return status;
266 static void dotty(lua_State *L)
268 int status;
269 const char *oldprogname = progname;
270 progname = NULL;
271 while ((status = loadline(L)) != -1) {
272 if (status == 0) status = docall(L, 0, 0);
273 report(L, status);
274 if (status == 0 && lua_gettop(L) > 0) { /* any result to print? */
275 lua_getglobal(L, "print");
276 lua_insert(L, 1);
277 if (lua_pcall(L, lua_gettop(L)-1, 0, 0) != 0)
278 l_message(progname,
279 lua_pushfstring(L, "error calling " LUA_QL("print") " (%s)",
280 lua_tostring(L, -1)));
283 lua_settop(L, 0); /* clear stack */
284 fputs("\n", stdout);
285 fflush(stdout);
286 progname = oldprogname;
289 static int handle_script(lua_State *L, char **argv, int n)
291 int status;
292 const char *fname;
293 int narg = getargs(L, argv, n); /* collect arguments */
294 lua_setglobal(L, "arg");
295 fname = argv[n];
296 if (strcmp(fname, "-") == 0 && strcmp(argv[n-1], "--") != 0)
297 fname = NULL; /* stdin */
298 status = luaL_loadfile(L, fname);
299 lua_insert(L, -(narg+1));
300 if (status == 0)
301 status = docall(L, narg, 0);
302 else
303 lua_pop(L, narg);
304 return report(L, status);
307 /* Load add-on module. */
308 static int loadjitmodule(lua_State *L)
310 lua_getglobal(L, "require");
311 lua_pushliteral(L, "jit.");
312 lua_pushvalue(L, -3);
313 lua_concat(L, 2);
314 if (lua_pcall(L, 1, 1, 0)) {
315 const char *msg = lua_tostring(L, -1);
316 if (msg && !strncmp(msg, "module ", 7)) {
317 err:
318 l_message(progname,
319 "unknown luaJIT command or jit.* modules not installed");
320 return 1;
321 } else {
322 return report(L, 1);
325 lua_getfield(L, -1, "start");
326 if (lua_isnil(L, -1)) goto err;
327 lua_remove(L, -2); /* Drop module table. */
328 return 0;
331 /* Run command with options. */
332 static int runcmdopt(lua_State *L, const char *opt)
334 int narg = 0;
335 if (opt && *opt) {
336 for (;;) { /* Split arguments. */
337 const char *p = strchr(opt, ',');
338 narg++;
339 if (!p) break;
340 if (p == opt)
341 lua_pushnil(L);
342 else
343 lua_pushlstring(L, opt, (size_t)(p - opt));
344 opt = p + 1;
346 if (*opt)
347 lua_pushstring(L, opt);
348 else
349 lua_pushnil(L);
351 return report(L, lua_pcall(L, narg, 0, 0));
354 /* JIT engine control command: try jit library first or load add-on module. */
355 static int dojitcmd(lua_State *L, const char *cmd)
357 const char *opt = strchr(cmd, '=');
358 lua_pushlstring(L, cmd, opt ? (size_t)(opt - cmd) : strlen(cmd));
359 lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
360 lua_getfield(L, -1, "jit"); /* Get jit.* module table. */
361 lua_remove(L, -2);
362 lua_pushvalue(L, -2);
363 lua_gettable(L, -2); /* Lookup library function. */
364 if (!lua_isfunction(L, -1)) {
365 lua_pop(L, 2); /* Drop non-function and jit.* table, keep module name. */
366 if (loadjitmodule(L))
367 return 1;
368 } else {
369 lua_remove(L, -2); /* Drop jit.* table. */
371 lua_remove(L, -2); /* Drop module name. */
372 return runcmdopt(L, opt ? opt+1 : opt);
375 /* Optimization flags. */
376 static int dojitopt(lua_State *L, const char *opt)
378 lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
379 lua_getfield(L, -1, "jit.opt"); /* Get jit.opt.* module table. */
380 lua_remove(L, -2);
381 lua_getfield(L, -1, "start");
382 lua_remove(L, -2);
383 return runcmdopt(L, opt);
386 /* Save or list bytecode. */
387 static int dobytecode(lua_State *L, char **argv)
389 int narg = 0;
390 lua_pushliteral(L, "bcsave");
391 if (loadjitmodule(L))
392 return 1;
393 if (argv[0][2]) {
394 narg++;
395 argv[0][1] = '-';
396 lua_pushstring(L, argv[0]+1);
398 for (argv++; *argv != NULL; narg++, argv++)
399 lua_pushstring(L, *argv);
400 return report(L, lua_pcall(L, narg, 0, 0));
403 /* check that argument has no extra characters at the end */
404 #define notail(x) {if ((x)[2] != '\0') return -1;}
406 #define FLAGS_INTERACTIVE 1
407 #define FLAGS_VERSION 2
408 #define FLAGS_EXEC 4
409 #define FLAGS_OPTION 8
410 #define FLAGS_NOENV 16
412 static int collectargs(char **argv, int *flags)
414 int i;
415 for (i = 1; argv[i] != NULL; i++) {
416 if (argv[i][0] != '-') /* Not an option? */
417 return i;
418 switch (argv[i][1]) { /* Check option. */
419 case '-':
420 notail(argv[i]);
421 return (argv[i+1] != NULL ? i+1 : 0);
422 case '\0':
423 return i;
424 case 'i':
425 notail(argv[i]);
426 *flags |= FLAGS_INTERACTIVE;
427 /* fallthrough */
428 case 'v':
429 notail(argv[i]);
430 *flags |= FLAGS_VERSION;
431 break;
432 case 'e':
433 *flags |= FLAGS_EXEC;
434 case 'j': /* LuaJIT extension */
435 case 'l':
436 *flags |= FLAGS_OPTION;
437 if (argv[i][2] == '\0') {
438 i++;
439 if (argv[i] == NULL) return -1;
441 break;
442 case 'O': break; /* LuaJIT extension */
443 case 'b': /* LuaJIT extension */
444 if (*flags) return -1;
445 *flags |= FLAGS_EXEC;
446 return 0;
447 case 'E':
448 *flags |= FLAGS_NOENV;
449 break;
450 default: return -1; /* invalid option */
453 return 0;
456 static int runargs(lua_State *L, char **argv, int n)
458 int i;
459 for (i = 1; i < n; i++) {
460 if (argv[i] == NULL) continue;
461 lua_assert(argv[i][0] == '-');
462 switch (argv[i][1]) { /* option */
463 case 'e': {
464 const char *chunk = argv[i] + 2;
465 if (*chunk == '\0') chunk = argv[++i];
466 lua_assert(chunk != NULL);
467 if (dostring(L, chunk, "=(command line)") != 0)
468 return 1;
469 break;
471 case 'l': {
472 const char *filename = argv[i] + 2;
473 if (*filename == '\0') filename = argv[++i];
474 lua_assert(filename != NULL);
475 if (dolibrary(L, filename))
476 return 1; /* stop if file fails */
477 break;
479 case 'j': { /* LuaJIT extension */
480 const char *cmd = argv[i] + 2;
481 if (*cmd == '\0') cmd = argv[++i];
482 lua_assert(cmd != NULL);
483 if (dojitcmd(L, cmd))
484 return 1;
485 break;
487 case 'O': /* LuaJIT extension */
488 if (dojitopt(L, argv[i] + 2))
489 return 1;
490 break;
491 case 'b': /* LuaJIT extension */
492 return dobytecode(L, argv+i);
493 default: break;
496 return 0;
499 static int handle_luainit(lua_State *L)
501 #if LJ_TARGET_CONSOLE
502 const char *init = NULL;
503 #else
504 const char *init = getenv(LUA_INIT);
505 #endif
506 if (init == NULL)
507 return 0; /* status OK */
508 else if (init[0] == '@')
509 return dofile(L, init+1);
510 else
511 return dostring(L, init, "=" LUA_INIT);
514 struct Smain {
515 char **argv;
516 int argc;
517 int status;
520 static int pmain(lua_State *L)
522 struct Smain *s = (struct Smain *)lua_touserdata(L, 1);
523 char **argv = s->argv;
524 int script;
525 int flags = 0;
526 globalL = L;
527 if (argv[0] && argv[0][0]) progname = argv[0];
528 LUAJIT_VERSION_SYM(); /* linker-enforced version check */
529 script = collectargs(argv, &flags);
530 if (script < 0) { /* invalid args? */
531 print_usage();
532 s->status = 1;
533 return 0;
535 if ((flags & FLAGS_NOENV)) {
536 lua_pushboolean(L, 1);
537 lua_setfield(L, LUA_REGISTRYINDEX, "LUA_NOENV");
539 lua_gc(L, LUA_GCSTOP, 0); /* stop collector during initialization */
540 luaL_openlibs(L); /* open libraries */
541 lua_gc(L, LUA_GCRESTART, -1);
542 if (!(flags & FLAGS_NOENV)) {
543 s->status = handle_luainit(L);
544 if (s->status != 0) return 0;
546 if ((flags & FLAGS_VERSION)) print_version();
547 s->status = runargs(L, argv, (script > 0) ? script : s->argc);
548 if (s->status != 0) return 0;
549 if (script) {
550 s->status = handle_script(L, argv, script);
551 if (s->status != 0) return 0;
553 if ((flags & FLAGS_INTERACTIVE)) {
554 print_jit_status(L);
555 dotty(L);
556 } else if (script == 0 && !(flags & (FLAGS_EXEC|FLAGS_VERSION))) {
557 if (lua_stdin_is_tty()) {
558 print_version();
559 print_jit_status(L);
560 dotty(L);
561 } else {
562 dofile(L, NULL); /* executes stdin as a file */
565 return 0;
568 int main(int argc, char **argv)
570 int status;
571 struct Smain s;
572 lua_State *L = lua_open(); /* create state */
573 if (L == NULL) {
574 l_message(argv[0], "cannot create state: not enough memory");
575 return EXIT_FAILURE;
577 s.argc = argc;
578 s.argv = argv;
579 status = lua_cpcall(L, pmain, &s);
580 report(L, status);
581 lua_close(L);
582 return (status || s.status) ? EXIT_FAILURE : EXIT_SUCCESS;