liolib.c 11 KB

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