25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 

514 satır
14 KiB

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