beta-0.89.2
[luatex.git] / source / libs / luajit / LuaJIT-src / src / luajit.c
blob0ebc73005f864a0106eb265dd1dd968543b1825a
1 /*
2 ** LuaJIT frontend. Runs commands, scripts, read-eval-print (REPL) etc.
3 ** Copyright (C) 2005-2015 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 fputs("usage: ", stderr);
65 fputs(progname, stderr);
66 fputs(" [options]... [script [args]...].\n"
67 "Available options are:\n"
68 " -e chunk Execute string " LUA_QL("chunk") ".\n"
69 " -l name Require library " LUA_QL("name") ".\n"
70 " -b ... Save or list bytecode.\n"
71 " -j cmd Perform LuaJIT control command.\n"
72 " -O[opt] Control LuaJIT optimizations.\n"
73 " -i Enter interactive mode after executing " LUA_QL("script") ".\n"
74 " -v Show version information.\n"
75 " -E Ignore environment variables.\n"
76 " -- Stop handling options.\n"
77 " - Execute stdin and stop handling options.\n", stderr);
78 fflush(stderr);
81 static void l_message(const char *pname, const char *msg)
83 if (pname) { fputs(pname, stderr); fputc(':', stderr); fputc(' ', stderr); }
84 fputs(msg, stderr); fputc('\n', stderr);
85 fflush(stderr);
88 static int report(lua_State *L, int status)
90 if (status && !lua_isnil(L, -1)) {
91 const char *msg = lua_tostring(L, -1);
92 if (msg == NULL) msg = "(error object is not a string)";
93 l_message(progname, msg);
94 lua_pop(L, 1);
96 return status;
99 static int traceback(lua_State *L)
101 if (!lua_isstring(L, 1)) { /* Non-string error object? Try metamethod. */
102 if (lua_isnoneornil(L, 1) ||
103 !luaL_callmeta(L, 1, "__tostring") ||
104 !lua_isstring(L, -1))
105 return 1; /* Return non-string error object. */
106 lua_remove(L, 1); /* Replace object by result of __tostring metamethod. */
108 luaL_traceback(L, L, lua_tostring(L, 1), 1);
109 return 1;
112 static int docall(lua_State *L, int narg, int clear)
114 int status;
115 int base = lua_gettop(L) - narg; /* function index */
116 lua_pushcfunction(L, traceback); /* push traceback function */
117 lua_insert(L, base); /* put it under chunk and args */
118 #if !LJ_TARGET_CONSOLE
119 signal(SIGINT, laction);
120 #endif
121 status = lua_pcall(L, narg, (clear ? 0 : LUA_MULTRET), base);
122 #if !LJ_TARGET_CONSOLE
123 signal(SIGINT, SIG_DFL);
124 #endif
125 lua_remove(L, base); /* remove traceback function */
126 /* force a complete garbage collection in case of errors */
127 if (status != 0) lua_gc(L, LUA_GCCOLLECT, 0);
128 return status;
131 static void print_version(void)
133 fputs(LUAJIT_VERSION " -- " LUAJIT_COPYRIGHT ". " LUAJIT_URL "\n", stdout);
136 static void print_jit_status(lua_State *L)
138 int n;
139 const char *s;
140 lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
141 lua_getfield(L, -1, "jit"); /* Get jit.* module table. */
142 lua_remove(L, -2);
143 lua_getfield(L, -1, "status");
144 lua_remove(L, -2);
145 n = lua_gettop(L);
146 lua_call(L, 0, LUA_MULTRET);
147 fputs(lua_toboolean(L, n) ? "JIT: ON" : "JIT: OFF", stdout);
148 for (n++; (s = lua_tostring(L, n)); n++) {
149 putc(' ', stdout);
150 fputs(s, stdout);
152 putc('\n', stdout);
155 static int getargs(lua_State *L, char **argv, int n)
157 int narg;
158 int i;
159 int argc = 0;
160 while (argv[argc]) argc++; /* count total number of arguments */
161 narg = argc - (n + 1); /* number of arguments to the script */
162 luaL_checkstack(L, narg + 3, "too many arguments to script");
163 for (i = n+1; i < argc; i++)
164 lua_pushstring(L, argv[i]);
165 lua_createtable(L, narg, n + 1);
166 for (i = 0; i < argc; i++) {
167 lua_pushstring(L, argv[i]);
168 lua_rawseti(L, -2, i - n);
170 return narg;
173 static int dofile(lua_State *L, const char *name)
175 int status = luaL_loadfile(L, name) || docall(L, 0, 1);
176 return report(L, status);
179 static int dostring(lua_State *L, const char *s, const char *name)
181 int status = luaL_loadbuffer(L, s, strlen(s), name) || docall(L, 0, 1);
182 return report(L, status);
185 static int dolibrary(lua_State *L, const char *name)
187 lua_getglobal(L, "require");
188 lua_pushstring(L, name);
189 return report(L, docall(L, 1, 1));
192 static void write_prompt(lua_State *L, int firstline)
194 const char *p;
195 lua_getfield(L, LUA_GLOBALSINDEX, firstline ? "_PROMPT" : "_PROMPT2");
196 p = lua_tostring(L, -1);
197 if (p == NULL) p = firstline ? LUA_PROMPT : LUA_PROMPT2;
198 fputs(p, stdout);
199 fflush(stdout);
200 lua_pop(L, 1); /* remove global */
203 static int incomplete(lua_State *L, int status)
205 if (status == LUA_ERRSYNTAX) {
206 size_t lmsg;
207 const char *msg = lua_tolstring(L, -1, &lmsg);
208 const char *tp = msg + lmsg - (sizeof(LUA_QL("<eof>")) - 1);
209 if (strstr(msg, LUA_QL("<eof>")) == tp) {
210 lua_pop(L, 1);
211 return 1;
214 return 0; /* else... */
217 static int pushline(lua_State *L, int firstline)
219 char buf[LUA_MAXINPUT];
220 write_prompt(L, firstline);
221 if (fgets(buf, LUA_MAXINPUT, stdin)) {
222 size_t len = strlen(buf);
223 if (len > 0 && buf[len-1] == '\n')
224 buf[len-1] = '\0';
225 if (firstline && buf[0] == '=')
226 lua_pushfstring(L, "return %s", buf+1);
227 else
228 lua_pushstring(L, buf);
229 return 1;
231 return 0;
234 static int loadline(lua_State *L)
236 int status;
237 lua_settop(L, 0);
238 if (!pushline(L, 1))
239 return -1; /* no input */
240 for (;;) { /* repeat until gets a complete line */
241 status = luaL_loadbuffer(L, lua_tostring(L, 1), lua_strlen(L, 1), "=stdin");
242 if (!incomplete(L, status)) break; /* cannot try to add lines? */
243 if (!pushline(L, 0)) /* no more input? */
244 return -1;
245 lua_pushliteral(L, "\n"); /* add a new line... */
246 lua_insert(L, -2); /* ...between the two lines */
247 lua_concat(L, 3); /* join them */
249 lua_remove(L, 1); /* remove line */
250 return status;
253 static void dotty(lua_State *L)
255 int status;
256 const char *oldprogname = progname;
257 progname = NULL;
258 while ((status = loadline(L)) != -1) {
259 if (status == 0) status = docall(L, 0, 0);
260 report(L, status);
261 if (status == 0 && lua_gettop(L) > 0) { /* any result to print? */
262 lua_getglobal(L, "print");
263 lua_insert(L, 1);
264 if (lua_pcall(L, lua_gettop(L)-1, 0, 0) != 0)
265 l_message(progname,
266 lua_pushfstring(L, "error calling " LUA_QL("print") " (%s)",
267 lua_tostring(L, -1)));
270 lua_settop(L, 0); /* clear stack */
271 fputs("\n", stdout);
272 fflush(stdout);
273 progname = oldprogname;
276 static int handle_script(lua_State *L, char **argv, int n)
278 int status;
279 const char *fname;
280 int narg = getargs(L, argv, n); /* collect arguments */
281 lua_setglobal(L, "arg");
282 fname = argv[n];
283 if (strcmp(fname, "-") == 0 && strcmp(argv[n-1], "--") != 0)
284 fname = NULL; /* stdin */
285 status = luaL_loadfile(L, fname);
286 lua_insert(L, -(narg+1));
287 if (status == 0)
288 status = docall(L, narg, 0);
289 else
290 lua_pop(L, narg);
291 return report(L, status);
294 /* Load add-on module. */
295 static int loadjitmodule(lua_State *L)
297 lua_getglobal(L, "require");
298 lua_pushliteral(L, "jit.");
299 lua_pushvalue(L, -3);
300 lua_concat(L, 2);
301 if (lua_pcall(L, 1, 1, 0)) {
302 const char *msg = lua_tostring(L, -1);
303 if (msg && !strncmp(msg, "module ", 7))
304 goto nomodule;
305 return report(L, 1);
307 lua_getfield(L, -1, "start");
308 if (lua_isnil(L, -1)) {
309 nomodule:
310 l_message(progname,
311 "unknown luaJIT command or jit.* modules not installed");
312 return 1;
314 lua_remove(L, -2); /* Drop module table. */
315 return 0;
318 /* Run command with options. */
319 static int runcmdopt(lua_State *L, const char *opt)
321 int narg = 0;
322 if (opt && *opt) {
323 for (;;) { /* Split arguments. */
324 const char *p = strchr(opt, ',');
325 narg++;
326 if (!p) break;
327 if (p == opt)
328 lua_pushnil(L);
329 else
330 lua_pushlstring(L, opt, (size_t)(p - opt));
331 opt = p + 1;
333 if (*opt)
334 lua_pushstring(L, opt);
335 else
336 lua_pushnil(L);
338 return report(L, lua_pcall(L, narg, 0, 0));
341 /* JIT engine control command: try jit library first or load add-on module. */
342 static int dojitcmd(lua_State *L, const char *cmd)
344 const char *opt = strchr(cmd, '=');
345 lua_pushlstring(L, cmd, opt ? (size_t)(opt - cmd) : strlen(cmd));
346 lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
347 lua_getfield(L, -1, "jit"); /* Get jit.* module table. */
348 lua_remove(L, -2);
349 lua_pushvalue(L, -2);
350 lua_gettable(L, -2); /* Lookup library function. */
351 if (!lua_isfunction(L, -1)) {
352 lua_pop(L, 2); /* Drop non-function and jit.* table, keep module name. */
353 if (loadjitmodule(L))
354 return 1;
355 } else {
356 lua_remove(L, -2); /* Drop jit.* table. */
358 lua_remove(L, -2); /* Drop module name. */
359 return runcmdopt(L, opt ? opt+1 : opt);
362 /* Optimization flags. */
363 static int dojitopt(lua_State *L, const char *opt)
365 lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
366 lua_getfield(L, -1, "jit.opt"); /* Get jit.opt.* module table. */
367 lua_remove(L, -2);
368 lua_getfield(L, -1, "start");
369 lua_remove(L, -2);
370 return runcmdopt(L, opt);
373 /* Save or list bytecode. */
374 static int dobytecode(lua_State *L, char **argv)
376 int narg = 0;
377 lua_pushliteral(L, "bcsave");
378 if (loadjitmodule(L))
379 return 1;
380 if (argv[0][2]) {
381 narg++;
382 argv[0][1] = '-';
383 lua_pushstring(L, argv[0]+1);
385 for (argv++; *argv != NULL; narg++, argv++)
386 lua_pushstring(L, *argv);
387 return report(L, lua_pcall(L, narg, 0, 0));
390 /* check that argument has no extra characters at the end */
391 #define notail(x) {if ((x)[2] != '\0') return -1;}
393 #define FLAGS_INTERACTIVE 1
394 #define FLAGS_VERSION 2
395 #define FLAGS_EXEC 4
396 #define FLAGS_OPTION 8
397 #define FLAGS_NOENV 16
399 static int collectargs(char **argv, int *flags)
401 int i;
402 for (i = 1; argv[i] != NULL; i++) {
403 if (argv[i][0] != '-') /* Not an option? */
404 return i;
405 switch (argv[i][1]) { /* Check option. */
406 case '-':
407 notail(argv[i]);
408 return (argv[i+1] != NULL ? i+1 : 0);
409 case '\0':
410 return i;
411 case 'i':
412 notail(argv[i]);
413 *flags |= FLAGS_INTERACTIVE;
414 /* fallthrough */
415 case 'v':
416 notail(argv[i]);
417 *flags |= FLAGS_VERSION;
418 break;
419 case 'e':
420 *flags |= FLAGS_EXEC;
421 case 'j': /* LuaJIT extension */
422 case 'l':
423 *flags |= FLAGS_OPTION;
424 if (argv[i][2] == '\0') {
425 i++;
426 if (argv[i] == NULL) return -1;
428 break;
429 case 'O': break; /* LuaJIT extension */
430 case 'b': /* LuaJIT extension */
431 if (*flags) return -1;
432 *flags |= FLAGS_EXEC;
433 return 0;
434 case 'E':
435 *flags |= FLAGS_NOENV;
436 break;
437 default: return -1; /* invalid option */
440 return 0;
443 static int runargs(lua_State *L, char **argv, int n)
445 int i;
446 for (i = 1; i < n; i++) {
447 if (argv[i] == NULL) continue;
448 lua_assert(argv[i][0] == '-');
449 switch (argv[i][1]) { /* option */
450 case 'e': {
451 const char *chunk = argv[i] + 2;
452 if (*chunk == '\0') chunk = argv[++i];
453 lua_assert(chunk != NULL);
454 if (dostring(L, chunk, "=(command line)") != 0)
455 return 1;
456 break;
458 case 'l': {
459 const char *filename = argv[i] + 2;
460 if (*filename == '\0') filename = argv[++i];
461 lua_assert(filename != NULL);
462 if (dolibrary(L, filename))
463 return 1; /* stop if file fails */
464 break;
466 case 'j': { /* LuaJIT extension */
467 const char *cmd = argv[i] + 2;
468 if (*cmd == '\0') cmd = argv[++i];
469 lua_assert(cmd != NULL);
470 if (dojitcmd(L, cmd))
471 return 1;
472 break;
474 case 'O': /* LuaJIT extension */
475 if (dojitopt(L, argv[i] + 2))
476 return 1;
477 break;
478 case 'b': /* LuaJIT extension */
479 return dobytecode(L, argv+i);
480 default: break;
483 return 0;
486 static int handle_luainit(lua_State *L)
488 #if LJ_TARGET_CONSOLE
489 const char *init = NULL;
490 #else
491 const char *init = getenv(LUA_INIT);
492 #endif
493 if (init == NULL)
494 return 0; /* status OK */
495 else if (init[0] == '@')
496 return dofile(L, init+1);
497 else
498 return dostring(L, init, "=" LUA_INIT);
501 static struct Smain {
502 char **argv;
503 int argc;
504 int status;
505 } smain;
507 static int pmain(lua_State *L)
509 struct Smain *s = &smain;
510 char **argv = s->argv;
511 int script;
512 int flags = 0;
513 globalL = L;
514 if (argv[0] && argv[0][0]) progname = argv[0];
515 LUAJIT_VERSION_SYM(); /* linker-enforced version check */
516 script = collectargs(argv, &flags);
517 if (script < 0) { /* invalid args? */
518 print_usage();
519 s->status = 1;
520 return 0;
522 if ((flags & FLAGS_NOENV)) {
523 lua_pushboolean(L, 1);
524 lua_setfield(L, LUA_REGISTRYINDEX, "LUA_NOENV");
526 lua_gc(L, LUA_GCSTOP, 0); /* stop collector during initialization */
527 luaL_openlibs(L); /* open libraries */
528 lua_gc(L, LUA_GCRESTART, -1);
529 if (!(flags & FLAGS_NOENV)) {
530 s->status = handle_luainit(L);
531 if (s->status != 0) return 0;
533 if ((flags & FLAGS_VERSION)) print_version();
534 s->status = runargs(L, argv, (script > 0) ? script : s->argc);
535 if (s->status != 0) return 0;
536 if (script) {
537 s->status = handle_script(L, argv, script);
538 if (s->status != 0) return 0;
540 if ((flags & FLAGS_INTERACTIVE)) {
541 print_jit_status(L);
542 dotty(L);
543 } else if (script == 0 && !(flags & (FLAGS_EXEC|FLAGS_VERSION))) {
544 if (lua_stdin_is_tty()) {
545 print_version();
546 print_jit_status(L);
547 dotty(L);
548 } else {
549 dofile(L, NULL); /* executes stdin as a file */
552 return 0;
555 int main(int argc, char **argv)
557 int status;
558 lua_State *L = lua_open(); /* create state */
559 if (L == NULL) {
560 l_message(argv[0], "cannot create state: not enough memory");
561 return EXIT_FAILURE;
563 smain.argc = argc;
564 smain.argv = argv;
565 status = lua_cpcall(L, pmain, NULL);
566 report(L, status);
567 lua_close(L);
568 return (status || smain.status) ? EXIT_FAILURE : EXIT_SUCCESS;