lua.c 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  1. /*
  2. ** $Id: lua.c,v 1.168 2007/09/05 17:17:39 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. static lua_State *globalL = NULL;
  15. static const char *progname = LUA_PROGNAME;
  16. static void lstop (lua_State *L, lua_Debug *ar) {
  17. (void)ar; /* unused arg. */
  18. lua_sethook(L, NULL, 0, 0);
  19. luaL_error(L, "interrupted!");
  20. }
  21. static void laction (int i) {
  22. signal(i, SIG_DFL); /* if another SIGINT happens before lstop,
  23. terminate process (default action) */
  24. lua_sethook(globalL, lstop, LUA_MASKCALL | LUA_MASKRET | LUA_MASKCOUNT, 1);
  25. }
  26. static void print_usage (void) {
  27. fprintf(stderr,
  28. "usage: %s [options] [script [args]]\n"
  29. "Available options are:\n"
  30. " -e stat execute string " LUA_QL("stat") "\n"
  31. " -l name require library " LUA_QL("name") "\n"
  32. " -i enter interactive mode after executing " LUA_QL("script") "\n"
  33. " -v show version information\n"
  34. " -- stop handling options\n"
  35. " - execute stdin and stop handling options\n"
  36. ,
  37. progname);
  38. fflush(stderr);
  39. }
  40. static void l_message (const char *pname, const char *msg) {
  41. if (pname) fprintf(stderr, "%s: ", pname);
  42. fprintf(stderr, "%s\n", msg);
  43. fflush(stderr);
  44. }
  45. static int report (lua_State *L, int status) {
  46. if (status != LUA_OK && !lua_isnil(L, -1)) {
  47. const char *msg = lua_tostring(L, -1);
  48. if (msg == NULL) msg = "(error object is not a string)";
  49. l_message(progname, msg);
  50. lua_pop(L, 1);
  51. /* force a complete garbage collection in case of errors */
  52. lua_gc(L, LUA_GCCOLLECT, 0);
  53. }
  54. return status;
  55. }
  56. static int traceback (lua_State *L) {
  57. const char *msg = lua_tostring(L, 1);
  58. if (msg)
  59. luaL_traceback(L, L, msg, 1);
  60. else if (!lua_isnoneornil(L, 1)) { /* is there an error object? */
  61. if (!luaL_callmeta(L, 1, "__tostring")) /* try its 'tostring' metamethod */
  62. lua_pushliteral(L, "(no error message)");
  63. }
  64. return 1;
  65. }
  66. static int docall (lua_State *L, int narg, int clear) {
  67. int status;
  68. int base = lua_gettop(L) - narg; /* function index */
  69. lua_pushcfunction(L, traceback); /* push traceback function */
  70. lua_insert(L, base); /* put it under chunk and args */
  71. globalL = L; /* to be available to 'laction' */
  72. signal(SIGINT, laction);
  73. status = lua_pcall(L, narg, (clear ? 0 : LUA_MULTRET), base);
  74. signal(SIGINT, SIG_DFL);
  75. lua_remove(L, base); /* remove traceback function */
  76. return status;
  77. }
  78. static void print_version (void) {
  79. l_message(NULL, LUA_COPYRIGHT);
  80. }
  81. static int getargs (lua_State *L, char **argv, int n) {
  82. int narg;
  83. int i;
  84. int argc = 0;
  85. while (argv[argc]) argc++; /* count total number of arguments */
  86. narg = argc - (n + 1); /* number of arguments to the script */
  87. luaL_checkstack(L, narg + 3, "too many arguments to script");
  88. for (i=n+1; i < argc; i++)
  89. lua_pushstring(L, argv[i]);
  90. lua_createtable(L, narg, n + 1);
  91. for (i=0; i < argc; i++) {
  92. lua_pushstring(L, argv[i]);
  93. lua_rawseti(L, -2, i - n);
  94. }
  95. return narg;
  96. }
  97. static int dofile (lua_State *L, const char *name) {
  98. int status = luaL_loadfile(L, name);
  99. if (status == LUA_OK) status = docall(L, 0, 1);
  100. return report(L, status);
  101. }
  102. static int dostring (lua_State *L, const char *s, const char *name) {
  103. int status = luaL_loadbuffer(L, s, strlen(s), name);
  104. if (status == LUA_OK) status = docall(L, 0, 1);
  105. return report(L, status);
  106. }
  107. static int dolibrary (lua_State *L, const char *name) {
  108. lua_getglobal(L, "require");
  109. lua_pushstring(L, name);
  110. return report(L, docall(L, 1, 1));
  111. }
  112. static const char *get_prompt (lua_State *L, int firstline) {
  113. const char *p;
  114. lua_getfield(L, LUA_GLOBALSINDEX, firstline ? "_PROMPT" : "_PROMPT2");
  115. p = lua_tostring(L, -1);
  116. if (p == NULL) p = (firstline ? LUA_PROMPT : LUA_PROMPT2);
  117. lua_pop(L, 1); /* remove global */
  118. return p;
  119. }
  120. /* mark in error messages for incomplete statements */
  121. #define mark "<eof>"
  122. #define marklen (sizeof(mark) - 1)
  123. static int incomplete (lua_State *L, int status) {
  124. if (status == LUA_ERRSYNTAX) {
  125. size_t lmsg;
  126. const char *msg = lua_tolstring(L, -1, &lmsg);
  127. if (lmsg >= marklen && strcmp(msg + lmsg - marklen, mark) == 0) {
  128. lua_pop(L, 1);
  129. return 1;
  130. }
  131. }
  132. return 0; /* else... */
  133. }
  134. static int pushline (lua_State *L, int firstline) {
  135. char buffer[LUA_MAXINPUT];
  136. char *b = buffer;
  137. size_t l;
  138. const char *prmt = get_prompt(L, firstline);
  139. if (lua_readline(L, b, prmt) == 0)
  140. return 0; /* no input */
  141. l = strlen(b);
  142. if (l > 0 && b[l-1] == '\n') /* line ends with newline? */
  143. b[l-1] = '\0'; /* remove it */
  144. if (firstline && b[0] == '=') /* first line starts with `=' ? */
  145. lua_pushfstring(L, "return %s", b+1); /* change it to `return' */
  146. else
  147. lua_pushstring(L, b);
  148. lua_freeline(L, b);
  149. return 1;
  150. }
  151. static int loadline (lua_State *L) {
  152. int status;
  153. lua_settop(L, 0);
  154. if (!pushline(L, 1))
  155. return -1; /* no input */
  156. for (;;) { /* repeat until gets a complete line */
  157. status = luaL_loadbuffer(L, lua_tostring(L, 1), lua_objlen(L, 1), "=stdin");
  158. if (!incomplete(L, status)) break; /* cannot try to add lines? */
  159. if (!pushline(L, 0)) /* no more input? */
  160. return -1;
  161. lua_pushliteral(L, "\n"); /* add a new line... */
  162. lua_insert(L, -2); /* ...between the two lines */
  163. lua_concat(L, 3); /* join them */
  164. }
  165. lua_saveline(L, 1);
  166. lua_remove(L, 1); /* remove line */
  167. return status;
  168. }
  169. static void dotty (lua_State *L) {
  170. int status;
  171. const char *oldprogname = progname;
  172. progname = NULL;
  173. while ((status = loadline(L)) != -1) {
  174. if (status == LUA_OK) status = docall(L, 0, 0);
  175. report(L, status);
  176. if (status == LUA_OK && lua_gettop(L) > 0) { /* any result to print? */
  177. lua_getglobal(L, "print");
  178. lua_insert(L, 1);
  179. if (lua_pcall(L, lua_gettop(L)-1, 0, 0) != LUA_OK)
  180. l_message(progname, lua_pushfstring(L,
  181. "error calling " LUA_QL("print") " (%s)",
  182. lua_tostring(L, -1)));
  183. }
  184. }
  185. lua_settop(L, 0); /* clear stack */
  186. fputs("\n", stdout);
  187. fflush(stdout);
  188. progname = oldprogname;
  189. }
  190. static int handle_script (lua_State *L, char **argv, int n) {
  191. int status;
  192. const char *fname;
  193. int narg = getargs(L, argv, n); /* collect arguments */
  194. lua_setglobal(L, "arg");
  195. fname = argv[n];
  196. if (strcmp(fname, "-") == 0 && strcmp(argv[n-1], "--") != 0)
  197. fname = NULL; /* stdin */
  198. status = luaL_loadfile(L, fname);
  199. lua_insert(L, -(narg+1));
  200. if (status == LUA_OK)
  201. status = docall(L, narg, 0);
  202. else
  203. lua_pop(L, narg);
  204. return report(L, status);
  205. }
  206. /* check that argument has no extra characters at the end */
  207. #define notail(x) {if ((x)[2] != '\0') return -1;}
  208. static int collectargs (char **argv, int *pi, int *pv, int *pe) {
  209. int i;
  210. for (i = 1; argv[i] != NULL; i++) {
  211. if (argv[i][0] != '-') /* not an option? */
  212. return i;
  213. switch (argv[i][1]) { /* option */
  214. case '-':
  215. notail(argv[i]);
  216. return (argv[i+1] != NULL ? i+1 : 0);
  217. case '\0':
  218. return i;
  219. case 'i':
  220. notail(argv[i]);
  221. *pi = 1; /* go through */
  222. case 'v':
  223. notail(argv[i]);
  224. *pv = 1;
  225. break;
  226. case 'e':
  227. *pe = 1; /* go through */
  228. case 'l':
  229. if (argv[i][2] == '\0') {
  230. i++;
  231. if (argv[i] == NULL) return -1;
  232. }
  233. break;
  234. default: return -1; /* invalid option */
  235. }
  236. }
  237. return 0;
  238. }
  239. static int runargs (lua_State *L, char **argv, int n) {
  240. int i;
  241. for (i = 1; i < n; i++) {
  242. if (argv[i] == NULL) continue;
  243. lua_assert(argv[i][0] == '-');
  244. switch (argv[i][1]) { /* option */
  245. case 'e': {
  246. const char *chunk = argv[i] + 2;
  247. if (*chunk == '\0') chunk = argv[++i];
  248. lua_assert(chunk != NULL);
  249. if (dostring(L, chunk, "=(command line)") != LUA_OK)
  250. return 0;
  251. break;
  252. }
  253. case 'l': {
  254. const char *filename = argv[i] + 2;
  255. if (*filename == '\0') filename = argv[++i];
  256. lua_assert(filename != NULL);
  257. if (dolibrary(L, filename) != LUA_OK)
  258. return 0; /* stop if file fails */
  259. break;
  260. }
  261. default: break;
  262. }
  263. }
  264. return 1;
  265. }
  266. static int handle_luainit (lua_State *L) {
  267. const char *init = getenv(LUA_INIT);
  268. if (init == NULL) return LUA_OK;
  269. else if (init[0] == '@')
  270. return dofile(L, init+1);
  271. else
  272. return dostring(L, init, "=" LUA_INIT);
  273. }
  274. struct Smain {
  275. int argc;
  276. char **argv;
  277. int ok;
  278. };
  279. static int pmain (lua_State *L) {
  280. struct Smain *s = (struct Smain *)lua_touserdata(L, 1);
  281. char **argv = s->argv;
  282. int script;
  283. int has_i = 0, has_v = 0, has_e = 0;
  284. if (argv[0] && argv[0][0]) progname = argv[0];
  285. lua_gc(L, LUA_GCSTOP, 0); /* stop collector during initialization */
  286. luaL_openlibs(L); /* open libraries */
  287. lua_gc(L, LUA_GCRESTART, 0);
  288. s->ok = (handle_luainit(L) == LUA_OK);
  289. if (!s->ok) return 0;
  290. script = collectargs(argv, &has_i, &has_v, &has_e);
  291. if (script < 0) { /* invalid args? */
  292. print_usage();
  293. s->ok = 0;
  294. return 0;
  295. }
  296. if (has_v) print_version();
  297. s->ok = runargs(L, argv, (script > 0) ? script : s->argc);
  298. if (!s->ok) return 0;
  299. if (script)
  300. s->ok = (handle_script(L, argv, script) == LUA_OK);
  301. if (!s->ok) return 0;
  302. if (has_i)
  303. dotty(L);
  304. else if (script == 0 && !has_e && !has_v) {
  305. if (lua_stdin_is_tty()) {
  306. print_version();
  307. dotty(L);
  308. }
  309. else dofile(L, NULL); /* executes stdin as a file */
  310. }
  311. return 0;
  312. }
  313. int main (int argc, char **argv) {
  314. int status;
  315. struct Smain s;
  316. lua_State *L = lua_open(); /* create state */
  317. if (L == NULL) {
  318. l_message(argv[0], "cannot create state: not enough memory");
  319. return EXIT_FAILURE;
  320. }
  321. s.argc = argc;
  322. s.argv = argv;
  323. status = lua_cpcall(L, &pmain, &s);
  324. report(L, status);
  325. lua_close(L);
  326. return (s.ok && status == LUA_OK) ? EXIT_SUCCESS : EXIT_FAILURE;
  327. }