1*f0dad708Snikita /* $NetBSD: liolib.c,v 1.10 2023/04/16 20:46:17 nikita Exp $ */
2bee09862Smbalmer
3dbec5304Smbalmer /*
4*f0dad708Snikita ** Id: liolib.c
5dbec5304Smbalmer ** Standard I/O (and system) library
6dbec5304Smbalmer ** See Copyright Notice in lua.h
7dbec5304Smbalmer */
8dbec5304Smbalmer
973008250Slneto #define liolib_c
1073008250Slneto #define LUA_LIB
11dbec5304Smbalmer
1273008250Slneto #include "lprefix.h"
134ab4902eSlneto
144ab4902eSlneto
154ab4902eSlneto #include <ctype.h>
16dbec5304Smbalmer #include <errno.h>
174ab4902eSlneto #include <locale.h>
18dbec5304Smbalmer #include <stdio.h>
19dbec5304Smbalmer #include <stdlib.h>
20dbec5304Smbalmer #include <string.h>
21dbec5304Smbalmer
22dbec5304Smbalmer #include "lua.h"
23dbec5304Smbalmer
24dbec5304Smbalmer #include "lauxlib.h"
25dbec5304Smbalmer #include "lualib.h"
26dbec5304Smbalmer
27dbec5304Smbalmer
282d6cb6c2Slneto
29dbec5304Smbalmer
304ab4902eSlneto /*
314ab4902eSlneto ** Change this macro to accept other modes for 'fopen' besides
324ab4902eSlneto ** the standard ones.
334ab4902eSlneto */
342d6cb6c2Slneto #if !defined(l_checkmode)
352d6cb6c2Slneto
362d6cb6c2Slneto /* accepted extensions to 'mode' in 'fopen' */
372d6cb6c2Slneto #if !defined(L_MODEEXT)
382d6cb6c2Slneto #define L_MODEEXT "b"
392d6cb6c2Slneto #endif
402d6cb6c2Slneto
412d6cb6c2Slneto /* Check whether 'mode' matches '[rwa]%+?[L_MODEEXT]*' */
l_checkmode(const char * mode)429e2f6347Smbalmer static int l_checkmode (const char *mode) {
439e2f6347Smbalmer return (*mode != '\0' && strchr("rwa", *(mode++)) != NULL &&
44*f0dad708Snikita (*mode != '+' || ((void)(++mode), 1)) && /* skip if char is '+' */
459e2f6347Smbalmer (strspn(mode, L_MODEEXT) == strlen(mode))); /* check extensions */
469e2f6347Smbalmer }
474ab4902eSlneto
484ab4902eSlneto #endif
494ab4902eSlneto
504ab4902eSlneto /*
514ab4902eSlneto ** {======================================================
524ab4902eSlneto ** l_popen spawns a new process connected to the current
534ab4902eSlneto ** one through the file streams.
544ab4902eSlneto ** =======================================================
554ab4902eSlneto */
564ab4902eSlneto
574ab4902eSlneto #if !defined(l_popen) /* { */
584ab4902eSlneto
594ab4902eSlneto #if defined(LUA_USE_POSIX) /* { */
604ab4902eSlneto
614ab4902eSlneto #define l_popen(L,c,m) (fflush(NULL), popen(c,m))
624ab4902eSlneto #define l_pclose(L,file) (pclose(file))
634ab4902eSlneto
6473008250Slneto #elif defined(LUA_USE_WINDOWS) /* }{ */
654ab4902eSlneto
664ab4902eSlneto #define l_popen(L,c,m) (_popen(c,m))
674ab4902eSlneto #define l_pclose(L,file) (_pclose(file))
684ab4902eSlneto
69*f0dad708Snikita #if !defined(l_checkmodep)
70*f0dad708Snikita /* Windows accepts "[rw][bt]?" as valid modes */
71*f0dad708Snikita #define l_checkmodep(m) ((m[0] == 'r' || m[0] == 'w') && \
72*f0dad708Snikita (m[1] == '\0' || ((m[1] == 'b' || m[1] == 't') && m[2] == '\0')))
73*f0dad708Snikita #endif
74*f0dad708Snikita
754ab4902eSlneto #else /* }{ */
764ab4902eSlneto
7773008250Slneto /* ISO C definitions */
784ab4902eSlneto #define l_popen(L,c,m) \
79*f0dad708Snikita ((void)c, (void)m, \
8073008250Slneto luaL_error(L, "'popen' not supported"), \
814ab4902eSlneto (FILE*)0)
824ab4902eSlneto #define l_pclose(L,file) ((void)L, (void)file, -1)
834ab4902eSlneto
844ab4902eSlneto #endif /* } */
854ab4902eSlneto
864ab4902eSlneto #endif /* } */
874ab4902eSlneto
88*f0dad708Snikita
89*f0dad708Snikita #if !defined(l_checkmodep)
90*f0dad708Snikita /* By default, Lua accepts only "r" or "w" as valid modes */
91*f0dad708Snikita #define l_checkmodep(m) ((m[0] == 'r' || m[0] == 'w') && m[1] == '\0')
92*f0dad708Snikita #endif
93*f0dad708Snikita
944ab4902eSlneto /* }====================================================== */
95dbec5304Smbalmer
96dbec5304Smbalmer
974ab4902eSlneto #if !defined(l_getc) /* { */
984ab4902eSlneto
994ab4902eSlneto #if defined(LUA_USE_POSIX)
1004ab4902eSlneto #define l_getc(f) getc_unlocked(f)
1014ab4902eSlneto #define l_lockfile(f) flockfile(f)
1024ab4902eSlneto #define l_unlockfile(f) funlockfile(f)
1034ab4902eSlneto #else
1044ab4902eSlneto #define l_getc(f) getc(f)
1054ab4902eSlneto #define l_lockfile(f) ((void)0)
1064ab4902eSlneto #define l_unlockfile(f) ((void)0)
1074ab4902eSlneto #endif
1084ab4902eSlneto
1094ab4902eSlneto #endif /* } */
110dbec5304Smbalmer
111dbec5304Smbalmer
1124ab4902eSlneto /*
1134ab4902eSlneto ** {======================================================
1144ab4902eSlneto ** l_fseek: configuration for longer offsets
1154ab4902eSlneto ** =======================================================
1164ab4902eSlneto */
1174ab4902eSlneto
1184ab4902eSlneto #if !defined(l_fseek) /* { */
1194ab4902eSlneto
1204ab4902eSlneto #if defined(LUA_USE_POSIX) /* { */
1214ab4902eSlneto
1224ab4902eSlneto #include <sys/types.h>
1234ab4902eSlneto
1244ab4902eSlneto #define l_fseek(f,o,w) fseeko(f,o,w)
1254ab4902eSlneto #define l_ftell(f) ftello(f)
1264ab4902eSlneto #define l_seeknum off_t
1274ab4902eSlneto
12873008250Slneto #elif defined(LUA_USE_WINDOWS) && !defined(_CRTIMP_TYPEINFO) \
1294ab4902eSlneto && defined(_MSC_VER) && (_MSC_VER >= 1400) /* }{ */
1304ab4902eSlneto
1314ab4902eSlneto /* Windows (but not DDK) and Visual C++ 2005 or higher */
1324ab4902eSlneto #define l_fseek(f,o,w) _fseeki64(f,o,w)
1334ab4902eSlneto #define l_ftell(f) _ftelli64(f)
1344ab4902eSlneto #define l_seeknum __int64
1354ab4902eSlneto
1364ab4902eSlneto #else /* }{ */
1374ab4902eSlneto
13873008250Slneto /* ISO C definitions */
1394ab4902eSlneto #define l_fseek(f,o,w) fseek(f,o,w)
1404ab4902eSlneto #define l_ftell(f) ftell(f)
1414ab4902eSlneto #define l_seeknum long
1424ab4902eSlneto
1434ab4902eSlneto #endif /* } */
1444ab4902eSlneto
1454ab4902eSlneto #endif /* } */
1464ab4902eSlneto
1474ab4902eSlneto /* }====================================================== */
148dbec5304Smbalmer
149dbec5304Smbalmer
150*f0dad708Snikita
1514ab4902eSlneto #define IO_PREFIX "_IO_"
15273008250Slneto #define IOPREF_LEN (sizeof(IO_PREFIX)/sizeof(char) - 1)
1534ab4902eSlneto #define IO_INPUT (IO_PREFIX "input")
1544ab4902eSlneto #define IO_OUTPUT (IO_PREFIX "output")
155dbec5304Smbalmer
156dbec5304Smbalmer
1574ab4902eSlneto typedef luaL_Stream LStream;
1584ab4902eSlneto
1594ab4902eSlneto
1604ab4902eSlneto #define tolstream(L) ((LStream *)luaL_checkudata(L, 1, LUA_FILEHANDLE))
1614ab4902eSlneto
1624ab4902eSlneto #define isclosed(p) ((p)->closef == NULL)
163dbec5304Smbalmer
164dbec5304Smbalmer
io_type(lua_State * L)165dbec5304Smbalmer static int io_type (lua_State *L) {
1664ab4902eSlneto LStream *p;
167dbec5304Smbalmer luaL_checkany(L, 1);
1684ab4902eSlneto p = (LStream *)luaL_testudata(L, 1, LUA_FILEHANDLE);
1694ab4902eSlneto if (p == NULL)
170*f0dad708Snikita luaL_pushfail(L); /* not a file */
1714ab4902eSlneto else if (isclosed(p))
172dbec5304Smbalmer lua_pushliteral(L, "closed file");
173dbec5304Smbalmer else
174dbec5304Smbalmer lua_pushliteral(L, "file");
175dbec5304Smbalmer return 1;
176dbec5304Smbalmer }
177dbec5304Smbalmer
178dbec5304Smbalmer
f_tostring(lua_State * L)1794ab4902eSlneto static int f_tostring (lua_State *L) {
1804ab4902eSlneto LStream *p = tolstream(L);
1814ab4902eSlneto if (isclosed(p))
1824ab4902eSlneto lua_pushliteral(L, "file (closed)");
1834ab4902eSlneto else
1844ab4902eSlneto lua_pushfstring(L, "file (%p)", p->f);
1854ab4902eSlneto return 1;
186dbec5304Smbalmer }
187dbec5304Smbalmer
188dbec5304Smbalmer
tofile(lua_State * L)1894ab4902eSlneto static FILE *tofile (lua_State *L) {
1904ab4902eSlneto LStream *p = tolstream(L);
191*f0dad708Snikita if (l_unlikely(isclosed(p)))
1924ab4902eSlneto luaL_error(L, "attempt to use a closed file");
1934ab4902eSlneto lua_assert(p->f);
1944ab4902eSlneto return p->f;
1954ab4902eSlneto }
1964ab4902eSlneto
197dbec5304Smbalmer
198dbec5304Smbalmer /*
19973008250Slneto ** When creating file handles, always creates a 'closed' file handle
200dbec5304Smbalmer ** before opening the actual file; so, if there is a memory error, the
2012d6cb6c2Slneto ** handle is in a consistent state.
202dbec5304Smbalmer */
newprefile(lua_State * L)2034ab4902eSlneto static LStream *newprefile (lua_State *L) {
204*f0dad708Snikita LStream *p = (LStream *)lua_newuserdatauv(L, sizeof(LStream), 0);
2054ab4902eSlneto p->closef = NULL; /* mark file handle as 'closed' */
2064ab4902eSlneto luaL_setmetatable(L, LUA_FILEHANDLE);
2074ab4902eSlneto return p;
208dbec5304Smbalmer }
209dbec5304Smbalmer
210dbec5304Smbalmer
21173008250Slneto /*
21273008250Slneto ** Calls the 'close' function from a file handle. The 'volatile' avoids
21373008250Slneto ** a bug in some versions of the Clang compiler (e.g., clang 3.0 for
21473008250Slneto ** 32 bits).
21573008250Slneto */
aux_close(lua_State * L)2164ab4902eSlneto static int aux_close (lua_State *L) {
2174ab4902eSlneto LStream *p = tolstream(L);
21873008250Slneto volatile lua_CFunction cf = p->closef;
2194ab4902eSlneto p->closef = NULL; /* mark stream as closed */
2204ab4902eSlneto return (*cf)(L); /* close it */
221dbec5304Smbalmer }
222dbec5304Smbalmer
223dbec5304Smbalmer
f_close(lua_State * L)2242bf4ff61Salnsn static int f_close (lua_State *L) {
2252bf4ff61Salnsn tofile(L); /* make sure argument is an open stream */
2262bf4ff61Salnsn return aux_close(L);
2272bf4ff61Salnsn }
2282bf4ff61Salnsn
2292bf4ff61Salnsn
io_close(lua_State * L)2304ab4902eSlneto static int io_close (lua_State *L) {
2314ab4902eSlneto if (lua_isnone(L, 1)) /* no argument? */
232*f0dad708Snikita lua_getfield(L, LUA_REGISTRYINDEX, IO_OUTPUT); /* use default output */
2332bf4ff61Salnsn return f_close(L);
2344ab4902eSlneto }
2354ab4902eSlneto
2364ab4902eSlneto
f_gc(lua_State * L)2374ab4902eSlneto static int f_gc (lua_State *L) {
2384ab4902eSlneto LStream *p = tolstream(L);
2394ab4902eSlneto if (!isclosed(p) && p->f != NULL)
2404ab4902eSlneto aux_close(L); /* ignore closed and incompletely open files */
2414ab4902eSlneto return 0;
242dbec5304Smbalmer }
243dbec5304Smbalmer
244dbec5304Smbalmer
245dbec5304Smbalmer /*
246dbec5304Smbalmer ** function to close regular files
247dbec5304Smbalmer */
io_fclose(lua_State * L)248dbec5304Smbalmer static int io_fclose (lua_State *L) {
2494ab4902eSlneto LStream *p = tolstream(L);
2504ab4902eSlneto int res = fclose(p->f);
2514ab4902eSlneto return luaL_fileresult(L, (res == 0), NULL);
252dbec5304Smbalmer }
253dbec5304Smbalmer
254dbec5304Smbalmer
newfile(lua_State * L)2554ab4902eSlneto static LStream *newfile (lua_State *L) {
2564ab4902eSlneto LStream *p = newprefile(L);
2574ab4902eSlneto p->f = NULL;
2584ab4902eSlneto p->closef = &io_fclose;
2594ab4902eSlneto return p;
260dbec5304Smbalmer }
261dbec5304Smbalmer
262dbec5304Smbalmer
opencheck(lua_State * L,const char * fname,const char * mode)2634ab4902eSlneto static void opencheck (lua_State *L, const char *fname, const char *mode) {
2644ab4902eSlneto LStream *p = newfile(L);
2654ab4902eSlneto p->f = fopen(fname, mode);
266*f0dad708Snikita if (l_unlikely(p->f == NULL))
26773008250Slneto luaL_error(L, "cannot open file '%s' (%s)", fname, strerror(errno));
268dbec5304Smbalmer }
269dbec5304Smbalmer
270dbec5304Smbalmer
io_open(lua_State * L)271dbec5304Smbalmer static int io_open (lua_State *L) {
272dbec5304Smbalmer const char *filename = luaL_checkstring(L, 1);
273dbec5304Smbalmer const char *mode = luaL_optstring(L, 2, "r");
2744ab4902eSlneto LStream *p = newfile(L);
2754ab4902eSlneto const char *md = mode; /* to traverse/check mode */
2764ab4902eSlneto luaL_argcheck(L, l_checkmode(md), 2, "invalid mode");
2774ab4902eSlneto p->f = fopen(filename, mode);
2784ab4902eSlneto return (p->f == NULL) ? luaL_fileresult(L, 0, filename) : 1;
279dbec5304Smbalmer }
280dbec5304Smbalmer
281dbec5304Smbalmer
282dbec5304Smbalmer /*
2834ab4902eSlneto ** function to close 'popen' files
284dbec5304Smbalmer */
io_pclose(lua_State * L)2854ab4902eSlneto static int io_pclose (lua_State *L) {
2864ab4902eSlneto LStream *p = tolstream(L);
287*f0dad708Snikita errno = 0;
2884ab4902eSlneto return luaL_execresult(L, l_pclose(L, p->f));
2894ab4902eSlneto }
2904ab4902eSlneto
2914ab4902eSlneto
io_popen(lua_State * L)292dbec5304Smbalmer static int io_popen (lua_State *L) {
293dbec5304Smbalmer const char *filename = luaL_checkstring(L, 1);
294dbec5304Smbalmer const char *mode = luaL_optstring(L, 2, "r");
2954ab4902eSlneto LStream *p = newprefile(L);
296*f0dad708Snikita luaL_argcheck(L, l_checkmodep(mode), 2, "invalid mode");
2974ab4902eSlneto p->f = l_popen(L, filename, mode);
2984ab4902eSlneto p->closef = &io_pclose;
2994ab4902eSlneto return (p->f == NULL) ? luaL_fileresult(L, 0, filename) : 1;
300dbec5304Smbalmer }
301dbec5304Smbalmer
302dbec5304Smbalmer
io_tmpfile(lua_State * L)303dbec5304Smbalmer static int io_tmpfile (lua_State *L) {
3044ab4902eSlneto LStream *p = newfile(L);
3054ab4902eSlneto p->f = tmpfile();
3064ab4902eSlneto return (p->f == NULL) ? luaL_fileresult(L, 0, NULL) : 1;
307dbec5304Smbalmer }
308dbec5304Smbalmer
309dbec5304Smbalmer
getiofile(lua_State * L,const char * findex)3104ab4902eSlneto static FILE *getiofile (lua_State *L, const char *findex) {
3114ab4902eSlneto LStream *p;
3124ab4902eSlneto lua_getfield(L, LUA_REGISTRYINDEX, findex);
3134ab4902eSlneto p = (LStream *)lua_touserdata(L, -1);
314*f0dad708Snikita if (l_unlikely(isclosed(p)))
315*f0dad708Snikita luaL_error(L, "default %s file is closed", findex + IOPREF_LEN);
3164ab4902eSlneto return p->f;
317dbec5304Smbalmer }
318dbec5304Smbalmer
319dbec5304Smbalmer
g_iofile(lua_State * L,const char * f,const char * mode)3204ab4902eSlneto static int g_iofile (lua_State *L, const char *f, const char *mode) {
321dbec5304Smbalmer if (!lua_isnoneornil(L, 1)) {
322dbec5304Smbalmer const char *filename = lua_tostring(L, 1);
3234ab4902eSlneto if (filename)
3244ab4902eSlneto opencheck(L, filename, mode);
325dbec5304Smbalmer else {
326dbec5304Smbalmer tofile(L); /* check that it's a valid file handle */
327dbec5304Smbalmer lua_pushvalue(L, 1);
328dbec5304Smbalmer }
3294ab4902eSlneto lua_setfield(L, LUA_REGISTRYINDEX, f);
330dbec5304Smbalmer }
331dbec5304Smbalmer /* return current value */
3324ab4902eSlneto lua_getfield(L, LUA_REGISTRYINDEX, f);
333dbec5304Smbalmer return 1;
334dbec5304Smbalmer }
335dbec5304Smbalmer
336dbec5304Smbalmer
io_input(lua_State * L)337dbec5304Smbalmer static int io_input (lua_State *L) {
338dbec5304Smbalmer return g_iofile(L, IO_INPUT, "r");
339dbec5304Smbalmer }
340dbec5304Smbalmer
341dbec5304Smbalmer
io_output(lua_State * L)342dbec5304Smbalmer static int io_output (lua_State *L) {
343dbec5304Smbalmer return g_iofile(L, IO_OUTPUT, "w");
344dbec5304Smbalmer }
345dbec5304Smbalmer
346dbec5304Smbalmer
347dbec5304Smbalmer static int io_readline (lua_State *L);
348dbec5304Smbalmer
349dbec5304Smbalmer
3502d6cb6c2Slneto /*
3512d6cb6c2Slneto ** maximum number of arguments to 'f:lines'/'io.lines' (it + 3 must fit
3522d6cb6c2Slneto ** in the limit for upvalues of a closure)
3532d6cb6c2Slneto */
3542d6cb6c2Slneto #define MAXARGLINE 250
3552d6cb6c2Slneto
356*f0dad708Snikita /*
357*f0dad708Snikita ** Auxiliary function to create the iteration function for 'lines'.
358*f0dad708Snikita ** The iteration function is a closure over 'io_readline', with
359*f0dad708Snikita ** the following upvalues:
360*f0dad708Snikita ** 1) The file being read (first value in the stack)
361*f0dad708Snikita ** 2) the number of arguments to read
362*f0dad708Snikita ** 3) a boolean, true iff file has to be closed when finished ('toclose')
363*f0dad708Snikita ** *) a variable number of format arguments (rest of the stack)
364*f0dad708Snikita */
aux_lines(lua_State * L,int toclose)3654ab4902eSlneto static void aux_lines (lua_State *L, int toclose) {
3664ab4902eSlneto int n = lua_gettop(L) - 1; /* number of arguments to read */
3672d6cb6c2Slneto luaL_argcheck(L, n <= MAXARGLINE, MAXARGLINE + 2, "too many arguments");
368*f0dad708Snikita lua_pushvalue(L, 1); /* file */
3694ab4902eSlneto lua_pushinteger(L, n); /* number of arguments to read */
370dbec5304Smbalmer lua_pushboolean(L, toclose); /* close/not close file when finished */
371*f0dad708Snikita lua_rotate(L, 2, 3); /* move the three values to their positions */
3724ab4902eSlneto lua_pushcclosure(L, io_readline, 3 + n);
373dbec5304Smbalmer }
374dbec5304Smbalmer
375dbec5304Smbalmer
f_lines(lua_State * L)376dbec5304Smbalmer static int f_lines (lua_State *L) {
377dbec5304Smbalmer tofile(L); /* check that it's a valid file handle */
3784ab4902eSlneto aux_lines(L, 0);
379dbec5304Smbalmer return 1;
380dbec5304Smbalmer }
381dbec5304Smbalmer
382dbec5304Smbalmer
383*f0dad708Snikita /*
384*f0dad708Snikita ** Return an iteration function for 'io.lines'. If file has to be
385*f0dad708Snikita ** closed, also returns the file itself as a second result (to be
386*f0dad708Snikita ** closed as the state at the exit of a generic for).
387*f0dad708Snikita */
io_lines(lua_State * L)388dbec5304Smbalmer static int io_lines (lua_State *L) {
3894ab4902eSlneto int toclose;
3904ab4902eSlneto if (lua_isnone(L, 1)) lua_pushnil(L); /* at least one argument */
3914ab4902eSlneto if (lua_isnil(L, 1)) { /* no file name? */
3924ab4902eSlneto lua_getfield(L, LUA_REGISTRYINDEX, IO_INPUT); /* get default input */
3934ab4902eSlneto lua_replace(L, 1); /* put it at index 1 */
3944ab4902eSlneto tofile(L); /* check that it's a valid file handle */
3954ab4902eSlneto toclose = 0; /* do not close it after iteration */
396dbec5304Smbalmer }
3974ab4902eSlneto else { /* open a new file */
398dbec5304Smbalmer const char *filename = luaL_checkstring(L, 1);
3994ab4902eSlneto opencheck(L, filename, "r");
4004ab4902eSlneto lua_replace(L, 1); /* put file at index 1 */
4014ab4902eSlneto toclose = 1; /* close it after iteration */
402dbec5304Smbalmer }
403*f0dad708Snikita aux_lines(L, toclose); /* push iteration function */
404*f0dad708Snikita if (toclose) {
405*f0dad708Snikita lua_pushnil(L); /* state */
406*f0dad708Snikita lua_pushnil(L); /* control */
407*f0dad708Snikita lua_pushvalue(L, 1); /* file is the to-be-closed variable (4th result) */
408*f0dad708Snikita return 4;
409*f0dad708Snikita }
410*f0dad708Snikita else
4114ab4902eSlneto return 1;
412dbec5304Smbalmer }
413dbec5304Smbalmer
414dbec5304Smbalmer
415dbec5304Smbalmer /*
416dbec5304Smbalmer ** {======================================================
417dbec5304Smbalmer ** READ
418dbec5304Smbalmer ** =======================================================
419dbec5304Smbalmer */
420dbec5304Smbalmer
421dbec5304Smbalmer
4224ab4902eSlneto /* maximum length of a numeral */
423c7f896d7Ssalazar #if !defined (L_MAXLENNUM)
424c7f896d7Ssalazar #define L_MAXLENNUM 200
425c7f896d7Ssalazar #endif
426c7f896d7Ssalazar
4274ab4902eSlneto
4284ab4902eSlneto /* auxiliary structure used by 'read_number' */
4294ab4902eSlneto typedef struct {
4304ab4902eSlneto FILE *f; /* file being read */
4314ab4902eSlneto int c; /* current character (look ahead) */
4324ab4902eSlneto int n; /* number of elements in buffer 'buff' */
433c7f896d7Ssalazar char buff[L_MAXLENNUM + 1]; /* +1 for ending '\0' */
4344ab4902eSlneto } RN;
4354ab4902eSlneto
4364ab4902eSlneto
4374ab4902eSlneto /*
4384ab4902eSlneto ** Add current char to buffer (if not out of space) and read next one
4394ab4902eSlneto */
nextc(RN * rn)4404ab4902eSlneto static int nextc (RN *rn) {
441*f0dad708Snikita if (l_unlikely(rn->n >= L_MAXLENNUM)) { /* buffer overflow? */
4424ab4902eSlneto rn->buff[0] = '\0'; /* invalidate result */
4434ab4902eSlneto return 0; /* fail */
444dbec5304Smbalmer }
4457e762f0eSalnsn else {
4464ab4902eSlneto rn->buff[rn->n++] = rn->c; /* save current char */
4474ab4902eSlneto rn->c = l_getc(rn->f); /* read next one */
4484ab4902eSlneto return 1;
4494ab4902eSlneto }
4504ab4902eSlneto }
4514ab4902eSlneto
4524ab4902eSlneto
4534ab4902eSlneto /*
454c7f896d7Ssalazar ** Accept current char if it is in 'set' (of size 2)
4554ab4902eSlneto */
test2(RN * rn,const char * set)4564ab4902eSlneto static int test2 (RN *rn, const char *set) {
457c7f896d7Ssalazar if (rn->c == set[0] || rn->c == set[1])
4584ab4902eSlneto return nextc(rn);
4594ab4902eSlneto else return 0;
4604ab4902eSlneto }
4614ab4902eSlneto
4624ab4902eSlneto
4634ab4902eSlneto /*
46473008250Slneto ** Read a sequence of (hex)digits
4654ab4902eSlneto */
readdigits(RN * rn,int hex)46673008250Slneto static int readdigits (RN *rn, int hex) {
4674ab4902eSlneto int count = 0;
46873008250Slneto while ((hex ? isxdigit(rn->c) : isdigit(rn->c)) && nextc(rn))
4694ab4902eSlneto count++;
4704ab4902eSlneto return count;
4714ab4902eSlneto }
4724ab4902eSlneto
4734ab4902eSlneto
4744ab4902eSlneto /*
4754ab4902eSlneto ** Read a number: first reads a valid prefix of a numeral into a buffer.
47673008250Slneto ** Then it calls 'lua_stringtonumber' to check whether the format is
477*f0dad708Snikita ** correct and to convert it to a Lua number.
4784ab4902eSlneto */
read_number(lua_State * L,FILE * f)4794ab4902eSlneto static int read_number (lua_State *L, FILE *f) {
4804ab4902eSlneto RN rn;
4814ab4902eSlneto int count = 0;
48273008250Slneto int hex = 0;
483bee09862Smbalmer char decp[2];
4844ab4902eSlneto rn.f = f; rn.n = 0;
485bee09862Smbalmer decp[0] = lua_getlocaledecpoint(); /* get decimal point from locale */
486c7f896d7Ssalazar decp[1] = '.'; /* always accept a dot */
4874ab4902eSlneto l_lockfile(rn.f);
4884ab4902eSlneto do { rn.c = l_getc(rn.f); } while (isspace(rn.c)); /* skip spaces */
489*f0dad708Snikita test2(&rn, "-+"); /* optional sign */
490c7f896d7Ssalazar if (test2(&rn, "00")) {
49173008250Slneto if (test2(&rn, "xX")) hex = 1; /* numeral is hexadecimal */
4924ab4902eSlneto else count = 1; /* count initial '0' as a valid digit */
4934ab4902eSlneto }
49473008250Slneto count += readdigits(&rn, hex); /* integral part */
4954ab4902eSlneto if (test2(&rn, decp)) /* decimal point? */
49673008250Slneto count += readdigits(&rn, hex); /* fractional part */
49773008250Slneto if (count > 0 && test2(&rn, (hex ? "pP" : "eE"))) { /* exponent mark? */
498*f0dad708Snikita test2(&rn, "-+"); /* exponent sign */
4994ab4902eSlneto readdigits(&rn, 0); /* exponent digits */
5004ab4902eSlneto }
5014ab4902eSlneto ungetc(rn.c, rn.f); /* unread look-ahead char */
5024ab4902eSlneto l_unlockfile(rn.f);
5034ab4902eSlneto rn.buff[rn.n] = '\0'; /* finish string */
504*f0dad708Snikita if (l_likely(lua_stringtonumber(L, rn.buff)))
505*f0dad708Snikita return 1; /* ok, it is a valid number */
5064ab4902eSlneto else { /* invalid format */
5077e762f0eSalnsn lua_pushnil(L); /* "result" to be removed */
5087e762f0eSalnsn return 0; /* read fails */
5097e762f0eSalnsn }
510dbec5304Smbalmer }
511dbec5304Smbalmer
512dbec5304Smbalmer
test_eof(lua_State * L,FILE * f)513dbec5304Smbalmer static int test_eof (lua_State *L, FILE *f) {
514dbec5304Smbalmer int c = getc(f);
5154ab4902eSlneto ungetc(c, f); /* no-op when c == EOF */
516bee09862Smbalmer lua_pushliteral(L, "");
517dbec5304Smbalmer return (c != EOF);
518dbec5304Smbalmer }
519dbec5304Smbalmer
520dbec5304Smbalmer
read_line(lua_State * L,FILE * f,int chop)5214ab4902eSlneto static int read_line (lua_State *L, FILE *f, int chop) {
5224ab4902eSlneto luaL_Buffer b;
523*f0dad708Snikita int c;
5244ab4902eSlneto luaL_buffinit(L, &b);
525*f0dad708Snikita do { /* may need to read several chunks to get whole line */
526*f0dad708Snikita char *buff = luaL_prepbuffer(&b); /* preallocate buffer space */
52773008250Slneto int i = 0;
52873008250Slneto l_lockfile(f); /* no memory errors can happen inside the lock */
52973008250Slneto while (i < LUAL_BUFFERSIZE && (c = l_getc(f)) != EOF && c != '\n')
530*f0dad708Snikita buff[i++] = c; /* read up to end of line or buffer limit */
5314ab4902eSlneto l_unlockfile(f);
53273008250Slneto luaL_addsize(&b, i);
533*f0dad708Snikita } while (c != EOF && c != '\n'); /* repeat until end of line */
53473008250Slneto if (!chop && c == '\n') /* want a newline and have one? */
53573008250Slneto luaL_addchar(&b, c); /* add ending newline to result */
5364ab4902eSlneto luaL_pushresult(&b); /* close buffer */
53773008250Slneto /* return ok if read something (either a newline or something else) */
5384ab4902eSlneto return (c == '\n' || lua_rawlen(L, -1) > 0);
5394ab4902eSlneto }
5404ab4902eSlneto
5414ab4902eSlneto
read_all(lua_State * L,FILE * f)5424ab4902eSlneto static void read_all (lua_State *L, FILE *f) {
5434ab4902eSlneto size_t nr;
544dbec5304Smbalmer luaL_Buffer b;
545dbec5304Smbalmer luaL_buffinit(L, &b);
5464ab4902eSlneto do { /* read file in chunks of LUAL_BUFFERSIZE bytes */
5472d6cb6c2Slneto char *p = luaL_prepbuffer(&b);
5484ab4902eSlneto nr = fread(p, sizeof(char), LUAL_BUFFERSIZE, f);
5494ab4902eSlneto luaL_addsize(&b, nr);
5504ab4902eSlneto } while (nr == LUAL_BUFFERSIZE);
551dbec5304Smbalmer luaL_pushresult(&b); /* close buffer */
552dbec5304Smbalmer }
553dbec5304Smbalmer
554dbec5304Smbalmer
read_chars(lua_State * L,FILE * f,size_t n)555dbec5304Smbalmer static int read_chars (lua_State *L, FILE *f, size_t n) {
556dbec5304Smbalmer size_t nr; /* number of chars actually read */
5574ab4902eSlneto char *p;
558dbec5304Smbalmer luaL_Buffer b;
559dbec5304Smbalmer luaL_buffinit(L, &b);
5604ab4902eSlneto p = luaL_prepbuffsize(&b, n); /* prepare buffer to read whole block */
5614ab4902eSlneto nr = fread(p, sizeof(char), n, f); /* try to read 'n' chars */
562dbec5304Smbalmer luaL_addsize(&b, nr);
563dbec5304Smbalmer luaL_pushresult(&b); /* close buffer */
5644ab4902eSlneto return (nr > 0); /* true iff read something */
565dbec5304Smbalmer }
566dbec5304Smbalmer
567dbec5304Smbalmer
g_read(lua_State * L,FILE * f,int first)568dbec5304Smbalmer static int g_read (lua_State *L, FILE *f, int first) {
569dbec5304Smbalmer int nargs = lua_gettop(L) - 1;
570*f0dad708Snikita int n, success;
571dbec5304Smbalmer clearerr(f);
572dbec5304Smbalmer if (nargs == 0) { /* no arguments? */
5734ab4902eSlneto success = read_line(L, f, 1);
574dbec5304Smbalmer n = first + 1; /* to return 1 result */
575dbec5304Smbalmer }
576*f0dad708Snikita else {
577*f0dad708Snikita /* ensure stack space for all results and for auxlib's buffer */
578dbec5304Smbalmer luaL_checkstack(L, nargs+LUA_MINSTACK, "too many arguments");
579dbec5304Smbalmer success = 1;
580dbec5304Smbalmer for (n = first; nargs-- && success; n++) {
581dbec5304Smbalmer if (lua_type(L, n) == LUA_TNUMBER) {
58273008250Slneto size_t l = (size_t)luaL_checkinteger(L, n);
583dbec5304Smbalmer success = (l == 0) ? test_eof(L, f) : read_chars(L, f, l);
584dbec5304Smbalmer }
585dbec5304Smbalmer else {
5864ab4902eSlneto const char *p = luaL_checkstring(L, n);
5874ab4902eSlneto if (*p == '*') p++; /* skip optional '*' (for compatibility) */
5884ab4902eSlneto switch (*p) {
589dbec5304Smbalmer case 'n': /* number */
590dbec5304Smbalmer success = read_number(L, f);
591dbec5304Smbalmer break;
592dbec5304Smbalmer case 'l': /* line */
5934ab4902eSlneto success = read_line(L, f, 1);
5944ab4902eSlneto break;
5954ab4902eSlneto case 'L': /* line with end-of-line */
5964ab4902eSlneto success = read_line(L, f, 0);
597dbec5304Smbalmer break;
598dbec5304Smbalmer case 'a': /* file */
5994ab4902eSlneto read_all(L, f); /* read entire file */
600dbec5304Smbalmer success = 1; /* always success */
601dbec5304Smbalmer break;
602dbec5304Smbalmer default:
603dbec5304Smbalmer return luaL_argerror(L, n, "invalid format");
604dbec5304Smbalmer }
605dbec5304Smbalmer }
606dbec5304Smbalmer }
607dbec5304Smbalmer }
608dbec5304Smbalmer if (ferror(f))
6094ab4902eSlneto return luaL_fileresult(L, 0, NULL);
610dbec5304Smbalmer if (!success) {
611dbec5304Smbalmer lua_pop(L, 1); /* remove last result */
612*f0dad708Snikita luaL_pushfail(L); /* push nil instead */
613dbec5304Smbalmer }
614dbec5304Smbalmer return n - first;
615dbec5304Smbalmer }
616dbec5304Smbalmer
617dbec5304Smbalmer
io_read(lua_State * L)618dbec5304Smbalmer static int io_read (lua_State *L) {
619dbec5304Smbalmer return g_read(L, getiofile(L, IO_INPUT), 1);
620dbec5304Smbalmer }
621dbec5304Smbalmer
622dbec5304Smbalmer
f_read(lua_State * L)623dbec5304Smbalmer static int f_read (lua_State *L) {
624dbec5304Smbalmer return g_read(L, tofile(L), 2);
625dbec5304Smbalmer }
626dbec5304Smbalmer
627dbec5304Smbalmer
628*f0dad708Snikita /*
629*f0dad708Snikita ** Iteration function for 'lines'.
630*f0dad708Snikita */
io_readline(lua_State * L)631dbec5304Smbalmer static int io_readline (lua_State *L) {
6324ab4902eSlneto LStream *p = (LStream *)lua_touserdata(L, lua_upvalueindex(1));
6334ab4902eSlneto int i;
6344ab4902eSlneto int n = (int)lua_tointeger(L, lua_upvalueindex(2));
6354ab4902eSlneto if (isclosed(p)) /* file is already closed? */
6364ab4902eSlneto return luaL_error(L, "file is already closed");
6374ab4902eSlneto lua_settop(L , 1);
6384ab4902eSlneto luaL_checkstack(L, n, "too many arguments");
6394ab4902eSlneto for (i = 1; i <= n; i++) /* push arguments to 'g_read' */
6404ab4902eSlneto lua_pushvalue(L, lua_upvalueindex(3 + i));
6414ab4902eSlneto n = g_read(L, p->f, 2); /* 'n' is number of results */
6424ab4902eSlneto lua_assert(n > 0); /* should return at least a nil */
64373008250Slneto if (lua_toboolean(L, -n)) /* read at least one value? */
6444ab4902eSlneto return n; /* return them */
645*f0dad708Snikita else { /* first result is false: EOF or error */
6464ab4902eSlneto if (n > 1) { /* is there error information? */
6474ab4902eSlneto /* 2nd result is error message */
6484ab4902eSlneto return luaL_error(L, "%s", lua_tostring(L, -n + 1));
6494ab4902eSlneto }
6504ab4902eSlneto if (lua_toboolean(L, lua_upvalueindex(3))) { /* generator created file? */
651*f0dad708Snikita lua_settop(L, 0); /* clear stack */
652*f0dad708Snikita lua_pushvalue(L, lua_upvalueindex(1)); /* push file at index 1 */
653dbec5304Smbalmer aux_close(L); /* close it */
654dbec5304Smbalmer }
655dbec5304Smbalmer return 0;
656dbec5304Smbalmer }
657dbec5304Smbalmer }
658dbec5304Smbalmer
659dbec5304Smbalmer /* }====================================================== */
660dbec5304Smbalmer
661dbec5304Smbalmer
g_write(lua_State * L,FILE * f,int arg)662dbec5304Smbalmer static int g_write (lua_State *L, FILE *f, int arg) {
6634ab4902eSlneto int nargs = lua_gettop(L) - arg;
664dbec5304Smbalmer int status = 1;
665dbec5304Smbalmer for (; nargs--; arg++) {
666dbec5304Smbalmer if (lua_type(L, arg) == LUA_TNUMBER) {
667dbec5304Smbalmer /* optimization: could be done exactly as for strings */
6684ab4902eSlneto int len = lua_isinteger(L, arg)
6699e2f6347Smbalmer ? fprintf(f, LUA_INTEGER_FMT,
6709e2f6347Smbalmer (LUAI_UACINT)lua_tointeger(L, arg))
6719e2f6347Smbalmer : fprintf(f, LUA_NUMBER_FMT,
6729e2f6347Smbalmer (LUAI_UACNUMBER)lua_tonumber(L, arg));
6734ab4902eSlneto status = status && (len > 0);
674dbec5304Smbalmer }
675dbec5304Smbalmer else {
676dbec5304Smbalmer size_t l;
677dbec5304Smbalmer const char *s = luaL_checklstring(L, arg, &l);
678dbec5304Smbalmer status = status && (fwrite(s, sizeof(char), l, f) == l);
679dbec5304Smbalmer }
680dbec5304Smbalmer }
681*f0dad708Snikita if (l_likely(status))
682*f0dad708Snikita return 1; /* file handle already on stack top */
6834ab4902eSlneto else return luaL_fileresult(L, status, NULL);
684dbec5304Smbalmer }
685dbec5304Smbalmer
686dbec5304Smbalmer
io_write(lua_State * L)687dbec5304Smbalmer static int io_write (lua_State *L) {
688dbec5304Smbalmer return g_write(L, getiofile(L, IO_OUTPUT), 1);
689dbec5304Smbalmer }
690dbec5304Smbalmer
691dbec5304Smbalmer
f_write(lua_State * L)692dbec5304Smbalmer static int f_write (lua_State *L) {
6934ab4902eSlneto FILE *f = tofile(L);
6944ab4902eSlneto lua_pushvalue(L, 1); /* push file at the stack top (to be returned) */
6954ab4902eSlneto return g_write(L, f, 2);
696dbec5304Smbalmer }
697dbec5304Smbalmer
698dbec5304Smbalmer
f_seek(lua_State * L)699dbec5304Smbalmer static int f_seek (lua_State *L) {
700dbec5304Smbalmer static const int mode[] = {SEEK_SET, SEEK_CUR, SEEK_END};
701dbec5304Smbalmer static const char *const modenames[] = {"set", "cur", "end", NULL};
702dbec5304Smbalmer FILE *f = tofile(L);
703dbec5304Smbalmer int op = luaL_checkoption(L, 2, "cur", modenames);
7044ab4902eSlneto lua_Integer p3 = luaL_optinteger(L, 3, 0);
7054ab4902eSlneto l_seeknum offset = (l_seeknum)p3;
7064ab4902eSlneto luaL_argcheck(L, (lua_Integer)offset == p3, 3,
7074ab4902eSlneto "not an integer in proper range");
7084ab4902eSlneto op = l_fseek(f, offset, mode[op]);
709*f0dad708Snikita if (l_unlikely(op))
7104ab4902eSlneto return luaL_fileresult(L, 0, NULL); /* error */
711dbec5304Smbalmer else {
7124ab4902eSlneto lua_pushinteger(L, (lua_Integer)l_ftell(f));
713dbec5304Smbalmer return 1;
714dbec5304Smbalmer }
715dbec5304Smbalmer }
716dbec5304Smbalmer
717dbec5304Smbalmer
f_setvbuf(lua_State * L)718dbec5304Smbalmer static int f_setvbuf (lua_State *L) {
719dbec5304Smbalmer static const int mode[] = {_IONBF, _IOFBF, _IOLBF};
720dbec5304Smbalmer static const char *const modenames[] = {"no", "full", "line", NULL};
721dbec5304Smbalmer FILE *f = tofile(L);
722dbec5304Smbalmer int op = luaL_checkoption(L, 2, NULL, modenames);
723dbec5304Smbalmer lua_Integer sz = luaL_optinteger(L, 3, LUAL_BUFFERSIZE);
72473008250Slneto int res = setvbuf(f, NULL, mode[op], (size_t)sz);
7254ab4902eSlneto return luaL_fileresult(L, res == 0, NULL);
726dbec5304Smbalmer }
727dbec5304Smbalmer
728dbec5304Smbalmer
729dbec5304Smbalmer
io_flush(lua_State * L)730dbec5304Smbalmer static int io_flush (lua_State *L) {
7314ab4902eSlneto return luaL_fileresult(L, fflush(getiofile(L, IO_OUTPUT)) == 0, NULL);
732dbec5304Smbalmer }
733dbec5304Smbalmer
734dbec5304Smbalmer
f_flush(lua_State * L)735dbec5304Smbalmer static int f_flush (lua_State *L) {
7364ab4902eSlneto return luaL_fileresult(L, fflush(tofile(L)) == 0, NULL);
737dbec5304Smbalmer }
738dbec5304Smbalmer
739dbec5304Smbalmer
7404ab4902eSlneto /*
7414ab4902eSlneto ** functions for 'io' library
7424ab4902eSlneto */
743dbec5304Smbalmer static const luaL_Reg iolib[] = {
744dbec5304Smbalmer {"close", io_close},
745dbec5304Smbalmer {"flush", io_flush},
746dbec5304Smbalmer {"input", io_input},
747dbec5304Smbalmer {"lines", io_lines},
748dbec5304Smbalmer {"open", io_open},
749dbec5304Smbalmer {"output", io_output},
750dbec5304Smbalmer {"popen", io_popen},
751dbec5304Smbalmer {"read", io_read},
752dbec5304Smbalmer {"tmpfile", io_tmpfile},
753dbec5304Smbalmer {"type", io_type},
754dbec5304Smbalmer {"write", io_write},
755dbec5304Smbalmer {NULL, NULL}
756dbec5304Smbalmer };
757dbec5304Smbalmer
758dbec5304Smbalmer
7594ab4902eSlneto /*
7604ab4902eSlneto ** methods for file handles
7614ab4902eSlneto */
762*f0dad708Snikita static const luaL_Reg meth[] = {
763dbec5304Smbalmer {"read", f_read},
764dbec5304Smbalmer {"write", f_write},
765*f0dad708Snikita {"lines", f_lines},
766*f0dad708Snikita {"flush", f_flush},
767*f0dad708Snikita {"seek", f_seek},
768*f0dad708Snikita {"close", f_close},
769*f0dad708Snikita {"setvbuf", f_setvbuf},
770*f0dad708Snikita {NULL, NULL}
771*f0dad708Snikita };
772*f0dad708Snikita
773*f0dad708Snikita
774*f0dad708Snikita /*
775*f0dad708Snikita ** metamethods for file handles
776*f0dad708Snikita */
777*f0dad708Snikita static const luaL_Reg metameth[] = {
778*f0dad708Snikita {"__index", NULL}, /* place holder */
7794ab4902eSlneto {"__gc", f_gc},
780*f0dad708Snikita {"__close", f_gc},
7814ab4902eSlneto {"__tostring", f_tostring},
782dbec5304Smbalmer {NULL, NULL}
783dbec5304Smbalmer };
784dbec5304Smbalmer
785dbec5304Smbalmer
createmeta(lua_State * L)786dbec5304Smbalmer static void createmeta (lua_State *L) {
787*f0dad708Snikita luaL_newmetatable(L, LUA_FILEHANDLE); /* metatable for file handles */
788*f0dad708Snikita luaL_setfuncs(L, metameth, 0); /* add metamethods to new metatable */
789*f0dad708Snikita luaL_newlibtable(L, meth); /* create method table */
790*f0dad708Snikita luaL_setfuncs(L, meth, 0); /* add file methods to method table */
791*f0dad708Snikita lua_setfield(L, -2, "__index"); /* metatable.__index = method table */
792*f0dad708Snikita lua_pop(L, 1); /* pop metatable */
793dbec5304Smbalmer }
794dbec5304Smbalmer
795dbec5304Smbalmer
7964ab4902eSlneto /*
7974ab4902eSlneto ** function to (not) close the standard files stdin, stdout, and stderr
7984ab4902eSlneto */
io_noclose(lua_State * L)7994ab4902eSlneto static int io_noclose (lua_State *L) {
8004ab4902eSlneto LStream *p = tolstream(L);
8014ab4902eSlneto p->closef = &io_noclose; /* keep file opened */
802*f0dad708Snikita luaL_pushfail(L);
8034ab4902eSlneto lua_pushliteral(L, "cannot close standard file");
8044ab4902eSlneto return 2;
8054ab4902eSlneto }
8064ab4902eSlneto
8074ab4902eSlneto
createstdfile(lua_State * L,FILE * f,const char * k,const char * fname)8084ab4902eSlneto static void createstdfile (lua_State *L, FILE *f, const char *k,
8094ab4902eSlneto const char *fname) {
8104ab4902eSlneto LStream *p = newprefile(L);
8114ab4902eSlneto p->f = f;
8124ab4902eSlneto p->closef = &io_noclose;
8134ab4902eSlneto if (k != NULL) {
814dbec5304Smbalmer lua_pushvalue(L, -1);
8154ab4902eSlneto lua_setfield(L, LUA_REGISTRYINDEX, k); /* add file to registry */
816dbec5304Smbalmer }
8174ab4902eSlneto lua_setfield(L, -2, fname); /* add file to module */
818dbec5304Smbalmer }
819dbec5304Smbalmer
820dbec5304Smbalmer
luaopen_io(lua_State * L)8214ab4902eSlneto LUAMOD_API int luaopen_io (lua_State *L) {
8224ab4902eSlneto luaL_newlib(L, iolib); /* new module */
823dbec5304Smbalmer createmeta(L);
824dbec5304Smbalmer /* create (and set) default files */
825dbec5304Smbalmer createstdfile(L, stdin, IO_INPUT, "stdin");
826dbec5304Smbalmer createstdfile(L, stdout, IO_OUTPUT, "stdout");
8274ab4902eSlneto createstdfile(L, stderr, NULL, "stderr");
828dbec5304Smbalmer return 1;
829dbec5304Smbalmer }
830dbec5304Smbalmer
831