liolib.c 12 KB

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