2
0

lua.c 18 KB

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