lua.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  1. /*
  2. ** $Id: lua.c,v 1.160.1.2 2007/12/28 15:32:23 roberto Exp $
  3. ** Lua stand-alone interpreter
  4. ** See Copyright Notice in lua.h
  5. */
  6. // #include "c_signal.h"
  7. #include "c_stdio.h"
  8. #include "c_stdlib.h"
  9. #include "c_string.h"
  10. #include "user_interface.h"
  11. #include "user_version.h"
  12. #include "driver/readline.h"
  13. #include "driver/uart.h"
  14. #include "platform.h"
  15. #define lua_c
  16. #include "lua.h"
  17. #include "lauxlib.h"
  18. #include "lualib.h"
  19. #include "legc.h"
  20. #ifdef LUA_FLASH_STORE
  21. #include "lflash.h"
  22. #endif
  23. #include "os_type.h"
  24. lua_State *globalL = NULL;
  25. static lua_Load gLoad;
  26. static const char *progname = LUA_PROGNAME;
  27. static void l_message (const char *pname, const char *msg) {
  28. #if defined(LUA_USE_STDIO)
  29. if (pname) c_fprintf(c_stderr, "%s: ", pname);
  30. c_fprintf(c_stderr, "%s\n", msg);
  31. c_fflush(c_stderr);
  32. #else
  33. if (pname) luai_writestringerror("%s: ", pname);
  34. luai_writestringerror("%s\n", msg);
  35. #endif
  36. }
  37. static int report (lua_State *L, int status) {
  38. if (status && !lua_isnil(L, -1)) {
  39. const char *msg = lua_tostring(L, -1);
  40. if (msg == NULL) msg = "(error object is not a string)";
  41. l_message(progname, msg);
  42. lua_pop(L, 1);
  43. }
  44. return status;
  45. }
  46. static int traceback (lua_State *L) {
  47. if (!lua_isstring(L, 1)) /* 'message' not a string? */
  48. return 1; /* keep it intact */
  49. lua_getfield(L, LUA_GLOBALSINDEX, "debug");
  50. if (!lua_istable(L, -1) && !lua_isrotable(L, -1)) {
  51. lua_pop(L, 1);
  52. return 1;
  53. }
  54. lua_getfield(L, -1, "traceback");
  55. if (!lua_isfunction(L, -1) && !lua_islightfunction(L, -1)) {
  56. lua_pop(L, 2);
  57. return 1;
  58. }
  59. lua_pushvalue(L, 1); /* pass error message */
  60. lua_pushinteger(L, 2); /* skip this function and traceback */
  61. lua_call(L, 2, 1); /* call debug.traceback */
  62. return 1;
  63. }
  64. static int docall (lua_State *L, int narg, int clear) {
  65. int status;
  66. int base = lua_gettop(L) - narg; /* function index */
  67. lua_pushcfunction(L, traceback); /* push traceback function */
  68. lua_insert(L, base); /* put it under chunk and args */
  69. // signal(SIGINT, laction);
  70. status = lua_pcall(L, narg, (clear ? 0 : LUA_MULTRET), base);
  71. // signal(SIGINT, SIG_DFL);
  72. lua_remove(L, base); /* remove traceback function */
  73. /* force a complete garbage collection in case of errors */
  74. if (status != 0) lua_gc(L, LUA_GCCOLLECT, 0);
  75. return status;
  76. }
  77. static void print_version (lua_State *L) {
  78. lua_pushliteral (L, "\n" NODE_VERSION " build " BUILD_DATE " powered by " LUA_RELEASE " on SDK ");
  79. lua_pushstring (L, SDK_VERSION);
  80. lua_concat (L, 2);
  81. const char *msg = lua_tostring (L, -1);
  82. l_message (NULL, msg);
  83. lua_pop (L, 1);
  84. }
  85. static int getargs (lua_State *L, char **argv, int n) {
  86. int narg;
  87. int i;
  88. int argc = 0;
  89. while (argv[argc]) argc++; /* count total number of arguments */
  90. narg = argc - (n + 1); /* number of arguments to the script */
  91. luaL_checkstack(L, narg + 3, "too many arguments to script");
  92. for (i=n+1; i < argc; i++)
  93. lua_pushstring(L, argv[i]);
  94. lua_createtable(L, narg, n + 1);
  95. for (i=0; i < argc; i++) {
  96. lua_pushstring(L, argv[i]);
  97. lua_rawseti(L, -2, i - n);
  98. }
  99. return narg;
  100. }
  101. static int dofsfile (lua_State *L, const char *name) {
  102. int status = luaL_loadfsfile(L, name) || docall(L, 0, 1);
  103. return report(L, status);
  104. }
  105. static int dostring (lua_State *L, const char *s, const char *name) {
  106. int status = luaL_loadbuffer(L, s, c_strlen(s), name) || docall(L, 0, 1);
  107. return report(L, status);
  108. }
  109. static int dolibrary (lua_State *L, const char *name) {
  110. lua_getglobal(L, "require");
  111. lua_pushstring(L, name);
  112. return report(L, docall(L, 1, 1));
  113. }
  114. static const char *get_prompt (lua_State *L, int firstline) {
  115. const char *p;
  116. lua_getfield(L, LUA_GLOBALSINDEX, firstline ? "_PROMPT" : "_PROMPT2");
  117. p = lua_tostring(L, -1);
  118. if (p == NULL) p = (firstline ? LUA_PROMPT : LUA_PROMPT2);
  119. lua_pop(L, 1); /* remove global */
  120. return p;
  121. }
  122. static int incomplete (lua_State *L, int status) {
  123. if (status == LUA_ERRSYNTAX) {
  124. size_t lmsg;
  125. const char *msg = lua_tolstring(L, -1, &lmsg);
  126. const char *tp = msg + lmsg - (sizeof(LUA_QL("<eof>")) - 1);
  127. if (c_strstr(msg, LUA_QL("<eof>")) == tp) {
  128. lua_pop(L, 1);
  129. return 1;
  130. }
  131. }
  132. return 0; /* else... */
  133. }
  134. /* check that argument has no extra characters at the end */
  135. #define notail(x) {if ((x)[2] != '\0') return -1;}
  136. static int collectargs (char **argv, int *pi, int *pv, int *pe) {
  137. int i;
  138. for (i = 1; argv[i] != NULL; i++) {
  139. if (argv[i][0] != '-') /* not an option? */
  140. return i;
  141. switch (argv[i][1]) { /* option */
  142. case '-':
  143. notail(argv[i]);
  144. return (argv[i+1] != NULL ? i+1 : 0);
  145. case '\0':
  146. return i;
  147. case 'i':
  148. notail(argv[i]);
  149. *pi = 1; /* go through */
  150. case 'v':
  151. notail(argv[i]);
  152. *pv = 1;
  153. break;
  154. case 'e':
  155. *pe = 1; /* go through */
  156. case 'm': /* go through */
  157. case 'l':
  158. if (argv[i][2] == '\0') {
  159. i++;
  160. if (argv[i] == NULL) return -1;
  161. }
  162. break;
  163. default: return -1; /* invalid option */
  164. }
  165. }
  166. return 0;
  167. }
  168. static int runargs (lua_State *L, char **argv, int n) {
  169. int i;
  170. for (i = 1; i < n; i++) {
  171. if (argv[i] == NULL) continue;
  172. lua_assert(argv[i][0] == '-');
  173. switch (argv[i][1]) { /* option */
  174. case 'e': {
  175. const char *chunk = argv[i] + 2;
  176. if (*chunk == '\0') chunk = argv[++i];
  177. lua_assert(chunk != NULL);
  178. if (dostring(L, chunk, "=(command line)") != 0)
  179. return 1;
  180. break;
  181. }
  182. case 'm': {
  183. const char *limit = argv[i] + 2;
  184. int memlimit=0;
  185. if (*limit == '\0') limit = argv[++i];
  186. lua_assert(limit != NULL);
  187. memlimit = c_atoi(limit);
  188. lua_gc(L, LUA_GCSETMEMLIMIT, memlimit);
  189. break;
  190. }
  191. case 'l': {
  192. const char *filename = argv[i] + 2;
  193. if (*filename == '\0') filename = argv[++i];
  194. lua_assert(filename != NULL);
  195. if (dolibrary(L, filename))
  196. return 1; /* stop if file fails */
  197. break;
  198. }
  199. default: break;
  200. }
  201. }
  202. return 0;
  203. }
  204. #ifndef LUA_INIT_STRING
  205. #define LUA_INIT_STRING "@init.lua"
  206. #endif
  207. static int handle_luainit (lua_State *L) {
  208. const char *init = LUA_INIT_STRING;
  209. if (init[0] == '@')
  210. return dofsfile(L, init+1);
  211. else
  212. return dostring(L, init, LUA_INIT);
  213. }
  214. struct Smain {
  215. int argc;
  216. char **argv;
  217. int status;
  218. };
  219. static int pmain (lua_State *L) {
  220. struct Smain *s = (struct Smain *)lua_touserdata(L, 1);
  221. char **argv = s->argv;
  222. int script;
  223. int has_i = 0, has_v = 0, has_e = 0;
  224. globalL = L;
  225. if (argv[0] && argv[0][0]) progname = argv[0];
  226. lua_gc(L, LUA_GCSTOP, 0); /* stop collector during initialization */
  227. luaL_openlibs(L); /* open libraries */
  228. lua_gc(L, LUA_GCRESTART, 0);
  229. print_version(L);
  230. s->status = handle_luainit(L);
  231. script = collectargs(argv, &has_i, &has_v, &has_e);
  232. if (script < 0) { /* invalid args? */
  233. s->status = 1;
  234. return 0;
  235. }
  236. s->status = runargs(L, argv, (script > 0) ? script : s->argc);
  237. if (s->status != 0) return 0;
  238. return 0;
  239. }
  240. static void dojob(lua_Load *load);
  241. static bool readline(lua_Load *load);
  242. #ifdef LUA_RPC
  243. int main (int argc, char **argv) {
  244. #else
  245. int lua_main (int argc, char **argv) {
  246. #endif
  247. int status;
  248. struct Smain s;
  249. #if defined(NODE_DEBUG) && defined(DEVELOPMENT_USE_GDB) && \
  250. defined(DEVELOPMENT_BREAK_ON_STARTUP_PIN) && DEVELOPMENT_BREAK_ON_STARTUP_PIN > 0
  251. platform_gpio_mode( DEVELOPMENT_BREAK_ON_STARTUP_PIN, PLATFORM_GPIO_INPUT, PLATFORM_GPIO_PULLUP );
  252. lua_assert(platform_gpio_read(DEVELOPMENT_BREAK_ON_STARTUP_PIN)); // Break if pin pulled low
  253. #endif
  254. lua_State *L = lua_open(); /* create state */
  255. if (L == NULL) {
  256. l_message(argv[0], "cannot create state: not enough memory");
  257. return EXIT_FAILURE;
  258. }
  259. s.argc = argc;
  260. s.argv = argv;
  261. status = lua_cpcall(L, &pmain, &s);
  262. report(L, status);
  263. gLoad.L = L;
  264. gLoad.firstline = 1;
  265. gLoad.done = 0;
  266. gLoad.line = c_malloc(LUA_MAXINPUT);
  267. gLoad.len = LUA_MAXINPUT;
  268. gLoad.line_position = 0;
  269. gLoad.prmt = get_prompt(L, 1);
  270. dojob(&gLoad);
  271. NODE_DBG("Heap size:%d.\n",system_get_free_heap_size());
  272. legc_set_mode( L, EGC_ALWAYS, 4096 );
  273. // legc_set_mode( L, EGC_ON_MEM_LIMIT, 4096 );
  274. // lua_close(L);
  275. return (status || s.status) ? EXIT_FAILURE : EXIT_SUCCESS;
  276. }
  277. int lua_put_line(const char *s, size_t l) {
  278. if (s == NULL || ++l < LUA_MAXINPUT || gLoad.line_position > 0)
  279. return 0;
  280. c_memcpy(gLoad.line, s, l);
  281. gLoad.line[l] = '\0';
  282. gLoad.line_position = l;
  283. gLoad.done = 1;
  284. NODE_DBG("Get command: %s\n", gLoad.line);
  285. return 1;
  286. }
  287. void lua_handle_input (bool force)
  288. {
  289. while (gLoad.L && (force || readline (&gLoad))) {
  290. NODE_DBG("Handle Input: first=%u, pos=%u, len=%u, actual=%u, line=%s\n", gLoad.firstline,
  291. gLoad.line_position, gLoad.len, c_strlen(gLoad.line), gLoad.line);
  292. dojob (&gLoad);
  293. force = false;
  294. }
  295. }
  296. void donejob(lua_Load *load){
  297. lua_close(load->L);
  298. }
  299. static void dojob(lua_Load *load){
  300. size_t l, rs;
  301. int status;
  302. char *b = load->line;
  303. lua_State *L = load->L;
  304. const char *oldprogname = progname;
  305. progname = NULL;
  306. do{
  307. if(load->done == 1){
  308. l = c_strlen(b);
  309. if (l > 0 && b[l-1] == '\n') /* line ends with newline? */
  310. b[l-1] = '\0'; /* remove it */
  311. if (load->firstline && b[0] == '=') /* first line starts with `=' ? */
  312. lua_pushfstring(L, "return %s", b+1); /* change it to `return' */
  313. else
  314. lua_pushstring(L, b);
  315. if(load->firstline != 1){
  316. lua_pushliteral(L, "\n"); /* add a new line... */
  317. lua_insert(L, -2); /* ...between the two lines */
  318. lua_concat(L, 3); /* join them */
  319. }
  320. status = luaL_loadbuffer(L, lua_tostring(L, 1), lua_strlen(L, 1), "=stdin");
  321. if (!incomplete(L, status)) { /* cannot try to add lines? */
  322. lua_remove(L, 1); /* remove line */
  323. if (status == 0) {
  324. status = docall(L, 0, 0);
  325. }
  326. report(L, status);
  327. if (status == 0 && lua_gettop(L) > 0) { /* any result to print? */
  328. lua_getglobal(L, "print");
  329. lua_insert(L, 1);
  330. if (lua_pcall(L, lua_gettop(L)-1, 0, 0) != 0)
  331. l_message(progname, lua_pushfstring(L,
  332. "error calling " LUA_QL("print") " (%s)",
  333. lua_tostring(L, -1)));
  334. }
  335. load->firstline = 1;
  336. load->prmt = get_prompt(L, 1);
  337. lua_settop(L, 0);
  338. /* force a complete garbage collection in case of errors */
  339. if (status != 0) lua_gc(L, LUA_GCCOLLECT, 0);
  340. } else {
  341. load->firstline = 0;
  342. load->prmt = get_prompt(L, 0);
  343. }
  344. }
  345. }while(0);
  346. progname = oldprogname;
  347. load->done = 0;
  348. load->line_position = 0;
  349. c_memset(load->line, 0, load->len);
  350. c_puts(load->prmt);
  351. }
  352. #ifndef uart_putc
  353. #define uart_putc uart0_putc
  354. #endif
  355. extern bool uart_on_data_cb(const char *buf, size_t len);
  356. extern bool uart0_echo;
  357. extern bool run_input;
  358. extern uint16_t need_len;
  359. extern int16_t end_char;
  360. static char last_nl_char = '\0';
  361. static bool readline(lua_Load *load){
  362. // NODE_DBG("readline() is called.\n");
  363. bool need_dojob = false;
  364. char ch;
  365. while (uart_getc(&ch))
  366. {
  367. if(run_input)
  368. {
  369. char tmp_last_nl_char = last_nl_char;
  370. // reset marker, will be finally set below when newline is processed
  371. last_nl_char = '\0';
  372. /* handle CR & LF characters
  373. filters second char of LF&CR (\n\r) or CR&LF (\r\n) sequences */
  374. if ((ch == '\r' && tmp_last_nl_char == '\n') || // \n\r sequence -> skip \r
  375. (ch == '\n' && tmp_last_nl_char == '\r')) // \r\n sequence -> skip \n
  376. {
  377. continue;
  378. }
  379. /* backspace key */
  380. else if (ch == 0x7f || ch == 0x08)
  381. {
  382. if (load->line_position > 0)
  383. {
  384. if(uart0_echo) uart_putc(0x08);
  385. if(uart0_echo) uart_putc(' ');
  386. if(uart0_echo) uart_putc(0x08);
  387. load->line_position--;
  388. }
  389. load->line[load->line_position] = 0;
  390. continue;
  391. }
  392. /* EOT(ctrl+d) */
  393. // else if (ch == 0x04)
  394. // {
  395. // if (load->line_position == 0)
  396. // // No input which makes lua interpreter close
  397. // donejob(load);
  398. // else
  399. // continue;
  400. // }
  401. /* end of line */
  402. if (ch == '\r' || ch == '\n')
  403. {
  404. last_nl_char = ch;
  405. load->line[load->line_position] = 0;
  406. if(uart0_echo) uart_putc('\n');
  407. uart_on_data_cb(load->line, load->line_position);
  408. if (load->line_position == 0)
  409. {
  410. /* Get a empty line, then go to get a new line */
  411. c_puts(load->prmt);
  412. continue;
  413. } else {
  414. load->done = 1;
  415. need_dojob = true;
  416. break;
  417. }
  418. }
  419. /* other control character or not an acsii character */
  420. // if (ch < 0x20 || ch >= 0x80)
  421. // {
  422. // continue;
  423. // }
  424. /* echo */
  425. if(uart0_echo) uart_putc(ch);
  426. /* it's a large line, discard it */
  427. if ( load->line_position + 1 >= load->len ){
  428. load->line_position = 0;
  429. }
  430. }
  431. load->line[load->line_position] = ch;
  432. load->line_position++;
  433. if(!run_input)
  434. {
  435. if( ((need_len!=0) && (load->line_position >= need_len)) || \
  436. (load->line_position >= load->len) || \
  437. ((end_char>=0) && ((unsigned char)ch==(unsigned char)end_char)) )
  438. {
  439. uart_on_data_cb(load->line, load->line_position);
  440. load->line_position = 0;
  441. }
  442. }
  443. ch = 0;
  444. }
  445. if( (load->line_position > 0) && (!run_input) && (need_len==0) && (end_char<0) )
  446. {
  447. uart_on_data_cb(load->line, load->line_position);
  448. load->line_position = 0;
  449. }
  450. return need_dojob;
  451. }