2
0

lua.c 18 KB

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