liolib.c 11 KB

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