2 ** LuaJIT frontend. Runs commands, scripts, read-eval-print (REPL) etc.
3 ** Copyright (C) 2005-2015 Mike Pall. See Copyright Notice in luajit.h
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
24 #define lua_stdin_is_tty() isatty(0)
25 #elif LJ_TARGET_WINDOWS
28 #define lua_stdin_is_tty() isatty(_fileno(stdin))
30 #define lua_stdin_is_tty() _isatty(_fileno(stdin))
33 #define lua_stdin_is_tty() 1
36 #if !LJ_TARGET_CONSOLE
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. */
50 lua_pushfstring(L
, "%sinterrupted!", lua_tostring(L
, -1));
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);
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
);
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
);
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
);
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);
112 static int docall(lua_State
*L
, int narg
, int clear
)
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
);
121 status
= lua_pcall(L
, narg
, (clear
? 0 : LUA_MULTRET
), base
);
122 #if !LJ_TARGET_CONSOLE
123 signal(SIGINT
, SIG_DFL
);
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);
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
)
140 lua_getfield(L
, LUA_REGISTRYINDEX
, "_LOADED");
141 lua_getfield(L
, -1, "jit"); /* Get jit.* module table. */
143 lua_getfield(L
, -1, "status");
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
++) {
155 static int getargs(lua_State
*L
, char **argv
, int n
)
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
);
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
)
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
;
200 lua_pop(L
, 1); /* remove global */
203 static int incomplete(lua_State
*L
, int status
)
205 if (status
== LUA_ERRSYNTAX
) {
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
) {
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')
225 if (firstline
&& buf
[0] == '=')
226 lua_pushfstring(L
, "return %s", buf
+1);
228 lua_pushstring(L
, buf
);
234 static int loadline(lua_State
*L
)
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? */
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 */
253 static void dotty(lua_State
*L
)
256 const char *oldprogname
= progname
;
258 while ((status
= loadline(L
)) != -1) {
259 if (status
== 0) status
= docall(L
, 0, 0);
261 if (status
== 0 && lua_gettop(L
) > 0) { /* any result to print? */
262 lua_getglobal(L
, "print");
264 if (lua_pcall(L
, lua_gettop(L
)-1, 0, 0) != 0)
266 lua_pushfstring(L
, "error calling " LUA_QL("print") " (%s)",
267 lua_tostring(L
, -1)));
270 lua_settop(L
, 0); /* clear stack */
273 progname
= oldprogname
;
276 static int handle_script(lua_State
*L
, char **argv
, int n
)
280 int narg
= getargs(L
, argv
, n
); /* collect arguments */
281 lua_setglobal(L
, "arg");
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));
288 status
= docall(L
, narg
, 0);
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);
301 if (lua_pcall(L
, 1, 1, 0)) {
302 const char *msg
= lua_tostring(L
, -1);
303 if (msg
&& !strncmp(msg
, "module ", 7))
307 lua_getfield(L
, -1, "start");
308 if (lua_isnil(L
, -1)) {
311 "unknown luaJIT command or jit.* modules not installed");
314 lua_remove(L
, -2); /* Drop module table. */
318 /* Run command with options. */
319 static int runcmdopt(lua_State
*L
, const char *opt
)
323 for (;;) { /* Split arguments. */
324 const char *p
= strchr(opt
, ',');
330 lua_pushlstring(L
, opt
, (size_t)(p
- opt
));
334 lua_pushstring(L
, opt
);
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. */
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
))
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. */
368 lua_getfield(L
, -1, "start");
370 return runcmdopt(L
, opt
);
373 /* Save or list bytecode. */
374 static int dobytecode(lua_State
*L
, char **argv
)
377 lua_pushliteral(L
, "bcsave");
378 if (loadjitmodule(L
))
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
396 #define FLAGS_OPTION 8
397 #define FLAGS_NOENV 16
399 static int collectargs(char **argv
, int *flags
)
402 for (i
= 1; argv
[i
] != NULL
; i
++) {
403 if (argv
[i
][0] != '-') /* Not an option? */
405 switch (argv
[i
][1]) { /* Check option. */
408 return (argv
[i
+1] != NULL
? i
+1 : 0);
413 *flags
|= FLAGS_INTERACTIVE
;
417 *flags
|= FLAGS_VERSION
;
420 *flags
|= FLAGS_EXEC
;
421 case 'j': /* LuaJIT extension */
423 *flags
|= FLAGS_OPTION
;
424 if (argv
[i
][2] == '\0') {
426 if (argv
[i
] == NULL
) return -1;
429 case 'O': break; /* LuaJIT extension */
430 case 'b': /* LuaJIT extension */
431 if (*flags
) return -1;
432 *flags
|= FLAGS_EXEC
;
435 *flags
|= FLAGS_NOENV
;
437 default: return -1; /* invalid option */
443 static int runargs(lua_State
*L
, char **argv
, int n
)
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 */
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)
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 */
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
))
474 case 'O': /* LuaJIT extension */
475 if (dojitopt(L
, argv
[i
] + 2))
478 case 'b': /* LuaJIT extension */
479 return dobytecode(L
, argv
+i
);
486 static int handle_luainit(lua_State
*L
)
488 #if LJ_TARGET_CONSOLE
489 const char *init
= NULL
;
491 const char *init
= getenv(LUA_INIT
);
494 return 0; /* status OK */
495 else if (init
[0] == '@')
496 return dofile(L
, init
+1);
498 return dostring(L
, init
, "=" LUA_INIT
);
501 static struct Smain
{
507 static int pmain(lua_State
*L
)
509 struct Smain
*s
= &smain
;
510 char **argv
= s
->argv
;
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? */
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;
537 s
->status
= handle_script(L
, argv
, script
);
538 if (s
->status
!= 0) return 0;
540 if ((flags
& FLAGS_INTERACTIVE
)) {
543 } else if (script
== 0 && !(flags
& (FLAGS_EXEC
|FLAGS_VERSION
))) {
544 if (lua_stdin_is_tty()) {
549 dofile(L
, NULL
); /* executes stdin as a file */
555 int main(int argc
, char **argv
)
558 lua_State
*L
= lua_open(); /* create state */
560 l_message(argv
[0], "cannot create state: not enough memory");
565 status
= lua_cpcall(L
, pmain
, NULL
);
568 return (status
|| smain
.status
) ? EXIT_FAILURE
: EXIT_SUCCESS
;