lua.c 13 KB

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