diff options
author | Lua Team <team@lua.org> | 2014-12-11 12:00:00 +0000 |
---|---|---|
committer | repogen <> | 2014-12-11 12:00:00 +0000 |
commit | fd9a52f7ff522a363ff2495d33b331c221981d60 (patch) | |
tree | a3fca3cc276f2a2ee44a498984497a9b82e685ee /src | |
parent | 92fdb95364ed274752b8634c8ba3dca1f1dc5fb3 (diff) | |
download | lua-github-5.3.0-rc0.tar.gz |
Lua 5.3.0-rc05.3.0-rc0
Diffstat (limited to 'src')
-rw-r--r-- | src/Makefile | 140 | ||||
-rw-r--r-- | src/lapi.c | 43 | ||||
-rw-r--r-- | src/lauxlib.c | 47 | ||||
-rw-r--r-- | src/lauxlib.h | 29 | ||||
-rw-r--r-- | src/lbaselib.c | 27 | ||||
-rw-r--r-- | src/lbitlib.c | 5 | ||||
-rw-r--r-- | src/lcode.c | 73 | ||||
-rw-r--r-- | src/lcorolib.c | 11 | ||||
-rw-r--r-- | src/lctype.c | 5 | ||||
-rw-r--r-- | src/ldblib.c | 48 | ||||
-rw-r--r-- | src/ldebug.c | 78 | ||||
-rw-r--r-- | src/ldebug.h | 7 | ||||
-rw-r--r-- | src/ldo.c | 42 | ||||
-rw-r--r-- | src/ldo.h | 4 | ||||
-rw-r--r-- | src/ldump.c | 9 | ||||
-rw-r--r-- | src/lfunc.c | 14 | ||||
-rw-r--r-- | src/lgc.c | 28 | ||||
-rw-r--r-- | src/lgc.h | 4 | ||||
-rw-r--r-- | src/linit.c | 40 | ||||
-rw-r--r-- | src/liolib.c | 47 | ||||
-rw-r--r-- | src/llex.c | 29 | ||||
-rw-r--r-- | src/llex.h | 8 | ||||
-rw-r--r-- | src/llimits.h | 50 | ||||
-rw-r--r-- | src/lmathlib.c | 16 | ||||
-rw-r--r-- | src/lmem.c | 18 | ||||
-rw-r--r-- | src/loadlib.c | 51 | ||||
-rw-r--r-- | src/lobject.c | 70 | ||||
-rw-r--r-- | src/lobject.h | 14 | ||||
-rw-r--r-- | src/lopcodes.c | 5 | ||||
-rw-r--r-- | src/lopcodes.h | 28 | ||||
-rw-r--r-- | src/loslib.c | 20 | ||||
-rw-r--r-- | src/lparser.c | 72 | ||||
-rw-r--r-- | src/lparser.h | 16 | ||||
-rw-r--r-- | src/lprefix.h | 39 | ||||
-rw-r--r-- | src/lstate.c | 15 | ||||
-rw-r--r-- | src/lstate.h | 18 | ||||
-rw-r--r-- | src/lstring.c | 10 | ||||
-rw-r--r-- | src/lstrlib.c | 192 | ||||
-rw-r--r-- | src/ltable.c | 46 | ||||
-rw-r--r-- | src/ltablib.c | 14 | ||||
-rw-r--r-- | src/ltm.c | 18 | ||||
-rw-r--r-- | src/ltm.h | 4 | ||||
-rw-r--r-- | src/lua.c | 33 | ||||
-rw-r--r-- | src/lua.h | 30 | ||||
-rw-r--r-- | src/luac.c | 13 | ||||
-rw-r--r-- | src/luaconf.h | 481 | ||||
-rw-r--r-- | src/lundump.c | 9 | ||||
-rw-r--r-- | src/lutf8lib.c | 10 | ||||
-rw-r--r-- | src/lvm.c | 111 | ||||
-rw-r--r-- | src/lzio.c | 10 |
50 files changed, 1189 insertions, 962 deletions
diff --git a/src/Makefile b/src/Makefile index 7be16dc3..7d1b02c6 100644 --- a/src/Makefile +++ b/src/Makefile @@ -26,7 +26,7 @@ MYOBJS= # == END OF USER SETTINGS -- NO NEED TO CHANGE ANYTHING BELOW THIS LINE ======= -PLATS= aix ansi bsd freebsd generic linux macosx mingw posix solaris +PLATS= aix bsd c89 freebsd generic linux macosx mingw posix solaris LUA_A= liblua.a CORE_O= lapi.o lcode.o lctype.o ldebug.o ldo.o ldump.o lfunc.o lgc.o llex.o \ @@ -91,16 +91,16 @@ none: aix: $(MAKE) $(ALL) CC="xlc" CFLAGS="-O2 -DLUA_USE_POSIX -DLUA_USE_DLOPEN" SYSLIBS="-ldl" SYSLDFLAGS="-brtl -bexpall" -ansi: - $(MAKE) $(ALL) SYSCFLAGS="-DLUA_ANSI -DLUA_32BITS" - @echo "" - @echo "Note: in ANSI mode, Lua is built with 32-bit numbers" - @echo " because ANSI C89 does not support 'long long'" - @echo "" - bsd: $(MAKE) $(ALL) SYSCFLAGS="-DLUA_USE_POSIX -DLUA_USE_DLOPEN" SYSLIBS="-Wl,-E" +c89: + $(MAKE) $(ALL) SYSCFLAGS="-DLUA_USE_C89" CC="gcc -std=c89" + @echo '' + @echo '*** C89 does not guarantee 64-bit integers for Lua.' + @echo '' + + freebsd: $(MAKE) $(ALL) SYSCFLAGS="-DLUA_USE_LINUX" SYSLIBS="-Wl,-E -lreadline" @@ -129,65 +129,69 @@ solaris: # DO NOT DELETE -lapi.o: lapi.c lua.h luaconf.h lapi.h llimits.h lstate.h lobject.h ltm.h \ - lzio.h lmem.h ldebug.h ldo.h lfunc.h lgc.h lstring.h ltable.h lundump.h \ - lvm.h -lauxlib.o: lauxlib.c lua.h luaconf.h lauxlib.h -lbaselib.o: lbaselib.c lua.h luaconf.h lauxlib.h lualib.h -lbitlib.o: lbitlib.c lua.h luaconf.h lauxlib.h lualib.h -lcode.o: lcode.c lua.h luaconf.h lcode.h llex.h lobject.h llimits.h \ - lzio.h lmem.h lopcodes.h lparser.h ldebug.h lstate.h ltm.h ldo.h lgc.h \ - lstring.h ltable.h lvm.h -lcorolib.o: lcorolib.c lua.h luaconf.h lauxlib.h lualib.h -lctype.o: lctype.c lctype.h lua.h luaconf.h llimits.h -ldblib.o: ldblib.c lua.h luaconf.h lauxlib.h lualib.h -ldebug.o: ldebug.c lua.h luaconf.h lapi.h llimits.h lstate.h lobject.h \ - ltm.h lzio.h lmem.h lcode.h llex.h lopcodes.h lparser.h ldebug.h ldo.h \ - lfunc.h lstring.h lgc.h ltable.h lvm.h -ldo.o: ldo.c lua.h luaconf.h lapi.h llimits.h lstate.h lobject.h ltm.h \ - lzio.h lmem.h ldebug.h ldo.h lfunc.h lgc.h lopcodes.h lparser.h \ - lstring.h ltable.h lundump.h lvm.h -ldump.o: ldump.c lua.h luaconf.h lobject.h llimits.h lstate.h ltm.h \ - lzio.h lmem.h lundump.h -lfunc.o: lfunc.c lua.h luaconf.h lfunc.h lobject.h llimits.h lgc.h \ - lstate.h ltm.h lzio.h lmem.h -lgc.o: lgc.c lua.h luaconf.h ldebug.h lstate.h lobject.h llimits.h ltm.h \ - lzio.h lmem.h ldo.h lfunc.h lgc.h lstring.h ltable.h -linit.o: linit.c lua.h luaconf.h lualib.h lauxlib.h -liolib.o: liolib.c lua.h luaconf.h lauxlib.h lualib.h -llex.o: llex.c lua.h luaconf.h lctype.h llimits.h ldo.h lobject.h \ - lstate.h ltm.h lzio.h lmem.h lgc.h llex.h lparser.h lstring.h ltable.h -lmathlib.o: lmathlib.c lua.h luaconf.h lauxlib.h lualib.h -lmem.o: lmem.c lua.h luaconf.h ldebug.h lstate.h lobject.h llimits.h \ - ltm.h lzio.h lmem.h ldo.h lgc.h -loadlib.o: loadlib.c lua.h luaconf.h lauxlib.h lualib.h -lobject.o: lobject.c lua.h luaconf.h lctype.h llimits.h ldebug.h lstate.h \ - lobject.h ltm.h lzio.h lmem.h ldo.h lstring.h lgc.h lvm.h -lopcodes.o: lopcodes.c lopcodes.h llimits.h lua.h luaconf.h -loslib.o: loslib.c lua.h luaconf.h lauxlib.h lualib.h -lparser.o: lparser.c lua.h luaconf.h lcode.h llex.h lobject.h llimits.h \ - lzio.h lmem.h lopcodes.h lparser.h ldebug.h lstate.h ltm.h ldo.h lfunc.h \ - lstring.h lgc.h ltable.h -lstate.o: lstate.c lua.h luaconf.h lapi.h llimits.h lstate.h lobject.h \ - ltm.h lzio.h lmem.h ldebug.h ldo.h lfunc.h lgc.h llex.h lstring.h \ - ltable.h -lstring.o: lstring.c lua.h luaconf.h ldebug.h lstate.h lobject.h \ - llimits.h ltm.h lzio.h lmem.h ldo.h lstring.h lgc.h -lstrlib.o: lstrlib.c lua.h luaconf.h lauxlib.h lualib.h -ltable.o: ltable.c lua.h luaconf.h ldebug.h lstate.h lobject.h llimits.h \ - ltm.h lzio.h lmem.h ldo.h lgc.h lstring.h ltable.h lvm.h -ltablib.o: ltablib.c lua.h luaconf.h lauxlib.h lualib.h -ltm.o: ltm.c lua.h luaconf.h ldebug.h lstate.h lobject.h llimits.h ltm.h \ - lzio.h lmem.h ldo.h lstring.h lgc.h ltable.h lvm.h -lua.o: lua.c lua.h luaconf.h lauxlib.h lualib.h -luac.o: luac.c lua.h luaconf.h lauxlib.h lobject.h llimits.h lstate.h \ - ltm.h lzio.h lmem.h lundump.h ldebug.h lopcodes.h -lundump.o: lundump.c lua.h luaconf.h ldebug.h lstate.h lobject.h \ - llimits.h ltm.h lzio.h lmem.h ldo.h lfunc.h lstring.h lgc.h lundump.h -lutf8lib.o: lutf8lib.c lua.h luaconf.h lauxlib.h lualib.h -lvm.o: lvm.c lua.h luaconf.h ldebug.h lstate.h lobject.h llimits.h ltm.h \ - lzio.h lmem.h ldo.h lfunc.h lgc.h lopcodes.h lstring.h ltable.h lvm.h -lzio.o: lzio.c lua.h luaconf.h llimits.h lmem.h lstate.h lobject.h ltm.h \ - lzio.h +lapi.o: lapi.c lprefix.h lua.h luaconf.h lapi.h llimits.h lstate.h \ + lobject.h ltm.h lzio.h lmem.h ldebug.h ldo.h lfunc.h lgc.h lstring.h \ + ltable.h lundump.h lvm.h +lauxlib.o: lauxlib.c lprefix.h lua.h luaconf.h lauxlib.h +lbaselib.o: lbaselib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h +lbitlib.o: lbitlib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h +lcode.o: lcode.c lprefix.h lua.h luaconf.h lcode.h llex.h lobject.h \ + llimits.h lzio.h lmem.h lopcodes.h lparser.h ldebug.h lstate.h ltm.h \ + ldo.h lgc.h lstring.h ltable.h lvm.h +lcorolib.o: lcorolib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h +lctype.o: lctype.c lprefix.h lctype.h lua.h luaconf.h llimits.h +ldblib.o: ldblib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h +ldebug.o: ldebug.c lprefix.h lua.h luaconf.h lapi.h llimits.h lstate.h \ + lobject.h ltm.h lzio.h lmem.h lcode.h llex.h lopcodes.h lparser.h \ + ldebug.h ldo.h lfunc.h lstring.h lgc.h ltable.h lvm.h +ldo.o: ldo.c lprefix.h lua.h luaconf.h lapi.h llimits.h lstate.h \ + lobject.h ltm.h lzio.h lmem.h ldebug.h ldo.h lfunc.h lgc.h lopcodes.h \ + lparser.h lstring.h ltable.h lundump.h lvm.h +ldump.o: ldump.c lprefix.h lua.h luaconf.h lobject.h llimits.h lstate.h \ + ltm.h lzio.h lmem.h lundump.h +lfunc.o: lfunc.c lprefix.h lua.h luaconf.h lfunc.h lobject.h llimits.h \ + lgc.h lstate.h ltm.h lzio.h lmem.h +lgc.o: lgc.c lprefix.h lua.h luaconf.h ldebug.h lstate.h lobject.h \ + llimits.h ltm.h lzio.h lmem.h ldo.h lfunc.h lgc.h lstring.h ltable.h +linit.o: linit.c lprefix.h lua.h luaconf.h lualib.h lauxlib.h +liolib.o: liolib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h +llex.o: llex.c lprefix.h lua.h luaconf.h lctype.h llimits.h ldo.h \ + lobject.h lstate.h ltm.h lzio.h lmem.h lgc.h llex.h lparser.h lstring.h \ + ltable.h +lmathlib.o: lmathlib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h +lmem.o: lmem.c lprefix.h lua.h luaconf.h ldebug.h lstate.h lobject.h \ + llimits.h ltm.h lzio.h lmem.h ldo.h lgc.h +loadlib.o: loadlib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h +lobject.o: lobject.c lprefix.h lua.h luaconf.h lctype.h llimits.h \ + ldebug.h lstate.h lobject.h ltm.h lzio.h lmem.h ldo.h lstring.h lgc.h \ + lvm.h +lopcodes.o: lopcodes.c lprefix.h lopcodes.h llimits.h lua.h luaconf.h +loslib.o: loslib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h +lparser.o: lparser.c lprefix.h lua.h luaconf.h lcode.h llex.h lobject.h \ + llimits.h lzio.h lmem.h lopcodes.h lparser.h ldebug.h lstate.h ltm.h \ + ldo.h lfunc.h lstring.h lgc.h ltable.h +lstate.o: lstate.c lprefix.h lua.h luaconf.h lapi.h llimits.h lstate.h \ + lobject.h ltm.h lzio.h lmem.h ldebug.h ldo.h lfunc.h lgc.h llex.h \ + lstring.h ltable.h +lstring.o: lstring.c lprefix.h lua.h luaconf.h ldebug.h lstate.h \ + lobject.h llimits.h ltm.h lzio.h lmem.h ldo.h lstring.h lgc.h +lstrlib.o: lstrlib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h +ltable.o: ltable.c lprefix.h lua.h luaconf.h ldebug.h lstate.h lobject.h \ + llimits.h ltm.h lzio.h lmem.h ldo.h lgc.h lstring.h ltable.h lvm.h +ltablib.o: ltablib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h +ltm.o: ltm.c lprefix.h lua.h luaconf.h ldebug.h lstate.h lobject.h \ + llimits.h ltm.h lzio.h lmem.h ldo.h lstring.h lgc.h ltable.h lvm.h +lua.o: lua.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h +luac.o: luac.c lprefix.h lua.h luaconf.h lauxlib.h lobject.h llimits.h \ + lstate.h ltm.h lzio.h lmem.h lundump.h ldebug.h lopcodes.h +lundump.o: lundump.c lprefix.h lua.h luaconf.h ldebug.h lstate.h \ + lobject.h llimits.h ltm.h lzio.h lmem.h ldo.h lfunc.h lstring.h lgc.h \ + lundump.h +lutf8lib.o: lutf8lib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h +lvm.o: lvm.c lprefix.h lua.h luaconf.h ldebug.h lstate.h lobject.h \ + llimits.h ltm.h lzio.h lmem.h ldo.h lfunc.h lgc.h lopcodes.h lstring.h \ + ltable.h lvm.h +lzio.o: lzio.c lprefix.h lua.h luaconf.h llimits.h lmem.h lstate.h \ + lobject.h ltm.h lzio.h # (end of Makefile) @@ -1,17 +1,18 @@ /* -** $Id: lapi.c,v 2.238 2014/10/17 19:17:55 roberto Exp $ +** $Id: lapi.c,v 2.243 2014/11/12 13:28:54 roberto Exp $ ** Lua API ** See Copyright Notice in lua.h */ +#define lapi_c +#define LUA_CORE + +#include "lprefix.h" + -#include <math.h> #include <stdarg.h> #include <string.h> -#define lapi_c -#define LUA_CORE - #include "lua.h" #include "lapi.h" @@ -93,22 +94,22 @@ static void growstack (lua_State *L, void *ud) { } -LUA_API int lua_checkstack (lua_State *L, int size) { +LUA_API int lua_checkstack (lua_State *L, int n) { int res; CallInfo *ci = L->ci; lua_lock(L); - api_check(size >= 0, "negative 'size'"); - if (L->stack_last - L->top > size) /* stack large enough? */ + api_check(n >= 0, "negative 'n'"); + if (L->stack_last - L->top > n) /* stack large enough? */ res = 1; /* yes; check is OK */ else { /* no; need to grow stack */ int inuse = cast_int(L->top - L->stack) + EXTRA_STACK; - if (inuse > LUAI_MAXSTACK - size) /* can grow without overflow? */ + if (inuse > LUAI_MAXSTACK - n) /* can grow without overflow? */ res = 0; /* no */ else /* try to grow stack */ - res = (luaD_rawrunprotected(L, &growstack, &size) == LUA_OK); + res = (luaD_rawrunprotected(L, &growstack, &n) == LUA_OK); } - if (res && ci->top < L->top + size) - ci->top = L->top + size; /* adjust frame top */ + if (res && ci->top < L->top + n) + ci->top = L->top + n; /* adjust frame top */ lua_unlock(L); return res; } @@ -178,7 +179,7 @@ LUA_API void lua_settop (lua_State *L, int idx) { } else { api_check(-(idx+1) <= (L->top - (func + 1)), "invalid new top"); - L->top += idx+1; /* `subtract' index (index is negative) */ + L->top += idx+1; /* 'subtract' index (index is negative) */ } lua_unlock(L); } @@ -375,7 +376,7 @@ LUA_API const char *lua_tolstring (lua_State *L, int idx, size_t *len) { if (len != NULL) *len = 0; return NULL; } - lua_lock(L); /* `luaO_tostring' may create a new string */ + lua_lock(L); /* 'luaO_tostring' may create a new string */ luaC_checkGC(L); o = index2addr(L, idx); /* previous call may reallocate the stack */ luaO_tostring(L, o); @@ -577,12 +578,12 @@ LUA_API int lua_pushthread (lua_State *L) { */ -LUA_API int lua_getglobal (lua_State *L, const char *var) { +LUA_API int lua_getglobal (lua_State *L, const char *name) { Table *reg = hvalue(&G(L)->l_registry); const TValue *gt; /* global table */ lua_lock(L); gt = luaH_getint(reg, LUA_RIDX_GLOBALS); - setsvalue2s(L, L->top++, luaS_new(L, var)); + setsvalue2s(L, L->top++, luaS_new(L, name)); luaV_gettable(L, gt, L->top - 1, L->top - 1); lua_unlock(L); return ttnov(L->top - 1); @@ -717,13 +718,13 @@ LUA_API int lua_getuservalue (lua_State *L, int idx) { */ -LUA_API void lua_setglobal (lua_State *L, const char *var) { +LUA_API void lua_setglobal (lua_State *L, const char *name) { Table *reg = hvalue(&G(L)->l_registry); const TValue *gt; /* global table */ lua_lock(L); api_checknelems(L, 1); gt = luaH_getint(reg, LUA_RIDX_GLOBALS); - setsvalue2s(L, L->top++, luaS_new(L, var)); + setsvalue2s(L, L->top++, luaS_new(L, name)); luaV_settable(L, gt, L->top - 1, L->top - 2); L->top -= 2; /* pop value and key */ lua_unlock(L); @@ -867,7 +868,7 @@ LUA_API void lua_setuservalue (lua_State *L, int idx) { /* -** `load' and `call' functions (run Lua code) +** 'load' and 'call' functions (run Lua code) */ @@ -902,7 +903,7 @@ LUA_API void lua_callk (lua_State *L, int nargs, int nresults, /* ** Execute a protected call. */ -struct CallS { /* data to `f_call' */ +struct CallS { /* data to 'f_call' */ StkId func; int nresults; }; @@ -969,7 +970,7 @@ LUA_API int lua_load (lua_State *L, lua_Reader reader, void *data, status = luaD_protectedparser(L, &z, chunkname, mode); if (status == LUA_OK) { /* no errors? */ LClosure *f = clLvalue(L->top - 1); /* get newly created function */ - if (f->nupvalues == 1) { /* does it have one upvalue? */ + if (f->nupvalues >= 1) { /* does it have an upvalue? */ /* get global table from registry */ Table *reg = hvalue(&G(L)->l_registry); const TValue *gt = luaH_getint(reg, LUA_RIDX_GLOBALS); diff --git a/src/lauxlib.c b/src/lauxlib.c index 0a6cea0a..2387141b 100644 --- a/src/lauxlib.c +++ b/src/lauxlib.c @@ -1,9 +1,14 @@ /* -** $Id: lauxlib.c,v 1.270 2014/10/22 11:44:20 roberto Exp $ +** $Id: lauxlib.c,v 1.277 2014/12/10 11:31:32 roberto Exp $ ** Auxiliary functions for building Lua libraries ** See Copyright Notice in lua.h */ +#define lauxlib_c +#define LUA_LIB + +#include "lprefix.h" + #include <errno.h> #include <stdarg.h> @@ -16,9 +21,6 @@ ** Any function declared here could be written as an application function. */ -#define lauxlib_c -#define LUA_LIB - #include "lua.h" #include "lauxlib.h" @@ -81,20 +83,18 @@ static int pushglobalfuncname (lua_State *L, lua_Debug *ar) { static void pushfuncname (lua_State *L, lua_Debug *ar) { - if (*ar->namewhat != '\0') /* is there a name? */ - lua_pushfstring(L, "function '%s'", ar->name); + if (pushglobalfuncname(L, ar)) { /* try first a global name */ + lua_pushfstring(L, "function '%s'", lua_tostring(L, -1)); + lua_remove(L, -2); /* remove name */ + } + else if (*ar->namewhat != '\0') /* is there a name from code? */ + lua_pushfstring(L, "%s '%s'", ar->namewhat, ar->name); /* use it */ else if (*ar->what == 'm') /* main? */ lua_pushliteral(L, "main chunk"); - else if (*ar->what == 'C') { - if (pushglobalfuncname(L, ar)) { - lua_pushfstring(L, "function '%s'", lua_tostring(L, -1)); - lua_remove(L, -2); /* remove name */ - } - else - lua_pushliteral(L, "?"); - } - else + else if (*ar->what != 'C') /* for Lua functions, use <file:line> */ lua_pushfstring(L, "function <%s:%d>", ar->short_src, ar->linedefined); + else /* nothing left... */ + lua_pushliteral(L, "?"); } @@ -156,7 +156,7 @@ LUALIB_API int luaL_argerror (lua_State *L, int arg, const char *extramsg) { return luaL_error(L, "bad argument #%d (%s)", arg, extramsg); lua_getinfo(L, "n", &ar); if (strcmp(ar.namewhat, "method") == 0) { - arg--; /* do not count `self' */ + arg--; /* do not count 'self' */ if (arg == 0) /* error is in the self argument itself? */ return luaL_error(L, "calling '%s' on bad self (%s)", ar.name, extramsg); @@ -277,8 +277,7 @@ LUALIB_API int luaL_execresult (lua_State *L, int stat) { */ LUALIB_API int luaL_newmetatable (lua_State *L, const char *tname) { - luaL_getmetatable(L, tname); /* try to get metatable */ - if (!lua_isnil(L, -1)) /* name already in use? */ + if (luaL_getmetatable(L, tname)) /* name already in use? */ return 0; /* leave previous value on top, but return 0 */ lua_pop(L, 1); lua_newtable(L); /* create metatable */ @@ -526,7 +525,7 @@ LUALIB_API int luaL_ref (lua_State *L, int t) { int ref; if (lua_isnil(L, -1)) { lua_pop(L, 1); /* remove from stack */ - return LUA_REFNIL; /* `nil' has a unique fixed reference */ + return LUA_REFNIL; /* 'nil' has a unique fixed reference */ } t = lua_absindex(L, t); lua_rawgeti(L, t, freelist); /* get first free element */ @@ -565,7 +564,7 @@ LUALIB_API void luaL_unref (lua_State *L, int t, int ref) { typedef struct LoadF { int n; /* number of pre-read characters */ FILE *f; /* file being read */ - char buff[LUAL_BUFFERSIZE]; /* area for reading file */ + char buff[BUFSIZ]; /* area for reading file */ } LoadF; @@ -658,7 +657,7 @@ LUALIB_API int luaL_loadfilex (lua_State *L, const char *filename, readstatus = ferror(lf.f); if (filename) fclose(lf.f); /* close file (even in case of errors) */ if (readstatus) { - lua_settop(L, fnameindex); /* ignore results from `lua_load' */ + lua_settop(L, fnameindex); /* ignore results from 'lua_load' */ return errfile(L, "read", fnameindex); } lua_remove(L, fnameindex); @@ -918,7 +917,7 @@ LUALIB_API const char *luaL_gsub (lua_State *L, const char *s, const char *p, while ((wild = strstr(s, p)) != NULL) { luaL_addlstring(&b, s, wild - s); /* push prefix */ luaL_addstring(&b, r); /* push replacement in place of pattern */ - s = wild + l; /* continue after `p' */ + s = wild + l; /* continue after 'p' */ } luaL_addstring(&b, s); /* push last suffix */ luaL_pushresult(&b); @@ -938,8 +937,8 @@ static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) { static int panic (lua_State *L) { - luai_writestringerror("PANIC: unprotected error in call to Lua API (%s)\n", - lua_tostring(L, -1)); + lua_writestringerror("PANIC: unprotected error in call to Lua API (%s)\n", + lua_tostring(L, -1)); return 0; /* return to Lua to abort */ } diff --git a/src/lauxlib.h b/src/lauxlib.h index cecceb3f..0bac2467 100644 --- a/src/lauxlib.h +++ b/src/lauxlib.h @@ -1,5 +1,5 @@ /* -** $Id: lauxlib.h,v 1.126 2014/10/01 11:54:56 roberto Exp $ +** $Id: lauxlib.h,v 1.128 2014/10/29 16:11:17 roberto Exp $ ** Auxiliary functions for building Lua libraries ** See Copyright Notice in lua.h */ @@ -16,7 +16,7 @@ -/* extra error code for `luaL_load' */ +/* extra error code for 'luaL_load' */ #define LUA_ERRFILE (LUA_ERRERR+1) @@ -205,6 +205,31 @@ LUALIB_API void (luaL_openlib) (lua_State *L, const char *libname, /* +** {================================================================== +** "Abstraction Layer" for basic report of messages and errors +** =================================================================== +*/ + +/* print a string */ +#if !defined(lua_writestring) +#define lua_writestring(s,l) fwrite((s), sizeof(char), (l), stdout) +#endif + +/* print a newline and flush the output */ +#if !defined(lua_writeline) +#define lua_writeline() (lua_writestring("\n", 1), fflush(stdout)) +#endif + +/* print an error message */ +#if !defined(lua_writestringerror) +#define lua_writestringerror(s,p) \ + (fprintf(stderr, (s), (p)), fflush(stderr)) +#endif + +/* }================================================================== */ + + +/* ** {============================================================ ** Compatibility with deprecated conversions ** ============================================================= diff --git a/src/lbaselib.c b/src/lbaselib.c index af04db0d..a2403952 100644 --- a/src/lbaselib.c +++ b/src/lbaselib.c @@ -1,9 +1,13 @@ /* -** $Id: lbaselib.c,v 1.303 2014/10/17 19:17:55 roberto Exp $ +** $Id: lbaselib.c,v 1.309 2014/12/10 12:26:42 roberto Exp $ ** Basic library ** See Copyright Notice in lua.h */ +#define lbaselib_c +#define LUA_LIB + +#include "lprefix.h" #include <ctype.h> @@ -11,9 +15,6 @@ #include <stdlib.h> #include <string.h> -#define lbaselib_c -#define LUA_LIB - #include "lua.h" #include "lauxlib.h" @@ -33,11 +34,11 @@ static int luaB_print (lua_State *L) { s = lua_tolstring(L, -1, &l); /* get result */ if (s == NULL) return luaL_error(L, "'tostring' must return a string to 'print'"); - if (i>1) luai_writestring("\t", 1); - luai_writestring(s, l); + if (i>1) lua_writestring("\t", 1); + lua_writestring(s, l); lua_pop(L, 1); /* pop result */ } - luai_writeline(); + lua_writeline(); return 0; } @@ -60,8 +61,6 @@ static const char *b_str2int (const char *s, int base, lua_Integer *pn) { s++; } while (isalnum((unsigned char)*s)); s += strspn(s, SPACECHARS); /* skip trailing spaces */ - if (*s != '\0') /* invalid trailing characters? */ - return NULL; *pn = (lua_Integer)((neg) ? (0u - n) : n); return s; } @@ -275,6 +274,7 @@ static int luaB_ipairs (lua_State *L) { #if defined(LUA_COMPAT_IPAIRS) return pairsmeta(L, "__ipairs", 1, iter); #else + luaL_checkany(L, 1); lua_pushcfunction(L, iter); /* iteration function */ lua_pushvalue(L, 1); /* state */ lua_pushinteger(L, 0); /* initial value */ @@ -325,7 +325,7 @@ static int luaB_loadfile (lua_State *L) { /* -** Reader for generic `load' function: `lua_load' uses the +** Reader for generic 'load' function: 'lua_load' uses the ** stack for internal stuff, so the reader cannot change the ** stack top. Instead, it keeps its resulting string in a ** reserved slot inside the stack. @@ -389,9 +389,10 @@ static int luaB_assert (lua_State *L) { if (lua_toboolean(L, 1)) /* condition is true? */ return lua_gettop(L); /* return all arguments */ else { /* error */ - if (lua_isnone(L, 2)) /* no error message? */ - lua_pushliteral(L, "assertion failed!"); /* use standard message */ - lua_remove(L, 1); /* remove the condition (if there is one...) */ + luaL_checkany(L, 1); /* there must be a condition */ + lua_remove(L, 1); /* remove it */ + lua_pushliteral(L, "assertion failed!"); /* default message */ + lua_settop(L, 1); /* leave only message (default if no other one) */ return luaB_error(L); /* call 'error' */ } } diff --git a/src/lbitlib.c b/src/lbitlib.c index cca6f402..15d5f0cd 100644 --- a/src/lbitlib.c +++ b/src/lbitlib.c @@ -1,5 +1,5 @@ /* -** $Id: lbitlib.c,v 1.27 2014/10/01 11:54:56 roberto Exp $ +** $Id: lbitlib.c,v 1.28 2014/11/02 19:19:04 roberto Exp $ ** Standard library for bitwise operations ** See Copyright Notice in lua.h */ @@ -7,6 +7,9 @@ #define lbitlib_c #define LUA_LIB +#include "lprefix.h" + + #include "lua.h" #include "lauxlib.h" diff --git a/src/lcode.c b/src/lcode.c index 72afce96..cfe4a210 100644 --- a/src/lcode.c +++ b/src/lcode.c @@ -1,16 +1,18 @@ /* -** $Id: lcode.c,v 2.90 2014/05/08 18:58:46 roberto Exp $ +** $Id: lcode.c,v 2.97 2014/11/24 14:59:22 roberto Exp $ ** Code generator for Lua ** See Copyright Notice in lua.h */ +#define lcode_c +#define LUA_CORE + +#include "lprefix.h" + #include <math.h> #include <stdlib.h> -#define lcode_c -#define LUA_CORE - #include "lua.h" #include "lcode.h" @@ -27,7 +29,11 @@ #include "lvm.h" -/* test for x == -0 */ +/* Maximum number of registers in a Lua function */ +#define MAXREGS 250 + + +/* test for x == -0 ('signbit' needs 'math.h') */ #if defined(signbit) #define isminuszero(x) ((x) == 0.0 && signbit(x)) #else @@ -107,7 +113,7 @@ static void fixjump (FuncState *fs, int pc, int dest) { /* -** returns current `pc' and marks it as a jump target (to avoid wrong +** returns current 'pc' and marks it as a jump target (to avoid wrong ** optimizations with consecutive instructions not in the same basic block). */ int luaK_getlabel (FuncState *fs) { @@ -230,7 +236,7 @@ void luaK_concat (FuncState *fs, int *l1, int l2) { static int luaK_code (FuncState *fs, Instruction i) { Proto *f = fs->f; - dischargejpc(fs); /* `pc' will change */ + dischargejpc(fs); /* 'pc' will change */ /* put new instruction in code array */ luaM_growvector(fs->ls->L, f->code, fs->pc, f->sizecode, Instruction, MAX_INT, "opcodes"); @@ -280,7 +286,7 @@ int luaK_codek (FuncState *fs, int reg, int k) { void luaK_checkstack (FuncState *fs, int n) { int newstack = fs->freereg + n; if (newstack > fs->f->maxstacksize) { - if (newstack >= MAXSTACK) + if (newstack >= MAXREGS) luaX_syntaxerror(fs->ls, "function or expression too complex"); fs->f->maxstacksize = cast_byte(newstack); } @@ -503,7 +509,7 @@ static void discharge2anyreg (FuncState *fs, expdesc *e) { static void exp2reg (FuncState *fs, expdesc *e, int reg) { discharge2reg(fs, e, reg); if (e->k == VJMP) - luaK_concat(fs, &e->t, e->u.info); /* put this jump in `t' list */ + luaK_concat(fs, &e->t, e->u.info); /* put this jump in 't' list */ if (hasjumps(e)) { int final; /* position after whole expression */ int p_f = NO_JUMP; /* position of an eventual LOAD false */ @@ -585,7 +591,7 @@ int luaK_exp2RK (FuncState *fs, expdesc *e) { } case VK: { vk: - if (e->u.info <= MAXINDEXRK) /* constant fits in argC? */ + if (e->u.info <= MAXINDEXRK) /* constant fits in 'argC'? */ return RKASK(e->u.info); else break; } @@ -677,7 +683,7 @@ void luaK_goiftrue (FuncState *fs, expdesc *e) { break; } } - luaK_concat(fs, &e->f, pc); /* insert last jump in `f' list */ + luaK_concat(fs, &e->f, pc); /* insert last jump in 'f' list */ luaK_patchtohere(fs, e->t); e->t = NO_JUMP; } @@ -700,7 +706,7 @@ void luaK_goiffalse (FuncState *fs, expdesc *e) { break; } } - luaK_concat(fs, &e->t, pc); /* insert last jump in `t' list */ + luaK_concat(fs, &e->t, pc); /* insert last jump in 't' list */ luaK_patchtohere(fs, e->f); e->f = NO_JUMP; } @@ -762,12 +768,10 @@ static int validop (int op, TValue *v1, TValue *v2) { (cast_void(tonumber(v2, &b)), b))) return 0; switch (op) { - case LUA_OPIDIV: /* division by 0 and conversion errors */ - return (tointeger(v1, &i) && tointeger(v2, &i) && i != 0); case LUA_OPBAND: case LUA_OPBOR: case LUA_OPBXOR: case LUA_OPSHL: case LUA_OPSHR: case LUA_OPBNOT: /* conversion errors */ return (tointeger(v1, &i) && tointeger(v2, &i)); - case LUA_OPMOD: /* integer module by 0 */ + case LUA_OPIDIV: case LUA_OPMOD: /* integer division by 0 */ return !(ttisinteger(v1) && ttisinteger(v2) && ivalue(v2) == 0); default: return 1; /* everything else is valid */ } @@ -797,19 +801,30 @@ static int constfolding (FuncState *fs, int op, expdesc *e1, expdesc *e2) { } -static void codearith (FuncState *fs, OpCode op, - expdesc *e1, expdesc *e2, int line) { - if (!constfolding(fs, op - OP_ADD + LUA_OPADD, e1, e2)) { +/* +** Code for binary and unary expressions that "produce values" +** (arithmetic operations, bitwise operations, concat, length). First +** try to do constant folding (only for numeric [arithmetic and +** bitwise] operations, which is what 'lua_arith' accepts). +** Expression to produce final result will be encoded in 'e1'. +*/ +static void codeexpval (FuncState *fs, OpCode op, + expdesc *e1, expdesc *e2, int line) { + lua_assert(op >= OP_ADD); + if (op <= OP_BNOT && constfolding(fs, op - OP_ADD + LUA_OPADD, e1, e2)) + return; /* result has been folded */ + else { int o1, o2; - if (op == OP_UNM || op == OP_BNOT || op == OP_LEN) { - o2 = 0; + /* move operands to registers (if needed) */ + if (op == OP_UNM || op == OP_BNOT || op == OP_LEN) { /* unary op? */ + o2 = 0; /* no second expression */ o1 = luaK_exp2anyreg(fs, e1); /* cannot operate on constants */ } else { /* regular case (binary operators) */ - o2 = luaK_exp2RK(fs, e2); + o2 = luaK_exp2RK(fs, e2); /* both operands are "RK" */ o1 = luaK_exp2RK(fs, e1); } - if (o1 > o2) { + if (o1 > o2) { /* free registers in proper order */ freeexp(fs, e1); freeexp(fs, e2); } @@ -817,8 +832,8 @@ static void codearith (FuncState *fs, OpCode op, freeexp(fs, e2); freeexp(fs, e1); } - e1->u.info = luaK_codeABC(fs, op, 0, o1, o2); - e1->k = VRELOCABLE; + e1->u.info = luaK_codeABC(fs, op, 0, o1, o2); /* generate opcode */ + e1->k = VRELOCABLE; /* all those operations are relocable */ luaK_fixline(fs, line); } } @@ -831,7 +846,7 @@ static void codecomp (FuncState *fs, OpCode op, int cond, expdesc *e1, freeexp(fs, e2); freeexp(fs, e1); if (cond == 0 && op != OP_EQ) { - int temp; /* exchange args to replace by `<' or `<=' */ + int temp; /* exchange args to replace by '<' or '<=' */ temp = o1; o1 = o2; o2 = temp; /* o1 <==> o2 */ cond = 1; } @@ -845,7 +860,7 @@ void luaK_prefix (FuncState *fs, UnOpr op, expdesc *e, int line) { e2.t = e2.f = NO_JUMP; e2.k = VKINT; e2.u.ival = 0; switch (op) { case OPR_MINUS: case OPR_BNOT: case OPR_LEN: { - codearith(fs, cast(OpCode, (op - OPR_MINUS) + OP_UNM), e, &e2, line); + codeexpval(fs, cast(OpCode, (op - OPR_MINUS) + OP_UNM), e, &e2, line); break; } case OPR_NOT: codenot(fs, e); break; @@ -865,7 +880,7 @@ void luaK_infix (FuncState *fs, BinOpr op, expdesc *v) { break; } case OPR_CONCAT: { - luaK_exp2nextreg(fs, v); /* operand must be on the `stack' */ + luaK_exp2nextreg(fs, v); /* operand must be on the 'stack' */ break; } case OPR_ADD: case OPR_SUB: @@ -911,7 +926,7 @@ void luaK_posfix (FuncState *fs, BinOpr op, } else { luaK_exp2nextreg(fs, e2); /* operand must be on the 'stack' */ - codearith(fs, OP_CONCAT, e1, e2, line); + codeexpval(fs, OP_CONCAT, e1, e2, line); } break; } @@ -919,7 +934,7 @@ void luaK_posfix (FuncState *fs, BinOpr op, case OPR_IDIV: case OPR_MOD: case OPR_POW: case OPR_BAND: case OPR_BOR: case OPR_BXOR: case OPR_SHL: case OPR_SHR: { - codearith(fs, cast(OpCode, (op - OPR_ADD) + OP_ADD), e1, e2, line); + codeexpval(fs, cast(OpCode, (op - OPR_ADD) + OP_ADD), e1, e2, line); break; } case OPR_EQ: case OPR_LT: case OPR_LE: { diff --git a/src/lcorolib.c b/src/lcorolib.c index cb6cfe5a..0c0b7fa6 100644 --- a/src/lcorolib.c +++ b/src/lcorolib.c @@ -1,15 +1,16 @@ /* -** $Id: lcorolib.c,v 1.7 2014/09/01 18:00:04 roberto Exp $ +** $Id: lcorolib.c,v 1.9 2014/11/02 19:19:04 roberto Exp $ ** Coroutine Library ** See Copyright Notice in lua.h */ +#define lcorolib_c +#define LUA_LIB -#include <stdlib.h> +#include "lprefix.h" -#define lcorolib_c -#define LUA_LIB +#include <stdlib.h> #include "lua.h" @@ -65,7 +66,7 @@ static int luaB_coresume (lua_State *L) { else { lua_pushboolean(L, 1); lua_insert(L, -(r + 1)); - return r + 1; /* return true + `resume' returns */ + return r + 1; /* return true + 'resume' returns */ } } diff --git a/src/lctype.c b/src/lctype.c index 55e433a5..ae9367e6 100644 --- a/src/lctype.c +++ b/src/lctype.c @@ -1,5 +1,5 @@ /* -** $Id: lctype.c,v 1.11 2011/10/03 16:19:23 roberto Exp $ +** $Id: lctype.c,v 1.12 2014/11/02 19:19:04 roberto Exp $ ** 'ctype' functions for Lua ** See Copyright Notice in lua.h */ @@ -7,6 +7,9 @@ #define lctype_c #define LUA_CORE +#include "lprefix.h" + + #include "lctype.h" #if !LUA_USE_CTYPE /* { */ diff --git a/src/ldblib.c b/src/ldblib.c index 3be75b55..c7aa7bb6 100644 --- a/src/ldblib.c +++ b/src/ldblib.c @@ -1,24 +1,30 @@ /* -** $Id: ldblib.c,v 1.143 2014/10/17 11:07:26 roberto Exp $ +** $Id: ldblib.c,v 1.147 2014/12/08 15:47:25 roberto Exp $ ** Interface from Lua to its debug API ** See Copyright Notice in lua.h */ +#define ldblib_c +#define LUA_LIB + +#include "lprefix.h" + #include <stdio.h> #include <stdlib.h> #include <string.h> -#define ldblib_c -#define LUA_LIB - #include "lua.h" #include "lauxlib.h" #include "lualib.h" -#define HOOKKEY "_HKEY" +/* +** The hook table at registry[&HOOKKEY] maps threads to their current +** hook function. (We only need the unique address of 'HOOKKEY'.) +*/ +static const int HOOKKEY = 0; static int db_getregistry (lua_State *L) { @@ -271,20 +277,13 @@ static int db_upvaluejoin (lua_State *L) { /* -** The hook table (at registry[HOOKKEY]) maps threads to their current -** hook function -*/ -#define gethooktable(L) luaL_getsubtable(L, LUA_REGISTRYINDEX, HOOKKEY) - - -/* ** Call hook function registered at hook table for the current ** thread (if there is one) */ static void hookf (lua_State *L, lua_Debug *ar) { static const char *const hooknames[] = {"call", "return", "line", "count", "tail call"}; - gethooktable(L); + lua_rawgetp(L, LUA_REGISTRYINDEX, &HOOKKEY); lua_pushthread(L); if (lua_rawget(L, -2) == LUA_TFUNCTION) { /* is there a hook function? */ lua_pushstring(L, hooknames[(int)ar->event]); /* push event name */ @@ -337,16 +336,19 @@ static int db_sethook (lua_State *L) { count = (int)luaL_optinteger(L, arg + 3, 0); func = hookf; mask = makemask(smask, count); } - if (gethooktable(L) == 0) { /* creating hook table? */ + if (lua_rawgetp(L, LUA_REGISTRYINDEX, &HOOKKEY) == LUA_TNIL) { + lua_createtable(L, 0, 2); /* create a hook table */ + lua_pushvalue(L, -1); + lua_rawsetp(L, LUA_REGISTRYINDEX, &HOOKKEY); /* set it in position */ lua_pushstring(L, "k"); lua_setfield(L, -2, "__mode"); /** hooktable.__mode = "k" */ lua_pushvalue(L, -1); lua_setmetatable(L, -2); /* setmetatable(hooktable) = hooktable */ } - lua_pushthread(L1); lua_xmove(L1, L, 1); /* key */ - lua_pushvalue(L, arg+1); /* value */ + lua_pushthread(L1); lua_xmove(L1, L, 1); /* key (thread) */ + lua_pushvalue(L, arg + 1); /* value (hook function) */ lua_rawset(L, -3); /* hooktable[L1] = new Lua hook */ - lua_sethook(L1, func, mask, count); /* set hooks */ + lua_sethook(L1, func, mask, count); return 0; } @@ -357,10 +359,12 @@ static int db_gethook (lua_State *L) { char buff[5]; int mask = lua_gethookmask(L1); lua_Hook hook = lua_gethook(L1); - if (hook != NULL && hook != hookf) /* external hook? */ + if (hook == NULL) /* no hook? */ + lua_pushnil(L); + else if (hook != hookf) /* external hook? */ lua_pushliteral(L, "external hook"); - else { - gethooktable(L); + else { /* hook table must exist */ + lua_rawgetp(L, LUA_REGISTRYINDEX, &HOOKKEY); lua_pushthread(L1); lua_xmove(L1, L, 1); lua_rawget(L, -2); /* 1st result = hooktable[L1] */ lua_remove(L, -2); /* remove hook table */ @@ -374,13 +378,13 @@ static int db_gethook (lua_State *L) { static int db_debug (lua_State *L) { for (;;) { char buffer[250]; - luai_writestringerror("%s", "lua_debug> "); + lua_writestringerror("%s", "lua_debug> "); if (fgets(buffer, sizeof(buffer), stdin) == 0 || strcmp(buffer, "cont\n") == 0) return 0; if (luaL_loadbuffer(L, buffer, strlen(buffer), "=(debug command)") || lua_pcall(L, 0, 0, 0)) - luai_writestringerror("%s\n", lua_tostring(L, -1)); + lua_writestringerror("%s\n", lua_tostring(L, -1)); lua_settop(L, 0); /* remove eventual returns */ } } diff --git a/src/ldebug.c b/src/ldebug.c index cf7d7ca6..5ca62ebf 100644 --- a/src/ldebug.c +++ b/src/ldebug.c @@ -1,18 +1,19 @@ /* -** $Id: ldebug.c,v 2.101 2014/10/17 16:28:21 roberto Exp $ +** $Id: ldebug.c,v 2.109 2014/12/10 11:30:09 roberto Exp $ ** Debug Interface ** See Copyright Notice in lua.h */ +#define ldebug_c +#define LUA_CORE + +#include "lprefix.h" + #include <stdarg.h> #include <stddef.h> #include <string.h> - -#define ldebug_c -#define LUA_CORE - #include "lua.h" #include "lapi.h" @@ -365,7 +366,7 @@ static int findsetreg (Proto *p, int lastpc, int reg) { case OP_JMP: { int b = GETARG_sBx(i); int dest = pc + 1 + b; - /* jump is forward and do not skip `lastpc'? */ + /* jump is forward and do not skip 'lastpc'? */ if (pc < dest && dest <= lastpc) { if (dest > jmptarget) jmptarget = dest; /* update 'jmptarget' */ @@ -437,10 +438,14 @@ static const char *getobjname (Proto *p, int lastpc, int reg, static const char *getfuncname (lua_State *L, CallInfo *ci, const char **name) { - TMS tm; + TMS tm = (TMS)0; /* to avoid warnings */ Proto *p = ci_func(ci)->p; /* calling function */ int pc = currentpc(ci); /* calling instruction index */ Instruction i = p->code[pc]; /* calling instruction */ + if (ci->callstatus & CIST_HOOKED) { /* was it called inside a hook? */ + *name = "?"; + return "hook"; + } switch (GET_OPCODE(i)) { case OP_CALL: case OP_TAILCALL: /* get function name */ @@ -450,26 +455,27 @@ static const char *getfuncname (lua_State *L, CallInfo *ci, const char **name) { return "for iterator"; } /* all other instructions can call only through metamethods */ - case OP_SELF: - case OP_GETTABUP: - case OP_GETTABLE: tm = TM_INDEX; break; - case OP_SETTABUP: - case OP_SETTABLE: tm = TM_NEWINDEX; break; - case OP_EQ: tm = TM_EQ; break; - case OP_ADD: tm = TM_ADD; break; - case OP_SUB: tm = TM_SUB; break; - case OP_MUL: tm = TM_MUL; break; - case OP_DIV: tm = TM_DIV; break; - case OP_IDIV: tm = TM_IDIV; break; - case OP_MOD: tm = TM_MOD; break; - case OP_POW: tm = TM_POW; break; + case OP_SELF: case OP_GETTABUP: case OP_GETTABLE: + tm = TM_INDEX; + break; + case OP_SETTABUP: case OP_SETTABLE: + tm = TM_NEWINDEX; + break; + case OP_ADD: case OP_SUB: case OP_MUL: case OP_MOD: + case OP_POW: case OP_DIV: case OP_IDIV: case OP_BAND: + case OP_BOR: case OP_BXOR: case OP_SHL: case OP_SHR: { + int offset = cast_int(GET_OPCODE(i)) - cast_int(OP_ADD); /* ORDER OP */ + tm = cast(TMS, offset + cast_int(TM_ADD)); /* ORDER TM */ + break; + } case OP_UNM: tm = TM_UNM; break; + case OP_BNOT: tm = TM_BNOT; break; case OP_LEN: tm = TM_LEN; break; + case OP_CONCAT: tm = TM_CONCAT; break; + case OP_EQ: tm = TM_EQ; break; case OP_LT: tm = TM_LT; break; case OP_LE: tm = TM_LE; break; - case OP_CONCAT: tm = TM_CONCAT; break; - default: - return NULL; /* else no useful name can be found */ + default: lua_assert(0); /* other instructions cannot call a function */ } *name = getstr(G(L)->tmname[tm]); return "metamethod"; @@ -480,17 +486,21 @@ static const char *getfuncname (lua_State *L, CallInfo *ci, const char **name) { /* -** only ANSI way to check whether a pointer points to an array -** (used only for error messages, so efficiency is not a big concern) +** The subtraction of two potentially unrelated pointers is +** not ISO C, but it should not crash a program; the subsequent +** checks are ISO C and ensure a correct result. */ static int isinstack (CallInfo *ci, const TValue *o) { - StkId p; - for (p = ci->u.l.base; p < ci->top; p++) - if (o == p) return 1; - return 0; + ptrdiff_t i = o - ci->u.l.base; + return (0 <= i && i < (ci->top - ci->u.l.base) && ci->u.l.base + i == o); } +/* +** Checks whether value 'o' came from an upvalue. (That can only happen +** with instructions OP_GETTABUP/OP_SETTABUP, which operate directly on +** upvalues.) +*/ static const char *getupvalname (CallInfo *ci, const TValue *o, const char **name) { LClosure *c = ci_func(ci); @@ -506,7 +516,7 @@ static const char *getupvalname (CallInfo *ci, const TValue *o, static const char *varinfo (lua_State *L, const TValue *o) { - const char *name; + const char *name = NULL; /* to avoid warnings */ CallInfo *ci = L->ci; const char *kind = NULL; if (isLua(ci)) { @@ -531,11 +541,12 @@ l_noret luaG_concaterror (lua_State *L, const TValue *p1, const TValue *p2) { } -l_noret luaG_aritherror (lua_State *L, const TValue *p1, const TValue *p2) { +l_noret luaG_opinterror (lua_State *L, const TValue *p1, + const TValue *p2, const char *msg) { lua_Number temp; if (!tonumber(p1, &temp)) /* first operand is wrong? */ p2 = p1; /* now second is wrong */ - luaG_typeerror(L, p2, "perform arithmetic on"); + luaG_typeerror(L, p2, msg); } @@ -579,10 +590,9 @@ static void addinfo (lua_State *L, const char *msg) { l_noret luaG_errormsg (lua_State *L) { if (L->errfunc != 0) { /* is there an error handling function? */ StkId errfunc = restorestack(L, L->errfunc); - if (!ttisfunction(errfunc)) luaD_throw(L, LUA_ERRERR); setobjs2s(L, L->top, L->top - 1); /* move argument */ setobjs2s(L, L->top - 1, errfunc); /* push function */ - L->top++; + L->top++; /* assume EXTRA_STACK */ luaD_call(L, L->top - 2, 1, 0); /* call it */ } luaD_throw(L, LUA_ERRRUN); diff --git a/src/ldebug.h b/src/ldebug.h index 1f3bf6cf..0d8966ca 100644 --- a/src/ldebug.h +++ b/src/ldebug.h @@ -1,5 +1,5 @@ /* -** $Id: ldebug.h,v 2.11 2014/02/25 14:31:16 roberto Exp $ +** $Id: ldebug.h,v 2.12 2014/11/10 14:46:05 roberto Exp $ ** Auxiliary functions from Debug Interface module ** See Copyright Notice in lua.h */ @@ -25,8 +25,9 @@ LUAI_FUNC l_noret luaG_typeerror (lua_State *L, const TValue *o, const char *opname); LUAI_FUNC l_noret luaG_concaterror (lua_State *L, const TValue *p1, const TValue *p2); -LUAI_FUNC l_noret luaG_aritherror (lua_State *L, const TValue *p1, - const TValue *p2); +LUAI_FUNC l_noret luaG_opinterror (lua_State *L, const TValue *p1, + const TValue *p2, + const char *msg); LUAI_FUNC l_noret luaG_tointerror (lua_State *L, const TValue *p1, const TValue *p2); LUAI_FUNC l_noret luaG_ordererror (lua_State *L, const TValue *p1, @@ -1,17 +1,19 @@ /* -** $Id: ldo.c,v 2.130 2014/10/17 16:28:21 roberto Exp $ +** $Id: ldo.c,v 2.135 2014/11/11 17:13:39 roberto Exp $ ** Stack and Call structure of Lua ** See Copyright Notice in lua.h */ +#define ldo_c +#define LUA_CORE + +#include "lprefix.h" + #include <setjmp.h> #include <stdlib.h> #include <string.h> -#define ldo_c -#define LUA_CORE - #include "lua.h" #include "lapi.h" @@ -67,7 +69,7 @@ #else /* }{ */ -/* ANSI handling with long jumps */ +/* ISO C handling with long jumps */ #define LUAI_THROW(L,c) longjmp((c)->b, 1) #define LUAI_TRY(L,c,a) if (setjmp((c)->b) == 0) { a } #define luai_jmpbuf jmp_buf @@ -119,8 +121,11 @@ l_noret luaD_throw (lua_State *L, int errcode) { } else { /* no handler at all; abort */ if (g->panic) { /* panic function? */ + seterrorobj(L, errcode, L->top); /* assume EXTRA_STACK */ + if (L->ci->top < L->top) + L->ci->top = L->top; /* pushing msg. can break this invariant */ lua_unlock(L); - g->panic(L); /* call it (last chance to jump out) */ + g->panic(L); /* call panic function (last chance to jump out) */ } abort(); } @@ -281,18 +286,21 @@ static StkId adjust_varargs (lua_State *L, Proto *p, int actual) { } -static StkId tryfuncTM (lua_State *L, StkId func) { +/* +** Check whether __call metafield of 'func' is a function. If so, put +** it in stack below original 'func' so that 'luaD_precall' can call +** it. Raise an error if __call metafield is not a function. +*/ +static void tryfuncTM (lua_State *L, StkId func) { const TValue *tm = luaT_gettmbyobj(L, func, TM_CALL); StkId p; - ptrdiff_t funcr = savestack(L, func); if (!ttisfunction(tm)) luaG_typeerror(L, func, "call"); - /* Open a hole inside the stack at `func' */ - for (p = L->top; p > func; p--) setobjs2s(L, p, p-1); - incr_top(L); - func = restorestack(L, funcr); /* previous call may change stack */ + /* Open a hole inside the stack at 'func' */ + for (p = L->top; p > func; p--) + setobjs2s(L, p, p-1); + L->top++; /* slot ensured by caller */ setobj2s(L, func, tm); /* tag method is the new function to be called */ - return func; } @@ -362,7 +370,9 @@ int luaD_precall (lua_State *L, StkId func, int nresults) { return 0; } default: { /* not a function */ - func = tryfuncTM(L, func); /* retry with 'function' tag method */ + luaD_checkstack(L, 1); /* ensure space for metamethod */ + func = restorestack(L, funcr); /* previous call may change stack */ + tryfuncTM(L, func); /* try to get '__call' metamethod */ return luaD_precall(L, func, nresults); /* now it must be a function */ } } @@ -575,7 +585,7 @@ LUA_API int lua_resume (lua_State *L, lua_State *from, int nargs) { status = luaD_rawrunprotected(L, unroll, &status); } if (errorstatus(status)) { /* unrecoverable error? */ - L->status = cast_byte(status); /* mark thread as `dead' */ + L->status = cast_byte(status); /* mark thread as 'dead' */ seterrorobj(L, status, L->top); /* push error message */ L->ci->top = L->top; } @@ -650,7 +660,7 @@ int luaD_pcall (lua_State *L, Pfunc func, void *u, /* ** Execute a protected parser. */ -struct SParser { /* data to `f_parser' */ +struct SParser { /* data to 'f_parser' */ ZIO *z; Mbuffer buff; /* dynamic structure used by the scanner */ Dyndata dyd; /* dynamic structures used by the parser */ @@ -1,5 +1,5 @@ /* -** $Id: ldo.h,v 2.20 2011/11/29 15:55:08 roberto Exp $ +** $Id: ldo.h,v 2.21 2014/10/25 11:50:46 roberto Exp $ ** Stack and Call structure of Lua ** See Copyright Notice in lua.h */ @@ -23,7 +23,7 @@ #define restorestack(L,n) ((TValue *)((char *)L->stack + (n))) -/* type of protected functions, to be ran by `runprotected' */ +/* type of protected functions, to be ran by 'runprotected' */ typedef void (*Pfunc) (lua_State *L, void *ud); LUAI_FUNC int luaD_protectedparser (lua_State *L, ZIO *z, const char *name, diff --git a/src/ldump.c b/src/ldump.c index 4418f3be..b6c7114f 100644 --- a/src/ldump.c +++ b/src/ldump.c @@ -1,14 +1,17 @@ /* -** $Id: ldump.c,v 2.33 2014/07/18 13:36:14 roberto Exp $ +** $Id: ldump.c,v 2.34 2014/11/02 19:19:04 roberto Exp $ ** save precompiled Lua chunks ** See Copyright Notice in lua.h */ -#include <stddef.h> - #define ldump_c #define LUA_CORE +#include "lprefix.h" + + +#include <stddef.h> + #include "lua.h" #include "lobject.h" diff --git a/src/lfunc.c b/src/lfunc.c index 8a78fb6e..67967dab 100644 --- a/src/lfunc.c +++ b/src/lfunc.c @@ -1,15 +1,17 @@ /* -** $Id: lfunc.c,v 2.43 2014/06/19 18:27:20 roberto Exp $ +** $Id: lfunc.c,v 2.45 2014/11/02 19:19:04 roberto Exp $ ** Auxiliary functions to manipulate prototypes and closures ** See Copyright Notice in lua.h */ - -#include <stddef.h> - #define lfunc_c #define LUA_CORE +#include "lprefix.h" + + +#include <stddef.h> + #include "lua.h" #include "lfunc.h" @@ -82,7 +84,7 @@ void luaF_close (lua_State *L, StkId level) { UpVal *uv; while (L->openupval != NULL && (uv = L->openupval)->v >= level) { lua_assert(upisopen(uv)); - L->openupval = uv->u.open.next; /* remove from `open' list */ + L->openupval = uv->u.open.next; /* remove from 'open' list */ if (uv->refcount == 0) /* no references? */ luaM_free(L, uv); /* free upvalue */ else { @@ -132,7 +134,7 @@ void luaF_freeproto (lua_State *L, Proto *f) { /* -** Look for n-th local variable at line `line' in function `func'. +** Look for n-th local variable at line 'line' in function 'func'. ** Returns NULL if not found. */ const char *luaF_getlocalname (const Proto *f, int local_number, int pc) { @@ -1,14 +1,17 @@ /* -** $Id: lgc.c,v 2.196 2014/10/03 12:54:37 roberto Exp $ +** $Id: lgc.c,v 2.200 2014/11/02 19:19:04 roberto Exp $ ** Garbage Collector ** See Copyright Notice in lua.h */ -#include <string.h> - #define lgc_c #define LUA_CORE +#include "lprefix.h" + + +#include <string.h> + #include "lua.h" #include "ldebug.h" @@ -119,14 +122,14 @@ static void removeentry (Node *n) { /* ** tells whether a key or value can be cleared from a weak ** table. Non-collectable objects are never removed from weak -** tables. Strings behave as `values', so are never removed too. for +** tables. Strings behave as 'values', so are never removed too. for ** other objects: if really collected, cannot keep them; for objects ** being finalized, keep them in keys, but not in values */ static int iscleared (global_State *g, const TValue *o) { if (!iscollectable(o)) return 0; else if (ttisstring(o)) { - markobject(g, tsvalue(o)); /* strings are `values', so are never weak */ + markobject(g, tsvalue(o)); /* strings are 'values', so are never weak */ return 0; } else return iswhite(gcvalue(o)); @@ -909,12 +912,15 @@ void luaC_checkfinalizer (lua_State *L, GCObject *o, Table *mt) { /* -** set a reasonable "time" to wait before starting a new GC cycle; -** cycle will start when memory use hits threshold +** Set a reasonable "time" to wait before starting a new GC cycle; cycle +** will start when memory use hits threshold. (Division by 'estimate' +** should be OK: it cannot be zero (because Lua cannot even start with +** less than PAUSEADJ bytes). */ static void setpause (global_State *g) { l_mem threshold, debt; l_mem estimate = g->GCestimate / PAUSEADJ; /* adjust 'estimate' */ + lua_assert(estimate > 0); threshold = (g->gcpause < MAX_LMEM / estimate) /* overflow? */ ? estimate * g->gcpause /* no overflow */ : MAX_LMEM; /* overflow; truncate to maximum */ @@ -972,7 +978,7 @@ static l_mem atomic (lua_State *L) { /* remark occasional upvalues of (maybe) dead threads */ remarkupvals(g); propagateall(g); /* propagate changes */ - work = g->GCmemtrav; /* stop counting (do not recount gray-agains) */ + work = g->GCmemtrav; /* stop counting (do not recount 'grayagain') */ g->gray = grayagain; propagateall(g); /* traverse 'grayagain' list */ g->GCmemtrav = 0; /* restart counting */ @@ -992,7 +998,7 @@ static l_mem atomic (lua_State *L) { /* at this point, all resurrected objects are marked. */ /* remove dead objects from weak tables */ clearkeys(g, g->ephemeron, NULL); /* clear keys from all ephemeron tables */ - clearkeys(g, g->allweak, NULL); /* clear keys from all allweak tables */ + clearkeys(g, g->allweak, NULL); /* clear keys from all 'allweak' tables */ /* clear values from resurrected weak tables */ clearvalues(g, g->weak, origweak); clearvalues(g, g->allweak, origall); @@ -1031,7 +1037,7 @@ static lu_mem singlestep (lua_State *L) { g->GCmemtrav = 0; lua_assert(g->gray); propagatemark(g); - if (g->gray == NULL) /* no more `gray' objects? */ + if (g->gray == NULL) /* no more gray objects? */ g->gcstate = GCSatomic; /* finish propagate phase */ return g->GCmemtrav; /* memory traversed in this step */ } @@ -1122,7 +1128,7 @@ void luaC_step (lua_State *L) { /* -** Performs a full GC cycle; if "isemergency", set a flag to avoid +** Performs a full GC cycle; if 'isemergency', set a flag to avoid ** some operations which could change the interpreter state in some ** unexpected ways (running finalizers and shrinking some structures). ** Before running the collection, check 'keepinvariant'; if it is true, @@ -1,5 +1,5 @@ /* -** $Id: lgc.h,v 2.85 2014/07/19 15:14:46 roberto Exp $ +** $Id: lgc.h,v 2.86 2014/10/25 11:50:46 roberto Exp $ ** Garbage Collector ** See Copyright Notice in lua.h */ @@ -74,7 +74,7 @@ #define testbit(x,b) testbits(x, bitmask(b)) -/* Layout for bit use in `marked' field: */ +/* Layout for bit use in 'marked' field: */ #define WHITE0BIT 0 /* object is white (type 0) */ #define WHITE1BIT 1 /* object is white (type 1) */ #define BLACKBIT 2 /* object is black */ diff --git a/src/linit.c b/src/linit.c index 904aca9a..ca9d100d 100644 --- a/src/linit.c +++ b/src/linit.c @@ -1,21 +1,32 @@ /* -** $Id: linit.c,v 1.34 2014/05/15 19:28:34 roberto Exp $ +** $Id: linit.c,v 1.37 2014/12/09 15:00:17 roberto Exp $ ** Initialization of libraries for lua.c and other clients ** See Copyright Notice in lua.h */ +#define linit_c +#define LUA_LIB + +#include "lprefix.h" + + /* ** If you embed Lua in your program and need to open the standard ** libraries, call luaL_openlibs in your program. If you need a ** different set of libraries, copy this file to your project and edit ** it to suit your needs. +** +** You can also *preload* libraries, so that a later 'require' can +** open the library, which is already linked to the application. +** For that, do the following code: +** +** luaL_getsubtable(L, LUA_REGISTRYINDEX, "_PRELOAD"); +** lua_pushcfunction(L, luaopen_modname); +** lua_setfield(L, -2, modname); +** lua_pop(L, 1); // remove _PRELOAD table */ - -#define linit_c -#define LUA_LIB - #include "lua.h" #include "lualib.h" @@ -35,8 +46,8 @@ static const luaL_Reg loadedlibs[] = { {LUA_OSLIBNAME, luaopen_os}, {LUA_STRLIBNAME, luaopen_string}, {LUA_MATHLIBNAME, luaopen_math}, - {LUA_DBLIBNAME, luaopen_debug}, {LUA_UTF8LIBNAME, luaopen_utf8}, + {LUA_DBLIBNAME, luaopen_debug}, #if defined(LUA_COMPAT_BITLIB) {LUA_BITLIBNAME, luaopen_bit32}, #endif @@ -44,27 +55,12 @@ static const luaL_Reg loadedlibs[] = { }; -/* -** these libs are preloaded and must be required before used -*/ -static const luaL_Reg preloadedlibs[] = { - {NULL, NULL} -}; - - LUALIB_API void luaL_openlibs (lua_State *L) { const luaL_Reg *lib; - /* call open functions from 'loadedlibs' and set results to global table */ + /* "require" functions from 'loadedlibs' and set results to global table */ for (lib = loadedlibs; lib->func; lib++) { luaL_requiref(L, lib->name, lib->func, 1); lua_pop(L, 1); /* remove lib */ } - /* add open functions from 'preloadedlibs' into 'package.preload' table */ - luaL_getsubtable(L, LUA_REGISTRYINDEX, "_PRELOAD"); - for (lib = preloadedlibs; lib->func; lib++) { - lua_pushcfunction(L, lib->func); - lua_setfield(L, -2, lib->name); - } - lua_pop(L, 1); /* remove _PRELOAD table */ } diff --git a/src/liolib.c b/src/liolib.c index 9101ecae..245036bd 100644 --- a/src/liolib.c +++ b/src/liolib.c @@ -1,18 +1,13 @@ /* -** $Id: liolib.c,v 2.136 2014/10/22 16:55:57 roberto Exp $ +** $Id: liolib.c,v 2.141 2014/11/21 12:17:33 roberto Exp $ ** Standard I/O (and system) library ** See Copyright Notice in lua.h */ +#define liolib_c +#define LUA_LIB -/* -** This definition must come before the inclusion of 'stdio.h'; it -** should not affect non-POSIX systems -*/ -#if !defined(_FILE_OFFSET_BITS) -#define _LARGEFILE_SOURCE 1 -#define _FILE_OFFSET_BITS 64 -#endif +#include "lprefix.h" #include <ctype.h> @@ -22,9 +17,6 @@ #include <stdlib.h> #include <string.h> -#define liolib_c -#define LUA_LIB - #include "lua.h" #include "lauxlib.h" @@ -60,14 +52,14 @@ #define l_popen(L,c,m) (fflush(NULL), popen(c,m)) #define l_pclose(L,file) (pclose(file)) -#elif defined(LUA_WIN) /* }{ */ +#elif defined(LUA_USE_WINDOWS) /* }{ */ #define l_popen(L,c,m) (_popen(c,m)) #define l_pclose(L,file) (_pclose(file)) #else /* }{ */ -/* ANSI definitions */ +/* ISO C definitions */ #define l_popen(L,c,m) \ ((void)((void)c, m), \ luaL_error(L, "'popen' not supported"), \ @@ -112,7 +104,7 @@ #define l_ftell(f) ftello(f) #define l_seeknum off_t -#elif defined(LUA_WIN) && !defined(_CRTIMP_TYPEINFO) \ +#elif defined(LUA_USE_WINDOWS) && !defined(_CRTIMP_TYPEINFO) \ && defined(_MSC_VER) && (_MSC_VER >= 1400) /* }{ */ /* Windows (but not DDK) and Visual C++ 2005 or higher */ @@ -122,7 +114,7 @@ #else /* }{ */ -/* ANSI definitions */ +/* ISO C definitions */ #define l_fseek(f,o,w) fseek(f,o,w) #define l_ftell(f) ftell(f) #define l_seeknum long @@ -182,7 +174,7 @@ static FILE *tofile (lua_State *L) { /* -** When creating file handles, always creates a `closed' file handle +** When creating file handles, always creates a 'closed' file handle ** before opening the actual file; so, if there is a memory error, the ** file is not left opened. */ @@ -474,12 +466,21 @@ static int read_line (lua_State *L, FILE *f, int chop) { luaL_Buffer b; int c; luaL_buffinit(L, &b); - l_lockfile(f); - while ((c = l_getc(f)) != EOF && c != '\n') - luaL_addchar(&b, c); - l_unlockfile(f); - if (!chop && c == '\n') luaL_addchar(&b, c); + for (;;) { + char *buff = luaL_prepbuffer(&b); /* pre-allocate buffer */ + int i = 0; + l_lockfile(f); /* no memory errors can happen inside the lock */ + while (i < LUAL_BUFFERSIZE && (c = l_getc(f)) != EOF && c != '\n') + buff[i++] = c; + l_unlockfile(f); + luaL_addsize(&b, i); + if (i < LUAL_BUFFERSIZE) + break; + } + if (!chop && c == '\n') /* want a newline and have one? */ + luaL_addchar(&b, c); /* add ending newline to result */ luaL_pushresult(&b); /* close buffer */ + /* return ok if read something (either a newline or something else) */ return (c == '\n' || lua_rawlen(L, -1) > 0); } @@ -524,7 +525,7 @@ static int g_read (lua_State *L, FILE *f, int first) { success = 1; for (n = first; nargs-- && success; n++) { if (lua_type(L, n) == LUA_TNUMBER) { - size_t l = (size_t)lua_tointeger(L, n); + size_t l = (size_t)luaL_checkinteger(L, n); success = (l == 0) ? test_eof(L, f) : read_chars(L, f, l); } else { @@ -1,16 +1,18 @@ /* -** $Id: llex.c,v 2.84 2014/10/22 11:44:20 roberto Exp $ +** $Id: llex.c,v 2.89 2014/11/14 16:06:09 roberto Exp $ ** Lexical Analyzer ** See Copyright Notice in lua.h */ +#define llex_c +#define LUA_CORE + +#include "lprefix.h" + #include <locale.h> #include <string.h> -#define llex_c -#define LUA_CORE - #include "lua.h" #include "lctype.h" @@ -41,7 +43,7 @@ static const char *const luaX_tokens [] = { "return", "then", "true", "until", "while", "//", "..", "...", "==", ">=", "<=", "~=", "<<", ">>", "::", "<eof>", - "<number>", "<number>", "<name>", "<string>" + "<number>", "<integer>", "<name>", "<string>" }; @@ -125,7 +127,7 @@ l_noret luaX_syntaxerror (LexState *ls, const char *msg) { */ TString *luaX_newstring (LexState *ls, const char *str, size_t l) { lua_State *L = ls->L; - TValue *o; /* entry for `str' */ + TValue *o; /* entry for 'str' */ TString *ts = luaS_newlstr(L, str, l); /* create new string */ setsvalue2s(L, L->top++, ts); /* temporarily anchor it in stack */ o = luaH_set(L, ls->h, L->top - 1); @@ -150,16 +152,17 @@ TString *luaX_newstring (LexState *ls, const char *str, size_t l) { static void inclinenumber (LexState *ls) { int old = ls->current; lua_assert(currIsNewline(ls)); - next(ls); /* skip `\n' or `\r' */ + next(ls); /* skip '\n' or '\r' */ if (currIsNewline(ls) && ls->current != old) - next(ls); /* skip `\n\r' or `\r\n' */ + next(ls); /* skip '\n\r' or '\r\n' */ if (++ls->linenumber >= MAX_INT) - luaX_syntaxerror(ls, "chunk has too many lines"); + lexerror(ls, "chunk has too many lines", 0); } void luaX_setinput (lua_State *L, LexState *ls, ZIO *z, TString *source, int firstchar) { + ls->t.token = 0; ls->decpoint = '.'; ls->L = L; ls->current = firstchar; @@ -298,7 +301,7 @@ static int skip_sep (LexState *ls) { static void read_long_string (LexState *ls, SemInfo *seminfo, int sep) { int line = ls->linenumber; /* initial line (for error message) */ - save_and_next(ls); /* skip 2nd `[' */ + save_and_next(ls); /* skip 2nd '[' */ if (currIsNewline(ls)) /* string starts with a newline? */ inclinenumber(ls); /* skip it */ for (;;) { @@ -312,7 +315,7 @@ static void read_long_string (LexState *ls, SemInfo *seminfo, int sep) { } case ']': { if (skip_sep(ls) == sep) { - save_and_next(ls); /* skip 2nd `]' */ + save_and_next(ls); /* skip 2nd ']' */ goto endloop; } break; @@ -438,7 +441,7 @@ static void read_string (LexState *ls, int del, SemInfo *seminfo) { } default: { esccheck(ls, lisdigit(ls->current), "invalid escape sequence"); - c = readdecesc(ls); /* digital escape \ddd */ + c = readdecesc(ls); /* digital escape '\ddd' */ goto only_save; } } @@ -480,7 +483,7 @@ static int llex (LexState *ls, SemInfo *seminfo) { next(ls); if (ls->current == '[') { /* long comment? */ int sep = skip_sep(ls); - luaZ_resetbuffer(ls->buff); /* `skip_sep' may dirty the buffer */ + luaZ_resetbuffer(ls->buff); /* 'skip_sep' may dirty the buffer */ if (sep >= 0) { read_long_string(ls, NULL, sep); /* skip long comment */ luaZ_resetbuffer(ls->buff); /* previous call may dirty the buff. */ @@ -1,5 +1,5 @@ /* -** $Id: llex.h,v 1.76 2013/12/30 20:47:58 roberto Exp $ +** $Id: llex.h,v 1.78 2014/10/29 15:38:24 roberto Exp $ ** Lexical Analyzer ** See Copyright Notice in lua.h */ @@ -14,6 +14,10 @@ #define FIRST_RESERVED 257 +#if !defined(LUA_ENV) +#define LUA_ENV "_ENV" +#endif + /* * WARNING: if you change the order of this enumeration, @@ -54,7 +58,7 @@ typedef struct Token { typedef struct LexState { int current; /* current character (charint) */ int linenumber; /* input line counter */ - int lastline; /* line of last token `consumed' */ + int lastline; /* line of last token 'consumed' */ Token t; /* current token */ Token lookahead; /* look ahead token */ struct FuncState *fs; /* current function (parser) */ diff --git a/src/llimits.h b/src/llimits.h index 1f41e257..59f342dc 100644 --- a/src/llimits.h +++ b/src/llimits.h @@ -1,6 +1,6 @@ /* -** $Id: llimits.h,v 1.120 2014/07/18 18:29:12 roberto Exp $ -** Limits, basic types, and some other `installation-dependent' definitions +** $Id: llimits.h,v 1.124 2014/11/02 19:33:33 roberto Exp $ +** Limits, basic types, and some other 'installation-dependent' definitions ** See Copyright Notice in lua.h */ @@ -14,16 +14,24 @@ #include "lua.h" - -typedef unsigned LUA_INT32 lu_int32; - +/* +** 'lu_mem' and 'l_mem' are unsigned/signed integers big enough to count +** the total memory used by Lua (in bytes). Usually, 'size_t' and +** 'ptrdiff_t' should work, but we use 'long' for 16-bit machines. +*/ +#if defined(LUAI_MEM) /* { external definitions? */ typedef LUAI_UMEM lu_mem; - typedef LUAI_MEM l_mem; +#elif LUAI_BITSINT >= 32 /* }{ */ +typedef size_t lu_mem; +typedef ptrdiff_t l_mem; +#else /* 16-bit ints */ /* }{ */ +typedef unsigned long lu_mem; +typedef long l_mem; +#endif /* } */ - -/* chars used as small naturals (so that `char' is reserved for characters) */ +/* chars used as small naturals (so that 'char' is reserved for characters) */ typedef unsigned char lu_byte; @@ -48,7 +56,7 @@ typedef unsigned char lu_byte; ** this is for hashing only; there is no problem if the integer ** cannot hold the whole pointer value */ -#define point2int(p) ((unsigned int)((lu_mem)(p) & UINT_MAX)) +#define point2int(p) ((unsigned int)((size_t)(p) & UINT_MAX)) @@ -112,7 +120,7 @@ typedef LUAI_UACINT l_uacInt; /* ** cast a lua_Unsigned to a signed lua_Integer; this cast is -** not strict ANSI C, but two-complement architectures should +** not strict ISO C, but two-complement architectures should ** work fine. */ #if !defined(l_castU2S) @@ -149,15 +157,15 @@ typedef LUAI_UACINT l_uacInt; /* -** type for virtual-machine instructions +** type for virtual-machine instructions; ** must be an unsigned with (at least) 4 bytes (see details in lopcodes.h) */ -typedef lu_int32 Instruction; - - +#if LUAI_BITSINT >= 32 +typedef unsigned int Instruction; +#else +typedef unsigned long Instruction; +#endif -/* maximum stack for a Lua function */ -#define MAXSTACK 250 @@ -174,12 +182,12 @@ typedef lu_int32 Instruction; #if !defined(lua_lock) -#define lua_lock(L) ((void) 0) -#define lua_unlock(L) ((void) 0) +#define lua_lock(L) ((void) 0) +#define lua_unlock(L) ((void) 0) #endif #if !defined(luai_threadyield) -#define luai_threadyield(L) {lua_unlock(L); lua_lock(L);} +#define luai_threadyield(L) {lua_unlock(L); lua_lock(L);} #endif @@ -205,11 +213,11 @@ typedef lu_int32 Instruction; #endif #if !defined(luai_userstateresume) -#define luai_userstateresume(L,n) ((void)L) +#define luai_userstateresume(L,n) ((void)L) #endif #if !defined(luai_userstateyield) -#define luai_userstateyield(L,n) ((void)L) +#define luai_userstateyield(L,n) ((void)L) #endif diff --git a/src/lmathlib.c b/src/lmathlib.c index 523e0b64..158f2337 100644 --- a/src/lmathlib.c +++ b/src/lmathlib.c @@ -1,16 +1,18 @@ /* -** $Id: lmathlib.c,v 1.110 2014/10/08 19:57:31 roberto Exp $ +** $Id: lmathlib.c,v 1.113 2014/11/07 11:31:58 roberto Exp $ ** Standard mathematical library ** See Copyright Notice in lua.h */ +#define lmathlib_c +#define LUA_LIB + +#include "lprefix.h" + #include <stdlib.h> #include <math.h> -#define lmathlib_c -#define LUA_LIB - #include "lua.h" #include "lauxlib.h" @@ -91,7 +93,7 @@ static int math_toint (lua_State *L) { static void pushnumint (lua_State *L, lua_Number d) { lua_Integer n; - if (lua_numtointeger(d, &n)) /* does 'd' fit in an integer? */ + if (lua_numbertointeger(d, &n)) /* does 'd' fit in an integer? */ lua_pushinteger(L, n); /* result is integer */ else lua_pushnumber(L, d); /* result is float */ @@ -256,8 +258,8 @@ static int math_random (lua_State *L) { } /* random integer in the interval [low, up] */ luaL_argcheck(L, low <= up, 1, "interval is empty"); - luaL_argcheck(L, (lua_Unsigned)up - low <= (lua_Unsigned)LUA_MAXINTEGER, - 1, "interval too large"); + luaL_argcheck(L, low >= 0 || up <= LUA_MAXINTEGER + low, 1, + "interval too large"); r *= (double)(up - low) + 1.0; lua_pushinteger(L, (lua_Integer)r + low); return 1; @@ -1,15 +1,17 @@ /* -** $Id: lmem.c,v 1.86 2014/07/15 21:26:50 roberto Exp $ +** $Id: lmem.c,v 1.89 2014/11/02 19:33:33 roberto Exp $ ** Interface to Memory Manager ** See Copyright Notice in lua.h */ - -#include <stddef.h> - #define lmem_c #define LUA_CORE +#include "lprefix.h" + + +#include <stddef.h> + #include "lua.h" #include "ldebug.h" @@ -24,15 +26,15 @@ /* ** About the realloc function: ** void * frealloc (void *ud, void *ptr, size_t osize, size_t nsize); -** (`osize' is the old size, `nsize' is the new size) +** ('osize' is the old size, 'nsize' is the new size) ** -** * frealloc(ud, NULL, x, s) creates a new block of size `s' (no +** * frealloc(ud, NULL, x, s) creates a new block of size 's' (no ** matter 'x'). ** -** * frealloc(ud, p, x, 0) frees the block `p' +** * frealloc(ud, p, x, 0) frees the block 'p' ** (in this specific case, frealloc must return NULL); ** particularly, frealloc(ud, NULL, 0, 0) does nothing -** (which is equivalent to free(NULL) in ANSI C) +** (which is equivalent to free(NULL) in ISO C) ** ** frealloc returns NULL if it cannot create or reallocate the area ** (any reallocation to an equal or smaller size cannot fail!) diff --git a/src/loadlib.c b/src/loadlib.c index 9cf5e69d..1dab9bd0 100644 --- a/src/loadlib.c +++ b/src/loadlib.c @@ -1,5 +1,5 @@ /* -** $Id: loadlib.c,v 1.117 2014/10/17 16:28:21 roberto Exp $ +** $Id: loadlib.c,v 1.123 2014/11/12 13:31:51 roberto Exp $ ** Dynamic library loader for Lua ** See Copyright Notice in lua.h ** @@ -8,22 +8,15 @@ ** systems. */ +#define loadlib_c +#define LUA_LIB -/* -** if needed, includes windows header before everything else -*/ -#if defined(_WIN32) -#include <windows.h> -#endif +#include "lprefix.h" #include <stdlib.h> #include <string.h> - -#define loadlib_c -#define LUA_LIB - #include "lua.h" #include "lauxlib.h" @@ -92,8 +85,11 @@ #define LUA_OFSEP "_" -/* table (in the registry) that keeps handles for all loaded C libraries */ -#define CLIBS "_CLIBS" +/* +** unique key for table in the registry that keeps handles +** for all loaded C libraries +*/ +static const int CLIBS = 0; #define LIB_FAIL "open" @@ -127,7 +123,7 @@ static lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym); -#if defined(LUA_USE_DLOPEN) +#if defined(LUA_USE_DLOPEN) /* { */ /* ** {======================================================================== ** This is an implementation of loadlib based on the dlfcn interface. @@ -161,13 +157,15 @@ static lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym) { -#elif defined(LUA_DL_DLL) +#elif defined(LUA_DL_DLL) /* }{ */ /* ** {====================================================================== ** This is an implementation of loadlib for Windows using native functions. ** ======================================================================= */ +#include <windows.h> + #undef setprogdir /* @@ -225,7 +223,7 @@ static lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym) { /* }====================================================== */ -#else +#else /* }{ */ /* ** {====================================================== ** Fallback for other systems @@ -258,7 +256,7 @@ static lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym) { } /* }====================================================== */ -#endif +#endif /* } */ /* @@ -266,7 +264,7 @@ static lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym) { */ static void *checkclib (lua_State *L, const char *path) { void *plib; - lua_getfield(L, LUA_REGISTRYINDEX, CLIBS); + lua_rawgetp(L, LUA_REGISTRYINDEX, &CLIBS); lua_getfield(L, -1, path); plib = lua_touserdata(L, -1); /* plib = CLIBS[path] */ lua_pop(L, 2); /* pop CLIBS table and 'plib' */ @@ -279,7 +277,7 @@ static void *checkclib (lua_State *L, const char *path) { ** registry.CLIBS[#CLIBS + 1] = plib -- also keep a list of all libraries */ static void addtoclib (lua_State *L, const char *path, void *plib) { - lua_getfield(L, LUA_REGISTRYINDEX, CLIBS); + lua_rawgetp(L, LUA_REGISTRYINDEX, &CLIBS); lua_pushlightuserdata(L, plib); lua_pushvalue(L, -1); lua_setfield(L, -3, path); /* CLIBS[path] = plib */ @@ -520,8 +518,8 @@ static void findloader (lua_State *L, const char *name) { int i; luaL_Buffer msg; /* to build error message */ luaL_buffinit(L, &msg); - lua_getfield(L, lua_upvalueindex(1), "searchers"); /* will be at index 3 */ - if (!lua_istable(L, 3)) + /* push 'package.searchers' to index 3 in the stack */ + if (lua_getfield(L, lua_upvalueindex(1), "searchers") != LUA_TTABLE) luaL_error(L, "'package.searchers' must be a table"); /* iterate over available searchers to find a loader */ for (i = 1; ; i++) { @@ -729,7 +727,7 @@ static void createsearcherstable (lua_State *L) { } #if defined(LUA_COMPAT_LOADERS) lua_pushvalue(L, -1); /* make a copy of 'searchers' table */ - lua_setfield(L, -3, "loaders"); /* put it in field `loaders' */ + lua_setfield(L, -3, "loaders"); /* put it in field 'loaders' */ #endif lua_setfield(L, -2, "searchers"); /* put it in field 'searchers' */ } @@ -740,17 +738,18 @@ static void createsearcherstable (lua_State *L) { ** setting a finalizer to close all libraries when closing state. */ static void createclibstable (lua_State *L) { - luaL_getsubtable(L, LUA_REGISTRYINDEX, CLIBS); /* create CLIBS table */ + lua_newtable(L); /* create CLIBS table */ lua_createtable(L, 0, 1); /* create metatable for CLIBS */ lua_pushcfunction(L, gctm); lua_setfield(L, -2, "__gc"); /* set finalizer for CLIBS table */ lua_setmetatable(L, -2); + lua_rawsetp(L, LUA_REGISTRYINDEX, &CLIBS); /* set CLIBS table in registry */ } LUAMOD_API int luaopen_package (lua_State *L) { createclibstable(L); - luaL_newlib(L, pk_funcs); /* create `package' table */ + luaL_newlib(L, pk_funcs); /* create 'package' table */ createsearcherstable(L); /* set field 'path' */ setpath(L, "path", LUA_PATHVARVERSION, LUA_PATH_VAR, LUA_PATH_DEFAULT); @@ -760,10 +759,10 @@ LUAMOD_API int luaopen_package (lua_State *L) { lua_pushliteral(L, LUA_DIRSEP "\n" LUA_PATH_SEP "\n" LUA_PATH_MARK "\n" LUA_EXEC_DIR "\n" LUA_IGMARK "\n"); lua_setfield(L, -2, "config"); - /* set field `loaded' */ + /* set field 'loaded' */ luaL_getsubtable(L, LUA_REGISTRYINDEX, "_LOADED"); lua_setfield(L, -2, "loaded"); - /* set field `preload' */ + /* set field 'preload' */ luaL_getsubtable(L, LUA_REGISTRYINDEX, "_PRELOAD"); lua_setfield(L, -2, "preload"); lua_pushglobaltable(L); diff --git a/src/lobject.c b/src/lobject.c index 28048dd7..ceb4b983 100644 --- a/src/lobject.c +++ b/src/lobject.c @@ -1,17 +1,20 @@ /* -** $Id: lobject.c,v 2.93 2014/10/17 16:28:21 roberto Exp $ +** $Id: lobject.c,v 2.100 2014/11/21 12:15:57 roberto Exp $ ** Some generic functions over Lua objects ** See Copyright Notice in lua.h */ +#define lobject_c +#define LUA_CORE + +#include "lprefix.h" + + #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> -#define lobject_c -#define LUA_CORE - #include "lua.h" #include "lctype.h" @@ -98,6 +101,7 @@ static lua_Number numarith (lua_State *L, int op, lua_Number v1, case LUA_OPMUL: return luai_nummul(L, v1, v2); case LUA_OPDIV: return luai_numdiv(L, v1, v2); case LUA_OPPOW: return luai_numpow(L, v1, v2); + case LUA_OPIDIV: return luai_numidiv(L, v1, v2); case LUA_OPUNM: return luai_numunm(L, v1); case LUA_OPMOD: { lua_Number m; @@ -112,9 +116,9 @@ static lua_Number numarith (lua_State *L, int op, lua_Number v1, void luaO_arith (lua_State *L, int op, const TValue *p1, const TValue *p2, TValue *res) { switch (op) { - case LUA_OPIDIV: case LUA_OPBAND: case LUA_OPBOR: - case LUA_OPBXOR: case LUA_OPSHL: case LUA_OPSHR: - case LUA_OPBNOT: { /* operates only on integers */ + case LUA_OPBAND: case LUA_OPBOR: case LUA_OPBXOR: + case LUA_OPSHL: case LUA_OPSHR: + case LUA_OPBNOT: { /* operate only on integers */ lua_Integer i1; lua_Integer i2; if (tointeger(p1, &i1) && tointeger(p2, &i2)) { setivalue(res, intarith(L, op, i1, i2)); @@ -162,24 +166,13 @@ static int isneg (const char **s) { } + /* -** {====================================================== -** lua_strx2number converts an hexadecimal numeric string to a number. -** In C99, 'strtod' does both conversions. C89, however, has no function -** to convert floating hexadecimal strings to numbers. For these -** systems, you can leave 'lua_strx2number' undefined and Lua will -** provide its own implementation. -** ======================================================= +** {================================================================== +** Lua's implementation for 'lua_strx2number' +** =================================================================== */ -#if !defined(lua_strx2number) /* { */ - -#if defined(LUA_USE_C99) /* { */ - -#define lua_strx2number(s,p) lua_str2number(s,p) - -#else /* }{ */ - -/* Lua's implementation for 'lua_strx2number' */ +#if !defined(lua_strx2number) #include <math.h> @@ -209,18 +202,12 @@ static lua_Number lua_strx2number (const char *s, char **endptr) { else dot = 1; } else if (lisxdigit(cast_uchar(*s))) { - if (sigdig == 0 && *s == '0') { /* non-significant zero? */ + if (sigdig == 0 && *s == '0') /* non-significant digit (zero)? */ nosigdig++; - if (dot) e--; /* zero after dot? correct exponent */ - } - else { - if (++sigdig <= MAXSIGDIG) { /* can read it without overflow? */ - r = (r * cast_num(16.0)) + luaO_hexavalue(cast_uchar(*s)); - if (dot) e--; /* decimal digit */ - } - else /* too many digits; ignore */ - if (!dot) e++; /* still count it for exponent */ - } + else if (++sigdig <= MAXSIGDIG) /* can read it without overflow? */ + r = (r * cast_num(16.0)) + luaO_hexavalue(*s); + else e++; /* too many digits; ignore, but still count for exponent */ + if (dot) e--; /* decimal digit? correct exponent */ } else break; /* neither a dot nor a digit */ } @@ -245,10 +232,7 @@ static lua_Number lua_strx2number (const char *s, char **endptr) { return l_mathop(ldexp)(r, e); } -#endif /* } */ - -#endif /* } */ - +#endif /* }====================================================== */ @@ -276,13 +260,13 @@ static const char *l_str2int (const char *s, lua_Integer *result) { (s[1] == 'x' || s[1] == 'X')) { /* hex? */ s += 2; /* skip '0x' */ for (; lisxdigit(cast_uchar(*s)); s++) { - a = a * 16 + luaO_hexavalue(cast_uchar(*s)); + a = a * 16 + luaO_hexavalue(*s); empty = 0; } } else { /* decimal */ for (; lisdigit(cast_uchar(*s)); s++) { - a = a * 10 + luaO_hexavalue(cast_uchar(*s)); + a = a * 10 + *s - '0'; empty = 0; } } @@ -317,8 +301,8 @@ int luaO_utf8esc (char *buff, unsigned long x) { buff[UTF8BUFFSZ - 1] = cast(char, x); else { /* need continuation bytes */ unsigned int mfb = 0x3f; /* maximum that fits in first byte */ - do { - buff[UTF8BUFFSZ - (n++)] = 0x80 | (x & 0x3f); /* add continuation byte */ + do { /* add continuation bytes */ + buff[UTF8BUFFSZ - (n++)] = cast(char, 0x80 | (x & 0x3f)); x >>= 6; /* remove added bits */ mfb >>= 1; /* now there is one less bit available in first byte */ } while (x > mfb); /* still needs continuation byte? */ @@ -399,7 +383,7 @@ const char *luaO_pushvfstring (lua_State *L, const char *fmt, va_list argp) { break; } case 'p': { - char buff[4*sizeof(void *) + 8]; /* should be enough space for a `%p' */ + char buff[4*sizeof(void *) + 8]; /* should be enough space for a '%p' */ int l = sprintf(buff, "%p", va_arg(argp, void *)); pushstr(L, buff, l); break; diff --git a/src/lobject.h b/src/lobject.h index 054df783..abe6e7af 100644 --- a/src/lobject.h +++ b/src/lobject.h @@ -1,5 +1,5 @@ /* -** $Id: lobject.h,v 2.103 2014/10/01 11:52:33 roberto Exp $ +** $Id: lobject.h,v 2.104 2014/10/25 11:50:46 roberto Exp $ ** Type definitions for Lua objects ** See Copyright Notice in lua.h */ @@ -345,7 +345,7 @@ typedef struct Udata { ** Ensures that address after this type is always fully aligned. */ typedef union UUdata { - L_Umaxalign dummy; /* ensures maximum alignment for `local' udata */ + L_Umaxalign dummy; /* ensures maximum alignment for 'local' udata */ Udata uv; } UUdata; @@ -399,10 +399,10 @@ typedef struct Proto { lu_byte is_vararg; lu_byte maxstacksize; /* maximum stack used by this function */ int sizeupvalues; /* size of 'upvalues' */ - int sizek; /* size of `k' */ + int sizek; /* size of 'k' */ int sizecode; int sizelineinfo; - int sizep; /* size of `p' */ + int sizep; /* size of 'p' */ int sizelocvars; int linedefined; int lastlinedefined; @@ -486,8 +486,8 @@ typedef struct Node { typedef struct Table { CommonHeader; lu_byte flags; /* 1<<p means tagmethod(p) is not present */ - lu_byte lsizenode; /* log2 of size of `node' array */ - unsigned int sizearray; /* size of `array' array */ + lu_byte lsizenode; /* log2 of size of 'node' array */ + unsigned int sizearray; /* size of 'array' array */ TValue *array; /* array part */ Node *node; Node *lastfree; /* any free position is before this position */ @@ -498,7 +498,7 @@ typedef struct Table { /* -** `module' operation for hashing (size is always a power of 2) +** 'module' operation for hashing (size is always a power of 2) */ #define lmod(s,size) \ (check_exp((size&(size-1))==0, (cast(int, (s) & ((size)-1))))) diff --git a/src/lopcodes.c b/src/lopcodes.c index 973e705d..8e2e6da3 100644 --- a/src/lopcodes.c +++ b/src/lopcodes.c @@ -1,13 +1,14 @@ /* -** $Id: lopcodes.c,v 1.53 2013/12/30 20:47:58 roberto Exp $ +** $Id: lopcodes.c,v 1.54 2014/11/02 19:19:04 roberto Exp $ ** Opcodes for Lua virtual machine ** See Copyright Notice in lua.h */ - #define lopcodes_c #define LUA_CORE +#include "lprefix.h" + #include "lopcodes.h" diff --git a/src/lopcodes.h b/src/lopcodes.h index eb6c2a0d..864b8e4b 100644 --- a/src/lopcodes.h +++ b/src/lopcodes.h @@ -1,5 +1,5 @@ /* -** $Id: lopcodes.h,v 1.147 2014/10/20 18:29:55 roberto Exp $ +** $Id: lopcodes.h,v 1.148 2014/10/25 11:50:46 roberto Exp $ ** Opcodes for Lua virtual machine ** See Copyright Notice in lua.h */ @@ -14,12 +14,12 @@ We assume that instructions are unsigned numbers. All instructions have an opcode in the first 6 bits. Instructions can have the following fields: - `A' : 8 bits - `B' : 9 bits - `C' : 9 bits + 'A' : 8 bits + 'B' : 9 bits + 'C' : 9 bits 'Ax' : 26 bits ('A', 'B', and 'C' together) - `Bx' : 18 bits (`B' and `C' together) - `sBx' : signed Bx + 'Bx' : 18 bits ('B' and 'C' together) + 'sBx' : signed Bx A signed argument is represented in excess K; that is, the number value is the unsigned value minus K. K is exactly the maximum value @@ -58,7 +58,7 @@ enum OpMode {iABC, iABx, iAsBx, iAx}; /* basic instruction format */ */ #if SIZE_Bx < LUAI_BITSINT-1 #define MAXARG_Bx ((1<<SIZE_Bx)-1) -#define MAXARG_sBx (MAXARG_Bx>>1) /* `sBx' is signed */ +#define MAXARG_sBx (MAXARG_Bx>>1) /* 'sBx' is signed */ #else #define MAXARG_Bx MAX_INT #define MAXARG_sBx MAX_INT @@ -76,10 +76,10 @@ enum OpMode {iABC, iABx, iAsBx, iAx}; /* basic instruction format */ #define MAXARG_C ((1<<SIZE_C)-1) -/* creates a mask with `n' 1 bits at position `p' */ +/* creates a mask with 'n' 1 bits at position 'p' */ #define MASK1(n,p) ((~((~(Instruction)0)<<(n)))<<(p)) -/* creates a mask with `n' 0 bits at position `p' */ +/* creates a mask with 'n' 0 bits at position 'p' */ #define MASK0(n,p) (~MASK1(n,p)) /* @@ -238,16 +238,16 @@ OP_EXTRAARG/* Ax extra (larger) argument for previous opcode */ /*=========================================================================== Notes: - (*) In OP_CALL, if (B == 0) then B = top. If (C == 0), then `top' is + (*) In OP_CALL, if (B == 0) then B = top. If (C == 0), then 'top' is set to last_result+1, so next open instruction (OP_CALL, OP_RETURN, - OP_SETLIST) may use `top'. + OP_SETLIST) may use 'top'. (*) In OP_VARARG, if (B == 0) then use actual number of varargs and set top (like in OP_CALL with C == 0). - (*) In OP_RETURN, if (B == 0) then return up to `top'. + (*) In OP_RETURN, if (B == 0) then return up to 'top'. - (*) In OP_SETLIST, if (B == 0) then B = `top'; if (C == 0) then next + (*) In OP_SETLIST, if (B == 0) then B = 'top'; if (C == 0) then next 'instruction' is EXTRAARG(real C). (*) In OP_LOADKX, the next 'instruction' is always EXTRAARG. @@ -255,7 +255,7 @@ OP_EXTRAARG/* Ax extra (larger) argument for previous opcode */ (*) For comparisons, A specifies what condition the test should accept (true or false). - (*) All `skips' (pc++) assume that next instruction is a jump. + (*) All 'skips' (pc++) assume that next instruction is a jump. ===========================================================================*/ diff --git a/src/loslib.c b/src/loslib.c index c721e711..b72ce961 100644 --- a/src/loslib.c +++ b/src/loslib.c @@ -1,9 +1,14 @@ /* -** $Id: loslib.c,v 1.49 2014/10/17 16:28:21 roberto Exp $ +** $Id: loslib.c,v 1.53 2014/12/10 15:42:42 roberto Exp $ ** Standard Operating System library ** See Copyright Notice in lua.h */ +#define loslib_c +#define LUA_LIB + +#include "lprefix.h" + #include <errno.h> #include <locale.h> @@ -11,9 +16,6 @@ #include <string.h> #include <time.h> -#define loslib_c -#define LUA_LIB - #include "lua.h" #include "lauxlib.h" @@ -25,9 +27,9 @@ ** list of valid conversion specifiers for the 'strftime' function */ -#if !defined(LUA_USE_POSIX) +#if defined(LUA_USE_C89) #define LUA_STRFTIMEOPTIONS { "aAbBcdHIjmMpSUwWxXyYz%", "" } -#else +#else /* C99 specification */ #define LUA_STRFTIMEOPTIONS \ { "aAbBcCdDeFgGhHIjmMnprRStTuUVwWxXyYzZ%", "", \ "E", "cCxXyY", \ @@ -74,7 +76,7 @@ #else /* }{ */ -/* ANSI definitions */ +/* ISO C definitions */ #define LUA_TMPNAMBUFSIZE L_tmpnam #define lua_tmpnam(b,e) { e = (tmpnam(b) == NULL); } @@ -97,7 +99,7 @@ #else /* }{ */ -/* ANSI definitions */ +/* ISO C definitions */ #define l_gmtime(t,r) ((void)r, gmtime(t)) #define l_localtime(t,r) ((void)r, localtime(t)) @@ -227,7 +229,7 @@ static int os_date (lua_State *L) { struct tm tmr, *stm; if (*s == '!') { /* UTC? */ stm = l_gmtime(&t, &tmr); - s++; /* skip `!' */ + s++; /* skip '!' */ } else stm = l_localtime(&t, &tmr); diff --git a/src/lparser.c b/src/lparser.c index 2c009658..98b92c22 100644 --- a/src/lparser.c +++ b/src/lparser.c @@ -1,15 +1,17 @@ /* -** $Id: lparser.c,v 2.143 2014/10/17 16:28:21 roberto Exp $ +** $Id: lparser.c,v 2.146 2014/11/27 18:41:43 roberto Exp $ ** Lua Parser ** See Copyright Notice in lua.h */ - -#include <string.h> - #define lparser_c #define LUA_CORE +#include "lprefix.h" + + +#include <string.h> + #include "lua.h" #include "lcode.h" @@ -49,7 +51,7 @@ typedef struct BlockCnt { short firstgoto; /* index of first pending goto in this block */ lu_byte nactvar; /* # active locals outside the block */ lu_byte upval; /* true if some variable in the block is an upvalue */ - lu_byte isloop; /* true if `block' is a loop */ + lu_byte isloop; /* true if 'block' is a loop */ } BlockCnt; @@ -63,7 +65,7 @@ static void expr (LexState *ls, expdesc *v); /* semantic error */ static l_noret semerror (LexState *ls, const char *msg) { - ls->t.token = 0; /* remove 'near to' from final message */ + ls->t.token = 0; /* remove "near <token>" from final message */ luaX_syntaxerror(ls, msg); } @@ -406,7 +408,7 @@ static void findgotos (LexState *ls, Labeldesc *lb) { /* -** "export" pending gotos to outer level, to check them against +** export pending gotos to outer level, to check them against ** outer labels; if the block being exited has upvalues, and ** the goto exits the scope of any variable (which can be the ** upvalue), close those variables being exited. @@ -442,7 +444,7 @@ static void enterblock (FuncState *fs, BlockCnt *bl, lu_byte isloop) { /* -** create a label named "break" to resolve break statements +** create a label named 'break' to resolve break statements */ static void breaklabel (LexState *ls) { TString *n = luaS_new(ls->L, "break"); @@ -574,7 +576,7 @@ static void close_func (LexState *ls) { /* ** check whether current token is in the follow set of a block. ** 'until' closes syntactical blocks, but do not close scope, -** so it handled in separate. +** so it is handled in separate. */ static int block_follow (LexState *ls, int withuntil) { switch (ls->t.token) { @@ -588,7 +590,7 @@ static int block_follow (LexState *ls, int withuntil) { static void statlist (LexState *ls) { - /* statlist -> { stat [`;'] } */ + /* statlist -> { stat [';'] } */ while (!block_follow(ls, 1)) { if (ls->t.token == TK_RETURN) { statement(ls); @@ -629,14 +631,14 @@ static void yindex (LexState *ls, expdesc *v) { struct ConsControl { expdesc v; /* last list item read */ expdesc *t; /* table descriptor */ - int nh; /* total number of `record' elements */ + int nh; /* total number of 'record' elements */ int na; /* total number of array elements */ int tostore; /* number of array elements pending to be stored */ }; static void recfield (LexState *ls, struct ConsControl *cc) { - /* recfield -> (NAME | `['exp1`]') = exp1 */ + /* recfield -> (NAME | '['exp1']') = exp1 */ FuncState *fs = ls->fs; int reg = ls->fs->freereg; expdesc key, val; @@ -743,12 +745,12 @@ static void constructor (LexState *ls, expdesc *t) { static void parlist (LexState *ls) { - /* parlist -> [ param { `,' param } ] */ + /* parlist -> [ param { ',' param } ] */ FuncState *fs = ls->fs; Proto *f = fs->f; int nparams = 0; f->is_vararg = 0; - if (ls->t.token != ')') { /* is `parlist' not empty? */ + if (ls->t.token != ')') { /* is 'parlist' not empty? */ do { switch (ls->t.token) { case TK_NAME: { /* param -> NAME */ @@ -756,7 +758,7 @@ static void parlist (LexState *ls) { nparams++; break; } - case TK_DOTS: { /* param -> `...' */ + case TK_DOTS: { /* param -> '...' */ luaX_next(ls); f->is_vararg = 1; break; @@ -772,7 +774,7 @@ static void parlist (LexState *ls) { static void body (LexState *ls, expdesc *e, int ismethod, int line) { - /* body -> `(' parlist `)' block END */ + /* body -> '(' parlist ')' block END */ FuncState new_fs; BlockCnt bl; new_fs.f = addprototype(ls); @@ -794,7 +796,7 @@ static void body (LexState *ls, expdesc *e, int ismethod, int line) { static int explist (LexState *ls, expdesc *v) { - /* explist -> expr { `,' expr } */ + /* explist -> expr { ',' expr } */ int n = 1; /* at least one expression */ expr(ls, v); while (testnext(ls, ',')) { @@ -811,7 +813,7 @@ static void funcargs (LexState *ls, expdesc *f, int line) { expdesc args; int base, nparams; switch (ls->t.token) { - case '(': { /* funcargs -> `(' [ explist ] `)' */ + case '(': { /* funcargs -> '(' [ explist ] ')' */ luaX_next(ls); if (ls->t.token == ')') /* arg list is empty? */ args.k = VVOID; @@ -828,7 +830,7 @@ static void funcargs (LexState *ls, expdesc *f, int line) { } case TK_STRING: { /* funcargs -> STRING */ codestring(ls, &args, ls->t.seminfo.ts); - luaX_next(ls); /* must use `seminfo' before `next' */ + luaX_next(ls); /* must use 'seminfo' before 'next' */ break; } default: { @@ -894,14 +896,14 @@ static void suffixedexp (LexState *ls, expdesc *v) { fieldsel(ls, v); break; } - case '[': { /* `[' exp1 `]' */ + case '[': { /* '[' exp1 ']' */ expdesc key; luaK_exp2anyregup(fs, v); yindex(ls, &key); luaK_indexed(fs, v, &key); break; } - case ':': { /* `:' NAME funcargs */ + case ':': { /* ':' NAME funcargs */ expdesc key; luaX_next(ls); checkname(ls, &key); @@ -1035,7 +1037,7 @@ static const struct { /* ** subexpr -> (simpleexp | unop subexpr) { binop subexpr } -** where `binop' is any binary operator with a priority higher than `limit' +** where 'binop' is any binary operator with a priority higher than 'limit' */ static BinOpr subexpr (LexState *ls, expdesc *v, int limit) { BinOpr op; @@ -1049,7 +1051,7 @@ static BinOpr subexpr (LexState *ls, expdesc *v, int limit) { luaK_prefix(ls->fs, uop, v, line); } else simpleexp(ls, v); - /* expand while operators have priorities higher than `limit' */ + /* expand while operators have priorities higher than 'limit' */ op = getbinopr(ls->t.token); while (op != OPR_NOBINOPR && priority[op].left > limit) { expdesc v2; @@ -1149,7 +1151,7 @@ static void assignment (LexState *ls, struct LHS_assign *lh, int nvars) { "C levels"); assignment(ls, &nv, nvars+1); } - else { /* assignment -> `=' explist */ + else { /* assignment -> '=' explist */ int nexps; checknext(ls, '='); nexps = explist(ls, &e); @@ -1173,7 +1175,7 @@ static int cond (LexState *ls) { /* cond -> exp */ expdesc v; expr(ls, &v); /* read condition */ - if (v.k == VNIL) v.k = VFALSE; /* `falses' are all equal here */ + if (v.k == VNIL) v.k = VFALSE; /* 'falses' are all equal here */ luaK_goiftrue(ls->fs, &v); return v.f; } @@ -1362,7 +1364,7 @@ static void forstat (LexState *ls, int line) { TString *varname; BlockCnt bl; enterblock(fs, &bl, 1); /* scope for loop and control variables */ - luaX_next(ls); /* skip `for' */ + luaX_next(ls); /* skip 'for' */ varname = str_checkname(ls); /* first variable name */ switch (ls->t.token) { case '=': fornum(ls, varname, line); break; @@ -1370,7 +1372,7 @@ static void forstat (LexState *ls, int line) { default: luaX_syntaxerror(ls, "'=' or 'in' expected"); } check_match(ls, TK_END, TK_FOR, line); - leaveblock(fs); /* loop scope (`break' jumps to this point) */ + leaveblock(fs); /* loop scope ('break' jumps to this point) */ } @@ -1400,7 +1402,7 @@ static void test_then_block (LexState *ls, int *escapelist) { enterblock(fs, &bl, 0); jf = v.f; } - statlist(ls); /* `then' part */ + statlist(ls); /* 'then' part */ leaveblock(fs); if (ls->t.token == TK_ELSE || ls->t.token == TK_ELSEIF) /* followed by 'else'/'elseif'? */ @@ -1417,7 +1419,7 @@ static void ifstat (LexState *ls, int line) { while (ls->t.token == TK_ELSEIF) test_then_block(ls, &escapelist); /* ELSEIF cond THEN block */ if (testnext(ls, TK_ELSE)) - block(ls); /* `else' part */ + block(ls); /* 'else' part */ check_match(ls, TK_END, TK_IF, line); luaK_patchtohere(fs, escapelist); /* patch escape list to 'if' end */ } @@ -1435,7 +1437,7 @@ static void localfunc (LexState *ls) { static void localstat (LexState *ls) { - /* stat -> LOCAL NAME {`,' NAME} [`=' explist] */ + /* stat -> LOCAL NAME {',' NAME} ['=' explist] */ int nvars = 0; int nexps; expdesc e; @@ -1455,7 +1457,7 @@ static void localstat (LexState *ls) { static int funcname (LexState *ls, expdesc *v) { - /* funcname -> NAME {fieldsel} [`:' NAME] */ + /* funcname -> NAME {fieldsel} [':' NAME] */ int ismethod = 0; singlevar(ls, v); while (ls->t.token == '.') @@ -1476,7 +1478,7 @@ static void funcstat (LexState *ls, int line) { ismethod = funcname(ls, &v); body(ls, &b, ismethod, line); luaK_storevar(ls->fs, &v, &b); - luaK_fixline(ls->fs, line); /* definition `happens' in the first line */ + luaK_fixline(ls->fs, line); /* definition "happens" in the first line */ } @@ -1518,8 +1520,8 @@ static void retstat (LexState *ls) { if (nret == 1) /* only one single value? */ first = luaK_exp2anyreg(fs, &e); else { - luaK_exp2nextreg(fs, &e); /* values must go to the `stack' */ - first = fs->nactvar; /* return all `active' values */ + luaK_exp2nextreg(fs, &e); /* values must go to the stack */ + first = fs->nactvar; /* return all active values */ lua_assert(nret == fs->freereg - first); } } @@ -1630,7 +1632,7 @@ LClosure *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff, incr_top(L); funcstate.f = cl->p = luaF_newproto(L); funcstate.f->source = luaS_new(L, name); /* create and anchor TString */ - luaC_objbarrier(L, funcstate.f, funcstate.f->source); + lua_assert(iswhite(funcstate.f)); /* do not need barrier here */ lexstate.buff = buff; lexstate.dyd = dyd; dyd->actvar.n = dyd->gt.n = dyd->label.n = 0; diff --git a/src/lparser.h b/src/lparser.h index efceb054..62c50cac 100644 --- a/src/lparser.h +++ b/src/lparser.h @@ -1,5 +1,5 @@ /* -** $Id: lparser.h,v 1.73 2014/06/19 18:27:20 roberto Exp $ +** $Id: lparser.h,v 1.74 2014/10/25 11:50:46 roberto Exp $ ** Lua Parser ** See Copyright Notice in lua.h */ @@ -21,7 +21,7 @@ typedef enum { VNIL, VTRUE, VFALSE, - VK, /* info = index of constant in `k' */ + VK, /* info = index of constant in 'k' */ VKFLT, /* nval = numerical float value */ VKINT, /* nval = numerical integer value */ VNONRELOC, /* info = result register */ @@ -50,8 +50,8 @@ typedef struct expdesc { lua_Number nval; /* for VKFLT */ lua_Integer ival; /* for VKINT */ } u; - int t; /* patch list of `exit when true' */ - int f; /* patch list of `exit when false' */ + int t; /* patch list of 'exit when true' */ + int f; /* patch list of 'exit when false' */ } expdesc; @@ -100,11 +100,11 @@ typedef struct FuncState { struct FuncState *prev; /* enclosing function */ struct LexState *ls; /* lexical state */ struct BlockCnt *bl; /* chain of current blocks */ - int pc; /* next position to code (equivalent to `ncode') */ + int pc; /* next position to code (equivalent to 'ncode') */ int lasttarget; /* 'label' of last 'jump label' */ - int jpc; /* list of pending jumps to `pc' */ - int nk; /* number of elements in `k' */ - int np; /* number of elements in `p' */ + int jpc; /* list of pending jumps to 'pc' */ + int nk; /* number of elements in 'k' */ + int np; /* number of elements in 'p' */ int firstlocal; /* index of first local var (in Dyndata array) */ short nlocvars; /* number of elements in 'f->locvars' */ lu_byte nactvar; /* number of active local variables */ diff --git a/src/lprefix.h b/src/lprefix.h new file mode 100644 index 00000000..c2a78cd7 --- /dev/null +++ b/src/lprefix.h @@ -0,0 +1,39 @@ +/* +** $Id: lprefix.h,v 1.1 2014/11/03 15:12:44 roberto Exp $ +** Definitions for Lua code that must come before any other header file +** See Copyright Notice in lua.h +*/ + +#ifndef lprefix_h +#define lprefix_h + + +/* +** Allows POSIX/XSI stuff +*/ +#if !defined(_XOPEN_SOURCE) +#define _XOPEN_SOURCE 600 +#endif + +/* +** Allows manipulation of large files in gcc and some other compilers +*/ +#if !defined(_FILE_OFFSET_BITS) +#define _LARGEFILE_SOURCE 1 +#define _FILE_OFFSET_BITS 64 +#endif + + +/* +** Windows stuff +*/ +#if defined(_WIN32) /* { */ + +#if !defined(_CRT_SECURE_NO_WARNINGS) +#define _CRT_SECURE_NO_WARNINGS /* avoid warnings about ISO C functions */ +#endif + +#endif /* } */ + +#endif + diff --git a/src/lstate.c b/src/lstate.c index 295fc4c7..ff6b02d3 100644 --- a/src/lstate.c +++ b/src/lstate.c @@ -1,16 +1,18 @@ /* -** $Id: lstate.c,v 2.125 2014/07/24 16:17:56 roberto Exp $ +** $Id: lstate.c,v 2.127 2014/11/02 19:33:33 roberto Exp $ ** Global State ** See Copyright Notice in lua.h */ +#define lstate_c +#define LUA_CORE + +#include "lprefix.h" + #include <stddef.h> #include <string.h> -#define lstate_c -#define LUA_CORE - #include "lua.h" #include "lapi.h" @@ -72,9 +74,8 @@ typedef struct LG { /* -** Compute an initial seed as random as possible. In ANSI, rely on -** Address Space Layout Randomization (if present) to increase -** randomness.. +** Compute an initial seed as random as possible. Rely on Address Space +** Layout Randomization (if present) to increase randomness.. */ #define addbuff(b,p,e) \ { size_t t = cast(size_t, e); \ diff --git a/src/lstate.h b/src/lstate.h index 3ecd4977..81e12c40 100644 --- a/src/lstate.h +++ b/src/lstate.h @@ -1,5 +1,5 @@ /* -** $Id: lstate.h,v 2.117 2014/10/07 18:29:13 roberto Exp $ +** $Id: lstate.h,v 2.119 2014/10/30 18:53:28 roberto Exp $ ** Global State ** See Copyright Notice in lua.h */ @@ -21,10 +21,10 @@ ** belong to one (and only one) of these lists, using field 'next' of ** the 'CommonHeader' for the link: ** -** allgc: all objects not marked for finalization; -** finobj: all objects marked for finalization; -** tobefnz: all objects ready to be finalized; -** fixedgc: all objects that are not to be collected (currently +** 'allgc': all objects not marked for finalization; +** 'finobj': all objects marked for finalization; +** 'tobefnz': all objects ready to be finalized; +** 'fixedgc': all objects that are not to be collected (currently ** only small strings, such as reserved words). */ @@ -103,11 +103,11 @@ typedef struct CallInfo { /* -** `global state', shared by all threads of this state +** 'global state', shared by all threads of this state */ typedef struct global_State { lua_Alloc frealloc; /* function to reallocate memory */ - void *ud; /* auxiliary data to `frealloc' */ + void *ud; /* auxiliary data to 'frealloc' */ lu_mem totalbytes; /* number of bytes currently allocated - GCdebt */ l_mem GCdebt; /* bytes allocated not yet compensated by the collector */ lu_mem GCmemtrav; /* memory traversed by the GC */ @@ -133,7 +133,7 @@ typedef struct global_State { Mbuffer buff; /* temporary buffer for string concatenation */ unsigned int gcfinnum; /* number of finalizers to call in each GC step */ int gcpause; /* size of pause between successive GCs */ - int gcstepmul; /* GC `granularity' */ + int gcstepmul; /* GC 'granularity' */ lua_CFunction panic; /* to be called in unprotected errors */ struct lua_State *mainthread; const lua_Number *version; /* pointer to version number */ @@ -144,7 +144,7 @@ typedef struct global_State { /* -** `per thread' state +** 'per thread' state */ struct lua_State { CommonHeader; diff --git a/src/lstring.c b/src/lstring.c index df28a7f2..2947113c 100644 --- a/src/lstring.c +++ b/src/lstring.c @@ -1,15 +1,17 @@ /* -** $Id: lstring.c,v 2.44 2014/07/21 16:02:10 roberto Exp $ +** $Id: lstring.c,v 2.45 2014/11/02 19:19:04 roberto Exp $ ** String table (keeps all strings handled by Lua) ** See Copyright Notice in lua.h */ - -#include <string.h> - #define lstring_c #define LUA_CORE +#include "lprefix.h" + + +#include <string.h> + #include "lua.h" #include "ldebug.h" diff --git a/src/lstrlib.c b/src/lstrlib.c index 748e2a81..a650b768 100644 --- a/src/lstrlib.c +++ b/src/lstrlib.c @@ -1,9 +1,14 @@ /* -** $Id: lstrlib.c,v 1.205 2014/10/20 16:44:54 roberto Exp $ +** $Id: lstrlib.c,v 1.221 2014/12/11 14:03:07 roberto Exp $ ** Standard library for string operations and pattern-matching ** See Copyright Notice in lua.h */ +#define lstrlib_c +#define LUA_LIB + +#include "lprefix.h" + #include <ctype.h> #include <limits.h> @@ -12,9 +17,6 @@ #include <stdlib.h> #include <string.h> -#define lstrlib_c -#define LUA_LIB - #include "lua.h" #include "lauxlib.h" @@ -30,10 +32,19 @@ #endif -/* macro to `unsign' a character */ +/* macro to 'unsign' a character */ #define uchar(c) ((unsigned char)(c)) +/* +** Some sizes are better limited to fit in 'int', but must also fit in +** 'size_t'. (We assume that 'lua_Integer' cannot be smaller than 'int'.) +*/ +#define MAXSIZE \ + (sizeof(size_t) < sizeof(int) ? (~(size_t)0) : (size_t)(INT_MAX)) + + + static int str_len (lua_State *L) { size_t l; @@ -103,13 +114,6 @@ static int str_upper (lua_State *L) { } -/* reasonable limit to avoid arithmetic overflow and strings too big */ -#if LUA_MAXINTEGER / 2 <= 0x10000000 -#define MAXSIZE ((size_t)(LUA_MAXINTEGER / 2)) -#else -#define MAXSIZE ((size_t)0x10000000) -#endif - static int str_rep (lua_State *L) { size_t l, lsep; const char *s = luaL_checklstring(L, 1, &l); @@ -255,11 +259,11 @@ static const char *classend (MatchState *ms, const char *p) { } case '[': { if (*p == '^') p++; - do { /* look for a `]' */ + do { /* look for a ']' */ if (p == ms->p_end) luaL_error(ms->L, "malformed pattern (missing ']')"); if (*(p++) == L_ESC && p < ms->p_end) - p++; /* skip escapes (e.g. `%]') */ + p++; /* skip escapes (e.g. '%]') */ } while (*p != ']'); return p+1; } @@ -294,7 +298,7 @@ static int matchbracketclass (int c, const char *p, const char *ec) { int sig = 1; if (*(p+1) == '^') { sig = 0; - p++; /* skip the `^' */ + p++; /* skip the '^' */ } while (++p < ec) { if (*p == L_ESC) { @@ -431,7 +435,7 @@ static const char *match (MatchState *ms, const char *s, const char *p) { break; } case '$': { - if ((p + 1) != ms->p_end) /* is the `$' the last char in pattern? */ + if ((p + 1) != ms->p_end) /* is the '$' the last char in pattern? */ goto dflt; /* no; go to default */ s = (s == ms->src_end) ? s : NULL; /* check end of string */ break; @@ -519,16 +523,16 @@ static const char *match (MatchState *ms, const char *s, const char *p) { static const char *lmemfind (const char *s1, size_t l1, const char *s2, size_t l2) { if (l2 == 0) return s1; /* empty strings are everywhere */ - else if (l2 > l1) return NULL; /* avoids a negative `l1' */ + else if (l2 > l1) return NULL; /* avoids a negative 'l1' */ else { - const char *init; /* to search for a `*s2' inside `s1' */ - l2--; /* 1st char will be checked by `memchr' */ - l1 = l1-l2; /* `s2' cannot be found after that */ + const char *init; /* to search for a '*s2' inside 's1' */ + l2--; /* 1st char will be checked by 'memchr' */ + l1 = l1-l2; /* 's2' cannot be found after that */ while (l1 > 0 && (init = (const char *)memchr(s1, *s2, l1)) != NULL) { init++; /* 1st char is already checked */ if (memcmp(init, s2+1, l2) == 0) return init-1; - else { /* correct `l1' and `s1' to try again */ + else { /* correct 'l1' and 's1' to try again */ l1 -= init-s1; s1 = init; } @@ -544,7 +548,7 @@ static void push_onecapture (MatchState *ms, int i, const char *s, if (i == 0) /* ms->level == 0, too */ lua_pushlstring(ms->L, s, e - s); /* add whole match */ else - luaL_error(ms->L, "invalid capture index"); + luaL_error(ms->L, "invalid capture index %%%d", i + 1); } else { ptrdiff_t l = ms->capture[i].len; @@ -879,7 +883,7 @@ static int str_format (lua_State *L) { else if (*++strfrmt == L_ESC) luaL_addchar(&b, *strfrmt++); /* %% */ else { /* format item */ - char form[MAX_FORMAT]; /* to store the format (`%...') */ + char form[MAX_FORMAT]; /* to store the format ('%...') */ char *buff = luaL_prepbuffsize(&b, MAX_ITEM); /* to put formatted item */ int nb = 0; /* number of bytes in added item */ if (++arg > top) @@ -897,10 +901,10 @@ static int str_format (lua_State *L) { nb = sprintf(buff, form, n); break; } - case 'e': case 'E': case 'f': #if defined(LUA_USE_AFORMAT) case 'a': case 'A': #endif + case 'e': case 'E': case 'f': case 'g': case 'G': { addlenmod(form, LUA_NUMBER_FRMLEN); nb = sprintf(buff, form, luaL_checknumber(L, arg)); @@ -925,7 +929,7 @@ static int str_format (lua_State *L) { break; } } - default: { /* also treat cases `pnLlh' */ + default: { /* also treat cases 'pnLlh' */ return luaL_error(L, "invalid option '%%%c' to 'format'", *(strfrmt - 1)); } @@ -947,6 +951,11 @@ static int str_format (lua_State *L) { */ +/* value used for padding */ +#if !defined(LUA_PACKPADBYTE) +#define LUA_PACKPADBYTE 0x00 +#endif + /* maximum size for the binary representation of an integer */ #define MAXINTSIZE 16 @@ -959,9 +968,6 @@ static int str_format (lua_State *L) { /* size of a lua_Integer */ #define SZINT ((int)sizeof(lua_Integer)) -/* mask for all ones in last byte in a lua Integer */ -#define HIGHERBYTE ((lua_Unsigned)MC << (NB * (SZINT - 1))) - /* dummy union to get native endianness */ static const union { @@ -1012,8 +1018,7 @@ typedef enum KOption { Kzstr, /* zero-terminated strings */ Kpadding, /* padding */ Kpaddalign, /* padding for alignment */ - Knop, /* no-op (configuration or spaces) */ - Keof /* end of format */ + Knop /* no-op (configuration or spaces) */ } KOption; @@ -1029,8 +1034,8 @@ static int getnum (const char **fmt, int df) { else { int a = 0; do { - a = a*10 + *((*fmt)++) - '0'; - } while (digit(**fmt) && a < (INT_MAX/10 - 10)); + a = a*10 + (*((*fmt)++) - '0'); + } while (digit(**fmt) && a <= ((int)MAXSIZE - 9)/10); return a; } } @@ -1043,7 +1048,8 @@ static int getnum (const char **fmt, int df) { static int getnumlimit (Header *h, const char **fmt, int df) { int sz = getnum(fmt, df); if (sz > MAXINTSIZE || sz <= 0) - luaL_error(h->L, "integral size (%d) out of limits [1,%d]", sz, MAXINTSIZE); + luaL_error(h->L, "integral size (%d) out of limits [1,%d]", + sz, MAXINTSIZE); return sz; } @@ -1080,20 +1086,22 @@ static KOption getoption (Header *h, const char **fmt, int *size) { case 'i': *size = getnumlimit(h, fmt, sizeof(int)); return Kint; case 'I': *size = getnumlimit(h, fmt, sizeof(int)); return Kuint; case 's': *size = getnumlimit(h, fmt, sizeof(size_t)); return Kstring; - case 'c': *size = getnum(fmt, 1); return Kchar; + case 'c': + *size = getnum(fmt, -1); + if (*size == -1) + luaL_error(h->L, "missing size for format option 'c'"); + return Kchar; case 'z': return Kzstr; case 'x': *size = 1; return Kpadding; case 'X': return Kpaddalign; - case ' ': return Knop; - case '\0': return Keof; - case '<': h->islittle = 1; return Knop; - case '>': h->islittle = 0; return Knop; - case '!': h->maxalign = getnumlimit(h, fmt, MAXALIGN); return Knop; - default: { - luaL_error(h->L, "invalid format option '%c'", opt); - return Knop; - } + case ' ': break; + case '<': h->islittle = 1; break; + case '>': h->islittle = 0; break; + case '=': h->islittle = nativeendian.little; break; + case '!': h->maxalign = getnumlimit(h, fmt, MAXALIGN); break; + default: luaL_error(h->L, "invalid format option '%c'", opt); } + return Knop; } @@ -1103,19 +1111,15 @@ static KOption getoption (Header *h, const char **fmt, int *size) { ** alignment requirements. ** Local variable 'size' gets the size to be aligned. (Kpadal option ** always gets its full alignment, other options are limited by -** the maximum alignment ('maxalign). Kchar option needs no aligment +** the maximum alignment ('maxalign'). Kchar option needs no alignment ** despite its size. */ static KOption getdetails (Header *h, size_t totalsize, const char **fmt, int *psize, int *ntoalign) { - int align; - KOption opt; - do { - opt = getoption(h, fmt, psize); - } while (opt == Knop); /* skip no-op options */ - align = *psize; /* usually, alignment follows size */ + KOption opt = getoption(h, fmt, psize); + int align = *psize; /* usually, alignment follows size */ if (opt == Kpaddalign) { /* 'X' gets alignment from following option */ - if (getoption(h, fmt, &align) == Kchar || align == 0) + if (**fmt == '\0' || getoption(h, fmt, &align) == Kchar || align == 0) luaL_argerror(h->L, 1, "invalid next option for option 'X'"); } if (align <= 1 || opt == Kchar) /* need no alignment? */ @@ -1131,15 +1135,25 @@ static KOption getdetails (Header *h, size_t totalsize, } +/* +** Pack integer 'n' with 'size' bytes and 'islittle' endianness. +** The final 'if' handles the case when 'size' is larger than +** the size of a Lua integer, correcting the extra sign-extension +** bytes if necessary (by default they would be zeros). +*/ static void packint (luaL_Buffer *b, lua_Unsigned n, - int islittle, int size, lua_Unsigned mask) { + int islittle, int size, int neg) { char *buff = luaL_prepbuffsize(b, size); int i; - for (i = 0; i < size - 1; i++) { - buff[islittle ? i : size - 1 - i] = (n & MC); - n = (n >> NB) | mask; + buff[islittle ? 0 : size - 1] = (char)(n & MC); /* first byte */ + for (i = 1; i < size; i++) { + n >>= NB; + buff[islittle ? i : size - 1 - i] = (char)(n & MC); + } + if (neg && size > SZINT) { /* negative number need sign extension? */ + for (i = SZINT; i < size; i++) /* correct extra bytes */ + buff[islittle ? i : size - 1 - i] = (char)MC; } - buff[islittle ? i : size - 1 - i] = (n & MC); luaL_addsize(b, size); /* add result to buffer */ } @@ -1171,21 +1185,21 @@ static int str_pack (lua_State *L) { initheader(L, &h); lua_pushnil(L); /* mark to separate arguments from string buffer */ luaL_buffinit(L, &b); - for (;;) { + while (*fmt != '\0') { int size, ntoalign; KOption opt = getdetails(&h, totalsize, &fmt, &size, &ntoalign); totalsize += ntoalign + size; - while (ntoalign-- > 0) luaL_addchar(&b, '\0'); /* fill alignment */ + while (ntoalign-- > 0) + luaL_addchar(&b, LUA_PACKPADBYTE); /* fill alignment */ arg++; switch (opt) { case Kint: { /* signed integers */ lua_Integer n = luaL_checkinteger(L, arg); - lua_Unsigned mask = (n < 0) ? HIGHERBYTE : 0; /* sign extension */ if (size < SZINT) { /* need overflow check? */ lua_Integer lim = (lua_Integer)1 << ((size * NB) - 1); luaL_argcheck(L, -lim <= n && n < lim, arg, "integer overflow"); } - packint(&b, (lua_Unsigned)n, h.islittle, size, mask); + packint(&b, (lua_Unsigned)n, h.islittle, size, (n < 0)); break; } case Kuint: { /* unsigned integers */ @@ -1235,18 +1249,50 @@ static int str_pack (lua_State *L) { totalsize += len + 1; break; } - case Kpadding: luaL_addchar(&b, '\0'); /* go through */ + case Kpadding: luaL_addchar(&b, LUA_PACKPADBYTE); /* go through */ case Kpaddalign: case Knop: arg--; /* undo increment */ break; - case Keof: /* end of format */ - luaL_pushresult(&b); - return 1; } } + luaL_pushresult(&b); + return 1; +} + + +static int str_packsize (lua_State *L) { + Header h; + const char *fmt = luaL_checkstring(L, 1); /* format string */ + size_t totalsize = 0; /* accumulate total size of result */ + initheader(L, &h); + while (*fmt != '\0') { + int size, ntoalign; + KOption opt = getdetails(&h, totalsize, &fmt, &size, &ntoalign); + size += ntoalign; /* total space used by option */ + luaL_argcheck(L, totalsize <= MAXSIZE - size, 1, + "format result too large"); + totalsize += size; + switch (opt) { + case Kstring: /* strings with length count */ + case Kzstr: /* zero-terminated string */ + luaL_argerror(L, 1, "variable-length format"); + break; + default: break; + } + } + lua_pushinteger(L, (lua_Integer)totalsize); + return 1; } +/* +** Unpack an integer with 'size' bytes and 'islittle' endianness. +** If size is smaller than the size of a Lua integer and integer +** is signed, must do sign extension (propagating the sign to the +** higher bits); if size is larger than the size of a Lua integer, +** it must check the unread bytes to see whether they do not cause an +** overflow. +*/ static lua_Integer unpackint (lua_State *L, const char *str, int islittle, int size, int issigned) { lua_Unsigned res = 0; @@ -1262,11 +1308,11 @@ static lua_Integer unpackint (lua_State *L, const char *str, res = ((res ^ mask) - mask); /* do sign extension */ } } - else { /* must check unread bytes */ + else if (size > SZINT) { /* must check unread bytes */ int mask = (!issigned || (lua_Integer)res >= 0) ? 0 : MC; for (i = limit; i < size; i++) { if ((unsigned char)str[islittle ? i : size - 1 - i] != mask) - luaL_error(L, "%d-bit integer does not fit into Lua Integer", size); + luaL_error(L, "%d-byte integer does not fit into Lua Integer", size); } } return (lua_Integer)res; @@ -1282,12 +1328,12 @@ static int str_unpack (lua_State *L) { int n = 0; /* number of results */ luaL_argcheck(L, pos <= ld, 3, "initial position out of string"); initheader(L, &h); - for (;;) { + while (*fmt != '\0') { int size, ntoalign; KOption opt = getdetails(&h, pos, &fmt, &size, &ntoalign); if ((size_t)ntoalign + size > ~pos || pos + ntoalign + size > ld) luaL_argerror(L, 2, "data string too short"); - pos += ntoalign; + pos += ntoalign; /* skip alignment */ /* stack space for item + next position */ luaL_checkstack(L, 2, "too many results"); n++; @@ -1317,24 +1363,23 @@ static int str_unpack (lua_State *L) { size_t len = (size_t)unpackint(L, data + pos, h.islittle, size, 0); luaL_argcheck(L, pos + len + size <= ld, 2, "data string too short"); lua_pushlstring(L, data + pos + size, len); - pos += len; + pos += len; /* skip string */ break; } case Kzstr: { size_t len = (int)strlen(data + pos); lua_pushlstring(L, data + pos, len); - pos += len + 1; /* skip final '\0' */ + pos += len + 1; /* skip string plus final '\0' */ break; } case Kpaddalign: case Kpadding: case Knop: n--; /* undo increment */ break; - case Keof: /* end of format */ - lua_pushinteger(L, pos + 1); /* next position */ - return n; } pos += size; } + lua_pushinteger(L, pos + 1); /* next position */ + return n + 1; } /* }====================================================== */ @@ -1356,6 +1401,7 @@ static const luaL_Reg strlib[] = { {"sub", str_sub}, {"upper", str_upper}, {"pack", str_pack}, + {"packsize", str_packsize}, {"unpack", str_unpack}, {NULL, NULL} }; diff --git a/src/ltable.c b/src/ltable.c index f7b836d5..e8ef146c 100644 --- a/src/ltable.c +++ b/src/ltable.c @@ -1,19 +1,24 @@ /* -** $Id: ltable.c,v 2.96 2014/10/17 16:28:21 roberto Exp $ +** $Id: ltable.c,v 2.99 2014/11/02 19:19:04 roberto Exp $ ** Lua tables (hash) ** See Copyright Notice in lua.h */ +#define ltable_c +#define LUA_CORE + +#include "lprefix.h" + /* ** Implementation of tables (aka arrays, objects, or hash tables). ** Tables keep its elements in two parts: an array part and a hash part. ** Non-negative integer keys are all candidates to be kept in the array -** part. The actual size of the array is the largest `n' such that at +** part. The actual size of the array is the largest 'n' such that at ** least half the slots between 0 and n are in use. ** Hash uses a mix of chained scatter table with Brent's variation. ** A main invariant of these tables is that, if an element is not -** in its main position (i.e. the `original' position that its hash gives +** in its main position (i.e. the 'original' position that its hash gives ** to it), then the colliding element is in its own main position. ** Hence even when the load factor reaches 100%, performance remains good. */ @@ -23,9 +28,6 @@ #include <string.h> #include <limits.h> -#define ltable_c -#define LUA_CORE - #include "lua.h" #include "ldebug.h" @@ -88,7 +90,7 @@ static const Node dummynode_ = { */ static int numisinteger (lua_Number x, lua_Integer *p) { if ((x) == l_floor(x)) /* integral value? */ - return lua_numtointeger(x, p); /* try as an integer */ + return lua_numbertointeger(x, p); /* try as an integer */ else return 0; } @@ -111,7 +113,7 @@ static Node *hashfloat (const Table *t, lua_Number n) { /* -** returns the `main' position of an element in a table (that is, the index +** returns the 'main' position of an element in a table (that is, the index ** of its hash value) */ static Node *mainposition (const Table *t, const TValue *key) { @@ -143,7 +145,7 @@ static Node *mainposition (const Table *t, const TValue *key) { /* -** returns the index for `key' if `key' is an appropriate key to live in +** returns the index for 'key' if 'key' is an appropriate key to live in ** the array part of the table, 0 otherwise. */ static unsigned int arrayindex (const TValue *key) { @@ -152,12 +154,12 @@ static unsigned int arrayindex (const TValue *key) { if (0 < k && (lua_Unsigned)k <= MAXASIZE) return cast(unsigned int, k); /* 'key' is an appropriate array index */ } - return 0; /* `key' did not match some condition */ + return 0; /* 'key' did not match some condition */ } /* -** returns the index of a `key' for table traversals. First goes all +** returns the index of a 'key' for table traversals. First goes all ** elements in the array part, then elements in the hash part. The ** beginning of a traversal is signaled by 0. */ @@ -165,13 +167,13 @@ static unsigned int findindex (lua_State *L, Table *t, StkId key) { unsigned int i; if (ttisnil(key)) return 0; /* first iteration */ i = arrayindex(key); - if (i != 0 && i <= t->sizearray) /* is `key' inside array part? */ + if (i != 0 && i <= t->sizearray) /* is 'key' inside array part? */ return i; /* yes; that's the index */ else { int nx; Node *n = mainposition(t, key); - for (;;) { /* check whether `key' is somewhere in the chain */ - /* key may be dead already, but it is ok to use it in `next' */ + for (;;) { /* check whether 'key' is somewhere in the chain */ + /* key may be dead already, but it is ok to use it in 'next' */ if (luaV_rawequalobj(gkey(n), key) || (ttisdeadkey(gkey(n)) && iscollectable(key) && deadvalue(gkey(n)) == gcvalue(key))) { @@ -244,7 +246,7 @@ static unsigned int computesizes (unsigned int nums[], unsigned int *narray) { static int countint (const TValue *key, unsigned int *nums) { unsigned int k = arrayindex(key); - if (k != 0) { /* is `key' an appropriate array index? */ + if (k != 0) { /* is 'key' an appropriate array index? */ nums[luaO_ceillog2(k)]++; /* count as such */ return 1; } @@ -256,7 +258,7 @@ static int countint (const TValue *key, unsigned int *nums) { static unsigned int numusearray (const Table *t, unsigned int *nums) { int lg; unsigned int ttlg; /* 2^lg */ - unsigned int ause = 0; /* summation of `nums' */ + unsigned int ause = 0; /* summation of 'nums' */ unsigned int i = 1; /* count to traverse all array keys */ /* traverse each slice */ for (lg = 0, ttlg = 1; lg <= MAXABITS; lg++, ttlg *= 2) { @@ -308,7 +310,7 @@ static void setarrayvector (lua_State *L, Table *t, unsigned int size) { static void setnodevector (lua_State *L, Table *t, unsigned int size) { int lsize; if (size == 0) { /* no elements to hash part? */ - t->node = cast(Node *, dummynode); /* use common `dummynode' */ + t->node = cast(Node *, dummynode); /* use common 'dummynode' */ lsize = 0; } else { @@ -498,7 +500,7 @@ const TValue *luaH_getint (Table *t, lua_Integer key) { return &t->array[key - 1]; else { Node *n = hashint(t, key); - for (;;) { /* check whether `key' is somewhere in the chain */ + for (;;) { /* check whether 'key' is somewhere in the chain */ if (ttisinteger(gkey(n)) && ivalue(gkey(n)) == key) return gval(n); /* that's it */ else { @@ -518,7 +520,7 @@ const TValue *luaH_getint (Table *t, lua_Integer key) { const TValue *luaH_getstr (Table *t, TString *key) { Node *n = hashstr(t, key); lua_assert(key->tt == LUA_TSHRSTR); - for (;;) { /* check whether `key' is somewhere in the chain */ + for (;;) { /* check whether 'key' is somewhere in the chain */ const TValue *k = gkey(n); if (ttisshrstring(k) && eqshrstr(tsvalue(k), key)) return gval(n); /* that's it */ @@ -548,7 +550,7 @@ const TValue *luaH_get (Table *t, const TValue *key) { } default: { Node *n = mainposition(t, key); - for (;;) { /* check whether `key' is somewhere in the chain */ + for (;;) { /* check whether 'key' is somewhere in the chain */ if (luaV_rawequalobj(gkey(n), key)) return gval(n); /* that's it */ else { @@ -592,7 +594,7 @@ void luaH_setint (lua_State *L, Table *t, lua_Integer key, TValue *value) { static int unbound_search (Table *t, unsigned int j) { unsigned int i = j; /* i is zero or a present index */ j++; - /* find `i' and `j' such that i is present and j is not */ + /* find 'i' and 'j' such that i is present and j is not */ while (!ttisnil(luaH_getint(t, j))) { i = j; if (j > cast(unsigned int, MAX_INT)/2) { /* overflow? */ @@ -614,7 +616,7 @@ static int unbound_search (Table *t, unsigned int j) { /* -** Try to find a boundary in table `t'. A `boundary' is an integer index +** Try to find a boundary in table 't'. A 'boundary' is an integer index ** such that t[i] is non-nil and t[i+1] is nil (and 0 if t[1] is nil). */ int luaH_getn (Table *t) { diff --git a/src/ltablib.c b/src/ltablib.c index 908acfbc..8f78afb7 100644 --- a/src/ltablib.c +++ b/src/ltablib.c @@ -1,16 +1,18 @@ /* -** $Id: ltablib.c,v 1.77 2014/10/17 16:28:21 roberto Exp $ +** $Id: ltablib.c,v 1.79 2014/11/02 19:19:04 roberto Exp $ ** Library for Table Manipulation ** See Copyright Notice in lua.h */ +#define ltablib_c +#define LUA_LIB + +#include "lprefix.h" + #include <limits.h> #include <stddef.h> -#define ltablib_c -#define LUA_LIB - #include "lua.h" #include "lauxlib.h" @@ -225,7 +227,7 @@ static int unpack (lua_State *L) { /* ** {====================================================== ** Quicksort -** (based on `Algorithms in MODULA-3', Robert Sedgewick; +** (based on 'Algorithms in MODULA-3', Robert Sedgewick; ** Addison-Wesley, 1993.) ** ======================================================= */ @@ -241,7 +243,7 @@ static int sort_comp (lua_State *L, int a, int b) { int res; lua_pushvalue(L, 2); lua_pushvalue(L, a-1); /* -1 to compensate function */ - lua_pushvalue(L, b-2); /* -2 to compensate function and `a' */ + lua_pushvalue(L, b-2); /* -2 to compensate function and 'a' */ lua_call(L, 2, 1); res = lua_toboolean(L, -1); lua_pop(L, 1); @@ -1,15 +1,17 @@ /* -** $Id: ltm.c,v 2.29 2014/07/18 13:36:14 roberto Exp $ +** $Id: ltm.c,v 2.33 2014/11/21 12:15:57 roberto Exp $ ** Tag methods ** See Copyright Notice in lua.h */ - -#include <string.h> - #define ltm_c #define LUA_CORE +#include "lprefix.h" + + +#include <string.h> + #include "lua.h" #include "ldebug.h" @@ -84,7 +86,7 @@ const TValue *luaT_gettmbyobj (lua_State *L, const TValue *o, TMS event) { void luaT_callTM (lua_State *L, const TValue *f, const TValue *p1, const TValue *p2, TValue *p3, int hasres) { ptrdiff_t result = savestack(L, p3); - setobj2s(L, L->top++, f); /* push function */ + setobj2s(L, L->top++, f); /* push function (assume EXTRA_STACK) */ setobj2s(L, L->top++, p1); /* 1st argument */ setobj2s(L, L->top++, p2); /* 2nd argument */ if (!hasres) /* no result? 'p3' is third argument */ @@ -115,15 +117,17 @@ void luaT_trybinTM (lua_State *L, const TValue *p1, const TValue *p2, switch (event) { case TM_CONCAT: luaG_concaterror(L, p1, p2); - case TM_IDIV: case TM_BAND: case TM_BOR: case TM_BXOR: + case TM_BAND: case TM_BOR: case TM_BXOR: case TM_SHL: case TM_SHR: case TM_BNOT: { lua_Number dummy; if (tonumber(p1, &dummy) && tonumber(p2, &dummy)) luaG_tointerror(L, p1, p2); + else + luaG_opinterror(L, p1, p2, "perform bitwise operation on"); /* else go through */ } default: - luaG_aritherror(L, p1, p2); + luaG_opinterror(L, p1, p2, "perform arithmetic on"); } } } @@ -1,5 +1,5 @@ /* -** $Id: ltm.h,v 2.20 2014/06/10 18:53:18 roberto Exp $ +** $Id: ltm.h,v 2.21 2014/10/25 11:50:46 roberto Exp $ ** Tag methods ** See Copyright Notice in lua.h */ @@ -21,7 +21,7 @@ typedef enum { TM_GC, TM_MODE, TM_LEN, - TM_EQ, /* last tag method with `fast' access */ + TM_EQ, /* last tag method with fast access */ TM_ADD, TM_SUB, TM_MUL, @@ -1,17 +1,19 @@ /* -** $Id: lua.c,v 1.217 2014/10/20 22:21:05 roberto Exp $ +** $Id: lua.c,v 1.222 2014/11/11 19:41:27 roberto Exp $ ** Lua stand-alone interpreter ** See Copyright Notice in lua.h */ +#define lua_c + +#include "lprefix.h" + #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <string.h> -#define lua_c - #include "lua.h" #include "lauxlib.h" @@ -50,14 +52,14 @@ #include <unistd.h> #define lua_stdin_is_tty() isatty(0) -#elif defined(LUA_WIN) /* }{ */ +#elif defined(LUA_USE_WINDOWS) /* }{ */ #include <io.h> #define lua_stdin_is_tty() _isatty(_fileno(stdin)) #else /* }{ */ -/* ANSI definition */ +/* ISO C definition */ #define lua_stdin_is_tty() 1 /* assume stdin is a tty */ #endif /* } */ @@ -126,12 +128,12 @@ static void laction (int i) { static void print_usage (const char *badoption) { - luai_writestringerror("%s: ", progname); + lua_writestringerror("%s: ", progname); if (badoption[1] == 'e' || badoption[1] == 'l') - luai_writestringerror("'%s' needs argument\n", badoption); + lua_writestringerror("'%s' needs argument\n", badoption); else - luai_writestringerror("unrecognized option '%s'\n", badoption); - luai_writestringerror( + lua_writestringerror("unrecognized option '%s'\n", badoption); + lua_writestringerror( "usage: %s [options] [script [args]]\n" "Available options are:\n" " -e stat execute string 'stat'\n" @@ -151,8 +153,8 @@ static void print_usage (const char *badoption) { ** (if present) */ static void l_message (const char *pname, const char *msg) { - if (pname) luai_writestringerror("%s: ", pname); - luai_writestringerror("%s\n", msg); + if (pname) lua_writestringerror("%s: ", pname); + lua_writestringerror("%s\n", msg); } @@ -208,8 +210,8 @@ static int docall (lua_State *L, int narg, int nres) { static void print_version (void) { - luai_writestring(LUA_COPYRIGHT, strlen(LUA_COPYRIGHT)); - luai_writeline(); + lua_writestring(LUA_COPYRIGHT, strlen(LUA_COPYRIGHT)); + lua_writeline(); } @@ -410,7 +412,7 @@ static void doREPL (lua_State *L) { else report(L, status); } lua_settop(L, 0); /* clear stack */ - luai_writeline(); + lua_writeline(); progname = oldprogname; } @@ -420,8 +422,7 @@ static void doREPL (lua_State *L) { */ static int pushargs (lua_State *L) { int i, n; - lua_getglobal(L, "arg"); - if (!lua_istable(L, -1)) + if (lua_getglobal(L, "arg") != LUA_TTABLE) luaL_error(L, "'arg' is not a table"); n = (int)luaL_len(L, -1); luaL_checkstack(L, n + 3, "too many arguments to script"); @@ -1,5 +1,5 @@ /* -** $Id: lua.h,v 1.319 2014/10/17 19:17:55 roberto Exp $ +** $Id: lua.h,v 1.324 2014/12/08 15:12:07 roberto Exp $ ** Lua - A Scripting Language ** Lua.org, PUC-Rio, Brazil (http://www.lua.org) ** See Copyright Notice at the end of this file @@ -19,7 +19,7 @@ #define LUA_VERSION_MAJOR "5" #define LUA_VERSION_MINOR "3" #define LUA_VERSION_NUM 503 -#define LUA_VERSION_RELEASE "0 (beta)" +#define LUA_VERSION_RELEASE "0" #define LUA_VERSION "Lua " LUA_VERSION_MAJOR "." LUA_VERSION_MINOR #define LUA_RELEASE LUA_VERSION "." LUA_VERSION_RELEASE @@ -28,7 +28,7 @@ /* mark for precompiled code ('<esc>Lua') */ -#define LUA_SIGNATURE "\033Lua" +#define LUA_SIGNATURE "\x1bLua" /* option for multiple returns in 'lua_pcall' and 'lua_call' */ #define LUA_MULTRET (-1) @@ -159,7 +159,7 @@ LUA_API void (lua_settop) (lua_State *L, int idx); LUA_API void (lua_pushvalue) (lua_State *L, int idx); LUA_API void (lua_rotate) (lua_State *L, int idx, int n); LUA_API void (lua_copy) (lua_State *L, int fromidx, int toidx); -LUA_API int (lua_checkstack) (lua_State *L, int sz); +LUA_API int (lua_checkstack) (lua_State *L, int n); LUA_API void (lua_xmove) (lua_State *from, lua_State *to, int n); @@ -222,7 +222,7 @@ LUA_API int (lua_compare) (lua_State *L, int idx1, int idx2, int op); LUA_API void (lua_pushnil) (lua_State *L); LUA_API void (lua_pushnumber) (lua_State *L, lua_Number n); LUA_API void (lua_pushinteger) (lua_State *L, lua_Integer n); -LUA_API const char *(lua_pushlstring) (lua_State *L, const char *s, size_t l); +LUA_API const char *(lua_pushlstring) (lua_State *L, const char *s, size_t len); LUA_API const char *(lua_pushstring) (lua_State *L, const char *s); LUA_API const char *(lua_pushvfstring) (lua_State *L, const char *fmt, va_list argp); @@ -236,7 +236,7 @@ LUA_API int (lua_pushthread) (lua_State *L); /* ** get functions (Lua -> stack) */ -LUA_API int (lua_getglobal) (lua_State *L, const char *var); +LUA_API int (lua_getglobal) (lua_State *L, const char *name); LUA_API int (lua_gettable) (lua_State *L, int idx); LUA_API int (lua_getfield) (lua_State *L, int idx, const char *k); LUA_API int (lua_geti) (lua_State *L, int idx, lua_Integer n); @@ -253,7 +253,7 @@ LUA_API int (lua_getuservalue) (lua_State *L, int idx); /* ** set functions (stack -> Lua) */ -LUA_API void (lua_setglobal) (lua_State *L, const char *var); +LUA_API void (lua_setglobal) (lua_State *L, const char *name); LUA_API void (lua_settable) (lua_State *L, int idx); LUA_API void (lua_setfield) (lua_State *L, int idx, const char *k); LUA_API void (lua_seti) (lua_State *L, int idx, lua_Integer n); @@ -276,8 +276,7 @@ LUA_API int (lua_pcallk) (lua_State *L, int nargs, int nresults, int errfunc, #define lua_pcall(L,n,r,f) lua_pcallk(L, (n), (r), (f), 0, NULL) LUA_API int (lua_load) (lua_State *L, lua_Reader reader, void *dt, - const char *chunkname, - const char *mode); + const char *chunkname, const char *mode); LUA_API int (lua_dump) (lua_State *L, lua_Writer writer, void *data, int strip); @@ -285,12 +284,13 @@ LUA_API int (lua_dump) (lua_State *L, lua_Writer writer, void *data, int strip); /* ** coroutine functions */ -LUA_API int (lua_yieldk) (lua_State *L, int nresults, lua_KContext ctx, - lua_KFunction k); +LUA_API int (lua_yieldk) (lua_State *L, int nresults, lua_KContext ctx, + lua_KFunction k); +LUA_API int (lua_resume) (lua_State *L, lua_State *from, int narg); +LUA_API int (lua_status) (lua_State *L); +LUA_API int (lua_isyieldable) (lua_State *L); + #define lua_yield(L,n) lua_yieldk(L, (n), 0, NULL) -LUA_API int (lua_resume) (lua_State *L, lua_State *from, int narg); -LUA_API int (lua_status) (lua_State *L); -LUA_API int lua_isyieldable (lua_State *L); /* @@ -382,7 +382,7 @@ LUA_API void (lua_setallocf) (lua_State *L, lua_Alloc f, void *ud); #if defined(LUA_COMPAT_APIINTCASTS) #define lua_pushunsigned(L,n) lua_pushinteger(L, (lua_Integer)(n)) -#define lua_tounsignedx(L,i,is) ((lua_Integer)lua_tointegerx(L,i,is)) +#define lua_tounsignedx(L,i,is) ((lua_Unsigned)lua_tointegerx(L,i,is)) #define lua_tounsigned(L,i) lua_tounsignedx(L,(i),NULL) #endif @@ -1,17 +1,20 @@ /* -** $Id: luac.c,v 1.69 2011/11/29 17:46:33 lhf Exp $ -** Lua compiler (saves bytecodes to files; also list bytecodes) +** $Id: luac.c,v 1.71 2014/11/26 12:08:59 lhf Exp $ +** Lua compiler (saves bytecodes to files; also lists bytecodes) ** See Copyright Notice in lua.h */ +#define luac_c +#define LUA_CORE + +#include "lprefix.h" + +#include <ctype.h> #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> -#define luac_c -#define LUA_CORE - #include "lua.h" #include "lauxlib.h" diff --git a/src/luaconf.h b/src/luaconf.h index ae395769..593ccd8d 100644 --- a/src/luaconf.h +++ b/src/luaconf.h @@ -1,5 +1,5 @@ /* -** $Id: luaconf.h,v 1.220 2014/10/21 14:38:46 roberto Exp $ +** $Id: luaconf.h,v 1.231 2014/12/10 11:56:55 roberto Exp $ ** Configuration file for Lua ** See Copyright Notice in lua.h */ @@ -8,9 +8,12 @@ #ifndef lconfig_h #define lconfig_h +#include <limits.h> +#include <stddef.h> + /* -** ================================================================== +** =================================================================== ** Search for "@@" to find all configurable definitions. ** =================================================================== */ @@ -18,107 +21,136 @@ /* ** {================================================================== -@@ LUA_INT_INT / LUA_INT_LONG / LUA_INT_LONGLONG defines type for -@@ Lua integers; you must define one of them. -@@ LUA_REAL_FLOAT / LUA_REAL_DOUBLE / LUA_REAL_LONGDOUBLE defines -@@ type for Lua floats. You must define one of them. -** -** These definitions set the numeric types for Lua. Lua should work fine -** with any mix of these previous options. The usual configurations -** are 64-bit integers and floats (the default) and 32-bit integers and -** floats (Small Lua, for restricted platforms). -** -** Note that C compilers not compliant with C99 may not have -** support for 'long long'. In that case, you should not use option -** 'LUA_INT_LONGLONG'; use instead option 'LUA_32BITS' for Small Lua -** (see below), or LUA_INT_LONG plus LUA_REAL_DOUBLE for an interpreter -** with 32-bit integers and double floating-point numbers. -** ===================================================================== +** System Configuration: macros to adapt (if needed) Lua to some +** particular platform, for instance compiling it as Small Lua (32 +** bits) or restricting it to C89. +** =================================================================== */ /* -** Just uncomment the next line for Small Lua; you can also define -** LUA_32BITS in the make file, but changing here you ensure that -** all software connected to Lua will be compiled with the same -** configuration. +@@ LUA_32BITS enables Small Lua (that is, Lua with 32-bit integers +** and 32-bit floats). You can also define LUA_32BITS in the make file, +** but changing here you ensure that all software connected to Lua will +** be compiled with the same configuration. */ /* #define LUA_32BITS */ -#if !defined(LUA_32BITS) && !defined(LUA_ANSI) -#define LUA_INT_LONGLONG -#define LUA_REAL_DOUBLE -#else /* Lua 32 bits */ -#define LUA_INT_LONG -#define LUA_REAL_FLOAT -#endif -/* }================================================================== */ +/* +@@ LUA_USE_C89 controls the use of non-ISO-C89 features. +** Define it if you want Lua to avoid the use of a few C99 features +** or Windows-specific features on Windows. +*/ +/* #define LUA_USE_C89 */ /* -@@ LUA_ANSI controls the use of non-ansi features. -** CHANGE it (define it) if you want Lua to avoid the use of any -** non-ansi feature or library. +** By default, Lua on Windows use (some) specific Windows features */ -#if !defined(LUA_ANSI) && defined(__STRICT_ANSI__) -#define LUA_ANSI +#if !defined(LUA_USE_C89) && defined(_WIN32) && !defined(_WIN32_WCE) +#define LUA_USE_WINDOWS /* enable goodies for regular Windows */ #endif -#if !defined(LUA_ANSI) && defined(_WIN32) && !defined(_WIN32_WCE) -#define LUA_WIN /* enable goodies for regular Windows platforms */ +#if defined(LUA_USE_WINDOWS) +#define LUA_DL_DLL /* enable support for DLL */ +#define LUA_USE_C89 /* broadly, Windows is C89 */ #endif -#if defined(LUA_WIN) -#define _CRT_SECURE_NO_WARNINGS /* avoid warnings about ANSI C functions */ -#define LUA_DL_DLL -#define LUA_USE_AFORMAT /* assume 'printf' handles 'aA' specifiers */ -#endif - - #if defined(LUA_USE_LINUX) -#define LUA_USE_C99 #define LUA_USE_POSIX #define LUA_USE_DLOPEN /* needs an extra library: -ldl */ #define LUA_USE_READLINE /* needs some extra libraries */ #endif + #if defined(LUA_USE_MACOSX) -#define LUA_USE_C99 #define LUA_USE_POSIX -#define LUA_USE_DLOPEN /* does not need -ldl */ +#define LUA_USE_DLOPEN /* MacOS does not need -ldl */ #define LUA_USE_READLINE /* needs an extra library: -lreadline */ #endif /* -@@ LUA_USE_C99 includes all functionality that depends on C 99. -** CHANGE it (define it) if your system is compatible. +@@ LUA_C89_NUMBERS ensures that Lua uses the largest types available for +** C89 ('long' and 'double'); Windows has '__int64', so it does not need +** to use this case. */ -#if defined(LUA_USE_C99) -#define LUA_USE_AFORMAT /* assume 'printf' handles 'aA' specifiers */ +#if defined(LUA_USE_C89) && !defined(LUA_USE_WINDOWS) +#define LUA_C89_NUMBERS #endif + /* -@@ LUA_USE_POSIX includes all functionality listed as X/Open System -@@ Interfaces Extension (XSI). -** CHANGE it (define it) if your system is XSI compatible. +@@ LUAI_BITSINT defines the (minimum) number of bits in an 'int'. */ -#if defined(LUA_USE_POSIX) +/* avoid undefined shifts */ +#if ((INT_MAX >> 15) >> 15) >= 1 +#define LUAI_BITSINT 32 +#else +/* 'int' always must have at least 16 bits */ +#define LUAI_BITSINT 16 #endif +/* +@@ LUA_INT_INT / LUA_INT_LONG / LUA_INT_LONGLONG defines the type for +** Lua integers. +@@ LUA_REAL_FLOAT / LUA_REAL_DOUBLE / LUA_REAL_LONGDOUBLE defines +** the type for Lua floats. +** Lua should work fine with any mix of these options (if supported +** by your C compiler). The usual configurations are 64-bit integers +** and 'double' (the default), 32-bit integers and 'float' (Small Lua, +** for restricted platforms), and 'long'/'double' (for C compilers not +** compliant with C99, which may not have support for 'long long'). +*/ + +#if defined(LUA_32BITS) /* { */ +/* +** Small Lua (32-bit integers and 'float') +*/ +#if LUAI_BITSINT >= 32 /* use 'int' if big enough */ +#define LUA_INT_INT +#else /* otherwise use 'long' */ +#define LUA_INT_LONG +#endif +#define LUA_REAL_FLOAT + +#elif defined(LUA_C89_NUMBERS) /* }{ */ +/* +** largest types available for C89 ('long' and 'double') +*/ +#define LUA_INT_LONG +#define LUA_REAL_DOUBLE + +#else /* }{ */ +/* +** default configuration for 64-bit Lua ('long long' and 'double'); +** Windows will use '__int64' +*/ +#define LUA_INT_LONGLONG +#define LUA_REAL_DOUBLE + +#endif /* } */ + +/* }================================================================== */ + + -#include <limits.h> -#include <stddef.h> + +/* +** {================================================================== +** Configuration for Paths. +** =================================================================== +*/ /* @@ LUA_PATH_DEFAULT is the default path that Lua uses to look for -@@ Lua libraries. +** Lua libraries. @@ LUA_CPATH_DEFAULT is the default path that Lua uses to look for -@@ C libraries. +** C libraries. ** CHANGE them if your machine has a non-conventional directory ** hierarchy or if you want to install your libraries in ** non-conventional directories. @@ -135,7 +167,7 @@ #define LUA_PATH_DEFAULT \ LUA_LDIR"?.lua;" LUA_LDIR"?\\init.lua;" \ LUA_CDIR"?.lua;" LUA_CDIR"?\\init.lua;" \ - LUA_SHRDIR"?.lua;" LUA_SHRDIR"?\\init.lua;" \ + LUA_SHRDIR"?.lua;" LUA_SHRDIR"?\\init.lua;" \ ".\\?.lua;" ".\\?\\init.lua" #define LUA_CPATH_DEFAULT \ LUA_CDIR"?.dll;" \ @@ -167,14 +199,14 @@ #define LUA_DIRSEP "/" #endif +/* }================================================================== */ + /* -@@ LUA_ENV is the name of the variable that holds the current -@@ environment, used to access global names. -** CHANGE it if you do not like this name. +** {================================================================== +** Marks for exported symbols in the C code +** =================================================================== */ -#define LUA_ENV "_ENV" - /* @@ LUA_API is a mark for all core API functions. @@ -207,10 +239,10 @@ /* @@ LUAI_FUNC is a mark for all extern functions that are not to be -@@ exported to outside modules. +** exported to outside modules. @@ LUAI_DDEF and LUAI_DDEC are marks for all extern (const) variables -@@ that are not to be exported to outside modules (LUAI_DDEF for -@@ definitions and LUAI_DDEC for declarations). +** that are not to be exported to outside modules (LUAI_DDEF for +** definitions and LUAI_DDEC for declarations). ** CHANGE them if you need to mark them in some special way. Elf/gcc ** (versions 3.2 and later) mark them as "hidden" to optimize access ** when Lua is compiled as a shared library. Not all elf targets support @@ -222,82 +254,14 @@ #if defined(__GNUC__) && ((__GNUC__*100 + __GNUC_MINOR__) >= 302) && \ defined(__ELF__) /* { */ #define LUAI_FUNC __attribute__((visibility("hidden"))) extern -#define LUAI_DDEC LUAI_FUNC -#define LUAI_DDEF /* empty */ - #else /* }{ */ #define LUAI_FUNC extern -#define LUAI_DDEC extern -#define LUAI_DDEF /* empty */ #endif /* } */ +#define LUAI_DDEC LUAI_FUNC +#define LUAI_DDEF /* empty */ - -/* -@@ LUA_EXTRASPACE defines the size of a raw memory area associated with -** a Lua state with very fast access. -** CHANGE it if you need a different size. -*/ -#define LUA_EXTRASPACE (sizeof(void *)) - - -/* -@@ LUA_QL describes how error messages quote program elements. -** Lua does not use these macros anymore; they are here for -** compatibility only. -*/ -#define LUA_QL(x) "'" x "'" -#define LUA_QS LUA_QL("%s") - - -/* -@@ LUA_IDSIZE gives the maximum size for the description of the source -@@ of a function in debug information. -** CHANGE it if you want a different size. -*/ -#define LUA_IDSIZE 60 - - -/* -@@ luai_writestring/luai_writeline define how 'print' prints its results. -** They are only used in libraries and the stand-alone program. -*/ -#define luai_writestring(s,l) fwrite((s), sizeof(char), (l), stdout) -#define luai_writeline() (luai_writestring("\n", 1), fflush(stdout)) - -/* -@@ luai_writestringerror defines how to print error messages. -** (A format string with one argument is enough for Lua...) -*/ -#define luai_writestringerror(s,p) \ - (fprintf(stderr, (s), (p)), fflush(stderr)) - - -/* -@@ LUAI_MAXSHORTLEN is the maximum length for short strings, that is, -** strings that are internalized. (Cannot be smaller than reserved words -** or tags for metamethods, as these strings must be internalized; -** #("function") = 8, #("__newindex") = 10.) -*/ -#define LUAI_MAXSHORTLEN 40 - - -/* -@@ LUA_KCONTEXT is the type of the context ('ctx') for continuation -@@ functions. It must be a numerical type; Lua will use 'intptr_t' if -@@ available. -*/ -#if defined (LUA_USE_C99) -#include <stdint.h> -#if defined (INTPTR_MAX) /* even in C99 this type is optional */ -#define LUA_KCONTEXT intptr_t -#endif -#endif - -#if !defined(LUA_KCONTEXT) -/* default definition (the nearest thing to 'intptr_t' in C89) */ -#define LUA_KCONTEXT ptrdiff_t -#endif +/* }================================================================== */ /* @@ -415,69 +379,6 @@ /* -@@ LUAI_BITSINT defines the number of bits in an int. -** CHANGE here if Lua cannot automatically detect the number of bits of -** your machine. Probably you do not need to change this. -*/ -/* avoid overflows in comparison */ -#if INT_MAX-20 < 32760 /* { */ -#define LUAI_BITSINT 16 -#elif INT_MAX > 2147483640L /* }{ */ -/* int has at least 32 bits */ -#define LUAI_BITSINT 32 -#else /* }{ */ -#error "you must define LUA_BITSINT with number of bits in an integer" -#endif /* } */ - - -/* -@@ LUA_INT32 is an signed integer with exactly 32 bits. -@@ LUAI_UMEM is an unsigned integer big enough to count the total -@@ memory used by Lua. -@@ LUAI_MEM is a signed integer big enough to count the total memory -@@ used by Lua. -** CHANGE here if for some weird reason the default definitions are not -** good enough for your machine. Probably you do not need to change -** this. -*/ -#if LUAI_BITSINT >= 32 /* { */ -#define LUA_INT32 int -#define LUAI_UMEM size_t -#define LUAI_MEM ptrdiff_t -#else /* }{ */ -/* 16-bit ints */ -#define LUA_INT32 long -#define LUAI_UMEM unsigned long -#define LUAI_MEM long -#endif /* } */ - - -/* -@@ LUAI_MAXSTACK limits the size of the Lua stack. -** CHANGE it if you need a different limit. This limit is arbitrary; -** its only purpose is to stop Lua from consuming unlimited stack -** space (and to reserve some numbers for pseudo-indices). -*/ -#if LUAI_BITSINT >= 32 -#define LUAI_MAXSTACK 1000000 -#else -#define LUAI_MAXSTACK 15000 -#endif - -/* reserve some space for error handling */ -#define LUAI_FIRSTPSEUDOIDX (-LUAI_MAXSTACK - 1000) - - - - -/* -@@ LUAL_BUFFERSIZE is the buffer size used by the lauxlib buffer system. -** CHANGE it if it uses too much C-stack space. -*/ -#define LUAL_BUFFERSIZE BUFSIZ - - -/* ** {================================================================== ** Configuration for Numbers. ** Change these definitions if no predefined LUA_REAL_* / LUA_INT_* @@ -495,7 +396,7 @@ @@ LUA_NUMBER_FMT is the format for writing floats. @@ lua_number2str converts a float to a string. ** -@@ l_mathop allows the addition of an 'l' or 'f' to all math operations +@@ l_mathop allows the addition of an 'l' or 'f' to all math operations. ** @@ lua_str2number converts a decimal numeric string to a number. */ @@ -547,29 +448,20 @@ #endif /* } */ -#if !defined(LUA_USE_C99) -/* 'strtof' and 'opf' variants for math functions are C99 */ -#undef l_mathop -#undef lua_str2number -#define l_mathop(op) (lua_Number)op -#define lua_str2number(s,p) ((lua_Number)strtod((s), (p))) -#endif - - #define l_floor(x) (l_mathop(floor)(x)) #define lua_number2str(s,n) sprintf((s), LUA_NUMBER_FMT, (n)) /* -@@ lua_numtointeger converts a float number to an integer, or +@@ lua_numbertointeger converts a float number to an integer, or ** returns 0 if float is not within the range of a lua_Integer. ** (The range comparisons are tricky because of rounding. The tests ** here assume a two-complement representation, where MININTEGER always ** has an exact representation as a float; MAXINTEGER may not have one, ** and therefore its conversion to float may have an ill-defined value.) */ -#define lua_numtointeger(n,p) \ +#define lua_numbertointeger(n,p) \ ((n) >= (LUA_NUMBER)(LUA_MININTEGER) && \ (n) < -(LUA_NUMBER)(LUA_MININTEGER) && \ (*(p) = (LUA_INTEGER)(n), 1)) @@ -583,9 +475,23 @@ /* the following operations need the math library */ #if defined(lobject_c) || defined(lvm_c) #include <math.h> + +/* floor division (defined as 'floor(a/b)') */ +#define luai_numidiv(L,a,b) ((void)L, l_mathop(floor)((a)/(b))) + +/* +** module: defined as 'a - floor(a/b)*b'; the previous definition gives +** NaN when 'b' is huge, but the result should be 'a'. 'fmod' gives the +** result of 'a - trunc(a/b)*b', and therefore must be corrected when +** 'trunc(a/b) ~= floor(a/b)'. That happens when the division has a +** non-integer negative result, which is equivalent to the test below +*/ #define luai_nummod(L,a,b,m) \ - { (m) = l_mathop(fmod)(a,b); if ((m) != 0 && (a)*(b) < 0) (m) += (b); } + { (m) = l_mathop(fmod)(a,b); if ((m)*(b) < 0) (m) += (b); } + +/* exponentiation */ #define luai_numpow(L,a,b) ((void)L, l_mathop(pow)(a,b)) + #endif /* these are quite standard operations */ @@ -659,7 +565,7 @@ #elif defined(LUA_INT_LONGLONG) /* }{ long long */ -#if defined(_WIN32) +#if defined(LUA_USE_WINDOWS) /* { */ #define LUA_INTEGER __int64 #define LUA_INTEGER_FRMLEN "I64" @@ -667,10 +573,11 @@ #define LUA_MAXINTEGER _I64_MAX #define LUA_MININTEGER _I64_MIN -#else +#else /* }{ */ #if !defined(LLONG_MAX) -#error "Compiler does not support 'long long'. See file 'luaconf.h' line 24" +#error "Compiler does not support 'long long'. Use option '-DLUA_32BITS' \ + or '-DLUA_C89_NUMBERS' (see file 'luaconf.h' for details)" #endif #define LUA_INTEGER long long @@ -679,37 +586,145 @@ #define LUA_MAXINTEGER LLONG_MAX #define LUA_MININTEGER LLONG_MIN +#endif /* } */ + +#else /* }{ */ + +#error "numeric integer type not defined" + +#endif /* } */ + +/* }================================================================== */ + + +/* +** {================================================================== +** Dependencies with C99 +** =================================================================== +*/ + +/* +@@ lua_strx2number converts an hexadecimal numeric string to a number. +** In C99, 'strtod' does both conversions. Otherwise, you can +** leave 'lua_strx2number' undefined and Lua will provide its own +** implementation. +*/ +#if !defined(LUA_USE_C89) +#define lua_strx2number(s,p) lua_str2number(s,p) #endif -#elif defined(LUA_INT_SHORT) /* }{ short int */ + /* -** this option is for tests only; it is not particularly useful and -** it does not pass the test suit. +@@ LUA_USE_AFORMAT allows '%a'/'%A' specifiers in 'string.format' +** Enable it if the C function 'printf' supports these specifiers. +** (C99 demands it and Windows also supports it.) */ +#if !defined(LUA_USE_C89) || defined(LUA_USE_WINDOWS) +#define LUA_USE_AFORMAT +#endif -#define LUA_INTEGER short int -#define LUA_INTEGER_FRMLEN "" -#define LUA_MAXINTEGER SHRT_MAX -#define LUA_MININTEGER SHRT_MIN +/* +** 'strtof' and 'opf' variants for math functions are not valid in +** C89. Otherwise, the macro 'HUGE_VALF' is a good proxy for testing the +** availability of these variants. ('math.h' is already included in +** all files that use these macros.) +*/ +#if defined(LUA_USE_C89) || (defined(HUGE_VAL) && !defined(HUGE_VALF)) +#undef l_mathop /* variants not available */ +#undef lua_str2number +#define l_mathop(op) (lua_Number)op /* no variant */ +#define lua_str2number(s,p) ((lua_Number)strtod((s), (p))) +#endif + + +/* +@@ LUA_KCONTEXT is the type of the context ('ctx') for continuation +** functions. It must be a numerical type; Lua will use 'intptr_t' if +** available, otherwise it will use 'ptrdiff_t' (the nearest thing to +** 'intptr_t' in C89) +*/ +#define LUA_KCONTEXT ptrdiff_t + +#if !defined(LUA_USE_C89) && defined(__STDC_VERSION__) && \ + __STDC_VERSION__ >= 199901L +#include <stdint.h> +#if defined (INTPTR_MAX) /* even in C99 this type is optional */ +#undef LUA_KCONTEXT +#define LUA_KCONTEXT intptr_t +#endif +#endif -#undef LUAI_UACINT -#define LUAI_UACINT int +/* }================================================================== */ -#undef LUAI_MAXSTACK -#define LUAI_MAXSTACK 15000 -#define l_castS2U(x) ((LUA_UNSIGNED)(unsigned short)(x)) +/* +** {================================================================== +** Macros that affect the API and must be stable (that is, must be the +** same when you compile Lua and when you compile code that links to +** Lua). You probably do not want/need to change them. +** ===================================================================== +*/ -#else /* }{ */ +/* +@@ LUAI_MAXSTACK limits the size of the Lua stack. +** CHANGE it if you need a different limit. This limit is arbitrary; +** its only purpose is to stop Lua from consuming unlimited stack +** space (and to reserve some numbers for pseudo-indices). +*/ +#if LUAI_BITSINT >= 32 +#define LUAI_MAXSTACK 1000000 +#else +#define LUAI_MAXSTACK 15000 +#endif -#error "numeric integer type not defined" +/* reserve some space for error handling */ +#define LUAI_FIRSTPSEUDOIDX (-LUAI_MAXSTACK - 1000) + + +/* +@@ LUA_EXTRASPACE defines the size of a raw memory area associated with +** a Lua state with very fast access. +** CHANGE it if you need a different size. +*/ +#define LUA_EXTRASPACE (sizeof(void *)) + + +/* +@@ LUA_IDSIZE gives the maximum size for the description of the source +@@ of a function in debug information. +** CHANGE it if you want a different size. +*/ +#define LUA_IDSIZE 60 + + +/* +@@ LUAI_MAXSHORTLEN is the maximum length for short strings, that is, +** strings that are internalized. (Cannot be smaller than reserved words +** or tags for metamethods, as these strings must be internalized; +** #("function") = 8, #("__newindex") = 10.) +*/ +#define LUAI_MAXSHORTLEN 40 -#endif /* } */ + +/* +@@ LUAL_BUFFERSIZE is the buffer size used by the lauxlib buffer system. +** CHANGE it if it uses too much C-stack space. +*/ +#define LUAL_BUFFERSIZE ((int)(0x80 * sizeof(void*) * sizeof(lua_Integer))) /* }================================================================== */ +/* +@@ LUA_QL describes how error messages quote program elements. +** Lua does not use these macros anymore; they are here for +** compatibility only. +*/ +#define LUA_QL(x) "'" x "'" +#define LUA_QS LUA_QL("%s") + + /* =================================================================== */ diff --git a/src/lundump.c b/src/lundump.c index 0cdca1af..510f3258 100644 --- a/src/lundump.c +++ b/src/lundump.c @@ -1,14 +1,17 @@ /* -** $Id: lundump.c,v 2.40 2014/06/19 18:27:20 roberto Exp $ +** $Id: lundump.c,v 2.41 2014/11/02 19:19:04 roberto Exp $ ** load precompiled Lua chunks ** See Copyright Notice in lua.h */ -#include <string.h> - #define lundump_c #define LUA_CORE +#include "lprefix.h" + + +#include <string.h> + #include "lua.h" #include "ldebug.h" diff --git a/src/lutf8lib.c b/src/lutf8lib.c index de139296..be4f087f 100644 --- a/src/lutf8lib.c +++ b/src/lutf8lib.c @@ -1,17 +1,19 @@ /* -** $Id: lutf8lib.c,v 1.12 2014/10/15 14:31:10 roberto Exp $ +** $Id: lutf8lib.c,v 1.13 2014/11/02 19:19:04 roberto Exp $ ** Standard library for UTF-8 manipulation ** See Copyright Notice in lua.h */ +#define lutf8lib_c +#define LUA_LIB + +#include "lprefix.h" + #include <assert.h> #include <stdlib.h> #include <string.h> -#define lutf8lib_c -#define LUA_LIB - #include "lua.h" #include "lauxlib.h" @@ -1,18 +1,20 @@ /* -** $Id: lvm.c,v 2.224 2014/10/17 16:28:21 roberto Exp $ +** $Id: lvm.c,v 2.230 2014/11/21 12:15:00 roberto Exp $ ** Lua virtual machine ** See Copyright Notice in lua.h */ +#define lvm_c +#define LUA_CORE + +#include "lprefix.h" + #include <limits.h> #include <stdio.h> #include <stdlib.h> #include <string.h> -#define lvm_c -#define LUA_CORE - #include "lua.h" #include "ldebug.h" @@ -28,6 +30,15 @@ #include "lvm.h" +/* +** You can define LUA_FLOORN2I if you want to convert floats to integers +** by flooring them (instead of raising an error if they are not +** integral values) +*/ +#if !defined(LUA_FLOORN2I) +#define LUA_FLOORN2I 0 +#endif + /* limit for table tag-method chains (to avoid loops) */ #define MAXTAGLOOP 2000 @@ -52,34 +63,31 @@ static int tofloat (const TValue *obj, lua_Number *n) { /* -** Try to convert a value to a float. Check 'isinteger' first, because -** in general the float case is already handled by the macro 'tonumber'. +** Try to convert a value to a float. The float case is already handled +** by the macro 'tonumber'. */ int luaV_tonumber_ (const TValue *obj, lua_Number *n) { TValue v; - again: if (ttisinteger(obj)) { *n = cast_num(ivalue(obj)); return 1; } - else if (ttisfloat(obj)) { - *n = fltvalue(obj); - return 1; - } else if (cvt2num(obj) && /* string convertible to number? */ luaO_str2num(svalue(obj), &v) == tsvalue(obj)->len + 1) { - obj = &v; - goto again; /* convert result from 'luaO_str2num' to a float */ + /* convert result of 'luaO_str2num' to a float */ + *n = (ttisinteger(&v)) ? cast_num(ivalue(&v)) : fltvalue(&v); + return 1; } - return 0; /* conversion failed */ + else + return 0; /* conversion failed */ } /* ** try to convert a value to an integer, rounding according to 'mode': ** mode == 0: accepts only integral values -** mode < 0: takes the floor of the number -** mode > 0: takes the ceil of the number +** mode == 1: takes the floor of the number +** mode == 2: takes the ceil of the number */ static int tointeger_aux (const TValue *obj, lua_Integer *p, int mode) { TValue v; @@ -89,10 +97,10 @@ static int tointeger_aux (const TValue *obj, lua_Integer *p, int mode) { lua_Number f = l_floor(n); if (n != f) { /* not an integral value? */ if (mode == 0) return 0; /* fails if mode demands integral value */ - else if (mode > 0) /* needs ceil? */ + else if (mode > 1) /* needs ceil? */ f += 1; /* convert floor to ceil (remember: n != f) */ } - return lua_numtointeger(f, p); + return lua_numbertointeger(f, p); } else if (ttisinteger(obj)) { *p = ivalue(obj); @@ -111,7 +119,7 @@ static int tointeger_aux (const TValue *obj, lua_Integer *p, int mode) { ** try to convert a value to an integer */ int luaV_tointeger_ (const TValue *obj, lua_Integer *p) { - return tointeger_aux(obj, p, 0); + return tointeger_aux(obj, p, LUA_FLOORN2I); } @@ -133,7 +141,7 @@ int luaV_tointeger_ (const TValue *obj, lua_Integer *p) { static int forlimit (const TValue *obj, lua_Integer *p, lua_Integer step, int *stopnow) { *stopnow = 0; /* usually, let loops run */ - if (!tointeger_aux(obj, p, (step < 0 ? 1 : -1))) { /* not fit in integer? */ + if (!tointeger_aux(obj, p, (step < 0 ? 2 : 1))) { /* not fit in integer? */ lua_Number n; /* try to convert to float */ if (!tonumber(obj, &n)) /* cannot convert to float? */ return 0; /* not a number */ @@ -158,7 +166,7 @@ void luaV_gettable (lua_State *L, const TValue *t, TValue *key, StkId val) { int loop; /* counter to avoid infinite loops */ for (loop = 0; loop < MAXTAGLOOP; loop++) { const TValue *tm; - if (ttistable(t)) { /* `t' is a table? */ + if (ttistable(t)) { /* 't' is a table? */ Table *h = hvalue(t); const TValue *res = luaH_get(h, key); /* do a primitive get */ if (!ttisnil(res) || /* result is not nil? */ @@ -188,7 +196,7 @@ void luaV_settable (lua_State *L, const TValue *t, TValue *key, StkId val) { int loop; /* counter to avoid infinite loops */ for (loop = 0; loop < MAXTAGLOOP; loop++) { const TValue *tm; - if (ttistable(t)) { /* `t' is a table? */ + if (ttistable(t)) { /* 't' is a table? */ Table *h = hvalue(t); TValue *oldval = cast(TValue *, luaH_get(h, key)); /* if previous value is not nil, there must be a previous entry @@ -240,12 +248,12 @@ static int l_strcmp (const TString *ls, const TString *rs) { if (temp != 0) /* not equal? */ return temp; /* done */ else { /* strings are equal up to a '\0' */ - size_t len = strlen(l); /* index of first `\0' in both strings */ + size_t len = strlen(l); /* index of first '\0' in both strings */ if (len == lr) /* 'rs' is finished? */ return (len == ll) ? 0 : 1; /* check 'ls' */ else if (len == ll) /* 'ls' is finished? */ return -1; /* 'ls' is smaller than 'rs' ('rs' is not finished) */ - /* both strings longer than `len'; go on comparing after the '\0' */ + /* both strings longer than 'len'; go on comparing after the '\0' */ len++; l += len; ll -= len; r += len; lr -= len; } @@ -283,9 +291,9 @@ int luaV_lessequal (lua_State *L, const TValue *l, const TValue *r) { return luai_numle(nl, nr); else if (ttisstring(l) && ttisstring(r)) /* both are strings? */ return l_strcmp(tsvalue(l), tsvalue(r)) <= 0; - else if ((res = luaT_callorderTM(L, l, r, TM_LE)) >= 0) /* first try `le' */ + else if ((res = luaT_callorderTM(L, l, r, TM_LE)) >= 0) /* first try 'le' */ return res; - else if ((res = luaT_callorderTM(L, r, l, TM_LT)) < 0) /* else try `lt' */ + else if ((res = luaT_callorderTM(L, r, l, TM_LT)) < 0) /* else try 'lt' */ luaG_ordererror(L, l, r); return !res; } @@ -420,8 +428,10 @@ void luaV_objlen (lua_State *L, StkId ra, const TValue *rb) { /* -** Integer division; return 'm // n'. (Assume that C division with -** negative operands follows C99 behavior.) +** Integer division; return 'm // n', that is, floor(m/n). +** C division truncates its result (rounds towards zero). +** 'floor(q) == trunc(q)' when 'q >= 0' or when 'q' is integer, +** otherwise 'floor(q) == trunc(q) - 1'. */ lua_Integer luaV_div (lua_State *L, lua_Integer m, lua_Integer n) { if (l_castS2U(n) + 1u <= 1u) { /* special cases: -1 or 0 */ @@ -430,18 +440,18 @@ lua_Integer luaV_div (lua_State *L, lua_Integer m, lua_Integer n) { return intop(-, 0, m); /* n==-1; avoid overflow with 0x80000...//-1 */ } else { - lua_Integer d = m / n; /* perform division */ - if ((m ^ n) >= 0 || m % n == 0) /* same signal or no rest? */ - return d; - else - return d - 1; /* correct 'div' for negative case */ + lua_Integer q = m / n; /* perform C division */ + if ((m ^ n) < 0 && m % n != 0) /* 'm/n' would be negative non-integer? */ + q -= 1; /* correct result for different rounding */ + return q; } } /* ** Integer modulus; return 'm % n'. (Assume that C '%' with -** negative operands follows C99 behavior.) +** negative operands follows C99 behavior. See previous comment +** about luaV_div.) */ lua_Integer luaV_mod (lua_State *L, lua_Integer m, lua_Integer n) { if (l_castS2U(n) + 1u <= 1u) { /* special cases: -1 or 0 */ @@ -451,10 +461,9 @@ lua_Integer luaV_mod (lua_State *L, lua_Integer m, lua_Integer n) { } else { lua_Integer r = m % n; - if (r == 0 || (m ^ n) >= 0) /* no rest or same signal? */ - return r; - else - return r + n; /* correct 'mod' for negative case */ + if (r != 0 && (m ^ n) < 0) /* 'm/n' would be non-integer negative? */ + r += n; /* correct result for different rounding */ + return r; } } @@ -596,7 +605,7 @@ void luaV_finishOp (lua_State *L) { /* -** some macros for common tasks in `luaV_execute' +** some macros for common tasks in 'luaV_execute' */ #if !defined luai_runtimecheck @@ -657,7 +666,7 @@ void luaV_execute (lua_State *L) { (--L->hookcount == 0 || L->hookmask & LUA_MASKLINE)) { Protect(luaG_traceexec(L)); } - /* WARNING: several calls may realloc the stack and invalidate `ra' */ + /* WARNING: several calls may realloc the stack and invalidate 'ra' */ ra = RA(i); lua_assert(base == ci->u.l.base); lua_assert(base <= L->top && L->top < L->stack + L->stacksize); @@ -770,15 +779,6 @@ void luaV_execute (lua_State *L) { } else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_DIV)); } ) - vmcase(OP_IDIV, /* integer division */ - TValue *rb = RKB(i); - TValue *rc = RKC(i); - lua_Integer ib; lua_Integer ic; - if (tointeger(rb, &ib) && tointeger(rc, &ic)) { - setivalue(ra, luaV_div(L, ib, ic)); - } - else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_IDIV)); } - ) vmcase(OP_BAND, TValue *rb = RKB(i); TValue *rc = RKC(i); @@ -839,6 +839,19 @@ void luaV_execute (lua_State *L) { } else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_MOD)); } ) + vmcase(OP_IDIV, /* floor division */ + TValue *rb = RKB(i); + TValue *rc = RKC(i); + lua_Number nb; lua_Number nc; + if (ttisinteger(rb) && ttisinteger(rc)) { + lua_Integer ib = ivalue(rb); lua_Integer ic = ivalue(rc); + setivalue(ra, luaV_div(L, ib, ic)); + } + else if (tonumber(rb, &nb) && tonumber(rc, &nc)) { + setfltvalue(ra, luai_numidiv(L, nb, nc)); + } + else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_IDIV)); } + ) vmcase(OP_POW, TValue *rb = RKB(i); TValue *rc = RKC(i); @@ -1,15 +1,17 @@ /* -** $Id: lzio.c,v 1.35 2012/05/14 13:34:18 roberto Exp $ +** $Id: lzio.c,v 1.36 2014/11/02 19:19:04 roberto Exp $ ** Buffered streams ** See Copyright Notice in lua.h */ - -#include <string.h> - #define lzio_c #define LUA_CORE +#include "lprefix.h" + + +#include <string.h> + #include "lua.h" #include "llimits.h" |