]> rtime.felk.cvut.cz Git - l4.git/blob - l4/pkg/lua/lib/contrib/src/liolib.c
update
[l4.git] / l4 / pkg / lua / lib / contrib / src / liolib.c
1 /*
2 ** $Id: liolib.c,v 2.73.1.4 2010/05/14 15:33:51 roberto Exp $
3 ** Standard I/O (and system) library
4 ** See Copyright Notice in lua.h
5 */
6
7
8 #include <errno.h>
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <string.h>
12 #include <ctype.h>
13
14 #define liolib_c
15 #define LUA_LIB
16
17 #include "lua.h"
18
19 #include "lauxlib.h"
20 #include "lualib.h"
21
22 #include "lnum.h"
23 #include "llex.h"
24
25 #define IO_INPUT        1
26 #define IO_OUTPUT       2
27
28
29 static const char *const fnames[] = {"input", "output"};
30
31
32 static int pushresult (lua_State *L, int i, const char *filename) {
33   int en = errno;  /* calls to Lua API may change this value */
34   if (i) {
35     lua_pushboolean(L, 1);
36     return 1;
37   }
38   else {
39     lua_pushnil(L);
40     if (filename)
41       lua_pushfstring(L, "%s: %s", filename, strerror(en));
42     else
43       lua_pushfstring(L, "%s", strerror(en));
44     lua_pushinteger(L, en);
45     return 3;
46   }
47 }
48
49
50 static void fileerror (lua_State *L, int arg, const char *filename) {
51   lua_pushfstring(L, "%s: %s", filename, strerror(errno));
52   luaL_argerror(L, arg, lua_tostring(L, -1));
53 }
54
55
56 #define tofilep(L)      ((FILE **)luaL_checkudata(L, 1, LUA_FILEHANDLE))
57
58
59 static int io_type (lua_State *L) {
60   void *ud;
61   luaL_checkany(L, 1);
62   ud = lua_touserdata(L, 1);
63   lua_getfield(L, LUA_REGISTRYINDEX, LUA_FILEHANDLE);
64   if (ud == NULL || !lua_getmetatable(L, 1) || !lua_rawequal(L, -2, -1))
65     lua_pushnil(L);  /* not a file */
66   else if (*((FILE **)ud) == NULL)
67     lua_pushliteral(L, "closed file");
68   else
69     lua_pushliteral(L, "file");
70   return 1;
71 }
72
73
74 static FILE *tofile (lua_State *L) {
75   FILE **f = tofilep(L);
76   if (*f == NULL)
77     luaL_error(L, "attempt to use a closed file");
78   return *f;
79 }
80
81
82
83 /*
84 ** When creating file handles, always creates a `closed' file handle
85 ** before opening the actual file; so, if there is a memory error, the
86 ** file is not left opened.
87 */
88 static FILE **newfile (lua_State *L) {
89   FILE **pf = (FILE **)lua_newuserdata(L, sizeof(FILE *));
90   *pf = NULL;  /* file handle is currently `closed' */
91   luaL_getmetatable(L, LUA_FILEHANDLE);
92   lua_setmetatable(L, -2);
93   return pf;
94 }
95
96
97 /*
98 ** function to (not) close the standard files stdin, stdout, and stderr
99 */
100 static int io_noclose (lua_State *L) {
101   lua_pushnil(L);
102   lua_pushliteral(L, "cannot close standard file");
103   return 2;
104 }
105
106
107 /*
108 ** function to close 'popen' files
109 */
110 static int io_pclose (lua_State *L) {
111   FILE **p = tofilep(L);
112   int ok = lua_pclose(L, *p);
113   *p = NULL;
114   return pushresult(L, ok, NULL);
115 }
116
117
118 /*
119 ** function to close regular files
120 */
121 static int io_fclose (lua_State *L) {
122   FILE **p = tofilep(L);
123   int ok = (fclose(*p) == 0);
124   *p = NULL;
125   return pushresult(L, ok, NULL);
126 }
127
128
129 static int aux_close (lua_State *L) {
130   lua_getfenv(L, 1);
131   lua_getfield(L, -1, "__close");
132   return (lua_tocfunction(L, -1))(L);
133 }
134
135
136 static int io_close (lua_State *L) {
137   if (lua_isnone(L, 1))
138     lua_rawgeti(L, LUA_ENVIRONINDEX, IO_OUTPUT);
139   tofile(L);  /* make sure argument is a file */
140   return aux_close(L);
141 }
142
143
144 static int io_gc (lua_State *L) {
145   FILE *f = *tofilep(L);
146   /* ignore closed files */
147   if (f != NULL)
148     aux_close(L);
149   return 0;
150 }
151
152
153 static int io_tostring (lua_State *L) {
154   FILE *f = *tofilep(L);
155   if (f == NULL)
156     lua_pushliteral(L, "file (closed)");
157   else
158     lua_pushfstring(L, "file (%p)", f);
159   return 1;
160 }
161
162
163 static int io_open (lua_State *L) {
164   const char *filename = luaL_checkstring(L, 1);
165   const char *mode = luaL_optstring(L, 2, "r");
166   FILE **pf = newfile(L);
167   *pf = fopen(filename, mode);
168   return (*pf == NULL) ? pushresult(L, 0, filename) : 1;
169 }
170
171
172 /*
173 ** this function has a separated environment, which defines the
174 ** correct __close for 'popen' files
175 */
176 static int io_popen (lua_State *L) {
177   const char *filename = luaL_checkstring(L, 1);
178   const char *mode = luaL_optstring(L, 2, "r");
179   FILE **pf = newfile(L);
180   *pf = lua_popen(L, filename, mode);
181   return (*pf == NULL) ? pushresult(L, 0, filename) : 1;
182 }
183
184
185 static int io_tmpfile (lua_State *L) {
186   FILE **pf = newfile(L);
187   *pf = tmpfile();
188   return (*pf == NULL) ? pushresult(L, 0, NULL) : 1;
189 }
190
191
192 static FILE *getiofile (lua_State *L, int findex) {
193   FILE *f;
194   lua_rawgeti(L, LUA_ENVIRONINDEX, findex);
195   f = *(FILE **)lua_touserdata(L, -1);
196   if (f == NULL)
197     luaL_error(L, "standard %s file is closed", fnames[findex - 1]);
198   return f;
199 }
200
201
202 static int g_iofile (lua_State *L, int f, const char *mode) {
203   if (!lua_isnoneornil(L, 1)) {
204     const char *filename = lua_tostring(L, 1);
205     if (filename) {
206       FILE **pf = newfile(L);
207       *pf = fopen(filename, mode);
208       if (*pf == NULL)
209         fileerror(L, 1, filename);
210     }
211     else {
212       tofile(L);  /* check that it's a valid file handle */
213       lua_pushvalue(L, 1);
214     }
215     lua_rawseti(L, LUA_ENVIRONINDEX, f);
216   }
217   /* return current value */
218   lua_rawgeti(L, LUA_ENVIRONINDEX, f);
219   return 1;
220 }
221
222
223 static int io_input (lua_State *L) {
224   return g_iofile(L, IO_INPUT, "r");
225 }
226
227
228 static int io_output (lua_State *L) {
229   return g_iofile(L, IO_OUTPUT, "w");
230 }
231
232
233 static int io_readline (lua_State *L);
234
235
236 static void aux_lines (lua_State *L, int idx, int toclose) {
237   lua_pushvalue(L, idx);
238   lua_pushboolean(L, toclose);  /* close/not close file when finished */
239   lua_pushcclosure(L, io_readline, 2);
240 }
241
242
243 static int f_lines (lua_State *L) {
244   tofile(L);  /* check that it's a valid file handle */
245   aux_lines(L, 1, 0);
246   return 1;
247 }
248
249
250 static int io_lines (lua_State *L) {
251   if (lua_isnoneornil(L, 1)) {  /* no arguments? */
252     /* will iterate over default input */
253     lua_rawgeti(L, LUA_ENVIRONINDEX, IO_INPUT);
254     return f_lines(L);
255   }
256   else {
257     const char *filename = luaL_checkstring(L, 1);
258     FILE **pf = newfile(L);
259     *pf = fopen(filename, "r");
260     if (*pf == NULL)
261       fileerror(L, 1, filename);
262     aux_lines(L, lua_gettop(L), 1);
263     return 1;
264   }
265 }
266
267
268 /*
269 ** {======================================================
270 ** READ
271 ** =======================================================
272 */
273
274 /*
275 * NOTE: Lua's usual '*n' format specifier reads numbers as floating point,
276 *       and converts to integer if they are. IN ORDER TO NOT LOSE ACCURACY,
277 *       a new '*i' format specifier is added (will also be speedier, on non-
278 *       FPU systems).
279 */
280
281 static int read_number (lua_State *L, FILE *f) {
282   lua_Number d;
283   if (fscanf(f, LUA_NUMBER_SCAN, &d) == 1) {
284 #ifdef LUA_TINT
285     lua_Integer tmp;
286     lua_number2integer(tmp, d);
287     if (cast_num(tmp) == d)
288         lua_pushinteger(L, tmp);
289     else
290 #endif
291     lua_pushnumber(L, d);
292     return 1;
293   }
294   else {
295     lua_pushnil(L);  /* "result" to be removed */
296     return 0;  /* read fails */
297   }
298 }
299
300 static int read_integer (lua_State *L, FILE *f) {
301   lua_Integer i;
302   if (fscanf(f, LUA_INTEGER_SCAN, &i) == 1) {
303     lua_pushinteger(L, i);
304     return 1;
305   }
306   else return 0;  /* read fails */
307 }
308
309 #ifdef LNUM_COMPLEX
310 static int read_complex (lua_State *L, FILE *f) {
311   /* NNN / NNNi / NNN+MMMi / NNN-MMMi */
312   lua_Number a,b;
313   if (fscanf(f, LUA_NUMBER_SCAN, &a) == 1) {
314     int c=fgetc(f);
315     switch(c) {
316         case 'i':
317             lua_pushcomplex(L, a*I);
318             return 1;
319         case '+':
320         case '-':
321             /* "i" is consumed if at the end; just 'NNN+MMM' will most likely
322              * behave as if "i" was there? (TBD: test)
323              */
324             if (fscanf(f, LUA_NUMBER_SCAN "i", &b) == 1) {
325                 lua_pushcomplex(L, a+ (c=='+' ? b:-b)*I);
326                 return 1;
327             }
328     }
329     ungetc( c,f );
330     lua_pushnumber(L,a);  /*real part only*/
331     return 1;
332   }
333   return 0;  /* read fails */
334 }
335 #endif
336
337
338 static int test_eof (lua_State *L, FILE *f) {
339   int c = getc(f);
340   ungetc(c, f);
341   lua_pushlstring(L, NULL, 0);
342   return (c != EOF);
343 }
344
345
346 static int read_line (lua_State *L, FILE *f) {
347   luaL_Buffer b;
348   luaL_buffinit(L, &b);
349   for (;;) {
350     size_t l;
351     char *p = luaL_prepbuffer(&b);
352     if (fgets(p, LUAL_BUFFERSIZE, f) == NULL) {  /* eof? */
353       luaL_pushresult(&b);  /* close buffer */
354       return (lua_objlen(L, -1) > 0);  /* check whether read something */
355     }
356     l = strlen(p);
357     if (l == 0 || p[l-1] != '\n')
358       luaL_addsize(&b, l);
359     else {
360       luaL_addsize(&b, l - 1);  /* do not include `eol' */
361       luaL_pushresult(&b);  /* close buffer */
362       return 1;  /* read at least an `eol' */
363     }
364   }
365 }
366
367
368 static int read_chars (lua_State *L, FILE *f, size_t n) {
369   size_t rlen;  /* how much to read */
370   size_t nr;  /* number of chars actually read */
371   luaL_Buffer b;
372   luaL_buffinit(L, &b);
373   rlen = LUAL_BUFFERSIZE;  /* try to read that much each time */
374   do {
375     char *p = luaL_prepbuffer(&b);
376     if (rlen > n) rlen = n;  /* cannot read more than asked */
377     nr = fread(p, sizeof(char), rlen, f);
378     luaL_addsize(&b, nr);
379     n -= nr;  /* still have to read `n' chars */
380   } while (n > 0 && nr == rlen);  /* until end of count or eof */
381   luaL_pushresult(&b);  /* close buffer */
382   return (n == 0 || lua_objlen(L, -1) > 0);
383 }
384
385
386 static int g_read (lua_State *L, FILE *f, int first) {
387   int nargs = lua_gettop(L) - 1;
388   int success;
389   int n;
390   clearerr(f);
391   if (nargs == 0) {  /* no arguments? */
392     success = read_line(L, f);
393     n = first+1;  /* to return 1 result */
394   }
395   else {  /* ensure stack space for all results and for auxlib's buffer */
396     luaL_checkstack(L, nargs+LUA_MINSTACK, "too many arguments");
397     success = 1;
398     for (n = first; nargs-- && success; n++) {
399       if (lua_type(L, n) == LUA_TNUMBER) {
400         size_t l = (size_t)lua_tointeger(L, n);
401         success = (l == 0) ? test_eof(L, f) : read_chars(L, f, l);
402       }
403       else {
404         const char *p = lua_tostring(L, n);
405         luaL_argcheck(L, p && p[0] == '*', n, "invalid option");
406         switch (p[1]) {
407           case 'n':  /* number */
408             success = read_number(L, f);
409             break;
410           case 'i':  /* integer (full accuracy) */
411             success = read_integer(L, f);
412             break;
413 #ifdef LNUM_COMPLEX
414           case 'c':  /* complex */
415             success = read_complex(L, f);
416             break;
417 #endif
418           case 'l':  /* line */
419             success = read_line(L, f);
420             break;
421           case 'a':  /* file */
422             read_chars(L, f, ~((size_t)0));  /* read MAX_SIZE_T chars */
423             success = 1; /* always success */
424             break;
425           default:
426             return luaL_argerror(L, n, "invalid format");
427         }
428       }
429     }
430   }
431   if (ferror(f))
432     return pushresult(L, 0, NULL);
433   if (!success) {
434     lua_pop(L, 1);  /* remove last result */
435     lua_pushnil(L);  /* push nil instead */
436   }
437   return n - first;
438 }
439
440
441 static int io_read (lua_State *L) {
442   return g_read(L, getiofile(L, IO_INPUT), 1);
443 }
444
445
446 static int f_read (lua_State *L) {
447   return g_read(L, tofile(L), 2);
448 }
449
450
451 static int io_readline (lua_State *L) {
452   FILE *f = *(FILE **)lua_touserdata(L, lua_upvalueindex(1));
453   int sucess;
454   if (f == NULL)  /* file is already closed? */
455     luaL_error(L, "file is already closed");
456   sucess = read_line(L, f);
457   if (ferror(f))
458     return luaL_error(L, "%s", strerror(errno));
459   if (sucess) return 1;
460   else {  /* EOF */
461     if (lua_toboolean(L, lua_upvalueindex(2))) {  /* generator created file? */
462       lua_settop(L, 0);
463       lua_pushvalue(L, lua_upvalueindex(1));
464       aux_close(L);  /* close it */
465     }
466     return 0;
467   }
468 }
469
470 /* }====================================================== */
471
472
473 static int g_write (lua_State *L, FILE *f, int arg) {
474   int nargs = lua_gettop(L) - 1;
475   int status = 1;
476   for (; nargs--; arg++) {
477     if (lua_type(L, arg) == LUA_TNUMBER) {
478       if (lua_isinteger(L,arg))
479           status = status && fprintf(f, LUA_INTEGER_FMT, lua_tointeger(L, arg)) > 0;
480       else
481           status = status && fprintf(f, LUA_NUMBER_FMT, lua_tonumber(L, arg)) > 0;
482     }
483     else {
484       size_t l;
485       const char *s = luaL_checklstring(L, arg, &l);
486       status = status && (fwrite(s, sizeof(char), l, f) == l);
487     }
488   }
489   return pushresult(L, status, NULL);
490 }
491
492
493 static int io_write (lua_State *L) {
494   return g_write(L, getiofile(L, IO_OUTPUT), 1);
495 }
496
497
498 static int f_write (lua_State *L) {
499   return g_write(L, tofile(L), 2);
500 }
501
502
503 static int f_seek (lua_State *L) {
504   static const int mode[] = {SEEK_SET, SEEK_CUR, SEEK_END};
505   static const char *const modenames[] = {"set", "cur", "end", NULL};
506   FILE *f = tofile(L);
507   int op = luaL_checkoption(L, 2, "cur", modenames);
508   long offset = luaL_optlong(L, 3, 0);
509   op = fseek(f, offset, mode[op]);
510   if (op)
511     return pushresult(L, 0, NULL);  /* error */
512   else {
513     lua_pushinteger(L, ftell(f));
514     return 1;
515   }
516 }
517
518
519 static int f_setvbuf (lua_State *L) {
520   static const int mode[] = {_IONBF, _IOFBF, _IOLBF};
521   static const char *const modenames[] = {"no", "full", "line", NULL};
522   FILE *f = tofile(L);
523   int op = luaL_checkoption(L, 2, NULL, modenames);
524   size_t sz = luaL_optint32(L, 3, LUAL_BUFFERSIZE);
525   int res = setvbuf(f, NULL, mode[op], sz);
526   return pushresult(L, res == 0, NULL);
527 }
528
529
530
531 static int io_flush (lua_State *L) {
532   return pushresult(L, fflush(getiofile(L, IO_OUTPUT)) == 0, NULL);
533 }
534
535
536 static int f_flush (lua_State *L) {
537   return pushresult(L, fflush(tofile(L)) == 0, NULL);
538 }
539
540
541 static const luaL_Reg iolib[] = {
542   {"close", io_close},
543   {"flush", io_flush},
544   {"input", io_input},
545   {"lines", io_lines},
546   {"open", io_open},
547   {"output", io_output},
548   {"popen", io_popen},
549   {"read", io_read},
550   {"tmpfile", io_tmpfile},
551   {"type", io_type},
552   {"write", io_write},
553   {NULL, NULL}
554 };
555
556
557 static const luaL_Reg flib[] = {
558   {"close", io_close},
559   {"flush", f_flush},
560   {"lines", f_lines},
561   {"read", f_read},
562   {"seek", f_seek},
563   {"setvbuf", f_setvbuf},
564   {"write", f_write},
565   {"__gc", io_gc},
566   {"__tostring", io_tostring},
567   {NULL, NULL}
568 };
569
570
571 static void createmeta (lua_State *L) {
572   luaL_newmetatable(L, LUA_FILEHANDLE);  /* create metatable for file handles */
573   lua_pushvalue(L, -1);  /* push metatable */
574   lua_setfield(L, -2, "__index");  /* metatable.__index = metatable */
575   luaL_register(L, NULL, flib);  /* file methods */
576 }
577
578
579 static void createstdfile (lua_State *L, FILE *f, int k, const char *fname) {
580   *newfile(L) = f;
581   if (k > 0) {
582     lua_pushvalue(L, -1);
583     lua_rawseti(L, LUA_ENVIRONINDEX, k);
584   }
585   lua_pushvalue(L, -2);  /* copy environment */
586   lua_setfenv(L, -2);  /* set it */
587   lua_setfield(L, -3, fname);
588 }
589
590
591 static void newfenv (lua_State *L, lua_CFunction cls) {
592   lua_createtable(L, 0, 1);
593   lua_pushcfunction(L, cls);
594   lua_setfield(L, -2, "__close");
595 }
596
597
598 LUALIB_API int luaopen_io (lua_State *L) {
599   createmeta(L);
600   /* create (private) environment (with fields IO_INPUT, IO_OUTPUT, __close) */
601   newfenv(L, io_fclose);
602   lua_replace(L, LUA_ENVIRONINDEX);
603   /* open library */
604   luaL_register(L, LUA_IOLIBNAME, iolib);
605   /* create (and set) default files */
606   newfenv(L, io_noclose);  /* close function for default files */
607   createstdfile(L, stdin, IO_INPUT, "stdin");
608   createstdfile(L, stdout, IO_OUTPUT, "stdout");
609   createstdfile(L, stderr, 0, "stderr");
610   lua_pop(L, 1);  /* pop environment for default files */
611   lua_getfield(L, -1, "popen");
612   newfenv(L, io_pclose);  /* create environment for 'popen' */
613   lua_setfenv(L, -2);  /* set fenv for 'popen' */
614   lua_pop(L, 1);  /* pop 'popen' */
615   return 1;
616 }
617