Subversion Repositories Kolibri OS

Rev

Blame | Last modification | View Log | RSS feed

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