Fix typo.
[luajit-2.0.git] / src / luajit.c
blobecf4ef26d87b0cf0e02d99dcd71f57c0d6257684
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 <signal.h>
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <string.h>
14 #define luajit_c
16 #include "lua.h"
17 #include "lauxlib.h"
18 #include "lualib.h"
19 #include "luajit.h"
21 #include "lj_arch.h"
23 #if LJ_TARGET_POSIX
24 #include <unistd.h>
25 #define lua_stdin_is_tty() isatty(0)
26 #elif LJ_TARGET_WINDOWS
27 #include <io.h>
28 #ifdef __BORLANDC__
29 #define lua_stdin_is_tty() isatty(_fileno(stdin))
30 #else
31 #define lua_stdin_is_tty() _isatty(_fileno(stdin))
32 #endif
33 #else
34 #define lua_stdin_is_tty() 1
35 #endif
37 static lua_State *globalL = NULL;
38 static const char *progname = LUA_PROGNAME;
40 static void lstop(lua_State *L, lua_Debug *ar)
42 (void)ar; /* unused arg. */
43 lua_sethook(L, NULL, 0, 0);
44 /* Avoid luaL_error -- a C hook doesn't add an extra frame. */
45 luaL_where(L, 0);
46 lua_pushfstring(L, "%sinterrupted!", lua_tostring(L, -1));
47 lua_error(L);
50 static void laction(int i)
52 signal(i, SIG_DFL); /* if another SIGINT happens before lstop,
53 terminate process (default action) */
54 lua_sethook(globalL, lstop, LUA_MASKCALL | LUA_MASKRET | LUA_MASKCOUNT, 1);
57 static void print_usage(void)
59 fprintf(stderr,
60 "usage: %s [options]... [script [args]...].\n"
61 "Available options are:\n"
62 " -e chunk Execute string " LUA_QL("chunk") ".\n"
63 " -l name Require library " LUA_QL("name") ".\n"
64 " -b ... Save or list bytecode.\n"
65 " -j cmd Perform LuaJIT control command.\n"
66 " -O[opt] Control LuaJIT optimizations.\n"
67 " -i Enter interactive mode after executing " LUA_QL("script") ".\n"
68 " -v Show version information.\n"
69 " -- Stop handling options.\n"
70 " - Execute stdin and stop handling options.\n"
72 progname);
73 fflush(stderr);
76 static void l_message(const char *pname, const char *msg)
78 if (pname) fprintf(stderr, "%s: ", pname);
79 fprintf(stderr, "%s\n", msg);
80 fflush(stderr);
83 static int report(lua_State *L, int status)
85 if (status && !lua_isnil(L, -1)) {
86 const char *msg = lua_tostring(L, -1);
87 if (msg == NULL) msg = "(error object is not a string)";
88 l_message(progname, msg);
89 lua_pop(L, 1);
91 return status;
94 static int traceback(lua_State *L)
96 if (!lua_isstring(L, 1)) { /* Non-string error object? Try metamethod. */
97 if (lua_isnoneornil(L, 1) ||
98 !luaL_callmeta(L, 1, "__tostring") ||
99 !lua_isstring(L, -1))
100 return 1; /* Return non-string error object. */
101 lua_remove(L, 1); /* Replace object by result of __tostring metamethod. */
103 lua_getfield(L, LUA_GLOBALSINDEX, "debug");
104 if (!lua_istable(L, -1)) {
105 lua_pop(L, 1);
106 return 1;
108 lua_getfield(L, -1, "traceback");
109 if (!lua_isfunction(L, -1)) {
110 lua_pop(L, 2);
111 return 1;
113 lua_pushvalue(L, 1); /* Push error message. */
114 lua_pushinteger(L, 2); /* Skip this function and debug.traceback(). */
115 lua_call(L, 2, 1); /* Call debug.traceback(). */
116 return 1;
119 static int docall(lua_State *L, int narg, int clear)
121 int status;
122 int base = lua_gettop(L) - narg; /* function index */
123 lua_pushcfunction(L, traceback); /* push traceback function */
124 lua_insert(L, base); /* put it under chunk and args */
125 signal(SIGINT, laction);
126 status = lua_pcall(L, narg, (clear ? 0 : LUA_MULTRET), base);
127 signal(SIGINT, SIG_DFL);
128 lua_remove(L, base); /* remove traceback function */
129 /* force a complete garbage collection in case of errors */
130 if (status != 0) lua_gc(L, LUA_GCCOLLECT, 0);
131 return status;
134 static void print_version(void)
136 fprintf(stderr,
137 LUAJIT_VERSION " -- " LUAJIT_COPYRIGHT ". " LUAJIT_URL "\n");
140 static void print_jit_status(lua_State *L)
142 int n;
143 const char *s;
144 lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
145 lua_getfield(L, -1, "jit"); /* Get jit.* module table. */
146 lua_remove(L, -2);
147 lua_getfield(L, -1, "status");
148 lua_remove(L, -2);
149 n = lua_gettop(L);
150 lua_call(L, 0, LUA_MULTRET);
151 fputs(lua_toboolean(L, n) ? "JIT: ON" : "JIT: OFF", stderr);
152 for (n++; (s = lua_tostring(L, n)); n++)
153 fprintf(stderr, " %s", s);
154 fputs("\n", stderr);
157 static int getargs(lua_State *L, char **argv, int n)
159 int narg;
160 int i;
161 int argc = 0;
162 while (argv[argc]) argc++; /* count total number of arguments */
163 narg = argc - (n + 1); /* number of arguments to the script */
164 luaL_checkstack(L, narg + 3, "too many arguments to script");
165 for (i = n+1; i < argc; i++)
166 lua_pushstring(L, argv[i]);
167 lua_createtable(L, narg, n + 1);
168 for (i = 0; i < argc; i++) {
169 lua_pushstring(L, argv[i]);
170 lua_rawseti(L, -2, i - n);
172 return narg;
175 static int dofile(lua_State *L, const char *name)
177 int status = luaL_loadfile(L, name) || docall(L, 0, 1);
178 return report(L, status);
181 static int dostring(lua_State *L, const char *s, const char *name)
183 int status = luaL_loadbuffer(L, s, strlen(s), name) || docall(L, 0, 1);
184 return report(L, status);
187 static int dolibrary(lua_State *L, const char *name)
189 lua_getglobal(L, "require");
190 lua_pushstring(L, name);
191 return report(L, docall(L, 1, 1));
194 static void write_prompt(lua_State *L, int firstline)
196 const char *p;
197 lua_getfield(L, LUA_GLOBALSINDEX, firstline ? "_PROMPT" : "_PROMPT2");
198 p = lua_tostring(L, -1);
199 if (p == NULL) p = firstline ? LUA_PROMPT : LUA_PROMPT2;
200 fputs(p, stdout);
201 fflush(stdout);
202 lua_pop(L, 1); /* remove global */
205 static int incomplete(lua_State *L, int status)
207 if (status == LUA_ERRSYNTAX) {
208 size_t lmsg;
209 const char *msg = lua_tolstring(L, -1, &lmsg);
210 const char *tp = msg + lmsg - (sizeof(LUA_QL("<eof>")) - 1);
211 if (strstr(msg, LUA_QL("<eof>")) == tp) {
212 lua_pop(L, 1);
213 return 1;
216 return 0; /* else... */
219 static int pushline(lua_State *L, int firstline)
221 char buf[LUA_MAXINPUT];
222 write_prompt(L, firstline);
223 if (fgets(buf, LUA_MAXINPUT, stdin)) {
224 size_t len = strlen(buf);
225 if (len > 0 && buf[len-1] == '\n')
226 buf[len-1] = '\0';
227 if (firstline && buf[0] == '=')
228 lua_pushfstring(L, "return %s", buf+1);
229 else
230 lua_pushstring(L, buf);
231 return 1;
233 return 0;
236 static int loadline(lua_State *L)
238 int status;
239 lua_settop(L, 0);
240 if (!pushline(L, 1))
241 return -1; /* no input */
242 for (;;) { /* repeat until gets a complete line */
243 status = luaL_loadbuffer(L, lua_tostring(L, 1), lua_strlen(L, 1), "=stdin");
244 if (!incomplete(L, status)) break; /* cannot try to add lines? */
245 if (!pushline(L, 0)) /* no more input? */
246 return -1;
247 lua_pushliteral(L, "\n"); /* add a new line... */
248 lua_insert(L, -2); /* ...between the two lines */
249 lua_concat(L, 3); /* join them */
251 lua_remove(L, 1); /* remove line */
252 return status;
255 static void dotty(lua_State *L)
257 int status;
258 const char *oldprogname = progname;
259 progname = NULL;
260 while ((status = loadline(L)) != -1) {
261 if (status == 0) status = docall(L, 0, 0);
262 report(L, status);
263 if (status == 0 && lua_gettop(L) > 0) { /* any result to print? */
264 lua_getglobal(L, "print");
265 lua_insert(L, 1);
266 if (lua_pcall(L, lua_gettop(L)-1, 0, 0) != 0)
267 l_message(progname,
268 lua_pushfstring(L, "error calling " LUA_QL("print") " (%s)",
269 lua_tostring(L, -1)));
272 lua_settop(L, 0); /* clear stack */
273 fputs("\n", stdout);
274 fflush(stdout);
275 progname = oldprogname;
278 static int handle_script(lua_State *L, char **argv, int n)
280 int status;
281 const char *fname;
282 int narg = getargs(L, argv, n); /* collect arguments */
283 lua_setglobal(L, "arg");
284 fname = argv[n];
285 if (strcmp(fname, "-") == 0 && strcmp(argv[n-1], "--") != 0)
286 fname = NULL; /* stdin */
287 status = luaL_loadfile(L, fname);
288 lua_insert(L, -(narg+1));
289 if (status == 0)
290 status = docall(L, narg, 0);
291 else
292 lua_pop(L, narg);
293 return report(L, status);
296 /* Load add-on module. */
297 static int loadjitmodule(lua_State *L)
299 lua_getglobal(L, "require");
300 lua_pushliteral(L, "jit.");
301 lua_pushvalue(L, -3);
302 lua_concat(L, 2);
303 if (lua_pcall(L, 1, 1, 0)) {
304 const char *msg = lua_tostring(L, -1);
305 if (msg && !strncmp(msg, "module ", 7)) {
306 err:
307 l_message(progname,
308 "unknown luaJIT command or jit.* modules not installed");
309 return 1;
310 } else {
311 return report(L, 1);
314 lua_getfield(L, -1, "start");
315 if (lua_isnil(L, -1)) goto err;
316 lua_remove(L, -2); /* Drop module table. */
317 return 0;
320 /* Run command with options. */
321 static int runcmdopt(lua_State *L, const char *opt)
323 int narg = 0;
324 if (opt && *opt) {
325 for (;;) { /* Split arguments. */
326 const char *p = strchr(opt, ',');
327 narg++;
328 if (!p) break;
329 if (p == opt)
330 lua_pushnil(L);
331 else
332 lua_pushlstring(L, opt, (size_t)(p - opt));
333 opt = p + 1;
335 if (*opt)
336 lua_pushstring(L, opt);
337 else
338 lua_pushnil(L);
340 return report(L, lua_pcall(L, narg, 0, 0));
343 /* JIT engine control command: try jit library first or load add-on module. */
344 static int dojitcmd(lua_State *L, const char *cmd)
346 const char *opt = strchr(cmd, '=');
347 lua_pushlstring(L, cmd, opt ? (size_t)(opt - cmd) : strlen(cmd));
348 lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
349 lua_getfield(L, -1, "jit"); /* Get jit.* module table. */
350 lua_remove(L, -2);
351 lua_pushvalue(L, -2);
352 lua_gettable(L, -2); /* Lookup library function. */
353 if (!lua_isfunction(L, -1)) {
354 lua_pop(L, 2); /* Drop non-function and jit.* table, keep module name. */
355 if (loadjitmodule(L))
356 return 1;
357 } else {
358 lua_remove(L, -2); /* Drop jit.* table. */
360 lua_remove(L, -2); /* Drop module name. */
361 return runcmdopt(L, opt ? opt+1 : opt);
364 /* Optimization flags. */
365 static int dojitopt(lua_State *L, const char *opt)
367 lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
368 lua_getfield(L, -1, "jit.opt"); /* Get jit.opt.* module table. */
369 lua_remove(L, -2);
370 lua_getfield(L, -1, "start");
371 lua_remove(L, -2);
372 return runcmdopt(L, opt);
375 /* Save or list bytecode. */
376 static int dobytecode(lua_State *L, char **argv)
378 int narg = 0;
379 lua_pushliteral(L, "bcsave");
380 if (loadjitmodule(L))
381 return 1;
382 if (argv[0][2]) {
383 narg++;
384 argv[0][1] = '-';
385 lua_pushstring(L, argv[0]+1);
387 for (argv++; *argv != NULL; narg++, argv++)
388 lua_pushstring(L, *argv);
389 return report(L, lua_pcall(L, narg, 0, 0));
392 /* check that argument has no extra characters at the end */
393 #define notail(x) {if ((x)[2] != '\0') return -1;}
395 #define FLAGS_INTERACTIVE 1
396 #define FLAGS_VERSION 2
397 #define FLAGS_EXEC 4
398 #define FLAGS_OPTION 8
400 static int collectargs(char **argv, int *flags)
402 int i;
403 for (i = 1; argv[i] != NULL; i++) {
404 if (argv[i][0] != '-') /* Not an option? */
405 return i;
406 switch (argv[i][1]) { /* Check option. */
407 case '-':
408 notail(argv[i]);
409 return (argv[i+1] != NULL ? i+1 : 0);
410 case '\0':
411 return i;
412 case 'i':
413 notail(argv[i]);
414 *flags |= FLAGS_INTERACTIVE;
415 /* fallthrough */
416 case 'v':
417 notail(argv[i]);
418 *flags |= FLAGS_VERSION;
419 break;
420 case 'e':
421 *flags |= FLAGS_EXEC;
422 case 'j': /* LuaJIT extension */
423 case 'l':
424 *flags |= FLAGS_OPTION;
425 if (argv[i][2] == '\0') {
426 i++;
427 if (argv[i] == NULL) return -1;
429 break;
430 case 'O': break; /* LuaJIT extension */
431 case 'b': /* LuaJIT extension */
432 if (*flags) return -1;
433 *flags |= FLAGS_EXEC;
434 return 0;
435 default: return -1; /* invalid option */
438 return 0;
441 static int runargs(lua_State *L, char **argv, int n)
443 int i;
444 for (i = 1; i < n; i++) {
445 if (argv[i] == NULL) continue;
446 lua_assert(argv[i][0] == '-');
447 switch (argv[i][1]) { /* option */
448 case 'e': {
449 const char *chunk = argv[i] + 2;
450 if (*chunk == '\0') chunk = argv[++i];
451 lua_assert(chunk != NULL);
452 if (dostring(L, chunk, "=(command line)") != 0)
453 return 1;
454 break;
456 case 'l': {
457 const char *filename = argv[i] + 2;
458 if (*filename == '\0') filename = argv[++i];
459 lua_assert(filename != NULL);
460 if (dolibrary(L, filename))
461 return 1; /* stop if file fails */
462 break;
464 case 'j': { /* LuaJIT extension */
465 const char *cmd = argv[i] + 2;
466 if (*cmd == '\0') cmd = argv[++i];
467 lua_assert(cmd != NULL);
468 if (dojitcmd(L, cmd))
469 return 1;
470 break;
472 case 'O': /* LuaJIT extension */
473 if (dojitopt(L, argv[i] + 2))
474 return 1;
475 break;
476 case 'b': /* LuaJIT extension */
477 return dobytecode(L, argv+i);
478 default: break;
481 return 0;
484 static int handle_luainit(lua_State *L)
486 const char *init = getenv(LUA_INIT);
487 if (init == NULL)
488 return 0; /* status OK */
489 else if (init[0] == '@')
490 return dofile(L, init+1);
491 else
492 return dostring(L, init, "=" LUA_INIT);
495 struct Smain {
496 char **argv;
497 int argc;
498 int status;
501 static int pmain(lua_State *L)
503 struct Smain *s = (struct Smain *)lua_touserdata(L, 1);
504 char **argv = s->argv;
505 int script;
506 int flags = 0;
507 globalL = L;
508 if (argv[0] && argv[0][0]) progname = argv[0];
509 LUAJIT_VERSION_SYM(); /* linker-enforced version check */
510 lua_gc(L, LUA_GCSTOP, 0); /* stop collector during initialization */
511 luaL_openlibs(L); /* open libraries */
512 lua_gc(L, LUA_GCRESTART, -1);
513 s->status = handle_luainit(L);
514 if (s->status != 0) return 0;
515 script = collectargs(argv, &flags);
516 if (script < 0) { /* invalid args? */
517 print_usage();
518 s->status = 1;
519 return 0;
521 if ((flags & FLAGS_VERSION)) print_version();
522 s->status = runargs(L, argv, (script > 0) ? script : s->argc);
523 if (s->status != 0) return 0;
524 if (script)
525 s->status = handle_script(L, argv, script);
526 if (s->status != 0) return 0;
527 if ((flags & FLAGS_INTERACTIVE)) {
528 print_jit_status(L);
529 dotty(L);
530 } else if (script == 0 && !(flags & (FLAGS_EXEC|FLAGS_VERSION))) {
531 if (lua_stdin_is_tty()) {
532 print_version();
533 print_jit_status(L);
534 dotty(L);
535 } else {
536 dofile(L, NULL); /* executes stdin as a file */
539 return 0;
542 int main(int argc, char **argv)
544 int status;
545 struct Smain s;
546 lua_State *L = lua_open(); /* create state */
547 if (L == NULL) {
548 l_message(argv[0], "cannot create state: not enough memory");
549 return EXIT_FAILURE;
551 s.argc = argc;
552 s.argv = argv;
553 status = lua_cpcall(L, pmain, &s);
554 report(L, status);
555 lua_close(L);
556 return (status || s.status) ? EXIT_FAILURE : EXIT_SUCCESS;