liolib.c 14 KB

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