liolib.c 12 KB

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