liolib.c 12 KB

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