liolib.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  1. /*
  2. ** $Id: liolib.c,v 1.31 1999/02/22 14:17:24 roberto Exp roberto $
  3. ** Standard I/O (and system) library
  4. ** See Copyright Notice in lua.h
  5. */
  6. #include <errno.h>
  7. #include <stdio.h>
  8. #include <stdlib.h>
  9. #include <string.h>
  10. #include <time.h>
  11. #include "lauxlib.h"
  12. #include "lua.h"
  13. #include "luadebug.h"
  14. #include "lualib.h"
  15. #ifndef OLD_ANSI
  16. #include <locale.h>
  17. #else
  18. /* no support for locale and for strerror: fake them */
  19. #define setlocale(a,b) 0
  20. #define LC_ALL 0
  21. #define LC_COLLATE 0
  22. #define LC_CTYPE 0
  23. #define LC_MONETARY 0
  24. #define LC_NUMERIC 0
  25. #define LC_TIME 0
  26. #define strerror(e) "(no error message provided by operating system)"
  27. #endif
  28. #define CLOSEDTAG 2
  29. #define IOTAG 1
  30. #define FIRSTARG 3 /* 1st and 2nd are upvalues */
  31. #define FINPUT "_INPUT"
  32. #define FOUTPUT "_OUTPUT"
  33. #define MODESIZE 3 /* string for file mode */
  34. #ifdef POPEN
  35. FILE *popen();
  36. int pclose();
  37. #else
  38. /* no support for popen */
  39. #define popen(x,y) NULL /* that is, popen always fails */
  40. #define pclose(x) (-1)
  41. #endif
  42. static void pushresult (int i) {
  43. if (i)
  44. lua_pushuserdata(NULL);
  45. else {
  46. lua_pushnil();
  47. lua_pushstring(strerror(errno));
  48. lua_pushnumber(errno);
  49. }
  50. }
  51. /*
  52. ** {======================================================
  53. ** FILE Operations
  54. ** =======================================================
  55. */
  56. static int gettag (int i) {
  57. return (int)lua_getnumber(lua_getparam(i));
  58. }
  59. static int ishandler (lua_Object f) {
  60. if (lua_isuserdata(f)) {
  61. if (lua_tag(f) == gettag(CLOSEDTAG))
  62. lua_error("cannot access a closed file");
  63. return lua_tag(f) == gettag(IOTAG);
  64. }
  65. else return 0;
  66. }
  67. static FILE *getfilebyname (char *name) {
  68. lua_Object f = lua_getglobal(name);
  69. if (!ishandler(f))
  70. luaL_verror("global variable `%.50s' is not a file handle", name);
  71. return lua_getuserdata(f);
  72. }
  73. static FILE *getfile (int arg) {
  74. lua_Object f = lua_getparam(arg);
  75. return (ishandler(f)) ? lua_getuserdata(f) : NULL;
  76. }
  77. static FILE *getfileparam (char *name, int *arg) {
  78. FILE *f = getfile(*arg);
  79. if (f) {
  80. (*arg)++;
  81. return f;
  82. }
  83. else
  84. return getfilebyname(name);
  85. }
  86. static void getmode (char mode, char *m) {
  87. m[0] = mode;
  88. if (*luaL_opt_string(FIRSTARG+1, "text") == 'b') {
  89. m[1] = 'b';
  90. m[2] = '\0';
  91. }
  92. else m[1] = '\0';
  93. }
  94. static void closefile (char *name) {
  95. FILE *f = getfilebyname(name);
  96. if (f == stdin || f == stdout) return;
  97. if (pclose(f) == -1)
  98. fclose(f);
  99. lua_pushobject(lua_getglobal(name));
  100. lua_settag(gettag(CLOSEDTAG));
  101. }
  102. static void setfile (FILE *f, char *name, int tag) {
  103. lua_pushusertag(f, tag);
  104. lua_setglobal(name);
  105. }
  106. static void setreturn (FILE *f, char *name) {
  107. int tag = gettag(IOTAG);
  108. setfile(f, name, tag);
  109. lua_pushusertag(f, tag);
  110. }
  111. static void io_readfrom (void) {
  112. FILE *current;
  113. lua_Object f = lua_getparam(FIRSTARG);
  114. if (f == LUA_NOOBJECT) {
  115. closefile(FINPUT);
  116. current = stdin;
  117. }
  118. else if (lua_tag(f) == gettag(IOTAG))
  119. current = lua_getuserdata(f);
  120. else {
  121. char *s = luaL_check_string(FIRSTARG);
  122. char m[MODESIZE];
  123. getmode('r', m);
  124. current = (*s == '|') ? popen(s+1, "r") : fopen(s, m);
  125. if (current == NULL) {
  126. pushresult(0);
  127. return;
  128. }
  129. }
  130. setreturn(current, FINPUT);
  131. }
  132. static void io_writeto (void) {
  133. FILE *current;
  134. lua_Object f = lua_getparam(FIRSTARG);
  135. if (f == LUA_NOOBJECT) {
  136. closefile(FOUTPUT);
  137. current = stdout;
  138. }
  139. else if (lua_tag(f) == gettag(IOTAG))
  140. current = lua_getuserdata(f);
  141. else {
  142. char *s = luaL_check_string(FIRSTARG);
  143. char m[MODESIZE];
  144. getmode('w', m);
  145. current = (*s == '|') ? popen(s+1,"w") : fopen(s, m);
  146. if (current == NULL) {
  147. pushresult(0);
  148. return;
  149. }
  150. }
  151. setreturn(current, FOUTPUT);
  152. }
  153. static void io_appendto (void) {
  154. char *s = luaL_check_string(FIRSTARG);
  155. char m[MODESIZE];
  156. FILE *fp;
  157. getmode('a', m);
  158. fp = fopen (s, m);
  159. if (fp != NULL)
  160. setreturn(fp, FOUTPUT);
  161. else
  162. pushresult(0);
  163. }
  164. /*
  165. ** {======================================================
  166. ** READ
  167. ** =======================================================
  168. */
  169. static int read_pattern (FILE *f, char *p) {
  170. int inskip = 0; /* {skip} level */
  171. int c = getc(f);
  172. while (*p != '\0') {
  173. switch (*p) {
  174. case '{':
  175. inskip++;
  176. p++;
  177. continue;
  178. case '}':
  179. if (!inskip) lua_error("unbalanced braces in read pattern");
  180. inskip--;
  181. p++;
  182. continue;
  183. default: {
  184. char *ep; /* get what is next */
  185. int m; /* match result */
  186. if (c != EOF)
  187. m = luaI_singlematch(c, p, &ep);
  188. else {
  189. luaI_singlematch(0, p, &ep); /* to set "ep" */
  190. m = 0; /* EOF matches no pattern */
  191. }
  192. if (m) {
  193. if (!inskip) luaL_addchar(c);
  194. c = getc(f);
  195. }
  196. switch (*ep) {
  197. case '*': /* repetition */
  198. if (!m) p = ep+1; /* else stay in (repeat) the same item */
  199. continue;
  200. case '?': /* optional */
  201. p = ep+1; /* continues reading the pattern */
  202. continue;
  203. default:
  204. if (!m) { /* pattern fails? */
  205. ungetc(c, f);
  206. return 0;
  207. }
  208. p = ep; /* continues reading the pattern */
  209. }
  210. }
  211. }
  212. }
  213. ungetc(c, f);
  214. return 1;
  215. }
  216. static int read_number (FILE *f) {
  217. double d;
  218. if (fscanf(f, "%lf", &d) == 1) {
  219. lua_pushnumber(d);
  220. return 1;
  221. }
  222. else return 0; /* read fails */
  223. }
  224. #define HUNK_LINE 1024
  225. #define HUNK_FILE BUFSIZ
  226. static int read_line (FILE *f) {
  227. /* equivalent to: return read_pattern(f, "[^\n]*{\n}"); */
  228. int n;
  229. char *b;
  230. do {
  231. b = luaL_openspace(HUNK_LINE);
  232. if (!fgets(b, HUNK_LINE, f)) return 0; /* read fails */
  233. n = strlen(b);
  234. luaL_addsize(n);
  235. } while (b[n-1] != '\n');
  236. luaL_addsize(-1); /* remove '\n' */
  237. return 1;
  238. }
  239. static void read_file (FILE *f) {
  240. /* equivalent to: return read_pattern(f, ".*"); */
  241. int n;
  242. do {
  243. char *b = luaL_openspace(HUNK_FILE);
  244. n = fread(b, sizeof(char), HUNK_FILE, f);
  245. luaL_addsize(n);
  246. } while (n==HUNK_FILE);
  247. }
  248. static void io_read (void) {
  249. static char *options[] = {"*n", "*l", "*a", ".*", "*w", NULL};
  250. int arg = FIRSTARG;
  251. FILE *f = getfileparam(FINPUT, &arg);
  252. char *p = luaL_opt_string(arg++, "*l");
  253. do { /* repeat for each part */
  254. long l;
  255. int success;
  256. luaL_resetbuffer();
  257. switch (luaL_findstring(p, options)) {
  258. case 0: /* number */
  259. if (!read_number(f)) return; /* read fails */
  260. continue; /* number is already pushed; avoid the "pushstring" */
  261. case 1: /* line */
  262. success = read_line(f);
  263. break;
  264. case 2: case 3: /* file */
  265. read_file(f);
  266. success = 1; /* always success */
  267. break;
  268. case 4: /* word */
  269. success = read_pattern(f, "{%s*}%S%S*");
  270. break;
  271. default:
  272. success = read_pattern(f, p);
  273. }
  274. l = luaL_getsize();
  275. if (!success && l==0) return; /* read fails */
  276. lua_pushlstring(luaL_buffer(), l);
  277. } while ((p = luaL_opt_string(arg++, NULL)) != NULL);
  278. }
  279. /* }====================================================== */
  280. static void io_write (void) {
  281. int arg = FIRSTARG;
  282. FILE *f = getfileparam(FOUTPUT, &arg);
  283. int status = 1;
  284. char *s;
  285. long l;
  286. while ((s = luaL_opt_lstr(arg++, NULL, &l)) != NULL)
  287. status = status && ((long)fwrite(s, 1, l, f) == l);
  288. pushresult(status);
  289. }
  290. static void io_seek (void) {
  291. static int mode[] = {SEEK_SET, SEEK_CUR, SEEK_END};
  292. static char *modenames[] = {"set", "cur", "end", NULL};
  293. FILE *f = getfile(FIRSTARG-1+1);
  294. int op = luaL_findstring(luaL_opt_string(FIRSTARG-1+2, "cur"), modenames);
  295. long offset = luaL_opt_long(FIRSTARG-1+3, 0);
  296. luaL_arg_check(f, FIRSTARG-1+1, "invalid file handler");
  297. luaL_arg_check(op != -1, FIRSTARG-1+2, "invalid mode");
  298. op = fseek(f, offset, mode[op]);
  299. if (op)
  300. pushresult(0); /* error */
  301. else
  302. lua_pushnumber(ftell(f));
  303. }
  304. static void io_flush (void) {
  305. FILE *f = getfile(FIRSTARG);
  306. luaL_arg_check(f || lua_getparam(FIRSTARG) == LUA_NOOBJECT, FIRSTARG,
  307. "invalid file handler");
  308. pushresult(fflush(f) == 0);
  309. }
  310. /* }====================================================== */
  311. /*
  312. ** {======================================================
  313. ** Other O.S. Operations
  314. ** =======================================================
  315. */
  316. static void io_execute (void) {
  317. lua_pushnumber(system(luaL_check_string(1)));
  318. }
  319. static void io_remove (void) {
  320. pushresult(remove(luaL_check_string(1)) == 0);
  321. }
  322. static void io_rename (void) {
  323. pushresult(rename(luaL_check_string(1),
  324. luaL_check_string(2)) == 0);
  325. }
  326. static void io_tmpname (void) {
  327. lua_pushstring(tmpnam(NULL));
  328. }
  329. static void io_getenv (void) {
  330. lua_pushstring(getenv(luaL_check_string(1))); /* if NULL push nil */
  331. }
  332. static void io_clock (void) {
  333. lua_pushnumber(((double)clock())/CLOCKS_PER_SEC);
  334. }
  335. static void io_date (void) {
  336. char b[256];
  337. char *s = luaL_opt_string(1, "%c");
  338. struct tm *tm;
  339. time_t t;
  340. time(&t); tm = localtime(&t);
  341. if (strftime(b,sizeof(b),s,tm))
  342. lua_pushstring(b);
  343. else
  344. lua_error("invalid `date' format");
  345. }
  346. static void setloc (void) {
  347. static int cat[] = {LC_ALL, LC_COLLATE, LC_CTYPE, LC_MONETARY, LC_NUMERIC,
  348. LC_TIME};
  349. static char *catnames[] = {"all", "collate", "ctype", "monetary",
  350. "numeric", "time", NULL};
  351. int op = luaL_findstring(luaL_opt_string(2, "all"), catnames);
  352. luaL_arg_check(op != -1, 2, "invalid option");
  353. lua_pushstring(setlocale(cat[op], luaL_check_string(1)));
  354. }
  355. static void io_exit (void) {
  356. lua_Object o = lua_getparam(1);
  357. exit(lua_isnumber(o) ? (int)lua_getnumber(o) : 1);
  358. }
  359. /* }====================================================== */
  360. static void io_debug (void) {
  361. for (;;) {
  362. char buffer[250];
  363. fprintf(stderr, "lua_debug> ");
  364. if (fgets(buffer, sizeof(buffer), stdin) == 0) return;
  365. if (strcmp(buffer, "cont\n") == 0) return;
  366. lua_dostring(buffer);
  367. }
  368. }
  369. #define MESSAGESIZE 150
  370. #define MAXMESSAGE (MESSAGESIZE*10)
  371. #define MAXSRC 40
  372. static void errorfb (void) {
  373. char buff[MAXMESSAGE];
  374. int level = 1; /* skip level 0 (it's this function) */
  375. lua_Object func;
  376. sprintf(buff, "lua error: %.200s\n", lua_getstring(lua_getparam(1)));
  377. while ((func = lua_stackedfunction(level++)) != LUA_NOOBJECT) {
  378. char *name;
  379. int currentline;
  380. char *chunkname;
  381. char buffchunk[MAXSRC];
  382. int linedefined;
  383. lua_funcinfo(func, &chunkname, &linedefined);
  384. luaL_chunkid(buffchunk, chunkname, MAXSRC);
  385. if (level == 2) strcat(buff, "Active Stack:\n");
  386. strcat(buff, "\t");
  387. if (strlen(buff) > MAXMESSAGE-MESSAGESIZE) {
  388. strcat(buff, "...\n");
  389. break; /* buffer is full */
  390. }
  391. switch (*lua_getobjname(func, &name)) {
  392. case 'g':
  393. sprintf(buff+strlen(buff), "function `%.50s'", name);
  394. break;
  395. case 't':
  396. sprintf(buff+strlen(buff), "`%.50s' tag method", name);
  397. break;
  398. default: {
  399. if (linedefined == 0)
  400. sprintf(buff+strlen(buff), "main of %.50s", buffchunk);
  401. else if (linedefined > 0)
  402. sprintf(buff+strlen(buff), "function <%d:%.50s>",
  403. linedefined, buffchunk);
  404. chunkname = NULL;
  405. }
  406. }
  407. if ((currentline = lua_currentline(func)) > 0)
  408. sprintf(buff+strlen(buff), " at line %d", currentline);
  409. if (chunkname)
  410. sprintf(buff+strlen(buff), " [in %.50s]", buffchunk);
  411. strcat(buff, "\n");
  412. }
  413. func = lua_rawgetglobal("_ALERT");
  414. if (lua_isfunction(func)) { /* avoid error loop if _ALERT is not defined */
  415. lua_pushstring(buff);
  416. lua_callfunction(func);
  417. }
  418. }
  419. static struct luaL_reg iolib[] = {
  420. {"setlocale", setloc},
  421. {"execute", io_execute},
  422. {"remove", io_remove},
  423. {"rename", io_rename},
  424. {"tmpname", io_tmpname},
  425. {"getenv", io_getenv},
  426. {"date", io_date},
  427. {"clock", io_clock},
  428. {"exit", io_exit},
  429. {"debug", io_debug},
  430. {"_ERRORMESSAGE", errorfb}
  431. };
  432. static struct luaL_reg iolibtag[] = {
  433. {"readfrom", io_readfrom},
  434. {"writeto", io_writeto},
  435. {"appendto", io_appendto},
  436. {"flush", io_flush},
  437. {"read", io_read},
  438. {"seek", io_seek},
  439. {"write", io_write}
  440. };
  441. static void openwithtags (void) {
  442. int iotag = lua_newtag();
  443. int closedtag = lua_newtag();
  444. int i;
  445. for (i=0; i<sizeof(iolibtag)/sizeof(iolibtag[0]); i++) {
  446. /* put both tags as upvalues for these functions */
  447. lua_pushnumber(iotag);
  448. lua_pushnumber(closedtag);
  449. lua_pushcclosure(iolibtag[i].func, 2);
  450. lua_setglobal(iolibtag[i].name);
  451. }
  452. setfile(stdin, FINPUT, iotag);
  453. setfile(stdout, FOUTPUT, iotag);
  454. setfile(stdin, "_STDIN", iotag);
  455. setfile(stdout, "_STDOUT", iotag);
  456. setfile(stderr, "_STDERR", iotag);
  457. }
  458. void lua_iolibopen (void) {
  459. luaL_openlib(iolib, (sizeof(iolib)/sizeof(iolib[0])));
  460. openwithtags();
  461. }