Imported from ../lua-4.0.1.tar.gz.
[lua.git] / src / lib / liolib.c
blob70f8057ac9c0856b7820ebff7365e3f147a9c918
1 /*
2 ** $Id: liolib.c,v 1.91 2000/10/31 13:10:24 roberto Exp $
3 ** Standard I/O (and system) library
4 ** See Copyright Notice in lua.h
5 */
8 #include <ctype.h>
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <string.h>
12 #include <time.h>
14 #include "lua.h"
16 #include "lauxlib.h"
17 #include "luadebug.h"
18 #include "lualib.h"
21 #ifndef OLD_ANSI
22 #include <errno.h>
23 #include <locale.h>
24 #define realloc(b,s) ((b) == NULL ? malloc(s) : (realloc)(b, s))
25 #define free(b) if (b) (free)(b)
26 #else
27 /* no support for locale and for strerror: fake them */
28 #define setlocale(a,b) ((void)a, strcmp((b),"C")==0?"C":NULL)
29 #define LC_ALL 0
30 #define LC_COLLATE 0
31 #define LC_CTYPE 0
32 #define LC_MONETARY 0
33 #define LC_NUMERIC 0
34 #define LC_TIME 0
35 #define strerror(e) "generic I/O error"
36 #define errno (-1)
37 #endif
41 #ifdef POPEN
42 /* FILE *popen();
43 int pclose(); */
44 #define CLOSEFILE(L, f) ((pclose(f) == -1) ? fclose(f) : 0)
45 #else
46 /* no support for popen */
47 #define popen(x,y) NULL /* that is, popen always fails */
48 #define CLOSEFILE(L, f) (fclose(f))
49 #endif
52 #define INFILE 0
53 #define OUTFILE 1
55 typedef struct IOCtrl {
56 int ref[2]; /* ref for strings _INPUT/_OUTPUT */
57 int iotag; /* tag for file handles */
58 int closedtag; /* tag for closed handles */
59 } IOCtrl;
63 static const char *const filenames[] = {"_INPUT", "_OUTPUT"};
66 static int pushresult (lua_State *L, int i) {
67 if (i) {
68 lua_pushuserdata(L, NULL);
69 return 1;
71 else {
72 lua_pushnil(L);
73 lua_pushstring(L, strerror(errno));
74 lua_pushnumber(L, errno);
75 return 3;;
81 ** {======================================================
82 ** FILE Operations
83 ** =======================================================
87 static FILE *gethandle (lua_State *L, IOCtrl *ctrl, int f) {
88 void *p = lua_touserdata(L, f);
89 if (p != NULL) { /* is `f' a userdata ? */
90 int ftag = lua_tag(L, f);
91 if (ftag == ctrl->iotag) /* does it have the correct tag? */
92 return (FILE *)p;
93 else if (ftag == ctrl->closedtag)
94 lua_error(L, "cannot access a closed file");
95 /* else go through */
97 return NULL;
101 static FILE *getnonullfile (lua_State *L, IOCtrl *ctrl, int arg) {
102 FILE *f = gethandle(L, ctrl, arg);
103 luaL_arg_check(L, f, arg, "invalid file handle");
104 return f;
108 static FILE *getfilebyref (lua_State *L, IOCtrl *ctrl, int inout) {
109 FILE *f;
110 lua_getglobals(L);
111 lua_getref(L, ctrl->ref[inout]);
112 lua_rawget(L, -2);
113 f = gethandle(L, ctrl, -1);
114 if (f == NULL)
115 luaL_verror(L, "global variable `%.10s' is not a file handle",
116 filenames[inout]);
117 return f;
121 static void setfilebyname (lua_State *L, IOCtrl *ctrl, FILE *f,
122 const char *name) {
123 lua_pushusertag(L, f, ctrl->iotag);
124 lua_setglobal(L, name);
128 #define setfile(L,ctrl,f,inout) (setfilebyname(L,ctrl,f,filenames[inout]))
131 static int setreturn (lua_State *L, IOCtrl *ctrl, FILE *f, int inout) {
132 if (f == NULL)
133 return pushresult(L, 0);
134 else {
135 setfile(L, ctrl, f, inout);
136 lua_pushusertag(L, f, ctrl->iotag);
137 return 1;
142 static int closefile (lua_State *L, IOCtrl *ctrl, FILE *f) {
143 if (f == stdin || f == stdout || f == stderr)
144 return 1;
145 else {
146 lua_pushusertag(L, f, ctrl->iotag);
147 lua_settag(L, ctrl->closedtag);
148 return (CLOSEFILE(L, f) == 0);
153 static int io_close (lua_State *L) {
154 IOCtrl *ctrl = (IOCtrl *)lua_touserdata(L, -1);
155 lua_pop(L, 1); /* remove upvalue */
156 return pushresult(L, closefile(L, ctrl, getnonullfile(L, ctrl, 1)));
160 static int file_collect (lua_State *L) {
161 IOCtrl *ctrl = (IOCtrl *)lua_touserdata(L, -1);
162 FILE *f = getnonullfile(L, ctrl, 1);
163 if (f != stdin && f != stdout && f != stderr)
164 CLOSEFILE(L, f);
165 return 0;
169 static int io_open (lua_State *L) {
170 IOCtrl *ctrl = (IOCtrl *)lua_touserdata(L, -1);
171 FILE *f;
172 lua_pop(L, 1); /* remove upvalue */
173 f = fopen(luaL_check_string(L, 1), luaL_check_string(L, 2));
174 if (f) {
175 lua_pushusertag(L, f, ctrl->iotag);
176 return 1;
178 else
179 return pushresult(L, 0);
184 static int io_fromto (lua_State *L, int inout, const char *mode) {
185 IOCtrl *ctrl = (IOCtrl *)lua_touserdata(L, -1);
186 FILE *current;
187 lua_pop(L, 1); /* remove upvalue */
188 if (lua_isnull(L, 1)) {
189 closefile(L, ctrl, getfilebyref(L, ctrl, inout));
190 current = (inout == 0) ? stdin : stdout;
192 else if (lua_tag(L, 1) == ctrl->iotag) /* deprecated option */
193 current = (FILE *)lua_touserdata(L, 1);
194 else {
195 const char *s = luaL_check_string(L, 1);
196 current = (*s == '|') ? popen(s+1, mode) : fopen(s, mode);
198 return setreturn(L, ctrl, current, inout);
202 static int io_readfrom (lua_State *L) {
203 return io_fromto(L, INFILE, "r");
207 static int io_writeto (lua_State *L) {
208 return io_fromto(L, OUTFILE, "w");
212 static int io_appendto (lua_State *L) {
213 IOCtrl *ctrl = (IOCtrl *)lua_touserdata(L, -1);
214 FILE *current;
215 lua_pop(L, 1); /* remove upvalue */
216 current = fopen(luaL_check_string(L, 1), "a");
217 return setreturn(L, ctrl, current, OUTFILE);
223 ** {======================================================
224 ** READ
225 ** =======================================================
230 #ifdef LUA_COMPAT_READPATTERN
233 ** We cannot lookahead without need, because this can lock stdin.
234 ** This flag signals when we need to read a next char.
236 #define NEED_OTHER (EOF-1) /* just some flag different from EOF */
239 static int read_pattern (lua_State *L, FILE *f, const char *p) {
240 int inskip = 0; /* {skip} level */
241 int c = NEED_OTHER;
242 luaL_Buffer b;
243 luaL_buffinit(L, &b);
244 while (*p != '\0') {
245 switch (*p) {
246 case '{':
247 inskip++;
248 p++;
249 continue;
250 case '}':
251 if (!inskip) lua_error(L, "unbalanced braces in read pattern");
252 inskip--;
253 p++;
254 continue;
255 default: {
256 const char *ep = luaI_classend(L, p); /* get what is next */
257 int m; /* match result */
258 if (c == NEED_OTHER) c = getc(f);
259 m = (c==EOF) ? 0 : luaI_singlematch(c, p, ep);
260 if (m) {
261 if (!inskip) luaL_putchar(&b, c);
262 c = NEED_OTHER;
264 switch (*ep) {
265 case '+': /* repetition (1 or more) */
266 if (!m) goto break_while; /* pattern fails? */
267 /* else go through */
268 case '*': /* repetition (0 or more) */
269 while (m) { /* reads the same item until it fails */
270 c = getc(f);
271 m = (c==EOF) ? 0 : luaI_singlematch(c, p, ep);
272 if (m && !inskip) luaL_putchar(&b, c);
274 /* go through to continue reading the pattern */
275 case '?': /* optional */
276 p = ep+1; /* continues reading the pattern */
277 continue;
278 default:
279 if (!m) goto break_while; /* pattern fails? */
280 p = ep; /* else continues reading the pattern */
284 } break_while:
285 if (c != NEED_OTHER) ungetc(c, f);
286 luaL_pushresult(&b); /* close buffer */
287 return (*p == '\0');
290 #else
292 #define read_pattern(L, f, p) (lua_error(L, "read patterns are deprecated"), 0)
294 #endif
297 static int read_number (lua_State *L, FILE *f) {
298 double d;
299 if (fscanf(f, "%lf", &d) == 1) {
300 lua_pushnumber(L, d);
301 return 1;
303 else return 0; /* read fails */
307 static int read_word (lua_State *L, FILE *f) {
308 int c;
309 luaL_Buffer b;
310 luaL_buffinit(L, &b);
311 do { c = fgetc(f); } while (isspace(c)); /* skip spaces */
312 while (c != EOF && !isspace(c)) {
313 luaL_putchar(&b, c);
314 c = fgetc(f);
316 ungetc(c, f);
317 luaL_pushresult(&b); /* close buffer */
318 return (lua_strlen(L, -1) > 0);
322 static int read_line (lua_State *L, FILE *f) {
323 int n = 0;
324 luaL_Buffer b;
325 luaL_buffinit(L, &b);
326 for (;;) {
327 char *p = luaL_prepbuffer(&b);
328 if (!fgets(p, LUAL_BUFFERSIZE, f)) /* read fails? */
329 break;
330 n = strlen(p);
331 if (p[n-1] != '\n')
332 luaL_addsize(&b, n);
333 else {
334 luaL_addsize(&b, n-1); /* do not add the `\n' */
335 break;
338 luaL_pushresult(&b); /* close buffer */
339 return (n > 0); /* read something? */
343 static void read_file (lua_State *L, FILE *f) {
344 size_t len = 0;
345 size_t size = BUFSIZ;
346 char *buffer = NULL;
347 for (;;) {
348 char *newbuffer = (char *)realloc(buffer, size);
349 if (newbuffer == NULL) {
350 free(buffer);
351 lua_error(L, "not enough memory to read a file");
353 buffer = newbuffer;
354 len += fread(buffer+len, sizeof(char), size-len, f);
355 if (len < size) break; /* did not read all it could */
356 size *= 2;
358 lua_pushlstring(L, buffer, len);
359 free(buffer);
363 static int read_chars (lua_State *L, FILE *f, size_t n) {
364 char *buffer;
365 size_t n1;
366 char statbuff[BUFSIZ];
367 if (n <= BUFSIZ)
368 buffer = statbuff;
369 else {
370 buffer = (char *)malloc(n);
371 if (buffer == NULL)
372 lua_error(L, "not enough memory to read a file");
374 n1 = fread(buffer, sizeof(char), n, f);
375 lua_pushlstring(L, buffer, n1);
376 if (buffer != statbuff) free(buffer);
377 return (n1 > 0 || n == 0);
381 static int io_read (lua_State *L) {
382 IOCtrl *ctrl = (IOCtrl *)lua_touserdata(L, -1);
383 int lastarg = lua_gettop(L) - 1;
384 int firstarg = 1;
385 FILE *f = gethandle(L, ctrl, firstarg);
386 int n;
387 if (f) firstarg++;
388 else f = getfilebyref(L, ctrl, INFILE); /* get _INPUT */
389 lua_pop(L, 1);
390 if (firstarg > lastarg) { /* no arguments? */
391 lua_settop(L, 0); /* erase upvalue and other eventual garbage */
392 firstarg = lastarg = 1; /* correct indices */
393 lua_pushstring(L, "*l"); /* push default argument */
395 else /* ensure stack space for all results and for auxlib's buffer */
396 luaL_checkstack(L, lastarg-firstarg+1+LUA_MINSTACK, "too many arguments");
397 for (n = firstarg; n<=lastarg; n++) {
398 int success;
399 if (lua_isnumber(L, n))
400 success = read_chars(L, f, (size_t)lua_tonumber(L, n));
401 else {
402 const char *p = luaL_check_string(L, n);
403 if (p[0] != '*')
404 success = read_pattern(L, f, p); /* deprecated! */
405 else {
406 switch (p[1]) {
407 case 'n': /* number */
408 if (!read_number(L, f)) goto endloop; /* read fails */
409 continue; /* number is already pushed; avoid the "pushstring" */
410 case 'l': /* line */
411 success = read_line(L, f);
412 break;
413 case 'a': /* file */
414 read_file(L, f);
415 success = 1; /* always success */
416 break;
417 case 'w': /* word */
418 success = read_word(L, f);
419 break;
420 default:
421 luaL_argerror(L, n, "invalid format");
422 success = 0; /* to avoid warnings */
426 if (!success) {
427 lua_pop(L, 1); /* remove last result */
428 break; /* read fails */
430 } endloop:
431 return n - firstarg;
434 /* }====================================================== */
437 static int io_write (lua_State *L) {
438 int lastarg = lua_gettop(L) - 1;
439 IOCtrl *ctrl = (IOCtrl *)lua_touserdata(L, -1);
440 int arg = 1;
441 int status = 1;
442 FILE *f = gethandle(L, ctrl, arg);
443 if (f) arg++;
444 else f = getfilebyref(L, ctrl, OUTFILE); /* get _OUTPUT */
445 for (; arg <= lastarg; arg++) {
446 if (lua_type(L, arg) == LUA_TNUMBER) { /* LUA_NUMBER */
447 /* optimization: could be done exactly as for strings */
448 status = status && fprintf(f, "%.16g", lua_tonumber(L, arg)) > 0;
450 else {
451 size_t l;
452 const char *s = luaL_check_lstr(L, arg, &l);
453 status = status && (fwrite(s, sizeof(char), l, f) == l);
456 pushresult(L, status);
457 return 1;
461 static int io_seek (lua_State *L) {
462 static const int mode[] = {SEEK_SET, SEEK_CUR, SEEK_END};
463 static const char *const modenames[] = {"set", "cur", "end", NULL};
464 IOCtrl *ctrl = (IOCtrl *)lua_touserdata(L, -1);
465 FILE *f;
466 int op;
467 long offset;
468 lua_pop(L, 1); /* remove upvalue */
469 f = getnonullfile(L, ctrl, 1);
470 op = luaL_findstring(luaL_opt_string(L, 2, "cur"), modenames);
471 offset = luaL_opt_long(L, 3, 0);
472 luaL_arg_check(L, op != -1, 2, "invalid mode");
473 op = fseek(f, offset, mode[op]);
474 if (op)
475 return pushresult(L, 0); /* error */
476 else {
477 lua_pushnumber(L, ftell(f));
478 return 1;
483 static int io_flush (lua_State *L) {
484 IOCtrl *ctrl = (IOCtrl *)lua_touserdata(L, -1);
485 FILE *f;
486 lua_pop(L, 1); /* remove upvalue */
487 f = gethandle(L, ctrl, 1);
488 luaL_arg_check(L, f || lua_isnull(L, 1), 1, "invalid file handle");
489 return pushresult(L, fflush(f) == 0);
492 /* }====================================================== */
496 ** {======================================================
497 ** Other O.S. Operations
498 ** =======================================================
501 static int io_execute (lua_State *L) {
502 lua_pushnumber(L, system(luaL_check_string(L, 1)));
503 return 1;
507 static int io_remove (lua_State *L) {
508 return pushresult(L, remove(luaL_check_string(L, 1)) == 0);
512 static int io_rename (lua_State *L) {
513 return pushresult(L, rename(luaL_check_string(L, 1),
514 luaL_check_string(L, 2)) == 0);
518 static int io_tmpname (lua_State *L) {
519 lua_pushstring(L, tmpnam(NULL));
520 return 1;
525 static int io_getenv (lua_State *L) {
526 lua_pushstring(L, getenv(luaL_check_string(L, 1))); /* if NULL push nil */
527 return 1;
531 static int io_clock (lua_State *L) {
532 lua_pushnumber(L, ((double)clock())/CLOCKS_PER_SEC);
533 return 1;
537 static int io_date (lua_State *L) {
538 char b[256];
539 const char *s = luaL_opt_string(L, 1, "%c");
540 struct tm *stm;
541 time_t t;
542 time(&t); stm = localtime(&t);
543 if (strftime(b, sizeof(b), s, stm))
544 lua_pushstring(L, b);
545 else
546 lua_error(L, "invalid `date' format");
547 return 1;
551 static int setloc (lua_State *L) {
552 static const int cat[] = {LC_ALL, LC_COLLATE, LC_CTYPE, LC_MONETARY,
553 LC_NUMERIC, LC_TIME};
554 static const char *const catnames[] = {"all", "collate", "ctype", "monetary",
555 "numeric", "time", NULL};
556 int op = luaL_findstring(luaL_opt_string(L, 2, "all"), catnames);
557 luaL_arg_check(L, op != -1, 2, "invalid option");
558 lua_pushstring(L, setlocale(cat[op], luaL_check_string(L, 1)));
559 return 1;
563 static int io_exit (lua_State *L) {
564 exit(luaL_opt_int(L, 1, EXIT_SUCCESS));
565 return 0; /* to avoid warnings */
568 /* }====================================================== */
572 static int io_debug (lua_State *L) {
573 for (;;) {
574 char buffer[250];
575 fprintf(stderr, "lua_debug> ");
576 if (fgets(buffer, sizeof(buffer), stdin) == 0 ||
577 strcmp(buffer, "cont\n") == 0)
578 return 0;
579 lua_dostring(L, buffer);
580 lua_settop(L, 0); /* remove eventual returns */
585 #define LEVELS1 12 /* size of the first part of the stack */
586 #define LEVELS2 10 /* size of the second part of the stack */
588 static int errorfb (lua_State *L) {
589 int level = 1; /* skip level 0 (it's this function) */
590 int firstpart = 1; /* still before eventual `...' */
591 lua_Debug ar;
592 luaL_Buffer b;
593 luaL_buffinit(L, &b);
594 luaL_addstring(&b, "error: ");
595 luaL_addstring(&b, luaL_check_string(L, 1));
596 luaL_addstring(&b, "\n");
597 while (lua_getstack(L, level++, &ar)) {
598 char buff[120]; /* enough to fit following `sprintf's */
599 if (level == 2)
600 luaL_addstring(&b, "stack traceback:\n");
601 else if (level > LEVELS1 && firstpart) {
602 /* no more than `LEVELS2' more levels? */
603 if (!lua_getstack(L, level+LEVELS2, &ar))
604 level--; /* keep going */
605 else {
606 luaL_addstring(&b, " ...\n"); /* too many levels */
607 while (lua_getstack(L, level+LEVELS2, &ar)) /* find last levels */
608 level++;
610 firstpart = 0;
611 continue;
613 sprintf(buff, "%4d: ", level-1);
614 luaL_addstring(&b, buff);
615 lua_getinfo(L, "Snl", &ar);
616 switch (*ar.namewhat) {
617 case 'g': case 'l': /* global, local */
618 sprintf(buff, "function `%.50s'", ar.name);
619 break;
620 case 'f': /* field */
621 sprintf(buff, "method `%.50s'", ar.name);
622 break;
623 case 't': /* tag method */
624 sprintf(buff, "`%.50s' tag method", ar.name);
625 break;
626 default: {
627 if (*ar.what == 'm') /* main? */
628 sprintf(buff, "main of %.70s", ar.short_src);
629 else if (*ar.what == 'C') /* C function? */
630 sprintf(buff, "%.70s", ar.short_src);
631 else
632 sprintf(buff, "function <%d:%.70s>", ar.linedefined, ar.short_src);
633 ar.source = NULL; /* do not print source again */
636 luaL_addstring(&b, buff);
637 if (ar.currentline > 0) {
638 sprintf(buff, " at line %d", ar.currentline);
639 luaL_addstring(&b, buff);
641 if (ar.source) {
642 sprintf(buff, " [%.70s]", ar.short_src);
643 luaL_addstring(&b, buff);
645 luaL_addstring(&b, "\n");
647 luaL_pushresult(&b);
648 lua_getglobal(L, LUA_ALERT);
649 if (lua_isfunction(L, -1)) { /* avoid loop if _ALERT is not defined */
650 lua_pushvalue(L, -2); /* error message */
651 lua_rawcall(L, 1, 0);
653 return 0;
658 static const struct luaL_reg iolib[] = {
659 {LUA_ERRORMESSAGE, errorfb},
660 {"clock", io_clock},
661 {"date", io_date},
662 {"debug", io_debug},
663 {"execute", io_execute},
664 {"exit", io_exit},
665 {"getenv", io_getenv},
666 {"remove", io_remove},
667 {"rename", io_rename},
668 {"setlocale", setloc},
669 {"tmpname", io_tmpname}
673 static const struct luaL_reg iolibtag[] = {
674 {"appendto", io_appendto},
675 {"closefile", io_close},
676 {"flush", io_flush},
677 {"openfile", io_open},
678 {"read", io_read},
679 {"readfrom", io_readfrom},
680 {"seek", io_seek},
681 {"write", io_write},
682 {"writeto", io_writeto}
686 static void openwithcontrol (lua_State *L) {
687 IOCtrl *ctrl = (IOCtrl *)lua_newuserdata(L, sizeof(IOCtrl));
688 unsigned int i;
689 ctrl->iotag = lua_newtag(L);
690 ctrl->closedtag = lua_newtag(L);
691 for (i=0; i<sizeof(iolibtag)/sizeof(iolibtag[0]); i++) {
692 /* put `ctrl' as upvalue for these functions */
693 lua_pushvalue(L, -1);
694 lua_pushcclosure(L, iolibtag[i].func, 1);
695 lua_setglobal(L, iolibtag[i].name);
697 /* create references to variable names */
698 lua_pushstring(L, filenames[INFILE]);
699 ctrl->ref[INFILE] = lua_ref(L, 1);
700 lua_pushstring(L, filenames[OUTFILE]);
701 ctrl->ref[OUTFILE] = lua_ref(L, 1);
702 /* predefined file handles */
703 setfile(L, ctrl, stdin, INFILE);
704 setfile(L, ctrl, stdout, OUTFILE);
705 setfilebyname(L, ctrl, stdin, "_STDIN");
706 setfilebyname(L, ctrl, stdout, "_STDOUT");
707 setfilebyname(L, ctrl, stderr, "_STDERR");
708 /* close files when collected */
709 lua_pushcclosure(L, file_collect, 1); /* pops `ctrl' from stack */
710 lua_settagmethod(L, ctrl->iotag, "gc");
714 LUALIB_API void lua_iolibopen (lua_State *L) {
715 luaL_openl(L, iolib);
716 openwithcontrol(L);