lua.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  1. /*
  2. ** $Id: lua.c,v 1.224 2015/03/10 14:15:06 roberto Exp roberto $
  3. ** Lua stand-alone interpreter
  4. ** See Copyright Notice in lua.h
  5. */
  6. #define lua_c
  7. #include "lprefix.h"
  8. #include <signal.h>
  9. #include <stdio.h>
  10. #include <stdlib.h>
  11. #include <string.h>
  12. #include "lua.h"
  13. #include "lauxlib.h"
  14. #include "lualib.h"
  15. #if !defined(LUA_PROMPT)
  16. #define LUA_PROMPT "> "
  17. #define LUA_PROMPT2 ">> "
  18. #endif
  19. #if !defined(LUA_PROGNAME)
  20. #define LUA_PROGNAME "lua"
  21. #endif
  22. #if !defined(LUA_MAXINPUT)
  23. #define LUA_MAXINPUT 512
  24. #endif
  25. #if !defined(LUA_INIT_VAR)
  26. #define LUA_INIT_VAR "LUA_INIT"
  27. #endif
  28. #define LUA_INITVARVERSION \
  29. LUA_INIT_VAR "_" LUA_VERSION_MAJOR "_" LUA_VERSION_MINOR
  30. /*
  31. ** lua_stdin_is_tty detects whether the standard input is a 'tty' (that
  32. ** is, whether we're running lua interactively).
  33. */
  34. #if !defined(lua_stdin_is_tty) /* { */
  35. #if defined(LUA_USE_POSIX) /* { */
  36. #include <unistd.h>
  37. #define lua_stdin_is_tty() isatty(0)
  38. #elif defined(LUA_USE_WINDOWS) /* }{ */
  39. #include <io.h>
  40. #define lua_stdin_is_tty() _isatty(_fileno(stdin))
  41. #else /* }{ */
  42. /* ISO C definition */
  43. #define lua_stdin_is_tty() 1 /* assume stdin is a tty */
  44. #endif /* } */
  45. #endif /* } */
  46. /*
  47. ** lua_readline defines how to show a prompt and then read a line from
  48. ** the standard input.
  49. ** lua_saveline defines how to "save" a read line in a "history".
  50. ** lua_freeline defines how to free a line read by lua_readline.
  51. */
  52. #if !defined(lua_readline) /* { */
  53. #if defined(LUA_USE_READLINE) /* { */
  54. #include <readline/readline.h>
  55. #include <readline/history.h>
  56. #define lua_readline(L,b,p) ((void)L, ((b)=readline(p)) != NULL)
  57. #define lua_saveline(L,line) ((void)L, add_history(line))
  58. #define lua_freeline(L,b) ((void)L, free(b))
  59. #else /* }{ */
  60. #define lua_readline(L,b,p) \
  61. ((void)L, fputs(p, stdout), fflush(stdout), /* show prompt */ \
  62. fgets(b, LUA_MAXINPUT, stdin) != NULL) /* get line */
  63. #define lua_saveline(L,line) { (void)L; (void)line; }
  64. #define lua_freeline(L,b) { (void)L; (void)b; }
  65. #endif /* } */
  66. #endif /* } */
  67. static lua_State *globalL = NULL;
  68. static const char *progname = LUA_PROGNAME;
  69. /*
  70. ** Hook set by signal function to stop the interpreter.
  71. */
  72. static void lstop (lua_State *L, lua_Debug *ar) {
  73. (void)ar; /* unused arg. */
  74. lua_sethook(L, NULL, 0, 0); /* reset hook */
  75. luaL_error(L, "interrupted!");
  76. }
  77. /*
  78. ** Function to be called at a C signal. Because a C signal cannot
  79. ** just change a Lua state (as there is no proper synchronization),
  80. ** this function only sets a hook that, when called, will stop the
  81. ** interpreter.
  82. */
  83. static void laction (int i) {
  84. signal(i, SIG_DFL); /* if another SIGINT happens, terminate process */
  85. lua_sethook(globalL, lstop, LUA_MASKCALL | LUA_MASKRET | LUA_MASKCOUNT, 1);
  86. }
  87. static void print_usage (const char *badoption) {
  88. lua_writestringerror("%s: ", progname);
  89. if (badoption[1] == 'e' || badoption[1] == 'l')
  90. lua_writestringerror("'%s' needs argument\n", badoption);
  91. else
  92. lua_writestringerror("unrecognized option '%s'\n", badoption);
  93. lua_writestringerror(
  94. "usage: %s [options] [script [args]]\n"
  95. "Available options are:\n"
  96. " -e stat execute string 'stat'\n"
  97. " -i enter interactive mode after executing 'script'\n"
  98. " -l name require library 'name'\n"
  99. " -v show version information\n"
  100. " -E ignore environment variables\n"
  101. " -- stop handling options\n"
  102. " - stop handling options and execute stdin\n"
  103. ,
  104. progname);
  105. }
  106. /*
  107. ** Prints an error message, adding the program name in front of it
  108. ** (if present)
  109. */
  110. static void l_message (const char *pname, const char *msg) {
  111. if (pname) lua_writestringerror("%s: ", pname);
  112. lua_writestringerror("%s\n", msg);
  113. }
  114. /*
  115. ** Check whether 'status' is not OK and, if so, prints the error
  116. ** message on the top of the stack. It assumes that the error object
  117. ** is a string, as it was either generated by Lua or by 'msghandler'.
  118. */
  119. static int report (lua_State *L, int status) {
  120. if (status != LUA_OK) {
  121. const char *msg = lua_tostring(L, -1);
  122. l_message(progname, msg);
  123. lua_pop(L, 1); /* remove message */
  124. }
  125. return status;
  126. }
  127. /*
  128. ** Message handler used to run all chunks
  129. */
  130. static int msghandler (lua_State *L) {
  131. const char *msg = lua_tostring(L, 1);
  132. if (msg == NULL) { /* is error object not a string? */
  133. if (luaL_callmeta(L, 1, "__tostring") && /* does it have a metamethod */
  134. lua_type(L, -1) == LUA_TSTRING) /* that produces a string? */
  135. return 1; /* that is the message */
  136. else
  137. msg = lua_pushfstring(L, "(error object is a %s value)",
  138. luaL_typename(L, 1));
  139. }
  140. luaL_traceback(L, L, msg, 1); /* append a standard traceback */
  141. return 1; /* return the traceback */
  142. }
  143. /*
  144. ** Interface to 'lua_pcall', which sets appropriate message function
  145. ** and C-signal handler. Used to run all chunks.
  146. */
  147. static int docall (lua_State *L, int narg, int nres) {
  148. int status;
  149. int base = lua_gettop(L) - narg; /* function index */
  150. lua_pushcfunction(L, msghandler); /* push message handler */
  151. lua_insert(L, base); /* put it under function and args */
  152. globalL = L; /* to be available to 'laction' */
  153. signal(SIGINT, laction); /* set C-signal handler */
  154. status = lua_pcall(L, narg, nres, base);
  155. signal(SIGINT, SIG_DFL); /* reset C-signal handler */
  156. lua_remove(L, base); /* remove message handler from the stack */
  157. return status;
  158. }
  159. static void print_version (void) {
  160. lua_writestring(LUA_COPYRIGHT, strlen(LUA_COPYRIGHT));
  161. lua_writeline();
  162. }
  163. /*
  164. ** Create the 'arg' table, which stores all arguments from the
  165. ** command line ('argv'). It should be aligned so that, at index 0,
  166. ** it has 'argv[script]', which is the script name. The arguments
  167. ** to the script (everything after 'script') go to positive indices;
  168. ** other arguments (before the script name) go to negative indices.
  169. ** If there is no script name, assume interpreter's name as base.
  170. */
  171. static void createargtable (lua_State *L, char **argv, int argc, int script) {
  172. int i, narg;
  173. if (script == argc) script = 0; /* no script name? */
  174. narg = argc - (script + 1); /* number of positive indices */
  175. lua_createtable(L, narg, script + 1);
  176. for (i = 0; i < argc; i++) {
  177. lua_pushstring(L, argv[i]);
  178. lua_rawseti(L, -2, i - script);
  179. }
  180. lua_setglobal(L, "arg");
  181. }
  182. static int dochunk (lua_State *L, int status) {
  183. if (status == LUA_OK) status = docall(L, 0, 0);
  184. return report(L, status);
  185. }
  186. static int dofile (lua_State *L, const char *name) {
  187. return dochunk(L, luaL_loadfile(L, name));
  188. }
  189. static int dostring (lua_State *L, const char *s, const char *name) {
  190. return dochunk(L, luaL_loadbuffer(L, s, strlen(s), name));
  191. }
  192. /*
  193. ** Calls 'require(name)' and stores the result in a global variable
  194. ** with the given name.
  195. */
  196. static int dolibrary (lua_State *L, const char *name) {
  197. int status;
  198. lua_getglobal(L, "require");
  199. lua_pushstring(L, name);
  200. status = docall(L, 1, 1); /* call 'require(name)' */
  201. if (status == LUA_OK)
  202. lua_setglobal(L, name); /* global[name] = require return */
  203. return report(L, status);
  204. }
  205. /*
  206. ** Returns the string to be used as a prompt by the interpreter.
  207. */
  208. static const char *get_prompt (lua_State *L, int firstline) {
  209. const char *p;
  210. lua_getglobal(L, firstline ? "_PROMPT" : "_PROMPT2");
  211. p = lua_tostring(L, -1);
  212. if (p == NULL) p = (firstline ? LUA_PROMPT : LUA_PROMPT2);
  213. return p;
  214. }
  215. /* mark in error messages for incomplete statements */
  216. #define EOFMARK "<eof>"
  217. #define marklen (sizeof(EOFMARK)/sizeof(char) - 1)
  218. /*
  219. ** Check whether 'status' signals a syntax error and the error
  220. ** message at the top of the stack ends with the above mark for
  221. ** incomplete statements.
  222. */
  223. static int incomplete (lua_State *L, int status) {
  224. if (status == LUA_ERRSYNTAX) {
  225. size_t lmsg;
  226. const char *msg = lua_tolstring(L, -1, &lmsg);
  227. if (lmsg >= marklen && strcmp(msg + lmsg - marklen, EOFMARK) == 0) {
  228. lua_pop(L, 1);
  229. return 1;
  230. }
  231. }
  232. return 0; /* else... */
  233. }
  234. /*
  235. ** Prompt the user, read a line, and push it into the Lua stack.
  236. */
  237. static int pushline (lua_State *L, int firstline) {
  238. char buffer[LUA_MAXINPUT];
  239. char *b = buffer;
  240. size_t l;
  241. const char *prmt = get_prompt(L, firstline);
  242. int readstatus = lua_readline(L, b, prmt);
  243. if (readstatus == 0)
  244. return 0; /* no input (prompt will be popped by caller) */
  245. lua_pop(L, 1); /* remove prompt */
  246. l = strlen(b);
  247. if (l > 0 && b[l-1] == '\n') /* line ends with newline? */
  248. b[--l] = '\0'; /* remove it */
  249. if (firstline && b[0] == '=') /* for compatibility with 5.2, ... */
  250. lua_pushfstring(L, "return %s", b + 1); /* change '=' to 'return' */
  251. else
  252. lua_pushlstring(L, b, l);
  253. lua_freeline(L, b);
  254. return 1;
  255. }
  256. /*
  257. ** Try to compile line on the stack as 'return <line>'; on return, stack
  258. ** has either compiled chunk or original line (if compilation failed).
  259. */
  260. static int addreturn (lua_State *L) {
  261. int status;
  262. size_t len; const char *line;
  263. lua_pushliteral(L, "return ");
  264. lua_pushvalue(L, -2); /* duplicate line */
  265. lua_concat(L, 2); /* new line is "return ..." */
  266. line = lua_tolstring(L, -1, &len);
  267. if ((status = luaL_loadbuffer(L, line, len, "=stdin")) == LUA_OK) {
  268. lua_remove(L, -3); /* remove original line */
  269. line += sizeof("return")/sizeof(char); /* remove 'return' for history */
  270. if (line[0] != '\0') /* non empty? */
  271. lua_saveline(L, line); /* keep history */
  272. }
  273. else
  274. lua_pop(L, 2); /* remove result from 'luaL_loadbuffer' and new line */
  275. return status;
  276. }
  277. /*
  278. ** Read multiple lines until a complete Lua statement
  279. */
  280. static int multiline (lua_State *L) {
  281. for (;;) { /* repeat until gets a complete statement */
  282. size_t len;
  283. const char *line = lua_tolstring(L, 1, &len); /* get what it has */
  284. int status = luaL_loadbuffer(L, line, len, "=stdin"); /* try it */
  285. if (!incomplete(L, status) || !pushline(L, 0)) {
  286. lua_saveline(L, line); /* keep history */
  287. return status; /* cannot or should not try to add continuation line */
  288. }
  289. lua_pushliteral(L, "\n"); /* add newline... */
  290. lua_insert(L, -2); /* ...between the two lines */
  291. lua_concat(L, 3); /* join them */
  292. }
  293. }
  294. /*
  295. ** Read a line and try to load (compile) it first as an expression (by
  296. ** adding "return " in front of it) and second as a statement. Return
  297. ** the final status of load/call with the resulting function (if any)
  298. ** in the top of the stack.
  299. */
  300. static int loadline (lua_State *L) {
  301. int status;
  302. lua_settop(L, 0);
  303. if (!pushline(L, 1))
  304. return -1; /* no input */
  305. if ((status = addreturn(L)) != LUA_OK) /* 'return ...' did not work? */
  306. status = multiline(L); /* try as command, maybe with continuation lines */
  307. lua_remove(L, 1); /* remove line from the stack */
  308. lua_assert(lua_gettop(L) == 1);
  309. return status;
  310. }
  311. /*
  312. ** Prints (calling the Lua 'print' function) any values on the stack
  313. */
  314. static void l_print (lua_State *L) {
  315. int n = lua_gettop(L);
  316. if (n > 0) { /* any result to be printed? */
  317. luaL_checkstack(L, LUA_MINSTACK, "too many results to print");
  318. lua_getglobal(L, "print");
  319. lua_insert(L, 1);
  320. if (lua_pcall(L, n, 0, 0) != LUA_OK)
  321. l_message(progname, lua_pushfstring(L, "error calling 'print' (%s)",
  322. lua_tostring(L, -1)));
  323. }
  324. }
  325. /*
  326. ** Do the REPL: repeatedly read (load) a line, evaluate (call) it, and
  327. ** print any results.
  328. */
  329. static void doREPL (lua_State *L) {
  330. int status;
  331. const char *oldprogname = progname;
  332. progname = NULL; /* no 'progname' on errors in interactive mode */
  333. while ((status = loadline(L)) != -1) {
  334. if (status == LUA_OK)
  335. status = docall(L, 0, LUA_MULTRET);
  336. if (status == LUA_OK) l_print(L);
  337. else report(L, status);
  338. }
  339. lua_settop(L, 0); /* clear stack */
  340. lua_writeline();
  341. progname = oldprogname;
  342. }
  343. /*
  344. ** Push on the stack the contents of table 'arg' from 1 to #arg
  345. */
  346. static int pushargs (lua_State *L) {
  347. int i, n;
  348. if (lua_getglobal(L, "arg") != LUA_TTABLE)
  349. luaL_error(L, "'arg' is not a table");
  350. n = (int)luaL_len(L, -1);
  351. luaL_checkstack(L, n + 3, "too many arguments to script");
  352. for (i = 1; i <= n; i++)
  353. lua_rawgeti(L, -i, i);
  354. lua_remove(L, -i); /* remove table from the stack */
  355. return n;
  356. }
  357. static int handle_script (lua_State *L, char **argv) {
  358. int status;
  359. const char *fname = argv[0];
  360. if (strcmp(fname, "-") == 0 && strcmp(argv[-1], "--") != 0)
  361. fname = NULL; /* stdin */
  362. status = luaL_loadfile(L, fname);
  363. if (status == LUA_OK) {
  364. int n = pushargs(L); /* push arguments to script */
  365. status = docall(L, n, LUA_MULTRET);
  366. }
  367. return report(L, status);
  368. }
  369. /* bits of various argument indicators in 'args' */
  370. #define has_error 1 /* bad option */
  371. #define has_i 2 /* -i */
  372. #define has_v 4 /* -v */
  373. #define has_e 8 /* -e */
  374. #define has_E 16 /* -E */
  375. /*
  376. ** Traverses all arguments from 'argv', returning a mask with those
  377. ** needed before running any Lua code (or an error code if it finds
  378. ** any invalid argument). 'first' returns the first not-handled argument
  379. ** (either the script name or a bad argument in case of error).
  380. */
  381. static int collectargs (char **argv, int *first) {
  382. int args = 0;
  383. int i;
  384. for (i = 1; argv[i] != NULL; i++) {
  385. *first = i;
  386. if (argv[i][0] != '-') /* not an option? */
  387. return args; /* stop handling options */
  388. switch (argv[i][1]) { /* else check option */
  389. case '-': /* '--' */
  390. if (argv[i][2] != '\0') /* extra characters after '--'? */
  391. return has_error; /* invalid option */
  392. *first = i + 1;
  393. return args;
  394. case '\0': /* '-' */
  395. return args; /* script "name" is '-' */
  396. case 'E':
  397. if (argv[i][2] != '\0') /* extra characters after 1st? */
  398. return has_error; /* invalid option */
  399. args |= has_E;
  400. break;
  401. case 'i':
  402. args |= has_i; /* (-i implies -v) *//* FALLTHROUGH */
  403. case 'v':
  404. if (argv[i][2] != '\0') /* extra characters after 1st? */
  405. return has_error; /* invalid option */
  406. args |= has_v;
  407. break;
  408. case 'e':
  409. args |= has_e; /* FALLTHROUGH */
  410. case 'l': /* both options need an argument */
  411. if (argv[i][2] == '\0') { /* no concatenated argument? */
  412. i++; /* try next 'argv' */
  413. if (argv[i] == NULL || argv[i][0] == '-')
  414. return has_error; /* no next argument or it is another option */
  415. }
  416. break;
  417. default: /* invalid option */
  418. return has_error;
  419. }
  420. }
  421. *first = i; /* no script name */
  422. return args;
  423. }
  424. /*
  425. ** Processes options 'e' and 'l', which involve running Lua code.
  426. ** Returns 0 if some code raises an error.
  427. */
  428. static int runargs (lua_State *L, char **argv, int n) {
  429. int i;
  430. for (i = 1; i < n; i++) {
  431. int option = argv[i][1];
  432. lua_assert(argv[i][0] == '-'); /* already checked */
  433. if (option == 'e' || option == 'l') {
  434. int status;
  435. const char *extra = argv[i] + 2; /* both options need an argument */
  436. if (*extra == '\0') extra = argv[++i];
  437. lua_assert(extra != NULL);
  438. status = (option == 'e')
  439. ? dostring(L, extra, "=(command line)")
  440. : dolibrary(L, extra);
  441. if (status != LUA_OK) return 0;
  442. }
  443. }
  444. return 1;
  445. }
  446. static int handle_luainit (lua_State *L) {
  447. const char *name = "=" LUA_INITVARVERSION;
  448. const char *init = getenv(name + 1);
  449. if (init == NULL) {
  450. name = "=" LUA_INIT_VAR;
  451. init = getenv(name + 1); /* try alternative name */
  452. }
  453. if (init == NULL) return LUA_OK;
  454. else if (init[0] == '@')
  455. return dofile(L, init+1);
  456. else
  457. return dostring(L, init, name);
  458. }
  459. /*
  460. ** Main body of stand-alone interpreter (to be called in protected mode).
  461. ** Reads the options and handles them all.
  462. */
  463. static int pmain (lua_State *L) {
  464. int argc = (int)lua_tointeger(L, 1);
  465. char **argv = (char **)lua_touserdata(L, 2);
  466. int script;
  467. int args = collectargs(argv, &script);
  468. luaL_checkversion(L); /* check that interpreter has correct version */
  469. if (argv[0] && argv[0][0]) progname = argv[0];
  470. if (args == has_error) { /* bad arg? */
  471. print_usage(argv[script]); /* 'script' has index of bad arg. */
  472. return 0;
  473. }
  474. if (args & has_v) /* option '-v'? */
  475. print_version();
  476. if (args & has_E) { /* option '-E'? */
  477. lua_pushboolean(L, 1); /* signal for libraries to ignore env. vars. */
  478. lua_setfield(L, LUA_REGISTRYINDEX, "LUA_NOENV");
  479. }
  480. luaL_openlibs(L); /* open standard libraries */
  481. createargtable(L, argv, argc, script); /* create table 'arg' */
  482. if (!(args & has_E)) { /* no option '-E'? */
  483. if (handle_luainit(L) != LUA_OK) /* run LUA_INIT */
  484. return 0; /* error running LUA_INIT */
  485. }
  486. if (!runargs(L, argv, script)) /* execute arguments -e and -l */
  487. return 0; /* something failed */
  488. if (script < argc && /* execute main script (if there is one) */
  489. handle_script(L, argv + script) != LUA_OK)
  490. return 0;
  491. if (args & has_i) /* -i option? */
  492. doREPL(L); /* do read-eval-print loop */
  493. else if (script == argc && !(args & (has_e | has_v))) { /* no arguments? */
  494. if (lua_stdin_is_tty()) { /* running in interactive mode? */
  495. print_version();
  496. doREPL(L); /* do read-eval-print loop */
  497. }
  498. else dofile(L, NULL); /* executes stdin as a file */
  499. }
  500. lua_pushboolean(L, 1); /* signal no errors */
  501. return 1;
  502. }
  503. int main (int argc, char **argv) {
  504. int status, result;
  505. lua_State *L = luaL_newstate(); /* create state */
  506. if (L == NULL) {
  507. l_message(argv[0], "cannot create state: not enough memory");
  508. return EXIT_FAILURE;
  509. }
  510. lua_pushcfunction(L, &pmain); /* to call 'pmain' in protected mode */
  511. lua_pushinteger(L, argc); /* 1st argument */
  512. lua_pushlightuserdata(L, argv); /* 2nd argument */
  513. status = lua_pcall(L, 2, 1, 0); /* do the call */
  514. result = lua_toboolean(L, -1); /* get result */
  515. report(L, status);
  516. lua_close(L);
  517. return (result && status == LUA_OK) ? EXIT_SUCCESS : EXIT_FAILURE;
  518. }