lua.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  1. /*
  2. ** $Id: lua.c,v 1.209 2014/02/05 14:22:55 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. static void lstop (lua_State *L, lua_Debug *ar) {
  71. (void)ar; /* unused arg. */
  72. lua_sethook(L, NULL, 0, 0);
  73. luaL_error(L, "interrupted!");
  74. }
  75. static void laction (int i) {
  76. signal(i, SIG_DFL); /* if another SIGINT happens before lstop,
  77. terminate process (default action) */
  78. lua_sethook(globalL, lstop, LUA_MASKCALL | LUA_MASKRET | LUA_MASKCOUNT, 1);
  79. }
  80. static void print_usage (const char *badoption) {
  81. luai_writestringerror("%s: ", progname);
  82. if (badoption[1] == 'e' || badoption[1] == 'l')
  83. luai_writestringerror("'%s' needs argument\n", badoption);
  84. else
  85. luai_writestringerror("unrecognized option '%s'\n", badoption);
  86. luai_writestringerror(
  87. "usage: %s [options] [script [args]]\n"
  88. "Available options are:\n"
  89. " -e stat execute string " LUA_QL("stat") "\n"
  90. " -i enter interactive mode after executing " LUA_QL("script") "\n"
  91. " -l name require library " LUA_QL("name") "\n"
  92. " -v show version information\n"
  93. " -E ignore environment variables\n"
  94. " -- stop handling options\n"
  95. " - stop handling options and execute stdin\n"
  96. ,
  97. progname);
  98. }
  99. static void l_message (const char *pname, const char *msg) {
  100. if (pname) luai_writestringerror("%s: ", pname);
  101. luai_writestringerror("%s\n", msg);
  102. }
  103. static int report (lua_State *L, int status) {
  104. if (status != LUA_OK && !lua_isnil(L, -1)) {
  105. const char *msg = lua_tostring(L, -1);
  106. if (msg == NULL) msg = "(error object is not a string)";
  107. l_message(progname, msg);
  108. lua_pop(L, 1);
  109. /* force a complete garbage collection in case of errors */
  110. lua_gc(L, LUA_GCCOLLECT, 0);
  111. }
  112. return status;
  113. }
  114. /* the next function is called unprotected, so it must avoid errors */
  115. static void finalreport (lua_State *L, int status) {
  116. if (status != LUA_OK) {
  117. const char *msg = (lua_type(L, -1) == LUA_TSTRING) ? lua_tostring(L, -1)
  118. : NULL;
  119. if (msg == NULL) msg = "(error object is not a string)";
  120. l_message(progname, msg);
  121. lua_pop(L, 1);
  122. }
  123. }
  124. static int traceback (lua_State *L) {
  125. const char *msg = lua_tostring(L, 1);
  126. if (msg)
  127. luaL_traceback(L, L, msg, 1);
  128. else if (!lua_isnoneornil(L, 1)) { /* is there an error object? */
  129. if (!luaL_callmeta(L, 1, "__tostring")) /* try its 'tostring' metamethod */
  130. lua_pushliteral(L, "(no error message)");
  131. }
  132. return 1;
  133. }
  134. static int docall (lua_State *L, int narg, int nres) {
  135. int status;
  136. int base = lua_gettop(L) - narg; /* function index */
  137. lua_pushcfunction(L, traceback); /* push traceback function */
  138. lua_insert(L, base); /* put it under chunk and args */
  139. globalL = L; /* to be available to 'laction' */
  140. signal(SIGINT, laction);
  141. status = lua_pcall(L, narg, nres, base);
  142. signal(SIGINT, SIG_DFL);
  143. lua_remove(L, base); /* remove traceback function */
  144. return status;
  145. }
  146. static void print_version (void) {
  147. luai_writestring(LUA_COPYRIGHT, strlen(LUA_COPYRIGHT));
  148. luai_writeline();
  149. }
  150. static int getargs (lua_State *L, char **argv, int n) {
  151. int narg;
  152. int i;
  153. int argc = 0;
  154. while (argv[argc]) argc++; /* count total number of arguments */
  155. narg = argc - (n + 1); /* number of arguments to the script */
  156. luaL_checkstack(L, narg + 3, "too many arguments to script");
  157. for (i=n+1; i < argc; i++)
  158. lua_pushstring(L, argv[i]);
  159. lua_createtable(L, narg, n + 1);
  160. for (i=0; i < argc; i++) {
  161. lua_pushstring(L, argv[i]);
  162. lua_rawseti(L, -2, i - n);
  163. }
  164. return narg;
  165. }
  166. static int dofile (lua_State *L, const char *name) {
  167. int status = luaL_loadfile(L, name);
  168. if (status == LUA_OK) status = docall(L, 0, 0);
  169. return report(L, status);
  170. }
  171. static int dostring (lua_State *L, const char *s, const char *name) {
  172. int status = luaL_loadbuffer(L, s, strlen(s), name);
  173. if (status == LUA_OK) status = docall(L, 0, 0);
  174. return report(L, status);
  175. }
  176. static int dolibrary (lua_State *L, const char *name) {
  177. int status;
  178. lua_getglobal(L, "require");
  179. lua_pushstring(L, name);
  180. status = docall(L, 1, 1); /* call 'require(name)' */
  181. if (status == LUA_OK)
  182. lua_setglobal(L, name); /* global[name] = require return */
  183. return report(L, status);
  184. }
  185. static const char *get_prompt (lua_State *L, int firstline) {
  186. const char *p;
  187. lua_getglobal(L, firstline ? "_PROMPT" : "_PROMPT2");
  188. p = lua_tostring(L, -1);
  189. if (p == NULL) p = (firstline ? LUA_PROMPT : LUA_PROMPT2);
  190. return p;
  191. }
  192. /* mark in error messages for incomplete statements */
  193. #define EOFMARK "<eof>"
  194. #define marklen (sizeof(EOFMARK)/sizeof(char) - 1)
  195. static int incomplete (lua_State *L, int status) {
  196. if (status == LUA_ERRSYNTAX) {
  197. size_t lmsg;
  198. const char *msg = lua_tolstring(L, -1, &lmsg);
  199. if (lmsg >= marklen && strcmp(msg + lmsg - marklen, EOFMARK) == 0) {
  200. lua_pop(L, 1);
  201. return 1;
  202. }
  203. }
  204. return 0; /* else... */
  205. }
  206. /* prompt the user, read a line, and push it into the Lua stack */
  207. static int pushline (lua_State *L, int firstline) {
  208. char buffer[LUA_MAXINPUT];
  209. char *b = buffer;
  210. size_t l;
  211. const char *prmt = get_prompt(L, firstline);
  212. int readstatus = lua_readline(L, b, prmt);
  213. if (readstatus == 0)
  214. return 0; /* no input (prompt will be popped by caller) */
  215. lua_pop(L, 1); /* remove prompt */
  216. l = strlen(b);
  217. if (l > 0 && b[l-1] == '\n') /* line ends with newline? */
  218. b[l-1] = '\0'; /* remove it */
  219. if (firstline && b[0] == '=') /* for compatibility with 5.2, ... */
  220. lua_pushfstring(L, "return %s", b + 1); /* change '=' to 'return' */
  221. else
  222. lua_pushstring(L, b);
  223. lua_freeline(L, b);
  224. return 1;
  225. }
  226. /* try to compile line on the stack as 'return <line>'; on return, stack
  227. has either compiled chunk or original line (if compilation failed) */
  228. static int addreturn (lua_State *L) {
  229. int status;
  230. size_t len; const char *line;
  231. lua_pushliteral(L, "return ");
  232. lua_pushvalue(L, -2); /* duplicate line */
  233. lua_concat(L, 2); /* new line is "return ..." */
  234. line = lua_tolstring(L, -1, &len);
  235. if ((status = luaL_loadbuffer(L, line, len, "=stdin")) == LUA_OK)
  236. lua_remove(L, -3); /* remove original line */
  237. else
  238. lua_pop(L, 2); /* remove result from 'luaL_loadbuffer' and new line */
  239. return status;
  240. }
  241. /* read multiple lines until a complete line */
  242. static int multiline (lua_State *L) {
  243. for (;;) { /* repeat until gets a complete line */
  244. size_t len;
  245. const char *line = lua_tolstring(L, 1, &len); /* get what it has */
  246. int status = luaL_loadbuffer(L, line, len, "=stdin"); /* try it */
  247. if (!incomplete(L, status) || !pushline(L, 0))
  248. return status; /* cannot/should not try to add continuation line */
  249. lua_pushliteral(L, "\n"); /* add newline... */
  250. lua_insert(L, -2); /* ...between the two lines */
  251. lua_concat(L, 3); /* join them */
  252. }
  253. }
  254. static int loadline (lua_State *L) {
  255. int status;
  256. lua_settop(L, 0);
  257. if (!pushline(L, 1))
  258. return -1; /* no input */
  259. if ((status = addreturn(L)) != LUA_OK) /* 'return ...' did not work? */
  260. status = multiline(L); /* try as command, maybe with continuation lines */
  261. lua_saveline(L, 1);
  262. lua_remove(L, 1); /* remove line */
  263. lua_assert(lua_gettop(L) == 1);
  264. return status;
  265. }
  266. static void dotty (lua_State *L) {
  267. int status;
  268. const char *oldprogname = progname;
  269. progname = NULL;
  270. while ((status = loadline(L)) != -1) {
  271. if (status == LUA_OK) status = docall(L, 0, LUA_MULTRET);
  272. report(L, status);
  273. if (status == LUA_OK && lua_gettop(L) > 0) { /* any result to print? */
  274. luaL_checkstack(L, LUA_MINSTACK, "too many results to print");
  275. lua_getglobal(L, "print");
  276. lua_insert(L, 1);
  277. if (lua_pcall(L, lua_gettop(L)-1, 0, 0) != LUA_OK)
  278. l_message(progname, lua_pushfstring(L,
  279. "error calling " LUA_QL("print") " (%s)",
  280. lua_tostring(L, -1)));
  281. }
  282. }
  283. lua_settop(L, 0); /* clear stack */
  284. luai_writeline();
  285. progname = oldprogname;
  286. }
  287. static int handle_script (lua_State *L, char **argv, int n) {
  288. int status;
  289. const char *fname;
  290. int narg = getargs(L, argv, n); /* collect arguments */
  291. lua_setglobal(L, "arg");
  292. fname = argv[n];
  293. if (strcmp(fname, "-") == 0 && strcmp(argv[n-1], "--") != 0)
  294. fname = NULL; /* stdin */
  295. status = luaL_loadfile(L, fname);
  296. lua_insert(L, -(narg+1));
  297. if (status == LUA_OK)
  298. status = docall(L, narg, LUA_MULTRET);
  299. else
  300. lua_pop(L, narg);
  301. return report(L, status);
  302. }
  303. /* check that argument has no extra characters at the end */
  304. #define noextrachars(x) {if ((x)[2] != '\0') return -1;}
  305. /* indices of various argument indicators in array args */
  306. #define has_i 0 /* -i */
  307. #define has_v 1 /* -v */
  308. #define has_e 2 /* -e */
  309. #define has_E 3 /* -E */
  310. #define num_has 4 /* number of 'has_*' */
  311. static int collectargs (char **argv, int *args) {
  312. int i;
  313. for (i = 1; argv[i] != NULL; i++) {
  314. if (argv[i][0] != '-') /* not an option? */
  315. return i;
  316. switch (argv[i][1]) { /* option */
  317. case '-':
  318. noextrachars(argv[i]);
  319. return (argv[i+1] != NULL ? i+1 : 0);
  320. case '\0':
  321. return i;
  322. case 'E':
  323. args[has_E] = 1;
  324. break;
  325. case 'i':
  326. noextrachars(argv[i]);
  327. args[has_i] = 1; /* go through */
  328. case 'v':
  329. noextrachars(argv[i]);
  330. args[has_v] = 1;
  331. break;
  332. case 'e':
  333. args[has_e] = 1; /* go through */
  334. case 'l': /* both options need an argument */
  335. if (argv[i][2] == '\0') { /* no concatenated argument? */
  336. i++; /* try next 'argv' */
  337. if (argv[i] == NULL || argv[i][0] == '-')
  338. return -(i - 1); /* no next argument or it is another option */
  339. }
  340. break;
  341. default: /* invalid option; return its index... */
  342. return -i; /* ...as a negative value */
  343. }
  344. }
  345. return 0;
  346. }
  347. static int runargs (lua_State *L, char **argv, int n) {
  348. int i;
  349. for (i = 1; i < n; i++) {
  350. lua_assert(argv[i][0] == '-');
  351. switch (argv[i][1]) { /* option */
  352. case 'e': {
  353. const char *chunk = argv[i] + 2;
  354. if (*chunk == '\0') chunk = argv[++i];
  355. lua_assert(chunk != NULL);
  356. if (dostring(L, chunk, "=(command line)") != LUA_OK)
  357. return 0;
  358. break;
  359. }
  360. case 'l': {
  361. const char *filename = argv[i] + 2;
  362. if (*filename == '\0') filename = argv[++i];
  363. lua_assert(filename != NULL);
  364. if (dolibrary(L, filename) != LUA_OK)
  365. return 0; /* stop if file fails */
  366. break;
  367. }
  368. default: break;
  369. }
  370. }
  371. return 1;
  372. }
  373. static int handle_luainit (lua_State *L) {
  374. const char *name = "=" LUA_INITVARVERSION;
  375. const char *init = getenv(name + 1);
  376. if (init == NULL) {
  377. name = "=" LUA_INIT_VAR;
  378. init = getenv(name + 1); /* try alternative name */
  379. }
  380. if (init == NULL) return LUA_OK;
  381. else if (init[0] == '@')
  382. return dofile(L, init+1);
  383. else
  384. return dostring(L, init, name);
  385. }
  386. static int pmain (lua_State *L) {
  387. int argc = (int)lua_tointeger(L, 1);
  388. char **argv = (char **)lua_touserdata(L, 2);
  389. int script;
  390. int args[num_has];
  391. args[has_i] = args[has_v] = args[has_e] = args[has_E] = 0;
  392. if (argv[0] && argv[0][0]) progname = argv[0];
  393. script = collectargs(argv, args);
  394. if (script < 0) { /* invalid arg? */
  395. print_usage(argv[-script]);
  396. return 0;
  397. }
  398. if (args[has_v]) print_version();
  399. if (args[has_E]) { /* option '-E'? */
  400. lua_pushboolean(L, 1); /* signal for libraries to ignore env. vars. */
  401. lua_setfield(L, LUA_REGISTRYINDEX, "LUA_NOENV");
  402. }
  403. /* open standard libraries */
  404. luaL_checkversion(L);
  405. lua_gc(L, LUA_GCSTOP, 0); /* stop collector during initialization */
  406. luaL_openlibs(L); /* open libraries */
  407. lua_gc(L, LUA_GCRESTART, 0);
  408. if (!args[has_E] && handle_luainit(L) != LUA_OK)
  409. return 0; /* error running LUA_INIT */
  410. /* execute arguments -e and -l */
  411. if (!runargs(L, argv, (script > 0) ? script : argc)) return 0;
  412. /* execute main script (if there is one) */
  413. if (script && handle_script(L, argv, script) != LUA_OK) return 0;
  414. if (args[has_i]) /* -i option? */
  415. dotty(L);
  416. else if (script == 0 && !args[has_e] && !args[has_v]) { /* no arguments? */
  417. if (lua_stdin_is_tty()) {
  418. print_version();
  419. dotty(L);
  420. }
  421. else dofile(L, NULL); /* executes stdin as a file */
  422. }
  423. lua_pushboolean(L, 1); /* signal no errors */
  424. return 1;
  425. }
  426. int main (int argc, char **argv) {
  427. int status, result;
  428. lua_State *L = luaL_newstate(); /* create state */
  429. if (L == NULL) {
  430. l_message(argv[0], "cannot create state: not enough memory");
  431. return EXIT_FAILURE;
  432. }
  433. /* call 'pmain' in protected mode */
  434. lua_pushcfunction(L, &pmain);
  435. lua_pushinteger(L, argc); /* 1st argument */
  436. lua_pushlightuserdata(L, argv); /* 2nd argument */
  437. status = lua_pcall(L, 2, 1, 0);
  438. result = lua_toboolean(L, -1); /* get result */
  439. finalreport(L, status);
  440. lua_close(L);
  441. return (result && status == LUA_OK) ? EXIT_SUCCESS : EXIT_FAILURE;
  442. }