2 ** LuaJIT frontend. Runs commands, scripts, read-eval-print (REPL) etc.
3 ** Copyright (C) 2005-2025 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 /* Improve signal handling on POSIX. Try CTRL-C on: luajit -e 'io.read()' */
41 static void signal_set(int sig
, void (*h
)(int))
44 memset(&sa
, 0, sizeof(sa
));
46 sigemptyset(&sa
.sa_mask
);
47 sigaction(sig
, &sa
, NULL
);
50 #define signal_set signal
55 static lua_State
*globalL
= NULL
;
56 static const char *progname
= LUA_PROGNAME
;
57 static char *empty_argv
[2] = { NULL
, NULL
};
59 #if !LJ_TARGET_CONSOLE
60 static void lstop(lua_State
*L
, lua_Debug
*ar
)
62 (void)ar
; /* unused arg. */
63 lua_sethook(L
, NULL
, 0, 0);
64 /* Avoid luaL_error -- a C hook doesn't add an extra frame. */
66 lua_pushfstring(L
, "%sinterrupted!", lua_tostring(L
, -1));
70 static void laction(int i
)
72 /* Terminate process if another SIGINT happens (double CTRL-C). */
73 signal_set(i
, SIG_DFL
);
74 lua_sethook(globalL
, lstop
, LUA_MASKCALL
| LUA_MASKRET
| LUA_MASKCOUNT
, 1);
78 static void print_usage(void)
80 fputs("usage: ", stderr
);
81 fputs(progname
, stderr
);
82 fputs(" [options]... [script [args]...].\n"
83 "Available options are:\n"
84 " -e chunk Execute string " LUA_QL("chunk") ".\n"
85 " -l name Require library " LUA_QL("name") ".\n"
86 " -b ... Save or list bytecode.\n"
87 " -j cmd Perform LuaJIT control command.\n"
88 " -O[opt] Control LuaJIT optimizations.\n"
89 " -i Enter interactive mode after executing " LUA_QL("script") ".\n"
90 " -v Show version information.\n"
91 " -E Ignore environment variables.\n"
92 " -- Stop handling options.\n"
93 " - Execute stdin and stop handling options.\n", stderr
);
97 static void l_message(const char *msg
)
99 if (progname
) { fputs(progname
, stderr
); fputc(':', stderr
); fputc(' ', stderr
); }
100 fputs(msg
, stderr
); fputc('\n', stderr
);
104 static int report(lua_State
*L
, int status
)
106 if (status
&& !lua_isnil(L
, -1)) {
107 const char *msg
= lua_tostring(L
, -1);
108 if (msg
== NULL
) msg
= "(error object is not a string)";
115 static int traceback(lua_State
*L
)
117 if (!lua_isstring(L
, 1)) { /* Non-string error object? Try metamethod. */
118 if (lua_isnoneornil(L
, 1) ||
119 !luaL_callmeta(L
, 1, "__tostring") ||
120 !lua_isstring(L
, -1))
121 return 1; /* Return non-string error object. */
122 lua_remove(L
, 1); /* Replace object by result of __tostring metamethod. */
124 luaL_traceback(L
, L
, lua_tostring(L
, 1), 1);
128 static int docall(lua_State
*L
, int narg
, int clear
)
131 int base
= lua_gettop(L
) - narg
; /* function index */
132 lua_pushcfunction(L
, traceback
); /* push traceback function */
133 lua_insert(L
, base
); /* put it under chunk and args */
134 #if !LJ_TARGET_CONSOLE
135 signal_set(SIGINT
, laction
);
137 status
= lua_pcall(L
, narg
, (clear
? 0 : LUA_MULTRET
), base
);
138 #if !LJ_TARGET_CONSOLE
139 signal_set(SIGINT
, SIG_DFL
);
141 lua_remove(L
, base
); /* remove traceback function */
142 /* force a complete garbage collection in case of errors */
143 if (status
!= LUA_OK
) lua_gc(L
, LUA_GCCOLLECT
, 0);
147 static void print_version(void)
149 fputs(LUAJIT_VERSION
" -- " LUAJIT_COPYRIGHT
". " LUAJIT_URL
"\n", stdout
);
152 static void print_jit_status(lua_State
*L
)
156 lua_getfield(L
, LUA_REGISTRYINDEX
, "_LOADED");
157 lua_getfield(L
, -1, "jit"); /* Get jit.* module table. */
159 lua_getfield(L
, -1, "status");
162 lua_call(L
, 0, LUA_MULTRET
);
163 fputs(lua_toboolean(L
, n
) ? "JIT: ON" : "JIT: OFF", stdout
);
164 for (n
++; (s
= lua_tostring(L
, n
)); n
++) {
169 lua_settop(L
, 0); /* clear stack */
172 static void createargtable(lua_State
*L
, char **argv
, int argc
, int argf
)
175 lua_createtable(L
, argc
- argf
, argf
);
176 for (i
= 0; i
< argc
; i
++) {
177 lua_pushstring(L
, argv
[i
]);
178 lua_rawseti(L
, -2, i
- argf
);
180 lua_setglobal(L
, "arg");
183 static int dofile(lua_State
*L
, const char *name
)
185 int status
= luaL_loadfile(L
, name
) || docall(L
, 0, 1);
186 return report(L
, status
);
189 static int dostring(lua_State
*L
, const char *s
, const char *name
)
191 int status
= luaL_loadbuffer(L
, s
, strlen(s
), name
) || docall(L
, 0, 1);
192 return report(L
, status
);
195 static int dolibrary(lua_State
*L
, const char *name
)
197 lua_getglobal(L
, "require");
198 lua_pushstring(L
, name
);
199 return report(L
, docall(L
, 1, 1));
202 static void write_prompt(lua_State
*L
, int firstline
)
205 lua_getfield(L
, LUA_GLOBALSINDEX
, firstline
? "_PROMPT" : "_PROMPT2");
206 p
= lua_tostring(L
, -1);
207 if (p
== NULL
) p
= firstline
? LUA_PROMPT
: LUA_PROMPT2
;
210 lua_pop(L
, 1); /* remove global */
213 static int incomplete(lua_State
*L
, int status
)
215 if (status
== LUA_ERRSYNTAX
) {
217 const char *msg
= lua_tolstring(L
, -1, &lmsg
);
218 const char *tp
= msg
+ lmsg
- (sizeof(LUA_QL("<eof>")) - 1);
219 if (strstr(msg
, LUA_QL("<eof>")) == tp
) {
224 return 0; /* else... */
227 static int pushline(lua_State
*L
, int firstline
)
229 char buf
[LUA_MAXINPUT
];
230 write_prompt(L
, firstline
);
231 if (fgets(buf
, LUA_MAXINPUT
, stdin
)) {
232 size_t len
= strlen(buf
);
233 if (len
> 0 && buf
[len
-1] == '\n')
235 if (firstline
&& buf
[0] == '=')
236 lua_pushfstring(L
, "return %s", buf
+1);
238 lua_pushstring(L
, buf
);
244 static int loadline(lua_State
*L
)
249 return -1; /* no input */
250 for (;;) { /* repeat until gets a complete line */
251 status
= luaL_loadbuffer(L
, lua_tostring(L
, 1), lua_strlen(L
, 1), "=stdin");
252 if (!incomplete(L
, status
)) break; /* cannot try to add lines? */
253 if (!pushline(L
, 0)) /* no more input? */
255 lua_pushliteral(L
, "\n"); /* add a new line... */
256 lua_insert(L
, -2); /* ...between the two lines */
257 lua_concat(L
, 3); /* join them */
259 lua_remove(L
, 1); /* remove line */
263 static void dotty(lua_State
*L
)
266 const char *oldprogname
= progname
;
268 while ((status
= loadline(L
)) != -1) {
269 if (status
== LUA_OK
) status
= docall(L
, 0, 0);
271 if (status
== LUA_OK
&& lua_gettop(L
) > 0) { /* any result to print? */
272 lua_getglobal(L
, "print");
274 if (lua_pcall(L
, lua_gettop(L
)-1, 0, 0) != 0)
275 l_message(lua_pushfstring(L
, "error calling " LUA_QL("print") " (%s)",
276 lua_tostring(L
, -1)));
279 lua_settop(L
, 0); /* clear stack */
282 progname
= oldprogname
;
285 static int handle_script(lua_State
*L
, char **argx
)
288 const char *fname
= argx
[0];
289 if (strcmp(fname
, "-") == 0 && strcmp(argx
[-1], "--") != 0)
290 fname
= NULL
; /* stdin */
291 status
= luaL_loadfile(L
, fname
);
292 if (status
== LUA_OK
) {
293 /* Fetch args from arg table. LUA_INIT or -e might have changed them. */
295 lua_getglobal(L
, "arg");
296 if (lua_istable(L
, -1)) {
299 lua_rawgeti(L
, -narg
, narg
);
300 } while (!lua_isnil(L
, -1));
302 lua_remove(L
, -narg
);
307 status
= docall(L
, narg
, 0);
309 return report(L
, status
);
312 /* Load add-on module. */
313 static int loadjitmodule(lua_State
*L
)
315 lua_getglobal(L
, "require");
316 lua_pushliteral(L
, "jit.");
317 lua_pushvalue(L
, -3);
319 if (lua_pcall(L
, 1, 1, 0)) {
320 const char *msg
= lua_tostring(L
, -1);
321 if (msg
&& !strncmp(msg
, "module ", 7))
325 lua_getfield(L
, -1, "start");
326 if (lua_isnil(L
, -1)) {
328 l_message("unknown luaJIT command or jit.* modules not installed");
331 lua_remove(L
, -2); /* Drop module table. */
335 /* Run command with options. */
336 static int runcmdopt(lua_State
*L
, const char *opt
)
340 for (;;) { /* Split arguments. */
341 const char *p
= strchr(opt
, ',');
347 lua_pushlstring(L
, opt
, (size_t)(p
- opt
));
351 lua_pushstring(L
, opt
);
355 return report(L
, lua_pcall(L
, narg
, 0, 0));
358 /* JIT engine control command: try jit library first or load add-on module. */
359 static int dojitcmd(lua_State
*L
, const char *cmd
)
361 const char *opt
= strchr(cmd
, '=');
362 lua_pushlstring(L
, cmd
, opt
? (size_t)(opt
- cmd
) : strlen(cmd
));
363 lua_getfield(L
, LUA_REGISTRYINDEX
, "_LOADED");
364 lua_getfield(L
, -1, "jit"); /* Get jit.* module table. */
366 lua_pushvalue(L
, -2);
367 lua_gettable(L
, -2); /* Lookup library function. */
368 if (!lua_isfunction(L
, -1)) {
369 lua_pop(L
, 2); /* Drop non-function and jit.* table, keep module name. */
370 if (loadjitmodule(L
))
373 lua_remove(L
, -2); /* Drop jit.* table. */
375 lua_remove(L
, -2); /* Drop module name. */
376 return runcmdopt(L
, opt
? opt
+1 : opt
);
379 /* Optimization flags. */
380 static int dojitopt(lua_State
*L
, const char *opt
)
382 lua_getfield(L
, LUA_REGISTRYINDEX
, "_LOADED");
383 lua_getfield(L
, -1, "jit.opt"); /* Get jit.opt.* module table. */
385 lua_getfield(L
, -1, "start");
387 return runcmdopt(L
, opt
);
390 /* Save or list bytecode. */
391 static int dobytecode(lua_State
*L
, char **argv
)
394 lua_pushliteral(L
, "bcsave");
395 if (loadjitmodule(L
))
400 lua_pushstring(L
, argv
[0]+1);
402 for (argv
++; *argv
!= NULL
; narg
++, argv
++)
403 lua_pushstring(L
, *argv
);
404 report(L
, lua_pcall(L
, narg
, 0, 0));
408 /* check that argument has no extra characters at the end */
409 #define notail(x) {if ((x)[2] != '\0') return -1;}
411 #define FLAGS_INTERACTIVE 1
412 #define FLAGS_VERSION 2
414 #define FLAGS_OPTION 8
415 #define FLAGS_NOENV 16
417 static int collectargs(char **argv
, int *flags
)
420 for (i
= 1; argv
[i
] != NULL
; i
++) {
421 if (argv
[i
][0] != '-') /* Not an option? */
423 switch (argv
[i
][1]) { /* Check option. */
431 *flags
|= FLAGS_INTERACTIVE
;
435 *flags
|= FLAGS_VERSION
;
438 *flags
|= FLAGS_EXEC
;
440 case 'j': /* LuaJIT extension */
442 *flags
|= FLAGS_OPTION
;
443 if (argv
[i
][2] == '\0') {
445 if (argv
[i
] == NULL
) return -1;
448 case 'O': break; /* LuaJIT extension */
449 case 'b': /* LuaJIT extension */
450 if (*flags
) return -1;
451 *flags
|= FLAGS_EXEC
;
454 *flags
|= FLAGS_NOENV
;
456 default: return -1; /* invalid option */
462 static int runargs(lua_State
*L
, char **argv
, int argn
)
465 for (i
= 1; i
< argn
; i
++) {
466 if (argv
[i
] == NULL
) continue;
467 lua_assert(argv
[i
][0] == '-');
468 switch (argv
[i
][1]) {
470 const char *chunk
= argv
[i
] + 2;
471 if (*chunk
== '\0') chunk
= argv
[++i
];
472 lua_assert(chunk
!= NULL
);
473 if (dostring(L
, chunk
, "=(command line)") != 0)
478 const char *filename
= argv
[i
] + 2;
479 if (*filename
== '\0') filename
= argv
[++i
];
480 lua_assert(filename
!= NULL
);
481 if (dolibrary(L
, filename
))
485 case 'j': { /* LuaJIT extension. */
486 const char *cmd
= argv
[i
] + 2;
487 if (*cmd
== '\0') cmd
= argv
[++i
];
488 lua_assert(cmd
!= NULL
);
489 if (dojitcmd(L
, cmd
))
493 case 'O': /* LuaJIT extension. */
494 if (dojitopt(L
, argv
[i
] + 2))
497 case 'b': /* LuaJIT extension. */
498 return dobytecode(L
, argv
+i
);
505 static int handle_luainit(lua_State
*L
)
507 #if LJ_TARGET_CONSOLE
508 const char *init
= NULL
;
510 const char *init
= getenv(LUA_INIT
);
514 else if (init
[0] == '@')
515 return dofile(L
, init
+1);
517 return dostring(L
, init
, "=" LUA_INIT
);
520 static struct Smain
{
526 static int pmain(lua_State
*L
)
528 struct Smain
*s
= &smain
;
529 char **argv
= s
->argv
;
533 LUAJIT_VERSION_SYM(); /* Linker-enforced version check. */
535 argn
= collectargs(argv
, &flags
);
536 if (argn
< 0) { /* Invalid args? */
542 if ((flags
& FLAGS_NOENV
)) {
543 lua_pushboolean(L
, 1);
544 lua_setfield(L
, LUA_REGISTRYINDEX
, "LUA_NOENV");
547 /* Stop collector during library initialization. */
548 lua_gc(L
, LUA_GCSTOP
, 0);
550 lua_gc(L
, LUA_GCRESTART
, -1);
552 createargtable(L
, argv
, s
->argc
, argn
);
554 if (!(flags
& FLAGS_NOENV
)) {
555 s
->status
= handle_luainit(L
);
556 if (s
->status
!= LUA_OK
) return 0;
559 if ((flags
& FLAGS_VERSION
)) print_version();
561 s
->status
= runargs(L
, argv
, argn
);
562 if (s
->status
!= LUA_OK
) return 0;
564 if (s
->argc
> argn
) {
565 s
->status
= handle_script(L
, argv
+ argn
);
566 if (s
->status
!= LUA_OK
) return 0;
569 if ((flags
& FLAGS_INTERACTIVE
)) {
572 } else if (s
->argc
== argn
&& !(flags
& (FLAGS_EXEC
|FLAGS_VERSION
))) {
573 if (lua_stdin_is_tty()) {
578 dofile(L
, NULL
); /* Executes stdin as a file. */
584 int main(int argc
, char **argv
)
588 if (!argv
[0]) argv
= empty_argv
; else if (argv
[0][0]) progname
= argv
[0];
591 l_message("cannot create state: not enough memory");
596 status
= lua_cpcall(L
, pmain
, NULL
);
599 return (status
|| smain
.status
> 0) ? EXIT_FAILURE
: EXIT_SUCCESS
;