lua.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. /*
  2. ** NodeMCU Lua 5.1 and 5.3 main initiator and comand interpreter
  3. ** See Copyright Notice in lua.h
  4. */
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <string.h>
  8. #include "user_version.h"
  9. #include "driver/input.h"
  10. #define lua_c
  11. #define LUA_CORE
  12. #ifndef LUA_VERSION_51 /* LUA_VERSION_NUM == 503 */
  13. #define LUA_VERSION_53
  14. #include "lua.h"
  15. #include "lauxlib.h"
  16. #include "lualib.h"
  17. #include "lprefix.h"
  18. #include "lgc.h"
  19. #include "lnodemcu.h"
  20. #endif
  21. #include "platform.h"
  22. #if !defined(LUA_PROMPT)
  23. #define LUA_PROMPT "> "
  24. #define LUA_PROMPT2 ">> "
  25. #endif
  26. #ifndef LUA_INIT_STRING
  27. #define LUA_INIT_STRING "@init.lua"
  28. #endif
  29. /*
  30. ** The NodeMCU version of lua.c is structurally different for standard lua.c
  31. ** as a result of architectural drivers arising from its context and being
  32. ** initiated within the startup sequence of an IoT SoC embedded runtime.
  33. **
  34. ** 1) Processing is based on a single threaded event loop model (somewhat akin
  35. ** to Node.js), so access to most system services is asyncronous and uses
  36. ** a callback mechanism. The Lua interactive mode processes input lines
  37. ** that are provided by the firmware on a line by line basis and indeed
  38. ** other Lua tasks might interleave any multiline processing, so the
  39. ** standard doREPL approach won't work.
  40. **
  41. ** 2) Most OS services and enviroment processing are supported so much of the
  42. ** standard functionality is irrelevant and is stripped out for simplicity.
  43. **
  44. ** 3) stderr and stdout redirection aren't offered as an OS service, so this
  45. ** is handled in the baselib print function and errors are sent to print.
  46. */
  47. lua_State *globalL = NULL;
  48. static int pmain (lua_State *L);
  49. void lua_input_string (const char *line, int len);
  50. /*
  51. ** Prints (calling the Lua 'print' function) to print n values on the stack
  52. */
  53. static void l_print (lua_State *L, int n) {
  54. if (n > 0) { /* any result to be printed? */
  55. luaL_checkstack(L, LUA_MINSTACK, "too many results to print");
  56. lua_getglobal(L, "print");
  57. lua_insert(L, -n-1);
  58. if (lua_pcall(L, n, 0, 0) != LUA_OK) {
  59. lua_writestringerror("error calling 'print' (%s)\n", lua_tostring(L, -1));
  60. lua_settop(L, -n-1);
  61. }
  62. }
  63. }
  64. /*
  65. ** Message handler is used with all chunks calls. Returns the traceback on ToS
  66. */
  67. static int msghandler (lua_State *L) {
  68. lua_getglobal(L, "debug");
  69. lua_getfield(L, -1, "traceback");
  70. if (lua_isfunction(L, -1)) {
  71. lua_insert(L, 1); /* insert tracback function above error */
  72. lua_pop(L, 1); /* dump the debug table entry */
  73. lua_pushinteger(L, 2); /* skip this function and traceback */
  74. lua_call(L, 2, 1); /* call debug.traceback and return it as a string */
  75. }
  76. return 1; /* return the traceback */
  77. }
  78. /*
  79. ** Interface to 'lua_pcall', which sets appropriate message function and error
  80. ** handler. Used to run all chunks. Results or error traceback left on stack.
  81. ** This function is interactive so unlike lua_pcallx(), the error is sent direct
  82. ** to the print function and erroring does not trigger an on error restart.
  83. */
  84. static int docall (lua_State *L, int narg) {
  85. int status;
  86. int base = lua_gettop(L) - narg; /* function index */
  87. lua_pushcfunction(L, msghandler); /* push message handler */
  88. lua_insert(L, base); /* put it under chunk and args */
  89. status = lua_pcall(L, narg, LUA_MULTRET, base);
  90. lua_remove(L, base); /* remove message handler from the stack */
  91. /* force a complete garbage collection in case of errors */
  92. if (status != 0) lua_gc(L, LUA_GCCOLLECT, 0);
  93. return status;
  94. }
  95. #ifndef DISABLE_STARTUP_BANNER
  96. static void print_version (lua_State *L) {
  97. lua_writestringerror( "\n" NODE_VERSION " build " BUILD_DATE
  98. " powered by " LUA_RELEASE " on SDK %s\n", SDK_VERSION);
  99. }
  100. #endif
  101. /*
  102. ** Returns the string to be used as a prompt by the interpreter.
  103. */
  104. static const char *get_prompt (lua_State *L, int firstline) {
  105. const char *p;
  106. lua_getglobal(L, firstline ? "_PROMPT" : "_PROMPT2");
  107. p = lua_tostring(L, -1);
  108. if (p == NULL) p = (firstline ? LUA_PROMPT : LUA_PROMPT2);
  109. lua_pop(L, 1); /* remove global */
  110. return p;
  111. }
  112. /*
  113. ** Check whether 'status' signals a syntax error and the error
  114. ** message at the top of the stack ends with the above mark for
  115. ** incomplete statements.
  116. */
  117. #ifdef LUA_VERSION_51
  118. #define EOFMARK LUA_QL("<eof>")
  119. #else
  120. #define EOFMARK "<eof>"
  121. #endif
  122. #define MARKLEN (sizeof(EOFMARK)/sizeof(char) - 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, EOFMARK)) {
  128. lua_pop(L, 1);
  129. return 1;
  130. }
  131. }
  132. return 0;
  133. }
  134. static void l_create_stdin (lua_State *L);
  135. /*
  136. ** Note that the Lua stack can't be used to stash part-line components as
  137. ** other C API and Lua functions might be executed as tasks between lines in
  138. ** a multiline, so a standard luaL_ref() registry entry is used instead.
  139. */
  140. static void dojob (lua_State *L) {
  141. static int MLref = LUA_NOREF; /* Lua Reg entry for cached multi-line */
  142. int status;
  143. const char *prompt;
  144. size_t l;
  145. const char *b = lua_tostring(L, -1); /* ToS contains next input line */
  146. if (MLref != LUA_NOREF) {
  147. /* processing multiline */
  148. lua_rawgeti(L, LUA_REGISTRYINDEX, MLref); /* insert prev lines(s) */
  149. lua_pushliteral(L, "\n"); /* insert CR */
  150. lua_pushvalue(L, -3); /* dup new line */
  151. lua_concat(L, 3); /* concat all 3 */
  152. lua_remove(L,-2); /* and shift down to ToS */
  153. } else if (b[0] == '=') { /* If firstline and of the format =<expression> */
  154. lua_pushfstring(L, "return %s", b+1);
  155. lua_remove(L, -2);
  156. }
  157. /*
  158. * ToS is at S[2] which contains the putative chunk to be compiled
  159. */
  160. b = lua_tolstring(L, -1, &l);
  161. status = luaL_loadbuffer(L, b, l, "=stdin");
  162. if (incomplete(L, status)) {
  163. /* Store line back in the Reg mlref sot */
  164. if (MLref == LUA_NOREF) {
  165. MLref = luaL_ref(L, LUA_REGISTRYINDEX);
  166. } else {
  167. lua_rawseti(L, LUA_REGISTRYINDEX, MLref);
  168. }
  169. } else {
  170. /* compile finished OK or with hard error */
  171. lua_remove(L, -2); /* remove line because now redundant */
  172. if (MLref != LUA_NOREF) { /* also remove multiline if it exists */
  173. luaL_unref(L, LUA_REGISTRYINDEX, MLref);
  174. MLref = LUA_NOREF;
  175. }
  176. /* Execute the compiled chunk of successful */
  177. if (status == 0)
  178. status = docall(L, 0);
  179. /* print any returned results or error message */
  180. if (status && !lua_isnil(L, -1)) {
  181. lua_pushliteral(L, "Lua error: ");
  182. lua_insert(L , -2);
  183. }
  184. l_print(L, lua_gettop(L) - 1); /* print error or results one stack */
  185. }
  186. prompt = get_prompt(L, MLref!= LUA_NOREF ? 0 : 1);
  187. input_setprompt(prompt);
  188. lua_writestring(prompt,strlen(prompt));
  189. }
  190. /*
  191. ** Main body of standalone interpreter.
  192. */
  193. static int pmain (lua_State *L) {
  194. const char *init = LUA_INIT_STRING;
  195. int status;
  196. lua_gc(L, LUA_GCSTOP, 0); /* stop GC during initialization */
  197. luaL_openlibs(L); /* Nodemcu open will throw to signal an LFS reload */
  198. #ifdef LUA_VERSION_51
  199. lua_setegcmode( L, EGC_ALWAYS, 4096 );
  200. #else
  201. lua_gc( L, LUA_GCSETMEMLIMIT, 4096 );
  202. #endif
  203. lua_gc(L, LUA_GCRESTART, 0); /* restart GC and set EGC mode */
  204. lua_settop(L, 0);
  205. l_create_stdin(L);
  206. input_setup(LUA_MAXINPUT, get_prompt(L, 1));
  207. lua_input_string(" \n", 2); /* queue CR to issue first prompt */
  208. #ifndef DISABLE_STARTUP_BANNER
  209. print_version(L);
  210. #endif
  211. /*
  212. * And last of all, kick off application initialisation. Note that if
  213. * LUA_INIT_STRING is a file reference and the file system is uninitialised
  214. * then attempting the open will trigger a file system format.
  215. */
  216. platform_rcr_read(PLATFORM_RCR_INITSTR, (void**) &init);
  217. status = (init[0] == '@') ?
  218. luaL_loadfile(L, init+1) :
  219. luaL_loadbuffer(L, init, strlen(init), "=INIT");
  220. if (status == LUA_OK)
  221. status = docall(L, 0);
  222. if (status != LUA_OK)
  223. l_print (L, 1);
  224. return 0;
  225. }
  226. /*
  227. ** The system initialisation CB nodemcu_init() calls lua_main() to startup the
  228. ** Lua environment by calling luaL_newstate() which initiates the core Lua VM.
  229. ** The initialisation of the libraries, etc. can potentially throw errors and
  230. ** so is wrapped in a protected call which also kicks off the user application
  231. ** through the LUA_INIT_STRING hook.
  232. */
  233. int lua_main (void) {
  234. lua_State *L = luaL_newstate();
  235. if (L == NULL) {
  236. lua_writestringerror( "cannot create state: %s", "not enough memory");
  237. return 0;
  238. }
  239. globalL = L;
  240. lua_pushcfunction(L, pmain);
  241. if (docall(L, 0) != LUA_OK) {
  242. if (strstr(lua_tostring(L, -1),"!LFSrestart!")) {
  243. lua_close(L);
  244. return 1; /* non-zero return to flag LFS reload */
  245. }
  246. l_print(L, 1);
  247. }
  248. return 0;
  249. }
  250. lua_State *lua_getstate(void) {
  251. return globalL;
  252. }
  253. /*
  254. ** The Lua interpreter is event-driven and task-oriented in NodeMCU rather than
  255. ** based on a readline poll loop as in the standard implementation. Input lines
  256. ** can come from one of two sources: the application can "push" lines for the
  257. ** interpreter to compile and execute, or they can come from the UART. To
  258. ** minimise application blocking, the lines are queued in a pipe when received,
  259. ** with the Lua interpreter task attached to the pipe as its reader task. This
  260. ** CB processes one line of input per task execution.
  261. **
  262. ** Even though lines can be emitted from independent sources (the UART and the
  263. ** node API), and they could in theory get interleaved, the strategy here is
  264. ** "let the programmer beware": interactive input will normally only occur in
  265. ** development and injected input occur in telnet type applications. If there
  266. ** is a need for interlocks, then the application should handle this.
  267. */
  268. void lua_input_string (const char *line, int len) {
  269. lua_State *L = globalL;
  270. lua_getfield(L, LUA_REGISTRYINDEX, "stdin");
  271. lua_rawgeti(L, -1, 1); /* get the pipe_write from stdin[1] */
  272. lua_insert(L, -2); /* stick above the pipe */
  273. lua_pushlstring(L, line, len);
  274. lua_call(L, 2, 0); /* stdin:write(line) */
  275. }
  276. /*
  277. ** CB reader for the stdin pipe, and follows the calling conventions for a
  278. ** pipe readers; it has one argument, the stdin pipe that it is reading.
  279. */
  280. static int l_read_stdin (lua_State *L) {
  281. size_t l;
  282. lua_settop(L, 1); /* pipe obj at S[1] */
  283. lua_getfield(L, 1, "read"); /* pobj:read at S[2] */
  284. lua_pushvalue(L, 1); /* dup pobj to S[3] */
  285. lua_pushliteral(L, "\n+"); /* S[4] = "\n+" */
  286. lua_call(L, 2, 1); /* S[2] = pobj:read("\n+") */
  287. const char* b = lua_tolstring(L, 2, &l); /* b = NULL if S[2] is nil */
  288. /*
  289. * If the pipe is empty, or the line not CR terminated, return false to
  290. * suppress automatic reposting
  291. */
  292. lua_pushboolean(L, false);
  293. if ((lua_isnil(L, 2) || l == 0))
  294. return 1; /* return false if pipe empty */
  295. if (b[l-1] != '\n') {
  296. /* likewise if not CR terminated, then unread and ditto */
  297. lua_insert(L, 1); /* insert false return above the pipe */
  298. lua_getfield(L, 2, "unread");
  299. lua_insert(L, 2); /* insert pipe.unread above the pipe */
  300. lua_call(L, 2, 0); /* pobj:unread(line) */
  301. return 1; /* return false */
  302. }
  303. lua_pop(L, 1); /* dump false value at ToS */
  304. /*
  305. * Now we can process a proper CR terminated line
  306. */
  307. lua_pushlstring(L, b, --l); /* remove end CR */
  308. lua_remove(L, 2);
  309. dojob(L);
  310. return 0;
  311. }
  312. /*
  313. ** Create and initialise the stdin pipe
  314. */
  315. static void l_create_stdin (lua_State *L) {
  316. lua_pushliteral(L, "stdin");
  317. lua_getglobal(L, "pipe");
  318. lua_getfield(L, -1, "create");
  319. lua_remove(L, -2);
  320. lua_pushcfunction(L, l_read_stdin);
  321. lua_pushinteger(L, LUA_TASK_LOW);
  322. lua_call(L, 2, 1); /* ToS = pipe.create(dojob, low_priority) */
  323. lua_rawset(L, LUA_REGISTRYINDEX); /* and stash input pipe in Reg["stdin"] */
  324. }