mirror of
https://github.com/lua/lua
synced 2026-06-08 15:34:49 +00:00
Compare commits
314 Commits
v5.4-alpha
..
v5.4.4
| Author | SHA1 | Date | |
|---|---|---|---|
| 5d708c3f9c | |||
| 8dd2c912d2 | |||
| 05ac2409ee | |||
| 597a53bbc6 | |||
| 86ec152433 | |||
| cf613cdc6f | |||
| 066e0f93c4 | |||
| 0bfc572e51 | |||
| 1de95e97ef | |||
| ad3942adba | |||
| 48835c76c8 | |||
| 6b3e116d44 | |||
| e8deac5a41 | |||
| bfbff3703e | |||
| 74d99057a5 | |||
| 1fce5bea81 | |||
| 3699446aaf | |||
| 0e5071b5fb | |||
| 87a9573b2e | |||
| deac067ed3 | |||
| 2ff3471722 | |||
| 9db4bfed6b | |||
| 91673a8ec0 | |||
| 41871f1803 | |||
| a393ac2554 | |||
| 65434b4d1b | |||
| 59acd79c05 | |||
| e2c07dcbf7 | |||
| 439e45a2f6 | |||
| 62fb934427 | |||
| 8a32e0aa4a | |||
| dbdc74dc55 | |||
| 6a0dace25a | |||
| 04e19712a5 | |||
| 901d760093 | |||
| c0ed74c1e1 | |||
| fc6c74f100 | |||
| 1e6918d553 | |||
| 681297187e | |||
| 5148954eed | |||
| d205f3a484 | |||
| 47cffdc723 | |||
| 36de01d988 | |||
| 7fbe215808 | |||
| bf10593a3a | |||
| bef250eb8d | |||
| ba81adaad9 | |||
| eadd8c7178 | |||
| 014daf43cb | |||
| 05b13651f9 | |||
| 81c6021fb4 | |||
| a7b8b27dd3 | |||
| 511d53a826 | |||
| f5df7f91f7 | |||
| e7803f7dbc | |||
| b7eb21c1ef | |||
| cf23a93d82 | |||
| 9a2de786de | |||
| 5276973224 | |||
| f9d857a81b | |||
| 1537d6680b | |||
| e0260eb2d4 | |||
| 5205f073c5 | |||
| 31925e4cc2 | |||
| 59c88f846d | |||
| c03c527fd2 | |||
| 38cc7d40a4 | |||
| bc970005ce | |||
| f79ccdca9b | |||
| 4e47f81188 | |||
| c63e5d212b | |||
| dee6433a89 | |||
| 2bfa13e520 | |||
| e500892e18 | |||
| 949187b049 | |||
| 58aa09a0b9 | |||
| 1f81baffad | |||
| 0e9254dfa0 | |||
| 6ccd24eff5 | |||
| d0f34d9137 | |||
| 825ac8eca8 | |||
| b07fc10e91 | |||
| cc1692515e | |||
| ce101dcaf7 | |||
| 553b37ce4f | |||
| 4bd10b6fe8 | |||
| 59e565d955 | |||
| 6188f3a654 | |||
| 7af27ef59d | |||
| 0ceada8da9 | |||
| f9d29b0c44 | |||
| 409256b784 | |||
| b17178b27a | |||
| e1ceea5674 | |||
| 748d6d4e7a | |||
| e2ea3b31c9 | |||
| 23051e830a | |||
| f15589f3b0 | |||
| 754ca0060f | |||
| c36ced53c9 | |||
| d41c36bf67 | |||
| d9d2904f09 | |||
| 65d2294454 | |||
| 131e3fd814 | |||
| 9d067ab73b | |||
| 2f4162bc47 | |||
| ab1aca94e8 | |||
| d282652561 | |||
| 58216600eb | |||
| 94cbe46511 | |||
| 69b71a6919 | |||
| d742a193e5 | |||
| e4a38eb0e8 | |||
| f07de22576 | |||
| 52c8679760 | |||
| 849b2ecbd2 | |||
| 30528049f1 | |||
| 9a89fb1c9d | |||
| c23cc86c54 | |||
| 171dcd7d74 | |||
| 5aa36e894f | |||
| 9ecd446141 | |||
| fb172d0a92 | |||
| 0085db4596 | |||
| 490d42b5f8 | |||
| 287b302acb | |||
| 5d8ce05b3f | |||
| f83de8e34e | |||
| 9f791535cd | |||
| 51c29ec0c4 | |||
| fbaf040f5e | |||
| e51564d1be | |||
| 98ec799591 | |||
| b6888a158b | |||
| 613513d09f | |||
| 8496112a18 | |||
| 6bc0f13505 | |||
| 8a89da07ba | |||
| f849885a4b | |||
| f7ce7e5faa | |||
| 65141832d2 | |||
| f13dc59416 | |||
| 7c3cb71fa4 | |||
| 68109afcdb | |||
| 9cf3299faf | |||
| b9b554e0f6 | |||
| 0dc5deca1c | |||
| b4c353434f | |||
| 71f70df327 | |||
| 663f83f647 | |||
| ae5b5ba529 | |||
| a585eae6e7 | |||
| d2c2e32e8a | |||
| 8c7c9ea065 | |||
| a6da1472c0 | |||
| 34affe7a63 | |||
| a2195644d8 | |||
| 1ecfbfa1a1 | |||
| e1d8770f12 | |||
| 0f1cd0eba9 | |||
| 127e7a6c89 | |||
| 6f5bd5072d | |||
| 56ec432281 | |||
| 31b8c2d438 | |||
| eb41999461 | |||
| 314c6057b7 | |||
| d39ea8b3ce | |||
| 6298903e35 | |||
| b57574d6fb | |||
| bfcf06d91a | |||
| 0280407fc5 | |||
| ae809e9fd1 | |||
| e96385aded | |||
| 56a165bf0f | |||
| 422ce50d2e | |||
| c33b1728ae | |||
| a304199836 | |||
| 6d7cd31fee | |||
| 993c58fde3 | |||
| d49b288728 | |||
| 69e84805e4 | |||
| 364e569945 | |||
| 63295f1f7f | |||
| 50523b107d | |||
| aa8d4a782d | |||
| efcf24be0c | |||
| 17dbaa8639 | |||
| 9514abc2da | |||
| 0be57b9b6d | |||
| 61a4e64a66 | |||
| 9a6f47f0ed | |||
| 948fb628d9 | |||
| a901c505ab | |||
| 0ddc0f47bd | |||
| cac075a122 | |||
| 9e0a8475cd | |||
| 7ccc6d8290 | |||
| 7288528a1e | |||
| 513559cc47 | |||
| e460752323 | |||
| 92594f0939 | |||
| e8a52281d9 | |||
| 6eb53b7526 | |||
| 9b7987a9d1 | |||
| 28ef7061bb | |||
| 46c3587a6f | |||
| 69c7139ff8 | |||
| 5ff408d218 | |||
| e3c83835e7 | |||
| bd1b87c579 | |||
| d7bb8df841 | |||
| c646e57fd6 | |||
| e0ab13c62f | |||
| e0cbaa50fa | |||
| 3747487320 | |||
| 1e0ad018ce | |||
| 95735bda46 | |||
| d30569c064 | |||
| 2d92102dee | |||
| 490ecfcaa1 | |||
| e174f43807 | |||
| 81f2401c6d | |||
| 508a705c1c | |||
| 6f1c033d72 | |||
| 5f83fb6582 | |||
| 679dc72c08 | |||
| 1499680f9e | |||
| bdcfae2e1c | |||
| 7d526e75a7 | |||
| c12983cf8a | |||
| ba9cd0d25a | |||
| b93f3b00bb | |||
| 4c32d9300c | |||
| 6e285e5392 | |||
| b8cdea0190 | |||
| e592f94a64 | |||
| 6e1aec7a67 | |||
| 6055a039b5 | |||
| 6c0e44464b | |||
| 6a84c32900 | |||
| 6a10f03ff8 | |||
| 7bd1e53753 | |||
| b98d41db99 | |||
| b2a580bdb1 | |||
| 89f6a85f03 | |||
| 6ef366644f | |||
| 03cde80b58 | |||
| 6b2e202df5 | |||
| 40d8832ee0 | |||
| 91dad09f65 | |||
| 4518e5df24 | |||
| 72a094bda7 | |||
| 46b84580d6 | |||
| df13f25948 | |||
| 643188d6e5 | |||
| 3df5624ff4 | |||
| be78aeae4c | |||
| 5bc47fe830 | |||
| 9405472565 | |||
| 45948e7e55 | |||
| b96b0b5abb | |||
| ca13be9af7 | |||
| a1d8eb2743 | |||
| f64a1b175a | |||
| 09b4e527a0 | |||
| 35a28a58b3 | |||
| 223bb04090 | |||
| fe040633a1 | |||
| f645d31573 | |||
| 35b4efc270 | |||
| 0d52913804 | |||
| b80077b8f3 | |||
| e70f275f32 | |||
| 9a37dc0ce6 | |||
| 0eb6aa4013 | |||
| 7f5c31cdca | |||
| 9e6807c3c9 | |||
| 2f22c6bb79 | |||
| 3c0d3c6fbe | |||
| 440a5ee78c | |||
| dc07719b0d | |||
| 9cdf6b7082 | |||
| 3c1d415bd3 | |||
| d36a31e673 | |||
| 024a6071ca | |||
| 4eefef07ab | |||
| 9c28ed05c9 | |||
| 8082906c05 | |||
| d6af81084d | |||
| 4846f7e3bb | |||
| c220b0a5d0 | |||
| 298f383ffc | |||
| 758c1ef445 | |||
| dd6d8db49a | |||
| 1fb4d53925 | |||
| f6aab3ec1f | |||
| be8445d7e4 | |||
| 3d296304ef | |||
| 54f7b46c1e | |||
| e888976bc6 | |||
| 4d46289331 | |||
| 8eca21c2e8 | |||
| 924bed7297 | |||
| 8b7cfee26b | |||
| c1a63c45f8 | |||
| 4487c28ced | |||
| 05ba288049 | |||
| 6b9490bd72 | |||
| e4b02ca8e4 | |||
| 20a9853e02 | |||
| 1d70708a78 | |||
| be73f72fcc | |||
| 3cd9b56ae6 | |||
| d2a9b4ffb8 |
+15
@@ -0,0 +1,15 @@
|
||||
.gitattributes
|
||||
|
||||
*.so
|
||||
*.o
|
||||
*.a
|
||||
|
||||
manual/manual.html
|
||||
|
||||
testes/time.txt
|
||||
testes/time-debug.txt
|
||||
|
||||
testes/libs/all
|
||||
|
||||
temp
|
||||
lua
|
||||
@@ -0,0 +1,7 @@
|
||||
# Lua
|
||||
|
||||
This is the repository of Lua development code, as seen by the Lua team. It contains the full history of all commits but is mirrored irregularly. For complete information about Lua, visit [Lua.org](https://www.lua.org/).
|
||||
|
||||
Please **do not** send pull requests. To report issues, post a message to the [Lua mailing list](https://www.lua.org/lua-l.html).
|
||||
|
||||
Download official Lua releases from [Lua.org](https://www.lua.org/download.html).
|
||||
@@ -1,8 +1,8 @@
|
||||
make -s -j
|
||||
cd testes/libs; make -s
|
||||
cd .. # back to directory 'testes'
|
||||
ulimit -S -s 2000
|
||||
if { ../lua all.lua; } then
|
||||
ulimit -S -s 1000
|
||||
if { ../lua -W all.lua; } then
|
||||
echo -e "\n\n final OK!!!!\n\n"
|
||||
else
|
||||
echo -e "\n\n >>>> BUG!!!!\n\n"
|
||||
|
||||
@@ -39,7 +39,7 @@ const char lua_ident[] =
|
||||
|
||||
|
||||
/*
|
||||
** Test for a valid index.
|
||||
** Test for a valid index (one that is not the 'nilvalue').
|
||||
** '!ttisnil(o)' implies 'o != &G(L)->nilvalue', so it is not needed.
|
||||
** However, it covers the most common cases in a faster way.
|
||||
*/
|
||||
@@ -53,6 +53,10 @@ const char lua_ident[] =
|
||||
#define isupvalue(i) ((i) < LUA_REGISTRYINDEX)
|
||||
|
||||
|
||||
/*
|
||||
** Convert an acceptable index to a pointer to its respective value.
|
||||
** Non-valid indices return the special nil value 'G(L)->nilvalue'.
|
||||
*/
|
||||
static TValue *index2value (lua_State *L, int idx) {
|
||||
CallInfo *ci = L->ci;
|
||||
if (idx > 0) {
|
||||
@@ -70,21 +74,28 @@ static TValue *index2value (lua_State *L, int idx) {
|
||||
else { /* upvalues */
|
||||
idx = LUA_REGISTRYINDEX - idx;
|
||||
api_check(L, idx <= MAXUPVAL + 1, "upvalue index too large");
|
||||
if (ttislcf(s2v(ci->func))) /* light C function? */
|
||||
return &G(L)->nilvalue; /* it has no upvalues */
|
||||
else {
|
||||
if (ttisCclosure(s2v(ci->func))) { /* C closure? */
|
||||
CClosure *func = clCvalue(s2v(ci->func));
|
||||
return (idx <= func->nupvalues) ? &func->upvalue[idx-1] : &G(L)->nilvalue;
|
||||
return (idx <= func->nupvalues) ? &func->upvalue[idx-1]
|
||||
: &G(L)->nilvalue;
|
||||
}
|
||||
else { /* light C function or Lua function (through a hook)?) */
|
||||
api_check(L, ttislcf(s2v(ci->func)), "caller not a C function");
|
||||
return &G(L)->nilvalue; /* no upvalues */
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
static StkId index2stack (lua_State *L, int idx) {
|
||||
|
||||
/*
|
||||
** Convert a valid actual index (not a pseudo-index) to its address.
|
||||
*/
|
||||
l_sinline StkId index2stack (lua_State *L, int idx) {
|
||||
CallInfo *ci = L->ci;
|
||||
if (idx > 0) {
|
||||
StkId o = ci->func + idx;
|
||||
api_check(L, o < L->top, "unacceptable index");
|
||||
api_check(L, o < L->top, "invalid index");
|
||||
return o;
|
||||
}
|
||||
else { /* non-positive index */
|
||||
@@ -97,8 +108,9 @@ static StkId index2stack (lua_State *L, int idx) {
|
||||
|
||||
LUA_API int lua_checkstack (lua_State *L, int n) {
|
||||
int res;
|
||||
CallInfo *ci = L->ci;
|
||||
CallInfo *ci;
|
||||
lua_lock(L);
|
||||
ci = L->ci;
|
||||
api_check(L, n >= 0, "negative 'n'");
|
||||
if (L->stack_last - L->top > n) /* stack large enough? */
|
||||
res = 1; /* yes; check is OK */
|
||||
@@ -170,20 +182,42 @@ LUA_API int lua_gettop (lua_State *L) {
|
||||
|
||||
|
||||
LUA_API void lua_settop (lua_State *L, int idx) {
|
||||
StkId func = L->ci->func;
|
||||
CallInfo *ci;
|
||||
StkId func, newtop;
|
||||
ptrdiff_t diff; /* difference for new top */
|
||||
lua_lock(L);
|
||||
ci = L->ci;
|
||||
func = ci->func;
|
||||
if (idx >= 0) {
|
||||
StkId newtop = (func + 1) + idx;
|
||||
api_check(L, idx <= L->stack_last - (func + 1), "new top too large");
|
||||
while (L->top < newtop)
|
||||
setnilvalue(s2v(L->top++));
|
||||
L->top = newtop;
|
||||
api_check(L, idx <= ci->top - (func + 1), "new top too large");
|
||||
diff = ((func + 1) + idx) - L->top;
|
||||
for (; diff > 0; diff--)
|
||||
setnilvalue(s2v(L->top++)); /* clear new slots */
|
||||
}
|
||||
else {
|
||||
api_check(L, -(idx+1) <= (L->top - (func + 1)), "invalid new top");
|
||||
L->top += idx+1; /* 'subtract' index (index is negative) */
|
||||
diff = idx + 1; /* will "subtract" index (as it is negative) */
|
||||
}
|
||||
luaF_close(L, L->top, LUA_OK);
|
||||
api_check(L, L->tbclist < L->top, "previous pop of an unclosed slot");
|
||||
newtop = L->top + diff;
|
||||
if (diff < 0 && L->tbclist >= newtop) {
|
||||
lua_assert(hastocloseCfunc(ci->nresults));
|
||||
luaF_close(L, newtop, CLOSEKTOP, 0);
|
||||
}
|
||||
L->top = newtop; /* correct top only after closing any upvalue */
|
||||
lua_unlock(L);
|
||||
}
|
||||
|
||||
|
||||
LUA_API void lua_closeslot (lua_State *L, int idx) {
|
||||
StkId level;
|
||||
lua_lock(L);
|
||||
level = index2stack(L, idx);
|
||||
api_check(L, hastocloseCfunc(L->ci->nresults) && L->tbclist == level,
|
||||
"no variable to close at given level");
|
||||
luaF_close(L, level, CLOSEKTOP, 0);
|
||||
level = index2stack(L, idx); /* stack may be moved */
|
||||
setnilvalue(s2v(level));
|
||||
lua_unlock(L);
|
||||
}
|
||||
|
||||
@@ -194,7 +228,7 @@ LUA_API void lua_settop (lua_State *L, int idx) {
|
||||
** Note that we move(copy) only the value inside the stack.
|
||||
** (We do not move additional fields that may exist.)
|
||||
*/
|
||||
static void reverse (lua_State *L, StkId from, StkId to) {
|
||||
l_sinline void reverse (lua_State *L, StkId from, StkId to) {
|
||||
for (; from < to; from++, to--) {
|
||||
TValue temp;
|
||||
setobj(L, &temp, s2v(from));
|
||||
@@ -227,7 +261,7 @@ LUA_API void lua_copy (lua_State *L, int fromidx, int toidx) {
|
||||
lua_lock(L);
|
||||
fr = index2value(L, fromidx);
|
||||
to = index2value(L, toidx);
|
||||
api_check(l, isvalid(L, to), "invalid index");
|
||||
api_check(L, isvalid(L, to), "invalid index");
|
||||
setobj(L, to, fr);
|
||||
if (isupvalue(toidx)) /* function upvalue? */
|
||||
luaC_barrier(L, clCvalue(s2v(L->ci->func)), fr);
|
||||
@@ -259,7 +293,7 @@ LUA_API int lua_type (lua_State *L, int idx) {
|
||||
|
||||
LUA_API const char *lua_typename (lua_State *L, int t) {
|
||||
UNUSED(L);
|
||||
api_check(L, LUA_TNONE <= t && t < LUA_NUMTAGS, "invalid tag");
|
||||
api_check(L, LUA_TNONE <= t && t < LUA_NUMTYPES, "invalid type");
|
||||
return ttypename(t);
|
||||
}
|
||||
|
||||
@@ -347,23 +381,21 @@ LUA_API size_t lua_stringtonumber (lua_State *L, const char *s) {
|
||||
|
||||
|
||||
LUA_API lua_Number lua_tonumberx (lua_State *L, int idx, int *pisnum) {
|
||||
lua_Number n;
|
||||
lua_Number n = 0;
|
||||
const TValue *o = index2value(L, idx);
|
||||
int isnum = tonumber(o, &n);
|
||||
if (!isnum)
|
||||
n = 0; /* call to 'tonumber' may change 'n' even if it fails */
|
||||
if (pisnum) *pisnum = isnum;
|
||||
if (pisnum)
|
||||
*pisnum = isnum;
|
||||
return n;
|
||||
}
|
||||
|
||||
|
||||
LUA_API lua_Integer lua_tointegerx (lua_State *L, int idx, int *pisnum) {
|
||||
lua_Integer res;
|
||||
lua_Integer res = 0;
|
||||
const TValue *o = index2value(L, idx);
|
||||
int isnum = tointeger(o, &res);
|
||||
if (!isnum)
|
||||
res = 0; /* call to 'tointeger' may change 'n' even if it fails */
|
||||
if (pisnum) *pisnum = isnum;
|
||||
if (pisnum)
|
||||
*pisnum = isnum;
|
||||
return res;
|
||||
}
|
||||
|
||||
@@ -375,20 +407,22 @@ LUA_API int lua_toboolean (lua_State *L, int idx) {
|
||||
|
||||
|
||||
LUA_API const char *lua_tolstring (lua_State *L, int idx, size_t *len) {
|
||||
TValue *o = index2value(L, idx);
|
||||
TValue *o;
|
||||
lua_lock(L);
|
||||
o = index2value(L, idx);
|
||||
if (!ttisstring(o)) {
|
||||
if (!cvt2str(o)) { /* not convertible? */
|
||||
if (len != NULL) *len = 0;
|
||||
lua_unlock(L);
|
||||
return NULL;
|
||||
}
|
||||
lua_lock(L); /* 'luaO_tostring' may create a new string */
|
||||
luaO_tostring(L, o);
|
||||
luaC_checkGC(L);
|
||||
o = index2value(L, idx); /* previous call may reallocate the stack */
|
||||
lua_unlock(L);
|
||||
}
|
||||
if (len != NULL)
|
||||
*len = vslen(o);
|
||||
lua_unlock(L);
|
||||
return svalue(o);
|
||||
}
|
||||
|
||||
@@ -396,10 +430,10 @@ LUA_API const char *lua_tolstring (lua_State *L, int idx, size_t *len) {
|
||||
LUA_API lua_Unsigned lua_rawlen (lua_State *L, int idx) {
|
||||
const TValue *o = index2value(L, idx);
|
||||
switch (ttypetag(o)) {
|
||||
case LUA_TSHRSTR: return tsvalue(o)->shrlen;
|
||||
case LUA_TLNGSTR: return tsvalue(o)->u.lnglen;
|
||||
case LUA_TUSERDATA: return uvalue(o)->len;
|
||||
case LUA_TTABLE: return luaH_getn(hvalue(o));
|
||||
case LUA_VSHRSTR: return tsvalue(o)->shrlen;
|
||||
case LUA_VLNGSTR: return tsvalue(o)->u.lnglen;
|
||||
case LUA_VUSERDATA: return uvalue(o)->len;
|
||||
case LUA_VTABLE: return luaH_getn(hvalue(o));
|
||||
default: return 0;
|
||||
}
|
||||
}
|
||||
@@ -414,7 +448,7 @@ LUA_API lua_CFunction lua_tocfunction (lua_State *L, int idx) {
|
||||
}
|
||||
|
||||
|
||||
static void *touserdata (const TValue *o) {
|
||||
l_sinline void *touserdata (const TValue *o) {
|
||||
switch (ttype(o)) {
|
||||
case LUA_TUSERDATA: return getudatamem(uvalue(o));
|
||||
case LUA_TLIGHTUSERDATA: return pvalue(o);
|
||||
@@ -445,8 +479,8 @@ LUA_API lua_State *lua_tothread (lua_State *L, int idx) {
|
||||
LUA_API const void *lua_topointer (lua_State *L, int idx) {
|
||||
const TValue *o = index2value(L, idx);
|
||||
switch (ttypetag(o)) {
|
||||
case LUA_TLCF: return cast_voidp(cast_sizet(fvalue(o)));
|
||||
case LUA_TUSERDATA: case LUA_TLIGHTUSERDATA:
|
||||
case LUA_VLCF: return cast_voidp(cast_sizet(fvalue(o)));
|
||||
case LUA_VUSERDATA: case LUA_VLIGHTUSERDATA:
|
||||
return touserdata(o);
|
||||
default: {
|
||||
if (iscollectable(o))
|
||||
@@ -562,6 +596,7 @@ LUA_API void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n) {
|
||||
while (n--) {
|
||||
setobj2n(L, &cl->upvalue[n], s2v(L->top + n));
|
||||
/* does not need barrier because closure is white */
|
||||
lua_assert(iswhite(cl));
|
||||
}
|
||||
setclCvalue(L, s2v(L->top), cl);
|
||||
api_incr_top(L);
|
||||
@@ -573,7 +608,10 @@ LUA_API void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n) {
|
||||
|
||||
LUA_API void lua_pushboolean (lua_State *L, int b) {
|
||||
lua_lock(L);
|
||||
setbvalue(s2v(L->top), (b != 0)); /* ensure that true is 1 */
|
||||
if (b)
|
||||
setbtvalue(s2v(L->top));
|
||||
else
|
||||
setbfvalue(s2v(L->top));
|
||||
api_incr_top(L);
|
||||
lua_unlock(L);
|
||||
}
|
||||
@@ -602,7 +640,7 @@ LUA_API int lua_pushthread (lua_State *L) {
|
||||
*/
|
||||
|
||||
|
||||
static int auxgetstr (lua_State *L, const TValue *t, const char *k) {
|
||||
l_sinline int auxgetstr (lua_State *L, const TValue *t, const char *k) {
|
||||
const TValue *slot;
|
||||
TString *str = luaS_new(L, k);
|
||||
if (luaV_fastget(L, t, str, slot, luaH_getstr)) {
|
||||
@@ -619,10 +657,21 @@ static int auxgetstr (lua_State *L, const TValue *t, const char *k) {
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** Get the global table in the registry. Since all predefined
|
||||
** indices in the registry were inserted right when the registry
|
||||
** was created and never removed, they must always be in the array
|
||||
** part of the registry.
|
||||
*/
|
||||
#define getGtable(L) \
|
||||
(&hvalue(&G(L)->l_registry)->array[LUA_RIDX_GLOBALS - 1])
|
||||
|
||||
|
||||
LUA_API int lua_getglobal (lua_State *L, const char *name) {
|
||||
Table *reg = hvalue(&G(L)->l_registry);
|
||||
const TValue *G;
|
||||
lua_lock(L);
|
||||
return auxgetstr(L, luaH_getint(reg, LUA_RIDX_GLOBALS), name);
|
||||
G = getGtable(L);
|
||||
return auxgetstr(L, G, name);
|
||||
}
|
||||
|
||||
|
||||
@@ -666,7 +715,7 @@ LUA_API int lua_geti (lua_State *L, int idx, lua_Integer n) {
|
||||
}
|
||||
|
||||
|
||||
static int finishrawget (lua_State *L, const TValue *val) {
|
||||
l_sinline int finishrawget (lua_State *L, const TValue *val) {
|
||||
if (isempty(val)) /* avoid copying empty items to the stack */
|
||||
setnilvalue(s2v(L->top));
|
||||
else
|
||||
@@ -800,9 +849,10 @@ static void auxsetstr (lua_State *L, const TValue *t, const char *k) {
|
||||
|
||||
|
||||
LUA_API void lua_setglobal (lua_State *L, const char *name) {
|
||||
Table *reg = hvalue(&G(L)->l_registry);
|
||||
const TValue *G;
|
||||
lua_lock(L); /* unlock done in 'auxsetstr' */
|
||||
auxsetstr(L, luaH_getint(reg, LUA_RIDX_GLOBALS), name);
|
||||
G = getGtable(L);
|
||||
auxsetstr(L, G, name);
|
||||
}
|
||||
|
||||
|
||||
@@ -847,21 +897,31 @@ LUA_API void lua_seti (lua_State *L, int idx, lua_Integer n) {
|
||||
}
|
||||
|
||||
|
||||
LUA_API void lua_rawset (lua_State *L, int idx) {
|
||||
static void aux_rawset (lua_State *L, int idx, TValue *key, int n) {
|
||||
Table *t;
|
||||
TValue *slot;
|
||||
lua_lock(L);
|
||||
api_checknelems(L, 2);
|
||||
api_checknelems(L, n);
|
||||
t = gettable(L, idx);
|
||||
slot = luaH_set(L, t, s2v(L->top - 2));
|
||||
setobj2t(L, slot, s2v(L->top - 1));
|
||||
luaH_set(L, t, key, s2v(L->top - 1));
|
||||
invalidateTMcache(t);
|
||||
luaC_barrierback(L, obj2gco(t), s2v(L->top - 1));
|
||||
L->top -= 2;
|
||||
L->top -= n;
|
||||
lua_unlock(L);
|
||||
}
|
||||
|
||||
|
||||
LUA_API void lua_rawset (lua_State *L, int idx) {
|
||||
aux_rawset(L, idx, s2v(L->top - 2), 2);
|
||||
}
|
||||
|
||||
|
||||
LUA_API void lua_rawsetp (lua_State *L, int idx, const void *p) {
|
||||
TValue k;
|
||||
setpvalue(&k, cast_voidp(p));
|
||||
aux_rawset(L, idx, &k, 1);
|
||||
}
|
||||
|
||||
|
||||
LUA_API void lua_rawseti (lua_State *L, int idx, lua_Integer n) {
|
||||
Table *t;
|
||||
lua_lock(L);
|
||||
@@ -874,21 +934,6 @@ LUA_API void lua_rawseti (lua_State *L, int idx, lua_Integer n) {
|
||||
}
|
||||
|
||||
|
||||
LUA_API void lua_rawsetp (lua_State *L, int idx, const void *p) {
|
||||
Table *t;
|
||||
TValue k, *slot;
|
||||
lua_lock(L);
|
||||
api_checknelems(L, 1);
|
||||
t = gettable(L, idx);
|
||||
setpvalue(&k, cast_voidp(p));
|
||||
slot = luaH_set(L, t, &k);
|
||||
setobj2t(L, slot, s2v(L->top - 1));
|
||||
luaC_barrierback(L, obj2gco(t), s2v(L->top - 1));
|
||||
L->top--;
|
||||
lua_unlock(L);
|
||||
}
|
||||
|
||||
|
||||
LUA_API int lua_setmetatable (lua_State *L, int objindex) {
|
||||
TValue *obj;
|
||||
Table *mt;
|
||||
@@ -1054,8 +1099,7 @@ LUA_API int lua_load (lua_State *L, lua_Reader reader, void *data,
|
||||
LClosure *f = clLvalue(s2v(L->top - 1)); /* get newly created function */
|
||||
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);
|
||||
const TValue *gt = getGtable(L);
|
||||
/* set global table as 1st upvalue of 'f' (may be LUA_ENV) */
|
||||
setobj(L, f->upvals[0]->v, gt);
|
||||
luaC_barrier(L, f->upvals[0], gt);
|
||||
@@ -1093,16 +1137,18 @@ LUA_API int lua_gc (lua_State *L, int what, ...) {
|
||||
va_list argp;
|
||||
int res = 0;
|
||||
global_State *g = G(L);
|
||||
if (g->gcstp & GCSTPGC) /* internal stop? */
|
||||
return -1; /* all options are invalid when stopped */
|
||||
lua_lock(L);
|
||||
va_start(argp, what);
|
||||
switch (what) {
|
||||
case LUA_GCSTOP: {
|
||||
g->gcrunning = 0;
|
||||
g->gcstp = GCSTPUSR; /* stopped by the user */
|
||||
break;
|
||||
}
|
||||
case LUA_GCRESTART: {
|
||||
luaE_setdebt(g, 0);
|
||||
g->gcrunning = 1;
|
||||
g->gcstp = 0; /* (GCSTPGC must be already zero here) */
|
||||
break;
|
||||
}
|
||||
case LUA_GCCOLLECT: {
|
||||
@@ -1121,8 +1167,8 @@ LUA_API int lua_gc (lua_State *L, int what, ...) {
|
||||
case LUA_GCSTEP: {
|
||||
int data = va_arg(argp, int);
|
||||
l_mem debt = 1; /* =1 to signal that it did an actual step */
|
||||
lu_byte oldrunning = g->gcrunning;
|
||||
g->gcrunning = 1; /* allow GC to run */
|
||||
lu_byte oldstp = g->gcstp;
|
||||
g->gcstp = 0; /* allow GC to run (GCSTPGC must be zero here) */
|
||||
if (data == 0) {
|
||||
luaE_setdebt(g, 0); /* do a basic step */
|
||||
luaC_step(L);
|
||||
@@ -1132,7 +1178,7 @@ LUA_API int lua_gc (lua_State *L, int what, ...) {
|
||||
luaE_setdebt(g, debt);
|
||||
luaC_checkGC(L);
|
||||
}
|
||||
g->gcrunning = oldrunning; /* restore previous state */
|
||||
g->gcstp = oldstp; /* restore previous state */
|
||||
if (debt > 0 && g->gcstate == GCSpause) /* end of cycle? */
|
||||
res = 1; /* signal it */
|
||||
break;
|
||||
@@ -1150,7 +1196,7 @@ LUA_API int lua_gc (lua_State *L, int what, ...) {
|
||||
break;
|
||||
}
|
||||
case LUA_GCISRUNNING: {
|
||||
res = g->gcrunning;
|
||||
res = gcrunning(g);
|
||||
break;
|
||||
}
|
||||
case LUA_GCGEN: {
|
||||
@@ -1193,9 +1239,15 @@ LUA_API int lua_gc (lua_State *L, int what, ...) {
|
||||
|
||||
|
||||
LUA_API int lua_error (lua_State *L) {
|
||||
TValue *errobj;
|
||||
lua_lock(L);
|
||||
errobj = s2v(L->top - 1);
|
||||
api_checknelems(L, 1);
|
||||
luaG_errormsg(L);
|
||||
/* error object is the memory error message? */
|
||||
if (ttisshrstring(errobj) && eqshrstr(tsvalue(errobj), G(L)->memerrmsg))
|
||||
luaM_error(L); /* raise a memory error */
|
||||
else
|
||||
luaG_errormsg(L); /* raise a regular error */
|
||||
/* code unreachable; will unlock when control actually leaves the kernel */
|
||||
return 0; /* to avoid warnings */
|
||||
}
|
||||
@@ -1224,8 +1276,7 @@ LUA_API void lua_toclose (lua_State *L, int idx) {
|
||||
lua_lock(L);
|
||||
o = index2stack(L, idx);
|
||||
nresults = L->ci->nresults;
|
||||
api_check(L, L->openupval == NULL || uplevel(L->openupval) <= o,
|
||||
"marked index below or equal new one");
|
||||
api_check(L, L->tbclist < o, "given index below or equal a marked one");
|
||||
luaF_newtbcupval(L, o); /* create new to-be-closed upvalue */
|
||||
if (!hastocloseCfunc(nresults)) /* function not marked yet? */
|
||||
L->ci->nresults = codeNresults(nresults); /* mark it */
|
||||
@@ -1237,14 +1288,12 @@ LUA_API void lua_toclose (lua_State *L, int idx) {
|
||||
LUA_API void lua_concat (lua_State *L, int n) {
|
||||
lua_lock(L);
|
||||
api_checknelems(L, n);
|
||||
if (n >= 2) {
|
||||
if (n > 0)
|
||||
luaV_concat(L, n);
|
||||
}
|
||||
else if (n == 0) { /* push empty string */
|
||||
setsvalue2s(L, L->top, luaS_newlstr(L, "", 0));
|
||||
else { /* nothing to concatenate */
|
||||
setsvalue2s(L, L->top, luaS_newlstr(L, "", 0)); /* push empty string */
|
||||
api_incr_top(L);
|
||||
}
|
||||
/* else n == 1; nothing to do */
|
||||
luaC_checkGC(L);
|
||||
lua_unlock(L);
|
||||
}
|
||||
@@ -1311,7 +1360,7 @@ LUA_API void *lua_newuserdatauv (lua_State *L, size_t size, int nuvalue) {
|
||||
static const char *aux_upvalue (TValue *fi, int n, TValue **val,
|
||||
GCObject **owner) {
|
||||
switch (ttypetag(fi)) {
|
||||
case LUA_TCCL: { /* C closure */
|
||||
case LUA_VCCL: { /* C closure */
|
||||
CClosure *f = clCvalue(fi);
|
||||
if (!(cast_uint(n) - 1u < cast_uint(f->nupvalues)))
|
||||
return NULL; /* 'n' not in [1, f->nupvalues] */
|
||||
@@ -1319,7 +1368,7 @@ static const char *aux_upvalue (TValue *fi, int n, TValue **val,
|
||||
if (owner) *owner = obj2gco(f);
|
||||
return "";
|
||||
}
|
||||
case LUA_TLCL: { /* Lua closure */
|
||||
case LUA_VLCL: { /* Lua closure */
|
||||
LClosure *f = clLvalue(fi);
|
||||
TString *name;
|
||||
Proto *p = f->p;
|
||||
@@ -1369,29 +1418,35 @@ LUA_API const char *lua_setupvalue (lua_State *L, int funcindex, int n) {
|
||||
|
||||
|
||||
static UpVal **getupvalref (lua_State *L, int fidx, int n, LClosure **pf) {
|
||||
static const UpVal *const nullup = NULL;
|
||||
LClosure *f;
|
||||
TValue *fi = index2value(L, fidx);
|
||||
api_check(L, ttisLclosure(fi), "Lua function expected");
|
||||
f = clLvalue(fi);
|
||||
api_check(L, (1 <= n && n <= f->p->sizeupvalues), "invalid upvalue index");
|
||||
if (pf) *pf = f;
|
||||
return &f->upvals[n - 1]; /* get its upvalue pointer */
|
||||
if (1 <= n && n <= f->p->sizeupvalues)
|
||||
return &f->upvals[n - 1]; /* get its upvalue pointer */
|
||||
else
|
||||
return (UpVal**)&nullup;
|
||||
}
|
||||
|
||||
|
||||
LUA_API void *lua_upvalueid (lua_State *L, int fidx, int n) {
|
||||
TValue *fi = index2value(L, fidx);
|
||||
switch (ttypetag(fi)) {
|
||||
case LUA_TLCL: { /* lua closure */
|
||||
case LUA_VLCL: { /* lua closure */
|
||||
return *getupvalref(L, fidx, n, NULL);
|
||||
}
|
||||
case LUA_TCCL: { /* C closure */
|
||||
case LUA_VCCL: { /* C closure */
|
||||
CClosure *f = clCvalue(fi);
|
||||
api_check(L, 1 <= n && n <= f->nupvalues, "invalid upvalue index");
|
||||
return &f->upvalue[n - 1];
|
||||
}
|
||||
if (1 <= n && n <= f->nupvalues)
|
||||
return &f->upvalue[n - 1];
|
||||
/* else */
|
||||
} /* FALLTHROUGH */
|
||||
case LUA_VLCF:
|
||||
return NULL; /* light C functions have no upvalues */
|
||||
default: {
|
||||
api_check(L, 0, "closure expected");
|
||||
api_check(L, 0, "function expected");
|
||||
return NULL;
|
||||
}
|
||||
}
|
||||
@@ -1403,6 +1458,7 @@ LUA_API void lua_upvaluejoin (lua_State *L, int fidx1, int n1,
|
||||
LClosure *f1;
|
||||
UpVal **up1 = getupvalref(L, fidx1, n1, &f1);
|
||||
UpVal **up2 = getupvalref(L, fidx2, n2, NULL);
|
||||
api_check(L, *up1 != NULL && *up2 != NULL, "invalid upvalue index");
|
||||
*up1 = *up2;
|
||||
luaC_objbarrier(L, f1, *up1);
|
||||
}
|
||||
|
||||
@@ -11,12 +11,22 @@
|
||||
#include "llimits.h"
|
||||
#include "lstate.h"
|
||||
|
||||
|
||||
/* Increments 'L->top', checking for stack overflows */
|
||||
#define api_incr_top(L) {L->top++; api_check(L, L->top <= L->ci->top, \
|
||||
"stack overflow");}
|
||||
|
||||
|
||||
/*
|
||||
** If a call returns too many multiple returns, the callee may not have
|
||||
** stack space to accommodate all results. In this case, this macro
|
||||
** increases its stack space ('L->ci->top').
|
||||
*/
|
||||
#define adjustresults(L,nres) \
|
||||
{ if ((nres) <= LUA_MULTRET && L->ci->top < L->top) L->ci->top = L->top; }
|
||||
|
||||
|
||||
/* Ensure the stack has at least 'n' elements */
|
||||
#define api_checknelems(L,n) api_check(L, (n) < (L->top - L->ci->func), \
|
||||
"not enough elements in the stack")
|
||||
|
||||
@@ -32,6 +42,8 @@
|
||||
|
||||
#define hastocloseCfunc(n) ((n) < LUA_MULTRET)
|
||||
|
||||
/* Map [-1, inf) (range of 'nresults') into (-inf, -2] */
|
||||
#define codeNresults(n) (-(n) - 3)
|
||||
#define decodeNresults(n) (-(n) - 3)
|
||||
|
||||
#endif
|
||||
|
||||
@@ -62,7 +62,7 @@ static int findfield (lua_State *L, int objidx, int level) {
|
||||
else if (findfield(L, objidx, level - 1)) { /* try recursively */
|
||||
/* stack: lib_name, lib_table, field_name (top) */
|
||||
lua_pushliteral(L, "."); /* place '.' between the two names */
|
||||
lua_replace(L, -3); /* (in the slot ocupied by table) */
|
||||
lua_replace(L, -3); /* (in the slot occupied by table) */
|
||||
lua_concat(L, 3); /* lib_name.field_name */
|
||||
return 1;
|
||||
}
|
||||
@@ -87,7 +87,7 @@ static int pushglobalfuncname (lua_State *L, lua_Debug *ar) {
|
||||
lua_remove(L, -2); /* remove original name */
|
||||
}
|
||||
lua_copy(L, -1, top + 1); /* copy name to proper place */
|
||||
lua_settop(L, top + 1); /* remove table "loaded" an name copy */
|
||||
lua_settop(L, top + 1); /* remove table "loaded" and name copy */
|
||||
return 1;
|
||||
}
|
||||
else {
|
||||
@@ -190,7 +190,7 @@ LUALIB_API int luaL_argerror (lua_State *L, int arg, const char *extramsg) {
|
||||
}
|
||||
|
||||
|
||||
int luaL_typeerror (lua_State *L, int arg, const char *tname) {
|
||||
LUALIB_API int luaL_typeerror (lua_State *L, int arg, const char *tname) {
|
||||
const char *msg;
|
||||
const char *typearg; /* name for the type of the actual argument */
|
||||
if (luaL_getmetafield(L, arg, "__name") == LUA_TSTRING)
|
||||
@@ -249,7 +249,7 @@ LUALIB_API int luaL_fileresult (lua_State *L, int stat, const char *fname) {
|
||||
return 1;
|
||||
}
|
||||
else {
|
||||
lua_pushnil(L);
|
||||
luaL_pushfail(L);
|
||||
if (fname)
|
||||
lua_pushfstring(L, "%s: %s", fname, strerror(en));
|
||||
else
|
||||
@@ -283,18 +283,18 @@ LUALIB_API int luaL_fileresult (lua_State *L, int stat, const char *fname) {
|
||||
|
||||
|
||||
LUALIB_API int luaL_execresult (lua_State *L, int stat) {
|
||||
const char *what = "exit"; /* type of termination */
|
||||
if (stat == -1) /* error? */
|
||||
if (stat != 0 && errno != 0) /* error with an 'errno'? */
|
||||
return luaL_fileresult(L, 0, NULL);
|
||||
else {
|
||||
const char *what = "exit"; /* type of termination */
|
||||
l_inspectstat(stat, what); /* interpret result */
|
||||
if (*what == 'e' && stat == 0) /* successful termination? */
|
||||
lua_pushboolean(L, 1);
|
||||
else
|
||||
lua_pushnil(L);
|
||||
luaL_pushfail(L);
|
||||
lua_pushstring(L, what);
|
||||
lua_pushinteger(L, stat);
|
||||
return 3; /* return true/nil,what,code */
|
||||
return 3; /* return true/fail,what,code */
|
||||
}
|
||||
}
|
||||
|
||||
@@ -378,7 +378,7 @@ LUALIB_API int luaL_checkoption (lua_State *L, int arg, const char *def,
|
||||
** but without 'msg'.)
|
||||
*/
|
||||
LUALIB_API void luaL_checkstack (lua_State *L, int space, const char *msg) {
|
||||
if (!lua_checkstack(L, space)) {
|
||||
if (l_unlikely(!lua_checkstack(L, space))) {
|
||||
if (msg)
|
||||
luaL_error(L, "stack overflow (%s)", msg);
|
||||
else
|
||||
@@ -388,20 +388,20 @@ LUALIB_API void luaL_checkstack (lua_State *L, int space, const char *msg) {
|
||||
|
||||
|
||||
LUALIB_API void luaL_checktype (lua_State *L, int arg, int t) {
|
||||
if (lua_type(L, arg) != t)
|
||||
if (l_unlikely(lua_type(L, arg) != t))
|
||||
tag_error(L, arg, t);
|
||||
}
|
||||
|
||||
|
||||
LUALIB_API void luaL_checkany (lua_State *L, int arg) {
|
||||
if (lua_type(L, arg) == LUA_TNONE)
|
||||
if (l_unlikely(lua_type(L, arg) == LUA_TNONE))
|
||||
luaL_argerror(L, arg, "value expected");
|
||||
}
|
||||
|
||||
|
||||
LUALIB_API const char *luaL_checklstring (lua_State *L, int arg, size_t *len) {
|
||||
const char *s = lua_tolstring(L, arg, len);
|
||||
if (!s) tag_error(L, arg, LUA_TSTRING);
|
||||
if (l_unlikely(!s)) tag_error(L, arg, LUA_TSTRING);
|
||||
return s;
|
||||
}
|
||||
|
||||
@@ -420,7 +420,7 @@ LUALIB_API const char *luaL_optlstring (lua_State *L, int arg,
|
||||
LUALIB_API lua_Number luaL_checknumber (lua_State *L, int arg) {
|
||||
int isnum;
|
||||
lua_Number d = lua_tonumberx(L, arg, &isnum);
|
||||
if (!isnum)
|
||||
if (l_unlikely(!isnum))
|
||||
tag_error(L, arg, LUA_TNUMBER);
|
||||
return d;
|
||||
}
|
||||
@@ -442,7 +442,7 @@ static void interror (lua_State *L, int arg) {
|
||||
LUALIB_API lua_Integer luaL_checkinteger (lua_State *L, int arg) {
|
||||
int isnum;
|
||||
lua_Integer d = lua_tointegerx(L, arg, &isnum);
|
||||
if (!isnum) {
|
||||
if (l_unlikely(!isnum)) {
|
||||
interror(L, arg);
|
||||
}
|
||||
return d;
|
||||
@@ -475,8 +475,10 @@ static void *resizebox (lua_State *L, int idx, size_t newsize) {
|
||||
lua_Alloc allocf = lua_getallocf(L, &ud);
|
||||
UBox *box = (UBox *)lua_touserdata(L, idx);
|
||||
void *temp = allocf(ud, box->box, box->bsize, newsize);
|
||||
if (temp == NULL && newsize > 0) /* allocation error? */
|
||||
luaL_error(L, "not enough memory for buffer allocation");
|
||||
if (l_unlikely(temp == NULL && newsize > 0)) { /* allocation error? */
|
||||
lua_pushliteral(L, "not enough memory");
|
||||
lua_error(L); /* raise a memory error */
|
||||
}
|
||||
box->box = temp;
|
||||
box->bsize = newsize;
|
||||
return temp;
|
||||
@@ -513,13 +515,22 @@ static void newbox (lua_State *L) {
|
||||
#define buffonstack(B) ((B)->b != (B)->init.b)
|
||||
|
||||
|
||||
/*
|
||||
** Whenever buffer is accessed, slot 'idx' must either be a box (which
|
||||
** cannot be NULL) or it is a placeholder for the buffer.
|
||||
*/
|
||||
#define checkbufferlevel(B,idx) \
|
||||
lua_assert(buffonstack(B) ? lua_touserdata(B->L, idx) != NULL \
|
||||
: lua_touserdata(B->L, idx) == (void*)B)
|
||||
|
||||
|
||||
/*
|
||||
** Compute new size for buffer 'B', enough to accommodate extra 'sz'
|
||||
** bytes.
|
||||
*/
|
||||
static size_t newbuffsize (luaL_Buffer *B, size_t sz) {
|
||||
size_t newsize = B->size * 2; /* double buffer size */
|
||||
if (MAX_SIZET - sz < B->n) /* overflow in (B->n + sz)? */
|
||||
if (l_unlikely(MAX_SIZET - sz < B->n)) /* overflow in (B->n + sz)? */
|
||||
return luaL_error(B->L, "buffer too large");
|
||||
if (newsize < B->n + sz) /* double is not big enough? */
|
||||
newsize = B->n + sz;
|
||||
@@ -529,10 +540,11 @@ static size_t newbuffsize (luaL_Buffer *B, size_t sz) {
|
||||
|
||||
/*
|
||||
** Returns a pointer to a free area with at least 'sz' bytes in buffer
|
||||
** 'B'. 'boxidx' is the relative position in the stack where the
|
||||
** buffer's box is or should be.
|
||||
** 'B'. 'boxidx' is the relative position in the stack where is the
|
||||
** buffer's box or its placeholder.
|
||||
*/
|
||||
static char *prepbuffsize (luaL_Buffer *B, size_t sz, int boxidx) {
|
||||
checkbufferlevel(B, boxidx);
|
||||
if (B->size - B->n >= sz) /* enough space? */
|
||||
return B->b + B->n;
|
||||
else {
|
||||
@@ -543,10 +555,9 @@ static char *prepbuffsize (luaL_Buffer *B, size_t sz, int boxidx) {
|
||||
if (buffonstack(B)) /* buffer already has a box? */
|
||||
newbuff = (char *)resizebox(L, boxidx, newsize); /* resize it */
|
||||
else { /* no box yet */
|
||||
lua_pushnil(L); /* reserve slot for final result */
|
||||
lua_remove(L, boxidx); /* remove placeholder */
|
||||
newbox(L); /* create a new box */
|
||||
/* move box (and slot) to its intended position */
|
||||
lua_rotate(L, boxidx - 1, 2);
|
||||
lua_insert(L, boxidx); /* move box to its intended position */
|
||||
lua_toclose(L, boxidx);
|
||||
newbuff = (char *)resizebox(L, boxidx, newsize);
|
||||
memcpy(newbuff, B->b, B->n * sizeof(char)); /* copy original content */
|
||||
@@ -581,11 +592,11 @@ LUALIB_API void luaL_addstring (luaL_Buffer *B, const char *s) {
|
||||
|
||||
LUALIB_API void luaL_pushresult (luaL_Buffer *B) {
|
||||
lua_State *L = B->L;
|
||||
checkbufferlevel(B, -1);
|
||||
lua_pushlstring(L, B->b, B->n);
|
||||
if (buffonstack(B)) {
|
||||
lua_copy(L, -1, -3); /* move string to reserved slot */
|
||||
lua_pop(L, 2); /* pop string and box (closing the box) */
|
||||
}
|
||||
if (buffonstack(B))
|
||||
lua_closeslot(L, -2); /* close the box */
|
||||
lua_remove(L, -2); /* remove box or placeholder from the stack */
|
||||
}
|
||||
|
||||
|
||||
@@ -620,6 +631,7 @@ LUALIB_API void luaL_buffinit (lua_State *L, luaL_Buffer *B) {
|
||||
B->b = B->init.b;
|
||||
B->n = 0;
|
||||
B->size = LUAL_BUFFERSIZE;
|
||||
lua_pushlightuserdata(L, (void*)B); /* push placeholder */
|
||||
}
|
||||
|
||||
|
||||
@@ -637,10 +649,14 @@ LUALIB_API char *luaL_buffinitsize (lua_State *L, luaL_Buffer *B, size_t sz) {
|
||||
** =======================================================
|
||||
*/
|
||||
|
||||
/* index of free-list header */
|
||||
#define freelist 0
|
||||
|
||||
/* index of free-list header (after the predefined values) */
|
||||
#define freelist (LUA_RIDX_LAST + 1)
|
||||
|
||||
/*
|
||||
** The previously freed references form a linked list:
|
||||
** t[freelist] is the index of a first free index, or zero if list is
|
||||
** empty; t[t[freelist]] is the index of the second element; etc.
|
||||
*/
|
||||
LUALIB_API int luaL_ref (lua_State *L, int t) {
|
||||
int ref;
|
||||
if (lua_isnil(L, -1)) {
|
||||
@@ -648,9 +664,16 @@ LUALIB_API int luaL_ref (lua_State *L, int t) {
|
||||
return LUA_REFNIL; /* 'nil' has a unique fixed reference */
|
||||
}
|
||||
t = lua_absindex(L, t);
|
||||
lua_rawgeti(L, t, freelist); /* get first free element */
|
||||
ref = (int)lua_tointeger(L, -1); /* ref = t[freelist] */
|
||||
lua_pop(L, 1); /* remove it from stack */
|
||||
if (lua_rawgeti(L, t, freelist) == LUA_TNIL) { /* first access? */
|
||||
ref = 0; /* list is empty */
|
||||
lua_pushinteger(L, 0); /* initialize as an empty list */
|
||||
lua_rawseti(L, t, freelist); /* ref = t[freelist] = 0 */
|
||||
}
|
||||
else { /* already initialized */
|
||||
lua_assert(lua_isinteger(L, -1));
|
||||
ref = (int)lua_tointeger(L, -1); /* ref = t[freelist] */
|
||||
}
|
||||
lua_pop(L, 1); /* remove element from stack */
|
||||
if (ref != 0) { /* any free element? */
|
||||
lua_rawgeti(L, t, ref); /* remove it from list */
|
||||
lua_rawseti(L, t, freelist); /* (t[freelist] = t[ref]) */
|
||||
@@ -666,6 +689,7 @@ LUALIB_API void luaL_unref (lua_State *L, int t, int ref) {
|
||||
if (ref >= 0) {
|
||||
t = lua_absindex(L, t);
|
||||
lua_rawgeti(L, t, freelist);
|
||||
lua_assert(lua_isinteger(L, -1));
|
||||
lua_rawseti(L, t, ref); /* t[ref] = t[freelist] */
|
||||
lua_pushinteger(L, ref);
|
||||
lua_rawseti(L, t, freelist); /* t[freelist] = ref */
|
||||
@@ -849,7 +873,7 @@ LUALIB_API lua_Integer luaL_len (lua_State *L, int idx) {
|
||||
int isnum;
|
||||
lua_len(L, idx);
|
||||
l = lua_tointegerx(L, -1, &isnum);
|
||||
if (!isnum)
|
||||
if (l_unlikely(!isnum))
|
||||
luaL_error(L, "object length is not an integer");
|
||||
lua_pop(L, 1); /* remove object */
|
||||
return l;
|
||||
@@ -857,6 +881,7 @@ LUALIB_API lua_Integer luaL_len (lua_State *L, int idx) {
|
||||
|
||||
|
||||
LUALIB_API const char *luaL_tolstring (lua_State *L, int idx, size_t *len) {
|
||||
idx = lua_absindex(L,idx);
|
||||
if (luaL_callmeta(L, idx, "__tostring")) { /* metafield? */
|
||||
if (!lua_isstring(L, -1))
|
||||
luaL_error(L, "'__tostring' must return a string");
|
||||
@@ -902,10 +927,10 @@ LUALIB_API const char *luaL_tolstring (lua_State *L, int idx, size_t *len) {
|
||||
LUALIB_API void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup) {
|
||||
luaL_checkstack(L, nup, "too many upvalues");
|
||||
for (; l->name != NULL; l++) { /* fill the table with given functions */
|
||||
int i;
|
||||
if (l->func == NULL) /* place holder? */
|
||||
lua_pushboolean(L, 0);
|
||||
else {
|
||||
int i;
|
||||
for (i = 0; i < nup; i++) /* copy upvalues to the top */
|
||||
lua_pushvalue(L, -nup);
|
||||
lua_pushcclosure(L, l->func, nup); /* closure with those upvalues */
|
||||
@@ -995,36 +1020,76 @@ static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) {
|
||||
|
||||
|
||||
static int panic (lua_State *L) {
|
||||
const char *msg = lua_tostring(L, -1);
|
||||
if (msg == NULL) msg = "error object is not a string";
|
||||
lua_writestringerror("PANIC: unprotected error in call to Lua API (%s)\n",
|
||||
lua_tostring(L, -1));
|
||||
msg);
|
||||
return 0; /* return to Lua to abort */
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** Emit a warning. '*previoustocont' signals whether previous message
|
||||
** was to be continued by the current one.
|
||||
** Warning functions:
|
||||
** warnfoff: warning system is off
|
||||
** warnfon: ready to start a new message
|
||||
** warnfcont: previous message is to be continued
|
||||
*/
|
||||
static void warnf (void *ud, const char *message, int tocont) {
|
||||
int *previoustocont = (int *)ud;
|
||||
if (!*previoustocont) /* previous message was the last? */
|
||||
lua_writestringerror("%s", "Lua warning: "); /* start a new warning */
|
||||
static void warnfoff (void *ud, const char *message, int tocont);
|
||||
static void warnfon (void *ud, const char *message, int tocont);
|
||||
static void warnfcont (void *ud, const char *message, int tocont);
|
||||
|
||||
|
||||
/*
|
||||
** Check whether message is a control message. If so, execute the
|
||||
** control or ignore it if unknown.
|
||||
*/
|
||||
static int checkcontrol (lua_State *L, const char *message, int tocont) {
|
||||
if (tocont || *(message++) != '@') /* not a control message? */
|
||||
return 0;
|
||||
else {
|
||||
if (strcmp(message, "off") == 0)
|
||||
lua_setwarnf(L, warnfoff, L); /* turn warnings off */
|
||||
else if (strcmp(message, "on") == 0)
|
||||
lua_setwarnf(L, warnfon, L); /* turn warnings on */
|
||||
return 1; /* it was a control message */
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
static void warnfoff (void *ud, const char *message, int tocont) {
|
||||
checkcontrol((lua_State *)ud, message, tocont);
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** Writes the message and handle 'tocont', finishing the message
|
||||
** if needed and setting the next warn function.
|
||||
*/
|
||||
static void warnfcont (void *ud, const char *message, int tocont) {
|
||||
lua_State *L = (lua_State *)ud;
|
||||
lua_writestringerror("%s", message); /* write message */
|
||||
if (!tocont) /* is this the last part? */
|
||||
if (tocont) /* not the last part? */
|
||||
lua_setwarnf(L, warnfcont, L); /* to be continued */
|
||||
else { /* last part */
|
||||
lua_writestringerror("%s", "\n"); /* finish message with end-of-line */
|
||||
*previoustocont = tocont;
|
||||
lua_setwarnf(L, warnfon, L); /* next call is a new message */
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
static void warnfon (void *ud, const char *message, int tocont) {
|
||||
if (checkcontrol((lua_State *)ud, message, tocont)) /* control message? */
|
||||
return; /* nothing else to be done */
|
||||
lua_writestringerror("%s", "Lua warning: "); /* start a new warning */
|
||||
warnfcont(ud, message, tocont); /* finish processing */
|
||||
}
|
||||
|
||||
|
||||
LUALIB_API lua_State *luaL_newstate (void) {
|
||||
lua_State *L = lua_newstate(l_alloc, NULL);
|
||||
if (L) {
|
||||
int *previoustocont; /* space for warning state */
|
||||
if (l_likely(L)) {
|
||||
lua_atpanic(L, &panic);
|
||||
previoustocont = (int *)lua_newuserdatauv(L, sizeof(int), 0);
|
||||
luaL_ref(L, LUA_REGISTRYINDEX); /* make sure it won't be collected */
|
||||
*previoustocont = 0; /* next message starts a new warning */
|
||||
lua_setwarnf(L, warnf, previoustocont);
|
||||
lua_setwarnf(L, warnfoff, L); /* default is warnings off */
|
||||
}
|
||||
return L;
|
||||
}
|
||||
|
||||
@@ -12,11 +12,12 @@
|
||||
#include <stddef.h>
|
||||
#include <stdio.h>
|
||||
|
||||
#include "luaconf.h"
|
||||
#include "lua.h"
|
||||
|
||||
|
||||
/* global table */
|
||||
#define LUA_GNAME "_G"
|
||||
#define LUA_GNAME "_G"
|
||||
|
||||
|
||||
typedef struct luaL_Buffer luaL_Buffer;
|
||||
@@ -101,7 +102,7 @@ LUALIB_API lua_State *(luaL_newstate) (void);
|
||||
|
||||
LUALIB_API lua_Integer (luaL_len) (lua_State *L, int idx);
|
||||
|
||||
LUALIB_API void luaL_addgsub (luaL_Buffer *b, const char *s,
|
||||
LUALIB_API void (luaL_addgsub) (luaL_Buffer *b, const char *s,
|
||||
const char *p, const char *r);
|
||||
LUALIB_API const char *(luaL_gsub) (lua_State *L, const char *s,
|
||||
const char *p, const char *r);
|
||||
@@ -130,10 +131,10 @@ LUALIB_API void (luaL_requiref) (lua_State *L, const char *modname,
|
||||
(luaL_checkversion(L), luaL_newlibtable(L,l), luaL_setfuncs(L,l,0))
|
||||
|
||||
#define luaL_argcheck(L, cond,arg,extramsg) \
|
||||
((void)((cond) || luaL_argerror(L, (arg), (extramsg))))
|
||||
((void)(luai_likely(cond) || luaL_argerror(L, (arg), (extramsg))))
|
||||
|
||||
#define luaL_argexpected(L,cond,arg,tname) \
|
||||
((void)((cond) || luaL_typeerror(L, (arg), (tname))))
|
||||
((void)(luai_likely(cond) || luaL_typeerror(L, (arg), (tname))))
|
||||
|
||||
#define luaL_checkstring(L,n) (luaL_checklstring(L, (n), NULL))
|
||||
#define luaL_optstring(L,n,d) (luaL_optlstring(L, (n), (d), NULL))
|
||||
@@ -153,6 +154,34 @@ LUALIB_API void (luaL_requiref) (lua_State *L, const char *modname,
|
||||
#define luaL_loadbuffer(L,s,sz,n) luaL_loadbufferx(L,s,sz,n,NULL)
|
||||
|
||||
|
||||
/*
|
||||
** Perform arithmetic operations on lua_Integer values with wrap-around
|
||||
** semantics, as the Lua core does.
|
||||
*/
|
||||
#define luaL_intop(op,v1,v2) \
|
||||
((lua_Integer)((lua_Unsigned)(v1) op (lua_Unsigned)(v2)))
|
||||
|
||||
|
||||
/* push the value used to represent failure/error */
|
||||
#define luaL_pushfail(L) lua_pushnil(L)
|
||||
|
||||
|
||||
/*
|
||||
** Internal assertions for in-house debugging
|
||||
*/
|
||||
#if !defined(lua_assert)
|
||||
|
||||
#if defined LUAI_ASSERT
|
||||
#include <assert.h>
|
||||
#define lua_assert(c) assert(c)
|
||||
#else
|
||||
#define lua_assert(c) ((void)0)
|
||||
#endif
|
||||
|
||||
#endif
|
||||
|
||||
|
||||
|
||||
/*
|
||||
** {======================================================
|
||||
** Generic Buffer manipulation
|
||||
@@ -181,6 +210,8 @@ struct luaL_Buffer {
|
||||
|
||||
#define luaL_addsize(B,s) ((B)->n += (s))
|
||||
|
||||
#define luaL_buffsub(B,s) ((B)->n -= (s))
|
||||
|
||||
LUALIB_API void (luaL_buffinit) (lua_State *L, luaL_Buffer *B);
|
||||
LUALIB_API char *(luaL_prepbuffsize) (luaL_Buffer *B, size_t sz);
|
||||
LUALIB_API void (luaL_addlstring) (luaL_Buffer *B, const char *s, size_t l);
|
||||
|
||||
+36
-14
@@ -48,9 +48,9 @@ static int luaB_warn (lua_State *L) {
|
||||
luaL_checkstring(L, 1); /* at least one argument */
|
||||
for (i = 2; i <= n; i++)
|
||||
luaL_checkstring(L, i); /* make sure all arguments are strings */
|
||||
for (i = 1; i <= n; i++) /* compose warning */
|
||||
for (i = 1; i < n; i++) /* compose warning */
|
||||
lua_warning(L, lua_tostring(L, i), 1);
|
||||
lua_warning(L, "", 0); /* close warning */
|
||||
lua_warning(L, lua_tostring(L, n), 0); /* close warning */
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -106,7 +106,7 @@ static int luaB_tonumber (lua_State *L) {
|
||||
return 1;
|
||||
} /* else not a number */
|
||||
} /* else not a number */
|
||||
lua_pushnil(L); /* not a number */
|
||||
luaL_pushfail(L); /* not a number */
|
||||
return 1;
|
||||
}
|
||||
|
||||
@@ -138,7 +138,7 @@ static int luaB_setmetatable (lua_State *L) {
|
||||
int t = lua_type(L, 2);
|
||||
luaL_checktype(L, 1, LUA_TTABLE);
|
||||
luaL_argexpected(L, t == LUA_TNIL || t == LUA_TTABLE, 2, "nil or table");
|
||||
if (luaL_getmetafield(L, 1, "__metatable") != LUA_TNIL)
|
||||
if (l_unlikely(luaL_getmetafield(L, 1, "__metatable") != LUA_TNIL))
|
||||
return luaL_error(L, "cannot change a protected metatable");
|
||||
lua_settop(L, 2);
|
||||
lua_setmetatable(L, 1);
|
||||
@@ -182,11 +182,20 @@ static int luaB_rawset (lua_State *L) {
|
||||
|
||||
|
||||
static int pushmode (lua_State *L, int oldmode) {
|
||||
lua_pushstring(L, (oldmode == LUA_GCINC) ? "incremental" : "generational");
|
||||
if (oldmode == -1)
|
||||
luaL_pushfail(L); /* invalid call to 'lua_gc' */
|
||||
else
|
||||
lua_pushstring(L, (oldmode == LUA_GCINC) ? "incremental"
|
||||
: "generational");
|
||||
return 1;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** check whether call to 'lua_gc' was valid (not inside a finalizer)
|
||||
*/
|
||||
#define checkvalres(res) { if (res == -1) break; }
|
||||
|
||||
static int luaB_collectgarbage (lua_State *L) {
|
||||
static const char *const opts[] = {"stop", "restart", "collect",
|
||||
"count", "step", "setpause", "setstepmul",
|
||||
@@ -199,12 +208,14 @@ static int luaB_collectgarbage (lua_State *L) {
|
||||
case LUA_GCCOUNT: {
|
||||
int k = lua_gc(L, o);
|
||||
int b = lua_gc(L, LUA_GCCOUNTB);
|
||||
checkvalres(k);
|
||||
lua_pushnumber(L, (lua_Number)k + ((lua_Number)b/1024));
|
||||
return 1;
|
||||
}
|
||||
case LUA_GCSTEP: {
|
||||
int step = (int)luaL_optinteger(L, 2, 0);
|
||||
int res = lua_gc(L, o, step);
|
||||
checkvalres(res);
|
||||
lua_pushboolean(L, res);
|
||||
return 1;
|
||||
}
|
||||
@@ -212,11 +223,13 @@ static int luaB_collectgarbage (lua_State *L) {
|
||||
case LUA_GCSETSTEPMUL: {
|
||||
int p = (int)luaL_optinteger(L, 2, 0);
|
||||
int previous = lua_gc(L, o, p);
|
||||
checkvalres(previous);
|
||||
lua_pushinteger(L, previous);
|
||||
return 1;
|
||||
}
|
||||
case LUA_GCISRUNNING: {
|
||||
int res = lua_gc(L, o);
|
||||
checkvalres(res);
|
||||
lua_pushboolean(L, res);
|
||||
return 1;
|
||||
}
|
||||
@@ -233,10 +246,13 @@ static int luaB_collectgarbage (lua_State *L) {
|
||||
}
|
||||
default: {
|
||||
int res = lua_gc(L, o);
|
||||
checkvalres(res);
|
||||
lua_pushinteger(L, res);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
luaL_pushfail(L); /* invalid call (inside a finalizer) */
|
||||
return 1;
|
||||
}
|
||||
|
||||
|
||||
@@ -260,6 +276,11 @@ static int luaB_next (lua_State *L) {
|
||||
}
|
||||
|
||||
|
||||
static int pairscont (lua_State *L, int status, lua_KContext k) {
|
||||
(void)L; (void)status; (void)k; /* unused */
|
||||
return 3;
|
||||
}
|
||||
|
||||
static int luaB_pairs (lua_State *L) {
|
||||
luaL_checkany(L, 1);
|
||||
if (luaL_getmetafield(L, 1, "__pairs") == LUA_TNIL) { /* no metamethod? */
|
||||
@@ -269,7 +290,7 @@ static int luaB_pairs (lua_State *L) {
|
||||
}
|
||||
else {
|
||||
lua_pushvalue(L, 1); /* argument 'self' to metamethod */
|
||||
lua_call(L, 1, 3); /* get 3 values from metamethod */
|
||||
lua_callk(L, 1, 3, 0, pairscont); /* get 3 values from metamethod */
|
||||
}
|
||||
return 3;
|
||||
}
|
||||
@@ -279,7 +300,8 @@ static int luaB_pairs (lua_State *L) {
|
||||
** Traversal function for 'ipairs'
|
||||
*/
|
||||
static int ipairsaux (lua_State *L) {
|
||||
lua_Integer i = luaL_checkinteger(L, 2) + 1;
|
||||
lua_Integer i = luaL_checkinteger(L, 2);
|
||||
i = luaL_intop(+, i, 1);
|
||||
lua_pushinteger(L, i);
|
||||
return (lua_geti(L, 1, i) == LUA_TNIL) ? 1 : 2;
|
||||
}
|
||||
@@ -299,7 +321,7 @@ static int luaB_ipairs (lua_State *L) {
|
||||
|
||||
|
||||
static int load_aux (lua_State *L, int status, int envidx) {
|
||||
if (status == LUA_OK) {
|
||||
if (l_likely(status == LUA_OK)) {
|
||||
if (envidx != 0) { /* 'env' parameter? */
|
||||
lua_pushvalue(L, envidx); /* environment for loaded function */
|
||||
if (!lua_setupvalue(L, -2, 1)) /* set it as 1st upvalue */
|
||||
@@ -308,9 +330,9 @@ static int load_aux (lua_State *L, int status, int envidx) {
|
||||
return 1;
|
||||
}
|
||||
else { /* error (message is on top of the stack) */
|
||||
lua_pushnil(L);
|
||||
luaL_pushfail(L);
|
||||
lua_insert(L, -2); /* put before error message */
|
||||
return 2; /* return nil plus error message */
|
||||
return 2; /* return fail plus error message */
|
||||
}
|
||||
}
|
||||
|
||||
@@ -355,7 +377,7 @@ static const char *generic_reader (lua_State *L, void *ud, size_t *size) {
|
||||
*size = 0;
|
||||
return NULL;
|
||||
}
|
||||
else if (!lua_isstring(L, -1))
|
||||
else if (l_unlikely(!lua_isstring(L, -1)))
|
||||
luaL_error(L, "reader function must return a string");
|
||||
lua_replace(L, RESERVEDSLOT); /* save string in reserved slot */
|
||||
return lua_tolstring(L, RESERVEDSLOT, size);
|
||||
@@ -393,7 +415,7 @@ static int dofilecont (lua_State *L, int d1, lua_KContext d2) {
|
||||
static int luaB_dofile (lua_State *L) {
|
||||
const char *fname = luaL_optstring(L, 1, NULL);
|
||||
lua_settop(L, 1);
|
||||
if (luaL_loadfile(L, fname) != LUA_OK)
|
||||
if (l_unlikely(luaL_loadfile(L, fname) != LUA_OK))
|
||||
return lua_error(L);
|
||||
lua_callk(L, 0, LUA_MULTRET, 0, dofilecont);
|
||||
return dofilecont(L, 0, 0);
|
||||
@@ -401,7 +423,7 @@ static int luaB_dofile (lua_State *L) {
|
||||
|
||||
|
||||
static int luaB_assert (lua_State *L) {
|
||||
if (lua_toboolean(L, 1)) /* condition is true? */
|
||||
if (l_likely(lua_toboolean(L, 1))) /* condition is true? */
|
||||
return lua_gettop(L); /* return all arguments */
|
||||
else { /* error */
|
||||
luaL_checkany(L, 1); /* there must be a condition */
|
||||
@@ -437,7 +459,7 @@ static int luaB_select (lua_State *L) {
|
||||
** ignored).
|
||||
*/
|
||||
static int finishpcall (lua_State *L, int status, lua_KContext extra) {
|
||||
if (status != LUA_OK && status != LUA_YIELD) { /* error? */
|
||||
if (l_unlikely(status != LUA_OK && status != LUA_YIELD)) { /* error? */
|
||||
lua_pushboolean(L, 0); /* first result (false) */
|
||||
lua_pushvalue(L, -2); /* error message */
|
||||
return 2; /* return false, msg */
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
#include "lprefix.h"
|
||||
|
||||
|
||||
#include <float.h>
|
||||
#include <limits.h>
|
||||
#include <math.h>
|
||||
#include <stdlib.h>
|
||||
@@ -52,7 +53,7 @@ l_noret luaK_semerror (LexState *ls, const char *msg) {
|
||||
** If expression is a numeric constant, fills 'v' with its value
|
||||
** and returns 1. Otherwise, returns 0.
|
||||
*/
|
||||
static int tonumeral(const expdesc *e, TValue *v) {
|
||||
static int tonumeral (const expdesc *e, TValue *v) {
|
||||
if (hasjumps(e))
|
||||
return 0; /* not a numeral */
|
||||
switch (e->k) {
|
||||
@@ -67,6 +68,45 @@ static int tonumeral(const expdesc *e, TValue *v) {
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** Get the constant value from a constant expression
|
||||
*/
|
||||
static TValue *const2val (FuncState *fs, const expdesc *e) {
|
||||
lua_assert(e->k == VCONST);
|
||||
return &fs->ls->dyd->actvar.arr[e->u.info].k;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** If expression is a constant, fills 'v' with its value
|
||||
** and returns 1. Otherwise, returns 0.
|
||||
*/
|
||||
int luaK_exp2const (FuncState *fs, const expdesc *e, TValue *v) {
|
||||
if (hasjumps(e))
|
||||
return 0; /* not a constant */
|
||||
switch (e->k) {
|
||||
case VFALSE:
|
||||
setbfvalue(v);
|
||||
return 1;
|
||||
case VTRUE:
|
||||
setbtvalue(v);
|
||||
return 1;
|
||||
case VNIL:
|
||||
setnilvalue(v);
|
||||
return 1;
|
||||
case VKSTR: {
|
||||
setsvalue(fs->ls->L, v, e->u.strval);
|
||||
return 1;
|
||||
}
|
||||
case VCONST: {
|
||||
setobj(fs->ls->L, v, const2val(fs, e));
|
||||
return 1;
|
||||
}
|
||||
default: return tonumeral(e, v);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** Return the previous instruction of the current code. If there
|
||||
** may be a jump target between the current instruction and the
|
||||
@@ -74,7 +114,7 @@ static int tonumeral(const expdesc *e, TValue *v) {
|
||||
** optimizations).
|
||||
*/
|
||||
static Instruction *previousinstruction (FuncState *fs) {
|
||||
static const Instruction invalidinstruction = -1;
|
||||
static const Instruction invalidinstruction = ~(Instruction)0;
|
||||
if (fs->pc > fs->lasttarget)
|
||||
return &fs->f->code[fs->pc - 1]; /* previous instruction */
|
||||
else
|
||||
@@ -275,15 +315,6 @@ void luaK_patchtohere (FuncState *fs, int list) {
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** MAXimum number of successive Instructions WiTHout ABSolute line
|
||||
** information.
|
||||
*/
|
||||
#if !defined(MAXIWTHABS)
|
||||
#define MAXIWTHABS 120
|
||||
#endif
|
||||
|
||||
|
||||
/* limit for difference between lines in relative line info. */
|
||||
#define LIMLINEDIFF 0x80
|
||||
|
||||
@@ -298,13 +329,13 @@ void luaK_patchtohere (FuncState *fs, int list) {
|
||||
static void savelineinfo (FuncState *fs, Proto *f, int line) {
|
||||
int linedif = line - fs->previousline;
|
||||
int pc = fs->pc - 1; /* last instruction coded */
|
||||
if (abs(linedif) >= LIMLINEDIFF || fs->iwthabs++ > MAXIWTHABS) {
|
||||
if (abs(linedif) >= LIMLINEDIFF || fs->iwthabs++ >= MAXIWTHABS) {
|
||||
luaM_growvector(fs->ls->L, f->abslineinfo, fs->nabslineinfo,
|
||||
f->sizeabslineinfo, AbsLineInfo, MAX_INT, "lines");
|
||||
f->abslineinfo[fs->nabslineinfo].pc = pc;
|
||||
f->abslineinfo[fs->nabslineinfo++].line = line;
|
||||
linedif = ABSLINEINFO; /* signal that there is absolute information */
|
||||
fs->iwthabs = 0; /* restart counter */
|
||||
fs->iwthabs = 1; /* restart counter */
|
||||
}
|
||||
luaM_growvector(fs->ls->L, f->lineinfo, pc, f->sizelineinfo, ls_byte,
|
||||
MAX_INT, "opcodes");
|
||||
@@ -323,12 +354,12 @@ static void removelastlineinfo (FuncState *fs) {
|
||||
Proto *f = fs->f;
|
||||
int pc = fs->pc - 1; /* last instruction coded */
|
||||
if (f->lineinfo[pc] != ABSLINEINFO) { /* relative line info? */
|
||||
fs->previousline -= f->lineinfo[pc]; /* last line saved */
|
||||
fs->iwthabs--;
|
||||
fs->previousline -= f->lineinfo[pc]; /* correct last line saved */
|
||||
fs->iwthabs--; /* undo previous increment */
|
||||
}
|
||||
else { /* absolute line information */
|
||||
lua_assert(f->abslineinfo[fs->nabslineinfo - 1].pc == pc);
|
||||
fs->nabslineinfo--; /* remove it */
|
||||
lua_assert(f->abslineinfo[fs->nabslineinfo].pc = pc);
|
||||
fs->iwthabs = MAXIWTHABS + 1; /* force next line info to be absolute */
|
||||
}
|
||||
}
|
||||
@@ -348,7 +379,7 @@ static void removelastinstruction (FuncState *fs) {
|
||||
** Emit instruction 'i', checking for array sizes and saving also its
|
||||
** line information. Return 'i' position.
|
||||
*/
|
||||
static int luaK_code (FuncState *fs, Instruction i) {
|
||||
int luaK_code (FuncState *fs, Instruction i) {
|
||||
Proto *f = fs->f;
|
||||
/* put new instruction in code array */
|
||||
luaM_growvector(fs->ls->L, f->code, fs->pc, f->sizecode, Instruction,
|
||||
@@ -458,7 +489,7 @@ void luaK_reserveregs (FuncState *fs, int n) {
|
||||
)
|
||||
*/
|
||||
static void freereg (FuncState *fs, int reg) {
|
||||
if (reg >= fs->nactvar) {
|
||||
if (reg >= luaY_nvarstack(fs)) {
|
||||
fs->freereg--;
|
||||
lua_assert(reg == fs->freereg);
|
||||
}
|
||||
@@ -506,11 +537,14 @@ static void freeexps (FuncState *fs, expdesc *e1, expdesc *e2) {
|
||||
** and try to reuse constants. Because some values should not be used
|
||||
** as keys (nil cannot be a key, integer keys can collapse with float
|
||||
** keys), the caller must provide a useful 'key' for indexing the cache.
|
||||
** Note that all functions share the same table, so entering or exiting
|
||||
** a function can make some indices wrong.
|
||||
*/
|
||||
static int addk (FuncState *fs, TValue *key, TValue *v) {
|
||||
TValue val;
|
||||
lua_State *L = fs->ls->L;
|
||||
Proto *f = fs->f;
|
||||
TValue *idx = luaH_set(L, fs->ls->h, key); /* index scanner table */
|
||||
const TValue *idx = luaH_get(fs->ls->h, key); /* query scanner table */
|
||||
int k, oldsize;
|
||||
if (ttisinteger(idx)) { /* is there an index there? */
|
||||
k = cast_int(ivalue(idx));
|
||||
@@ -524,7 +558,8 @@ static int addk (FuncState *fs, TValue *key, TValue *v) {
|
||||
k = fs->nk;
|
||||
/* numerical value does not need GC barrier;
|
||||
table has no metatable, so it does not need to invalidate cache */
|
||||
setivalue(idx, k);
|
||||
setivalue(&val, k);
|
||||
luaH_finishset(L, fs->ls->h, key, idx, &val);
|
||||
luaM_growvector(L, f->k, k, f->sizek, TValue, MAXARG_Ax, "constants");
|
||||
while (oldsize < f->sizek) setnilvalue(&f->k[oldsize++]);
|
||||
setobj(L, &f->k[k], v);
|
||||
@@ -537,7 +572,7 @@ static int addk (FuncState *fs, TValue *key, TValue *v) {
|
||||
/*
|
||||
** Add a string to list of constants and return its index.
|
||||
*/
|
||||
int luaK_stringK (FuncState *fs, TString *s) {
|
||||
static int stringK (FuncState *fs, TString *s) {
|
||||
TValue o;
|
||||
setsvalue(fs->ls->L, &o, s);
|
||||
return addk(fs, &o, &o); /* use string itself as key */
|
||||
@@ -546,33 +581,60 @@ int luaK_stringK (FuncState *fs, TString *s) {
|
||||
|
||||
/*
|
||||
** Add an integer to list of constants and return its index.
|
||||
** Integers use userdata as keys to avoid collision with floats with
|
||||
** same value; conversion to 'void*' is used only for hashing, so there
|
||||
** are no "precision" problems.
|
||||
*/
|
||||
static int luaK_intK (FuncState *fs, lua_Integer n) {
|
||||
TValue k, o;
|
||||
setpvalue(&k, cast_voidp(cast_sizet(n)));
|
||||
TValue o;
|
||||
setivalue(&o, n);
|
||||
return addk(fs, &k, &o);
|
||||
return addk(fs, &o, &o); /* use integer itself as key */
|
||||
}
|
||||
|
||||
/*
|
||||
** Add a float to list of constants and return its index.
|
||||
** Add a float to list of constants and return its index. Floats
|
||||
** with integral values need a different key, to avoid collision
|
||||
** with actual integers. To that, we add to the number its smaller
|
||||
** power-of-two fraction that is still significant in its scale.
|
||||
** For doubles, that would be 1/2^52.
|
||||
** (This method is not bulletproof: there may be another float
|
||||
** with that value, and for floats larger than 2^53 the result is
|
||||
** still an integer. At worst, this only wastes an entry with
|
||||
** a duplicate.)
|
||||
*/
|
||||
static int luaK_numberK (FuncState *fs, lua_Number r) {
|
||||
TValue o;
|
||||
lua_Integer ik;
|
||||
setfltvalue(&o, r);
|
||||
return addk(fs, &o, &o); /* use number itself as key */
|
||||
if (!luaV_flttointeger(r, &ik, F2Ieq)) /* not an integral value? */
|
||||
return addk(fs, &o, &o); /* use number itself as key */
|
||||
else { /* must build an alternative key */
|
||||
const int nbm = l_floatatt(MANT_DIG);
|
||||
const lua_Number q = l_mathop(ldexp)(l_mathop(1.0), -nbm + 1);
|
||||
const lua_Number k = (ik == 0) ? q : r + r*q; /* new key */
|
||||
TValue kv;
|
||||
setfltvalue(&kv, k);
|
||||
/* result is not an integral value, unless value is too large */
|
||||
lua_assert(!luaV_flttointeger(k, &ik, F2Ieq) ||
|
||||
l_mathop(fabs)(r) >= l_mathop(1e6));
|
||||
return addk(fs, &kv, &o);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** Add a boolean to list of constants and return its index.
|
||||
** Add a false to list of constants and return its index.
|
||||
*/
|
||||
static int boolK (FuncState *fs, int b) {
|
||||
static int boolF (FuncState *fs) {
|
||||
TValue o;
|
||||
setbvalue(&o, b);
|
||||
setbfvalue(&o);
|
||||
return addk(fs, &o, &o); /* use boolean itself as key */
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** Add a true to list of constants and return its index.
|
||||
*/
|
||||
static int boolT (FuncState *fs) {
|
||||
TValue o;
|
||||
setbtvalue(&o);
|
||||
return addk(fs, &o, &o); /* use boolean itself as key */
|
||||
}
|
||||
|
||||
@@ -590,12 +652,12 @@ static int nilK (FuncState *fs) {
|
||||
|
||||
|
||||
/*
|
||||
** Check whether 'i' can be stored in an 'sC' operand.
|
||||
** Equivalent to (0 <= i + OFFSET_sC && i + OFFSET_sC <= MAXARG_C)
|
||||
** but without risk of overflows in the addition.
|
||||
** Check whether 'i' can be stored in an 'sC' operand. Equivalent to
|
||||
** (0 <= int2sC(i) && int2sC(i) <= MAXARG_C) but without risk of
|
||||
** overflows in the hidden addition inside 'int2sC'.
|
||||
*/
|
||||
static int fitsC (lua_Integer i) {
|
||||
return (-OFFSET_sC <= i && i <= MAXARG_C - OFFSET_sC);
|
||||
return (l_castS2U(i) + OFFSET_sC <= cast_uint(MAXARG_C));
|
||||
}
|
||||
|
||||
|
||||
@@ -615,35 +677,67 @@ void luaK_int (FuncState *fs, int reg, lua_Integer i) {
|
||||
}
|
||||
|
||||
|
||||
static int floatI (lua_Number f, lua_Integer *fi) {
|
||||
return (luaV_flttointeger(f, fi, 0) && fitsBx(*fi));
|
||||
}
|
||||
|
||||
|
||||
static void luaK_float (FuncState *fs, int reg, lua_Number f) {
|
||||
lua_Integer fi;
|
||||
if (floatI(f, &fi))
|
||||
if (luaV_flttointeger(f, &fi, F2Ieq) && fitsBx(fi))
|
||||
luaK_codeAsBx(fs, OP_LOADF, reg, cast_int(fi));
|
||||
else
|
||||
luaK_codek(fs, reg, luaK_numberK(fs, f));
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** Convert a constant in 'v' into an expression description 'e'
|
||||
*/
|
||||
static void const2exp (TValue *v, expdesc *e) {
|
||||
switch (ttypetag(v)) {
|
||||
case LUA_VNUMINT:
|
||||
e->k = VKINT; e->u.ival = ivalue(v);
|
||||
break;
|
||||
case LUA_VNUMFLT:
|
||||
e->k = VKFLT; e->u.nval = fltvalue(v);
|
||||
break;
|
||||
case LUA_VFALSE:
|
||||
e->k = VFALSE;
|
||||
break;
|
||||
case LUA_VTRUE:
|
||||
e->k = VTRUE;
|
||||
break;
|
||||
case LUA_VNIL:
|
||||
e->k = VNIL;
|
||||
break;
|
||||
case LUA_VSHRSTR: case LUA_VLNGSTR:
|
||||
e->k = VKSTR; e->u.strval = tsvalue(v);
|
||||
break;
|
||||
default: lua_assert(0);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** Fix an expression to return the number of results 'nresults'.
|
||||
** Either 'e' is a multi-ret expression (function call or vararg)
|
||||
** or 'nresults' is LUA_MULTRET (as any expression can satisfy that).
|
||||
** 'e' must be a multi-ret expression (function call or vararg).
|
||||
*/
|
||||
void luaK_setreturns (FuncState *fs, expdesc *e, int nresults) {
|
||||
Instruction *pc = &getinstruction(fs, e);
|
||||
if (e->k == VCALL) /* expression is an open function call? */
|
||||
SETARG_C(*pc, nresults + 1);
|
||||
else if (e->k == VVARARG) {
|
||||
else {
|
||||
lua_assert(e->k == VVARARG);
|
||||
SETARG_C(*pc, nresults + 1);
|
||||
SETARG_A(*pc, fs->freereg);
|
||||
luaK_reserveregs(fs, 1);
|
||||
}
|
||||
else lua_assert(nresults == LUA_MULTRET);
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** Convert a VKSTR to a VK
|
||||
*/
|
||||
static void str2K (FuncState *fs, expdesc *e) {
|
||||
lua_assert(e->k == VKSTR);
|
||||
e->u.info = stringK(fs, e->u.strval);
|
||||
e->k = VK;
|
||||
}
|
||||
|
||||
|
||||
@@ -672,18 +766,22 @@ void luaK_setoneret (FuncState *fs, expdesc *e) {
|
||||
|
||||
|
||||
/*
|
||||
** Ensure that expression 'e' is not a variable.
|
||||
** Ensure that expression 'e' is not a variable (nor a <const>).
|
||||
** (Expression still may have jump lists.)
|
||||
*/
|
||||
void luaK_dischargevars (FuncState *fs, expdesc *e) {
|
||||
switch (e->k) {
|
||||
case VCONST: {
|
||||
const2exp(const2val(fs, e), e);
|
||||
break;
|
||||
}
|
||||
case VLOCAL: { /* already in a register */
|
||||
e->u.info = e->u.var.idx;
|
||||
e->u.info = e->u.var.ridx;
|
||||
e->k = VNONRELOC; /* becomes a non-relocatable value */
|
||||
break;
|
||||
}
|
||||
case VUPVAL: { /* move value to some (pending) register */
|
||||
e->u.info = luaK_codeABC(fs, OP_GETUPVAL, 0, e->u.var.idx, 0);
|
||||
e->u.info = luaK_codeABC(fs, OP_GETUPVAL, 0, e->u.info, 0);
|
||||
e->k = VRELOC;
|
||||
break;
|
||||
}
|
||||
@@ -720,8 +818,8 @@ void luaK_dischargevars (FuncState *fs, expdesc *e) {
|
||||
|
||||
|
||||
/*
|
||||
** Ensures expression value is in register 'reg' (and therefore
|
||||
** 'e' will become a non-relocatable expression).
|
||||
** Ensure expression value is in register 'reg', making 'e' a
|
||||
** non-relocatable expression.
|
||||
** (Expression still may have jump lists.)
|
||||
*/
|
||||
static void discharge2reg (FuncState *fs, expdesc *e, int reg) {
|
||||
@@ -731,10 +829,17 @@ static void discharge2reg (FuncState *fs, expdesc *e, int reg) {
|
||||
luaK_nil(fs, reg, 1);
|
||||
break;
|
||||
}
|
||||
case VFALSE: case VTRUE: {
|
||||
luaK_codeABC(fs, OP_LOADBOOL, reg, e->k == VTRUE, 0);
|
||||
case VFALSE: {
|
||||
luaK_codeABC(fs, OP_LOADFALSE, reg, 0, 0);
|
||||
break;
|
||||
}
|
||||
case VTRUE: {
|
||||
luaK_codeABC(fs, OP_LOADTRUE, reg, 0, 0);
|
||||
break;
|
||||
}
|
||||
case VKSTR: {
|
||||
str2K(fs, e);
|
||||
} /* FALLTHROUGH */
|
||||
case VK: {
|
||||
luaK_codek(fs, reg, e->u.info);
|
||||
break;
|
||||
@@ -768,7 +873,8 @@ static void discharge2reg (FuncState *fs, expdesc *e, int reg) {
|
||||
|
||||
|
||||
/*
|
||||
** Ensures expression value is in any register.
|
||||
** Ensure expression value is in a register, making 'e' a
|
||||
** non-relocatable expression.
|
||||
** (Expression still may have jump lists.)
|
||||
*/
|
||||
static void discharge2anyreg (FuncState *fs, expdesc *e) {
|
||||
@@ -779,9 +885,9 @@ static void discharge2anyreg (FuncState *fs, expdesc *e) {
|
||||
}
|
||||
|
||||
|
||||
static int code_loadbool (FuncState *fs, int A, int b, int jump) {
|
||||
static int code_loadbool (FuncState *fs, int A, OpCode op) {
|
||||
luaK_getlabel(fs); /* those instructions may be jump targets */
|
||||
return luaK_codeABC(fs, OP_LOADBOOL, A, b, jump);
|
||||
return luaK_codeABC(fs, op, A, 0, 0);
|
||||
}
|
||||
|
||||
|
||||
@@ -815,8 +921,8 @@ static void exp2reg (FuncState *fs, expdesc *e, int reg) {
|
||||
int p_t = NO_JUMP; /* position of an eventual LOAD true */
|
||||
if (need_value(fs, e->t) || need_value(fs, e->f)) {
|
||||
int fj = (e->k == VJMP) ? NO_JUMP : luaK_jump(fs);
|
||||
p_f = code_loadbool(fs, reg, 0, 1); /* load false and skip next i. */
|
||||
p_t = code_loadbool(fs, reg, 1, 0); /* load true */
|
||||
p_f = code_loadbool(fs, reg, OP_LFALSESKIP); /* skip next inst. */
|
||||
p_t = code_loadbool(fs, reg, OP_LOADTRUE);
|
||||
/* jump around these booleans if 'e' is not a test */
|
||||
luaK_patchtohere(fs, fj);
|
||||
}
|
||||
@@ -850,12 +956,15 @@ int luaK_exp2anyreg (FuncState *fs, expdesc *e) {
|
||||
if (e->k == VNONRELOC) { /* expression already has a register? */
|
||||
if (!hasjumps(e)) /* no jumps? */
|
||||
return e->u.info; /* result is already in a register */
|
||||
if (e->u.info >= fs->nactvar) { /* reg. is not a local? */
|
||||
if (e->u.info >= luaY_nvarstack(fs)) { /* reg. is not a local? */
|
||||
exp2reg(fs, e, e->u.info); /* put final result in it */
|
||||
return e->u.info;
|
||||
}
|
||||
/* else expression has jumps and cannot change its register
|
||||
to hold the jump values, because it is a local variable.
|
||||
Go through to the default case. */
|
||||
}
|
||||
luaK_exp2nextreg(fs, e); /* otherwise, use next available register */
|
||||
luaK_exp2nextreg(fs, e); /* default: use next available register */
|
||||
return e->u.info;
|
||||
}
|
||||
|
||||
@@ -890,11 +999,12 @@ static int luaK_exp2K (FuncState *fs, expdesc *e) {
|
||||
if (!hasjumps(e)) {
|
||||
int info;
|
||||
switch (e->k) { /* move constants to 'k' */
|
||||
case VTRUE: info = boolK(fs, 1); break;
|
||||
case VFALSE: info = boolK(fs, 0); break;
|
||||
case VTRUE: info = boolT(fs); break;
|
||||
case VFALSE: info = boolF(fs); break;
|
||||
case VNIL: info = nilK(fs); break;
|
||||
case VKINT: info = luaK_intK(fs, e->u.ival); break;
|
||||
case VKFLT: info = luaK_numberK(fs, e->u.nval); break;
|
||||
case VKSTR: info = stringK(fs, e->u.strval); break;
|
||||
case VK: info = e->u.info; break;
|
||||
default: return 0; /* not a constant */
|
||||
}
|
||||
@@ -939,12 +1049,12 @@ void luaK_storevar (FuncState *fs, expdesc *var, expdesc *ex) {
|
||||
switch (var->k) {
|
||||
case VLOCAL: {
|
||||
freeexp(fs, ex);
|
||||
exp2reg(fs, ex, var->u.var.idx); /* compute 'ex' into proper place */
|
||||
exp2reg(fs, ex, var->u.var.ridx); /* compute 'ex' into proper place */
|
||||
return;
|
||||
}
|
||||
case VUPVAL: {
|
||||
int e = luaK_exp2anyreg(fs, ex);
|
||||
luaK_codeABC(fs, OP_SETUPVAL, e, var->u.var.idx, 0);
|
||||
luaK_codeABC(fs, OP_SETUPVAL, e, var->u.info, 0);
|
||||
break;
|
||||
}
|
||||
case VINDEXUP: {
|
||||
@@ -1029,7 +1139,7 @@ void luaK_goiftrue (FuncState *fs, expdesc *e) {
|
||||
pc = e->u.info; /* save jump position */
|
||||
break;
|
||||
}
|
||||
case VK: case VKFLT: case VKINT: case VTRUE: {
|
||||
case VK: case VKFLT: case VKINT: case VKSTR: case VTRUE: {
|
||||
pc = NO_JUMP; /* always true; do nothing */
|
||||
break;
|
||||
}
|
||||
@@ -1074,13 +1184,12 @@ void luaK_goiffalse (FuncState *fs, expdesc *e) {
|
||||
** Code 'not e', doing constant folding.
|
||||
*/
|
||||
static void codenot (FuncState *fs, expdesc *e) {
|
||||
luaK_dischargevars(fs, e);
|
||||
switch (e->k) {
|
||||
case VNIL: case VFALSE: {
|
||||
e->k = VTRUE; /* true == not nil == not false */
|
||||
break;
|
||||
}
|
||||
case VK: case VKFLT: case VKINT: case VTRUE: {
|
||||
case VK: case VKFLT: case VKINT: case VKSTR: case VTRUE: {
|
||||
e->k = VFALSE; /* false == not "x" == not 0.5 == not 1 == not true */
|
||||
break;
|
||||
}
|
||||
@@ -1143,15 +1252,16 @@ static int isSCint (expdesc *e) {
|
||||
** Check whether expression 'e' is a literal integer or float in
|
||||
** proper range to fit in a register (sB or sC).
|
||||
*/
|
||||
static int isSCnumber (expdesc *e, lua_Integer *i, int *isfloat) {
|
||||
static int isSCnumber (expdesc *e, int *pi, int *isfloat) {
|
||||
lua_Integer i;
|
||||
if (e->k == VKINT)
|
||||
*i = e->u.ival;
|
||||
else if (!(e->k == VKFLT && floatI(e->u.nval, i)))
|
||||
return 0; /* not a number */
|
||||
else
|
||||
i = e->u.ival;
|
||||
else if (e->k == VKFLT && luaV_flttointeger(e->u.nval, &i, F2Ieq))
|
||||
*isfloat = 1;
|
||||
if (!hasjumps(e) && fitsC(*i)) {
|
||||
*i += OFFSET_sC;
|
||||
else
|
||||
return 0; /* not a number */
|
||||
if (!hasjumps(e) && fitsC(i)) {
|
||||
*pi = int2sC(cast_int(i));
|
||||
return 1;
|
||||
}
|
||||
else
|
||||
@@ -1166,18 +1276,20 @@ static int isSCnumber (expdesc *e, lua_Integer *i, int *isfloat) {
|
||||
** values in registers.
|
||||
*/
|
||||
void luaK_indexed (FuncState *fs, expdesc *t, expdesc *k) {
|
||||
if (k->k == VKSTR)
|
||||
str2K(fs, k);
|
||||
lua_assert(!hasjumps(t) &&
|
||||
(t->k == VLOCAL || t->k == VNONRELOC || t->k == VUPVAL));
|
||||
if (t->k == VUPVAL && !isKstr(fs, k)) /* upvalue indexed by non string? */
|
||||
if (t->k == VUPVAL && !isKstr(fs, k)) /* upvalue indexed by non 'Kstr'? */
|
||||
luaK_exp2anyreg(fs, t); /* put it in a register */
|
||||
if (t->k == VUPVAL) {
|
||||
t->u.ind.t = t->u.var.idx; /* upvalue index */
|
||||
t->u.ind.t = t->u.info; /* upvalue index */
|
||||
t->u.ind.idx = k->u.info; /* literal string */
|
||||
t->k = VINDEXUP;
|
||||
}
|
||||
else {
|
||||
/* register index of the table */
|
||||
t->u.ind.t = (t->k == VLOCAL) ? t->u.var.idx: t->u.info;
|
||||
t->u.ind.t = (t->k == VLOCAL) ? t->u.var.ridx: t->u.info;
|
||||
if (isKstr(fs, k)) {
|
||||
t->u.ind.idx = k->u.info; /* literal string */
|
||||
t->k = VINDEXSTR;
|
||||
@@ -1204,7 +1316,8 @@ static int validop (int op, TValue *v1, TValue *v2) {
|
||||
case LUA_OPBAND: case LUA_OPBOR: case LUA_OPBXOR:
|
||||
case LUA_OPSHL: case LUA_OPSHR: case LUA_OPBNOT: { /* conversion errors */
|
||||
lua_Integer i;
|
||||
return (tointegerns(v1, &i) && tointegerns(v2, &i));
|
||||
return (luaV_tointegerns(v1, &i, LUA_FLOORN2I) &&
|
||||
luaV_tointegerns(v2, &i, LUA_FLOORN2I));
|
||||
}
|
||||
case LUA_OPDIV: case LUA_OPIDIV: case LUA_OPMOD: /* division by 0 */
|
||||
return (nvalue(v2) != 0);
|
||||
@@ -1218,7 +1331,7 @@ static int validop (int op, TValue *v1, TValue *v2) {
|
||||
** (In this case, 'e1' has the final result.)
|
||||
*/
|
||||
static int constfolding (FuncState *fs, int op, expdesc *e1,
|
||||
const expdesc *e2) {
|
||||
const expdesc *e2) {
|
||||
TValue v1, v2, res;
|
||||
if (!tonumeral(e1, &v1) || !tonumeral(e2, &v2) || !validop(op, &v1, &v2))
|
||||
return 0; /* non-numeric operands or not safe to fold */
|
||||
@@ -1257,18 +1370,18 @@ static void codeunexpval (FuncState *fs, OpCode op, expdesc *e, int line) {
|
||||
** (everything but logical operators 'and'/'or' and comparison
|
||||
** operators).
|
||||
** Expression to produce final result will be encoded in 'e1'.
|
||||
** Because 'luaK_exp2anyreg' can free registers, its calls must be
|
||||
** in "stack order" (that is, first on 'e2', which may have more
|
||||
** recent registers to be released).
|
||||
*/
|
||||
static void finishbinexpval (FuncState *fs, expdesc *e1, expdesc *e2,
|
||||
OpCode op, int v2, int k, int line) {
|
||||
OpCode op, int v2, int flip, int line,
|
||||
OpCode mmop, TMS event) {
|
||||
int v1 = luaK_exp2anyreg(fs, e1);
|
||||
int pc = luaK_codeABCk(fs, op, 0, v1, v2, k);
|
||||
int pc = luaK_codeABCk(fs, op, 0, v1, v2, 0);
|
||||
freeexps(fs, e1, e2);
|
||||
e1->u.info = pc;
|
||||
e1->k = VRELOC; /* all those operations are relocatable */
|
||||
luaK_fixline(fs, line);
|
||||
luaK_codeABCk(fs, mmop, v1, v2, event, flip); /* to call metamethod */
|
||||
luaK_fixline(fs, line);
|
||||
}
|
||||
|
||||
|
||||
@@ -1279,17 +1392,43 @@ static void finishbinexpval (FuncState *fs, expdesc *e1, expdesc *e2,
|
||||
static void codebinexpval (FuncState *fs, OpCode op,
|
||||
expdesc *e1, expdesc *e2, int line) {
|
||||
int v2 = luaK_exp2anyreg(fs, e2); /* both operands are in registers */
|
||||
finishbinexpval(fs, e1, e2, op, v2, 0, line);
|
||||
lua_assert(OP_ADD <= op && op <= OP_SHR);
|
||||
finishbinexpval(fs, e1, e2, op, v2, 0, line, OP_MMBIN,
|
||||
cast(TMS, (op - OP_ADD) + TM_ADD));
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** Code binary operators ('+', '-', ...) with immediate operands.
|
||||
** Code binary operators with immediate operands.
|
||||
*/
|
||||
static void codebini (FuncState *fs, OpCode op,
|
||||
expdesc *e1, expdesc *e2, int k, int line) {
|
||||
int v2 = cast_int(e2->u.ival) + OFFSET_sC; /* immediate operand */
|
||||
finishbinexpval(fs, e1, e2, op, v2, k, line);
|
||||
expdesc *e1, expdesc *e2, int flip, int line,
|
||||
TMS event) {
|
||||
int v2 = int2sC(cast_int(e2->u.ival)); /* immediate operand */
|
||||
lua_assert(e2->k == VKINT);
|
||||
finishbinexpval(fs, e1, e2, op, v2, flip, line, OP_MMBINI, event);
|
||||
}
|
||||
|
||||
|
||||
/* Try to code a binary operator negating its second operand.
|
||||
** For the metamethod, 2nd operand must keep its original value.
|
||||
*/
|
||||
static int finishbinexpneg (FuncState *fs, expdesc *e1, expdesc *e2,
|
||||
OpCode op, int line, TMS event) {
|
||||
if (!luaK_isKint(e2))
|
||||
return 0; /* not an integer constant */
|
||||
else {
|
||||
lua_Integer i2 = e2->u.ival;
|
||||
if (!(fitsC(i2) && fitsC(-i2)))
|
||||
return 0; /* not in the proper range */
|
||||
else { /* operating a small integer constant */
|
||||
int v2 = cast_int(i2);
|
||||
finishbinexpval(fs, e1, e2, op, int2sC(-v2), 0, line, OP_MMBINI, event);
|
||||
/* correct metamethod argument */
|
||||
SETARG_B(fs->f->code[fs->pc - 1], int2sC(v2));
|
||||
return 1; /* successfully coded */
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1300,19 +1439,18 @@ static void swapexps (expdesc *e1, expdesc *e2) {
|
||||
|
||||
/*
|
||||
** Code arithmetic operators ('+', '-', ...). If second operand is a
|
||||
** constant in the proper range, use variant opcodes with immediate
|
||||
** operands or K operands.
|
||||
** constant in the proper range, use variant opcodes with K operands.
|
||||
*/
|
||||
static void codearith (FuncState *fs, OpCode op,
|
||||
static void codearith (FuncState *fs, BinOpr opr,
|
||||
expdesc *e1, expdesc *e2, int flip, int line) {
|
||||
if (isSCint(e2)) /* immediate operand? */
|
||||
codebini(fs, cast(OpCode, op - OP_ADD + OP_ADDI), e1, e2, flip, line);
|
||||
else if (tonumeral(e2, NULL) && luaK_exp2K(fs, e2)) { /* K operand? */
|
||||
TMS event = cast(TMS, opr + TM_ADD);
|
||||
if (tonumeral(e2, NULL) && luaK_exp2K(fs, e2)) { /* K operand? */
|
||||
int v2 = e2->u.info; /* K index */
|
||||
op = cast(OpCode, op - OP_ADD + OP_ADDK);
|
||||
finishbinexpval(fs, e1, e2, op, v2, flip, line);
|
||||
OpCode op = cast(OpCode, opr + OP_ADDK);
|
||||
finishbinexpval(fs, e1, e2, op, v2, flip, line, OP_MMBINK, event);
|
||||
}
|
||||
else { /* 'e2' is neither an immediate nor a K operand */
|
||||
OpCode op = cast(OpCode, opr + OP_ADD);
|
||||
if (flip)
|
||||
swapexps(e1, e2); /* back to original order */
|
||||
codebinexpval(fs, op, e1, e2, line); /* use standard operators */
|
||||
@@ -1325,14 +1463,17 @@ static void codearith (FuncState *fs, OpCode op,
|
||||
** numeric constant, change order of operands to try to use an
|
||||
** immediate or K operator.
|
||||
*/
|
||||
static void codecommutative (FuncState *fs, OpCode op,
|
||||
static void codecommutative (FuncState *fs, BinOpr op,
|
||||
expdesc *e1, expdesc *e2, int line) {
|
||||
int flip = 0;
|
||||
if (tonumeral(e1, NULL)) { /* is first operand a numeric constant? */
|
||||
swapexps(e1, e2); /* change order */
|
||||
flip = 1;
|
||||
}
|
||||
codearith(fs, op, e1, e2, flip, line);
|
||||
if (op == OPR_ADD && isSCint(e2)) /* immediate operand? */
|
||||
codebini(fs, cast(OpCode, OP_ADDI), e1, e2, flip, line, TM_ADD);
|
||||
else
|
||||
codearith(fs, op, e1, e2, flip, line);
|
||||
}
|
||||
|
||||
|
||||
@@ -1342,41 +1483,23 @@ static void codecommutative (FuncState *fs, OpCode op,
|
||||
*/
|
||||
static void codebitwise (FuncState *fs, BinOpr opr,
|
||||
expdesc *e1, expdesc *e2, int line) {
|
||||
int inv = 0;
|
||||
int flip = 0;
|
||||
int v2;
|
||||
OpCode op;
|
||||
if (e1->k == VKINT && luaK_exp2RK(fs, e1)) {
|
||||
swapexps(e1, e2); /* 'e2' will be the constant operand */
|
||||
inv = 1;
|
||||
flip = 1;
|
||||
}
|
||||
else if (!(e2->k == VKINT && luaK_exp2RK(fs, e2))) { /* no constants? */
|
||||
op = cast(OpCode, opr - OPR_BAND + OP_BAND);
|
||||
op = cast(OpCode, opr + OP_ADD);
|
||||
codebinexpval(fs, op, e1, e2, line); /* all-register opcodes */
|
||||
return;
|
||||
}
|
||||
v2 = e2->u.info; /* index in K array */
|
||||
op = cast(OpCode, opr - OPR_BAND + OP_BANDK);
|
||||
op = cast(OpCode, opr + OP_ADDK);
|
||||
lua_assert(ttisinteger(&fs->f->k[v2]));
|
||||
finishbinexpval(fs, e1, e2, op, v2, inv, line);
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** Code shift operators. If second operand is constant, use immediate
|
||||
** operand (negating it if shift is in the other direction).
|
||||
*/
|
||||
static void codeshift (FuncState *fs, OpCode op,
|
||||
expdesc *e1, expdesc *e2, int line) {
|
||||
if (isSCint(e2)) {
|
||||
int changedir = 0;
|
||||
if (op == OP_SHL) {
|
||||
changedir = 1;
|
||||
e2->u.ival = -(e2->u.ival);
|
||||
}
|
||||
codebini(fs, OP_SHRI, e1, e2, changedir, line);
|
||||
}
|
||||
else
|
||||
codebinexpval(fs, op, e1, e2, line);
|
||||
finishbinexpval(fs, e1, e2, op, v2, flip, line, OP_MMBINK,
|
||||
cast(TMS, opr + TM_ADD));
|
||||
}
|
||||
|
||||
|
||||
@@ -1386,18 +1509,18 @@ static void codeshift (FuncState *fs, OpCode op,
|
||||
*/
|
||||
static void codeorder (FuncState *fs, OpCode op, expdesc *e1, expdesc *e2) {
|
||||
int r1, r2;
|
||||
lua_Integer im;
|
||||
int im;
|
||||
int isfloat = 0;
|
||||
if (isSCnumber(e2, &im, &isfloat)) {
|
||||
/* use immediate operand */
|
||||
r1 = luaK_exp2anyreg(fs, e1);
|
||||
r2 = cast_int(im);
|
||||
r2 = im;
|
||||
op = cast(OpCode, (op - OP_LT) + OP_LTI);
|
||||
}
|
||||
else if (isSCnumber(e1, &im, &isfloat)) {
|
||||
/* transform (A < B) to (B > A) and (A <= B) to (B >= A) */
|
||||
r1 = luaK_exp2anyreg(fs, e2);
|
||||
r2 = cast_int(im);
|
||||
r2 = im;
|
||||
op = (op == OP_LT) ? OP_GTI : OP_GEI;
|
||||
}
|
||||
else { /* regular case, compare two registers */
|
||||
@@ -1416,17 +1539,17 @@ static void codeorder (FuncState *fs, OpCode op, expdesc *e1, expdesc *e2) {
|
||||
*/
|
||||
static void codeeq (FuncState *fs, BinOpr opr, expdesc *e1, expdesc *e2) {
|
||||
int r1, r2;
|
||||
lua_Integer im;
|
||||
int im;
|
||||
int isfloat = 0; /* not needed here, but kept for symmetry */
|
||||
OpCode op;
|
||||
if (e1->k != VNONRELOC) {
|
||||
lua_assert(e1->k == VK || e1->k == VKINT || e1->k == VKFLT);
|
||||
swapexps(e1, e2);
|
||||
}
|
||||
r1 = luaK_exp2anyreg(fs, e1); /* 1nd expression must be in register */
|
||||
r1 = luaK_exp2anyreg(fs, e1); /* 1st expression must be in register */
|
||||
if (isSCnumber(e2, &im, &isfloat)) {
|
||||
op = OP_EQI;
|
||||
r2 = cast_int(im); /* immediate operand */
|
||||
r2 = im; /* immediate operand */
|
||||
}
|
||||
else if (luaK_exp2RK(fs, e2)) { /* 1st expression is constant? */
|
||||
op = OP_EQK;
|
||||
@@ -1447,11 +1570,12 @@ static void codeeq (FuncState *fs, BinOpr opr, expdesc *e1, expdesc *e2) {
|
||||
*/
|
||||
void luaK_prefix (FuncState *fs, UnOpr op, expdesc *e, int line) {
|
||||
static const expdesc ef = {VKINT, {0}, NO_JUMP, NO_JUMP};
|
||||
luaK_dischargevars(fs, e);
|
||||
switch (op) {
|
||||
case OPR_MINUS: case OPR_BNOT: /* use 'ef' as fake 2nd operand */
|
||||
if (constfolding(fs, op + LUA_OPUNM, e, &ef))
|
||||
break;
|
||||
/* FALLTHROUGH */
|
||||
/* else */ /* FALLTHROUGH */
|
||||
case OPR_LEN:
|
||||
codeunexpval(fs, cast(OpCode, op + OP_UNM), e, line);
|
||||
break;
|
||||
@@ -1466,6 +1590,7 @@ void luaK_prefix (FuncState *fs, UnOpr op, expdesc *e, int line) {
|
||||
** 2nd operand.
|
||||
*/
|
||||
void luaK_infix (FuncState *fs, BinOpr op, expdesc *v) {
|
||||
luaK_dischargevars(fs, v);
|
||||
switch (op) {
|
||||
case OPR_AND: {
|
||||
luaK_goiftrue(fs, v); /* go ahead only if 'v' is true */
|
||||
@@ -1497,8 +1622,7 @@ void luaK_infix (FuncState *fs, BinOpr op, expdesc *v) {
|
||||
}
|
||||
case OPR_LT: case OPR_LE:
|
||||
case OPR_GT: case OPR_GE: {
|
||||
lua_Integer dummy;
|
||||
int dummy2;
|
||||
int dummy, dummy2;
|
||||
if (!isSCnumber(v, &dummy, &dummy2))
|
||||
luaK_exp2anyreg(fs, v);
|
||||
/* else keep numeral, which may be an immediate operand */
|
||||
@@ -1535,17 +1659,18 @@ static void codeconcat (FuncState *fs, expdesc *e1, expdesc *e2, int line) {
|
||||
*/
|
||||
void luaK_posfix (FuncState *fs, BinOpr opr,
|
||||
expdesc *e1, expdesc *e2, int line) {
|
||||
luaK_dischargevars(fs, e2);
|
||||
if (foldbinop(opr) && constfolding(fs, opr + LUA_OPADD, e1, e2))
|
||||
return; /* done by folding */
|
||||
switch (opr) {
|
||||
case OPR_AND: {
|
||||
lua_assert(e1->t == NO_JUMP); /* list closed by 'luK_infix' */
|
||||
luaK_dischargevars(fs, e2);
|
||||
lua_assert(e1->t == NO_JUMP); /* list closed by 'luaK_infix' */
|
||||
luaK_concat(fs, &e2->f, e1->f);
|
||||
*e1 = *e2;
|
||||
break;
|
||||
}
|
||||
case OPR_OR: {
|
||||
lua_assert(e1->f == NO_JUMP); /* list closed by 'luK_infix' */
|
||||
luaK_dischargevars(fs, e2);
|
||||
lua_assert(e1->f == NO_JUMP); /* list closed by 'luaK_infix' */
|
||||
luaK_concat(fs, &e2->t, e1->t);
|
||||
*e1 = *e2;
|
||||
break;
|
||||
@@ -1556,35 +1681,39 @@ void luaK_posfix (FuncState *fs, BinOpr opr,
|
||||
break;
|
||||
}
|
||||
case OPR_ADD: case OPR_MUL: {
|
||||
if (!constfolding(fs, opr + LUA_OPADD, e1, e2))
|
||||
codecommutative(fs, cast(OpCode, opr + OP_ADD), e1, e2, line);
|
||||
codecommutative(fs, opr, e1, e2, line);
|
||||
break;
|
||||
}
|
||||
case OPR_SUB: case OPR_DIV:
|
||||
case OPR_IDIV: case OPR_MOD: case OPR_POW: {
|
||||
if (!constfolding(fs, opr + LUA_OPADD, e1, e2))
|
||||
codearith(fs, cast(OpCode, opr + OP_ADD), e1, e2, 0, line);
|
||||
case OPR_SUB: {
|
||||
if (finishbinexpneg(fs, e1, e2, OP_ADDI, line, TM_SUB))
|
||||
break; /* coded as (r1 + -I) */
|
||||
/* ELSE */
|
||||
} /* FALLTHROUGH */
|
||||
case OPR_DIV: case OPR_IDIV: case OPR_MOD: case OPR_POW: {
|
||||
codearith(fs, opr, e1, e2, 0, line);
|
||||
break;
|
||||
}
|
||||
case OPR_BAND: case OPR_BOR: case OPR_BXOR: {
|
||||
if (!constfolding(fs, opr + LUA_OPADD, e1, e2))
|
||||
codebitwise(fs, opr, e1, e2, line);
|
||||
codebitwise(fs, opr, e1, e2, line);
|
||||
break;
|
||||
}
|
||||
case OPR_SHL: {
|
||||
if (!constfolding(fs, LUA_OPSHL, e1, e2)) {
|
||||
if (isSCint(e1)) {
|
||||
swapexps(e1, e2);
|
||||
codebini(fs, OP_SHLI, e1, e2, 1, line);
|
||||
}
|
||||
else
|
||||
codeshift(fs, OP_SHL, e1, e2, line);
|
||||
if (isSCint(e1)) {
|
||||
swapexps(e1, e2);
|
||||
codebini(fs, OP_SHLI, e1, e2, 1, line, TM_SHL); /* I << r2 */
|
||||
}
|
||||
else if (finishbinexpneg(fs, e1, e2, OP_SHRI, line, TM_SHL)) {
|
||||
/* coded as (r1 >> -I) */;
|
||||
}
|
||||
else /* regular case (two registers) */
|
||||
codebinexpval(fs, OP_SHL, e1, e2, line);
|
||||
break;
|
||||
}
|
||||
case OPR_SHR: {
|
||||
if (!constfolding(fs, LUA_OPSHR, e1, e2))
|
||||
codeshift(fs, OP_SHR, e1, e2, line);
|
||||
if (isSCint(e2))
|
||||
codebini(fs, OP_SHRI, e1, e2, 0, line, TM_SHR); /* r1 >> I */
|
||||
else /* regular case (two registers) */
|
||||
codebinexpval(fs, OP_SHR, e1, e2, line);
|
||||
break;
|
||||
}
|
||||
case OPR_EQ: case OPR_NE: {
|
||||
@@ -1618,6 +1747,17 @@ void luaK_fixline (FuncState *fs, int line) {
|
||||
}
|
||||
|
||||
|
||||
void luaK_settablesize (FuncState *fs, int pc, int ra, int asize, int hsize) {
|
||||
Instruction *inst = &fs->f->code[pc];
|
||||
int rb = (hsize != 0) ? luaO_ceillog2(hsize) + 1 : 0; /* hash size */
|
||||
int extra = asize / (MAXARG_C + 1); /* higher bits of array size */
|
||||
int rc = asize % (MAXARG_C + 1); /* lower bits of array size */
|
||||
int k = (extra > 0); /* true iff needs extra argument */
|
||||
*inst = CREATE_ABCk(OP_NEWTABLE, ra, rb, rc, k);
|
||||
*(inst + 1) = CREATE_Ax(OP_EXTRAARG, extra);
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** Emit a SETLIST instruction.
|
||||
** 'base' is register that keeps table;
|
||||
@@ -1626,17 +1766,17 @@ void luaK_fixline (FuncState *fs, int line) {
|
||||
** table (or LUA_MULTRET to add up to stack top).
|
||||
*/
|
||||
void luaK_setlist (FuncState *fs, int base, int nelems, int tostore) {
|
||||
int c = (nelems - 1)/LFIELDS_PER_FLUSH + 1;
|
||||
int b = (tostore == LUA_MULTRET) ? 0 : tostore;
|
||||
lua_assert(tostore != 0 && tostore <= LFIELDS_PER_FLUSH);
|
||||
if (c <= MAXARG_C)
|
||||
luaK_codeABC(fs, OP_SETLIST, base, b, c);
|
||||
else if (c <= MAXARG_Ax) {
|
||||
luaK_codeABC(fs, OP_SETLIST, base, b, 0);
|
||||
codeextraarg(fs, c);
|
||||
if (tostore == LUA_MULTRET)
|
||||
tostore = 0;
|
||||
if (nelems <= MAXARG_C)
|
||||
luaK_codeABC(fs, OP_SETLIST, base, tostore, nelems);
|
||||
else {
|
||||
int extra = nelems / (MAXARG_C + 1);
|
||||
nelems %= (MAXARG_C + 1);
|
||||
luaK_codeABCk(fs, OP_SETLIST, base, tostore, nelems, 1);
|
||||
codeextraarg(fs, extra);
|
||||
}
|
||||
else
|
||||
luaX_syntaxerror(fs->ls, "constructor too long");
|
||||
fs->freereg = base + 1; /* free registers with list values */
|
||||
}
|
||||
|
||||
@@ -1675,10 +1815,10 @@ void luaK_finish (FuncState *fs) {
|
||||
SET_OPCODE(*pc, OP_RETURN);
|
||||
} /* FALLTHROUGH */
|
||||
case OP_RETURN: case OP_TAILCALL: {
|
||||
if (fs->needclose || p->is_vararg) {
|
||||
SETARG_C(*pc, p->is_vararg ? p->numparams + 1 : 0);
|
||||
SETARG_k(*pc, 1); /* signal that there is extra work */
|
||||
}
|
||||
if (fs->needclose)
|
||||
SETARG_k(*pc, 1); /* signal that it needs to close */
|
||||
if (p->is_vararg)
|
||||
SETARG_C(*pc, p->numparams + 1); /* signal that it is vararg */
|
||||
break;
|
||||
}
|
||||
case OP_JMP: {
|
||||
|
||||
@@ -24,19 +24,27 @@
|
||||
** grep "ORDER OPR" if you change these enums (ORDER OP)
|
||||
*/
|
||||
typedef enum BinOpr {
|
||||
/* arithmetic operators */
|
||||
OPR_ADD, OPR_SUB, OPR_MUL, OPR_MOD, OPR_POW,
|
||||
OPR_DIV,
|
||||
OPR_IDIV,
|
||||
OPR_DIV, OPR_IDIV,
|
||||
/* bitwise operators */
|
||||
OPR_BAND, OPR_BOR, OPR_BXOR,
|
||||
OPR_SHL, OPR_SHR,
|
||||
/* string operator */
|
||||
OPR_CONCAT,
|
||||
/* comparison operators */
|
||||
OPR_EQ, OPR_LT, OPR_LE,
|
||||
OPR_NE, OPR_GT, OPR_GE,
|
||||
/* logical operators */
|
||||
OPR_AND, OPR_OR,
|
||||
OPR_NOBINOPR
|
||||
} BinOpr;
|
||||
|
||||
|
||||
/* true if operation is foldable (that is, it is arithmetic or bitwise) */
|
||||
#define foldbinop(op) ((op) <= OPR_SHR)
|
||||
|
||||
|
||||
#define luaK_codeABC(fs,o,a,b,c) luaK_codeABCk(fs,o,a,b,c,0)
|
||||
|
||||
|
||||
@@ -51,16 +59,17 @@ typedef enum UnOpr { OPR_MINUS, OPR_BNOT, OPR_NOT, OPR_LEN, OPR_NOUNOPR } UnOpr;
|
||||
|
||||
#define luaK_jumpto(fs,t) luaK_patchlist(fs, luaK_jump(fs), t)
|
||||
|
||||
LUAI_FUNC int luaK_code (FuncState *fs, Instruction i);
|
||||
LUAI_FUNC int luaK_codeABx (FuncState *fs, OpCode o, int A, unsigned int Bx);
|
||||
LUAI_FUNC int luaK_codeAsBx (FuncState *fs, OpCode o, int A, int Bx);
|
||||
LUAI_FUNC int luaK_codeABCk (FuncState *fs, OpCode o, int A,
|
||||
int B, int C, int k);
|
||||
LUAI_FUNC int luaK_isKint (expdesc *e);
|
||||
LUAI_FUNC int luaK_exp2const (FuncState *fs, const expdesc *e, TValue *v);
|
||||
LUAI_FUNC void luaK_fixline (FuncState *fs, int line);
|
||||
LUAI_FUNC void luaK_nil (FuncState *fs, int from, int n);
|
||||
LUAI_FUNC void luaK_reserveregs (FuncState *fs, int n);
|
||||
LUAI_FUNC void luaK_checkstack (FuncState *fs, int n);
|
||||
LUAI_FUNC int luaK_stringK (FuncState *fs, TString *s);
|
||||
LUAI_FUNC void luaK_int (FuncState *fs, int reg, lua_Integer n);
|
||||
LUAI_FUNC void luaK_dischargevars (FuncState *fs, expdesc *e);
|
||||
LUAI_FUNC int luaK_exp2anyreg (FuncState *fs, expdesc *e);
|
||||
@@ -85,6 +94,8 @@ LUAI_FUNC void luaK_prefix (FuncState *fs, UnOpr op, expdesc *v, int line);
|
||||
LUAI_FUNC void luaK_infix (FuncState *fs, BinOpr op, expdesc *v);
|
||||
LUAI_FUNC void luaK_posfix (FuncState *fs, BinOpr op, expdesc *v1,
|
||||
expdesc *v2, int line);
|
||||
LUAI_FUNC void luaK_settablesize (FuncState *fs, int pc,
|
||||
int ra, int asize, int hsize);
|
||||
LUAI_FUNC void luaK_setlist (FuncState *fs, int base, int nelems, int tostore);
|
||||
LUAI_FUNC void luaK_finish (FuncState *fs);
|
||||
LUAI_FUNC l_noret luaK_semerror (LexState *ls, const char *msg);
|
||||
|
||||
+15
-10
@@ -31,14 +31,14 @@ static lua_State *getco (lua_State *L) {
|
||||
*/
|
||||
static int auxresume (lua_State *L, lua_State *co, int narg) {
|
||||
int status, nres;
|
||||
if (!lua_checkstack(co, narg)) {
|
||||
if (l_unlikely(!lua_checkstack(co, narg))) {
|
||||
lua_pushliteral(L, "too many arguments to resume");
|
||||
return -1; /* error flag */
|
||||
}
|
||||
lua_xmove(L, co, narg);
|
||||
status = lua_resume(co, L, narg, &nres);
|
||||
if (status == LUA_OK || status == LUA_YIELD) {
|
||||
if (!lua_checkstack(L, nres + 1)) {
|
||||
if (l_likely(status == LUA_OK || status == LUA_YIELD)) {
|
||||
if (l_unlikely(!lua_checkstack(L, nres + 1))) {
|
||||
lua_pop(co, nres); /* remove results anyway */
|
||||
lua_pushliteral(L, "too many results to resume");
|
||||
return -1; /* error flag */
|
||||
@@ -57,7 +57,7 @@ static int luaB_coresume (lua_State *L) {
|
||||
lua_State *co = getco(L);
|
||||
int r;
|
||||
r = auxresume(L, co, lua_gettop(L) - 1);
|
||||
if (r < 0) {
|
||||
if (l_unlikely(r < 0)) {
|
||||
lua_pushboolean(L, 0);
|
||||
lua_insert(L, -2);
|
||||
return 2; /* return false + error message */
|
||||
@@ -73,11 +73,15 @@ static int luaB_coresume (lua_State *L) {
|
||||
static int luaB_auxwrap (lua_State *L) {
|
||||
lua_State *co = lua_tothread(L, lua_upvalueindex(1));
|
||||
int r = auxresume(L, co, lua_gettop(L));
|
||||
if (r < 0) {
|
||||
if (l_unlikely(r < 0)) { /* error? */
|
||||
int stat = lua_status(co);
|
||||
if (stat != LUA_OK && stat != LUA_YIELD)
|
||||
lua_resetthread(co); /* close variables in case of errors */
|
||||
if (lua_type(L, -1) == LUA_TSTRING) { /* error object is a string? */
|
||||
if (stat != LUA_OK && stat != LUA_YIELD) { /* error in the coroutine? */
|
||||
stat = lua_resetthread(co); /* close its tbc variables */
|
||||
lua_assert(stat != LUA_OK);
|
||||
lua_xmove(co, L, 1); /* move error message to the caller */
|
||||
}
|
||||
if (stat != LUA_ERRMEM && /* not a memory error and ... */
|
||||
lua_type(L, -1) == LUA_TSTRING) { /* ... error object is a string? */
|
||||
luaL_where(L, 1); /* add extra info, if available */
|
||||
lua_insert(L, -2);
|
||||
lua_concat(L, 2);
|
||||
@@ -116,7 +120,8 @@ static int luaB_yield (lua_State *L) {
|
||||
#define COS_NORM 3
|
||||
|
||||
|
||||
static const char *statname[] = {"running", "dead", "suspended", "normal"};
|
||||
static const char *const statname[] =
|
||||
{"running", "dead", "suspended", "normal"};
|
||||
|
||||
|
||||
static int auxstatus (lua_State *L, lua_State *co) {
|
||||
@@ -174,7 +179,7 @@ static int luaB_close (lua_State *L) {
|
||||
}
|
||||
else {
|
||||
lua_pushboolean(L, 0);
|
||||
lua_xmove(co, L, 1); /* copy error message */
|
||||
lua_xmove(co, L, 1); /* move error message */
|
||||
return 2;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,6 +16,15 @@
|
||||
|
||||
#include <limits.h>
|
||||
|
||||
|
||||
#if defined (LUA_UCID) /* accept UniCode IDentifiers? */
|
||||
/* consider all non-ascii codepoints to be alphabetic */
|
||||
#define NONA 0x01
|
||||
#else
|
||||
#define NONA 0x00 /* default */
|
||||
#endif
|
||||
|
||||
|
||||
LUAI_DDEF const lu_byte luai_ctype_[UCHAR_MAX + 2] = {
|
||||
0x00, /* EOZ */
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 0. */
|
||||
@@ -34,22 +43,22 @@ LUAI_DDEF const lu_byte luai_ctype_[UCHAR_MAX + 2] = {
|
||||
0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05,
|
||||
0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, /* 7. */
|
||||
0x05, 0x05, 0x05, 0x04, 0x04, 0x04, 0x04, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 8. */
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 9. */
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* a. */
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* b. */
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* c. */
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* d. */
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* e. */
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* f. */
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, /* 8. */
|
||||
NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA,
|
||||
NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, /* 9. */
|
||||
NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA,
|
||||
NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, /* a. */
|
||||
NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA,
|
||||
NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, /* b. */
|
||||
NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA,
|
||||
0x00, 0x00, NONA, NONA, NONA, NONA, NONA, NONA, /* c. */
|
||||
NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA,
|
||||
NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, /* d. */
|
||||
NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA,
|
||||
NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA, /* e. */
|
||||
NONA, NONA, NONA, NONA, NONA, NONA, NONA, NONA,
|
||||
NONA, NONA, NONA, NONA, NONA, 0x00, 0x00, 0x00, /* f. */
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
|
||||
};
|
||||
|
||||
#endif /* } */
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
/*
|
||||
** WARNING: the functions defined here do not necessarily correspond
|
||||
** to the similar functions in the standard C ctype.h. They are
|
||||
** optimized for the specific needs of Lua
|
||||
** optimized for the specific needs of Lua.
|
||||
*/
|
||||
|
||||
#if !defined(LUA_USE_CTYPE)
|
||||
@@ -61,13 +61,19 @@
|
||||
#define lisprint(c) testprop(c, MASK(PRINTBIT))
|
||||
#define lisxdigit(c) testprop(c, MASK(XDIGITBIT))
|
||||
|
||||
|
||||
/*
|
||||
** this 'ltolower' only works for alphabetic characters
|
||||
** In ASCII, this 'ltolower' is correct for alphabetic characters and
|
||||
** for '.'. That is enough for Lua needs. ('check_exp' ensures that
|
||||
** the character either is an upper-case letter or is unchanged by
|
||||
** the transformation, which holds for lower-case letters and '.'.)
|
||||
*/
|
||||
#define ltolower(c) ((c) | ('A' ^ 'a'))
|
||||
#define ltolower(c) \
|
||||
check_exp(('A' <= (c) && (c) <= 'Z') || (c) == ((c) | ('A' ^ 'a')), \
|
||||
(c) | ('A' ^ 'a'))
|
||||
|
||||
|
||||
/* two more entries for 0 and -1 (EOZ) */
|
||||
/* one entry for each character and for -1 (EOZ) */
|
||||
LUAI_DDEC(const lu_byte luai_ctype_[UCHAR_MAX + 2];)
|
||||
|
||||
|
||||
|
||||
@@ -21,10 +21,10 @@
|
||||
|
||||
|
||||
/*
|
||||
** The hook table at registry[&HOOKKEY] maps threads to their current
|
||||
** hook function. (We only need the unique address of 'HOOKKEY'.)
|
||||
** The hook table at registry[HOOKKEY] maps threads to their current
|
||||
** hook function.
|
||||
*/
|
||||
static const int HOOKKEY = 0;
|
||||
static const char *const HOOKKEY = "_HOOKKEY";
|
||||
|
||||
|
||||
/*
|
||||
@@ -33,7 +33,7 @@ static const int HOOKKEY = 0;
|
||||
** checked.
|
||||
*/
|
||||
static void checkstack (lua_State *L, lua_State *L1, int n) {
|
||||
if (L != L1 && !lua_checkstack(L1, n))
|
||||
if (l_unlikely(L != L1 && !lua_checkstack(L1, n)))
|
||||
luaL_error(L, "stack overflow");
|
||||
}
|
||||
|
||||
@@ -65,7 +65,7 @@ static int db_setmetatable (lua_State *L) {
|
||||
static int db_getuservalue (lua_State *L) {
|
||||
int n = (int)luaL_optinteger(L, 2, 1);
|
||||
if (lua_type(L, 1) != LUA_TUSERDATA)
|
||||
lua_pushnil(L);
|
||||
luaL_pushfail(L);
|
||||
else if (lua_getiuservalue(L, 1, n) != LUA_TNONE) {
|
||||
lua_pushboolean(L, 1);
|
||||
return 2;
|
||||
@@ -80,7 +80,7 @@ static int db_setuservalue (lua_State *L) {
|
||||
luaL_checkany(L, 2);
|
||||
lua_settop(L, 2);
|
||||
if (!lua_setiuservalue(L, 1, n))
|
||||
lua_pushnil(L);
|
||||
luaL_pushfail(L);
|
||||
return 1;
|
||||
}
|
||||
|
||||
@@ -152,6 +152,7 @@ static int db_getinfo (lua_State *L) {
|
||||
lua_State *L1 = getthread(L, &arg);
|
||||
const char *options = luaL_optstring(L, arg+2, "flnSrtu");
|
||||
checkstack(L, L1, 3);
|
||||
luaL_argcheck(L, options[0] != '>', arg + 2, "invalid option '>'");
|
||||
if (lua_isfunction(L, arg + 1)) { /* info about a function? */
|
||||
options = lua_pushfstring(L, ">%s", options); /* add '>' to 'options' */
|
||||
lua_pushvalue(L, arg + 1); /* move function to 'L1' stack */
|
||||
@@ -159,7 +160,7 @@ static int db_getinfo (lua_State *L) {
|
||||
}
|
||||
else { /* stack level */
|
||||
if (!lua_getstack(L1, (int)luaL_checkinteger(L, arg + 1), &ar)) {
|
||||
lua_pushnil(L); /* level out of range */
|
||||
luaL_pushfail(L); /* level out of range */
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
@@ -202,8 +203,6 @@ static int db_getinfo (lua_State *L) {
|
||||
static int db_getlocal (lua_State *L) {
|
||||
int arg;
|
||||
lua_State *L1 = getthread(L, &arg);
|
||||
lua_Debug ar;
|
||||
const char *name;
|
||||
int nvar = (int)luaL_checkinteger(L, arg + 2); /* local-variable index */
|
||||
if (lua_isfunction(L, arg + 1)) { /* function argument? */
|
||||
lua_pushvalue(L, arg + 1); /* push function */
|
||||
@@ -211,8 +210,10 @@ static int db_getlocal (lua_State *L) {
|
||||
return 1; /* return only name (there is no value) */
|
||||
}
|
||||
else { /* stack-level argument */
|
||||
lua_Debug ar;
|
||||
const char *name;
|
||||
int level = (int)luaL_checkinteger(L, arg + 1);
|
||||
if (!lua_getstack(L1, level, &ar)) /* out of range? */
|
||||
if (l_unlikely(!lua_getstack(L1, level, &ar))) /* out of range? */
|
||||
return luaL_argerror(L, arg+1, "level out of range");
|
||||
checkstack(L, L1, 1);
|
||||
name = lua_getlocal(L1, &ar, nvar);
|
||||
@@ -223,7 +224,7 @@ static int db_getlocal (lua_State *L) {
|
||||
return 2;
|
||||
}
|
||||
else {
|
||||
lua_pushnil(L); /* no name (nor value) */
|
||||
luaL_pushfail(L); /* no name (nor value) */
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
@@ -237,7 +238,7 @@ static int db_setlocal (lua_State *L) {
|
||||
lua_Debug ar;
|
||||
int level = (int)luaL_checkinteger(L, arg + 1);
|
||||
int nvar = (int)luaL_checkinteger(L, arg + 2);
|
||||
if (!lua_getstack(L1, level, &ar)) /* out of range? */
|
||||
if (l_unlikely(!lua_getstack(L1, level, &ar))) /* out of range? */
|
||||
return luaL_argerror(L, arg+1, "level out of range");
|
||||
luaL_checkany(L, arg+3);
|
||||
lua_settop(L, arg+3);
|
||||
@@ -281,25 +282,33 @@ static int db_setupvalue (lua_State *L) {
|
||||
** Check whether a given upvalue from a given closure exists and
|
||||
** returns its index
|
||||
*/
|
||||
static int checkupval (lua_State *L, int argf, int argnup) {
|
||||
static void *checkupval (lua_State *L, int argf, int argnup, int *pnup) {
|
||||
void *id;
|
||||
int nup = (int)luaL_checkinteger(L, argnup); /* upvalue index */
|
||||
luaL_checktype(L, argf, LUA_TFUNCTION); /* closure */
|
||||
luaL_argcheck(L, (lua_getupvalue(L, argf, nup) != NULL), argnup,
|
||||
"invalid upvalue index");
|
||||
return nup;
|
||||
id = lua_upvalueid(L, argf, nup);
|
||||
if (pnup) {
|
||||
luaL_argcheck(L, id != NULL, argnup, "invalid upvalue index");
|
||||
*pnup = nup;
|
||||
}
|
||||
return id;
|
||||
}
|
||||
|
||||
|
||||
static int db_upvalueid (lua_State *L) {
|
||||
int n = checkupval(L, 1, 2);
|
||||
lua_pushlightuserdata(L, lua_upvalueid(L, 1, n));
|
||||
void *id = checkupval(L, 1, 2, NULL);
|
||||
if (id != NULL)
|
||||
lua_pushlightuserdata(L, id);
|
||||
else
|
||||
luaL_pushfail(L);
|
||||
return 1;
|
||||
}
|
||||
|
||||
|
||||
static int db_upvaluejoin (lua_State *L) {
|
||||
int n1 = checkupval(L, 1, 2);
|
||||
int n2 = checkupval(L, 3, 4);
|
||||
int n1, n2;
|
||||
checkupval(L, 1, 2, &n1);
|
||||
checkupval(L, 3, 4, &n2);
|
||||
luaL_argcheck(L, !lua_iscfunction(L, 1), 1, "Lua function expected");
|
||||
luaL_argcheck(L, !lua_iscfunction(L, 3), 3, "Lua function expected");
|
||||
lua_upvaluejoin(L, 1, n1, 3, n2);
|
||||
@@ -314,7 +323,7 @@ static int db_upvaluejoin (lua_State *L) {
|
||||
static void hookf (lua_State *L, lua_Debug *ar) {
|
||||
static const char *const hooknames[] =
|
||||
{"call", "return", "line", "count", "tail call"};
|
||||
lua_rawgetp(L, LUA_REGISTRYINDEX, &HOOKKEY);
|
||||
lua_getfield(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 */
|
||||
@@ -367,14 +376,12 @@ static int db_sethook (lua_State *L) {
|
||||
count = (int)luaL_optinteger(L, arg + 3, 0);
|
||||
func = hookf; mask = makemask(smask, count);
|
||||
}
|
||||
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");
|
||||
if (!luaL_getsubtable(L, LUA_REGISTRYINDEX, HOOKKEY)) {
|
||||
/* table just created; initialize it */
|
||||
lua_pushliteral(L, "k");
|
||||
lua_setfield(L, -2, "__mode"); /** hooktable.__mode = "k" */
|
||||
lua_pushvalue(L, -1);
|
||||
lua_setmetatable(L, -2); /* setmetatable(hooktable) = hooktable */
|
||||
lua_setmetatable(L, -2); /* metatable(hooktable) = hooktable */
|
||||
}
|
||||
checkstack(L, L1, 1);
|
||||
lua_pushthread(L1); lua_xmove(L1, L, 1); /* key (thread) */
|
||||
@@ -391,12 +398,14 @@ static int db_gethook (lua_State *L) {
|
||||
char buff[5];
|
||||
int mask = lua_gethookmask(L1);
|
||||
lua_Hook hook = lua_gethook(L1);
|
||||
if (hook == NULL) /* no hook? */
|
||||
lua_pushnil(L);
|
||||
if (hook == NULL) { /* no hook? */
|
||||
luaL_pushfail(L);
|
||||
return 1;
|
||||
}
|
||||
else if (hook != hookf) /* external hook? */
|
||||
lua_pushliteral(L, "external hook");
|
||||
else { /* hook table must exist */
|
||||
lua_rawgetp(L, LUA_REGISTRYINDEX, &HOOKKEY);
|
||||
lua_getfield(L, LUA_REGISTRYINDEX, HOOKKEY);
|
||||
checkstack(L, L1, 1);
|
||||
lua_pushthread(L1); lua_xmove(L1, L, 1);
|
||||
lua_rawget(L, -2); /* 1st result = hooktable[L1] */
|
||||
@@ -412,12 +421,12 @@ static int db_debug (lua_State *L) {
|
||||
for (;;) {
|
||||
char buffer[250];
|
||||
lua_writestringerror("%s", "lua_debug> ");
|
||||
if (fgets(buffer, sizeof(buffer), stdin) == 0 ||
|
||||
if (fgets(buffer, sizeof(buffer), stdin) == NULL ||
|
||||
strcmp(buffer, "cont\n") == 0)
|
||||
return 0;
|
||||
if (luaL_loadbuffer(L, buffer, strlen(buffer), "=(debug command)") ||
|
||||
lua_pcall(L, 0, 0, 0))
|
||||
lua_writestringerror("%s\n", lua_tostring(L, -1));
|
||||
lua_writestringerror("%s\n", luaL_tolstring(L, -1, NULL));
|
||||
lua_settop(L, 0); /* remove eventual returns */
|
||||
}
|
||||
}
|
||||
@@ -437,6 +446,14 @@ static int db_traceback (lua_State *L) {
|
||||
}
|
||||
|
||||
|
||||
static int db_setcstacklimit (lua_State *L) {
|
||||
int limit = (int)luaL_checkinteger(L, 1);
|
||||
int res = lua_setcstacklimit(L, limit);
|
||||
lua_pushinteger(L, res);
|
||||
return 1;
|
||||
}
|
||||
|
||||
|
||||
static const luaL_Reg dblib[] = {
|
||||
{"debug", db_debug},
|
||||
{"getuservalue", db_getuservalue},
|
||||
@@ -454,6 +471,7 @@ static const luaL_Reg dblib[] = {
|
||||
{"setmetatable", db_setmetatable},
|
||||
{"setupvalue", db_setupvalue},
|
||||
{"traceback", db_traceback},
|
||||
{"setcstacklimit", db_setcstacklimit},
|
||||
{NULL, NULL}
|
||||
};
|
||||
|
||||
|
||||
@@ -31,15 +31,11 @@
|
||||
|
||||
|
||||
|
||||
#define noLuaClosure(f) ((f) == NULL || (f)->c.tt == LUA_TCCL)
|
||||
#define noLuaClosure(f) ((f) == NULL || (f)->c.tt == LUA_VCCL)
|
||||
|
||||
|
||||
/* Active Lua function (given call info) */
|
||||
#define ci_func(ci) (clLvalue(s2v((ci)->func)))
|
||||
|
||||
|
||||
static const char *funcnamefromcode (lua_State *L, CallInfo *ci,
|
||||
const char **name);
|
||||
static const char *funcnamefromcall (lua_State *L, CallInfo *ci,
|
||||
const char **name);
|
||||
|
||||
|
||||
static int currentpc (CallInfo *ci) {
|
||||
@@ -50,10 +46,16 @@ static int currentpc (CallInfo *ci) {
|
||||
|
||||
/*
|
||||
** Get a "base line" to find the line corresponding to an instruction.
|
||||
** For that, search the array of absolute line info for the largest saved
|
||||
** instruction smaller or equal to the wanted instruction. A special
|
||||
** case is when there is no absolute info or the instruction is before
|
||||
** the first absolute one.
|
||||
** Base lines are regularly placed at MAXIWTHABS intervals, so usually
|
||||
** an integer division gets the right place. When the source file has
|
||||
** large sequences of empty/comment lines, it may need extra entries,
|
||||
** so the original estimate needs a correction.
|
||||
** If the original estimate is -1, the initial 'if' ensures that the
|
||||
** 'while' will run at least once.
|
||||
** The assertion that the estimate is a lower bound for the correct base
|
||||
** is valid as long as the debug info has been generated with the same
|
||||
** value for MAXIWTHABS or smaller. (Previous releases use a little
|
||||
** smaller value.)
|
||||
*/
|
||||
static int getbaseline (const Proto *f, int pc, int *basepc) {
|
||||
if (f->sizeabslineinfo == 0 || pc < f->abslineinfo[0].pc) {
|
||||
@@ -61,20 +63,12 @@ static int getbaseline (const Proto *f, int pc, int *basepc) {
|
||||
return f->linedefined;
|
||||
}
|
||||
else {
|
||||
unsigned int i;
|
||||
if (pc >= f->abslineinfo[f->sizeabslineinfo - 1].pc)
|
||||
i = f->sizeabslineinfo - 1; /* instruction is after last saved one */
|
||||
else { /* binary search */
|
||||
unsigned int j = f->sizeabslineinfo - 1; /* pc < anchorlines[j] */
|
||||
i = 0; /* abslineinfo[i] <= pc */
|
||||
while (i < j - 1) {
|
||||
unsigned int m = (j + i) / 2;
|
||||
if (pc >= f->abslineinfo[m].pc)
|
||||
i = m;
|
||||
else
|
||||
j = m;
|
||||
}
|
||||
}
|
||||
int i = cast_uint(pc) / MAXIWTHABS - 1; /* get an estimate */
|
||||
/* estimate must be a lower bound of the correct base */
|
||||
lua_assert(i < 0 ||
|
||||
(i < f->sizeabslineinfo && f->abslineinfo[i].pc <= pc));
|
||||
while (i + 1 < f->sizeabslineinfo && pc >= f->abslineinfo[i + 1].pc)
|
||||
i++; /* low estimate; adjust it */
|
||||
*basepc = f->abslineinfo[i].pc;
|
||||
return f->abslineinfo[i].line;
|
||||
}
|
||||
@@ -101,19 +95,21 @@ int luaG_getfuncline (const Proto *f, int pc) {
|
||||
}
|
||||
|
||||
|
||||
static int currentline (CallInfo *ci) {
|
||||
static int getcurrentline (CallInfo *ci) {
|
||||
return luaG_getfuncline(ci_func(ci)->p, currentpc(ci));
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** This function can be called asynchronously (e.g. during a signal),
|
||||
** under "reasonable" assumptions. A new 'ci' is completely linked
|
||||
** in the list before it becomes part of the "active" list, and
|
||||
** we assume that pointers are atomic (see comment in next function).
|
||||
** (If we traverse one more item, there is no problem. If we traverse
|
||||
** one less item, the worst that can happen is that the signal will
|
||||
** not interrupt the script.)
|
||||
** Set 'trap' for all active Lua frames.
|
||||
** This function can be called during a signal, under "reasonable"
|
||||
** assumptions. A new 'ci' is completely linked in the list before it
|
||||
** becomes part of the "active" list, and we assume that pointers are
|
||||
** atomic; see comment in next function.
|
||||
** (A compiler doing interprocedural optimizations could, theoretically,
|
||||
** reorder memory writes in such a way that the list could be
|
||||
** temporarily broken while inserting a new element. We simply assume it
|
||||
** has no good reasons to do that.)
|
||||
*/
|
||||
static void settraps (CallInfo *ci) {
|
||||
for (; ci != NULL; ci = ci->previous)
|
||||
@@ -123,22 +119,20 @@ static void settraps (CallInfo *ci) {
|
||||
|
||||
|
||||
/*
|
||||
** This function can be called asynchronously (e.g. during a signal),
|
||||
** under "reasonable" assumptions.
|
||||
** Fields 'oldpc', 'basehookcount', and 'hookcount' (set by
|
||||
** 'resethookcount') are for debug only, and it is no problem if they
|
||||
** get arbitrary values (causes at most one wrong hook call). 'hookmask'
|
||||
** is an atomic value. We assume that pointers are atomic too (e.g., gcc
|
||||
** ensures that for all platforms where it runs). Moreover, 'hook' is
|
||||
** always checked before being called (see 'luaD_hook').
|
||||
** This function can be called during a signal, under "reasonable"
|
||||
** assumptions.
|
||||
** Fields 'basehookcount' and 'hookcount' (set by 'resethookcount')
|
||||
** are for debug only, and it is no problem if they get arbitrary
|
||||
** values (causes at most one wrong hook call). 'hookmask' is an atomic
|
||||
** value. We assume that pointers are atomic too (e.g., gcc ensures that
|
||||
** for all platforms where it runs). Moreover, 'hook' is always checked
|
||||
** before being called (see 'luaD_hook').
|
||||
*/
|
||||
LUA_API void lua_sethook (lua_State *L, lua_Hook func, int mask, int count) {
|
||||
if (func == NULL || mask == 0) { /* turn off hooks? */
|
||||
mask = 0;
|
||||
func = NULL;
|
||||
}
|
||||
if (isLua(L->ci))
|
||||
L->oldpc = L->ci->u.l.savedpc;
|
||||
L->hook = func;
|
||||
L->basehookcount = count;
|
||||
resethookcount(L);
|
||||
@@ -190,8 +184,8 @@ static const char *upvalname (const Proto *p, int uv) {
|
||||
static const char *findvararg (CallInfo *ci, int n, StkId *pos) {
|
||||
if (clLvalue(s2v(ci->func))->p->is_vararg) {
|
||||
int nextra = ci->u.l.nextraargs;
|
||||
if (n <= nextra) {
|
||||
*pos = ci->func - nextra + (n - 1);
|
||||
if (n >= -nextra) { /* 'n' is negative */
|
||||
*pos = ci->func - nextra - (n + 1);
|
||||
return "(vararg)"; /* generic name for any vararg */
|
||||
}
|
||||
}
|
||||
@@ -204,7 +198,7 @@ const char *luaG_findlocal (lua_State *L, CallInfo *ci, int n, StkId *pos) {
|
||||
const char *name = NULL;
|
||||
if (isLua(ci)) {
|
||||
if (n < 0) /* access to vararg values? */
|
||||
return findvararg(ci, -n, pos);
|
||||
return findvararg(ci, n, pos);
|
||||
else
|
||||
name = luaF_getlocalname(ci_func(ci)->p, n, currentpc(ci));
|
||||
}
|
||||
@@ -306,9 +300,16 @@ static void collectvalidlines (lua_State *L, Closure *f) {
|
||||
Table *t = luaH_new(L); /* new table to store active lines */
|
||||
sethvalue2s(L, L->top, t); /* push it on stack */
|
||||
api_incr_top(L);
|
||||
setbvalue(&v, 1); /* boolean 'true' to be the value of all indices */
|
||||
for (i = 0; i < p->sizelineinfo; i++) { /* for all lines with code */
|
||||
currentline = nextline(p, currentline, i);
|
||||
setbtvalue(&v); /* boolean 'true' to be the value of all indices */
|
||||
if (!p->is_vararg) /* regular function? */
|
||||
i = 0; /* consider all instructions */
|
||||
else { /* vararg function */
|
||||
lua_assert(GET_OPCODE(p->code[0]) == OP_VARARGPREP);
|
||||
currentline = nextline(p, currentline, 0);
|
||||
i = 1; /* skip first instruction (OP_VARARGPREP) */
|
||||
}
|
||||
for (; i < p->sizelineinfo; i++) { /* for each instruction */
|
||||
currentline = nextline(p, currentline, i); /* get its line */
|
||||
luaH_setint(L, t, currentline, &v); /* table[line] = true */
|
||||
}
|
||||
}
|
||||
@@ -316,15 +317,9 @@ static void collectvalidlines (lua_State *L, Closure *f) {
|
||||
|
||||
|
||||
static const char *getfuncname (lua_State *L, CallInfo *ci, const char **name) {
|
||||
if (ci == NULL) /* no 'ci'? */
|
||||
return NULL; /* no info */
|
||||
else if (ci->callstatus & CIST_FIN) { /* is this a finalizer? */
|
||||
*name = "__gc";
|
||||
return "metamethod"; /* report it as such */
|
||||
}
|
||||
/* calling function is a known Lua function? */
|
||||
else if (!(ci->callstatus & CIST_TAIL) && isLua(ci->previous))
|
||||
return funcnamefromcode(L, ci->previous, name);
|
||||
/* calling function is a known function? */
|
||||
if (ci != NULL && !(ci->callstatus & CIST_TAIL))
|
||||
return funcnamefromcall(L, ci->previous, name);
|
||||
else return NULL; /* no way to find a name */
|
||||
}
|
||||
|
||||
@@ -339,7 +334,7 @@ static int auxgetinfo (lua_State *L, const char *what, lua_Debug *ar,
|
||||
break;
|
||||
}
|
||||
case 'l': {
|
||||
ar->currentline = (ci && isLua(ci)) ? currentline(ci) : -1;
|
||||
ar->currentline = (ci && isLua(ci)) ? getcurrentline(ci) : -1;
|
||||
break;
|
||||
}
|
||||
case 'u': {
|
||||
@@ -465,12 +460,14 @@ static int filterpc (int pc, int jmptarget) {
|
||||
|
||||
|
||||
/*
|
||||
** try to find last instruction before 'lastpc' that modified register 'reg'
|
||||
** Try to find last instruction before 'lastpc' that modified register 'reg'.
|
||||
*/
|
||||
static int findsetreg (const Proto *p, int lastpc, int reg) {
|
||||
int pc;
|
||||
int setreg = -1; /* keep last instruction that changed 'reg' */
|
||||
int jmptarget = 0; /* any code before this address is conditional */
|
||||
if (testMMMode(GET_OPCODE(p->code[lastpc])))
|
||||
lastpc--; /* previous instruction was not actually executed */
|
||||
for (pc = 0; pc < lastpc; pc++) {
|
||||
Instruction i = p->code[pc];
|
||||
OpCode op = GET_OPCODE(i);
|
||||
@@ -594,16 +591,10 @@ static const char *getobjname (const Proto *p, int lastpc, int reg,
|
||||
** Returns what the name is (e.g., "for iterator", "method",
|
||||
** "metamethod") and sets '*name' to point to the name.
|
||||
*/
|
||||
static const char *funcnamefromcode (lua_State *L, CallInfo *ci,
|
||||
const char **name) {
|
||||
static const char *funcnamefromcode (lua_State *L, const Proto *p,
|
||||
int pc, const char **name) {
|
||||
TMS tm = (TMS)0; /* (initial value avoids warnings) */
|
||||
const 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:
|
||||
@@ -620,24 +611,8 @@ static const char *funcnamefromcode (lua_State *L, CallInfo *ci,
|
||||
case OP_SETTABUP: case OP_SETTABLE: case OP_SETI: case OP_SETFIELD:
|
||||
tm = TM_NEWINDEX;
|
||||
break;
|
||||
case OP_ADDI: case OP_SUBI: case OP_MULI: case OP_MODI:
|
||||
case OP_POWI: case OP_DIVI: case OP_IDIVI: {
|
||||
int offset = GET_OPCODE(i) - OP_ADDI; /* ORDER OP */
|
||||
tm = cast(TMS, offset + TM_ADD); /* ORDER TM */
|
||||
break;
|
||||
}
|
||||
case OP_ADDK: case OP_SUBK: case OP_MULK: case OP_MODK:
|
||||
case OP_POWK: case OP_DIVK: case OP_IDIVK:
|
||||
case OP_BANDK: case OP_BORK: case OP_BXORK: {
|
||||
int offset = GET_OPCODE(i) - OP_ADDK; /* ORDER OP */
|
||||
tm = cast(TMS, offset + TM_ADD); /* ORDER TM */
|
||||
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 = GET_OPCODE(i) - OP_ADD; /* ORDER OP */
|
||||
tm = cast(TMS, offset + TM_ADD); /* ORDER TM */
|
||||
case OP_MMBIN: case OP_MMBINI: case OP_MMBINK: {
|
||||
tm = cast(TMS, GETARG_C(i));
|
||||
break;
|
||||
}
|
||||
case OP_UNM: tm = TM_UNM; break;
|
||||
@@ -645,12 +620,10 @@ static const char *funcnamefromcode (lua_State *L, CallInfo *ci,
|
||||
case OP_LEN: tm = TM_LEN; break;
|
||||
case OP_CONCAT: tm = TM_CONCAT; break;
|
||||
case OP_EQ: tm = TM_EQ; break;
|
||||
case OP_LT: case OP_LE: case OP_LTI: case OP_LEI:
|
||||
*name = "order"; /* '<=' can call '__lt', etc. */
|
||||
return "metamethod";
|
||||
case OP_SHRI: case OP_SHLI:
|
||||
*name = "shift";
|
||||
return "metamethod";
|
||||
/* no cases for OP_EQI and OP_EQK, as they don't call metamethods */
|
||||
case OP_LT: case OP_LTI: case OP_GTI: tm = TM_LT; break;
|
||||
case OP_LE: case OP_LEI: case OP_GEI: tm = TM_LE; break;
|
||||
case OP_CLOSE: case OP_RETURN: tm = TM_CLOSE; break;
|
||||
default:
|
||||
return NULL; /* cannot find a reasonable name */
|
||||
}
|
||||
@@ -658,19 +631,43 @@ static const char *funcnamefromcode (lua_State *L, CallInfo *ci,
|
||||
return "metamethod";
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** Try to find a name for a function based on how it was called.
|
||||
*/
|
||||
static const char *funcnamefromcall (lua_State *L, CallInfo *ci,
|
||||
const char **name) {
|
||||
if (ci->callstatus & CIST_HOOKED) { /* was it called inside a hook? */
|
||||
*name = "?";
|
||||
return "hook";
|
||||
}
|
||||
else if (ci->callstatus & CIST_FIN) { /* was it called as a finalizer? */
|
||||
*name = "__gc";
|
||||
return "metamethod"; /* report it as such */
|
||||
}
|
||||
else if (isLua(ci))
|
||||
return funcnamefromcode(L, ci_func(ci)->p, currentpc(ci), name);
|
||||
else
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/* }====================================================== */
|
||||
|
||||
|
||||
|
||||
/*
|
||||
** 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.
|
||||
** Check whether pointer 'o' points to some value in the stack
|
||||
** frame of the current function. Because 'o' may not point to a
|
||||
** value in this stack, we cannot compare it with the region
|
||||
** boundaries (undefined behaviour in ISO C).
|
||||
*/
|
||||
static int isinstack (CallInfo *ci, const TValue *o) {
|
||||
StkId base = ci->func + 1;
|
||||
ptrdiff_t i = cast(StkId, o) - base;
|
||||
return (0 <= i && i < (ci->top - base) && s2v(base + i) == o);
|
||||
StkId pos;
|
||||
for (pos = ci->func + 1; pos < ci->top; pos++) {
|
||||
if (o == s2v(pos))
|
||||
return 1;
|
||||
}
|
||||
return 0; /* not found */
|
||||
}
|
||||
|
||||
|
||||
@@ -693,9 +690,21 @@ static const char *getupvalname (CallInfo *ci, const TValue *o,
|
||||
}
|
||||
|
||||
|
||||
static const char *formatvarinfo (lua_State *L, const char *kind,
|
||||
const char *name) {
|
||||
if (kind == NULL)
|
||||
return ""; /* no information */
|
||||
else
|
||||
return luaO_pushfstring(L, " (%s '%s')", kind, name);
|
||||
}
|
||||
|
||||
/*
|
||||
** Build a string with a "description" for the value 'o', such as
|
||||
** "variable 'x'" or "upvalue 'y'".
|
||||
*/
|
||||
static const char *varinfo (lua_State *L, const TValue *o) {
|
||||
const char *name = NULL; /* to avoid warnings */
|
||||
CallInfo *ci = L->ci;
|
||||
const char *name = NULL; /* to avoid warnings */
|
||||
const char *kind = NULL;
|
||||
if (isLua(ci)) {
|
||||
kind = getupvalname(ci, o, &name); /* check whether 'o' is an upvalue */
|
||||
@@ -703,13 +712,40 @@ static const char *varinfo (lua_State *L, const TValue *o) {
|
||||
kind = getobjname(ci_func(ci)->p, currentpc(ci),
|
||||
cast_int(cast(StkId, o) - (ci->func + 1)), &name);
|
||||
}
|
||||
return (kind) ? luaO_pushfstring(L, " (%s '%s')", kind, name) : "";
|
||||
return formatvarinfo(L, kind, name);
|
||||
}
|
||||
|
||||
|
||||
l_noret luaG_typeerror (lua_State *L, const TValue *o, const char *op) {
|
||||
/*
|
||||
** Raise a type error
|
||||
*/
|
||||
static l_noret typeerror (lua_State *L, const TValue *o, const char *op,
|
||||
const char *extra) {
|
||||
const char *t = luaT_objtypename(L, o);
|
||||
luaG_runerror(L, "attempt to %s a %s value%s", op, t, varinfo(L, o));
|
||||
luaG_runerror(L, "attempt to %s a %s value%s", op, t, extra);
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** Raise a type error with "standard" information about the faulty
|
||||
** object 'o' (using 'varinfo').
|
||||
*/
|
||||
l_noret luaG_typeerror (lua_State *L, const TValue *o, const char *op) {
|
||||
typeerror(L, o, op, varinfo(L, o));
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** Raise an error for calling a non-callable object. Try to find a name
|
||||
** for the object based on how it was called ('funcnamefromcall'); if it
|
||||
** cannot get a name there, try 'varinfo'.
|
||||
*/
|
||||
l_noret luaG_callerror (lua_State *L, const TValue *o) {
|
||||
CallInfo *ci = L->ci;
|
||||
const char *name = NULL; /* to avoid warnings */
|
||||
const char *kind = funcnamefromcall(L, ci, &name);
|
||||
const char *extra = kind ? formatvarinfo(L, kind, name) : varinfo(L, o);
|
||||
typeerror(L, o, "call", extra);
|
||||
}
|
||||
|
||||
|
||||
@@ -738,7 +774,7 @@ l_noret luaG_opinterror (lua_State *L, const TValue *p1,
|
||||
*/
|
||||
l_noret luaG_tointerror (lua_State *L, const TValue *p1, const TValue *p2) {
|
||||
lua_Integer temp;
|
||||
if (!tointegerns(p1, &temp))
|
||||
if (!luaV_tointegerns(p1, &temp, LUA_FLOORN2I))
|
||||
p2 = p1;
|
||||
luaG_runerror(L, "number%s has no integer representation", varinfo(L, p2));
|
||||
}
|
||||
@@ -789,27 +825,56 @@ l_noret luaG_runerror (lua_State *L, const char *fmt, ...) {
|
||||
msg = luaO_pushvfstring(L, fmt, argp); /* format message */
|
||||
va_end(argp);
|
||||
if (isLua(ci)) /* if Lua function, add source:line information */
|
||||
luaG_addinfo(L, msg, ci_func(ci)->p->source, currentline(ci));
|
||||
luaG_addinfo(L, msg, ci_func(ci)->p->source, getcurrentline(ci));
|
||||
luaG_errormsg(L);
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** Check whether new instruction 'newpc' is in a different line from
|
||||
** previous instruction 'oldpc'.
|
||||
** previous instruction 'oldpc'. More often than not, 'newpc' is only
|
||||
** one or a few instructions after 'oldpc' (it must be after, see
|
||||
** caller), so try to avoid calling 'luaG_getfuncline'. If they are
|
||||
** too far apart, there is a good chance of a ABSLINEINFO in the way,
|
||||
** so it goes directly to 'luaG_getfuncline'.
|
||||
*/
|
||||
static int changedline (const Proto *p, int oldpc, int newpc) {
|
||||
while (oldpc++ < newpc) {
|
||||
if (p->lineinfo[oldpc] != 0)
|
||||
return (luaG_getfuncline(p, oldpc - 1) != luaG_getfuncline(p, newpc));
|
||||
if (p->lineinfo == NULL) /* no debug information? */
|
||||
return 0;
|
||||
if (newpc - oldpc < MAXIWTHABS / 2) { /* not too far apart? */
|
||||
int delta = 0; /* line diference */
|
||||
int pc = oldpc;
|
||||
for (;;) {
|
||||
int lineinfo = p->lineinfo[++pc];
|
||||
if (lineinfo == ABSLINEINFO)
|
||||
break; /* cannot compute delta; fall through */
|
||||
delta += lineinfo;
|
||||
if (pc == newpc)
|
||||
return (delta != 0); /* delta computed successfully */
|
||||
}
|
||||
}
|
||||
return 0; /* no line changes in the way */
|
||||
/* either instructions are too far apart or there is an absolute line
|
||||
info in the way; compute line difference explicitly */
|
||||
return (luaG_getfuncline(p, oldpc) != luaG_getfuncline(p, newpc));
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** Traces the execution of a Lua function. Called before the execution
|
||||
** of each opcode, when debug is on. 'L->oldpc' stores the last
|
||||
** instruction traced, to detect line changes. When entering a new
|
||||
** function, 'npci' will be zero and will test as a new line whatever
|
||||
** the value of 'oldpc'. Some exceptional conditions may return to
|
||||
** a function without setting 'oldpc'. In that case, 'oldpc' may be
|
||||
** invalid; if so, use zero as a valid value. (A wrong but valid 'oldpc'
|
||||
** at most causes an extra call to a line hook.)
|
||||
** This function is not "Protected" when called, so it should correct
|
||||
** 'L->top' before calling anything that can run the GC.
|
||||
*/
|
||||
int luaG_traceexec (lua_State *L, const Instruction *pc) {
|
||||
CallInfo *ci = L->ci;
|
||||
lu_byte mask = L->hookmask;
|
||||
const Proto *p = ci_func(ci)->p;
|
||||
int counthook;
|
||||
if (!(mask & (LUA_MASKLINE | LUA_MASKCOUNT))) { /* no hooks? */
|
||||
ci->u.l.trap = 0; /* don't need to stop again */
|
||||
@@ -826,20 +891,20 @@ int luaG_traceexec (lua_State *L, const Instruction *pc) {
|
||||
ci->callstatus &= ~CIST_HOOKYIELD; /* erase mark */
|
||||
return 1; /* do not call hook again (VM yielded, so it did not move) */
|
||||
}
|
||||
if (!isIT(*(ci->u.l.savedpc - 1)))
|
||||
L->top = ci->top; /* prepare top */
|
||||
if (!isIT(*(ci->u.l.savedpc - 1))) /* top not being used? */
|
||||
L->top = ci->top; /* correct top */
|
||||
if (counthook)
|
||||
luaD_hook(L, LUA_HOOKCOUNT, -1, 0, 0); /* call count hook */
|
||||
if (mask & LUA_MASKLINE) {
|
||||
const Proto *p = ci_func(ci)->p;
|
||||
/* 'L->oldpc' may be invalid; use zero in this case */
|
||||
int oldpc = (L->oldpc < p->sizecode) ? L->oldpc : 0;
|
||||
int npci = pcRel(pc, p);
|
||||
if (npci == 0 || /* call linehook when enter a new function, */
|
||||
pc <= L->oldpc || /* when jump back (loop), or when */
|
||||
changedline(p, pcRel(L->oldpc, p), npci)) { /* enter new line */
|
||||
if (npci <= oldpc || /* call hook when jump back (loop), */
|
||||
changedline(p, oldpc, npci)) { /* or when enter new line */
|
||||
int newline = luaG_getfuncline(p, npci);
|
||||
luaD_hook(L, LUA_HOOKLINE, newline, 0, 0); /* call line hook */
|
||||
}
|
||||
L->oldpc = pc; /* 'pc' of last call to line hook */
|
||||
L->oldpc = npci; /* 'pc' of last call to line hook */
|
||||
}
|
||||
if (L->status == LUA_YIELD) { /* did hook yield? */
|
||||
if (counthook)
|
||||
|
||||
@@ -13,6 +13,11 @@
|
||||
|
||||
#define pcRel(pc, p) (cast_int((pc) - (p)->code) - 1)
|
||||
|
||||
|
||||
/* Active Lua function (given call info) */
|
||||
#define ci_func(ci) (clLvalue(s2v((ci)->func)))
|
||||
|
||||
|
||||
#define resethookcount(L) (L->hookcount = L->basehookcount)
|
||||
|
||||
/*
|
||||
@@ -21,11 +26,22 @@
|
||||
*/
|
||||
#define ABSLINEINFO (-0x80)
|
||||
|
||||
|
||||
/*
|
||||
** MAXimum number of successive Instructions WiTHout ABSolute line
|
||||
** information. (A power of two allows fast divisions.)
|
||||
*/
|
||||
#if !defined(MAXIWTHABS)
|
||||
#define MAXIWTHABS 128
|
||||
#endif
|
||||
|
||||
|
||||
LUAI_FUNC int luaG_getfuncline (const Proto *f, int pc);
|
||||
LUAI_FUNC const char *luaG_findlocal (lua_State *L, CallInfo *ci, int n,
|
||||
StkId *pos);
|
||||
LUAI_FUNC l_noret luaG_typeerror (lua_State *L, const TValue *o,
|
||||
const char *opname);
|
||||
LUAI_FUNC l_noret luaG_callerror (lua_State *L, const TValue *o);
|
||||
LUAI_FUNC l_noret luaG_forerror (lua_State *L, const TValue *o,
|
||||
const char *what);
|
||||
LUAI_FUNC l_noret luaG_concaterror (lua_State *L, const TValue *p1,
|
||||
|
||||
@@ -98,11 +98,12 @@ void luaD_seterrorobj (lua_State *L, int errcode, StkId oldtop) {
|
||||
setsvalue2s(L, oldtop, luaS_newliteral(L, "error in error handling"));
|
||||
break;
|
||||
}
|
||||
case CLOSEPROTECT: {
|
||||
case LUA_OK: { /* special case only for closing upvalues */
|
||||
setnilvalue(s2v(oldtop)); /* no error message */
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
lua_assert(errorstatus(errcode)); /* real error */
|
||||
setobjs2s(L, oldtop, L->top - 1); /* error message on current top */
|
||||
break;
|
||||
}
|
||||
@@ -118,17 +119,13 @@ l_noret luaD_throw (lua_State *L, int errcode) {
|
||||
}
|
||||
else { /* thread has no error handler */
|
||||
global_State *g = G(L);
|
||||
errcode = luaF_close(L, L->stack, errcode); /* close all upvalues */
|
||||
L->status = cast_byte(errcode); /* mark it as dead */
|
||||
errcode = luaE_resetthread(L, errcode); /* close all upvalues */
|
||||
if (g->mainthread->errorJmp) { /* main thread has a handler? */
|
||||
setobjs2s(L, g->mainthread->top++, L->top - 1); /* copy error obj. */
|
||||
luaD_throw(g->mainthread, errcode); /* re-throw in main thread */
|
||||
}
|
||||
else { /* no handler at all; abort */
|
||||
if (g->panic) { /* panic function? */
|
||||
luaD_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 panic function (last chance to jump out) */
|
||||
}
|
||||
@@ -139,9 +136,8 @@ l_noret luaD_throw (lua_State *L, int errcode) {
|
||||
|
||||
|
||||
int luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud) {
|
||||
l_uint32 oldnCcalls = L->nCcalls - L->nci;
|
||||
l_uint32 oldnCcalls = L->nCcalls;
|
||||
struct lua_longjmp lj;
|
||||
lua_assert(L->nCcalls >= L->nci);
|
||||
lj.status = LUA_OK;
|
||||
lj.previous = L->errorJmp; /* chain new error handler */
|
||||
L->errorJmp = &lj;
|
||||
@@ -149,7 +145,7 @@ int luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud) {
|
||||
(*f)(L, ud);
|
||||
);
|
||||
L->errorJmp = lj.previous; /* restore old error handler */
|
||||
L->nCcalls = oldnCcalls + L->nci;
|
||||
L->nCcalls = oldnCcalls;
|
||||
return lj.status;
|
||||
}
|
||||
|
||||
@@ -164,9 +160,8 @@ int luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud) {
|
||||
static void correctstack (lua_State *L, StkId oldstack, StkId newstack) {
|
||||
CallInfo *ci;
|
||||
UpVal *up;
|
||||
if (oldstack == newstack)
|
||||
return; /* stack address did not change */
|
||||
L->top = (L->top - oldstack) + newstack;
|
||||
L->tbclist = (L->tbclist - oldstack) + newstack;
|
||||
for (up = L->openupval; up != NULL; up = up->u.open.next)
|
||||
up->v = s2v((uplevel(up) - oldstack) + newstack);
|
||||
for (ci = L->ci; ci != NULL; ci = ci->previous) {
|
||||
@@ -182,22 +177,37 @@ static void correctstack (lua_State *L, StkId oldstack, StkId newstack) {
|
||||
#define ERRORSTACKSIZE (LUAI_MAXSTACK + 200)
|
||||
|
||||
|
||||
/*
|
||||
** Reallocate the stack to a new size, correcting all pointers into
|
||||
** it. (There are pointers to a stack from its upvalues, from its list
|
||||
** of call infos, plus a few individual pointers.) The reallocation is
|
||||
** done in two steps (allocation + free) because the correction must be
|
||||
** done while both addresses (the old stack and the new one) are valid.
|
||||
** (In ISO C, any pointer use after the pointer has been deallocated is
|
||||
** undefined behavior.)
|
||||
** In case of allocation error, raise an error or return false according
|
||||
** to 'raiseerror'.
|
||||
*/
|
||||
int luaD_reallocstack (lua_State *L, int newsize, int raiseerror) {
|
||||
int lim = L->stacksize;
|
||||
StkId newstack = luaM_reallocvector(L, L->stack, lim, newsize, StackValue);
|
||||
int oldsize = stacksize(L);
|
||||
int i;
|
||||
StkId newstack = luaM_reallocvector(L, NULL, 0,
|
||||
newsize + EXTRA_STACK, StackValue);
|
||||
lua_assert(newsize <= LUAI_MAXSTACK || newsize == ERRORSTACKSIZE);
|
||||
lua_assert(L->stack_last - L->stack == L->stacksize - EXTRA_STACK);
|
||||
if (unlikely(newstack == NULL)) { /* reallocation failed? */
|
||||
if (l_unlikely(newstack == NULL)) { /* reallocation failed? */
|
||||
if (raiseerror)
|
||||
luaM_error(L);
|
||||
else return 0; /* do not raise an error */
|
||||
}
|
||||
for (; lim < newsize; lim++)
|
||||
setnilvalue(s2v(newstack + lim)); /* erase new segment */
|
||||
/* number of elements to be copied to the new stack */
|
||||
i = ((oldsize <= newsize) ? oldsize : newsize) + EXTRA_STACK;
|
||||
memcpy(newstack, L->stack, i * sizeof(StackValue));
|
||||
for (; i < newsize + EXTRA_STACK; i++)
|
||||
setnilvalue(s2v(newstack + i)); /* erase new segment */
|
||||
correctstack(L, L->stack, newstack);
|
||||
luaM_freearray(L, L->stack, oldsize + EXTRA_STACK);
|
||||
L->stack = newstack;
|
||||
L->stacksize = newsize;
|
||||
L->stack_last = L->stack + newsize - EXTRA_STACK;
|
||||
L->stack_last = L->stack + newsize;
|
||||
return 1;
|
||||
}
|
||||
|
||||
@@ -207,52 +217,73 @@ int luaD_reallocstack (lua_State *L, int newsize, int raiseerror) {
|
||||
** is true, raises any error; otherwise, return 0 in case of errors.
|
||||
*/
|
||||
int luaD_growstack (lua_State *L, int n, int raiseerror) {
|
||||
int size = L->stacksize;
|
||||
int newsize = 2 * size; /* tentative new size */
|
||||
if (unlikely(size > LUAI_MAXSTACK)) { /* need more space after extra size? */
|
||||
int size = stacksize(L);
|
||||
if (l_unlikely(size > LUAI_MAXSTACK)) {
|
||||
/* if stack is larger than maximum, thread is already using the
|
||||
extra space reserved for errors, that is, thread is handling
|
||||
a stack error; cannot grow further than that. */
|
||||
lua_assert(stacksize(L) == ERRORSTACKSIZE);
|
||||
if (raiseerror)
|
||||
luaD_throw(L, LUA_ERRERR); /* error inside message handler */
|
||||
else return 0;
|
||||
return 0; /* if not 'raiseerror', just signal it */
|
||||
}
|
||||
else {
|
||||
int needed = cast_int(L->top - L->stack) + n + EXTRA_STACK;
|
||||
int newsize = 2 * size; /* tentative new size */
|
||||
int needed = cast_int(L->top - L->stack) + n;
|
||||
if (newsize > LUAI_MAXSTACK) /* cannot cross the limit */
|
||||
newsize = LUAI_MAXSTACK;
|
||||
if (newsize < needed) /* but must respect what was asked for */
|
||||
newsize = needed;
|
||||
if (unlikely(newsize > LUAI_MAXSTACK)) { /* stack overflow? */
|
||||
if (l_likely(newsize <= LUAI_MAXSTACK))
|
||||
return luaD_reallocstack(L, newsize, raiseerror);
|
||||
else { /* stack overflow */
|
||||
/* add extra size to be able to handle the error message */
|
||||
luaD_reallocstack(L, ERRORSTACKSIZE, raiseerror);
|
||||
if (raiseerror)
|
||||
luaG_runerror(L, "stack overflow");
|
||||
else return 0;
|
||||
return 0;
|
||||
}
|
||||
} /* else no errors */
|
||||
return luaD_reallocstack(L, newsize, raiseerror);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
static int stackinuse (lua_State *L) {
|
||||
CallInfo *ci;
|
||||
int res;
|
||||
StkId lim = L->top;
|
||||
for (ci = L->ci; ci != NULL; ci = ci->previous) {
|
||||
if (lim < ci->top) lim = ci->top;
|
||||
}
|
||||
lua_assert(lim <= L->stack_last);
|
||||
return cast_int(lim - L->stack) + 1; /* part of stack in use */
|
||||
res = cast_int(lim - L->stack) + 1; /* part of stack in use */
|
||||
if (res < LUA_MINSTACK)
|
||||
res = LUA_MINSTACK; /* ensure a minimum size */
|
||||
return res;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** If stack size is more than 3 times the current use, reduce that size
|
||||
** to twice the current use. (So, the final stack size is at most 2/3 the
|
||||
** previous size, and half of its entries are empty.)
|
||||
** As a particular case, if stack was handling a stack overflow and now
|
||||
** it is not, 'max' (limited by LUAI_MAXSTACK) will be smaller than
|
||||
** stacksize (equal to ERRORSTACKSIZE in this case), and so the stack
|
||||
** will be reduced to a "regular" size.
|
||||
*/
|
||||
void luaD_shrinkstack (lua_State *L) {
|
||||
int inuse = stackinuse(L);
|
||||
int goodsize = inuse + (inuse / 8) + 2*EXTRA_STACK;
|
||||
if (goodsize > LUAI_MAXSTACK)
|
||||
goodsize = LUAI_MAXSTACK; /* respect stack limit */
|
||||
int nsize = inuse * 2; /* proposed new size */
|
||||
int max = inuse * 3; /* maximum "reasonable" size */
|
||||
if (max > LUAI_MAXSTACK) {
|
||||
max = LUAI_MAXSTACK; /* respect stack limit */
|
||||
if (nsize > LUAI_MAXSTACK)
|
||||
nsize = LUAI_MAXSTACK;
|
||||
}
|
||||
/* if thread is currently not handling a stack overflow and its
|
||||
good size is smaller than current size, shrink its stack */
|
||||
if (inuse <= (LUAI_MAXSTACK - EXTRA_STACK) &&
|
||||
goodsize < L->stacksize)
|
||||
luaD_reallocstack(L, goodsize, 0); /* ok if that fails */
|
||||
size is larger than maximum "reasonable" size, shrink it */
|
||||
if (inuse <= LUAI_MAXSTACK && stacksize(L) > max)
|
||||
luaD_reallocstack(L, nsize, 0); /* ok if that fails */
|
||||
else /* don't change stack */
|
||||
condmovestack(L,{},{}); /* (change only for debugging) */
|
||||
luaE_shrinkCI(L); /* shrink CI list */
|
||||
@@ -278,8 +309,8 @@ void luaD_hook (lua_State *L, int event, int line,
|
||||
if (hook && L->allowhook) { /* make sure there is a hook */
|
||||
int mask = CIST_HOOKED;
|
||||
CallInfo *ci = L->ci;
|
||||
ptrdiff_t top = savestack(L, L->top);
|
||||
ptrdiff_t ci_top = savestack(L, ci->top);
|
||||
ptrdiff_t top = savestack(L, L->top); /* preserve original 'top' */
|
||||
ptrdiff_t ci_top = savestack(L, ci->top); /* idem for 'ci->top' */
|
||||
lua_Debug ar;
|
||||
ar.event = event;
|
||||
ar.currentline = line;
|
||||
@@ -289,8 +320,10 @@ void luaD_hook (lua_State *L, int event, int line,
|
||||
ci->u2.transferinfo.ftransfer = ftransfer;
|
||||
ci->u2.transferinfo.ntransfer = ntransfer;
|
||||
}
|
||||
if (isLua(ci) && L->top < ci->top)
|
||||
L->top = ci->top; /* protect entire activation register */
|
||||
luaD_checkstack(L, LUA_MINSTACK); /* ensure minimum stack size */
|
||||
if (L->top + LUA_MINSTACK > ci->top)
|
||||
if (ci->top < L->top + LUA_MINSTACK)
|
||||
ci->top = L->top + LUA_MINSTACK;
|
||||
L->allowhook = 0; /* cannot call hooks inside a hook */
|
||||
ci->callstatus |= mask;
|
||||
@@ -312,55 +345,60 @@ void luaD_hook (lua_State *L, int event, int line,
|
||||
** active.
|
||||
*/
|
||||
void luaD_hookcall (lua_State *L, CallInfo *ci) {
|
||||
int hook = (ci->callstatus & CIST_TAIL) ? LUA_HOOKTAILCALL : LUA_HOOKCALL;
|
||||
Proto *p;
|
||||
if (!(L->hookmask & LUA_MASKCALL)) /* some other hook? */
|
||||
return; /* don't call hook */
|
||||
p = clLvalue(s2v(ci->func))->p;
|
||||
L->top = ci->top; /* prepare top */
|
||||
ci->u.l.savedpc++; /* hooks assume 'pc' is already incremented */
|
||||
luaD_hook(L, hook, -1, 1, p->numparams);
|
||||
ci->u.l.savedpc--; /* correct 'pc' */
|
||||
L->oldpc = 0; /* set 'oldpc' for new function */
|
||||
if (L->hookmask & LUA_MASKCALL) { /* is call hook on? */
|
||||
int event = (ci->callstatus & CIST_TAIL) ? LUA_HOOKTAILCALL
|
||||
: LUA_HOOKCALL;
|
||||
Proto *p = ci_func(ci)->p;
|
||||
ci->u.l.savedpc++; /* hooks assume 'pc' is already incremented */
|
||||
luaD_hook(L, event, -1, 1, p->numparams);
|
||||
ci->u.l.savedpc--; /* correct 'pc' */
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
static StkId rethook (lua_State *L, CallInfo *ci, StkId firstres, int nres) {
|
||||
ptrdiff_t oldtop = savestack(L, L->top); /* hook may change top */
|
||||
int delta = 0;
|
||||
if (isLuacode(ci)) {
|
||||
Proto *p = clLvalue(s2v(ci->func))->p;
|
||||
if (p->is_vararg)
|
||||
delta = ci->u.l.nextraargs + p->numparams + 1;
|
||||
if (L->top < ci->top)
|
||||
L->top = ci->top; /* correct top to run hook */
|
||||
}
|
||||
/*
|
||||
** Executes a return hook for Lua and C functions and sets/corrects
|
||||
** 'oldpc'. (Note that this correction is needed by the line hook, so it
|
||||
** is done even when return hooks are off.)
|
||||
*/
|
||||
static void rethook (lua_State *L, CallInfo *ci, int nres) {
|
||||
if (L->hookmask & LUA_MASKRET) { /* is return hook on? */
|
||||
StkId firstres = L->top - nres; /* index of first result */
|
||||
int delta = 0; /* correction for vararg functions */
|
||||
int ftransfer;
|
||||
if (isLua(ci)) {
|
||||
Proto *p = ci_func(ci)->p;
|
||||
if (p->is_vararg)
|
||||
delta = ci->u.l.nextraargs + p->numparams + 1;
|
||||
}
|
||||
ci->func += delta; /* if vararg, back to virtual 'func' */
|
||||
ftransfer = cast(unsigned short, firstres - ci->func);
|
||||
luaD_hook(L, LUA_HOOKRET, -1, ftransfer, nres); /* call it */
|
||||
ci->func -= delta;
|
||||
}
|
||||
if (isLua(ci->previous))
|
||||
L->oldpc = ci->previous->u.l.savedpc; /* update 'oldpc' */
|
||||
return restorestack(L, oldtop);
|
||||
if (isLua(ci = ci->previous))
|
||||
L->oldpc = pcRel(ci->u.l.savedpc, ci_func(ci)->p); /* set 'oldpc' */
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** Check whether __call metafield of 'func' is a function. If so, put
|
||||
** it in stack below original 'func' so that 'luaD_call' can call
|
||||
** it. Raise an error if __call metafield is not a function.
|
||||
** Check whether 'func' has a '__call' metafield. If so, put it in the
|
||||
** stack, below original 'func', so that 'luaD_precall' can call it. Raise
|
||||
** an error if there is no '__call' metafield.
|
||||
*/
|
||||
void luaD_tryfuncTM (lua_State *L, StkId func) {
|
||||
const TValue *tm = luaT_gettmbyobj(L, s2v(func), TM_CALL);
|
||||
StkId luaD_tryfuncTM (lua_State *L, StkId func) {
|
||||
const TValue *tm;
|
||||
StkId p;
|
||||
if (unlikely(!ttisfunction(tm)))
|
||||
luaG_typeerror(L, s2v(func), "call");
|
||||
for (p = L->top; p > func; p--)
|
||||
checkstackGCp(L, 1, func); /* space for metamethod */
|
||||
tm = luaT_gettmbyobj(L, s2v(func), TM_CALL); /* (after previous GC) */
|
||||
if (l_unlikely(ttisnil(tm)))
|
||||
luaG_callerror(L, s2v(func)); /* nothing to call */
|
||||
for (p = L->top; p > func; p--) /* open space for metamethod */
|
||||
setobjs2s(L, p, p-1);
|
||||
L->top++; /* assume EXTRA_STACK */
|
||||
L->top++; /* stack space pre-allocated by the caller */
|
||||
setobj2s(L, func, tm); /* metamethod is the new function to be called */
|
||||
return func;
|
||||
}
|
||||
|
||||
|
||||
@@ -370,7 +408,7 @@ void luaD_tryfuncTM (lua_State *L, StkId func) {
|
||||
** expressions, multiple results for tail calls/single parameters)
|
||||
** separated.
|
||||
*/
|
||||
static void moveresults (lua_State *L, StkId res, int nres, int wanted) {
|
||||
l_sinline void moveresults (lua_State *L, StkId res, int nres, int wanted) {
|
||||
StkId firstresult;
|
||||
int i;
|
||||
switch (wanted) { /* handle typical cases separately */
|
||||
@@ -380,27 +418,34 @@ static void moveresults (lua_State *L, StkId res, int nres, int wanted) {
|
||||
case 1: /* one value needed */
|
||||
if (nres == 0) /* no results? */
|
||||
setnilvalue(s2v(res)); /* adjust with nil */
|
||||
else
|
||||
else /* at least one result */
|
||||
setobjs2s(L, res, L->top - nres); /* move it to proper place */
|
||||
L->top = res + 1;
|
||||
return;
|
||||
case LUA_MULTRET:
|
||||
wanted = nres; /* we want all results */
|
||||
break;
|
||||
default: /* multiple results (or to-be-closed variables) */
|
||||
default: /* two/more results and/or to-be-closed variables */
|
||||
if (hastocloseCfunc(wanted)) { /* to-be-closed variables? */
|
||||
ptrdiff_t savedres = savestack(L, res);
|
||||
luaF_close(L, res, LUA_OK); /* may change the stack */
|
||||
res = restorestack(L, savedres);
|
||||
wanted = codeNresults(wanted); /* correct value */
|
||||
L->ci->callstatus |= CIST_CLSRET; /* in case of yields */
|
||||
L->ci->u2.nres = nres;
|
||||
luaF_close(L, res, CLOSEKTOP, 1);
|
||||
L->ci->callstatus &= ~CIST_CLSRET;
|
||||
if (L->hookmask) /* if needed, call hook after '__close's */
|
||||
rethook(L, L->ci, nres);
|
||||
res = restorestack(L, savedres); /* close and hook can move stack */
|
||||
wanted = decodeNresults(wanted);
|
||||
if (wanted == LUA_MULTRET)
|
||||
wanted = nres;
|
||||
wanted = nres; /* we want all results */
|
||||
}
|
||||
break;
|
||||
}
|
||||
/* generic case */
|
||||
firstresult = L->top - nres; /* index of first result */
|
||||
/* move all results to correct place */
|
||||
for (i = 0; i < nres && i < wanted; i++)
|
||||
if (nres > wanted) /* extra results? */
|
||||
nres = wanted; /* don't need them */
|
||||
for (i = 0; i < nres; i++) /* move all results to correct place */
|
||||
setobjs2s(L, res + i, firstresult + i);
|
||||
for (; i < wanted; i++) /* complete wanted number of results */
|
||||
setnilvalue(s2v(res + i));
|
||||
@@ -409,147 +454,249 @@ static void moveresults (lua_State *L, StkId res, int nres, int wanted) {
|
||||
|
||||
|
||||
/*
|
||||
** Finishes a function call: calls hook if necessary, removes CallInfo,
|
||||
** moves current number of results to proper place.
|
||||
** Finishes a function call: calls hook if necessary, moves current
|
||||
** number of results to proper place, and returns to previous call
|
||||
** info. If function has to close variables, hook must be called after
|
||||
** that.
|
||||
*/
|
||||
void luaD_poscall (lua_State *L, CallInfo *ci, int nres) {
|
||||
if (L->hookmask)
|
||||
L->top = rethook(L, ci, L->top - nres, nres);
|
||||
L->ci = ci->previous; /* back to caller */
|
||||
int wanted = ci->nresults;
|
||||
if (l_unlikely(L->hookmask && !hastocloseCfunc(wanted)))
|
||||
rethook(L, ci, nres);
|
||||
/* move results to proper place */
|
||||
moveresults(L, ci->func, nres, ci->nresults);
|
||||
moveresults(L, ci->func, nres, wanted);
|
||||
/* function cannot be in any of these cases when returning */
|
||||
lua_assert(!(ci->callstatus &
|
||||
(CIST_HOOKED | CIST_YPCALL | CIST_FIN | CIST_TRAN | CIST_CLSRET)));
|
||||
L->ci = ci->previous; /* back to caller (after closing variables) */
|
||||
}
|
||||
|
||||
|
||||
|
||||
#define next_ci(L) (L->ci = (L->ci->next ? L->ci->next : luaE_extendCI(L)))
|
||||
#define next_ci(L) (L->ci->next ? L->ci->next : luaE_extendCI(L))
|
||||
|
||||
|
||||
l_sinline CallInfo *prepCallInfo (lua_State *L, StkId func, int nret,
|
||||
int mask, StkId top) {
|
||||
CallInfo *ci = L->ci = next_ci(L); /* new frame */
|
||||
ci->func = func;
|
||||
ci->nresults = nret;
|
||||
ci->callstatus = mask;
|
||||
ci->top = top;
|
||||
return ci;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** precall for C functions
|
||||
*/
|
||||
l_sinline int precallC (lua_State *L, StkId func, int nresults,
|
||||
lua_CFunction f) {
|
||||
int n; /* number of returns */
|
||||
CallInfo *ci;
|
||||
checkstackGCp(L, LUA_MINSTACK, func); /* ensure minimum stack size */
|
||||
L->ci = ci = prepCallInfo(L, func, nresults, CIST_C,
|
||||
L->top + LUA_MINSTACK);
|
||||
lua_assert(ci->top <= L->stack_last);
|
||||
if (l_unlikely(L->hookmask & LUA_MASKCALL)) {
|
||||
int narg = cast_int(L->top - func) - 1;
|
||||
luaD_hook(L, LUA_HOOKCALL, -1, 1, narg);
|
||||
}
|
||||
lua_unlock(L);
|
||||
n = (*f)(L); /* do the actual call */
|
||||
lua_lock(L);
|
||||
api_checknelems(L, n);
|
||||
luaD_poscall(L, ci, n);
|
||||
return n;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** Prepare a function for a tail call, building its call info on top
|
||||
** of the current call info. 'narg1' is the number of arguments plus 1
|
||||
** (so that it includes the function itself).
|
||||
** (so that it includes the function itself). Return the number of
|
||||
** results, if it was a C function, or -1 for a Lua function.
|
||||
*/
|
||||
void luaD_pretailcall (lua_State *L, CallInfo *ci, StkId func, int narg1) {
|
||||
Proto *p = clLvalue(s2v(func))->p;
|
||||
int fsize = p->maxstacksize; /* frame size */
|
||||
int nfixparams = p->numparams;
|
||||
int i;
|
||||
for (i = 0; i < narg1; i++) /* move down function and arguments */
|
||||
setobjs2s(L, ci->func + i, func + i);
|
||||
checkstackGC(L, fsize);
|
||||
func = ci->func; /* moved-down function */
|
||||
for (; narg1 <= nfixparams; narg1++)
|
||||
setnilvalue(s2v(func + narg1)); /* complete missing arguments */
|
||||
ci->top = func + 1 + fsize; /* top for new function */
|
||||
lua_assert(ci->top <= L->stack_last);
|
||||
ci->u.l.savedpc = p->code; /* starting point */
|
||||
ci->callstatus |= CIST_TAIL;
|
||||
L->top = func + narg1; /* set top */
|
||||
int luaD_pretailcall (lua_State *L, CallInfo *ci, StkId func,
|
||||
int narg1, int delta) {
|
||||
retry:
|
||||
switch (ttypetag(s2v(func))) {
|
||||
case LUA_VCCL: /* C closure */
|
||||
return precallC(L, func, LUA_MULTRET, clCvalue(s2v(func))->f);
|
||||
case LUA_VLCF: /* light C function */
|
||||
return precallC(L, func, LUA_MULTRET, fvalue(s2v(func)));
|
||||
case LUA_VLCL: { /* Lua function */
|
||||
Proto *p = clLvalue(s2v(func))->p;
|
||||
int fsize = p->maxstacksize; /* frame size */
|
||||
int nfixparams = p->numparams;
|
||||
int i;
|
||||
checkstackGCp(L, fsize - delta, func);
|
||||
ci->func -= delta; /* restore 'func' (if vararg) */
|
||||
for (i = 0; i < narg1; i++) /* move down function and arguments */
|
||||
setobjs2s(L, ci->func + i, func + i);
|
||||
func = ci->func; /* moved-down function */
|
||||
for (; narg1 <= nfixparams; narg1++)
|
||||
setnilvalue(s2v(func + narg1)); /* complete missing arguments */
|
||||
ci->top = func + 1 + fsize; /* top for new function */
|
||||
lua_assert(ci->top <= L->stack_last);
|
||||
ci->u.l.savedpc = p->code; /* starting point */
|
||||
ci->callstatus |= CIST_TAIL;
|
||||
L->top = func + narg1; /* set top */
|
||||
return -1;
|
||||
}
|
||||
default: { /* not a function */
|
||||
func = luaD_tryfuncTM(L, func); /* try to get '__call' metamethod */
|
||||
/* return luaD_pretailcall(L, ci, func, narg1 + 1, delta); */
|
||||
narg1++;
|
||||
goto retry; /* try again */
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** Call a function (C or Lua). The function to be called is at *func.
|
||||
** The arguments are on the stack, right after the function.
|
||||
** When returns, all the results are on the stack, starting at the original
|
||||
** function position.
|
||||
** Prepares the call to a function (C or Lua). For C functions, also do
|
||||
** the call. The function to be called is at '*func'. The arguments
|
||||
** are on the stack, right after the function. Returns the CallInfo
|
||||
** to be executed, if it was a Lua function. Otherwise (a C function)
|
||||
** returns NULL, with all the results on the stack, starting at the
|
||||
** original function position.
|
||||
*/
|
||||
void luaD_call (lua_State *L, StkId func, int nresults) {
|
||||
lua_CFunction f;
|
||||
TValue *funcv = s2v(func);
|
||||
switch (ttypetag(funcv)) {
|
||||
case LUA_TCCL: /* C closure */
|
||||
f = clCvalue(funcv)->f;
|
||||
goto Cfunc;
|
||||
case LUA_TLCF: /* light C function */
|
||||
f = fvalue(funcv);
|
||||
Cfunc: {
|
||||
int n; /* number of returns */
|
||||
CallInfo *luaD_precall (lua_State *L, StkId func, int nresults) {
|
||||
retry:
|
||||
switch (ttypetag(s2v(func))) {
|
||||
case LUA_VCCL: /* C closure */
|
||||
precallC(L, func, nresults, clCvalue(s2v(func))->f);
|
||||
return NULL;
|
||||
case LUA_VLCF: /* light C function */
|
||||
precallC(L, func, nresults, fvalue(s2v(func)));
|
||||
return NULL;
|
||||
case LUA_VLCL: { /* Lua function */
|
||||
CallInfo *ci;
|
||||
checkstackp(L, LUA_MINSTACK, func); /* ensure minimum stack size */
|
||||
ci = next_ci(L);
|
||||
ci->nresults = nresults;
|
||||
ci->callstatus = CIST_C;
|
||||
ci->top = L->top + LUA_MINSTACK;
|
||||
ci->func = func;
|
||||
lua_assert(ci->top <= L->stack_last);
|
||||
if (L->hookmask & LUA_MASKCALL) {
|
||||
int narg = cast_int(L->top - func) - 1;
|
||||
luaD_hook(L, LUA_HOOKCALL, -1, 1, narg);
|
||||
}
|
||||
lua_unlock(L);
|
||||
n = (*f)(L); /* do the actual call */
|
||||
lua_lock(L);
|
||||
api_checknelems(L, n);
|
||||
luaD_poscall(L, ci, n);
|
||||
break;
|
||||
}
|
||||
case LUA_TLCL: { /* Lua function */
|
||||
CallInfo *ci;
|
||||
Proto *p = clLvalue(funcv)->p;
|
||||
Proto *p = clLvalue(s2v(func))->p;
|
||||
int narg = cast_int(L->top - func) - 1; /* number of real arguments */
|
||||
int nfixparams = p->numparams;
|
||||
int fsize = p->maxstacksize; /* frame size */
|
||||
checkstackp(L, fsize, func);
|
||||
ci = next_ci(L);
|
||||
ci->nresults = nresults;
|
||||
checkstackGCp(L, fsize, func);
|
||||
L->ci = ci = prepCallInfo(L, func, nresults, 0, func + 1 + fsize);
|
||||
ci->u.l.savedpc = p->code; /* starting point */
|
||||
ci->callstatus = 0;
|
||||
ci->top = func + 1 + fsize;
|
||||
ci->func = func;
|
||||
for (; narg < nfixparams; narg++)
|
||||
setnilvalue(s2v(L->top++)); /* complete missing arguments */
|
||||
lua_assert(ci->top <= L->stack_last);
|
||||
luaV_execute(L, ci); /* run the function */
|
||||
break;
|
||||
return ci;
|
||||
}
|
||||
default: { /* not a function */
|
||||
luaD_tryfuncTM(L, func); /* try to get '__call' metamethod */
|
||||
luaD_call(L, func, nresults); /* now it must be a function */
|
||||
break;
|
||||
func = luaD_tryfuncTM(L, func); /* try to get '__call' metamethod */
|
||||
/* return luaD_precall(L, func, nresults); */
|
||||
goto retry; /* try again with metamethod */
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** Call a function (C or Lua) through C. 'inc' can be 1 (increment
|
||||
** number of recursive invocations in the C stack) or nyci (the same
|
||||
** plus increment number of non-yieldable calls).
|
||||
*/
|
||||
l_sinline void ccall (lua_State *L, StkId func, int nResults, int inc) {
|
||||
CallInfo *ci;
|
||||
L->nCcalls += inc;
|
||||
if (l_unlikely(getCcalls(L) >= LUAI_MAXCCALLS))
|
||||
luaE_checkcstack(L);
|
||||
if ((ci = luaD_precall(L, func, nResults)) != NULL) { /* Lua function? */
|
||||
ci->callstatus = CIST_FRESH; /* mark that it is a "fresh" execute */
|
||||
luaV_execute(L, ci); /* call it */
|
||||
}
|
||||
L->nCcalls -= inc;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** External interface for 'ccall'
|
||||
*/
|
||||
void luaD_call (lua_State *L, StkId func, int nResults) {
|
||||
ccall(L, func, nResults, 1);
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** Similar to 'luaD_call', but does not allow yields during the call.
|
||||
** If there is a stack overflow, freeing all CI structures will
|
||||
** force the subsequent call to invoke 'luaE_extendCI', which then
|
||||
** will raise any errors.
|
||||
*/
|
||||
void luaD_callnoyield (lua_State *L, StkId func, int nResults) {
|
||||
incXCcalls(L);
|
||||
if (getCcalls(L) >= LUAI_MAXCSTACK) /* possible stack overflow? */
|
||||
luaE_freeCI(L);
|
||||
luaD_call(L, func, nResults);
|
||||
decXCcalls(L);
|
||||
ccall(L, func, nResults, nyci);
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** Completes the execution of an interrupted C function, calling its
|
||||
** continuation function.
|
||||
** Finish the job of 'lua_pcallk' after it was interrupted by an yield.
|
||||
** (The caller, 'finishCcall', does the final call to 'adjustresults'.)
|
||||
** The main job is to complete the 'luaD_pcall' called by 'lua_pcallk'.
|
||||
** If a '__close' method yields here, eventually control will be back
|
||||
** to 'finishCcall' (when that '__close' method finally returns) and
|
||||
** 'finishpcallk' will run again and close any still pending '__close'
|
||||
** methods. Similarly, if a '__close' method errs, 'precover' calls
|
||||
** 'unroll' which calls ''finishCcall' and we are back here again, to
|
||||
** close any pending '__close' methods.
|
||||
** Note that, up to the call to 'luaF_close', the corresponding
|
||||
** 'CallInfo' is not modified, so that this repeated run works like the
|
||||
** first one (except that it has at least one less '__close' to do). In
|
||||
** particular, field CIST_RECST preserves the error status across these
|
||||
** multiple runs, changing only if there is a new error.
|
||||
*/
|
||||
static void finishCcall (lua_State *L, int status) {
|
||||
CallInfo *ci = L->ci;
|
||||
int n;
|
||||
/* must have a continuation and must be able to call it */
|
||||
lua_assert(ci->u.c.k != NULL && yieldable(L));
|
||||
/* error status can only happen in a protected call */
|
||||
lua_assert((ci->callstatus & CIST_YPCALL) || status == LUA_YIELD);
|
||||
if (ci->callstatus & CIST_YPCALL) { /* was inside a pcall? */
|
||||
ci->callstatus &= ~CIST_YPCALL; /* continuation is also inside it */
|
||||
L->errfunc = ci->u.c.old_errfunc; /* with the same error function */
|
||||
static int finishpcallk (lua_State *L, CallInfo *ci) {
|
||||
int status = getcistrecst(ci); /* get original status */
|
||||
if (l_likely(status == LUA_OK)) /* no error? */
|
||||
status = LUA_YIELD; /* was interrupted by an yield */
|
||||
else { /* error */
|
||||
StkId func = restorestack(L, ci->u2.funcidx);
|
||||
L->allowhook = getoah(ci->callstatus); /* restore 'allowhook' */
|
||||
luaF_close(L, func, status, 1); /* can yield or raise an error */
|
||||
func = restorestack(L, ci->u2.funcidx); /* stack may be moved */
|
||||
luaD_seterrorobj(L, status, func);
|
||||
luaD_shrinkstack(L); /* restore stack size in case of overflow */
|
||||
setcistrecst(ci, LUA_OK); /* clear original status */
|
||||
}
|
||||
ci->callstatus &= ~CIST_YPCALL;
|
||||
L->errfunc = ci->u.c.old_errfunc;
|
||||
/* if it is here, there were errors or yields; unlike 'lua_pcallk',
|
||||
do not change status */
|
||||
return status;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** Completes the execution of a C function interrupted by an yield.
|
||||
** The interruption must have happened while the function was either
|
||||
** closing its tbc variables in 'moveresults' or executing
|
||||
** 'lua_callk'/'lua_pcallk'. In the first case, it just redoes
|
||||
** 'luaD_poscall'. In the second case, the call to 'finishpcallk'
|
||||
** finishes the interrupted execution of 'lua_pcallk'. After that, it
|
||||
** calls the continuation of the interrupted function and finally it
|
||||
** completes the job of the 'luaD_call' that called the function. In
|
||||
** the call to 'adjustresults', we do not know the number of results
|
||||
** of the function called by 'lua_callk'/'lua_pcallk', so we are
|
||||
** conservative and use LUA_MULTRET (always adjust).
|
||||
*/
|
||||
static void finishCcall (lua_State *L, CallInfo *ci) {
|
||||
int n; /* actual number of results from C function */
|
||||
if (ci->callstatus & CIST_CLSRET) { /* was returning? */
|
||||
lua_assert(hastocloseCfunc(ci->nresults));
|
||||
n = ci->u2.nres; /* just redo 'luaD_poscall' */
|
||||
/* don't need to reset CIST_CLSRET, as it will be set again anyway */
|
||||
}
|
||||
else {
|
||||
int status = LUA_YIELD; /* default if there were no errors */
|
||||
/* must have a continuation and must be able to call it */
|
||||
lua_assert(ci->u.c.k != NULL && yieldable(L));
|
||||
if (ci->callstatus & CIST_YPCALL) /* was inside a 'lua_pcallk'? */
|
||||
status = finishpcallk(L, ci); /* finish it */
|
||||
adjustresults(L, LUA_MULTRET); /* finish 'lua_callk' */
|
||||
lua_unlock(L);
|
||||
n = (*ci->u.c.k)(L, status, ci->u.c.ctx); /* call continuation */
|
||||
lua_lock(L);
|
||||
api_checknelems(L, n);
|
||||
}
|
||||
/* finish 'lua_callk'/'lua_pcall'; CIST_YPCALL and 'errfunc' already
|
||||
handled */
|
||||
adjustresults(L, ci->nresults);
|
||||
lua_unlock(L);
|
||||
n = (*ci->u.c.k)(L, status, ci->u.c.ctx); /* call continuation function */
|
||||
lua_lock(L);
|
||||
api_checknelems(L, n);
|
||||
luaD_poscall(L, ci, n); /* finish 'luaD_call' */
|
||||
}
|
||||
|
||||
@@ -557,18 +704,14 @@ static void finishCcall (lua_State *L, int status) {
|
||||
/*
|
||||
** Executes "full continuation" (everything in the stack) of a
|
||||
** previously interrupted coroutine until the stack is empty (or another
|
||||
** interruption long-jumps out of the loop). If the coroutine is
|
||||
** recovering from an error, 'ud' points to the error status, which must
|
||||
** be passed to the first continuation function (otherwise the default
|
||||
** status is LUA_YIELD).
|
||||
** interruption long-jumps out of the loop).
|
||||
*/
|
||||
static void unroll (lua_State *L, void *ud) {
|
||||
CallInfo *ci;
|
||||
if (ud != NULL) /* error status? */
|
||||
finishCcall(L, *(int *)ud); /* finish 'lua_pcallk' callee */
|
||||
UNUSED(ud);
|
||||
while ((ci = L->ci) != &L->base_ci) { /* something in the stack */
|
||||
if (!isLua(ci)) /* C function? */
|
||||
finishCcall(L, LUA_YIELD); /* complete its execution */
|
||||
finishCcall(L, ci); /* complete its execution */
|
||||
else { /* Lua function */
|
||||
luaV_finishOp(L); /* finish interrupted instruction */
|
||||
luaV_execute(L, ci); /* execute down to higher C 'boundary' */
|
||||
@@ -591,28 +734,6 @@ static CallInfo *findpcall (lua_State *L) {
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** Recovers from an error in a coroutine. Finds a recover point (if
|
||||
** there is one) and completes the execution of the interrupted
|
||||
** 'luaD_pcall'. If there is no recover point, returns zero.
|
||||
*/
|
||||
static int recover (lua_State *L, int status) {
|
||||
StkId oldtop;
|
||||
CallInfo *ci = findpcall(L);
|
||||
if (ci == NULL) return 0; /* no recovery point */
|
||||
/* "finish" luaD_pcall */
|
||||
oldtop = restorestack(L, ci->u2.funcidx);
|
||||
luaF_close(L, oldtop, status); /* may change the stack */
|
||||
oldtop = restorestack(L, ci->u2.funcidx);
|
||||
luaD_seterrorobj(L, status, oldtop);
|
||||
L->ci = ci;
|
||||
L->allowhook = getoah(ci->callstatus); /* restore original 'allowhook' */
|
||||
luaD_shrinkstack(L);
|
||||
L->errfunc = ci->u.c.old_errfunc;
|
||||
return 1; /* continue running the coroutine */
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** Signal an error in the call to 'lua_resume', not in the execution
|
||||
** of the coroutine itself. (Such errors should not be handled by any
|
||||
@@ -638,14 +759,15 @@ static void resume (lua_State *L, void *ud) {
|
||||
int n = *(cast(int*, ud)); /* number of arguments */
|
||||
StkId firstArg = L->top - n; /* first argument */
|
||||
CallInfo *ci = L->ci;
|
||||
if (L->status == LUA_OK) { /* starting a coroutine? */
|
||||
luaD_call(L, firstArg - 1, LUA_MULTRET);
|
||||
}
|
||||
if (L->status == LUA_OK) /* starting a coroutine? */
|
||||
ccall(L, firstArg - 1, LUA_MULTRET, 0); /* just call its body */
|
||||
else { /* resuming from previous yield */
|
||||
lua_assert(L->status == LUA_YIELD);
|
||||
L->status = LUA_OK; /* mark that it is running (again) */
|
||||
if (isLua(ci)) /* yielded inside a hook? */
|
||||
if (isLua(ci)) { /* yielded inside a hook? */
|
||||
L->top = firstArg; /* discard arguments */
|
||||
luaV_execute(L, ci); /* just continue running Lua code */
|
||||
}
|
||||
else { /* 'common' yield */
|
||||
if (ci->u.c.k != NULL) { /* does it have a continuation function? */
|
||||
lua_unlock(L);
|
||||
@@ -659,6 +781,26 @@ static void resume (lua_State *L, void *ud) {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** Unrolls a coroutine in protected mode while there are recoverable
|
||||
** errors, that is, errors inside a protected call. (Any error
|
||||
** interrupts 'unroll', and this loop protects it again so it can
|
||||
** continue.) Stops with a normal end (status == LUA_OK), an yield
|
||||
** (status == LUA_YIELD), or an unprotected error ('findpcall' doesn't
|
||||
** find a recover point).
|
||||
*/
|
||||
static int precover (lua_State *L, int status) {
|
||||
CallInfo *ci;
|
||||
while (errorstatus(status) && (ci = findpcall(L)) != NULL) {
|
||||
L->ci = ci; /* go down to recovery functions */
|
||||
setcistrecst(ci, status); /* status to finish 'pcall' */
|
||||
status = luaD_rawrunprotected(L, unroll, NULL);
|
||||
}
|
||||
return status;
|
||||
}
|
||||
|
||||
|
||||
LUA_API int lua_resume (lua_State *L, lua_State *from, int nargs,
|
||||
int *nresults) {
|
||||
int status;
|
||||
@@ -671,21 +813,16 @@ LUA_API int lua_resume (lua_State *L, lua_State *from, int nargs,
|
||||
}
|
||||
else if (L->status != LUA_YIELD) /* ended with errors? */
|
||||
return resume_error(L, "cannot resume dead coroutine", nargs);
|
||||
if (from == NULL)
|
||||
L->nCcalls = 1;
|
||||
else /* correct 'nCcalls' for this thread */
|
||||
L->nCcalls = getCcalls(from) - from->nci + L->nci + CSTACKCF;
|
||||
if (L->nCcalls >= LUAI_MAXCSTACK)
|
||||
L->nCcalls = (from) ? getCcalls(from) : 0;
|
||||
if (getCcalls(L) >= LUAI_MAXCCALLS)
|
||||
return resume_error(L, "C stack overflow", nargs);
|
||||
L->nCcalls++;
|
||||
luai_userstateresume(L, nargs);
|
||||
api_checknelems(L, (L->status == LUA_OK) ? nargs + 1 : nargs);
|
||||
status = luaD_rawrunprotected(L, resume, &nargs);
|
||||
/* continue running after recoverable errors */
|
||||
while (errorstatus(status) && recover(L, status)) {
|
||||
/* unroll continuation */
|
||||
status = luaD_rawrunprotected(L, unroll, &status);
|
||||
}
|
||||
if (likely(!errorstatus(status)))
|
||||
status = precover(L, status);
|
||||
if (l_likely(!errorstatus(status)))
|
||||
lua_assert(status == L->status); /* normal end or yield */
|
||||
else { /* unrecoverable error */
|
||||
L->status = cast_byte(status); /* mark thread as 'dead' */
|
||||
@@ -706,26 +843,27 @@ LUA_API int lua_isyieldable (lua_State *L) {
|
||||
|
||||
LUA_API int lua_yieldk (lua_State *L, int nresults, lua_KContext ctx,
|
||||
lua_KFunction k) {
|
||||
CallInfo *ci = L->ci;
|
||||
CallInfo *ci;
|
||||
luai_userstateyield(L, nresults);
|
||||
lua_lock(L);
|
||||
ci = L->ci;
|
||||
api_checknelems(L, nresults);
|
||||
if (unlikely(!yieldable(L))) {
|
||||
if (l_unlikely(!yieldable(L))) {
|
||||
if (L != G(L)->mainthread)
|
||||
luaG_runerror(L, "attempt to yield across a C-call boundary");
|
||||
else
|
||||
luaG_runerror(L, "attempt to yield from outside a coroutine");
|
||||
}
|
||||
L->status = LUA_YIELD;
|
||||
ci->u2.nyield = nresults; /* save number of results */
|
||||
if (isLua(ci)) { /* inside a hook? */
|
||||
lua_assert(!isLuacode(ci));
|
||||
api_check(L, nresults == 0, "hooks cannot yield values");
|
||||
api_check(L, k == NULL, "hooks cannot continue after yielding");
|
||||
ci->u2.nyield = 0; /* no results */
|
||||
}
|
||||
else {
|
||||
if ((ci->u.c.k = k) != NULL) /* is there a continuation? */
|
||||
ci->u.c.ctx = ctx; /* save context */
|
||||
ci->u2.nyield = nresults; /* save number of results */
|
||||
luaD_throw(L, LUA_YIELD);
|
||||
}
|
||||
lua_assert(ci->callstatus & CIST_HOOKED); /* must be inside a hook */
|
||||
@@ -734,6 +872,45 @@ LUA_API int lua_yieldk (lua_State *L, int nresults, lua_KContext ctx,
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** Auxiliary structure to call 'luaF_close' in protected mode.
|
||||
*/
|
||||
struct CloseP {
|
||||
StkId level;
|
||||
int status;
|
||||
};
|
||||
|
||||
|
||||
/*
|
||||
** Auxiliary function to call 'luaF_close' in protected mode.
|
||||
*/
|
||||
static void closepaux (lua_State *L, void *ud) {
|
||||
struct CloseP *pcl = cast(struct CloseP *, ud);
|
||||
luaF_close(L, pcl->level, pcl->status, 0);
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** Calls 'luaF_close' in protected mode. Return the original status
|
||||
** or, in case of errors, the new status.
|
||||
*/
|
||||
int luaD_closeprotected (lua_State *L, ptrdiff_t level, int status) {
|
||||
CallInfo *old_ci = L->ci;
|
||||
lu_byte old_allowhooks = L->allowhook;
|
||||
for (;;) { /* keep closing upvalues until no more errors */
|
||||
struct CloseP pcl;
|
||||
pcl.level = restorestack(L, level); pcl.status = status;
|
||||
status = luaD_rawrunprotected(L, &closepaux, &pcl);
|
||||
if (l_likely(status == LUA_OK)) /* no more errors? */
|
||||
return pcl.status;
|
||||
else { /* an error occurred; restore saved state and repeat */
|
||||
L->ci = old_ci;
|
||||
L->allowhook = old_allowhooks;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** Call the C function 'func' in protected mode, restoring basic
|
||||
** thread information ('allowhook', etc.) and in particular
|
||||
@@ -747,14 +924,12 @@ int luaD_pcall (lua_State *L, Pfunc func, void *u,
|
||||
ptrdiff_t old_errfunc = L->errfunc;
|
||||
L->errfunc = ef;
|
||||
status = luaD_rawrunprotected(L, func, u);
|
||||
if (unlikely(status != LUA_OK)) { /* an error occurred? */
|
||||
StkId oldtop = restorestack(L, old_top);
|
||||
if (l_unlikely(status != LUA_OK)) { /* an error occurred? */
|
||||
L->ci = old_ci;
|
||||
L->allowhook = old_allowhooks;
|
||||
status = luaF_close(L, oldtop, status);
|
||||
oldtop = restorestack(L, old_top); /* previous call may change stack */
|
||||
luaD_seterrorobj(L, status, oldtop);
|
||||
luaD_shrinkstack(L);
|
||||
status = luaD_closeprotected(L, old_top, status);
|
||||
luaD_seterrorobj(L, status, restorestack(L, old_top));
|
||||
luaD_shrinkstack(L); /* restore stack size in case of overflow */
|
||||
}
|
||||
L->errfunc = old_errfunc;
|
||||
return status;
|
||||
|
||||
@@ -17,11 +17,13 @@
|
||||
** Macro to check stack size and grow stack if needed. Parameters
|
||||
** 'pre'/'pos' allow the macro to preserve a pointer into the
|
||||
** stack across reallocations, doing the work only when needed.
|
||||
** It also allows the running of one GC step when the stack is
|
||||
** reallocated.
|
||||
** 'condmovestack' is used in heavy tests to force a stack reallocation
|
||||
** at every check.
|
||||
*/
|
||||
#define luaD_checkstackaux(L,n,pre,pos) \
|
||||
if (L->stack_last - L->top <= (n)) \
|
||||
if (l_unlikely(L->stack_last - L->top <= (n))) \
|
||||
{ pre; luaD_growstack(L, n, 1); pos; } \
|
||||
else { condmovestack(L,pre,pos); }
|
||||
|
||||
@@ -35,7 +37,7 @@
|
||||
|
||||
|
||||
/* macro to check stack size, preserving 'p' */
|
||||
#define checkstackp(L,n,p) \
|
||||
#define checkstackGCp(L,n,p) \
|
||||
luaD_checkstackaux(L, n, \
|
||||
ptrdiff_t t__ = savestack(L, p); /* save 'p' */ \
|
||||
luaC_checkGC(L), /* stack grow uses memory */ \
|
||||
@@ -44,7 +46,7 @@
|
||||
|
||||
/* macro to check stack size and GC */
|
||||
#define checkstackGC(L,fsize) \
|
||||
luaD_checkstackaux(L, (fsize), (void)0, luaC_checkGC(L))
|
||||
luaD_checkstackaux(L, (fsize), luaC_checkGC(L), (void)0)
|
||||
|
||||
|
||||
/* type of protected functions, to be ran by 'runprotected' */
|
||||
@@ -56,10 +58,12 @@ LUAI_FUNC int luaD_protectedparser (lua_State *L, ZIO *z, const char *name,
|
||||
LUAI_FUNC void luaD_hook (lua_State *L, int event, int line,
|
||||
int fTransfer, int nTransfer);
|
||||
LUAI_FUNC void luaD_hookcall (lua_State *L, CallInfo *ci);
|
||||
LUAI_FUNC void luaD_pretailcall (lua_State *L, CallInfo *ci, StkId func, int n);
|
||||
LUAI_FUNC int luaD_pretailcall (lua_State *L, CallInfo *ci, StkId func, int narg1, int delta);
|
||||
LUAI_FUNC CallInfo *luaD_precall (lua_State *L, StkId func, int nResults);
|
||||
LUAI_FUNC void luaD_call (lua_State *L, StkId func, int nResults);
|
||||
LUAI_FUNC void luaD_callnoyield (lua_State *L, StkId func, int nResults);
|
||||
LUAI_FUNC void luaD_tryfuncTM (lua_State *L, StkId func);
|
||||
LUAI_FUNC StkId luaD_tryfuncTM (lua_State *L, StkId func);
|
||||
LUAI_FUNC int luaD_closeprotected (lua_State *L, ptrdiff_t level, int status);
|
||||
LUAI_FUNC int luaD_pcall (lua_State *L, Pfunc func, void *u,
|
||||
ptrdiff_t oldtop, ptrdiff_t ef);
|
||||
LUAI_FUNC void luaD_poscall (lua_State *L, CallInfo *ci, int nres);
|
||||
|
||||
@@ -29,15 +29,15 @@ typedef struct {
|
||||
|
||||
|
||||
/*
|
||||
** All high-level dumps go through DumpVector; you can change it to
|
||||
** All high-level dumps go through dumpVector; you can change it to
|
||||
** change the endianness of the result
|
||||
*/
|
||||
#define DumpVector(v,n,D) DumpBlock(v,(n)*sizeof((v)[0]),D)
|
||||
#define dumpVector(D,v,n) dumpBlock(D,v,(n)*sizeof((v)[0]))
|
||||
|
||||
#define DumpLiteral(s,D) DumpBlock(s, sizeof(s) - sizeof(char), D)
|
||||
#define dumpLiteral(D, s) dumpBlock(D,s,sizeof(s) - sizeof(char))
|
||||
|
||||
|
||||
static void DumpBlock (const void *b, size_t size, DumpState *D) {
|
||||
static void dumpBlock (DumpState *D, const void *b, size_t size) {
|
||||
if (D->status == 0 && size > 0) {
|
||||
lua_unlock(D->L);
|
||||
D->status = (*D->writer)(D->L, b, size, D->data);
|
||||
@@ -46,19 +46,19 @@ static void DumpBlock (const void *b, size_t size, DumpState *D) {
|
||||
}
|
||||
|
||||
|
||||
#define DumpVar(x,D) DumpVector(&x,1,D)
|
||||
#define dumpVar(D,x) dumpVector(D,&x,1)
|
||||
|
||||
|
||||
static void DumpByte (int y, DumpState *D) {
|
||||
static void dumpByte (DumpState *D, int y) {
|
||||
lu_byte x = (lu_byte)y;
|
||||
DumpVar(x, D);
|
||||
dumpVar(D, x);
|
||||
}
|
||||
|
||||
|
||||
/* DumpInt Buff Size */
|
||||
/* dumpInt Buff Size */
|
||||
#define DIBS ((sizeof(size_t) * 8 / 7) + 1)
|
||||
|
||||
static void DumpSize (size_t x, DumpState *D) {
|
||||
static void dumpSize (DumpState *D, size_t x) {
|
||||
lu_byte buff[DIBS];
|
||||
int n = 0;
|
||||
do {
|
||||
@@ -66,146 +66,144 @@ static void DumpSize (size_t x, DumpState *D) {
|
||||
x >>= 7;
|
||||
} while (x != 0);
|
||||
buff[DIBS - 1] |= 0x80; /* mark last byte */
|
||||
DumpVector(buff + DIBS - n, n, D);
|
||||
dumpVector(D, buff + DIBS - n, n);
|
||||
}
|
||||
|
||||
|
||||
static void DumpInt (int x, DumpState *D) {
|
||||
DumpSize(x, D);
|
||||
static void dumpInt (DumpState *D, int x) {
|
||||
dumpSize(D, x);
|
||||
}
|
||||
|
||||
|
||||
static void DumpNumber (lua_Number x, DumpState *D) {
|
||||
DumpVar(x, D);
|
||||
static void dumpNumber (DumpState *D, lua_Number x) {
|
||||
dumpVar(D, x);
|
||||
}
|
||||
|
||||
|
||||
static void DumpInteger (lua_Integer x, DumpState *D) {
|
||||
DumpVar(x, D);
|
||||
static void dumpInteger (DumpState *D, lua_Integer x) {
|
||||
dumpVar(D, x);
|
||||
}
|
||||
|
||||
|
||||
static void DumpString (const TString *s, DumpState *D) {
|
||||
static void dumpString (DumpState *D, const TString *s) {
|
||||
if (s == NULL)
|
||||
DumpSize(0, D);
|
||||
dumpSize(D, 0);
|
||||
else {
|
||||
size_t size = tsslen(s);
|
||||
const char *str = getstr(s);
|
||||
DumpSize(size + 1, D);
|
||||
DumpVector(str, size, D);
|
||||
dumpSize(D, size + 1);
|
||||
dumpVector(D, str, size);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
static void DumpCode (const Proto *f, DumpState *D) {
|
||||
DumpInt(f->sizecode, D);
|
||||
DumpVector(f->code, f->sizecode, D);
|
||||
static void dumpCode (DumpState *D, const Proto *f) {
|
||||
dumpInt(D, f->sizecode);
|
||||
dumpVector(D, f->code, f->sizecode);
|
||||
}
|
||||
|
||||
|
||||
static void DumpFunction(const Proto *f, TString *psource, DumpState *D);
|
||||
static void dumpFunction(DumpState *D, const Proto *f, TString *psource);
|
||||
|
||||
static void DumpConstants (const Proto *f, DumpState *D) {
|
||||
static void dumpConstants (DumpState *D, const Proto *f) {
|
||||
int i;
|
||||
int n = f->sizek;
|
||||
DumpInt(n, D);
|
||||
dumpInt(D, n);
|
||||
for (i = 0; i < n; i++) {
|
||||
const TValue *o = &f->k[i];
|
||||
DumpByte(ttypetag(o), D);
|
||||
switch (ttypetag(o)) {
|
||||
case LUA_TNIL:
|
||||
int tt = ttypetag(o);
|
||||
dumpByte(D, tt);
|
||||
switch (tt) {
|
||||
case LUA_VNUMFLT:
|
||||
dumpNumber(D, fltvalue(o));
|
||||
break;
|
||||
case LUA_TBOOLEAN:
|
||||
DumpByte(bvalue(o), D);
|
||||
case LUA_VNUMINT:
|
||||
dumpInteger(D, ivalue(o));
|
||||
break;
|
||||
case LUA_TNUMFLT:
|
||||
DumpNumber(fltvalue(o), D);
|
||||
case LUA_VSHRSTR:
|
||||
case LUA_VLNGSTR:
|
||||
dumpString(D, tsvalue(o));
|
||||
break;
|
||||
case LUA_TNUMINT:
|
||||
DumpInteger(ivalue(o), D);
|
||||
break;
|
||||
case LUA_TSHRSTR:
|
||||
case LUA_TLNGSTR:
|
||||
DumpString(tsvalue(o), D);
|
||||
break;
|
||||
default: lua_assert(0);
|
||||
default:
|
||||
lua_assert(tt == LUA_VNIL || tt == LUA_VFALSE || tt == LUA_VTRUE);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
static void DumpProtos (const Proto *f, DumpState *D) {
|
||||
static void dumpProtos (DumpState *D, const Proto *f) {
|
||||
int i;
|
||||
int n = f->sizep;
|
||||
DumpInt(n, D);
|
||||
dumpInt(D, n);
|
||||
for (i = 0; i < n; i++)
|
||||
DumpFunction(f->p[i], f->source, D);
|
||||
dumpFunction(D, f->p[i], f->source);
|
||||
}
|
||||
|
||||
|
||||
static void DumpUpvalues (const Proto *f, DumpState *D) {
|
||||
static void dumpUpvalues (DumpState *D, const Proto *f) {
|
||||
int i, n = f->sizeupvalues;
|
||||
DumpInt(n, D);
|
||||
dumpInt(D, n);
|
||||
for (i = 0; i < n; i++) {
|
||||
DumpByte(f->upvalues[i].instack, D);
|
||||
DumpByte(f->upvalues[i].idx, D);
|
||||
dumpByte(D, f->upvalues[i].instack);
|
||||
dumpByte(D, f->upvalues[i].idx);
|
||||
dumpByte(D, f->upvalues[i].kind);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
static void DumpDebug (const Proto *f, DumpState *D) {
|
||||
static void dumpDebug (DumpState *D, const Proto *f) {
|
||||
int i, n;
|
||||
n = (D->strip) ? 0 : f->sizelineinfo;
|
||||
DumpInt(n, D);
|
||||
DumpVector(f->lineinfo, n, D);
|
||||
dumpInt(D, n);
|
||||
dumpVector(D, f->lineinfo, n);
|
||||
n = (D->strip) ? 0 : f->sizeabslineinfo;
|
||||
DumpInt(n, D);
|
||||
dumpInt(D, n);
|
||||
for (i = 0; i < n; i++) {
|
||||
DumpInt(f->abslineinfo[i].pc, D);
|
||||
DumpInt(f->abslineinfo[i].line, D);
|
||||
dumpInt(D, f->abslineinfo[i].pc);
|
||||
dumpInt(D, f->abslineinfo[i].line);
|
||||
}
|
||||
n = (D->strip) ? 0 : f->sizelocvars;
|
||||
DumpInt(n, D);
|
||||
dumpInt(D, n);
|
||||
for (i = 0; i < n; i++) {
|
||||
DumpString(f->locvars[i].varname, D);
|
||||
DumpInt(f->locvars[i].startpc, D);
|
||||
DumpInt(f->locvars[i].endpc, D);
|
||||
dumpString(D, f->locvars[i].varname);
|
||||
dumpInt(D, f->locvars[i].startpc);
|
||||
dumpInt(D, f->locvars[i].endpc);
|
||||
}
|
||||
n = (D->strip) ? 0 : f->sizeupvalues;
|
||||
DumpInt(n, D);
|
||||
dumpInt(D, n);
|
||||
for (i = 0; i < n; i++)
|
||||
DumpString(f->upvalues[i].name, D);
|
||||
dumpString(D, f->upvalues[i].name);
|
||||
}
|
||||
|
||||
|
||||
static void DumpFunction (const Proto *f, TString *psource, DumpState *D) {
|
||||
static void dumpFunction (DumpState *D, const Proto *f, TString *psource) {
|
||||
if (D->strip || f->source == psource)
|
||||
DumpString(NULL, D); /* no debug info or same source as its parent */
|
||||
dumpString(D, NULL); /* no debug info or same source as its parent */
|
||||
else
|
||||
DumpString(f->source, D);
|
||||
DumpInt(f->linedefined, D);
|
||||
DumpInt(f->lastlinedefined, D);
|
||||
DumpByte(f->numparams, D);
|
||||
DumpByte(f->is_vararg, D);
|
||||
DumpByte(f->maxstacksize, D);
|
||||
DumpCode(f, D);
|
||||
DumpConstants(f, D);
|
||||
DumpUpvalues(f, D);
|
||||
DumpProtos(f, D);
|
||||
DumpDebug(f, D);
|
||||
dumpString(D, f->source);
|
||||
dumpInt(D, f->linedefined);
|
||||
dumpInt(D, f->lastlinedefined);
|
||||
dumpByte(D, f->numparams);
|
||||
dumpByte(D, f->is_vararg);
|
||||
dumpByte(D, f->maxstacksize);
|
||||
dumpCode(D, f);
|
||||
dumpConstants(D, f);
|
||||
dumpUpvalues(D, f);
|
||||
dumpProtos(D, f);
|
||||
dumpDebug(D, f);
|
||||
}
|
||||
|
||||
|
||||
static void DumpHeader (DumpState *D) {
|
||||
DumpLiteral(LUA_SIGNATURE, D);
|
||||
DumpInt(LUAC_VERSION, D);
|
||||
DumpByte(LUAC_FORMAT, D);
|
||||
DumpLiteral(LUAC_DATA, D);
|
||||
DumpByte(sizeof(Instruction), D);
|
||||
DumpByte(sizeof(lua_Integer), D);
|
||||
DumpByte(sizeof(lua_Number), D);
|
||||
DumpInteger(LUAC_INT, D);
|
||||
DumpNumber(LUAC_NUM, D);
|
||||
static void dumpHeader (DumpState *D) {
|
||||
dumpLiteral(D, LUA_SIGNATURE);
|
||||
dumpByte(D, LUAC_VERSION);
|
||||
dumpByte(D, LUAC_FORMAT);
|
||||
dumpLiteral(D, LUAC_DATA);
|
||||
dumpByte(D, sizeof(Instruction));
|
||||
dumpByte(D, sizeof(lua_Integer));
|
||||
dumpByte(D, sizeof(lua_Number));
|
||||
dumpInteger(D, LUAC_INT);
|
||||
dumpNumber(D, LUAC_NUM);
|
||||
}
|
||||
|
||||
|
||||
@@ -220,9 +218,9 @@ int luaU_dump(lua_State *L, const Proto *f, lua_Writer w, void *data,
|
||||
D.data = data;
|
||||
D.strip = strip;
|
||||
D.status = 0;
|
||||
DumpHeader(&D);
|
||||
DumpByte(f->sizeupvalues, &D);
|
||||
DumpFunction(f, NULL, &D);
|
||||
dumpHeader(&D);
|
||||
dumpByte(&D, f->sizeupvalues);
|
||||
dumpFunction(&D, f, NULL);
|
||||
return D.status;
|
||||
}
|
||||
|
||||
|
||||
@@ -24,20 +24,20 @@
|
||||
|
||||
|
||||
|
||||
CClosure *luaF_newCclosure (lua_State *L, int n) {
|
||||
GCObject *o = luaC_newobj(L, LUA_TCCL, sizeCclosure(n));
|
||||
CClosure *luaF_newCclosure (lua_State *L, int nupvals) {
|
||||
GCObject *o = luaC_newobj(L, LUA_VCCL, sizeCclosure(nupvals));
|
||||
CClosure *c = gco2ccl(o);
|
||||
c->nupvalues = cast_byte(n);
|
||||
c->nupvalues = cast_byte(nupvals);
|
||||
return c;
|
||||
}
|
||||
|
||||
|
||||
LClosure *luaF_newLclosure (lua_State *L, int n) {
|
||||
GCObject *o = luaC_newobj(L, LUA_TLCL, sizeLclosure(n));
|
||||
LClosure *luaF_newLclosure (lua_State *L, int nupvals) {
|
||||
GCObject *o = luaC_newobj(L, LUA_VLCL, sizeLclosure(nupvals));
|
||||
LClosure *c = gco2lcl(o);
|
||||
c->p = NULL;
|
||||
c->nupvalues = cast_byte(n);
|
||||
while (n--) c->upvals[n] = NULL;
|
||||
c->nupvalues = cast_byte(nupvals);
|
||||
while (nupvals--) c->upvals[nupvals] = NULL;
|
||||
return c;
|
||||
}
|
||||
|
||||
@@ -48,25 +48,26 @@ LClosure *luaF_newLclosure (lua_State *L, int n) {
|
||||
void luaF_initupvals (lua_State *L, LClosure *cl) {
|
||||
int i;
|
||||
for (i = 0; i < cl->nupvalues; i++) {
|
||||
GCObject *o = luaC_newobj(L, LUA_TUPVAL, sizeof(UpVal));
|
||||
GCObject *o = luaC_newobj(L, LUA_VUPVAL, sizeof(UpVal));
|
||||
UpVal *uv = gco2upv(o);
|
||||
uv->v = &uv->u.value; /* make it closed */
|
||||
setnilvalue(uv->v);
|
||||
cl->upvals[i] = uv;
|
||||
luaC_objbarrier(L, cl, o);
|
||||
luaC_objbarrier(L, cl, uv);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** Create a new upvalue with the given tag at the given level,
|
||||
** and link it to the list of open upvalues of 'L' after entry 'prev'.
|
||||
** Create a new upvalue at the given level, and link it to the list of
|
||||
** open upvalues of 'L' after entry 'prev'.
|
||||
**/
|
||||
static UpVal *newupval (lua_State *L, int tag, StkId level, UpVal **prev) {
|
||||
GCObject *o = luaC_newobj(L, tag, sizeof(UpVal));
|
||||
static UpVal *newupval (lua_State *L, int tbc, StkId level, UpVal **prev) {
|
||||
GCObject *o = luaC_newobj(L, LUA_VUPVAL, sizeof(UpVal));
|
||||
UpVal *uv = gco2upv(o);
|
||||
UpVal *next = *prev;
|
||||
uv->v = s2v(level); /* current value lives in the stack */
|
||||
uv->tbc = tbc;
|
||||
uv->u.open.next = next; /* link it to list of open upvalues */
|
||||
uv->u.open.previous = prev;
|
||||
if (next)
|
||||
@@ -81,7 +82,7 @@ static UpVal *newupval (lua_State *L, int tag, StkId level, UpVal **prev) {
|
||||
|
||||
|
||||
/*
|
||||
** Find and reuse, or create if it does not exist, a regular upvalue
|
||||
** Find and reuse, or create if it does not exist, an upvalue
|
||||
** at the given level.
|
||||
*/
|
||||
UpVal *luaF_findupval (lua_State *L, StkId level) {
|
||||
@@ -89,103 +90,93 @@ UpVal *luaF_findupval (lua_State *L, StkId level) {
|
||||
UpVal *p;
|
||||
lua_assert(isintwups(L) || L->openupval == NULL);
|
||||
while ((p = *pp) != NULL && uplevel(p) >= level) { /* search for it */
|
||||
if (uplevel(p) == level && !isdead(G(L), p)) /* corresponding upvalue? */
|
||||
lua_assert(!isdead(G(L), p));
|
||||
if (uplevel(p) == level) /* corresponding upvalue? */
|
||||
return p; /* return it */
|
||||
pp = &p->u.open.next;
|
||||
}
|
||||
/* not found: create a new upvalue after 'pp' */
|
||||
return newupval(L, LUA_TUPVAL, level, pp);
|
||||
}
|
||||
|
||||
|
||||
static void callclose (lua_State *L, void *ud) {
|
||||
UNUSED(ud);
|
||||
luaD_callnoyield(L, L->top - 3, 0);
|
||||
return newupval(L, 0, level, pp);
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** Prepare closing method plus its arguments for object 'obj' with
|
||||
** error message 'err'. (This function assumes EXTRA_STACK.)
|
||||
** Call closing method for object 'obj' with error message 'err'. The
|
||||
** boolean 'yy' controls whether the call is yieldable.
|
||||
** (This function assumes EXTRA_STACK.)
|
||||
*/
|
||||
static int prepclosingmethod (lua_State *L, TValue *obj, TValue *err) {
|
||||
static void callclosemethod (lua_State *L, TValue *obj, TValue *err, int yy) {
|
||||
StkId top = L->top;
|
||||
const TValue *tm = luaT_gettmbyobj(L, obj, TM_CLOSE);
|
||||
if (ttisnil(tm)) /* no metamethod? */
|
||||
return 0; /* nothing to call */
|
||||
setobj2s(L, top, tm); /* will call metamethod... */
|
||||
setobj2s(L, top + 1, obj); /* with 'self' as the 1st argument */
|
||||
setobj2s(L, top + 2, err); /* and error msg. as 2nd argument */
|
||||
L->top = top + 3; /* add function and arguments */
|
||||
return 1;
|
||||
if (yy)
|
||||
luaD_call(L, top, 0);
|
||||
else
|
||||
luaD_callnoyield(L, top, 0);
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** Prepare and call a closing method. If status is OK, code is still
|
||||
** inside the original protected call, and so any error will be handled
|
||||
** there. Otherwise, a previous error already activated original
|
||||
** protected call, and so the call to the closing method must be
|
||||
** protected here. (A status = CLOSEPROTECT behaves like a previous
|
||||
** error, to also run the closing method in protected mode).
|
||||
** If status is OK, the call to the closing method will be pushed
|
||||
** at the top of the stack. Otherwise, values are pushed after
|
||||
** the 'level' of the upvalue being closed, as everything after
|
||||
** that won't be used again.
|
||||
** Check whether object at given level has a close metamethod and raise
|
||||
** an error if not.
|
||||
*/
|
||||
static int callclosemth (lua_State *L, TValue *uv, StkId level, int status) {
|
||||
if (likely(status == LUA_OK)) {
|
||||
if (prepclosingmethod(L, uv, &G(L)->nilvalue)) /* something to call? */
|
||||
callclose(L, NULL); /* call closing method */
|
||||
else if (!ttisnil(uv)) { /* non-closable non-nil value? */
|
||||
int idx = cast_int(level - L->ci->func);
|
||||
const char *vname = luaG_findlocal(L, L->ci, idx, NULL);
|
||||
if (vname == NULL) vname = "?";
|
||||
luaG_runerror(L, "attempt to close non-closable variable '%s'", vname);
|
||||
}
|
||||
static void checkclosemth (lua_State *L, StkId level) {
|
||||
const TValue *tm = luaT_gettmbyobj(L, s2v(level), TM_CLOSE);
|
||||
if (ttisnil(tm)) { /* no metamethod? */
|
||||
int idx = cast_int(level - L->ci->func); /* variable index */
|
||||
const char *vname = luaG_findlocal(L, L->ci, idx, NULL);
|
||||
if (vname == NULL) vname = "?";
|
||||
luaG_runerror(L, "variable '%s' got a non-closable value", vname);
|
||||
}
|
||||
else { /* must close the object in protected mode */
|
||||
ptrdiff_t oldtop = savestack(L, level + 1);
|
||||
/* save error message and set stack top to 'level + 1' */
|
||||
luaD_seterrorobj(L, status, level);
|
||||
if (prepclosingmethod(L, uv, s2v(level))) { /* something to call? */
|
||||
int newstatus = luaD_pcall(L, callclose, NULL, oldtop, 0);
|
||||
if (newstatus != LUA_OK && status == CLOSEPROTECT) /* first error? */
|
||||
status = newstatus; /* this will be the new error */
|
||||
else /* leave original error (or nil) on top */
|
||||
L->top = restorestack(L, oldtop);
|
||||
}
|
||||
/* else no metamethod; ignore this case and keep original error */
|
||||
}
|
||||
return status;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** Try to create a to-be-closed upvalue
|
||||
** (can raise a memory-allocation error)
|
||||
** Prepare and call a closing method.
|
||||
** If status is CLOSEKTOP, the call to the closing method will be pushed
|
||||
** at the top of the stack. Otherwise, values can be pushed right after
|
||||
** the 'level' of the upvalue being closed, as everything after that
|
||||
** won't be used again.
|
||||
*/
|
||||
static void trynewtbcupval (lua_State *L, void *ud) {
|
||||
StkId level = cast(StkId, ud);
|
||||
lua_assert(L->openupval == NULL || uplevel(L->openupval) < level);
|
||||
newupval(L, LUA_TUPVALTBC, level, &L->openupval);
|
||||
static void prepcallclosemth (lua_State *L, StkId level, int status, int yy) {
|
||||
TValue *uv = s2v(level); /* value being closed */
|
||||
TValue *errobj;
|
||||
if (status == CLOSEKTOP)
|
||||
errobj = &G(L)->nilvalue; /* error object is nil */
|
||||
else { /* 'luaD_seterrorobj' will set top to level + 2 */
|
||||
errobj = s2v(level + 1); /* error object goes after 'uv' */
|
||||
luaD_seterrorobj(L, status, level + 1); /* set error object */
|
||||
}
|
||||
callclosemethod(L, uv, errobj, yy);
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** Create a to-be-closed upvalue. If there is a memory error
|
||||
** when creating the upvalue, the closing method must be called here,
|
||||
** as there is no upvalue to call it later.
|
||||
** Maximum value for deltas in 'tbclist', dependent on the type
|
||||
** of delta. (This macro assumes that an 'L' is in scope where it
|
||||
** is used.)
|
||||
*/
|
||||
#define MAXDELTA \
|
||||
((256ul << ((sizeof(L->stack->tbclist.delta) - 1) * 8)) - 1)
|
||||
|
||||
|
||||
/*
|
||||
** Insert a variable in the list of to-be-closed variables.
|
||||
*/
|
||||
void luaF_newtbcupval (lua_State *L, StkId level) {
|
||||
int status = luaD_rawrunprotected(L, trynewtbcupval, level);
|
||||
if (unlikely(status != LUA_OK)) { /* memory error creating upvalue? */
|
||||
lua_assert(status == LUA_ERRMEM);
|
||||
luaD_seterrorobj(L, LUA_ERRMEM, level + 1); /* save error message */
|
||||
if (prepclosingmethod(L, s2v(level), s2v(level + 1)))
|
||||
callclose(L, NULL); /* call closing method */
|
||||
luaD_throw(L, LUA_ERRMEM); /* throw memory error */
|
||||
lua_assert(level > L->tbclist);
|
||||
if (l_isfalse(s2v(level)))
|
||||
return; /* false doesn't need to be closed */
|
||||
checkclosemth(L, level); /* value must have a close method */
|
||||
while (cast_uint(level - L->tbclist) > MAXDELTA) {
|
||||
L->tbclist += MAXDELTA; /* create a dummy node at maximum delta */
|
||||
L->tbclist->tbclist.delta = 0;
|
||||
}
|
||||
level->tbclist.delta = cast(unsigned short, level - L->tbclist);
|
||||
L->tbclist = level;
|
||||
}
|
||||
|
||||
|
||||
@@ -197,30 +188,57 @@ void luaF_unlinkupval (UpVal *uv) {
|
||||
}
|
||||
|
||||
|
||||
int luaF_close (lua_State *L, StkId level, int status) {
|
||||
/*
|
||||
** Close all upvalues up to the given stack level.
|
||||
*/
|
||||
void luaF_closeupval (lua_State *L, StkId level) {
|
||||
UpVal *uv;
|
||||
while ((uv = L->openupval) != NULL && uplevel(uv) >= level) {
|
||||
StkId upl = uplevel(uv);
|
||||
StkId upl; /* stack index pointed by 'uv' */
|
||||
while ((uv = L->openupval) != NULL && (upl = uplevel(uv)) >= level) {
|
||||
TValue *slot = &uv->u.value; /* new position for value */
|
||||
luaF_unlinkupval(uv);
|
||||
lua_assert(uplevel(uv) < L->top);
|
||||
luaF_unlinkupval(uv); /* remove upvalue from 'openupval' list */
|
||||
setobj(L, slot, uv->v); /* move value to upvalue slot */
|
||||
uv->v = slot; /* now current value lives here */
|
||||
if (!iswhite(uv))
|
||||
gray2black(uv); /* closed upvalues cannot be gray */
|
||||
luaC_barrier(L, uv, slot);
|
||||
if (uv->tt == LUA_TUPVALTBC && status != NOCLOSINGMETH) {
|
||||
/* must run closing method */
|
||||
ptrdiff_t levelrel = savestack(L, level);
|
||||
status = callclosemth(L, uv->v, upl, status); /* may change the stack */
|
||||
level = restorestack(L, levelrel);
|
||||
if (!iswhite(uv)) { /* neither white nor dead? */
|
||||
nw2black(uv); /* closed upvalues cannot be gray */
|
||||
luaC_barrier(L, uv, slot);
|
||||
}
|
||||
}
|
||||
return status;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** Remove firt element from the tbclist plus its dummy nodes.
|
||||
*/
|
||||
static void poptbclist (lua_State *L) {
|
||||
StkId tbc = L->tbclist;
|
||||
lua_assert(tbc->tbclist.delta > 0); /* first element cannot be dummy */
|
||||
tbc -= tbc->tbclist.delta;
|
||||
while (tbc > L->stack && tbc->tbclist.delta == 0)
|
||||
tbc -= MAXDELTA; /* remove dummy nodes */
|
||||
L->tbclist = tbc;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** Close all upvalues and to-be-closed variables up to the given stack
|
||||
** level.
|
||||
*/
|
||||
void luaF_close (lua_State *L, StkId level, int status, int yy) {
|
||||
ptrdiff_t levelrel = savestack(L, level);
|
||||
luaF_closeupval(L, level); /* first, close the upvalues */
|
||||
while (L->tbclist >= level) { /* traverse tbc's down to that level */
|
||||
StkId tbc = L->tbclist; /* get variable index */
|
||||
poptbclist(L); /* remove it from list */
|
||||
prepcallclosemth(L, tbc, status, yy); /* close variable */
|
||||
level = restorestack(L, levelrel);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Proto *luaF_newproto (lua_State *L) {
|
||||
GCObject *o = luaC_newobj(L, LUA_TPROTO, sizeof(Proto));
|
||||
GCObject *o = luaC_newobj(L, LUA_VPROTO, sizeof(Proto));
|
||||
Proto *f = gco2p(o);
|
||||
f->k = NULL;
|
||||
f->sizek = 0;
|
||||
|
||||
@@ -42,24 +42,19 @@
|
||||
#define MAXMISS 10
|
||||
|
||||
|
||||
/*
|
||||
** Special "status" for 'luaF_close'
|
||||
*/
|
||||
|
||||
/* close upvalues without running their closing methods */
|
||||
#define NOCLOSINGMETH (-1)
|
||||
|
||||
/* close upvalues running all closing methods in protected mode */
|
||||
#define CLOSEPROTECT (-2)
|
||||
/* special status to close upvalues preserving the top of the stack */
|
||||
#define CLOSEKTOP (-1)
|
||||
|
||||
|
||||
LUAI_FUNC Proto *luaF_newproto (lua_State *L);
|
||||
LUAI_FUNC CClosure *luaF_newCclosure (lua_State *L, int nelems);
|
||||
LUAI_FUNC LClosure *luaF_newLclosure (lua_State *L, int nelems);
|
||||
LUAI_FUNC CClosure *luaF_newCclosure (lua_State *L, int nupvals);
|
||||
LUAI_FUNC LClosure *luaF_newLclosure (lua_State *L, int nupvals);
|
||||
LUAI_FUNC void luaF_initupvals (lua_State *L, LClosure *cl);
|
||||
LUAI_FUNC UpVal *luaF_findupval (lua_State *L, StkId level);
|
||||
LUAI_FUNC void luaF_newtbcupval (lua_State *L, StkId level);
|
||||
LUAI_FUNC int luaF_close (lua_State *L, StkId level, int status);
|
||||
LUAI_FUNC void luaF_closeupval (lua_State *L, StkId level);
|
||||
LUAI_FUNC void luaF_close (lua_State *L, StkId level, int status, int yy);
|
||||
LUAI_FUNC void luaF_unlinkupval (UpVal *uv);
|
||||
LUAI_FUNC void luaF_freeproto (lua_State *L, Proto *f);
|
||||
LUAI_FUNC const char *luaF_getlocalname (const Proto *func, int local_number,
|
||||
|
||||
@@ -12,16 +12,16 @@
|
||||
#include "lstate.h"
|
||||
|
||||
/*
|
||||
** Collectable objects may have one of three colors: white, which
|
||||
** means the object is not marked; gray, which means the
|
||||
** object is marked, but its references may be not marked; and
|
||||
** black, which means that the object and all its references are marked.
|
||||
** The main invariant of the garbage collector, while marking objects,
|
||||
** is that a black object can never point to a white one. Moreover,
|
||||
** any gray object must be in a "gray list" (gray, grayagain, weak,
|
||||
** allweak, ephemeron) so that it can be visited again before finishing
|
||||
** the collection cycle. These lists have no meaning when the invariant
|
||||
** is not being enforced (e.g., sweep phase).
|
||||
** Collectable objects may have one of three colors: white, which means
|
||||
** the object is not marked; gray, which means the object is marked, but
|
||||
** its references may be not marked; and black, which means that the
|
||||
** object and all its references are marked. The main invariant of the
|
||||
** garbage collector, while marking objects, is that a black object can
|
||||
** never point to a white one. Moreover, any gray object must be in a
|
||||
** "gray list" (gray, grayagain, weak, allweak, ephemeron) so that it
|
||||
** can be visited again before finishing the collection cycle. (Open
|
||||
** upvalues are an exception to this rule.) These lists have no meaning
|
||||
** when the invariant is not being enforced (e.g., sweep phase).
|
||||
*/
|
||||
|
||||
|
||||
@@ -69,14 +69,16 @@
|
||||
|
||||
/*
|
||||
** Layout for bit use in 'marked' field. First three bits are
|
||||
** used for object "age" in generational mode. Last bit is free
|
||||
** to be used by respective objects.
|
||||
** used for object "age" in generational mode. Last bit is used
|
||||
** by tests.
|
||||
*/
|
||||
#define WHITE0BIT 3 /* object is white (type 0) */
|
||||
#define WHITE1BIT 4 /* object is white (type 1) */
|
||||
#define BLACKBIT 5 /* object is black */
|
||||
#define FINALIZEDBIT 6 /* object has been marked for finalization */
|
||||
|
||||
#define TESTBIT 7
|
||||
|
||||
|
||||
|
||||
#define WHITEBITS bit2mask(WHITE0BIT, WHITE1BIT)
|
||||
@@ -94,7 +96,8 @@
|
||||
#define isdead(g,v) isdeadm(otherwhite(g), (v)->marked)
|
||||
|
||||
#define changewhite(x) ((x)->marked ^= WHITEBITS)
|
||||
#define gray2black(x) l_setbit((x)->marked, BLACKBIT)
|
||||
#define nw2black(x) \
|
||||
check_exp(!iswhite(x), l_setbit((x)->marked, BLACKBIT))
|
||||
|
||||
#define luaC_white(g) cast_byte((g)->currentwhite & WHITEBITS)
|
||||
|
||||
@@ -145,6 +148,16 @@
|
||||
*/
|
||||
#define isdecGCmodegen(g) (g->gckind == KGC_GEN || g->lastatomic != 0)
|
||||
|
||||
|
||||
/*
|
||||
** Control when GC is running:
|
||||
*/
|
||||
#define GCSTPUSR 1 /* bit true when GC stopped by user */
|
||||
#define GCSTPGC 2 /* bit true when GC stopped by itself */
|
||||
#define GCSTPCLS 4 /* bit true when closing Lua state */
|
||||
#define gcrunning(g) ((g)->gcstp == 0)
|
||||
|
||||
|
||||
/*
|
||||
** Does one step of collection when debt becomes positive. 'pre'/'pos'
|
||||
** allows some adjustments to be done only when needed. macro
|
||||
|
||||
@@ -64,6 +64,12 @@ static int l_checkmode (const char *mode) {
|
||||
#define l_popen(L,c,m) (_popen(c,m))
|
||||
#define l_pclose(L,file) (_pclose(file))
|
||||
|
||||
#if !defined(l_checkmodep)
|
||||
/* Windows accepts "[rw][bt]?" as valid modes */
|
||||
#define l_checkmodep(m) ((m[0] == 'r' || m[0] == 'w') && \
|
||||
(m[1] == '\0' || ((m[1] == 'b' || m[1] == 't') && m[2] == '\0')))
|
||||
#endif
|
||||
|
||||
#else /* }{ */
|
||||
|
||||
/* ISO C definitions */
|
||||
@@ -77,6 +83,12 @@ static int l_checkmode (const char *mode) {
|
||||
|
||||
#endif /* } */
|
||||
|
||||
|
||||
#if !defined(l_checkmodep)
|
||||
/* By default, Lua accepts only "r" or "w" as valid modes */
|
||||
#define l_checkmodep(m) ((m[0] == 'r' || m[0] == 'w') && m[1] == '\0')
|
||||
#endif
|
||||
|
||||
/* }====================================================== */
|
||||
|
||||
|
||||
@@ -153,7 +165,7 @@ static int io_type (lua_State *L) {
|
||||
luaL_checkany(L, 1);
|
||||
p = (LStream *)luaL_testudata(L, 1, LUA_FILEHANDLE);
|
||||
if (p == NULL)
|
||||
lua_pushnil(L); /* not a file */
|
||||
luaL_pushfail(L); /* not a file */
|
||||
else if (isclosed(p))
|
||||
lua_pushliteral(L, "closed file");
|
||||
else
|
||||
@@ -174,7 +186,7 @@ static int f_tostring (lua_State *L) {
|
||||
|
||||
static FILE *tofile (lua_State *L) {
|
||||
LStream *p = tolstream(L);
|
||||
if (isclosed(p))
|
||||
if (l_unlikely(isclosed(p)))
|
||||
luaL_error(L, "attempt to use a closed file");
|
||||
lua_assert(p->f);
|
||||
return p->f;
|
||||
@@ -215,7 +227,7 @@ static int f_close (lua_State *L) {
|
||||
|
||||
static int io_close (lua_State *L) {
|
||||
if (lua_isnone(L, 1)) /* no argument? */
|
||||
lua_getfield(L, LUA_REGISTRYINDEX, IO_OUTPUT); /* use standard output */
|
||||
lua_getfield(L, LUA_REGISTRYINDEX, IO_OUTPUT); /* use default output */
|
||||
return f_close(L);
|
||||
}
|
||||
|
||||
@@ -249,7 +261,7 @@ static LStream *newfile (lua_State *L) {
|
||||
static void opencheck (lua_State *L, const char *fname, const char *mode) {
|
||||
LStream *p = newfile(L);
|
||||
p->f = fopen(fname, mode);
|
||||
if (p->f == NULL)
|
||||
if (l_unlikely(p->f == NULL))
|
||||
luaL_error(L, "cannot open file '%s' (%s)", fname, strerror(errno));
|
||||
}
|
||||
|
||||
@@ -270,6 +282,7 @@ static int io_open (lua_State *L) {
|
||||
*/
|
||||
static int io_pclose (lua_State *L) {
|
||||
LStream *p = tolstream(L);
|
||||
errno = 0;
|
||||
return luaL_execresult(L, l_pclose(L, p->f));
|
||||
}
|
||||
|
||||
@@ -278,6 +291,7 @@ static int io_popen (lua_State *L) {
|
||||
const char *filename = luaL_checkstring(L, 1);
|
||||
const char *mode = luaL_optstring(L, 2, "r");
|
||||
LStream *p = newprefile(L);
|
||||
luaL_argcheck(L, l_checkmodep(mode), 2, "invalid mode");
|
||||
p->f = l_popen(L, filename, mode);
|
||||
p->closef = &io_pclose;
|
||||
return (p->f == NULL) ? luaL_fileresult(L, 0, filename) : 1;
|
||||
@@ -295,8 +309,8 @@ static FILE *getiofile (lua_State *L, const char *findex) {
|
||||
LStream *p;
|
||||
lua_getfield(L, LUA_REGISTRYINDEX, findex);
|
||||
p = (LStream *)lua_touserdata(L, -1);
|
||||
if (isclosed(p))
|
||||
luaL_error(L, "standard %s file is closed", findex + IOPREF_LEN);
|
||||
if (l_unlikely(isclosed(p)))
|
||||
luaL_error(L, "default %s file is closed", findex + IOPREF_LEN);
|
||||
return p->f;
|
||||
}
|
||||
|
||||
@@ -338,7 +352,7 @@ static int io_readline (lua_State *L);
|
||||
#define MAXARGLINE 250
|
||||
|
||||
/*
|
||||
** Auxiliar function to create the iteration function for 'lines'.
|
||||
** Auxiliary function to create the iteration function for 'lines'.
|
||||
** The iteration function is a closure over 'io_readline', with
|
||||
** the following upvalues:
|
||||
** 1) The file being read (first value in the stack)
|
||||
@@ -422,7 +436,7 @@ typedef struct {
|
||||
** Add current char to buffer (if not out of space) and read next one
|
||||
*/
|
||||
static int nextc (RN *rn) {
|
||||
if (rn->n >= L_MAXLENNUM) { /* buffer overflow? */
|
||||
if (l_unlikely(rn->n >= L_MAXLENNUM)) { /* buffer overflow? */
|
||||
rn->buff[0] = '\0'; /* invalidate result */
|
||||
return 0; /* fail */
|
||||
}
|
||||
@@ -485,8 +499,8 @@ static int read_number (lua_State *L, FILE *f) {
|
||||
ungetc(rn.c, rn.f); /* unread look-ahead char */
|
||||
l_unlockfile(rn.f);
|
||||
rn.buff[rn.n] = '\0'; /* finish string */
|
||||
if (lua_stringtonumber(L, rn.buff)) /* is this a valid number? */
|
||||
return 1; /* ok */
|
||||
if (l_likely(lua_stringtonumber(L, rn.buff)))
|
||||
return 1; /* ok, it is a valid number */
|
||||
else { /* invalid format */
|
||||
lua_pushnil(L); /* "result" to be removed */
|
||||
return 0; /* read fails */
|
||||
@@ -593,7 +607,7 @@ static int g_read (lua_State *L, FILE *f, int first) {
|
||||
return luaL_fileresult(L, 0, NULL);
|
||||
if (!success) {
|
||||
lua_pop(L, 1); /* remove last result */
|
||||
lua_pushnil(L); /* push nil instead */
|
||||
luaL_pushfail(L); /* push nil instead */
|
||||
}
|
||||
return n - first;
|
||||
}
|
||||
@@ -626,7 +640,7 @@ static int io_readline (lua_State *L) {
|
||||
lua_assert(n > 0); /* should return at least a nil */
|
||||
if (lua_toboolean(L, -n)) /* read at least one value? */
|
||||
return n; /* return them */
|
||||
else { /* first result is nil: EOF or error */
|
||||
else { /* first result is false: EOF or error */
|
||||
if (n > 1) { /* is there error information? */
|
||||
/* 2nd result is error message */
|
||||
return luaL_error(L, "%s", lua_tostring(L, -n + 1));
|
||||
@@ -662,7 +676,8 @@ static int g_write (lua_State *L, FILE *f, int arg) {
|
||||
status = status && (fwrite(s, sizeof(char), l, f) == l);
|
||||
}
|
||||
}
|
||||
if (status) return 1; /* file handle already on stack top */
|
||||
if (l_likely(status))
|
||||
return 1; /* file handle already on stack top */
|
||||
else return luaL_fileresult(L, status, NULL);
|
||||
}
|
||||
|
||||
@@ -689,7 +704,7 @@ static int f_seek (lua_State *L) {
|
||||
luaL_argcheck(L, (lua_Integer)offset == p3, 3,
|
||||
"not an integer in proper range");
|
||||
op = l_fseek(f, offset, mode[op]);
|
||||
if (op)
|
||||
if (l_unlikely(op))
|
||||
return luaL_fileresult(L, 0, NULL); /* error */
|
||||
else {
|
||||
lua_pushinteger(L, (lua_Integer)l_ftell(f));
|
||||
@@ -742,14 +757,23 @@ static const luaL_Reg iolib[] = {
|
||||
/*
|
||||
** methods for file handles
|
||||
*/
|
||||
static const luaL_Reg flib[] = {
|
||||
{"close", f_close},
|
||||
{"flush", f_flush},
|
||||
{"lines", f_lines},
|
||||
static const luaL_Reg meth[] = {
|
||||
{"read", f_read},
|
||||
{"seek", f_seek},
|
||||
{"setvbuf", f_setvbuf},
|
||||
{"write", f_write},
|
||||
{"lines", f_lines},
|
||||
{"flush", f_flush},
|
||||
{"seek", f_seek},
|
||||
{"close", f_close},
|
||||
{"setvbuf", f_setvbuf},
|
||||
{NULL, NULL}
|
||||
};
|
||||
|
||||
|
||||
/*
|
||||
** metamethods for file handles
|
||||
*/
|
||||
static const luaL_Reg metameth[] = {
|
||||
{"__index", NULL}, /* place holder */
|
||||
{"__gc", f_gc},
|
||||
{"__close", f_gc},
|
||||
{"__tostring", f_tostring},
|
||||
@@ -758,11 +782,12 @@ static const luaL_Reg flib[] = {
|
||||
|
||||
|
||||
static void createmeta (lua_State *L) {
|
||||
luaL_newmetatable(L, LUA_FILEHANDLE); /* create metatable for file handles */
|
||||
lua_pushvalue(L, -1); /* push metatable */
|
||||
lua_setfield(L, -2, "__index"); /* metatable.__index = metatable */
|
||||
luaL_setfuncs(L, flib, 0); /* add file methods to new metatable */
|
||||
lua_pop(L, 1); /* pop new metatable */
|
||||
luaL_newmetatable(L, LUA_FILEHANDLE); /* metatable for file handles */
|
||||
luaL_setfuncs(L, metameth, 0); /* add metamethods to new metatable */
|
||||
luaL_newlibtable(L, meth); /* create method table */
|
||||
luaL_setfuncs(L, meth, 0); /* add file methods to method table */
|
||||
lua_setfield(L, -2, "__index"); /* metatable.__index = method table */
|
||||
lua_pop(L, 1); /* pop metatable */
|
||||
}
|
||||
|
||||
|
||||
@@ -772,7 +797,7 @@ static void createmeta (lua_State *L) {
|
||||
static int io_noclose (lua_State *L) {
|
||||
LStream *p = tolstream(L);
|
||||
p->closef = &io_noclose; /* keep file opened */
|
||||
lua_pushnil(L);
|
||||
luaL_pushfail(L);
|
||||
lua_pushliteral(L, "cannot close standard file");
|
||||
return 2;
|
||||
}
|
||||
|
||||
+7
-8
@@ -16,7 +16,7 @@
|
||||
#define vmbreak vmfetch(); vmdispatch(GET_OPCODE(i));
|
||||
|
||||
|
||||
static void *disptab[NUM_OPCODES] = {
|
||||
static const void *const disptab[NUM_OPCODES] = {
|
||||
|
||||
#if 0
|
||||
** you can update the following list with this command:
|
||||
@@ -30,7 +30,9 @@ static void *disptab[NUM_OPCODES] = {
|
||||
&&L_OP_LOADF,
|
||||
&&L_OP_LOADK,
|
||||
&&L_OP_LOADKX,
|
||||
&&L_OP_LOADBOOL,
|
||||
&&L_OP_LOADFALSE,
|
||||
&&L_OP_LFALSESKIP,
|
||||
&&L_OP_LOADTRUE,
|
||||
&&L_OP_LOADNIL,
|
||||
&&L_OP_GETUPVAL,
|
||||
&&L_OP_SETUPVAL,
|
||||
@@ -45,12 +47,6 @@ static void *disptab[NUM_OPCODES] = {
|
||||
&&L_OP_NEWTABLE,
|
||||
&&L_OP_SELF,
|
||||
&&L_OP_ADDI,
|
||||
&&L_OP_SUBI,
|
||||
&&L_OP_MULI,
|
||||
&&L_OP_MODI,
|
||||
&&L_OP_POWI,
|
||||
&&L_OP_DIVI,
|
||||
&&L_OP_IDIVI,
|
||||
&&L_OP_ADDK,
|
||||
&&L_OP_SUBK,
|
||||
&&L_OP_MULK,
|
||||
@@ -75,6 +71,9 @@ static void *disptab[NUM_OPCODES] = {
|
||||
&&L_OP_BXOR,
|
||||
&&L_OP_SHL,
|
||||
&&L_OP_SHR,
|
||||
&&L_OP_MMBIN,
|
||||
&&L_OP_MMBINI,
|
||||
&&L_OP_MMBINK,
|
||||
&&L_OP_UNM,
|
||||
&&L_OP_BNOT,
|
||||
&&L_OP_NOT,
|
||||
|
||||
@@ -81,7 +81,6 @@ void luaX_init (lua_State *L) {
|
||||
|
||||
const char *luaX_token2str (LexState *ls, int token) {
|
||||
if (token < FIRST_RESERVED) { /* single-byte symbols? */
|
||||
lua_assert(token == cast_uchar(token));
|
||||
if (lisprint(token))
|
||||
return luaO_pushfstring(ls->L, "'%c'", token);
|
||||
else /* control character */
|
||||
@@ -123,26 +122,29 @@ l_noret luaX_syntaxerror (LexState *ls, const char *msg) {
|
||||
|
||||
|
||||
/*
|
||||
** creates a new string and anchors it in scanner's table so that
|
||||
** it will not be collected until the end of the compilation
|
||||
** (by that time it should be anchored somewhere)
|
||||
** Creates a new string and anchors it in scanner's table so that it
|
||||
** will not be collected until the end of the compilation; by that time
|
||||
** it should be anchored somewhere. It also internalizes long strings,
|
||||
** ensuring there is only one copy of each unique string. The table
|
||||
** here is used as a set: the string enters as the key, while its value
|
||||
** is irrelevant. We use the string itself as the value only because it
|
||||
** is a TValue readly available. Later, the code generation can change
|
||||
** this value.
|
||||
*/
|
||||
TString *luaX_newstring (LexState *ls, const char *str, size_t l) {
|
||||
lua_State *L = ls->L;
|
||||
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, s2v(L->top - 1));
|
||||
if (isempty(o)) { /* not in use yet? */
|
||||
/* boolean value does not need GC barrier;
|
||||
table is not a metatable, so it does not need to invalidate cache */
|
||||
setbvalue(o, 1); /* t[string] = true */
|
||||
const TValue *o = luaH_getstr(ls->h, ts);
|
||||
if (!ttisnil(o)) /* string already present? */
|
||||
ts = keystrval(nodefromval(o)); /* get saved copy */
|
||||
else { /* not in use yet */
|
||||
TValue *stv = s2v(L->top++); /* reserve stack space for string */
|
||||
setsvalue(L, stv, ts); /* temporarily anchor the string */
|
||||
luaH_finishset(L, ls->h, stv, o, stv); /* t[string] = string */
|
||||
/* table is not a metatable, so it does not need to invalidate cache */
|
||||
luaC_checkGC(L);
|
||||
L->top--; /* remove string from stack */
|
||||
}
|
||||
else { /* string already present */
|
||||
ts = keystrval(nodefromval(o)); /* re-use value previously stored */
|
||||
}
|
||||
L->top--; /* remove string from stack */
|
||||
return ts;
|
||||
}
|
||||
|
||||
@@ -211,8 +213,16 @@ static int check_next2 (LexState *ls, const char *set) {
|
||||
|
||||
/* LUA_NUMBER */
|
||||
/*
|
||||
** this function is quite liberal in what it accepts, as 'luaO_str2num'
|
||||
** will reject ill-formed numerals.
|
||||
** This function is quite liberal in what it accepts, as 'luaO_str2num'
|
||||
** will reject ill-formed numerals. Roughly, it accepts the following
|
||||
** pattern:
|
||||
**
|
||||
** %d(%x|%.|([Ee][+-]?))* | 0[Xx](%x|%.|([Pp][+-]?))*
|
||||
**
|
||||
** The only tricky part is to accept [+-] only after a valid exponent
|
||||
** mark, to avoid reading '3-4' or '0xe+1' as a single number.
|
||||
**
|
||||
** The caller might have already read an initial dot.
|
||||
*/
|
||||
static int read_numeral (LexState *ls, SemInfo *seminfo) {
|
||||
TValue obj;
|
||||
@@ -223,15 +233,13 @@ static int read_numeral (LexState *ls, SemInfo *seminfo) {
|
||||
if (first == '0' && check_next2(ls, "xX")) /* hexadecimal? */
|
||||
expo = "Pp";
|
||||
for (;;) {
|
||||
if (check_next2(ls, expo)) /* exponent part? */
|
||||
if (check_next2(ls, expo)) /* exponent mark? */
|
||||
check_next2(ls, "-+"); /* optional exponent sign */
|
||||
if (lisxdigit(ls->current))
|
||||
save_and_next(ls);
|
||||
else if (ls->current == '.')
|
||||
else if (lisxdigit(ls->current) || ls->current == '.') /* '%x|%.' */
|
||||
save_and_next(ls);
|
||||
else break;
|
||||
}
|
||||
if (lislalnum(ls->current)) /* is numeral touching an alpha num? */
|
||||
if (lislalpha(ls->current)) /* is numeral touching a letter? */
|
||||
save_and_next(ls); /* force an error */
|
||||
save(ls, '\0');
|
||||
if (luaO_str2num(luaZ_buffer(ls->buff), &obj) == 0) /* format error? */
|
||||
@@ -249,9 +257,10 @@ static int read_numeral (LexState *ls, SemInfo *seminfo) {
|
||||
|
||||
|
||||
/*
|
||||
** reads a sequence '[=*[' or ']=*]', leaving the last bracket.
|
||||
** If sequence is well formed, return its number of '='s + 2; otherwise,
|
||||
** return 1 if there is no '='s or 0 otherwise (an unfinished '[==...').
|
||||
** read a sequence '[=*[' or ']=*]', leaving the last bracket. If
|
||||
** sequence is well formed, return its number of '='s + 2; otherwise,
|
||||
** return 1 if it is a single bracket (no '='s and no 2nd bracket);
|
||||
** otherwise (an unfinished '[==...') return 0.
|
||||
*/
|
||||
static size_t skip_sep (LexState *ls) {
|
||||
size_t count = 0;
|
||||
@@ -476,34 +485,34 @@ static int llex (LexState *ls, SemInfo *seminfo) {
|
||||
}
|
||||
case '=': {
|
||||
next(ls);
|
||||
if (check_next1(ls, '=')) return TK_EQ;
|
||||
if (check_next1(ls, '=')) return TK_EQ; /* '==' */
|
||||
else return '=';
|
||||
}
|
||||
case '<': {
|
||||
next(ls);
|
||||
if (check_next1(ls, '=')) return TK_LE;
|
||||
else if (check_next1(ls, '<')) return TK_SHL;
|
||||
if (check_next1(ls, '=')) return TK_LE; /* '<=' */
|
||||
else if (check_next1(ls, '<')) return TK_SHL; /* '<<' */
|
||||
else return '<';
|
||||
}
|
||||
case '>': {
|
||||
next(ls);
|
||||
if (check_next1(ls, '=')) return TK_GE;
|
||||
else if (check_next1(ls, '>')) return TK_SHR;
|
||||
if (check_next1(ls, '=')) return TK_GE; /* '>=' */
|
||||
else if (check_next1(ls, '>')) return TK_SHR; /* '>>' */
|
||||
else return '>';
|
||||
}
|
||||
case '/': {
|
||||
next(ls);
|
||||
if (check_next1(ls, '/')) return TK_IDIV;
|
||||
if (check_next1(ls, '/')) return TK_IDIV; /* '//' */
|
||||
else return '/';
|
||||
}
|
||||
case '~': {
|
||||
next(ls);
|
||||
if (check_next1(ls, '=')) return TK_NE;
|
||||
if (check_next1(ls, '=')) return TK_NE; /* '~=' */
|
||||
else return '~';
|
||||
}
|
||||
case ':': {
|
||||
next(ls);
|
||||
if (check_next1(ls, ':')) return TK_DBCOLON;
|
||||
if (check_next1(ls, ':')) return TK_DBCOLON; /* '::' */
|
||||
else return ':';
|
||||
}
|
||||
case '"': case '\'': { /* short literal strings */
|
||||
@@ -542,7 +551,7 @@ static int llex (LexState *ls, SemInfo *seminfo) {
|
||||
return TK_NAME;
|
||||
}
|
||||
}
|
||||
else { /* single-char tokens (+ - / ...) */
|
||||
else { /* single-char tokens ('+', '*', '%', '{', '}', ...) */
|
||||
int c = ls->current;
|
||||
next(ls);
|
||||
return c;
|
||||
|
||||
@@ -7,11 +7,17 @@
|
||||
#ifndef llex_h
|
||||
#define llex_h
|
||||
|
||||
#include <limits.h>
|
||||
|
||||
#include "lobject.h"
|
||||
#include "lzio.h"
|
||||
|
||||
|
||||
#define FIRST_RESERVED 257
|
||||
/*
|
||||
** Single-char tokens (terminal symbols) are represented by their own
|
||||
** numeric code. Other tokens start at the following value.
|
||||
*/
|
||||
#define FIRST_RESERVED (UCHAR_MAX + 1)
|
||||
|
||||
|
||||
#if !defined(LUA_ENV)
|
||||
|
||||
@@ -84,7 +84,15 @@ typedef LUAI_UACNUMBER l_uacNumber;
|
||||
typedef LUAI_UACINT l_uacInt;
|
||||
|
||||
|
||||
/* internal assertions for in-house debugging */
|
||||
/*
|
||||
** Internal assertions for in-house debugging
|
||||
*/
|
||||
#if defined LUAI_ASSERT
|
||||
#undef NDEBUG
|
||||
#include <assert.h>
|
||||
#define lua_assert(c) assert(c)
|
||||
#endif
|
||||
|
||||
#if defined(lua_assert)
|
||||
#define check_exp(c,e) (lua_assert(c), (e))
|
||||
/* to avoid problems with conditions too long */
|
||||
@@ -99,7 +107,7 @@ typedef LUAI_UACINT l_uacInt;
|
||||
** assertion for checking API calls
|
||||
*/
|
||||
#if !defined(luai_apicheck)
|
||||
#define luai_apicheck(l,e) lua_assert(e)
|
||||
#define luai_apicheck(l,e) ((void)l, lua_assert(e))
|
||||
#endif
|
||||
|
||||
#define api_check(l,e,msg) luai_apicheck(l,(e) && msg)
|
||||
@@ -141,22 +149,6 @@ typedef LUAI_UACINT l_uacInt;
|
||||
#endif
|
||||
|
||||
|
||||
/*
|
||||
** macros to improve jump prediction (used mainly for error handling)
|
||||
*/
|
||||
#if !defined(likely)
|
||||
|
||||
#if defined(__GNUC__)
|
||||
#define likely(x) (__builtin_expect(((x) != 0), 1))
|
||||
#define unlikely(x) (__builtin_expect(((x) != 0), 0))
|
||||
#else
|
||||
#define likely(x) (x)
|
||||
#define unlikely(x) (x)
|
||||
#endif
|
||||
|
||||
#endif
|
||||
|
||||
|
||||
/*
|
||||
** non-return type
|
||||
*/
|
||||
@@ -173,6 +165,20 @@ typedef LUAI_UACINT l_uacInt;
|
||||
#endif
|
||||
|
||||
|
||||
/*
|
||||
** Inline functions
|
||||
*/
|
||||
#if !defined(LUA_USE_C89)
|
||||
#define l_inline inline
|
||||
#elif defined(__GNUC__)
|
||||
#define l_inline __inline__
|
||||
#else
|
||||
#define l_inline /* empty */
|
||||
#endif
|
||||
|
||||
#define l_sinline static l_inline
|
||||
|
||||
|
||||
/*
|
||||
** type for virtual-machine instructions;
|
||||
** must be an unsigned with (at least) 4 bytes (see details in lopcodes.h)
|
||||
@@ -226,6 +232,17 @@ typedef l_uint32 Instruction;
|
||||
#endif
|
||||
|
||||
|
||||
/*
|
||||
** Maximum depth for nested C calls, syntactical nested non-terminals,
|
||||
** and other features implemented through recursion in C. (Value must
|
||||
** fit in a 16-bit unsigned integer. It must also be compatible with
|
||||
** the size of the C stack.)
|
||||
*/
|
||||
#if !defined(LUAI_MAXCCALLS)
|
||||
#define LUAI_MAXCCALLS 200
|
||||
#endif
|
||||
|
||||
|
||||
/*
|
||||
** macros that are executed whenever program enters the Lua core
|
||||
** ('lua_lock') and leaves the core ('lua_unlock')
|
||||
@@ -307,7 +324,8 @@ typedef l_uint32 Instruction;
|
||||
|
||||
/* exponentiation */
|
||||
#if !defined(luai_numpow)
|
||||
#define luai_numpow(L,a,b) ((void)L, l_mathop(pow)(a,b))
|
||||
#define luai_numpow(L,a,b) \
|
||||
((void)L, (b == 2) ? (a)*(a) : l_mathop(pow)(a,b))
|
||||
#endif
|
||||
|
||||
/* the others are quite standard operations */
|
||||
@@ -336,14 +354,14 @@ typedef l_uint32 Instruction;
|
||||
#else
|
||||
/* realloc stack keeping its size */
|
||||
#define condmovestack(L,pre,pos) \
|
||||
{ int sz_ = (L)->stacksize; pre; luaD_reallocstack((L), sz_, 0); pos; }
|
||||
{ int sz_ = stacksize(L); pre; luaD_reallocstack((L), sz_, 0); pos; }
|
||||
#endif
|
||||
|
||||
#if !defined(HARDMEMTESTS)
|
||||
#define condchangemem(L,pre,pos) ((void)0)
|
||||
#else
|
||||
#define condchangemem(L,pre,pos) \
|
||||
{ if (G(L)->gcrunning) { pre; luaC_fullgc(L, 0); pos; } }
|
||||
{ if (gcrunning(G(L))) { pre; luaC_fullgc(L, 0); pos; } }
|
||||
#endif
|
||||
|
||||
#endif
|
||||
|
||||
+34
-26
@@ -73,11 +73,11 @@ static int math_atan (lua_State *L) {
|
||||
static int math_toint (lua_State *L) {
|
||||
int valid;
|
||||
lua_Integer n = lua_tointegerx(L, 1, &valid);
|
||||
if (valid)
|
||||
if (l_likely(valid))
|
||||
lua_pushinteger(L, n);
|
||||
else {
|
||||
luaL_checkany(L, 1);
|
||||
lua_pushnil(L); /* value is not convertible to integer */
|
||||
luaL_pushfail(L); /* value is not convertible to integer */
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
@@ -175,7 +175,8 @@ static int math_log (lua_State *L) {
|
||||
lua_Number base = luaL_checknumber(L, 2);
|
||||
#if !defined(LUA_USE_C89)
|
||||
if (base == l_mathop(2.0))
|
||||
res = l_mathop(log2)(x); else
|
||||
res = l_mathop(log2)(x);
|
||||
else
|
||||
#endif
|
||||
if (base == l_mathop(10.0))
|
||||
res = l_mathop(log10)(x);
|
||||
@@ -235,7 +236,7 @@ static int math_type (lua_State *L) {
|
||||
lua_pushstring(L, (lua_isinteger(L, 1)) ? "integer" : "float");
|
||||
else {
|
||||
luaL_checkany(L, 1);
|
||||
lua_pushnil(L);
|
||||
luaL_pushfail(L);
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
@@ -249,7 +250,7 @@ static int math_type (lua_State *L) {
|
||||
*/
|
||||
|
||||
/* number of binary digits in the mantissa of a float */
|
||||
#define FIGS l_mathlim(MANT_DIG)
|
||||
#define FIGS l_floatatt(MANT_DIG)
|
||||
|
||||
#if FIGS > 64
|
||||
/* there are only 64 random bits; use them all */
|
||||
@@ -328,7 +329,7 @@ static Rand64 nextrand (Rand64 *state) {
|
||||
*/
|
||||
|
||||
/* must throw out the extra (64 - FIGS) bits */
|
||||
#define shift64_FIG (64 - FIGS)
|
||||
#define shift64_FIG (64 - FIGS)
|
||||
|
||||
/* to scale to [0, 1), multiply by scaleFIG = 2^(-FIGS) */
|
||||
#define scaleFIG (l_mathop(0.5) / ((Rand64)1 << (FIGS - 1)))
|
||||
@@ -474,7 +475,7 @@ static lua_Number I2d (Rand64 x) {
|
||||
|
||||
/* 2^(-FIGS) = 1.0 / 2^30 / 2^3 / 2^(FIGS-33) */
|
||||
#define scaleFIG \
|
||||
((lua_Number)1.0 / (UONE << 30) / 8.0 / (UONE << (FIGS - 33)))
|
||||
(l_mathop(1.0) / (UONE << 30) / l_mathop(8.0) / (UONE << (FIGS - 33)))
|
||||
|
||||
/*
|
||||
** use FIGS - 32 bits from lower half, throwing out the other
|
||||
@@ -485,7 +486,7 @@ static lua_Number I2d (Rand64 x) {
|
||||
/*
|
||||
** higher 32 bits go after those (FIGS - 32) bits: shiftHI = 2^(FIGS - 32)
|
||||
*/
|
||||
#define shiftHI ((lua_Number)(UONE << (FIGS - 33)) * 2.0)
|
||||
#define shiftHI ((lua_Number)(UONE << (FIGS - 33)) * l_mathop(2.0))
|
||||
|
||||
|
||||
static lua_Number I2d (Rand64 x) {
|
||||
@@ -522,16 +523,18 @@ typedef struct {
|
||||
** Project the random integer 'ran' into the interval [0, n].
|
||||
** Because 'ran' has 2^B possible values, the projection can only be
|
||||
** uniform when the size of the interval is a power of 2 (exact
|
||||
** division). To get a uniform projection into [0, n], we first compute
|
||||
** 'lim', the smallest Mersenne number not smaller than 'n'. We then
|
||||
** project 'ran' into the interval [0, lim]. If the result is inside
|
||||
** [0, n], we are done. Otherwise, we try with another 'ran', until we
|
||||
** have a result inside the interval.
|
||||
** division). Otherwise, to get a uniform projection into [0, n], we
|
||||
** first compute 'lim', the smallest Mersenne number not smaller than
|
||||
** 'n'. We then project 'ran' into the interval [0, lim]. If the result
|
||||
** is inside [0, n], we are done. Otherwise, we try with another 'ran',
|
||||
** until we have a result inside the interval.
|
||||
*/
|
||||
static lua_Unsigned project (lua_Unsigned ran, lua_Unsigned n,
|
||||
RanState *state) {
|
||||
lua_Unsigned lim = n;
|
||||
if ((lim & (lim + 1)) > 0) { /* 'lim + 1' is not a power of 2? */
|
||||
if ((n & (n + 1)) == 0) /* is 'n + 1' a power of 2? */
|
||||
return ran & n; /* no bias */
|
||||
else {
|
||||
lua_Unsigned lim = n;
|
||||
/* compute the smallest (2^b - 1) not smaller than 'n' */
|
||||
lim |= (lim >> 1);
|
||||
lim |= (lim >> 2);
|
||||
@@ -541,13 +544,13 @@ static lua_Unsigned project (lua_Unsigned ran, lua_Unsigned n,
|
||||
#if (LUA_MAXUNSIGNED >> 31) >= 3
|
||||
lim |= (lim >> 32); /* integer type has more than 32 bits */
|
||||
#endif
|
||||
lua_assert((lim & (lim + 1)) == 0 /* 'lim + 1' is a power of 2, */
|
||||
&& lim >= n /* not smaller than 'n', */
|
||||
&& (lim >> 1) < n); /* and it is the smallest one */
|
||||
while ((ran &= lim) > n) /* project 'ran' into [0..lim] */
|
||||
ran = I2UInt(nextrand(state->s)); /* not inside [0..n]? try again */
|
||||
return ran;
|
||||
}
|
||||
lua_assert((lim & (lim + 1)) == 0 /* 'lim + 1' is a power of 2, */
|
||||
&& lim >= n /* not smaller than 'n', */
|
||||
&& (lim == 0 || (lim >> 1) < n)); /* and it is the smallest one */
|
||||
while ((ran &= lim) > n) /* project 'ran' into [0..lim] */
|
||||
ran = I2UInt(nextrand(state->s)); /* not inside [0..n]? try again */
|
||||
return ran;
|
||||
}
|
||||
|
||||
|
||||
@@ -586,7 +589,8 @@ static int math_random (lua_State *L) {
|
||||
}
|
||||
|
||||
|
||||
static void setseed (Rand64 *state, lua_Unsigned n1, lua_Unsigned n2) {
|
||||
static void setseed (lua_State *L, Rand64 *state,
|
||||
lua_Unsigned n1, lua_Unsigned n2) {
|
||||
int i;
|
||||
state[0] = Int2I(n1);
|
||||
state[1] = Int2I(0xff); /* avoid a zero state */
|
||||
@@ -594,6 +598,8 @@ static void setseed (Rand64 *state, lua_Unsigned n1, lua_Unsigned n2) {
|
||||
state[3] = Int2I(0);
|
||||
for (i = 0; i < 16; i++)
|
||||
nextrand(state); /* discard initial values to "spread" seed */
|
||||
lua_pushinteger(L, n1);
|
||||
lua_pushinteger(L, n2);
|
||||
}
|
||||
|
||||
|
||||
@@ -605,20 +611,21 @@ static void setseed (Rand64 *state, lua_Unsigned n1, lua_Unsigned n2) {
|
||||
static void randseed (lua_State *L, RanState *state) {
|
||||
lua_Unsigned seed1 = (lua_Unsigned)time(NULL);
|
||||
lua_Unsigned seed2 = (lua_Unsigned)(size_t)L;
|
||||
setseed(state->s, seed1, seed2);
|
||||
setseed(L, state->s, seed1, seed2);
|
||||
}
|
||||
|
||||
|
||||
static int math_randomseed (lua_State *L) {
|
||||
RanState *state = (RanState *)lua_touserdata(L, lua_upvalueindex(1));
|
||||
if (lua_isnone(L, 1))
|
||||
if (lua_isnone(L, 1)) {
|
||||
randseed(L, state);
|
||||
}
|
||||
else {
|
||||
lua_Integer n1 = luaL_checkinteger(L, 1);
|
||||
lua_Integer n2 = luaL_optinteger(L, 2, 0);
|
||||
setseed(state->s, n1, n2);
|
||||
setseed(L, state->s, n1, n2);
|
||||
}
|
||||
return 0;
|
||||
return 2; /* return seeds */
|
||||
}
|
||||
|
||||
|
||||
@@ -635,6 +642,7 @@ static const luaL_Reg randfuncs[] = {
|
||||
static void setrandfunc (lua_State *L) {
|
||||
RanState *state = (RanState *)lua_newuserdatauv(L, sizeof(RanState), 0);
|
||||
randseed(L, state); /* initialize with a "random" seed */
|
||||
lua_pop(L, 2); /* remove pushed seeds */
|
||||
luaL_setfuncs(L, randfuncs, 1);
|
||||
}
|
||||
|
||||
|
||||
@@ -22,34 +22,57 @@
|
||||
#include "lstate.h"
|
||||
|
||||
|
||||
#if defined(HARDMEMTESTS)
|
||||
#define hardtest(L,os,s) /* force a GC whenever possible */ \
|
||||
if ((s) > (os) && (G(L))->gcrunning) luaC_fullgc(L, 1);
|
||||
#if defined(EMERGENCYGCTESTS)
|
||||
/*
|
||||
** First allocation will fail whenever not building initial state.
|
||||
** (This fail will trigger 'tryagain' and a full GC cycle at every
|
||||
** allocation.)
|
||||
*/
|
||||
static void *firsttry (global_State *g, void *block, size_t os, size_t ns) {
|
||||
if (completestate(g) && ns > 0) /* frees never fail */
|
||||
return NULL; /* fail */
|
||||
else /* normal allocation */
|
||||
return (*g->frealloc)(g->ud, block, os, ns);
|
||||
}
|
||||
#else
|
||||
#define hardtest(L,os,s) ((void)0)
|
||||
#define firsttry(g,block,os,ns) ((*g->frealloc)(g->ud, block, os, ns))
|
||||
#endif
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
/*
|
||||
** About the realloc function:
|
||||
** void * frealloc (void *ud, void *ptr, size_t osize, size_t nsize);
|
||||
** void *frealloc (void *ud, void *ptr, size_t osize, size_t nsize);
|
||||
** ('osize' is the old size, 'nsize' is the new size)
|
||||
**
|
||||
** * frealloc(ud, NULL, x, s) creates a new block of size 's' (no
|
||||
** matter 'x').
|
||||
** - frealloc(ud, p, x, 0) frees the block 'p' and returns NULL.
|
||||
** Particularly, frealloc(ud, NULL, 0, 0) does nothing,
|
||||
** which is equivalent to free(NULL) in ISO C.
|
||||
**
|
||||
** * 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 ISO C)
|
||||
** - frealloc(ud, NULL, x, s) creates a new block of size 's'
|
||||
** (no matter 'x'). Returns NULL if it cannot create the new block.
|
||||
**
|
||||
** frealloc returns NULL if it cannot create or reallocate the area
|
||||
** (any reallocation to an equal or smaller size cannot fail!)
|
||||
** - otherwise, frealloc(ud, b, x, y) reallocates the block 'b' from
|
||||
** size 'x' to size 'y'. Returns NULL if it cannot reallocate the
|
||||
** block to the new size.
|
||||
*/
|
||||
|
||||
|
||||
|
||||
|
||||
/*
|
||||
** {==================================================================
|
||||
** Functions to allocate/deallocate arrays for the Parser
|
||||
** ===================================================================
|
||||
*/
|
||||
|
||||
/*
|
||||
** Minimum size for arrays during parsing, to avoid overhead of
|
||||
** reallocating to size 1, then 2, and then 4. All these arrays
|
||||
** will be reallocated to exact sizes or erased when parsing ends.
|
||||
*/
|
||||
#define MINSIZEARRAY 4
|
||||
|
||||
|
||||
@@ -60,7 +83,7 @@ void *luaM_growaux_ (lua_State *L, void *block, int nelems, int *psize,
|
||||
if (nelems + 1 <= size) /* does one extra element still fit? */
|
||||
return block; /* nothing to be done */
|
||||
if (size >= limit / 2) { /* cannot double it? */
|
||||
if (unlikely(size >= limit)) /* cannot grow even a little? */
|
||||
if (l_unlikely(size >= limit)) /* cannot grow even a little? */
|
||||
luaG_runerror(L, "too many %s (limit is %d)", what, limit);
|
||||
size = limit; /* still have at least one free place */
|
||||
}
|
||||
@@ -71,32 +94,32 @@ void *luaM_growaux_ (lua_State *L, void *block, int nelems, int *psize,
|
||||
}
|
||||
lua_assert(nelems + 1 <= size && size <= limit);
|
||||
/* 'limit' ensures that multiplication will not overflow */
|
||||
newblock = luaM_realloc_(L, block, cast_sizet(*psize) * size_elems,
|
||||
cast_sizet(size) * size_elems);
|
||||
if (unlikely(newblock == NULL))
|
||||
luaM_error(L);
|
||||
newblock = luaM_saferealloc_(L, block, cast_sizet(*psize) * size_elems,
|
||||
cast_sizet(size) * size_elems);
|
||||
*psize = size; /* update only when everything else is OK */
|
||||
return newblock;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** In prototypes, the size of the array is also its number of
|
||||
** elements (to save memory). So, if it cannot shrink an array
|
||||
** to its number of elements, the only option is to raise an
|
||||
** error.
|
||||
*/
|
||||
void *luaM_shrinkvector_ (lua_State *L, void *block, int *size,
|
||||
int final_n, int size_elem) {
|
||||
global_State *g = G(L);
|
||||
void *newblock;
|
||||
size_t oldsize = cast_sizet((*size) * size_elem);
|
||||
size_t newsize = cast_sizet(final_n * size_elem);
|
||||
lua_assert(newsize <= oldsize);
|
||||
newblock = (*g->frealloc)(g->ud, block, oldsize, newsize);
|
||||
if (unlikely(newblock == NULL && final_n > 0)) /* allocation failed? */
|
||||
luaM_error(L);
|
||||
else {
|
||||
g->GCdebt += newsize - oldsize;
|
||||
*size = final_n;
|
||||
return newblock;
|
||||
}
|
||||
newblock = luaM_saferealloc_(L, block, oldsize, newsize);
|
||||
*size = final_n;
|
||||
return newblock;
|
||||
}
|
||||
|
||||
/* }================================================================== */
|
||||
|
||||
|
||||
l_noret luaM_toobig (lua_State *L) {
|
||||
luaG_runerror(L, "memory allocation error: block too big");
|
||||
@@ -115,15 +138,17 @@ void luaM_free_ (lua_State *L, void *block, size_t osize) {
|
||||
|
||||
|
||||
/*
|
||||
** In case of allocation fail, this function will call the GC to try
|
||||
** to free some memory and then try the allocation again.
|
||||
** (It should not be called when shrinking a block, because then the
|
||||
** interpreter may be in the middle of a collection step.)
|
||||
** In case of allocation fail, this function will do an emergency
|
||||
** collection to free some memory and then try the allocation again.
|
||||
** The GC should not be called while state is not fully built, as the
|
||||
** collector is not yet fully initialized. Also, it should not be called
|
||||
** when 'gcstopem' is true, because then the interpreter is in the
|
||||
** middle of a collection step.
|
||||
*/
|
||||
static void *tryagain (lua_State *L, void *block,
|
||||
size_t osize, size_t nsize) {
|
||||
global_State *g = G(L);
|
||||
if (ttisnil(&g->nilvalue)) { /* is state fully build? */
|
||||
if (completestate(g) && !g->gcstopem) {
|
||||
luaC_fullgc(L, 1); /* try to free some memory... */
|
||||
return (*g->frealloc)(g->ud, block, osize, nsize); /* try again */
|
||||
}
|
||||
@@ -132,19 +157,17 @@ static void *tryagain (lua_State *L, void *block,
|
||||
|
||||
|
||||
/*
|
||||
** generic allocation routine.
|
||||
** Generic allocation routine.
|
||||
*/
|
||||
void *luaM_realloc_ (lua_State *L, void *block, size_t osize, size_t nsize) {
|
||||
void *newblock;
|
||||
global_State *g = G(L);
|
||||
lua_assert((osize == 0) == (block == NULL));
|
||||
hardtest(L, osize, nsize);
|
||||
newblock = (*g->frealloc)(g->ud, block, osize, nsize);
|
||||
if (unlikely(newblock == NULL && nsize > 0)) {
|
||||
if (nsize > osize) /* not shrinking a block? */
|
||||
newblock = tryagain(L, block, osize, nsize);
|
||||
newblock = firsttry(g, block, osize, nsize);
|
||||
if (l_unlikely(newblock == NULL && nsize > 0)) {
|
||||
newblock = tryagain(L, block, osize, nsize);
|
||||
if (newblock == NULL) /* still no memory? */
|
||||
return NULL;
|
||||
return NULL; /* do not update 'GCdebt' */
|
||||
}
|
||||
lua_assert((nsize == 0) == (newblock == NULL));
|
||||
g->GCdebt = (g->GCdebt + nsize) - osize;
|
||||
@@ -155,20 +178,19 @@ void *luaM_realloc_ (lua_State *L, void *block, size_t osize, size_t nsize) {
|
||||
void *luaM_saferealloc_ (lua_State *L, void *block, size_t osize,
|
||||
size_t nsize) {
|
||||
void *newblock = luaM_realloc_(L, block, osize, nsize);
|
||||
if (unlikely(newblock == NULL && nsize > 0)) /* allocation failed? */
|
||||
if (l_unlikely(newblock == NULL && nsize > 0)) /* allocation failed? */
|
||||
luaM_error(L);
|
||||
return newblock;
|
||||
}
|
||||
|
||||
|
||||
void *luaM_malloc_ (lua_State *L, size_t size, int tag) {
|
||||
hardtest(L, 0, size);
|
||||
if (size == 0)
|
||||
return NULL; /* that's all */
|
||||
else {
|
||||
global_State *g = G(L);
|
||||
void *newblock = (*g->frealloc)(g->ud, NULL, tag, size);
|
||||
if (unlikely(newblock == NULL)) {
|
||||
void *newblock = firsttry(g, NULL, tag, size);
|
||||
if (l_unlikely(newblock == NULL)) {
|
||||
newblock = tryagain(L, NULL, tag, size);
|
||||
if (newblock == NULL)
|
||||
luaM_error(L);
|
||||
|
||||
@@ -56,10 +56,10 @@
|
||||
|
||||
|
||||
/*
|
||||
** unique key for table in the registry that keeps handles
|
||||
** key for table in the registry that keeps handles
|
||||
** for all loaded C libraries
|
||||
*/
|
||||
static const int CLIBS = 0;
|
||||
static const char *const CLIBS = "_CLIBS";
|
||||
|
||||
#define LIB_FAIL "open"
|
||||
|
||||
@@ -67,6 +67,13 @@ static const int CLIBS = 0;
|
||||
#define setprogdir(L) ((void)0)
|
||||
|
||||
|
||||
/*
|
||||
** Special type equivalent to '(void*)' for functions in gcc
|
||||
** (to suppress warnings when converting function pointers)
|
||||
*/
|
||||
typedef void (*voidf)(void);
|
||||
|
||||
|
||||
/*
|
||||
** system-dependent functions
|
||||
*/
|
||||
@@ -125,14 +132,16 @@ static void lsys_unloadlib (void *lib) {
|
||||
|
||||
static void *lsys_load (lua_State *L, const char *path, int seeglb) {
|
||||
void *lib = dlopen(path, RTLD_NOW | (seeglb ? RTLD_GLOBAL : RTLD_LOCAL));
|
||||
if (lib == NULL) lua_pushstring(L, dlerror());
|
||||
if (l_unlikely(lib == NULL))
|
||||
lua_pushstring(L, dlerror());
|
||||
return lib;
|
||||
}
|
||||
|
||||
|
||||
static lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym) {
|
||||
lua_CFunction f = cast_func(dlsym(lib, sym));
|
||||
if (f == NULL) lua_pushstring(L, dlerror());
|
||||
if (l_unlikely(f == NULL))
|
||||
lua_pushstring(L, dlerror());
|
||||
return f;
|
||||
}
|
||||
|
||||
@@ -206,7 +215,7 @@ static void *lsys_load (lua_State *L, const char *path, int seeglb) {
|
||||
|
||||
|
||||
static lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym) {
|
||||
lua_CFunction f = (lua_CFunction)GetProcAddress((HMODULE)lib, sym);
|
||||
lua_CFunction f = (lua_CFunction)(voidf)GetProcAddress((HMODULE)lib, sym);
|
||||
if (f == NULL) pusherror(L);
|
||||
return f;
|
||||
}
|
||||
@@ -269,8 +278,6 @@ static lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym) {
|
||||
#endif
|
||||
|
||||
|
||||
#define AUXMARK "\1" /* auxiliary mark */
|
||||
|
||||
|
||||
/*
|
||||
** return registry.LUA_NOENV as a boolean
|
||||
@@ -308,7 +315,7 @@ static void setpath (lua_State *L, const char *fieldname,
|
||||
luaL_addchar(&b, *LUA_PATH_SEP);
|
||||
}
|
||||
luaL_addstring(&b, dft); /* add default */
|
||||
if (dftmark < path + len - 2) { /* is there a sufix after ';;'? */
|
||||
if (dftmark < path + len - 2) { /* is there a suffix after ';;'? */
|
||||
luaL_addchar(&b, *LUA_PATH_SEP);
|
||||
luaL_addlstring(&b, dftmark + 2, (path + len - 2) - dftmark);
|
||||
}
|
||||
@@ -327,7 +334,7 @@ static void setpath (lua_State *L, const char *fieldname,
|
||||
*/
|
||||
static void *checkclib (lua_State *L, const char *path) {
|
||||
void *plib;
|
||||
lua_rawgetp(L, LUA_REGISTRYINDEX, &CLIBS);
|
||||
lua_getfield(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' */
|
||||
@@ -340,7 +347,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_rawgetp(L, LUA_REGISTRYINDEX, &CLIBS);
|
||||
lua_getfield(L, LUA_REGISTRYINDEX, CLIBS);
|
||||
lua_pushlightuserdata(L, plib);
|
||||
lua_pushvalue(L, -1);
|
||||
lua_setfield(L, -3, path); /* CLIBS[path] = plib */
|
||||
@@ -405,13 +412,13 @@ static int ll_loadlib (lua_State *L) {
|
||||
const char *path = luaL_checkstring(L, 1);
|
||||
const char *init = luaL_checkstring(L, 2);
|
||||
int stat = lookforfunc(L, path, init);
|
||||
if (stat == 0) /* no errors? */
|
||||
if (l_likely(stat == 0)) /* no errors? */
|
||||
return 1; /* return the loaded function */
|
||||
else { /* error; error message is on stack top */
|
||||
lua_pushnil(L);
|
||||
luaL_pushfail(L);
|
||||
lua_insert(L, -2);
|
||||
lua_pushstring(L, (stat == ERRLIB) ? LIB_FAIL : "init");
|
||||
return 3; /* return nil, error message, and where */
|
||||
return 3; /* return fail, error message, and where */
|
||||
}
|
||||
}
|
||||
|
||||
@@ -458,13 +465,13 @@ static const char *getnextfilename (char **path, char *end) {
|
||||
/*
|
||||
** Given a path such as ";blabla.so;blublu.so", pushes the string
|
||||
**
|
||||
** no file 'blabla.so'
|
||||
** no file 'blabla.so'
|
||||
** no file 'blublu.so'
|
||||
*/
|
||||
static void pusherrornotfound (lua_State *L, const char *path) {
|
||||
luaL_Buffer b;
|
||||
luaL_buffinit(L, &b);
|
||||
luaL_addstring(&b, "\n\tno file '");
|
||||
luaL_addstring(&b, "no file '");
|
||||
luaL_addgsub(&b, path, LUA_PATH_SEP, "'\n\tno file '");
|
||||
luaL_addstring(&b, "'");
|
||||
luaL_pushresult(&b);
|
||||
@@ -505,9 +512,9 @@ static int ll_searchpath (lua_State *L) {
|
||||
luaL_optstring(L, 4, LUA_DIRSEP));
|
||||
if (f != NULL) return 1;
|
||||
else { /* error message is on top of the stack */
|
||||
lua_pushnil(L);
|
||||
luaL_pushfail(L);
|
||||
lua_insert(L, -2);
|
||||
return 2; /* return nil + error message */
|
||||
return 2; /* return fail + error message */
|
||||
}
|
||||
}
|
||||
|
||||
@@ -518,14 +525,14 @@ static const char *findfile (lua_State *L, const char *name,
|
||||
const char *path;
|
||||
lua_getfield(L, lua_upvalueindex(1), pname);
|
||||
path = lua_tostring(L, -1);
|
||||
if (path == NULL)
|
||||
if (l_unlikely(path == NULL))
|
||||
luaL_error(L, "'package.%s' must be a string", pname);
|
||||
return searchpath(L, name, path, ".", dirsep);
|
||||
}
|
||||
|
||||
|
||||
static int checkload (lua_State *L, int stat, const char *filename) {
|
||||
if (stat) { /* module loaded successfully? */
|
||||
if (l_likely(stat)) { /* module loaded successfully? */
|
||||
lua_pushstring(L, filename); /* will be 2nd argument to module */
|
||||
return 2; /* return open function and file name */
|
||||
}
|
||||
@@ -591,7 +598,7 @@ static int searcher_Croot (lua_State *L) {
|
||||
if (stat != ERRFUNC)
|
||||
return checkload(L, 0, filename); /* real error */
|
||||
else { /* open function not found */
|
||||
lua_pushfstring(L, "\n\tno module '%s' in file '%s'", name, filename);
|
||||
lua_pushfstring(L, "no module '%s' in file '%s'", name, filename);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
@@ -604,7 +611,7 @@ static int searcher_preload (lua_State *L) {
|
||||
const char *name = luaL_checkstring(L, 1);
|
||||
lua_getfield(L, LUA_REGISTRYINDEX, LUA_PRELOAD_TABLE);
|
||||
if (lua_getfield(L, -1, name) == LUA_TNIL) { /* not found? */
|
||||
lua_pushfstring(L, "\n\tno field package.preload['%s']", name);
|
||||
lua_pushfstring(L, "no field package.preload['%s']", name);
|
||||
return 1;
|
||||
}
|
||||
else {
|
||||
@@ -618,13 +625,16 @@ static void findloader (lua_State *L, const char *name) {
|
||||
int i;
|
||||
luaL_Buffer msg; /* to build error message */
|
||||
/* push 'package.searchers' to index 3 in the stack */
|
||||
if (lua_getfield(L, lua_upvalueindex(1), "searchers") != LUA_TTABLE)
|
||||
if (l_unlikely(lua_getfield(L, lua_upvalueindex(1), "searchers")
|
||||
!= LUA_TTABLE))
|
||||
luaL_error(L, "'package.searchers' must be a table");
|
||||
luaL_buffinit(L, &msg);
|
||||
/* iterate over available searchers to find a loader */
|
||||
for (i = 1; ; i++) {
|
||||
if (lua_rawgeti(L, 3, i) == LUA_TNIL) { /* no more searchers? */
|
||||
luaL_addstring(&msg, "\n\t"); /* error-message prefix */
|
||||
if (l_unlikely(lua_rawgeti(L, 3, i) == LUA_TNIL)) { /* no more searchers? */
|
||||
lua_pop(L, 1); /* remove nil */
|
||||
luaL_buffsub(&msg, 2); /* remove prefix */
|
||||
luaL_pushresult(&msg); /* create error message */
|
||||
luaL_error(L, "module '%s' not found:%s", name, lua_tostring(L, -1));
|
||||
}
|
||||
@@ -636,8 +646,10 @@ static void findloader (lua_State *L, const char *name) {
|
||||
lua_pop(L, 1); /* remove extra return */
|
||||
luaL_addvalue(&msg); /* concatenate error message */
|
||||
}
|
||||
else
|
||||
else { /* no error message */
|
||||
lua_pop(L, 2); /* remove both returns */
|
||||
luaL_buffsub(&msg, 2); /* remove prefix */
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -716,12 +728,11 @@ static void createsearcherstable (lua_State *L) {
|
||||
** setting a finalizer to close all libraries when closing state.
|
||||
*/
|
||||
static void createclibstable (lua_State *L) {
|
||||
lua_newtable(L); /* create CLIBS table */
|
||||
luaL_getsubtable(L, LUA_REGISTRYINDEX, CLIBS); /* 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 */
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -29,32 +29,6 @@
|
||||
#include "lvm.h"
|
||||
|
||||
|
||||
/*
|
||||
** converts an integer to a "floating point byte", represented as
|
||||
** (eeeeexxx), where the real value is (1xxx) * 2^(eeeee - 1) if
|
||||
** eeeee != 0 and (xxx) otherwise.
|
||||
*/
|
||||
int luaO_int2fb (unsigned int x) {
|
||||
int e = 0; /* exponent */
|
||||
if (x < 8) return x;
|
||||
while (x >= (8 << 4)) { /* coarse steps */
|
||||
x = (x + 0xf) >> 4; /* x = ceil(x / 16) */
|
||||
e += 4;
|
||||
}
|
||||
while (x >= (8 << 1)) { /* fine steps */
|
||||
x = (x + 1) >> 1; /* x = ceil(x / 2) */
|
||||
e++;
|
||||
}
|
||||
return ((e+1) << 3) | (cast_int(x) - 8);
|
||||
}
|
||||
|
||||
|
||||
/* converts back */
|
||||
int luaO_fb2int (int x) {
|
||||
return (x < 8) ? x : ((x & 7) + 8) << ((x >> 3) - 1);
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** Computes ceil(log2(x))
|
||||
*/
|
||||
@@ -190,7 +164,7 @@ static int isneg (const char **s) {
|
||||
*/
|
||||
static lua_Number lua_strx2number (const char *s, char **endptr) {
|
||||
int dot = lua_getlocaledecpoint();
|
||||
lua_Number r = 0.0; /* result (accumulator) */
|
||||
lua_Number r = l_mathop(0.0); /* result (accumulator) */
|
||||
int sigdig = 0; /* number of significant digits */
|
||||
int nosigdig = 0; /* number of non-significant digits */
|
||||
int e = 0; /* exponent correction */
|
||||
@@ -200,7 +174,7 @@ static lua_Number lua_strx2number (const char *s, char **endptr) {
|
||||
while (lisspace(cast_uchar(*s))) s++; /* skip initial spaces */
|
||||
neg = isneg(&s); /* check sign */
|
||||
if (!(*s == '0' && (*(s + 1) == 'x' || *(s + 1) == 'X'))) /* check '0x' */
|
||||
return 0.0; /* invalid format (no '0x') */
|
||||
return l_mathop(0.0); /* invalid format (no '0x') */
|
||||
for (s += 2; ; s++) { /* skip '0x' and read numeral */
|
||||
if (*s == dot) {
|
||||
if (hasdot) break; /* second dot? stop loop */
|
||||
@@ -210,14 +184,14 @@ static lua_Number lua_strx2number (const char *s, char **endptr) {
|
||||
if (sigdig == 0 && *s == '0') /* non-significant digit (zero)? */
|
||||
nosigdig++;
|
||||
else if (++sigdig <= MAXSIGDIG) /* can read it without overflow? */
|
||||
r = (r * cast_num(16.0)) + luaO_hexavalue(*s);
|
||||
r = (r * l_mathop(16.0)) + luaO_hexavalue(*s);
|
||||
else e++; /* too many digits; ignore, but still count for exponent */
|
||||
if (hasdot) e--; /* decimal digit? correct exponent */
|
||||
}
|
||||
else break; /* neither a dot nor a digit */
|
||||
}
|
||||
if (nosigdig + sigdig == 0) /* no digits? */
|
||||
return 0.0; /* invalid format */
|
||||
return l_mathop(0.0); /* invalid format */
|
||||
*endptr = cast_charp(s); /* valid up to here */
|
||||
e *= 4; /* each digit multiplies/divides value by 2^4 */
|
||||
if (*s == 'p' || *s == 'P') { /* exponent part? */
|
||||
@@ -226,7 +200,7 @@ static lua_Number lua_strx2number (const char *s, char **endptr) {
|
||||
s++; /* skip 'p' */
|
||||
neg1 = isneg(&s); /* sign */
|
||||
if (!lisdigit(cast_uchar(*s)))
|
||||
return 0.0; /* invalid; must have at least one digit */
|
||||
return l_mathop(0.0); /* invalid; must have at least one digit */
|
||||
while (lisdigit(cast_uchar(*s))) /* read exponent */
|
||||
exp1 = exp1 * 10 + *(s++) - '0';
|
||||
if (neg1) exp1 = -exp1;
|
||||
@@ -241,37 +215,42 @@ static lua_Number lua_strx2number (const char *s, char **endptr) {
|
||||
/* }====================================================== */
|
||||
|
||||
|
||||
/* maximum length of a numeral */
|
||||
/* maximum length of a numeral to be converted to a number */
|
||||
#if !defined (L_MAXLENNUM)
|
||||
#define L_MAXLENNUM 200
|
||||
#endif
|
||||
|
||||
/*
|
||||
** Convert string 's' to a Lua number (put in 'result'). Return NULL on
|
||||
** fail or the address of the ending '\0' on success. ('mode' == 'x')
|
||||
** means a hexadecimal numeral.
|
||||
*/
|
||||
static const char *l_str2dloc (const char *s, lua_Number *result, int mode) {
|
||||
char *endptr;
|
||||
*result = (mode == 'x') ? lua_strx2number(s, &endptr) /* try to convert */
|
||||
: lua_str2number(s, &endptr);
|
||||
if (endptr == s) return NULL; /* nothing recognized? */
|
||||
while (lisspace(cast_uchar(*endptr))) endptr++; /* skip trailing spaces */
|
||||
return (*endptr == '\0') ? endptr : NULL; /* OK if no trailing characters */
|
||||
return (*endptr == '\0') ? endptr : NULL; /* OK iff no trailing chars */
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** Convert string 's' to a Lua number (put in 'result'). Return NULL
|
||||
** on fail or the address of the ending '\0' on success.
|
||||
** 'pmode' points to (and 'mode' contains) special things in the string:
|
||||
** - 'x'/'X' means a hexadecimal numeral
|
||||
** - 'n'/'N' means 'inf' or 'nan' (which should be rejected)
|
||||
** - '.' just optimizes the search for the common case (nothing special)
|
||||
** Convert string 's' to a Lua number (put in 'result') handling the
|
||||
** current locale.
|
||||
** This function accepts both the current locale or a dot as the radix
|
||||
** mark. If the conversion fails, it may mean number has a dot but
|
||||
** locale accepts something else. In that case, the code copies 's'
|
||||
** to a buffer (because 's' is read-only), changes the dot to the
|
||||
** current locale radix mark, and tries to convert again.
|
||||
** The variable 'mode' checks for special characters in the string:
|
||||
** - 'n' means 'inf' or 'nan' (which should be rejected)
|
||||
** - 'x' means a hexadecimal numeral
|
||||
** - '.' just optimizes the search for the common case (no special chars)
|
||||
*/
|
||||
static const char *l_str2d (const char *s, lua_Number *result) {
|
||||
const char *endptr;
|
||||
const char *pmode = strpbrk(s, ".xXnN");
|
||||
const char *pmode = strpbrk(s, ".xXnN"); /* look for special chars */
|
||||
int mode = pmode ? ltolower(cast_uchar(*pmode)) : 0;
|
||||
if (mode == 'n') /* reject 'inf' and 'nan' */
|
||||
return NULL;
|
||||
@@ -279,7 +258,7 @@ static const char *l_str2d (const char *s, lua_Number *result) {
|
||||
if (endptr == NULL) { /* failed? may be a different locale */
|
||||
char buff[L_MAXLENNUM + 1];
|
||||
const char *pdot = strchr(s, '.');
|
||||
if (strlen(s) > L_MAXLENNUM || pdot == NULL)
|
||||
if (pdot == NULL || strlen(s) > L_MAXLENNUM)
|
||||
return NULL; /* string too long or no dot; fail */
|
||||
strcpy(buff, s); /* copy string to buffer */
|
||||
buff[pdot - s] = lua_getlocaledecpoint(); /* correct decimal point */
|
||||
@@ -359,8 +338,15 @@ int luaO_utf8esc (char *buff, unsigned long x) {
|
||||
}
|
||||
|
||||
|
||||
/* maximum length of the conversion of a number to a string */
|
||||
#define MAXNUMBER2STR 50
|
||||
/*
|
||||
** Maximum length of the conversion of a number to a string. Must be
|
||||
** enough to accommodate both LUA_INTEGER_FMT and LUA_NUMBER_FMT.
|
||||
** (For a long long int, this is 19 digits plus a sign and a final '\0',
|
||||
** adding to 21. For a long double, it can go to a sign, 33 digits,
|
||||
** the dot, an exponent letter, an exponent sign, 5 exponent digits,
|
||||
** and a final '\0', adding to 43.)
|
||||
*/
|
||||
#define MAXNUMBER2STR 44
|
||||
|
||||
|
||||
/*
|
||||
@@ -401,7 +387,7 @@ void luaO_tostring (lua_State *L, TValue *obj) {
|
||||
*/
|
||||
|
||||
/* size for buffer space used by 'luaO_pushvfstring' */
|
||||
#define BUFVFS 400
|
||||
#define BUFVFS 200
|
||||
|
||||
/* buffer used by 'luaO_pushvfstring' */
|
||||
typedef struct BuffFS {
|
||||
@@ -413,18 +399,16 @@ typedef struct BuffFS {
|
||||
|
||||
|
||||
/*
|
||||
** Push given string to the stack, as part of the buffer. If the stack
|
||||
** is almost full, join all partial strings in the stack into one.
|
||||
** Push given string to the stack, as part of the buffer, and
|
||||
** join the partial strings in the stack into one.
|
||||
*/
|
||||
static void pushstr (BuffFS *buff, const char *str, size_t l) {
|
||||
lua_State *L = buff->L;
|
||||
setsvalue2s(L, L->top, luaS_newlstr(L, str, l));
|
||||
L->top++; /* may use one extra slot */
|
||||
buff->pushed++;
|
||||
if (buff->pushed > 1 && L->top + 1 >= L->stack_last) {
|
||||
luaV_concat(L, buff->pushed); /* join all partial results into one */
|
||||
buff->pushed = 1;
|
||||
}
|
||||
luaV_concat(L, buff->pushed); /* join partial results into one */
|
||||
buff->pushed = 1;
|
||||
}
|
||||
|
||||
|
||||
@@ -547,8 +531,7 @@ const char *luaO_pushvfstring (lua_State *L, const char *fmt, va_list argp) {
|
||||
}
|
||||
addstr2buff(&buff, fmt, strlen(fmt)); /* rest of 'fmt' */
|
||||
clearbuff(&buff); /* empty buffer into the stack */
|
||||
if (buff.pushed > 1)
|
||||
luaV_concat(L, buff.pushed); /* join all partial results */
|
||||
lua_assert(buff.pushed == 1);
|
||||
return svalue(s2v(L->top - 1));
|
||||
}
|
||||
|
||||
|
||||
@@ -17,24 +17,30 @@
|
||||
|
||||
|
||||
/*
|
||||
** Extra tags for non-values
|
||||
** Extra types for collectable non-values
|
||||
*/
|
||||
#define LUA_TUPVAL LUA_NUMTAGS /* upvalues */
|
||||
#define LUA_TPROTO (LUA_NUMTAGS+1) /* function prototypes */
|
||||
#define LUA_TUPVAL LUA_NUMTYPES /* upvalues */
|
||||
#define LUA_TPROTO (LUA_NUMTYPES+1) /* function prototypes */
|
||||
#define LUA_TDEADKEY (LUA_NUMTYPES+2) /* removed keys in tables */
|
||||
|
||||
|
||||
|
||||
/*
|
||||
** number of all possible tags (including LUA_TNONE)
|
||||
** number of all possible types (including LUA_TNONE but excluding DEADKEY)
|
||||
*/
|
||||
#define LUA_TOTALTAGS (LUA_TPROTO + 2)
|
||||
#define LUA_TOTALTYPES (LUA_TPROTO + 2)
|
||||
|
||||
|
||||
/*
|
||||
** tags for Tagged Values have the following use of bits:
|
||||
** bits 0-3: actual tag (a LUA_T* value)
|
||||
** bits 0-3: actual tag (a LUA_T* constant)
|
||||
** bits 4-5: variant bits
|
||||
** bit 6: whether value is collectable
|
||||
*/
|
||||
|
||||
/* add variant bits to a type */
|
||||
#define makevariant(t,v) ((t) | ((v) << 4))
|
||||
|
||||
|
||||
|
||||
/*
|
||||
@@ -43,7 +49,6 @@
|
||||
typedef union Value {
|
||||
struct GCObject *gc; /* collectable objects */
|
||||
void *p; /* light userdata */
|
||||
int b; /* booleans */
|
||||
lua_CFunction f; /* light C functions */
|
||||
lua_Integer i; /* integer numbers */
|
||||
lua_Number n; /* float numbers */
|
||||
@@ -63,7 +68,7 @@ typedef struct TValue {
|
||||
|
||||
|
||||
#define val_(o) ((o)->value_)
|
||||
#define valraw(o) (&val_(o))
|
||||
#define valraw(o) (val_(o))
|
||||
|
||||
|
||||
/* raw type tag of a TValue */
|
||||
@@ -86,24 +91,36 @@ typedef struct TValue {
|
||||
|
||||
|
||||
/* Macros for internal tests */
|
||||
|
||||
/* collectable object has the same tag as the original value */
|
||||
#define righttt(obj) (ttypetag(obj) == gcvalue(obj)->tt)
|
||||
|
||||
/*
|
||||
** Any value being manipulated by the program either is non
|
||||
** collectable, or the collectable object has the right tag
|
||||
** and it is not dead. The option 'L == NULL' allows other
|
||||
** macros using this one to be used where L is not available.
|
||||
*/
|
||||
#define checkliveness(L,obj) \
|
||||
lua_longassert(!iscollectable(obj) || \
|
||||
(righttt(obj) && (L == NULL || !isdead(G(L),gcvalue(obj)))))
|
||||
((void)L, lua_longassert(!iscollectable(obj) || \
|
||||
(righttt(obj) && (L == NULL || !isdead(G(L),gcvalue(obj))))))
|
||||
|
||||
|
||||
/* Macros to set values */
|
||||
|
||||
/* set a value's tag */
|
||||
#define settt_(o,t) ((o)->tt_=(t))
|
||||
|
||||
|
||||
/* main macro to copy values (from 'obj2' to 'obj1') */
|
||||
#define setobj(L,obj1,obj2) \
|
||||
{ TValue *io1=(obj1); const TValue *io2=(obj2); \
|
||||
io1->value_ = io2->value_; io1->tt_ = io2->tt_; \
|
||||
(void)L; checkliveness(L,io1); lua_assert(!isreallyempty(io1)); }
|
||||
io1->value_ = io2->value_; settt_(io1, io2->tt_); \
|
||||
checkliveness(L,io1); lua_assert(!isnonstrictnil(io1)); }
|
||||
|
||||
/*
|
||||
** different types of assignments, according to destination
|
||||
** Different types of assignments, according to source and destination.
|
||||
** (They are mostly equal now, but may be different in the future.)
|
||||
*/
|
||||
|
||||
/* from stack to stack */
|
||||
@@ -118,13 +135,25 @@ typedef struct TValue {
|
||||
#define setobj2t setobj
|
||||
|
||||
|
||||
|
||||
/*
|
||||
** Entries in a Lua stack. Field 'tbclist' forms a list of all
|
||||
** to-be-closed variables active in this stack. Dummy entries are
|
||||
** used when the distance between two tbc variables does not fit
|
||||
** in an unsigned short. They are represented by delta==0, and
|
||||
** their real delta is always the maximum value that fits in
|
||||
** that field.
|
||||
*/
|
||||
typedef union StackValue {
|
||||
TValue val;
|
||||
struct {
|
||||
TValuefields;
|
||||
unsigned short delta;
|
||||
} tbclist;
|
||||
} StackValue;
|
||||
|
||||
|
||||
typedef StackValue *StkId; /* index to stack elements */
|
||||
/* index to stack elements */
|
||||
typedef StackValue *StkId;
|
||||
|
||||
/* convert a 'StackValue' to a 'TValue' */
|
||||
#define s2v(o) (&(o)->val)
|
||||
@@ -137,36 +166,34 @@ typedef StackValue *StkId; /* index to stack elements */
|
||||
** ===================================================================
|
||||
*/
|
||||
|
||||
/* Standard nil */
|
||||
#define LUA_VNIL makevariant(LUA_TNIL, 0)
|
||||
|
||||
/* Empty slot (which might be different from a slot containing nil) */
|
||||
#define LUA_VEMPTY makevariant(LUA_TNIL, 1)
|
||||
|
||||
/* Value returned for a key not found in a table (absent key) */
|
||||
#define LUA_VABSTKEY makevariant(LUA_TNIL, 2)
|
||||
|
||||
|
||||
/* macro to test for (any kind of) nil */
|
||||
#define ttisnil(v) checktype((v), LUA_TNIL)
|
||||
|
||||
/* macro to test for a "pure" nil */
|
||||
#define ttisstrictnil(o) checktag((o), LUA_TNIL)
|
||||
|
||||
/* macro to test for a standard nil */
|
||||
#define ttisstrictnil(o) checktag((o), LUA_VNIL)
|
||||
|
||||
|
||||
#define setnilvalue(obj) settt_(obj, LUA_TNIL)
|
||||
#define setnilvalue(obj) settt_(obj, LUA_VNIL)
|
||||
|
||||
|
||||
/*
|
||||
** Variant tag, used only in tables to signal an empty slot
|
||||
** (which might be different from a slot containing nil)
|
||||
*/
|
||||
#define LUA_TEMPTY (LUA_TNIL | (1 << 4))
|
||||
|
||||
/*
|
||||
** Variant used only in the value returned for a key not found in a
|
||||
** table (absent key).
|
||||
*/
|
||||
#define LUA_TABSTKEY (LUA_TNIL | (2 << 4))
|
||||
|
||||
|
||||
#define isabstkey(v) checktag((v), LUA_TABSTKEY)
|
||||
#define isabstkey(v) checktag((v), LUA_VABSTKEY)
|
||||
|
||||
|
||||
/*
|
||||
** macro to detect non-standard nils (used only in assertions)
|
||||
*/
|
||||
#define isreallyempty(v) (ttisnil(v) && !ttisstrictnil(v))
|
||||
#define isnonstrictnil(v) (ttisnil(v) && !ttisstrictnil(v))
|
||||
|
||||
|
||||
/*
|
||||
@@ -178,11 +205,11 @@ typedef StackValue *StkId; /* index to stack elements */
|
||||
|
||||
|
||||
/* macro defining a value corresponding to an absent key */
|
||||
#define ABSTKEYCONSTANT {NULL}, LUA_TABSTKEY
|
||||
#define ABSTKEYCONSTANT {NULL}, LUA_VABSTKEY
|
||||
|
||||
|
||||
/* mark an entry as empty */
|
||||
#define setempty(v) settt_(v, LUA_TEMPTY)
|
||||
#define setempty(v) settt_(v, LUA_VEMPTY)
|
||||
|
||||
|
||||
|
||||
@@ -195,16 +222,20 @@ typedef StackValue *StkId; /* index to stack elements */
|
||||
** ===================================================================
|
||||
*/
|
||||
|
||||
#define ttisboolean(o) checktag((o), LUA_TBOOLEAN)
|
||||
|
||||
#define bvalue(o) check_exp(ttisboolean(o), val_(o).b)
|
||||
#define LUA_VFALSE makevariant(LUA_TBOOLEAN, 0)
|
||||
#define LUA_VTRUE makevariant(LUA_TBOOLEAN, 1)
|
||||
|
||||
#define bvalueraw(v) ((v).b)
|
||||
#define ttisboolean(o) checktype((o), LUA_TBOOLEAN)
|
||||
#define ttisfalse(o) checktag((o), LUA_VFALSE)
|
||||
#define ttistrue(o) checktag((o), LUA_VTRUE)
|
||||
|
||||
#define l_isfalse(o) (ttisnil(o) || (ttisboolean(o) && bvalue(o) == 0))
|
||||
|
||||
#define setbvalue(obj,x) \
|
||||
{ TValue *io=(obj); val_(io).b=(x); settt_(io, LUA_TBOOLEAN); }
|
||||
#define l_isfalse(o) (ttisfalse(o) || ttisnil(o))
|
||||
|
||||
|
||||
#define setbfvalue(obj) settt_(obj, LUA_VFALSE)
|
||||
#define setbtvalue(obj) settt_(obj, LUA_VTRUE)
|
||||
|
||||
/* }================================================================== */
|
||||
|
||||
@@ -215,13 +246,15 @@ typedef StackValue *StkId; /* index to stack elements */
|
||||
** ===================================================================
|
||||
*/
|
||||
|
||||
#define ttisthread(o) checktag((o), ctb(LUA_TTHREAD))
|
||||
#define LUA_VTHREAD makevariant(LUA_TTHREAD, 0)
|
||||
|
||||
#define ttisthread(o) checktag((o), ctb(LUA_VTHREAD))
|
||||
|
||||
#define thvalue(o) check_exp(ttisthread(o), gco2th(val_(o).gc))
|
||||
|
||||
#define setthvalue(L,obj,x) \
|
||||
{ TValue *io = (obj); lua_State *x_ = (x); \
|
||||
val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_TTHREAD)); \
|
||||
val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_VTHREAD)); \
|
||||
checkliveness(L,io); }
|
||||
|
||||
#define setthvalue2s(L,o,t) setthvalue(L,s2v(o),t)
|
||||
@@ -274,12 +307,12 @@ typedef struct GCObject {
|
||||
*/
|
||||
|
||||
/* Variant tags for numbers */
|
||||
#define LUA_TNUMFLT (LUA_TNUMBER | (1 << 4)) /* float numbers */
|
||||
#define LUA_TNUMINT (LUA_TNUMBER | (2 << 4)) /* integer numbers */
|
||||
#define LUA_VNUMINT makevariant(LUA_TNUMBER, 0) /* integer numbers */
|
||||
#define LUA_VNUMFLT makevariant(LUA_TNUMBER, 1) /* float numbers */
|
||||
|
||||
#define ttisnumber(o) checktype((o), LUA_TNUMBER)
|
||||
#define ttisfloat(o) checktag((o), LUA_TNUMFLT)
|
||||
#define ttisinteger(o) checktag((o), LUA_TNUMINT)
|
||||
#define ttisfloat(o) checktag((o), LUA_VNUMFLT)
|
||||
#define ttisinteger(o) checktag((o), LUA_VNUMINT)
|
||||
|
||||
#define nvalue(o) check_exp(ttisnumber(o), \
|
||||
(ttisinteger(o) ? cast_num(ivalue(o)) : fltvalue(o)))
|
||||
@@ -290,13 +323,13 @@ typedef struct GCObject {
|
||||
#define ivalueraw(v) ((v).i)
|
||||
|
||||
#define setfltvalue(obj,x) \
|
||||
{ TValue *io=(obj); val_(io).n=(x); settt_(io, LUA_TNUMFLT); }
|
||||
{ TValue *io=(obj); val_(io).n=(x); settt_(io, LUA_VNUMFLT); }
|
||||
|
||||
#define chgfltvalue(obj,x) \
|
||||
{ TValue *io=(obj); lua_assert(ttisfloat(io)); val_(io).n=(x); }
|
||||
|
||||
#define setivalue(obj,x) \
|
||||
{ TValue *io=(obj); val_(io).i=(x); settt_(io, LUA_TNUMINT); }
|
||||
{ TValue *io=(obj); val_(io).i=(x); settt_(io, LUA_VNUMINT); }
|
||||
|
||||
#define chgivalue(obj,x) \
|
||||
{ TValue *io=(obj); lua_assert(ttisinteger(io)); val_(io).i=(x); }
|
||||
@@ -311,12 +344,12 @@ typedef struct GCObject {
|
||||
*/
|
||||
|
||||
/* Variant tags for strings */
|
||||
#define LUA_TSHRSTR (LUA_TSTRING | (1 << 4)) /* short strings */
|
||||
#define LUA_TLNGSTR (LUA_TSTRING | (2 << 4)) /* long strings */
|
||||
#define LUA_VSHRSTR makevariant(LUA_TSTRING, 0) /* short strings */
|
||||
#define LUA_VLNGSTR makevariant(LUA_TSTRING, 1) /* long strings */
|
||||
|
||||
#define ttisstring(o) checktype((o), LUA_TSTRING)
|
||||
#define ttisshrstring(o) checktag((o), ctb(LUA_TSHRSTR))
|
||||
#define ttislngstring(o) checktag((o), ctb(LUA_TLNGSTR))
|
||||
#define ttisshrstring(o) checktag((o), ctb(LUA_VSHRSTR))
|
||||
#define ttislngstring(o) checktag((o), ctb(LUA_VLNGSTR))
|
||||
|
||||
#define tsvalueraw(v) (gco2ts((v).gc))
|
||||
|
||||
@@ -335,8 +368,7 @@ typedef struct GCObject {
|
||||
|
||||
|
||||
/*
|
||||
** Header for string value; string bytes follow the end of this structure
|
||||
** (aligned according to 'UTString'; see next).
|
||||
** Header for a string value.
|
||||
*/
|
||||
typedef struct TString {
|
||||
CommonHeader;
|
||||
@@ -347,23 +379,22 @@ typedef struct TString {
|
||||
size_t lnglen; /* length for long strings */
|
||||
struct TString *hnext; /* linked list for hash table */
|
||||
} u;
|
||||
char contents[1];
|
||||
} TString;
|
||||
|
||||
|
||||
|
||||
/*
|
||||
** Get the actual string (array of bytes) from a 'TString'.
|
||||
** (Access to 'extra' ensures that value is really a 'TString'.)
|
||||
*/
|
||||
#define getstr(ts) \
|
||||
check_exp(sizeof((ts)->extra), cast_charp((ts)) + sizeof(TString))
|
||||
#define getstr(ts) ((ts)->contents)
|
||||
|
||||
|
||||
/* get the actual string (array of bytes) from a Lua value */
|
||||
#define svalue(o) getstr(tsvalue(o))
|
||||
|
||||
/* get string length from 'TString *s' */
|
||||
#define tsslen(s) ((s)->tt == LUA_TSHRSTR ? (s)->shrlen : (s)->u.lnglen)
|
||||
#define tsslen(s) ((s)->tt == LUA_VSHRSTR ? (s)->shrlen : (s)->u.lnglen)
|
||||
|
||||
/* get string length from 'TValue *o' */
|
||||
#define vslen(o) tsslen(tsvalue(o))
|
||||
@@ -377,8 +408,17 @@ typedef struct TString {
|
||||
** ===================================================================
|
||||
*/
|
||||
|
||||
#define ttislightuserdata(o) checktag((o), LUA_TLIGHTUSERDATA)
|
||||
#define ttisfulluserdata(o) checktype((o), LUA_TUSERDATA)
|
||||
|
||||
/*
|
||||
** Light userdata should be a variant of userdata, but for compatibility
|
||||
** reasons they are also different types.
|
||||
*/
|
||||
#define LUA_VLIGHTUSERDATA makevariant(LUA_TLIGHTUSERDATA, 0)
|
||||
|
||||
#define LUA_VUSERDATA makevariant(LUA_TUSERDATA, 0)
|
||||
|
||||
#define ttislightuserdata(o) checktag((o), LUA_VLIGHTUSERDATA)
|
||||
#define ttisfulluserdata(o) checktag((o), ctb(LUA_VUSERDATA))
|
||||
|
||||
#define pvalue(o) check_exp(ttislightuserdata(o), val_(o).p)
|
||||
#define uvalue(o) check_exp(ttisfulluserdata(o), gco2u(val_(o).gc))
|
||||
@@ -386,11 +426,11 @@ typedef struct TString {
|
||||
#define pvalueraw(v) ((v).p)
|
||||
|
||||
#define setpvalue(obj,x) \
|
||||
{ TValue *io=(obj); val_(io).p=(x); settt_(io, LUA_TLIGHTUSERDATA); }
|
||||
{ TValue *io=(obj); val_(io).p=(x); settt_(io, LUA_VLIGHTUSERDATA); }
|
||||
|
||||
#define setuvalue(L,obj,x) \
|
||||
{ TValue *io = (obj); Udata *x_ = (x); \
|
||||
val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_TUSERDATA)); \
|
||||
val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_VUSERDATA)); \
|
||||
checkliveness(L,io); }
|
||||
|
||||
|
||||
@@ -453,6 +493,9 @@ typedef struct Udata0 {
|
||||
** ===================================================================
|
||||
*/
|
||||
|
||||
#define LUA_VPROTO makevariant(LUA_TPROTO, 0)
|
||||
|
||||
|
||||
/*
|
||||
** Description of an upvalue for function prototypes
|
||||
*/
|
||||
@@ -460,6 +503,7 @@ typedef struct Upvaldesc {
|
||||
TString *name; /* upvalue name (for debug information) */
|
||||
lu_byte instack; /* whether it is in stack (register) */
|
||||
lu_byte idx; /* index of upvalue (in stack or in outer function's list) */
|
||||
lu_byte kind; /* kind of corresponding variable */
|
||||
} Upvaldesc;
|
||||
|
||||
|
||||
@@ -522,20 +566,24 @@ typedef struct Proto {
|
||||
|
||||
/*
|
||||
** {==================================================================
|
||||
** Closures
|
||||
** Functions
|
||||
** ===================================================================
|
||||
*/
|
||||
|
||||
#define LUA_VUPVAL makevariant(LUA_TUPVAL, 0)
|
||||
|
||||
|
||||
/* Variant tags for functions */
|
||||
#define LUA_TLCL (LUA_TFUNCTION | (1 << 4)) /* Lua closure */
|
||||
#define LUA_TLCF (LUA_TFUNCTION | (2 << 4)) /* light C function */
|
||||
#define LUA_TCCL (LUA_TFUNCTION | (3 << 4)) /* C closure */
|
||||
#define LUA_VLCL makevariant(LUA_TFUNCTION, 0) /* Lua closure */
|
||||
#define LUA_VLCF makevariant(LUA_TFUNCTION, 1) /* light C function */
|
||||
#define LUA_VCCL makevariant(LUA_TFUNCTION, 2) /* C closure */
|
||||
|
||||
#define ttisfunction(o) checktype(o, LUA_TFUNCTION)
|
||||
#define ttisclosure(o) ((rawtt(o) & 0x1F) == LUA_TLCL)
|
||||
#define ttisLclosure(o) checktag((o), ctb(LUA_TLCL))
|
||||
#define ttislcf(o) checktag((o), LUA_TLCF)
|
||||
#define ttisCclosure(o) checktag((o), ctb(LUA_TCCL))
|
||||
#define ttisLclosure(o) checktag((o), ctb(LUA_VLCL))
|
||||
#define ttislcf(o) checktag((o), LUA_VLCF)
|
||||
#define ttisCclosure(o) checktag((o), ctb(LUA_VCCL))
|
||||
#define ttisclosure(o) (ttisLclosure(o) || ttisCclosure(o))
|
||||
|
||||
|
||||
#define isLfunction(o) ttisLclosure(o)
|
||||
|
||||
@@ -548,17 +596,17 @@ typedef struct Proto {
|
||||
|
||||
#define setclLvalue(L,obj,x) \
|
||||
{ TValue *io = (obj); LClosure *x_ = (x); \
|
||||
val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_TLCL)); \
|
||||
val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_VLCL)); \
|
||||
checkliveness(L,io); }
|
||||
|
||||
#define setclLvalue2s(L,o,cl) setclLvalue(L,s2v(o),cl)
|
||||
|
||||
#define setfvalue(obj,x) \
|
||||
{ TValue *io=(obj); val_(io).f=(x); settt_(io, LUA_TLCF); }
|
||||
{ TValue *io=(obj); val_(io).f=(x); settt_(io, LUA_VLCF); }
|
||||
|
||||
#define setclCvalue(L,obj,x) \
|
||||
{ TValue *io = (obj); CClosure *x_ = (x); \
|
||||
val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_TCCL)); \
|
||||
val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_VCCL)); \
|
||||
checkliveness(L,io); }
|
||||
|
||||
|
||||
@@ -567,6 +615,7 @@ typedef struct Proto {
|
||||
*/
|
||||
typedef struct UpVal {
|
||||
CommonHeader;
|
||||
lu_byte tbc; /* true if it represents a to-be-closed variable */
|
||||
TValue *v; /* points to stack or to its own value */
|
||||
union {
|
||||
struct { /* (when open) */
|
||||
@@ -578,9 +627,6 @@ typedef struct UpVal {
|
||||
} UpVal;
|
||||
|
||||
|
||||
/* variant for "To Be Closed" upvalues */
|
||||
#define LUA_TUPVALTBC (LUA_TUPVAL | (1 << 4))
|
||||
|
||||
|
||||
#define ClosureHeader \
|
||||
CommonHeader; lu_byte nupvalues; GCObject *gclist
|
||||
@@ -616,13 +662,15 @@ typedef union Closure {
|
||||
** ===================================================================
|
||||
*/
|
||||
|
||||
#define ttistable(o) checktag((o), ctb(LUA_TTABLE))
|
||||
#define LUA_VTABLE makevariant(LUA_TTABLE, 0)
|
||||
|
||||
#define ttistable(o) checktag((o), ctb(LUA_VTABLE))
|
||||
|
||||
#define hvalue(o) check_exp(ttistable(o), gco2t(val_(o).gc))
|
||||
|
||||
#define sethvalue(L,obj,x) \
|
||||
{ TValue *io = (obj); Table *x_ = (x); \
|
||||
val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_TTABLE)); \
|
||||
val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_VTABLE)); \
|
||||
checkliveness(L,io); }
|
||||
|
||||
#define sethvalue2s(L,o,h) sethvalue(L,s2v(o),h)
|
||||
@@ -650,14 +698,14 @@ typedef union Node {
|
||||
#define setnodekey(L,node,obj) \
|
||||
{ Node *n_=(node); const TValue *io_=(obj); \
|
||||
n_->u.key_val = io_->value_; n_->u.key_tt = io_->tt_; \
|
||||
(void)L; checkliveness(L,io_); }
|
||||
checkliveness(L,io_); }
|
||||
|
||||
|
||||
/* copy a value from a key */
|
||||
#define getnodekey(L,obj,node) \
|
||||
{ TValue *io_=(obj); const Node *n_=(node); \
|
||||
io_->value_ = n_->u.key_val; io_->tt_ = n_->u.key_tt; \
|
||||
(void)L; checkliveness(L,io_); }
|
||||
checkliveness(L,io_); }
|
||||
|
||||
|
||||
/*
|
||||
@@ -668,9 +716,9 @@ typedef union Node {
|
||||
*/
|
||||
|
||||
#define BITRAS (1 << 7)
|
||||
#define isrealasize(t) (!((t)->marked & BITRAS))
|
||||
#define setrealasize(t) ((t)->marked &= cast_byte(~BITRAS))
|
||||
#define setnorealasize(t) ((t)->marked |= BITRAS)
|
||||
#define isrealasize(t) (!((t)->flags & BITRAS))
|
||||
#define setrealasize(t) ((t)->flags &= cast_byte(~BITRAS))
|
||||
#define setnorealasize(t) ((t)->flags |= BITRAS)
|
||||
|
||||
|
||||
typedef struct Table {
|
||||
@@ -693,9 +741,9 @@ typedef struct Table {
|
||||
#define keyval(node) ((node)->u.key_val)
|
||||
|
||||
#define keyisnil(node) (keytt(node) == LUA_TNIL)
|
||||
#define keyisinteger(node) (keytt(node) == LUA_TNUMINT)
|
||||
#define keyisinteger(node) (keytt(node) == LUA_VNUMINT)
|
||||
#define keyival(node) (keyval(node).i)
|
||||
#define keyisshrstr(node) (keytt(node) == ctb(LUA_TSHRSTR))
|
||||
#define keyisshrstr(node) (keytt(node) == ctb(LUA_VSHRSTR))
|
||||
#define keystrval(node) (gco2ts(keyval(node).gc))
|
||||
|
||||
#define setnilkey(node) (keytt(node) = LUA_TNIL)
|
||||
@@ -707,13 +755,13 @@ typedef struct Table {
|
||||
|
||||
|
||||
/*
|
||||
** Use a "nil table" to mark dead keys in a table. Those keys serve
|
||||
** to keep space for removed entries, which may still be part of
|
||||
** chains. Note that the 'keytt' does not have the BIT_ISCOLLECTABLE
|
||||
** set, so these values are considered not collectable and are different
|
||||
** from any valid value.
|
||||
** Dead keys in tables have the tag DEADKEY but keep their original
|
||||
** gcvalue. This distinguishes them from regular keys but allows them to
|
||||
** be found when searched in a special way. ('next' needs that to find
|
||||
** keys removed from a table during a traversal.)
|
||||
*/
|
||||
#define setdeadkey(n) (keytt(n) = LUA_TTABLE, gckey(n) = NULL)
|
||||
#define setdeadkey(node) (keytt(node) = LUA_TDEADKEY)
|
||||
#define keyisdead(node) (keytt(node) == LUA_TDEADKEY)
|
||||
|
||||
/* }================================================================== */
|
||||
|
||||
@@ -733,8 +781,6 @@ typedef struct Table {
|
||||
/* size of buffer for 'luaO_utf8esc' function */
|
||||
#define UTF8BUFFSZ 8
|
||||
|
||||
LUAI_FUNC int luaO_int2fb (unsigned int x);
|
||||
LUAI_FUNC int luaO_fb2int (int x);
|
||||
LUAI_FUNC int luaO_utf8esc (char *buff, unsigned long x);
|
||||
LUAI_FUNC int luaO_ceillog2 (unsigned int x);
|
||||
LUAI_FUNC int luaO_rawarith (lua_State *L, int op, const TValue *p1,
|
||||
|
||||
+84
-87
@@ -10,98 +10,95 @@
|
||||
#include "lprefix.h"
|
||||
|
||||
|
||||
#include <stddef.h>
|
||||
|
||||
#include "lopcodes.h"
|
||||
|
||||
|
||||
/* ORDER OP */
|
||||
|
||||
LUAI_DDEF const lu_byte luaP_opmodes[NUM_OPCODES] = {
|
||||
/* OT IT T A mode opcode */
|
||||
opmode(0, 0, 0, 1, iABC) /* OP_MOVE */
|
||||
,opmode(0, 0, 0, 1, iAsBx) /* OP_LOADI */
|
||||
,opmode(0, 0, 0, 1, iAsBx) /* OP_LOADF */
|
||||
,opmode(0, 0, 0, 1, iABx) /* OP_LOADK */
|
||||
,opmode(0, 0, 0, 1, iABx) /* OP_LOADKX */
|
||||
,opmode(0, 0, 0, 1, iABC) /* OP_LOADBOOL */
|
||||
,opmode(0, 0, 0, 1, iABC) /* OP_LOADNIL */
|
||||
,opmode(0, 0, 0, 1, iABC) /* OP_GETUPVAL */
|
||||
,opmode(0, 0, 0, 0, iABC) /* OP_SETUPVAL */
|
||||
,opmode(0, 0, 0, 1, iABC) /* OP_GETTABUP */
|
||||
,opmode(0, 0, 0, 1, iABC) /* OP_GETTABLE */
|
||||
,opmode(0, 0, 0, 1, iABC) /* OP_GETI */
|
||||
,opmode(0, 0, 0, 1, iABC) /* OP_GETFIELD */
|
||||
,opmode(0, 0, 0, 0, iABC) /* OP_SETTABUP */
|
||||
,opmode(0, 0, 0, 0, iABC) /* OP_SETTABLE */
|
||||
,opmode(0, 0, 0, 0, iABC) /* OP_SETI */
|
||||
,opmode(0, 0, 0, 0, iABC) /* OP_SETFIELD */
|
||||
,opmode(0, 0, 0, 1, iABC) /* OP_NEWTABLE */
|
||||
,opmode(0, 0, 0, 1, iABC) /* OP_SELF */
|
||||
,opmode(0, 0, 0, 1, iABC) /* OP_ADDI */
|
||||
,opmode(0, 0, 0, 1, iABC) /* OP_SUBI */
|
||||
,opmode(0, 0, 0, 1, iABC) /* OP_MULI */
|
||||
,opmode(0, 0, 0, 1, iABC) /* OP_MODI */
|
||||
,opmode(0, 0, 0, 1, iABC) /* OP_POWI */
|
||||
,opmode(0, 0, 0, 1, iABC) /* OP_DIVI */
|
||||
,opmode(0, 0, 0, 1, iABC) /* OP_IDIVI */
|
||||
,opmode(0, 0, 0, 1, iABC) /* OP_ADDK */
|
||||
,opmode(0, 0, 0, 1, iABC) /* OP_SUBK */
|
||||
,opmode(0, 0, 0, 1, iABC) /* OP_MULK */
|
||||
,opmode(0, 0, 0, 1, iABC) /* OP_MODK */
|
||||
,opmode(0, 0, 0, 1, iABC) /* OP_POWK */
|
||||
,opmode(0, 0, 0, 1, iABC) /* OP_DIVK */
|
||||
,opmode(0, 0, 0, 1, iABC) /* OP_IDIVK */
|
||||
,opmode(0, 0, 0, 1, iABC) /* OP_BANDK */
|
||||
,opmode(0, 0, 0, 1, iABC) /* OP_BORK */
|
||||
,opmode(0, 0, 0, 1, iABC) /* OP_BXORK */
|
||||
,opmode(0, 0, 0, 1, iABC) /* OP_SHRI */
|
||||
,opmode(0, 0, 0, 1, iABC) /* OP_SHLI */
|
||||
,opmode(0, 0, 0, 1, iABC) /* OP_ADD */
|
||||
,opmode(0, 0, 0, 1, iABC) /* OP_SUB */
|
||||
,opmode(0, 0, 0, 1, iABC) /* OP_MUL */
|
||||
,opmode(0, 0, 0, 1, iABC) /* OP_MOD */
|
||||
,opmode(0, 0, 0, 1, iABC) /* OP_POW */
|
||||
,opmode(0, 0, 0, 1, iABC) /* OP_DIV */
|
||||
,opmode(0, 0, 0, 1, iABC) /* OP_IDIV */
|
||||
,opmode(0, 0, 0, 1, iABC) /* OP_BAND */
|
||||
,opmode(0, 0, 0, 1, iABC) /* OP_BOR */
|
||||
,opmode(0, 0, 0, 1, iABC) /* OP_BXOR */
|
||||
,opmode(0, 0, 0, 1, iABC) /* OP_SHL */
|
||||
,opmode(0, 0, 0, 1, iABC) /* OP_SHR */
|
||||
,opmode(0, 0, 0, 1, iABC) /* OP_UNM */
|
||||
,opmode(0, 0, 0, 1, iABC) /* OP_BNOT */
|
||||
,opmode(0, 0, 0, 1, iABC) /* OP_NOT */
|
||||
,opmode(0, 0, 0, 1, iABC) /* OP_LEN */
|
||||
,opmode(0, 0, 0, 1, iABC) /* OP_CONCAT */
|
||||
,opmode(0, 0, 0, 0, iABC) /* OP_CLOSE */
|
||||
,opmode(0, 0, 0, 0, iABC) /* OP_TBC */
|
||||
,opmode(0, 0, 0, 0, isJ) /* OP_JMP */
|
||||
,opmode(0, 0, 1, 0, iABC) /* OP_EQ */
|
||||
,opmode(0, 0, 1, 0, iABC) /* OP_LT */
|
||||
,opmode(0, 0, 1, 0, iABC) /* OP_LE */
|
||||
,opmode(0, 0, 1, 0, iABC) /* OP_EQK */
|
||||
,opmode(0, 0, 1, 0, iABC) /* OP_EQI */
|
||||
,opmode(0, 0, 1, 0, iABC) /* OP_LTI */
|
||||
,opmode(0, 0, 1, 0, iABC) /* OP_LEI */
|
||||
,opmode(0, 0, 1, 0, iABC) /* OP_GTI */
|
||||
,opmode(0, 0, 1, 0, iABC) /* OP_GEI */
|
||||
,opmode(0, 0, 1, 0, iABC) /* OP_TEST */
|
||||
,opmode(0, 0, 1, 1, iABC) /* OP_TESTSET */
|
||||
,opmode(1, 1, 0, 1, iABC) /* OP_CALL */
|
||||
,opmode(1, 1, 0, 1, iABC) /* OP_TAILCALL */
|
||||
,opmode(0, 1, 0, 0, iABC) /* OP_RETURN */
|
||||
,opmode(0, 0, 0, 0, iABC) /* OP_RETURN0 */
|
||||
,opmode(0, 0, 0, 0, iABC) /* OP_RETURN1 */
|
||||
,opmode(0, 0, 0, 1, iABx) /* OP_FORLOOP */
|
||||
,opmode(0, 0, 0, 1, iABx) /* OP_FORPREP */
|
||||
,opmode(0, 0, 0, 0, iABx) /* OP_TFORPREP */
|
||||
,opmode(0, 0, 0, 0, iABC) /* OP_TFORCALL */
|
||||
,opmode(0, 0, 0, 1, iABx) /* OP_TFORLOOP */
|
||||
,opmode(0, 1, 0, 0, iABC) /* OP_SETLIST */
|
||||
,opmode(0, 0, 0, 1, iABx) /* OP_CLOSURE */
|
||||
,opmode(1, 0, 0, 1, iABC) /* OP_VARARG */
|
||||
,opmode(0, 0, 0, 1, iABC) /* OP_VARARGPREP */
|
||||
,opmode(0, 0, 0, 0, iAx) /* OP_EXTRAARG */
|
||||
/* MM OT IT T A mode opcode */
|
||||
opmode(0, 0, 0, 0, 1, iABC) /* OP_MOVE */
|
||||
,opmode(0, 0, 0, 0, 1, iAsBx) /* OP_LOADI */
|
||||
,opmode(0, 0, 0, 0, 1, iAsBx) /* OP_LOADF */
|
||||
,opmode(0, 0, 0, 0, 1, iABx) /* OP_LOADK */
|
||||
,opmode(0, 0, 0, 0, 1, iABx) /* OP_LOADKX */
|
||||
,opmode(0, 0, 0, 0, 1, iABC) /* OP_LOADFALSE */
|
||||
,opmode(0, 0, 0, 0, 1, iABC) /* OP_LFALSESKIP */
|
||||
,opmode(0, 0, 0, 0, 1, iABC) /* OP_LOADTRUE */
|
||||
,opmode(0, 0, 0, 0, 1, iABC) /* OP_LOADNIL */
|
||||
,opmode(0, 0, 0, 0, 1, iABC) /* OP_GETUPVAL */
|
||||
,opmode(0, 0, 0, 0, 0, iABC) /* OP_SETUPVAL */
|
||||
,opmode(0, 0, 0, 0, 1, iABC) /* OP_GETTABUP */
|
||||
,opmode(0, 0, 0, 0, 1, iABC) /* OP_GETTABLE */
|
||||
,opmode(0, 0, 0, 0, 1, iABC) /* OP_GETI */
|
||||
,opmode(0, 0, 0, 0, 1, iABC) /* OP_GETFIELD */
|
||||
,opmode(0, 0, 0, 0, 0, iABC) /* OP_SETTABUP */
|
||||
,opmode(0, 0, 0, 0, 0, iABC) /* OP_SETTABLE */
|
||||
,opmode(0, 0, 0, 0, 0, iABC) /* OP_SETI */
|
||||
,opmode(0, 0, 0, 0, 0, iABC) /* OP_SETFIELD */
|
||||
,opmode(0, 0, 0, 0, 1, iABC) /* OP_NEWTABLE */
|
||||
,opmode(0, 0, 0, 0, 1, iABC) /* OP_SELF */
|
||||
,opmode(0, 0, 0, 0, 1, iABC) /* OP_ADDI */
|
||||
,opmode(0, 0, 0, 0, 1, iABC) /* OP_ADDK */
|
||||
,opmode(0, 0, 0, 0, 1, iABC) /* OP_SUBK */
|
||||
,opmode(0, 0, 0, 0, 1, iABC) /* OP_MULK */
|
||||
,opmode(0, 0, 0, 0, 1, iABC) /* OP_MODK */
|
||||
,opmode(0, 0, 0, 0, 1, iABC) /* OP_POWK */
|
||||
,opmode(0, 0, 0, 0, 1, iABC) /* OP_DIVK */
|
||||
,opmode(0, 0, 0, 0, 1, iABC) /* OP_IDIVK */
|
||||
,opmode(0, 0, 0, 0, 1, iABC) /* OP_BANDK */
|
||||
,opmode(0, 0, 0, 0, 1, iABC) /* OP_BORK */
|
||||
,opmode(0, 0, 0, 0, 1, iABC) /* OP_BXORK */
|
||||
,opmode(0, 0, 0, 0, 1, iABC) /* OP_SHRI */
|
||||
,opmode(0, 0, 0, 0, 1, iABC) /* OP_SHLI */
|
||||
,opmode(0, 0, 0, 0, 1, iABC) /* OP_ADD */
|
||||
,opmode(0, 0, 0, 0, 1, iABC) /* OP_SUB */
|
||||
,opmode(0, 0, 0, 0, 1, iABC) /* OP_MUL */
|
||||
,opmode(0, 0, 0, 0, 1, iABC) /* OP_MOD */
|
||||
,opmode(0, 0, 0, 0, 1, iABC) /* OP_POW */
|
||||
,opmode(0, 0, 0, 0, 1, iABC) /* OP_DIV */
|
||||
,opmode(0, 0, 0, 0, 1, iABC) /* OP_IDIV */
|
||||
,opmode(0, 0, 0, 0, 1, iABC) /* OP_BAND */
|
||||
,opmode(0, 0, 0, 0, 1, iABC) /* OP_BOR */
|
||||
,opmode(0, 0, 0, 0, 1, iABC) /* OP_BXOR */
|
||||
,opmode(0, 0, 0, 0, 1, iABC) /* OP_SHL */
|
||||
,opmode(0, 0, 0, 0, 1, iABC) /* OP_SHR */
|
||||
,opmode(1, 0, 0, 0, 0, iABC) /* OP_MMBIN */
|
||||
,opmode(1, 0, 0, 0, 0, iABC) /* OP_MMBINI*/
|
||||
,opmode(1, 0, 0, 0, 0, iABC) /* OP_MMBINK*/
|
||||
,opmode(0, 0, 0, 0, 1, iABC) /* OP_UNM */
|
||||
,opmode(0, 0, 0, 0, 1, iABC) /* OP_BNOT */
|
||||
,opmode(0, 0, 0, 0, 1, iABC) /* OP_NOT */
|
||||
,opmode(0, 0, 0, 0, 1, iABC) /* OP_LEN */
|
||||
,opmode(0, 0, 0, 0, 1, iABC) /* OP_CONCAT */
|
||||
,opmode(0, 0, 0, 0, 0, iABC) /* OP_CLOSE */
|
||||
,opmode(0, 0, 0, 0, 0, iABC) /* OP_TBC */
|
||||
,opmode(0, 0, 0, 0, 0, isJ) /* OP_JMP */
|
||||
,opmode(0, 0, 0, 1, 0, iABC) /* OP_EQ */
|
||||
,opmode(0, 0, 0, 1, 0, iABC) /* OP_LT */
|
||||
,opmode(0, 0, 0, 1, 0, iABC) /* OP_LE */
|
||||
,opmode(0, 0, 0, 1, 0, iABC) /* OP_EQK */
|
||||
,opmode(0, 0, 0, 1, 0, iABC) /* OP_EQI */
|
||||
,opmode(0, 0, 0, 1, 0, iABC) /* OP_LTI */
|
||||
,opmode(0, 0, 0, 1, 0, iABC) /* OP_LEI */
|
||||
,opmode(0, 0, 0, 1, 0, iABC) /* OP_GTI */
|
||||
,opmode(0, 0, 0, 1, 0, iABC) /* OP_GEI */
|
||||
,opmode(0, 0, 0, 1, 0, iABC) /* OP_TEST */
|
||||
,opmode(0, 0, 0, 1, 1, iABC) /* OP_TESTSET */
|
||||
,opmode(0, 1, 1, 0, 1, iABC) /* OP_CALL */
|
||||
,opmode(0, 1, 1, 0, 1, iABC) /* OP_TAILCALL */
|
||||
,opmode(0, 0, 1, 0, 0, iABC) /* OP_RETURN */
|
||||
,opmode(0, 0, 0, 0, 0, iABC) /* OP_RETURN0 */
|
||||
,opmode(0, 0, 0, 0, 0, iABC) /* OP_RETURN1 */
|
||||
,opmode(0, 0, 0, 0, 1, iABx) /* OP_FORLOOP */
|
||||
,opmode(0, 0, 0, 0, 1, iABx) /* OP_FORPREP */
|
||||
,opmode(0, 0, 0, 0, 0, iABx) /* OP_TFORPREP */
|
||||
,opmode(0, 0, 0, 0, 0, iABC) /* OP_TFORCALL */
|
||||
,opmode(0, 0, 0, 0, 1, iABx) /* OP_TFORLOOP */
|
||||
,opmode(0, 0, 1, 0, 0, iABC) /* OP_SETLIST */
|
||||
,opmode(0, 0, 0, 0, 1, iABx) /* OP_CLOSURE */
|
||||
,opmode(0, 1, 0, 0, 1, iABC) /* OP_VARARG */
|
||||
,opmode(0, 0, 1, 0, 1, iABC) /* OP_VARARGPREP */
|
||||
,opmode(0, 0, 0, 0, 0, iAx) /* OP_EXTRAARG */
|
||||
};
|
||||
|
||||
|
||||
+133
-106
@@ -17,11 +17,11 @@
|
||||
|
||||
3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0
|
||||
1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
|
||||
iABC C(8) | B(8) |k| A(8) | Op(7) |
|
||||
iABx Bx(17) | A(8) | Op(7) |
|
||||
iAsB sBx (signed)(17) | A(8) | Op(7) |
|
||||
iAx Ax(25) | Op(7) |
|
||||
isJ sJ(25) | Op(7) |
|
||||
iABC C(8) | B(8) |k| A(8) | Op(7) |
|
||||
iABx Bx(17) | A(8) | Op(7) |
|
||||
iAsBx sBx (signed)(17) | A(8) | Op(7) |
|
||||
iAx Ax(25) | Op(7) |
|
||||
isJ sJ(25) | Op(7) |
|
||||
|
||||
A signed argument is represented in excess K: the represented value is
|
||||
the written unsigned value minus K, where K is half the maximum for the
|
||||
@@ -97,6 +97,9 @@ enum OpMode {iABC, iABx, iAsBx, iAx, isJ}; /* basic instruction formats */
|
||||
#define MAXARG_C ((1<<SIZE_C)-1)
|
||||
#define OFFSET_sC (MAXARG_C >> 1)
|
||||
|
||||
#define int2sC(i) ((i) + OFFSET_sC)
|
||||
#define sC2int(i) ((i) - OFFSET_sC)
|
||||
|
||||
|
||||
/* creates a mask with 'n' 1 bits at position 'p' */
|
||||
#define MASK1(n,p) ((~((~(Instruction)0)<<(n)))<<(p))
|
||||
@@ -123,14 +126,14 @@ enum OpMode {iABC, iABx, iAsBx, iAx, isJ}; /* basic instruction formats */
|
||||
#define SETARG_A(i,v) setarg(i, v, POS_A, SIZE_A)
|
||||
|
||||
#define GETARG_B(i) check_exp(checkopm(i, iABC), getarg(i, POS_B, SIZE_B))
|
||||
#define GETARG_sB(i) (GETARG_B(i) - OFFSET_sC)
|
||||
#define GETARG_sB(i) sC2int(GETARG_B(i))
|
||||
#define SETARG_B(i,v) setarg(i, v, POS_B, SIZE_B)
|
||||
|
||||
#define GETARG_C(i) check_exp(checkopm(i, iABC), getarg(i, POS_C, SIZE_C))
|
||||
#define GETARG_sC(i) (GETARG_C(i) - OFFSET_sC)
|
||||
#define GETARG_sC(i) sC2int(GETARG_C(i))
|
||||
#define SETARG_C(i,v) setarg(i, v, POS_C, SIZE_C)
|
||||
|
||||
#define TESTARG_k(i) (cast_int(((i) & (1u << POS_k))))
|
||||
#define TESTARG_k(i) check_exp(checkopm(i, iABC), (cast_int(((i) & (1u << POS_k)))))
|
||||
#define GETARG_k(i) check_exp(checkopm(i, iABC), getarg(i, POS_k, 1))
|
||||
#define SETARG_k(i,v) setarg(i, v, POS_k, 1)
|
||||
|
||||
@@ -180,127 +183,128 @@ enum OpMode {iABC, iABx, iAsBx, iAx, isJ}; /* basic instruction formats */
|
||||
|
||||
|
||||
/*
|
||||
** R(x) - register
|
||||
** K(x) - constant (in constant table)
|
||||
** RK(x) == if k(i) then K(x) else R(x)
|
||||
** R[x] - register
|
||||
** K[x] - constant (in constant table)
|
||||
** RK(x) == if k(i) then K[x] else R[x]
|
||||
*/
|
||||
|
||||
|
||||
/*
|
||||
** grep "ORDER OP" if you change these enums
|
||||
** Grep "ORDER OP" if you change these enums. Opcodes marked with a (*)
|
||||
** has extra descriptions in the notes after the enumeration.
|
||||
*/
|
||||
|
||||
typedef enum {
|
||||
/*----------------------------------------------------------------------
|
||||
name args description
|
||||
name args description
|
||||
------------------------------------------------------------------------*/
|
||||
OP_MOVE,/* A B R(A) := R(B) */
|
||||
OP_LOADI,/* A sBx R(A) := sBx */
|
||||
OP_LOADF,/* A sBx R(A) := (lua_Number)sBx */
|
||||
OP_LOADK,/* A Bx R(A) := K(Bx) */
|
||||
OP_LOADKX,/* A R(A) := K(extra arg) */
|
||||
OP_LOADBOOL,/* A B C R(A) := (Bool)B; if (C) pc++ */
|
||||
OP_LOADNIL,/* A B R(A), R(A+1), ..., R(A+B) := nil */
|
||||
OP_GETUPVAL,/* A B R(A) := UpValue[B] */
|
||||
OP_SETUPVAL,/* A B UpValue[B] := R(A) */
|
||||
OP_MOVE,/* A B R[A] := R[B] */
|
||||
OP_LOADI,/* A sBx R[A] := sBx */
|
||||
OP_LOADF,/* A sBx R[A] := (lua_Number)sBx */
|
||||
OP_LOADK,/* A Bx R[A] := K[Bx] */
|
||||
OP_LOADKX,/* A R[A] := K[extra arg] */
|
||||
OP_LOADFALSE,/* A R[A] := false */
|
||||
OP_LFALSESKIP,/*A R[A] := false; pc++ (*) */
|
||||
OP_LOADTRUE,/* A R[A] := true */
|
||||
OP_LOADNIL,/* A B R[A], R[A+1], ..., R[A+B] := nil */
|
||||
OP_GETUPVAL,/* A B R[A] := UpValue[B] */
|
||||
OP_SETUPVAL,/* A B UpValue[B] := R[A] */
|
||||
|
||||
OP_GETTABUP,/* A B C R(A) := UpValue[B][K(C):string] */
|
||||
OP_GETTABLE,/* A B C R(A) := R(B)[R(C)] */
|
||||
OP_GETI,/* A B C R(A) := R(B)[C] */
|
||||
OP_GETFIELD,/* A B C R(A) := R(B)[K(C):string] */
|
||||
OP_GETTABUP,/* A B C R[A] := UpValue[B][K[C]:string] */
|
||||
OP_GETTABLE,/* A B C R[A] := R[B][R[C]] */
|
||||
OP_GETI,/* A B C R[A] := R[B][C] */
|
||||
OP_GETFIELD,/* A B C R[A] := R[B][K[C]:string] */
|
||||
|
||||
OP_SETTABUP,/* A B C UpValue[A][K(B):string] := RK(C) */
|
||||
OP_SETTABLE,/* A B C R(A)[R(B)] := RK(C) */
|
||||
OP_SETI,/* A B C R(A)[B] := RK(C) */
|
||||
OP_SETFIELD,/* A B C R(A)[K(B):string] := RK(C) */
|
||||
OP_SETTABUP,/* A B C UpValue[A][K[B]:string] := RK(C) */
|
||||
OP_SETTABLE,/* A B C R[A][R[B]] := RK(C) */
|
||||
OP_SETI,/* A B C R[A][B] := RK(C) */
|
||||
OP_SETFIELD,/* A B C R[A][K[B]:string] := RK(C) */
|
||||
|
||||
OP_NEWTABLE,/* A B C R(A) := {} (size = B,C) */
|
||||
OP_NEWTABLE,/* A B C k R[A] := {} */
|
||||
|
||||
OP_SELF,/* A B C R(A+1) := R(B); R(A) := R(B)[RK(C):string] */
|
||||
OP_SELF,/* A B C R[A+1] := R[B]; R[A] := R[B][RK(C):string] */
|
||||
|
||||
OP_ADDI,/* A B sC R(A) := R(B) + C */
|
||||
OP_SUBI,/* A B sC R(A) := R(B) - C */
|
||||
OP_MULI,/* A B sC R(A) := R(B) * C */
|
||||
OP_MODI,/* A B sC R(A) := R(B) % C */
|
||||
OP_POWI,/* A B sC R(A) := R(B) ^ C */
|
||||
OP_DIVI,/* A B sC R(A) := R(B) / C */
|
||||
OP_IDIVI,/* A B sC R(A) := R(B) // C */
|
||||
OP_ADDI,/* A B sC R[A] := R[B] + sC */
|
||||
|
||||
OP_ADDK,/* A B C R(A) := R(B) + K(C) */
|
||||
OP_SUBK,/* A B C R(A) := R(B) - K(C) */
|
||||
OP_MULK,/* A B C R(A) := R(B) * K(C) */
|
||||
OP_MODK,/* A B C R(A) := R(B) % K(C) */
|
||||
OP_POWK,/* A B C R(A) := R(B) ^ K(C) */
|
||||
OP_DIVK,/* A B C R(A) := R(B) / K(C) */
|
||||
OP_IDIVK,/* A B C R(A) := R(B) // K(C) */
|
||||
OP_ADDK,/* A B C R[A] := R[B] + K[C]:number */
|
||||
OP_SUBK,/* A B C R[A] := R[B] - K[C]:number */
|
||||
OP_MULK,/* A B C R[A] := R[B] * K[C]:number */
|
||||
OP_MODK,/* A B C R[A] := R[B] % K[C]:number */
|
||||
OP_POWK,/* A B C R[A] := R[B] ^ K[C]:number */
|
||||
OP_DIVK,/* A B C R[A] := R[B] / K[C]:number */
|
||||
OP_IDIVK,/* A B C R[A] := R[B] // K[C]:number */
|
||||
|
||||
OP_BANDK,/* A B C R(A) := R(B) & K(C):integer */
|
||||
OP_BORK,/* A B C R(A) := R(B) | K(C):integer */
|
||||
OP_BXORK,/* A B C R(A) := R(B) ~ K(C):integer */
|
||||
OP_BANDK,/* A B C R[A] := R[B] & K[C]:integer */
|
||||
OP_BORK,/* A B C R[A] := R[B] | K[C]:integer */
|
||||
OP_BXORK,/* A B C R[A] := R[B] ~ K[C]:integer */
|
||||
|
||||
OP_SHRI,/* A B sC R(A) := R(B) >> C */
|
||||
OP_SHLI,/* A B sC R(A) := C << R(B) */
|
||||
OP_SHRI,/* A B sC R[A] := R[B] >> sC */
|
||||
OP_SHLI,/* A B sC R[A] := sC << R[B] */
|
||||
|
||||
OP_ADD,/* A B C R(A) := R(B) + R(C) */
|
||||
OP_SUB,/* A B C R(A) := R(B) - R(C) */
|
||||
OP_MUL,/* A B C R(A) := R(B) * R(C) */
|
||||
OP_MOD,/* A B C R(A) := R(B) % R(C) */
|
||||
OP_POW,/* A B C R(A) := R(B) ^ R(C) */
|
||||
OP_DIV,/* A B C R(A) := R(B) / R(C) */
|
||||
OP_IDIV,/* A B C R(A) := R(B) // R(C) */
|
||||
OP_ADD,/* A B C R[A] := R[B] + R[C] */
|
||||
OP_SUB,/* A B C R[A] := R[B] - R[C] */
|
||||
OP_MUL,/* A B C R[A] := R[B] * R[C] */
|
||||
OP_MOD,/* A B C R[A] := R[B] % R[C] */
|
||||
OP_POW,/* A B C R[A] := R[B] ^ R[C] */
|
||||
OP_DIV,/* A B C R[A] := R[B] / R[C] */
|
||||
OP_IDIV,/* A B C R[A] := R[B] // R[C] */
|
||||
|
||||
OP_BAND,/* A B C R(A) := R(B) & R(C) */
|
||||
OP_BOR,/* A B C R(A) := R(B) | R(C) */
|
||||
OP_BXOR,/* A B C R(A) := R(B) ~ R(C) */
|
||||
OP_SHL,/* A B C R(A) := R(B) << R(C) */
|
||||
OP_SHR,/* A B C R(A) := R(B) >> R(C) */
|
||||
OP_BAND,/* A B C R[A] := R[B] & R[C] */
|
||||
OP_BOR,/* A B C R[A] := R[B] | R[C] */
|
||||
OP_BXOR,/* A B C R[A] := R[B] ~ R[C] */
|
||||
OP_SHL,/* A B C R[A] := R[B] << R[C] */
|
||||
OP_SHR,/* A B C R[A] := R[B] >> R[C] */
|
||||
|
||||
OP_UNM,/* A B R(A) := -R(B) */
|
||||
OP_BNOT,/* A B R(A) := ~R(B) */
|
||||
OP_NOT,/* A B R(A) := not R(B) */
|
||||
OP_LEN,/* A B R(A) := length of R(B) */
|
||||
OP_MMBIN,/* A B C call C metamethod over R[A] and R[B] (*) */
|
||||
OP_MMBINI,/* A sB C k call C metamethod over R[A] and sB */
|
||||
OP_MMBINK,/* A B C k call C metamethod over R[A] and K[B] */
|
||||
|
||||
OP_CONCAT,/* A B R(A) := R(A).. ... ..R(A + B - 1) */
|
||||
OP_UNM,/* A B R[A] := -R[B] */
|
||||
OP_BNOT,/* A B R[A] := ~R[B] */
|
||||
OP_NOT,/* A B R[A] := not R[B] */
|
||||
OP_LEN,/* A B R[A] := #R[B] (length operator) */
|
||||
|
||||
OP_CLOSE,/* A close all upvalues >= R(A) */
|
||||
OP_CONCAT,/* A B R[A] := R[A].. ... ..R[A + B - 1] */
|
||||
|
||||
OP_CLOSE,/* A close all upvalues >= R[A] */
|
||||
OP_TBC,/* A mark variable A "to be closed" */
|
||||
OP_JMP,/* k sJ pc += sJ (k is used in code generation) */
|
||||
OP_EQ,/* A B if ((R(A) == R(B)) ~= k) then pc++ */
|
||||
OP_LT,/* A B if ((R(A) < R(B)) ~= k) then pc++ */
|
||||
OP_LE,/* A B if ((R(A) <= R(B)) ~= k) then pc++ */
|
||||
OP_JMP,/* sJ pc += sJ */
|
||||
OP_EQ,/* A B k if ((R[A] == R[B]) ~= k) then pc++ */
|
||||
OP_LT,/* A B k if ((R[A] < R[B]) ~= k) then pc++ */
|
||||
OP_LE,/* A B k if ((R[A] <= R[B]) ~= k) then pc++ */
|
||||
|
||||
OP_EQK,/* A B if ((R(A) == K(B)) ~= k) then pc++ */
|
||||
OP_EQI,/* A sB if ((R(A) == sB) ~= k) then pc++ */
|
||||
OP_LTI,/* A sB if ((R(A) < sB) ~= k) then pc++ */
|
||||
OP_LEI,/* A sB if ((R(A) <= sB) ~= k) then pc++ */
|
||||
OP_GTI,/* A sB if ((R(A) > sB) ~= k) then pc++ */
|
||||
OP_GEI,/* A sB if ((R(A) >= sB) ~= k) then pc++ */
|
||||
OP_EQK,/* A B k if ((R[A] == K[B]) ~= k) then pc++ */
|
||||
OP_EQI,/* A sB k if ((R[A] == sB) ~= k) then pc++ */
|
||||
OP_LTI,/* A sB k if ((R[A] < sB) ~= k) then pc++ */
|
||||
OP_LEI,/* A sB k if ((R[A] <= sB) ~= k) then pc++ */
|
||||
OP_GTI,/* A sB k if ((R[A] > sB) ~= k) then pc++ */
|
||||
OP_GEI,/* A sB k if ((R[A] >= sB) ~= k) then pc++ */
|
||||
|
||||
OP_TEST,/* A if (not R(A) == k) then pc++ */
|
||||
OP_TESTSET,/* A B if (not R(B) == k) then pc++ else R(A) := R(B) */
|
||||
OP_TEST,/* A k if (not R[A] == k) then pc++ */
|
||||
OP_TESTSET,/* A B k if (not R[B] == k) then pc++ else R[A] := R[B] (*) */
|
||||
|
||||
OP_CALL,/* A B C R(A), ... ,R(A+C-2) := R(A)(R(A+1), ... ,R(A+B-1)) */
|
||||
OP_TAILCALL,/* A B C return R(A)(R(A+1), ... ,R(A+B-1)) */
|
||||
OP_CALL,/* A B C R[A], ... ,R[A+C-2] := R[A](R[A+1], ... ,R[A+B-1]) */
|
||||
OP_TAILCALL,/* A B C k return R[A](R[A+1], ... ,R[A+B-1]) */
|
||||
|
||||
OP_RETURN,/* A B C return R(A), ... ,R(A+B-2) (see note) */
|
||||
OP_RETURN0,/* return */
|
||||
OP_RETURN1,/* A return R(A) */
|
||||
OP_RETURN,/* A B C k return R[A], ... ,R[A+B-2] (see note) */
|
||||
OP_RETURN0,/* return */
|
||||
OP_RETURN1,/* A return R[A] */
|
||||
|
||||
OP_FORLOOP,/* A Bx R(A)+=R(A+2);
|
||||
if R(A) <?= R(A+1) then { pc-=Bx; R(A+3)=R(A) } */
|
||||
OP_FORPREP,/* A Bx R(A)-=R(A+2); pc+=Bx */
|
||||
OP_FORLOOP,/* A Bx update counters; if loop continues then pc-=Bx; */
|
||||
OP_FORPREP,/* A Bx <check values and prepare counters>;
|
||||
if not to run then pc+=Bx+1; */
|
||||
|
||||
OP_TFORPREP,/* A Bx create upvalue for R(A + 3); pc+=Bx */
|
||||
OP_TFORCALL,/* A C R(A+4), ... ,R(A+3+C) := R(A)(R(A+1), R(A+2)); */
|
||||
OP_TFORLOOP,/* A Bx if R(A+2) ~= nil then { R(A)=R(A+2); pc -= Bx } */
|
||||
OP_TFORPREP,/* A Bx create upvalue for R[A + 3]; pc+=Bx */
|
||||
OP_TFORCALL,/* A C R[A+4], ... ,R[A+3+C] := R[A](R[A+1], R[A+2]); */
|
||||
OP_TFORLOOP,/* A Bx if R[A+2] ~= nil then { R[A]=R[A+2]; pc -= Bx } */
|
||||
|
||||
OP_SETLIST,/* A B C R(A)[(C-1)*FPF+i] := R(A+i), 1 <= i <= B */
|
||||
OP_SETLIST,/* A B C k R[A][C+i] := R[A+i], 1 <= i <= B */
|
||||
|
||||
OP_CLOSURE,/* A Bx R(A) := closure(KPROTO[Bx]) */
|
||||
OP_CLOSURE,/* A Bx R[A] := closure(KPROTO[Bx]) */
|
||||
|
||||
OP_VARARG,/* A C R(A), R(A+1), ..., R(A+C-2) = vararg */
|
||||
OP_VARARG,/* A C R[A], R[A+1], ..., R[A+C-2] = vararg */
|
||||
|
||||
OP_VARARGPREP,/*A (adjust vararg parameters) */
|
||||
OP_VARARGPREP,/*A (adjust vararg parameters) */
|
||||
|
||||
OP_EXTRAARG/* Ax extra (larger) argument for previous opcode */
|
||||
} OpCode;
|
||||
@@ -312,6 +316,18 @@ OP_EXTRAARG/* Ax extra (larger) argument for previous opcode */
|
||||
|
||||
/*===========================================================================
|
||||
Notes:
|
||||
|
||||
(*) Opcode OP_LFALSESKIP is used to convert a condition to a boolean
|
||||
value, in a code equivalent to (not cond ? false : true). (It
|
||||
produces false and skips the next instruction producing true.)
|
||||
|
||||
(*) Opcodes OP_MMBIN and variants follow each arithmetic and
|
||||
bitwise opcode. If the operation succeeds, it skips this next
|
||||
opcode. Otherwise, this opcode calls the corresponding metamethod.
|
||||
|
||||
(*) Opcode OP_TESTSET is used in short-circuit expressions that need
|
||||
both to jump and to produce a value, such as (a = b or c).
|
||||
|
||||
(*) In OP_CALL, if (B == 0) then B = top - A. If (C == 0), then
|
||||
'top' is set to last_result+1, so next open instruction (OP_CALL,
|
||||
OP_RETURN*, OP_SETLIST) may use 'top'.
|
||||
@@ -321,24 +337,33 @@ OP_EXTRAARG/* Ax extra (larger) argument for previous opcode */
|
||||
|
||||
(*) In OP_RETURN, if (B == 0) then return up to 'top'.
|
||||
|
||||
(*) In OP_SETLIST, if (B == 0) then real B = 'top'; if (C == 0) then
|
||||
next 'instruction' is EXTRAARG(real C).
|
||||
(*) In OP_LOADKX and OP_NEWTABLE, the next instruction is always
|
||||
OP_EXTRAARG.
|
||||
|
||||
(*) In OP_LOADKX, the next 'instruction' is always EXTRAARG.
|
||||
(*) In OP_SETLIST, if (B == 0) then real B = 'top'; if k, then
|
||||
real C = EXTRAARG _ C (the bits of EXTRAARG concatenated with the
|
||||
bits of C).
|
||||
|
||||
(*) In OP_NEWTABLE, B is log2 of the hash size (which is always a
|
||||
power of 2) plus 1, or zero for size zero. If not k, the array size
|
||||
is C. Otherwise, the array size is EXTRAARG _ C.
|
||||
|
||||
(*) For comparisons, k specifies what condition the test should accept
|
||||
(true or false).
|
||||
|
||||
(*) In OP_MMBINI/OP_MMBINK, k means the arguments were flipped
|
||||
(the constant is the first operand).
|
||||
|
||||
(*) All 'skips' (pc++) assume that next instruction is a jump.
|
||||
|
||||
(*) In instructions OP_RETURN/OP_TAILCALL, 'k' specifies that the
|
||||
function either builds upvalues, which may need to be closed, or is
|
||||
vararg, which must be corrected before returning. When 'k' is true,
|
||||
C > 0 means the function is vararg and (C - 1) is its number of
|
||||
fixed parameters.
|
||||
function builds upvalues, which may need to be closed. C > 0 means
|
||||
the function is vararg, so that its 'func' must be corrected before
|
||||
returning; in this case, (C - 1) is its number of fixed parameters.
|
||||
|
||||
(*) In comparisons with an immediate operand, C signals whether the
|
||||
original operand was a float.
|
||||
original operand was a float. (It must be corrected in case of
|
||||
metamethods.)
|
||||
|
||||
===========================================================================*/
|
||||
|
||||
@@ -350,6 +375,7 @@ OP_EXTRAARG/* Ax extra (larger) argument for previous opcode */
|
||||
** bit 4: operator is a test (next instruction must be a jump)
|
||||
** bit 5: instruction uses 'L->top' set by previous instruction (when B == 0)
|
||||
** bit 6: instruction sets 'L->top' for next instruction (when C == 0)
|
||||
** bit 7: instruction is an MM instruction (call a metamethod)
|
||||
*/
|
||||
|
||||
LUAI_DDEC(const lu_byte luaP_opmodes[NUM_OPCODES];)
|
||||
@@ -359,6 +385,7 @@ LUAI_DDEC(const lu_byte luaP_opmodes[NUM_OPCODES];)
|
||||
#define testTMode(m) (luaP_opmodes[m] & (1 << 4))
|
||||
#define testITMode(m) (luaP_opmodes[m] & (1 << 5))
|
||||
#define testOTMode(m) (luaP_opmodes[m] & (1 << 6))
|
||||
#define testMMMode(m) (luaP_opmodes[m] & (1 << 7))
|
||||
|
||||
/* "out top" (set top for next instruction) */
|
||||
#define isOT(i) \
|
||||
@@ -368,11 +395,11 @@ LUAI_DDEC(const lu_byte luaP_opmodes[NUM_OPCODES];)
|
||||
/* "in top" (uses top from previous instruction) */
|
||||
#define isIT(i) (testITMode(GET_OPCODE(i)) && GETARG_B(i) == 0)
|
||||
|
||||
#define opmode(ot,it,t,a,m) (((ot)<<6) | ((it)<<5) | ((t)<<4) | ((a)<<3) | (m))
|
||||
#define opmode(mm,ot,it,t,a,m) \
|
||||
(((mm) << 7) | ((ot) << 6) | ((it) << 5) | ((t) << 4) | ((a) << 3) | (m))
|
||||
|
||||
|
||||
/* number of list items to accumulate before a SETLIST instruction */
|
||||
#define LFIELDS_PER_FLUSH 50
|
||||
|
||||
|
||||
#endif
|
||||
|
||||
+9
-7
@@ -7,6 +7,9 @@
|
||||
#if !defined(lopnames_h)
|
||||
#define lopnames_h
|
||||
|
||||
#include <stddef.h>
|
||||
|
||||
|
||||
/* ORDER OP */
|
||||
|
||||
static const char *const opnames[] = {
|
||||
@@ -15,7 +18,9 @@ static const char *const opnames[] = {
|
||||
"LOADF",
|
||||
"LOADK",
|
||||
"LOADKX",
|
||||
"LOADBOOL",
|
||||
"LOADFALSE",
|
||||
"LFALSESKIP",
|
||||
"LOADTRUE",
|
||||
"LOADNIL",
|
||||
"GETUPVAL",
|
||||
"SETUPVAL",
|
||||
@@ -30,12 +35,6 @@ static const char *const opnames[] = {
|
||||
"NEWTABLE",
|
||||
"SELF",
|
||||
"ADDI",
|
||||
"SUBI",
|
||||
"MULI",
|
||||
"MODI",
|
||||
"POWI",
|
||||
"DIVI",
|
||||
"IDIVI",
|
||||
"ADDK",
|
||||
"SUBK",
|
||||
"MULK",
|
||||
@@ -60,6 +59,9 @@ static const char *const opnames[] = {
|
||||
"BXOR",
|
||||
"SHL",
|
||||
"SHR",
|
||||
"MMBIN",
|
||||
"MMBINI",
|
||||
"MMBINK",
|
||||
"UNM",
|
||||
"BNOT",
|
||||
"NOT",
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
#include "lprefix.h"
|
||||
|
||||
|
||||
#include <errno.h>
|
||||
#include <locale.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
@@ -58,18 +59,20 @@
|
||||
** ===================================================================
|
||||
*/
|
||||
|
||||
#if !defined(l_time_t) /* { */
|
||||
/*
|
||||
** type to represent time_t in Lua
|
||||
*/
|
||||
#if !defined(LUA_NUMTIME) /* { */
|
||||
|
||||
#define l_timet lua_Integer
|
||||
#define l_pushtime(L,t) lua_pushinteger(L,(lua_Integer)(t))
|
||||
#define l_gettime(L,arg) luaL_checkinteger(L, arg)
|
||||
|
||||
static time_t l_checktime (lua_State *L, int arg) {
|
||||
lua_Integer t = luaL_checkinteger(L, arg);
|
||||
luaL_argcheck(L, (time_t)t == t, arg, "time out-of-bounds");
|
||||
return (time_t)t;
|
||||
}
|
||||
#else /* }{ */
|
||||
|
||||
#define l_timet lua_Number
|
||||
#define l_pushtime(L,t) lua_pushnumber(L,(lua_Number)(t))
|
||||
#define l_gettime(L,arg) luaL_checknumber(L, arg)
|
||||
|
||||
#endif /* } */
|
||||
|
||||
@@ -89,7 +92,7 @@ static time_t l_checktime (lua_State *L, int arg) {
|
||||
|
||||
/* ISO C definitions */
|
||||
#define l_gmtime(t,r) ((void)(r)->tm_sec, gmtime(t))
|
||||
#define l_localtime(t,r) ((void)(r)->tm_sec, localtime(t))
|
||||
#define l_localtime(t,r) ((void)(r)->tm_sec, localtime(t))
|
||||
|
||||
#endif /* } */
|
||||
|
||||
@@ -136,10 +139,11 @@ static time_t l_checktime (lua_State *L, int arg) {
|
||||
|
||||
|
||||
|
||||
|
||||
static int os_execute (lua_State *L) {
|
||||
const char *cmd = luaL_optstring(L, 1, NULL);
|
||||
int stat = system(cmd);
|
||||
int stat;
|
||||
errno = 0;
|
||||
stat = system(cmd);
|
||||
if (cmd != NULL)
|
||||
return luaL_execresult(L, stat);
|
||||
else {
|
||||
@@ -166,7 +170,7 @@ static int os_tmpname (lua_State *L) {
|
||||
char buff[LUA_TMPNAMBUFSIZE];
|
||||
int err;
|
||||
lua_tmpnam(buff, err);
|
||||
if (err)
|
||||
if (l_unlikely(err))
|
||||
return luaL_error(L, "unable to generate a unique filename");
|
||||
lua_pushstring(L, buff);
|
||||
return 1;
|
||||
@@ -193,11 +197,25 @@ static int os_clock (lua_State *L) {
|
||||
** =======================================================
|
||||
*/
|
||||
|
||||
static void setfield (lua_State *L, const char *key, int value) {
|
||||
lua_pushinteger(L, value);
|
||||
/*
|
||||
** About the overflow check: an overflow cannot occur when time
|
||||
** is represented by a lua_Integer, because either lua_Integer is
|
||||
** large enough to represent all int fields or it is not large enough
|
||||
** to represent a time that cause a field to overflow. However, if
|
||||
** times are represented as doubles and lua_Integer is int, then the
|
||||
** time 0x1.e1853b0d184f6p+55 would cause an overflow when adding 1900
|
||||
** to compute the year.
|
||||
*/
|
||||
static void setfield (lua_State *L, const char *key, int value, int delta) {
|
||||
#if (defined(LUA_NUMTIME) && LUA_MAXINTEGER <= INT_MAX)
|
||||
if (l_unlikely(value > LUA_MAXINTEGER - delta))
|
||||
luaL_error(L, "field '%s' is out-of-bound", key);
|
||||
#endif
|
||||
lua_pushinteger(L, (lua_Integer)value + delta);
|
||||
lua_setfield(L, -2, key);
|
||||
}
|
||||
|
||||
|
||||
static void setboolfield (lua_State *L, const char *key, int value) {
|
||||
if (value < 0) /* undefined? */
|
||||
return; /* does not set field */
|
||||
@@ -210,14 +228,14 @@ static void setboolfield (lua_State *L, const char *key, int value) {
|
||||
** Set all fields from structure 'tm' in the table on top of the stack
|
||||
*/
|
||||
static void setallfields (lua_State *L, struct tm *stm) {
|
||||
setfield(L, "sec", stm->tm_sec);
|
||||
setfield(L, "min", stm->tm_min);
|
||||
setfield(L, "hour", stm->tm_hour);
|
||||
setfield(L, "day", stm->tm_mday);
|
||||
setfield(L, "month", stm->tm_mon + 1);
|
||||
setfield(L, "year", stm->tm_year + 1900);
|
||||
setfield(L, "wday", stm->tm_wday + 1);
|
||||
setfield(L, "yday", stm->tm_yday + 1);
|
||||
setfield(L, "year", stm->tm_year, 1900);
|
||||
setfield(L, "month", stm->tm_mon, 1);
|
||||
setfield(L, "day", stm->tm_mday, 0);
|
||||
setfield(L, "hour", stm->tm_hour, 0);
|
||||
setfield(L, "min", stm->tm_min, 0);
|
||||
setfield(L, "sec", stm->tm_sec, 0);
|
||||
setfield(L, "yday", stm->tm_yday, 1);
|
||||
setfield(L, "wday", stm->tm_wday, 1);
|
||||
setboolfield(L, "isdst", stm->tm_isdst);
|
||||
}
|
||||
|
||||
@@ -230,24 +248,21 @@ static int getboolfield (lua_State *L, const char *key) {
|
||||
}
|
||||
|
||||
|
||||
/* maximum value for date fields (to avoid arithmetic overflows with 'int') */
|
||||
#if !defined(L_MAXDATEFIELD)
|
||||
#define L_MAXDATEFIELD (INT_MAX / 2)
|
||||
#endif
|
||||
|
||||
static int getfield (lua_State *L, const char *key, int d, int delta) {
|
||||
int isnum;
|
||||
int t = lua_getfield(L, -1, key); /* get field and its type */
|
||||
lua_Integer res = lua_tointegerx(L, -1, &isnum);
|
||||
if (!isnum) { /* field is not an integer? */
|
||||
if (t != LUA_TNIL) /* some other value? */
|
||||
if (l_unlikely(t != LUA_TNIL)) /* some other value? */
|
||||
return luaL_error(L, "field '%s' is not an integer", key);
|
||||
else if (d < 0) /* absent field; no default? */
|
||||
else if (l_unlikely(d < 0)) /* absent field; no default? */
|
||||
return luaL_error(L, "field '%s' missing in date table", key);
|
||||
res = d;
|
||||
}
|
||||
else {
|
||||
if (!(-L_MAXDATEFIELD <= res && res <= L_MAXDATEFIELD))
|
||||
/* unsigned avoids overflow when lua_Integer has 32 bits */
|
||||
if (!(res >= 0 ? (lua_Unsigned)res <= (lua_Unsigned)INT_MAX + delta
|
||||
: (lua_Integer)INT_MIN + delta <= res))
|
||||
return luaL_error(L, "field '%s' is out-of-bound", key);
|
||||
res -= delta;
|
||||
}
|
||||
@@ -275,6 +290,13 @@ static const char *checkoption (lua_State *L, const char *conv,
|
||||
}
|
||||
|
||||
|
||||
static time_t l_checktime (lua_State *L, int arg) {
|
||||
l_timet t = l_gettime(L, arg);
|
||||
luaL_argcheck(L, (time_t)t == t, arg, "time out-of-bounds");
|
||||
return (time_t)t;
|
||||
}
|
||||
|
||||
|
||||
/* maximum size for an individual 'strftime' item */
|
||||
#define SIZETIMEFMT 250
|
||||
|
||||
@@ -293,7 +315,7 @@ static int os_date (lua_State *L) {
|
||||
stm = l_localtime(&t, &tmr);
|
||||
if (stm == NULL) /* invalid date? */
|
||||
return luaL_error(L,
|
||||
"time result cannot be represented in this installation");
|
||||
"date result cannot be represented in this installation");
|
||||
if (strcmp(s, "*t") == 0) {
|
||||
lua_createtable(L, 0, 9); /* 9 = number of fields */
|
||||
setallfields(L, stm);
|
||||
@@ -329,12 +351,12 @@ static int os_time (lua_State *L) {
|
||||
struct tm ts;
|
||||
luaL_checktype(L, 1, LUA_TTABLE);
|
||||
lua_settop(L, 1); /* make sure table is at the top */
|
||||
ts.tm_sec = getfield(L, "sec", 0, 0);
|
||||
ts.tm_min = getfield(L, "min", 0, 0);
|
||||
ts.tm_hour = getfield(L, "hour", 12, 0);
|
||||
ts.tm_mday = getfield(L, "day", -1, 0);
|
||||
ts.tm_mon = getfield(L, "month", -1, 1);
|
||||
ts.tm_year = getfield(L, "year", -1, 1900);
|
||||
ts.tm_mon = getfield(L, "month", -1, 1);
|
||||
ts.tm_mday = getfield(L, "day", -1, 0);
|
||||
ts.tm_hour = getfield(L, "hour", 12, 0);
|
||||
ts.tm_min = getfield(L, "min", 0, 0);
|
||||
ts.tm_sec = getfield(L, "sec", 0, 0);
|
||||
ts.tm_isdst = getboolfield(L, "isdst");
|
||||
t = mktime(&ts);
|
||||
setallfields(L, &ts); /* update fields with normalized values */
|
||||
|
||||
@@ -23,18 +23,23 @@
|
||||
|
||||
/* kinds of variables/expressions */
|
||||
typedef enum {
|
||||
VVOID, /* when 'expdesc' describes the last expression a list,
|
||||
VVOID, /* when 'expdesc' describes the last expression of a list,
|
||||
this kind means an empty list (so, no expression) */
|
||||
VNIL, /* constant nil */
|
||||
VTRUE, /* constant true */
|
||||
VFALSE, /* constant false */
|
||||
VK, /* constant in 'k'; info = index of constant in 'k' */
|
||||
VKFLT, /* floating constant; nval = numerical float value */
|
||||
VKINT, /* integer constant; nval = numerical integer value */
|
||||
VKINT, /* integer constant; ival = numerical integer value */
|
||||
VKSTR, /* string constant; strval = TString address;
|
||||
(string is fixed by the lexer) */
|
||||
VNONRELOC, /* expression has its value in a fixed register;
|
||||
info = result register */
|
||||
VLOCAL, /* local variable; var.idx = local register */
|
||||
VUPVAL, /* upvalue variable; var.idx = index of upvalue in 'upvalues' */
|
||||
VLOCAL, /* local variable; var.ridx = register index;
|
||||
var.vidx = relative index in 'actvar.arr' */
|
||||
VUPVAL, /* upvalue variable; info = index of upvalue in 'upvalues' */
|
||||
VCONST, /* compile-time <const> variable;
|
||||
info = absolute index in 'actvar.arr' */
|
||||
VINDEXED, /* indexed variable;
|
||||
ind.t = table register;
|
||||
ind.idx = key's R index */
|
||||
@@ -65,13 +70,15 @@ typedef struct expdesc {
|
||||
union {
|
||||
lua_Integer ival; /* for VKINT */
|
||||
lua_Number nval; /* for VKFLT */
|
||||
TString *strval; /* for VKSTR */
|
||||
int info; /* for generic use */
|
||||
struct { /* for indexed variables */
|
||||
short idx; /* index (R or "long" K) */
|
||||
lu_byte t; /* table (register or upvalue) */
|
||||
} ind;
|
||||
struct { /* for local variables and upvalues */
|
||||
lu_byte idx; /* index of the variable */
|
||||
struct { /* for local variables */
|
||||
lu_byte ridx; /* register holding the variable */
|
||||
unsigned short vidx; /* compiler index (in 'actvar.arr') */
|
||||
} var;
|
||||
} u;
|
||||
int t; /* patch list of 'exit when true' */
|
||||
@@ -79,20 +86,32 @@ typedef struct expdesc {
|
||||
} expdesc;
|
||||
|
||||
|
||||
/* kinds of variables */
|
||||
#define VDKREG 0 /* regular */
|
||||
#define RDKCONST 1 /* constant */
|
||||
#define RDKTOCLOSE 2 /* to-be-closed */
|
||||
#define RDKCTC 3 /* compile-time constant */
|
||||
|
||||
/* description of an active local variable */
|
||||
typedef struct Vardesc {
|
||||
TString *name;
|
||||
short idx; /* index of the variable in the Proto's 'locvars' array */
|
||||
lu_byte ro; /* true if variable is 'const' */
|
||||
typedef union Vardesc {
|
||||
struct {
|
||||
TValuefields; /* constant value (if it is a compile-time constant) */
|
||||
lu_byte kind;
|
||||
lu_byte ridx; /* register holding the variable */
|
||||
short pidx; /* index of the variable in the Proto's 'locvars' array */
|
||||
TString *name; /* variable name */
|
||||
} vd;
|
||||
TValue k; /* constant value (if any) */
|
||||
} Vardesc;
|
||||
|
||||
|
||||
|
||||
/* description of pending goto statements and label statements */
|
||||
typedef struct Labeldesc {
|
||||
TString *name; /* label identifier */
|
||||
int pc; /* position in code */
|
||||
int line; /* line where it appeared */
|
||||
lu_byte nactvar; /* local level where it appears in current block */
|
||||
lu_byte nactvar; /* number of active variables in that position */
|
||||
lu_byte close; /* goto that escapes upvalues */
|
||||
} Labeldesc;
|
||||
|
||||
@@ -107,7 +126,7 @@ typedef struct Labellist {
|
||||
|
||||
/* dynamic structures used by the parser */
|
||||
typedef struct Dyndata {
|
||||
struct { /* list of active local variables */
|
||||
struct { /* list of all active local variables */
|
||||
Vardesc *arr;
|
||||
int n;
|
||||
int size;
|
||||
@@ -135,7 +154,7 @@ typedef struct FuncState {
|
||||
int nabslineinfo; /* number of elements in 'abslineinfo' */
|
||||
int firstlocal; /* index of first local var (in Dyndata array) */
|
||||
int firstlabel; /* index of first label (in 'dyd->label->arr') */
|
||||
short nlocvars; /* number of elements in 'f->locvars' */
|
||||
short ndebugvars; /* number of elements in 'f->locvars' */
|
||||
lu_byte nactvar; /* number of active local variables */
|
||||
lu_byte nups; /* number of upvalues */
|
||||
lu_byte freereg; /* first free register */
|
||||
@@ -144,6 +163,7 @@ typedef struct FuncState {
|
||||
} FuncState;
|
||||
|
||||
|
||||
LUAI_FUNC int luaY_nvarstack (FuncState *fs);
|
||||
LUAI_FUNC LClosure *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff,
|
||||
Dyndata *dyd, const char *name, int firstchar);
|
||||
|
||||
|
||||
@@ -33,7 +33,7 @@
|
||||
/*
|
||||
** Windows stuff
|
||||
*/
|
||||
#if defined(_WIN32) /* { */
|
||||
#if defined(_WIN32) /* { */
|
||||
|
||||
#if !defined(_CRT_SECURE_NO_WARNINGS)
|
||||
#define _CRT_SECURE_NO_WARNINGS /* avoid warnings about ISO C functions */
|
||||
|
||||
@@ -96,45 +96,15 @@ void luaE_setdebt (global_State *g, l_mem debt) {
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** Increment count of "C calls" and check for overflows. In case of
|
||||
** a stack overflow, check appropriate error ("regular" overflow or
|
||||
** overflow while handling stack overflow).
|
||||
** If 'nCcalls' is larger than LUAI_MAXCSTACK but smaller than
|
||||
** LUAI_MAXCSTACK + CSTACKCF (plus 2 to avoid by-one errors), it means
|
||||
** it has just entered the "overflow zone", so the function raises an
|
||||
** overflow error.
|
||||
** If 'nCcalls' is larger than LUAI_MAXCSTACK + CSTACKCF + 2
|
||||
** (which means it is already handling an overflow) but smaller than
|
||||
** 9/8 of LUAI_MAXCSTACK, does not report an error (to allow message
|
||||
** handling to work).
|
||||
** Otherwise, report a stack overflow while handling a stack overflow
|
||||
** (probably caused by a repeating error in the message handling
|
||||
** function).
|
||||
*/
|
||||
void luaE_enterCcall (lua_State *L) {
|
||||
int ncalls = getCcalls(L);
|
||||
L->nCcalls++;
|
||||
if (ncalls >= LUAI_MAXCSTACK) { /* possible overflow? */
|
||||
luaE_freeCI(L); /* release unused CIs */
|
||||
ncalls = getCcalls(L); /* update call count */
|
||||
if (ncalls >= LUAI_MAXCSTACK) { /* still overflow? */
|
||||
if (ncalls <= LUAI_MAXCSTACK + CSTACKCF + 2) {
|
||||
/* no error before increments; raise the error now */
|
||||
L->nCcalls += (CSTACKCF + 4); /* avoid raising it again */
|
||||
luaG_runerror(L, "C stack overflow");
|
||||
}
|
||||
else if (ncalls >= (LUAI_MAXCSTACK + (LUAI_MAXCSTACK >> 3)))
|
||||
luaD_throw(L, LUA_ERRERR); /* error while handling stack error */
|
||||
}
|
||||
}
|
||||
LUA_API int lua_setcstacklimit (lua_State *L, unsigned int limit) {
|
||||
UNUSED(L); UNUSED(limit);
|
||||
return LUAI_MAXCCALLS; /* warning?? */
|
||||
}
|
||||
|
||||
|
||||
CallInfo *luaE_extendCI (lua_State *L) {
|
||||
CallInfo *ci;
|
||||
lua_assert(L->ci->next == NULL);
|
||||
luaE_enterCcall(L);
|
||||
ci = luaM_new(L, CallInfo);
|
||||
lua_assert(L->ci->next == NULL);
|
||||
L->ci->next = ci;
|
||||
@@ -153,44 +123,69 @@ void luaE_freeCI (lua_State *L) {
|
||||
CallInfo *ci = L->ci;
|
||||
CallInfo *next = ci->next;
|
||||
ci->next = NULL;
|
||||
L->nCcalls -= L->nci; /* subtract removed elements from 'nCcalls' */
|
||||
while ((ci = next) != NULL) {
|
||||
next = ci->next;
|
||||
luaM_free(L, ci);
|
||||
L->nci--;
|
||||
}
|
||||
L->nCcalls += L->nci; /* adjust result */
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** free half of the CallInfo structures not in use by a thread
|
||||
** free half of the CallInfo structures not in use by a thread,
|
||||
** keeping the first one.
|
||||
*/
|
||||
void luaE_shrinkCI (lua_State *L) {
|
||||
CallInfo *ci = L->ci;
|
||||
CallInfo *next2; /* next's next */
|
||||
L->nCcalls -= L->nci; /* subtract removed elements from 'nCcalls' */
|
||||
/* while there are two nexts */
|
||||
while (ci->next != NULL && (next2 = ci->next->next) != NULL) {
|
||||
luaM_free(L, ci->next); /* free next */
|
||||
CallInfo *ci = L->ci->next; /* first free CallInfo */
|
||||
CallInfo *next;
|
||||
if (ci == NULL)
|
||||
return; /* no extra elements */
|
||||
while ((next = ci->next) != NULL) { /* two extra elements? */
|
||||
CallInfo *next2 = next->next; /* next's next */
|
||||
ci->next = next2; /* remove next from the list */
|
||||
L->nci--;
|
||||
ci->next = next2; /* remove 'next' from the list */
|
||||
next2->previous = ci;
|
||||
ci = next2; /* keep next's next */
|
||||
luaM_free(L, next); /* free next */
|
||||
if (next2 == NULL)
|
||||
break; /* no more elements */
|
||||
else {
|
||||
next2->previous = ci;
|
||||
ci = next2; /* continue */
|
||||
}
|
||||
}
|
||||
L->nCcalls += L->nci; /* adjust result */
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** Called when 'getCcalls(L)' larger or equal to LUAI_MAXCCALLS.
|
||||
** If equal, raises an overflow error. If value is larger than
|
||||
** LUAI_MAXCCALLS (which means it is handling an overflow) but
|
||||
** not much larger, does not report an error (to allow overflow
|
||||
** handling to work).
|
||||
*/
|
||||
void luaE_checkcstack (lua_State *L) {
|
||||
if (getCcalls(L) == LUAI_MAXCCALLS)
|
||||
luaG_runerror(L, "C stack overflow");
|
||||
else if (getCcalls(L) >= (LUAI_MAXCCALLS / 10 * 11))
|
||||
luaD_throw(L, LUA_ERRERR); /* error while handling stack error */
|
||||
}
|
||||
|
||||
|
||||
LUAI_FUNC void luaE_incCstack (lua_State *L) {
|
||||
L->nCcalls++;
|
||||
if (l_unlikely(getCcalls(L) >= LUAI_MAXCCALLS))
|
||||
luaE_checkcstack(L);
|
||||
}
|
||||
|
||||
|
||||
static void stack_init (lua_State *L1, lua_State *L) {
|
||||
int i; CallInfo *ci;
|
||||
/* initialize stack array */
|
||||
L1->stack = luaM_newvector(L, BASIC_STACK_SIZE, StackValue);
|
||||
L1->stacksize = BASIC_STACK_SIZE;
|
||||
for (i = 0; i < BASIC_STACK_SIZE; i++)
|
||||
L1->stack = luaM_newvector(L, BASIC_STACK_SIZE + EXTRA_STACK, StackValue);
|
||||
L1->tbclist = L1->stack;
|
||||
for (i = 0; i < BASIC_STACK_SIZE + EXTRA_STACK; i++)
|
||||
setnilvalue(s2v(L1->stack + i)); /* erase new stack */
|
||||
L1->top = L1->stack;
|
||||
L1->stack_last = L1->stack + L1->stacksize - EXTRA_STACK;
|
||||
L1->stack_last = L1->stack + BASIC_STACK_SIZE;
|
||||
/* initialize first ci */
|
||||
ci = &L1->base_ci;
|
||||
ci->next = ci->previous = NULL;
|
||||
@@ -211,7 +206,7 @@ static void freestack (lua_State *L) {
|
||||
L->ci = &L->base_ci; /* free the entire 'ci' list */
|
||||
luaE_freeCI(L);
|
||||
lua_assert(L->nci == 0);
|
||||
luaM_freearray(L, L->stack, L->stacksize); /* free stack array */
|
||||
luaM_freearray(L, L->stack, stacksize(L) + EXTRA_STACK); /* free stack */
|
||||
}
|
||||
|
||||
|
||||
@@ -219,24 +214,19 @@ static void freestack (lua_State *L) {
|
||||
** Create registry table and its predefined values
|
||||
*/
|
||||
static void init_registry (lua_State *L, global_State *g) {
|
||||
TValue temp;
|
||||
/* create registry */
|
||||
Table *registry = luaH_new(L);
|
||||
sethvalue(L, &g->l_registry, registry);
|
||||
luaH_resize(L, registry, LUA_RIDX_LAST, 0);
|
||||
/* registry[LUA_RIDX_MAINTHREAD] = L */
|
||||
setthvalue(L, &temp, L); /* temp = L */
|
||||
luaH_setint(L, registry, LUA_RIDX_MAINTHREAD, &temp);
|
||||
/* registry[LUA_RIDX_GLOBALS] = table of globals */
|
||||
sethvalue(L, &temp, luaH_new(L)); /* temp = new table (global table) */
|
||||
luaH_setint(L, registry, LUA_RIDX_GLOBALS, &temp);
|
||||
setthvalue(L, ®istry->array[LUA_RIDX_MAINTHREAD - 1], L);
|
||||
/* registry[LUA_RIDX_GLOBALS] = new table (table of globals) */
|
||||
sethvalue(L, ®istry->array[LUA_RIDX_GLOBALS - 1], luaH_new(L));
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** open parts of the state that may cause memory-allocation errors.
|
||||
** ('g->nilvalue' being a nil value flags that the state was completely
|
||||
** build.)
|
||||
*/
|
||||
static void f_luaopen (lua_State *L, void *ud) {
|
||||
global_State *g = G(L);
|
||||
@@ -246,8 +236,8 @@ static void f_luaopen (lua_State *L, void *ud) {
|
||||
luaS_init(L);
|
||||
luaT_init(L);
|
||||
luaX_init(L);
|
||||
g->gcrunning = 1; /* allow gc */
|
||||
setnilvalue(&g->nilvalue);
|
||||
g->gcstp = 0; /* allow gc */
|
||||
setnilvalue(&g->nilvalue); /* now state is complete */
|
||||
luai_userstateopen(L);
|
||||
}
|
||||
|
||||
@@ -261,10 +251,9 @@ static void preinit_thread (lua_State *L, global_State *g) {
|
||||
L->stack = NULL;
|
||||
L->ci = NULL;
|
||||
L->nci = 0;
|
||||
L->stacksize = 0;
|
||||
L->twups = L; /* thread has no upvalues */
|
||||
L->errorJmp = NULL;
|
||||
L->nCcalls = 0;
|
||||
L->errorJmp = NULL;
|
||||
L->hook = NULL;
|
||||
L->hookmask = 0;
|
||||
L->basehookcount = 0;
|
||||
@@ -273,15 +262,20 @@ static void preinit_thread (lua_State *L, global_State *g) {
|
||||
L->openupval = NULL;
|
||||
L->status = LUA_OK;
|
||||
L->errfunc = 0;
|
||||
L->oldpc = 0;
|
||||
}
|
||||
|
||||
|
||||
static void close_state (lua_State *L) {
|
||||
global_State *g = G(L);
|
||||
luaF_close(L, L->stack, CLOSEPROTECT); /* close all upvalues */
|
||||
luaC_freeallobjects(L); /* collect all objects */
|
||||
if (ttisnil(&g->nilvalue)) /* closing a fully built state? */
|
||||
if (!completestate(g)) /* closing a partially built state? */
|
||||
luaC_freeallobjects(L); /* just collect its objects */
|
||||
else { /* closing a fully built state */
|
||||
L->ci = &L->base_ci; /* unwind CallInfo list */
|
||||
luaD_closeprotected(L, 1, LUA_OK); /* close all upvalues */
|
||||
luaC_freeallobjects(L); /* collect all objects */
|
||||
luai_userstateclose(L);
|
||||
}
|
||||
luaM_freearray(L, G(L)->strt.hash, G(L)->strt.size);
|
||||
freestack(L);
|
||||
lua_assert(gettotalbytes(g) == sizeof(LG));
|
||||
@@ -290,14 +284,15 @@ static void close_state (lua_State *L) {
|
||||
|
||||
|
||||
LUA_API lua_State *lua_newthread (lua_State *L) {
|
||||
global_State *g = G(L);
|
||||
global_State *g;
|
||||
lua_State *L1;
|
||||
lua_lock(L);
|
||||
g = G(L);
|
||||
luaC_checkGC(L);
|
||||
/* create new thread */
|
||||
L1 = &cast(LX *, luaM_newobject(L, LUA_TTHREAD, sizeof(LX)))->l;
|
||||
L1->marked = luaC_white(g);
|
||||
L1->tt = LUA_TTHREAD;
|
||||
L1->tt = LUA_VTHREAD;
|
||||
/* link it on list 'allgc' */
|
||||
L1->next = g->allgc;
|
||||
g->allgc = obj2gco(L1);
|
||||
@@ -321,7 +316,7 @@ LUA_API lua_State *lua_newthread (lua_State *L) {
|
||||
|
||||
void luaE_freethread (lua_State *L, lua_State *L1) {
|
||||
LX *l = fromstate(L1);
|
||||
luaF_close(L1, L1->stack, NOCLOSINGMETH); /* close all upvalues */
|
||||
luaF_closeupval(L1, L1->stack); /* close all upvalues */
|
||||
lua_assert(L1->openupval == NULL);
|
||||
luai_userstatefree(L, L1);
|
||||
freestack(L1);
|
||||
@@ -329,24 +324,29 @@ void luaE_freethread (lua_State *L, lua_State *L1) {
|
||||
}
|
||||
|
||||
|
||||
int lua_resetthread (lua_State *L) {
|
||||
CallInfo *ci;
|
||||
int luaE_resetthread (lua_State *L, int status) {
|
||||
CallInfo *ci = L->ci = &L->base_ci; /* unwind CallInfo list */
|
||||
setnilvalue(s2v(L->stack)); /* 'function' entry for basic 'ci' */
|
||||
ci->func = L->stack;
|
||||
ci->callstatus = CIST_C;
|
||||
if (status == LUA_YIELD)
|
||||
status = LUA_OK;
|
||||
L->status = LUA_OK; /* so it can run __close metamethods */
|
||||
status = luaD_closeprotected(L, 1, status);
|
||||
if (status != LUA_OK) /* errors? */
|
||||
luaD_seterrorobj(L, status, L->stack + 1);
|
||||
else
|
||||
L->top = L->stack + 1;
|
||||
ci->top = L->top + LUA_MINSTACK;
|
||||
luaD_reallocstack(L, cast_int(ci->top - L->stack), 0);
|
||||
return status;
|
||||
}
|
||||
|
||||
|
||||
LUA_API int lua_resetthread (lua_State *L) {
|
||||
int status;
|
||||
lua_lock(L);
|
||||
ci = &L->base_ci;
|
||||
status = luaF_close(L, L->stack, CLOSEPROTECT);
|
||||
setnilvalue(s2v(L->stack)); /* 'function' entry for basic 'ci' */
|
||||
if (status != CLOSEPROTECT) /* real errors? */
|
||||
luaD_seterrorobj(L, status, L->stack + 1);
|
||||
else {
|
||||
status = LUA_OK;
|
||||
L->top = L->stack + 1;
|
||||
}
|
||||
ci->callstatus = CIST_C;
|
||||
ci->func = L->stack;
|
||||
ci->top = L->top + LUA_MINSTACK;
|
||||
L->ci = ci;
|
||||
L->status = status;
|
||||
status = luaE_resetthread(L, L->status);
|
||||
lua_unlock(L);
|
||||
return status;
|
||||
}
|
||||
@@ -360,29 +360,31 @@ LUA_API lua_State *lua_newstate (lua_Alloc f, void *ud) {
|
||||
if (l == NULL) return NULL;
|
||||
L = &l->l.l;
|
||||
g = &l->g;
|
||||
L->tt = LUA_TTHREAD;
|
||||
L->tt = LUA_VTHREAD;
|
||||
g->currentwhite = bitmask(WHITE0BIT);
|
||||
L->marked = luaC_white(g);
|
||||
preinit_thread(L, g);
|
||||
g->allgc = obj2gco(L); /* by now, only object is the main thread */
|
||||
L->next = NULL;
|
||||
incnny(L); /* main thread is always non yieldable */
|
||||
g->frealloc = f;
|
||||
g->ud = ud;
|
||||
g->warnf = NULL;
|
||||
g->ud_warn = NULL;
|
||||
g->mainthread = L;
|
||||
g->seed = luai_makeseed(L);
|
||||
g->gcrunning = 0; /* no GC while building state */
|
||||
g->gcstp = GCSTPGC; /* no GC while building state */
|
||||
g->strt.size = g->strt.nuse = 0;
|
||||
g->strt.hash = NULL;
|
||||
setnilvalue(&g->l_registry);
|
||||
g->panic = NULL;
|
||||
g->gcstate = GCSpause;
|
||||
g->gckind = KGC_INC;
|
||||
g->gcstopem = 0;
|
||||
g->gcemergency = 0;
|
||||
g->finobj = g->tobefnz = g->fixedgc = NULL;
|
||||
g->survival = g->old = g->reallyold = NULL;
|
||||
g->finobjsur = g->finobjold = g->finobjrold = NULL;
|
||||
g->firstold1 = g->survival = g->old1 = g->reallyold = NULL;
|
||||
g->finobjsur = g->finobjold1 = g->finobjrold = NULL;
|
||||
g->sweepgc = NULL;
|
||||
g->gray = g->grayagain = NULL;
|
||||
g->weak = g->ephemeron = g->allweak = NULL;
|
||||
@@ -407,8 +409,8 @@ LUA_API lua_State *lua_newstate (lua_Alloc f, void *ud) {
|
||||
|
||||
|
||||
LUA_API void lua_close (lua_State *L) {
|
||||
L = G(L)->mainthread; /* only the main thread can be closed */
|
||||
lua_lock(L);
|
||||
L = G(L)->mainthread; /* only the main thread can be closed */
|
||||
close_state(L);
|
||||
}
|
||||
|
||||
@@ -420,3 +422,19 @@ void luaE_warning (lua_State *L, const char *msg, int tocont) {
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** Generate a warning from an error message
|
||||
*/
|
||||
void luaE_warnerror (lua_State *L, const char *where) {
|
||||
TValue *errobj = s2v(L->top - 1); /* error object */
|
||||
const char *msg = (ttisstring(errobj))
|
||||
? svalue(errobj)
|
||||
: "error object is not a string";
|
||||
/* produce warning "error in %s (%s)" (where, msg) */
|
||||
luaE_warning(L, "error in ", 1);
|
||||
luaE_warning(L, where, 1);
|
||||
luaE_warning(L, " (", 1);
|
||||
luaE_warning(L, msg, 1);
|
||||
luaE_warning(L, ")", 0);
|
||||
}
|
||||
|
||||
|
||||
@@ -32,13 +32,29 @@
|
||||
**
|
||||
** 'allgc' -> 'survival': new objects;
|
||||
** 'survival' -> 'old': objects that survived one collection;
|
||||
** 'old' -> 'reallyold': objects that became old in last collection;
|
||||
** 'old1' -> 'reallyold': objects that became old in last collection;
|
||||
** 'reallyold' -> NULL: objects old for more than one cycle.
|
||||
**
|
||||
** 'finobj' -> 'finobjsur': new objects marked for finalization;
|
||||
** 'finobjsur' -> 'finobjold': survived """";
|
||||
** 'finobjold' -> 'finobjrold': just old """";
|
||||
** 'finobjsur' -> 'finobjold1': survived """";
|
||||
** 'finobjold1' -> 'finobjrold': just old """";
|
||||
** 'finobjrold' -> NULL: really old """".
|
||||
**
|
||||
** All lists can contain elements older than their main ages, due
|
||||
** to 'luaC_checkfinalizer' and 'udata2finalize', which move
|
||||
** objects between the normal lists and the "marked for finalization"
|
||||
** lists. Moreover, barriers can age young objects in young lists as
|
||||
** OLD0, which then become OLD1. However, a list never contains
|
||||
** elements younger than their main ages.
|
||||
**
|
||||
** The generational collector also uses a pointer 'firstold1', which
|
||||
** points to the first OLD1 object in the list. It is used to optimize
|
||||
** 'markold'. (Potentially OLD1 objects can be anywhere between 'allgc'
|
||||
** and 'reallyold', but often the list has no OLD1 objects or they are
|
||||
** after 'old1'.) Note the difference between it and 'old1':
|
||||
** 'firstold1': no OLD1 objects before this point; there can be all
|
||||
** ages after it.
|
||||
** 'old1': no objects younger than OLD1 after this point.
|
||||
*/
|
||||
|
||||
/*
|
||||
@@ -47,7 +63,7 @@
|
||||
** can become gray have such a field. The field is not the same
|
||||
** in all objects, but it always has this name.) Any gray object
|
||||
** must belong to one of these lists, and all objects in these lists
|
||||
** must be gray:
|
||||
** must be gray (with two exceptions explained below):
|
||||
**
|
||||
** 'gray': regular gray objects, still waiting to be visited.
|
||||
** 'grayagain': objects that must be revisited at the atomic phase.
|
||||
@@ -58,33 +74,26 @@
|
||||
** 'weak': tables with weak values to be cleared;
|
||||
** 'ephemeron': ephemeron tables with white->white entries;
|
||||
** 'allweak': tables with weak keys and/or weak values to be cleared.
|
||||
**
|
||||
** The exceptions to that "gray rule" are:
|
||||
** - TOUCHED2 objects in generational mode stay in a gray list (because
|
||||
** they must be visited again at the end of the cycle), but they are
|
||||
** marked black because assignments to them must activate barriers (to
|
||||
** move them back to TOUCHED1).
|
||||
** - Open upvales are kept gray to avoid barriers, but they stay out
|
||||
** of gray lists. (They don't even have a 'gclist' field.)
|
||||
*/
|
||||
|
||||
|
||||
|
||||
/*
|
||||
** About 'nCcalls': each thread in Lua (a lua_State) keeps a count of
|
||||
** how many "C calls" it can do in the C stack, to avoid C-stack overflow.
|
||||
** This count is very rough approximation; it considers only recursive
|
||||
** functions inside the interpreter, as non-recursive calls can be
|
||||
** considered using a fixed (although unknown) amount of stack space.
|
||||
**
|
||||
** The count itself has two parts: the lower part is the count itself;
|
||||
** the higher part counts the number of non-yieldable calls in the stack.
|
||||
**
|
||||
** Because calls to external C functions can use of unkown amount
|
||||
** of space (e.g., functions using an auxiliary buffer), calls
|
||||
** to these functions add more than one to the count.
|
||||
**
|
||||
** The proper count also includes the number of CallInfo structures
|
||||
** allocated by Lua, as a kind of "potential" calls. So, when Lua
|
||||
** calls a function (and "consumes" one CallInfo), it needs neither to
|
||||
** increment nor to check 'nCcalls', as its use of C stack is already
|
||||
** accounted for.
|
||||
** About 'nCcalls': This count has two parts: the lower 16 bits counts
|
||||
** the number of recursive invocations in the C stack; the higher
|
||||
** 16 bits counts the number of non-yieldable calls in the stack.
|
||||
** (They are together so that we can change and save both with one
|
||||
** instruction.)
|
||||
*/
|
||||
|
||||
/* number of "C stack slots" used by an external C function */
|
||||
#define CSTACKCF 10
|
||||
|
||||
/* true if this thread does not have non-yieldable calls in the stack */
|
||||
#define yieldable(L) (((L)->nCcalls & 0xffff0000) == 0)
|
||||
@@ -99,13 +108,8 @@
|
||||
/* Decrement the number of non-yieldable calls */
|
||||
#define decnny(L) ((L)->nCcalls -= 0x10000)
|
||||
|
||||
/* Increment the number of non-yieldable calls and nCcalls */
|
||||
#define incXCcalls(L) ((L)->nCcalls += 0x10000 + CSTACKCF)
|
||||
|
||||
/* Decrement the number of non-yieldable calls and nCcalls */
|
||||
#define decXCcalls(L) ((L)->nCcalls -= 0x10000 + CSTACKCF)
|
||||
|
||||
|
||||
/* Non-yieldable call increment */
|
||||
#define nyci (0x10000 | 1)
|
||||
|
||||
|
||||
|
||||
@@ -123,12 +127,20 @@ struct lua_longjmp; /* defined in ldo.c */
|
||||
#endif
|
||||
|
||||
|
||||
/* extra stack space to handle TM calls and some other extras */
|
||||
/*
|
||||
** Extra stack space to handle TM calls and some other extras. This
|
||||
** space is not included in 'stack_last'. It is used only to avoid stack
|
||||
** checks, either because the element will be promptly popped or because
|
||||
** there will be a stack check soon after the push. Function frames
|
||||
** never use this extra space, so it does not need to be kept clean.
|
||||
*/
|
||||
#define EXTRA_STACK 5
|
||||
|
||||
|
||||
#define BASIC_STACK_SIZE (2*LUA_MINSTACK)
|
||||
|
||||
#define stacksize(th) cast_int((th)->stack_last - (th)->stack)
|
||||
|
||||
|
||||
/* kinds of Garbage Collection */
|
||||
#define KGC_INC 0 /* incremental gc */
|
||||
@@ -144,6 +156,18 @@ typedef struct stringtable {
|
||||
|
||||
/*
|
||||
** Information about a call.
|
||||
** About union 'u':
|
||||
** - field 'l' is used only for Lua functions;
|
||||
** - field 'c' is used only for C functions.
|
||||
** About union 'u2':
|
||||
** - field 'funcidx' is used only by C functions while doing a
|
||||
** protected call;
|
||||
** - field 'nyield' is used only while a function is "doing" an
|
||||
** yield (from the yield until the next resume);
|
||||
** - field 'nres' is used only while closing tbc variables when
|
||||
** returning from a function;
|
||||
** - field 'transferinfo' is used only during call/returnhooks,
|
||||
** before the function starts or after it ends.
|
||||
*/
|
||||
typedef struct CallInfo {
|
||||
StkId func; /* function index in the stack */
|
||||
@@ -152,7 +176,7 @@ typedef struct CallInfo {
|
||||
union {
|
||||
struct { /* only for Lua functions */
|
||||
const Instruction *savedpc;
|
||||
l_signalT trap;
|
||||
volatile l_signalT trap;
|
||||
int nextraargs; /* # of extra arguments in vararg functions */
|
||||
} l;
|
||||
struct { /* only for C functions */
|
||||
@@ -164,9 +188,10 @@ typedef struct CallInfo {
|
||||
union {
|
||||
int funcidx; /* called-function index */
|
||||
int nyield; /* number of values yielded */
|
||||
struct { /* info about transfered values (for call/return hooks) */
|
||||
unsigned short ftransfer; /* offset of first value transfered */
|
||||
unsigned short ntransfer; /* number of values transfered */
|
||||
int nres; /* number of values returned */
|
||||
struct { /* info about transferred values (for call/return hooks) */
|
||||
unsigned short ftransfer; /* offset of first value transferred */
|
||||
unsigned short ntransfer; /* number of values transferred */
|
||||
} transferinfo;
|
||||
} u2;
|
||||
short nresults; /* expected number of results from this function */
|
||||
@@ -179,16 +204,34 @@ typedef struct CallInfo {
|
||||
*/
|
||||
#define CIST_OAH (1<<0) /* original value of 'allowhook' */
|
||||
#define CIST_C (1<<1) /* call is running a C function */
|
||||
#define CIST_HOOKED (1<<2) /* call is running a debug hook */
|
||||
#define CIST_YPCALL (1<<3) /* call is a yieldable protected call */
|
||||
#define CIST_TAIL (1<<4) /* call was tail called */
|
||||
#define CIST_HOOKYIELD (1<<5) /* last hook called yielded */
|
||||
#define CIST_FIN (1<<6) /* call is running a finalizer */
|
||||
#define CIST_TRAN (1<<7) /* 'ci' has transfer information */
|
||||
#define CIST_FRESH (1<<2) /* call is on a fresh "luaV_execute" frame */
|
||||
#define CIST_HOOKED (1<<3) /* call is running a debug hook */
|
||||
#define CIST_YPCALL (1<<4) /* doing a yieldable protected call */
|
||||
#define CIST_TAIL (1<<5) /* call was tail called */
|
||||
#define CIST_HOOKYIELD (1<<6) /* last hook called yielded */
|
||||
#define CIST_FIN (1<<7) /* function "called" a finalizer */
|
||||
#define CIST_TRAN (1<<8) /* 'ci' has transfer information */
|
||||
#define CIST_CLSRET (1<<9) /* function is closing tbc variables */
|
||||
/* Bits 10-12 are used for CIST_RECST (see below) */
|
||||
#define CIST_RECST 10
|
||||
#if defined(LUA_COMPAT_LT_LE)
|
||||
#define CIST_LEQ (1<<8) /* using __lt for __le */
|
||||
#define CIST_LEQ (1<<13) /* using __lt for __le */
|
||||
#endif
|
||||
|
||||
|
||||
/*
|
||||
** Field CIST_RECST stores the "recover status", used to keep the error
|
||||
** status while closing to-be-closed variables in coroutines, so that
|
||||
** Lua can correctly resume after an yield from a __close method called
|
||||
** because of an error. (Three bits are enough for error status.)
|
||||
*/
|
||||
#define getcistrecst(ci) (((ci)->callstatus >> CIST_RECST) & 7)
|
||||
#define setcistrecst(ci,st) \
|
||||
check_exp(((st) & 7) == (st), /* status must fit in three bits */ \
|
||||
((ci)->callstatus = ((ci)->callstatus & ~(7 << CIST_RECST)) \
|
||||
| ((st) << CIST_RECST)))
|
||||
|
||||
|
||||
/* active function is a Lua function */
|
||||
#define isLua(ci) (!((ci)->callstatus & CIST_C))
|
||||
|
||||
@@ -217,9 +260,10 @@ typedef struct global_State {
|
||||
lu_byte currentwhite;
|
||||
lu_byte gcstate; /* state of garbage collector */
|
||||
lu_byte gckind; /* kind of GC running */
|
||||
lu_byte gcstopem; /* stops emergency collections */
|
||||
lu_byte genminormul; /* control for minor generational collections */
|
||||
lu_byte genmajormul; /* control for major generational collections */
|
||||
lu_byte gcrunning; /* true if GC is running */
|
||||
lu_byte gcstp; /* control whether GC is running */
|
||||
lu_byte gcemergency; /* true if this is an emergency collection */
|
||||
lu_byte gcpause; /* size of pause between successive GCs */
|
||||
lu_byte gcstepmul; /* GC "speed" */
|
||||
@@ -236,10 +280,11 @@ typedef struct global_State {
|
||||
GCObject *fixedgc; /* list of objects not to be collected */
|
||||
/* fields for generational collector */
|
||||
GCObject *survival; /* start of objects that survived one GC cycle */
|
||||
GCObject *old; /* start of old objects */
|
||||
GCObject *reallyold; /* old objects with more than one cycle */
|
||||
GCObject *old1; /* start of old1 objects */
|
||||
GCObject *reallyold; /* objects more than one cycle old ("really old") */
|
||||
GCObject *firstold1; /* first OLD1 object in the list (if any) */
|
||||
GCObject *finobjsur; /* list of survival objects with finalizers */
|
||||
GCObject *finobjold; /* list of old objects with finalizers */
|
||||
GCObject *finobjold1; /* list of old1 objects with finalizers */
|
||||
GCObject *finobjrold; /* list of really old objects with finalizers */
|
||||
struct lua_State *twups; /* list of threads with open upvalues */
|
||||
lua_CFunction panic; /* to be called in unprotected errors */
|
||||
@@ -264,29 +309,41 @@ struct lua_State {
|
||||
StkId top; /* first free slot in the stack */
|
||||
global_State *l_G;
|
||||
CallInfo *ci; /* call info for current function */
|
||||
const Instruction *oldpc; /* last pc traced */
|
||||
StkId stack_last; /* last free slot in the stack */
|
||||
StkId stack_last; /* end of stack (last element + 1) */
|
||||
StkId stack; /* stack base */
|
||||
UpVal *openupval; /* list of open upvalues in this stack */
|
||||
StkId tbclist; /* list of to-be-closed variables */
|
||||
GCObject *gclist;
|
||||
struct lua_State *twups; /* list of threads with open upvalues */
|
||||
struct lua_longjmp *errorJmp; /* current error recover point */
|
||||
CallInfo base_ci; /* CallInfo for first level (C calling Lua) */
|
||||
volatile lua_Hook hook;
|
||||
ptrdiff_t errfunc; /* current error handling function (stack index) */
|
||||
l_uint32 nCcalls; /* number of allowed nested C calls - 'nci' */
|
||||
int stacksize;
|
||||
l_uint32 nCcalls; /* number of nested (non-yieldable | C) calls */
|
||||
int oldpc; /* last pc traced */
|
||||
int basehookcount;
|
||||
int hookcount;
|
||||
l_signalT hookmask;
|
||||
volatile l_signalT hookmask;
|
||||
};
|
||||
|
||||
|
||||
#define G(L) (L->l_G)
|
||||
|
||||
/*
|
||||
** 'g->nilvalue' being a nil value flags that the state was completely
|
||||
** build.
|
||||
*/
|
||||
#define completestate(g) ttisnil(&g->nilvalue)
|
||||
|
||||
|
||||
/*
|
||||
** Union of all collectable objects (only for conversions)
|
||||
** ISO C99, 6.5.2.3 p.5:
|
||||
** "if a union contains several structures that share a common initial
|
||||
** sequence [...], and if the union object currently contains one
|
||||
** of these structures, it is permitted to inspect the common initial
|
||||
** part of any of them anywhere that a declaration of the complete type
|
||||
** of the union is visible."
|
||||
*/
|
||||
union GCUnion {
|
||||
GCObject gc; /* common header */
|
||||
@@ -300,21 +357,25 @@ union GCUnion {
|
||||
};
|
||||
|
||||
|
||||
/*
|
||||
** ISO C99, 6.7.2.1 p.14:
|
||||
** "A pointer to a union object, suitably converted, points to each of
|
||||
** its members [...], and vice versa."
|
||||
*/
|
||||
#define cast_u(o) cast(union GCUnion *, (o))
|
||||
|
||||
/* macros to convert a GCObject into a specific value */
|
||||
#define gco2ts(o) \
|
||||
check_exp(novariant((o)->tt) == LUA_TSTRING, &((cast_u(o))->ts))
|
||||
#define gco2u(o) check_exp((o)->tt == LUA_TUSERDATA, &((cast_u(o))->u))
|
||||
#define gco2lcl(o) check_exp((o)->tt == LUA_TLCL, &((cast_u(o))->cl.l))
|
||||
#define gco2ccl(o) check_exp((o)->tt == LUA_TCCL, &((cast_u(o))->cl.c))
|
||||
#define gco2u(o) check_exp((o)->tt == LUA_VUSERDATA, &((cast_u(o))->u))
|
||||
#define gco2lcl(o) check_exp((o)->tt == LUA_VLCL, &((cast_u(o))->cl.l))
|
||||
#define gco2ccl(o) check_exp((o)->tt == LUA_VCCL, &((cast_u(o))->cl.c))
|
||||
#define gco2cl(o) \
|
||||
check_exp(novariant((o)->tt) == LUA_TFUNCTION, &((cast_u(o))->cl))
|
||||
#define gco2t(o) check_exp((o)->tt == LUA_TTABLE, &((cast_u(o))->h))
|
||||
#define gco2p(o) check_exp((o)->tt == LUA_TPROTO, &((cast_u(o))->p))
|
||||
#define gco2th(o) check_exp((o)->tt == LUA_TTHREAD, &((cast_u(o))->th))
|
||||
#define gco2upv(o) \
|
||||
check_exp(novariant((o)->tt) == LUA_TUPVAL, &((cast_u(o))->upv))
|
||||
#define gco2t(o) check_exp((o)->tt == LUA_VTABLE, &((cast_u(o))->h))
|
||||
#define gco2p(o) check_exp((o)->tt == LUA_VPROTO, &((cast_u(o))->p))
|
||||
#define gco2th(o) check_exp((o)->tt == LUA_VTHREAD, &((cast_u(o))->th))
|
||||
#define gco2upv(o) check_exp((o)->tt == LUA_VUPVAL, &((cast_u(o))->upv))
|
||||
|
||||
|
||||
/*
|
||||
@@ -332,11 +393,12 @@ LUAI_FUNC void luaE_freethread (lua_State *L, lua_State *L1);
|
||||
LUAI_FUNC CallInfo *luaE_extendCI (lua_State *L);
|
||||
LUAI_FUNC void luaE_freeCI (lua_State *L);
|
||||
LUAI_FUNC void luaE_shrinkCI (lua_State *L);
|
||||
LUAI_FUNC void luaE_enterCcall (lua_State *L);
|
||||
LUAI_FUNC void luaE_checkcstack (lua_State *L);
|
||||
LUAI_FUNC void luaE_incCstack (lua_State *L);
|
||||
LUAI_FUNC void luaE_warning (lua_State *L, const char *msg, int tocont);
|
||||
LUAI_FUNC void luaE_warnerror (lua_State *L, const char *where);
|
||||
LUAI_FUNC int luaE_resetthread (lua_State *L, int status);
|
||||
|
||||
|
||||
#define luaE_exitCcall(L) ((L)->nCcalls--)
|
||||
|
||||
#endif
|
||||
|
||||
|
||||
@@ -22,16 +22,6 @@
|
||||
#include "lstring.h"
|
||||
|
||||
|
||||
/*
|
||||
** Lua will use at most ~(2^LUAI_HASHLIMIT) bytes from a string to
|
||||
** compute its hash
|
||||
*/
|
||||
#if !defined(LUAI_HASHLIMIT)
|
||||
#define LUAI_HASHLIMIT 5
|
||||
#endif
|
||||
|
||||
|
||||
|
||||
/*
|
||||
** Maximum size for string table.
|
||||
*/
|
||||
@@ -43,7 +33,7 @@
|
||||
*/
|
||||
int luaS_eqlngstr (TString *a, TString *b) {
|
||||
size_t len = a->u.lnglen;
|
||||
lua_assert(a->tt == LUA_TLNGSTR && b->tt == LUA_TLNGSTR);
|
||||
lua_assert(a->tt == LUA_VLNGSTR && b->tt == LUA_VLNGSTR);
|
||||
return (a == b) || /* same instance or... */
|
||||
((len == b->u.lnglen) && /* equal length and ... */
|
||||
(memcmp(getstr(a), getstr(b), len) == 0)); /* equal contents */
|
||||
@@ -52,17 +42,17 @@ int luaS_eqlngstr (TString *a, TString *b) {
|
||||
|
||||
unsigned int luaS_hash (const char *str, size_t l, unsigned int seed) {
|
||||
unsigned int h = seed ^ cast_uint(l);
|
||||
size_t step = (l >> LUAI_HASHLIMIT) + 1;
|
||||
for (; l >= step; l -= step)
|
||||
for (; l > 0; l--)
|
||||
h ^= ((h<<5) + (h>>2) + cast_byte(str[l - 1]));
|
||||
return h;
|
||||
}
|
||||
|
||||
|
||||
unsigned int luaS_hashlongstr (TString *ts) {
|
||||
lua_assert(ts->tt == LUA_TLNGSTR);
|
||||
lua_assert(ts->tt == LUA_VLNGSTR);
|
||||
if (ts->extra == 0) { /* no hash? */
|
||||
ts->hash = luaS_hash(getstr(ts), ts->u.lnglen, ts->hash);
|
||||
size_t len = ts->u.lnglen;
|
||||
ts->hash = luaS_hash(getstr(ts), len, ts->hash);
|
||||
ts->extra = 1; /* now it has its hash */
|
||||
}
|
||||
return ts->hash;
|
||||
@@ -99,7 +89,7 @@ void luaS_resize (lua_State *L, int nsize) {
|
||||
if (nsize < osize) /* shrinking table? */
|
||||
tablerehash(tb->hash, osize, nsize); /* depopulate shrinking part */
|
||||
newvect = luaM_reallocvector(L, tb->hash, osize, nsize, TString*);
|
||||
if (unlikely(newvect == NULL)) { /* reallocation failed? */
|
||||
if (l_unlikely(newvect == NULL)) { /* reallocation failed? */
|
||||
if (nsize < osize) /* was it shrinking table? */
|
||||
tablerehash(tb->hash, nsize, osize); /* restore to original size */
|
||||
/* leave table as it was */
|
||||
@@ -165,7 +155,7 @@ static TString *createstrobj (lua_State *L, size_t l, int tag, unsigned int h) {
|
||||
|
||||
|
||||
TString *luaS_createlngstrobj (lua_State *L, size_t l) {
|
||||
TString *ts = createstrobj(L, l, LUA_TLNGSTR, G(L)->seed);
|
||||
TString *ts = createstrobj(L, l, LUA_VLNGSTR, G(L)->seed);
|
||||
ts->u.lnglen = l;
|
||||
return ts;
|
||||
}
|
||||
@@ -182,7 +172,7 @@ void luaS_remove (lua_State *L, TString *ts) {
|
||||
|
||||
|
||||
static void growstrtab (lua_State *L, stringtable *tb) {
|
||||
if (unlikely(tb->nuse == MAX_INT)) { /* too many strings? */
|
||||
if (l_unlikely(tb->nuse == MAX_INT)) { /* too many strings? */
|
||||
luaC_fullgc(L, 1); /* try to free some... */
|
||||
if (tb->nuse == MAX_INT) /* still too many? */
|
||||
luaM_error(L); /* cannot even create a message... */
|
||||
@@ -215,7 +205,7 @@ static TString *internshrstr (lua_State *L, const char *str, size_t l) {
|
||||
growstrtab(L, tb);
|
||||
list = &tb->hash[lmod(h, tb->size)]; /* rehash with new size */
|
||||
}
|
||||
ts = createstrobj(L, l, LUA_TSHRSTR, h);
|
||||
ts = createstrobj(L, l, LUA_VSHRSTR, h);
|
||||
memcpy(getstr(ts), str, l * sizeof(char));
|
||||
ts->shrlen = cast_byte(l);
|
||||
ts->u.hnext = *list;
|
||||
@@ -233,7 +223,7 @@ TString *luaS_newlstr (lua_State *L, const char *str, size_t l) {
|
||||
return internshrstr(L, str, l);
|
||||
else {
|
||||
TString *ts;
|
||||
if (unlikely(l >= (MAX_SIZE - sizeof(TString))/sizeof(char)))
|
||||
if (l_unlikely(l >= (MAX_SIZE - sizeof(TString))/sizeof(char)))
|
||||
luaM_toobig(L);
|
||||
ts = luaS_createlngstrobj(L, l);
|
||||
memcpy(getstr(ts), str, l * sizeof(char));
|
||||
@@ -269,9 +259,9 @@ Udata *luaS_newudata (lua_State *L, size_t s, int nuvalue) {
|
||||
Udata *u;
|
||||
int i;
|
||||
GCObject *o;
|
||||
if (unlikely(s > MAX_SIZE - udatamemoffset(nuvalue)))
|
||||
if (l_unlikely(s > MAX_SIZE - udatamemoffset(nuvalue)))
|
||||
luaM_toobig(L);
|
||||
o = luaC_newobj(L, LUA_TUSERDATA, sizeudata(nuvalue, s));
|
||||
o = luaC_newobj(L, LUA_VUSERDATA, sizeudata(nuvalue, s));
|
||||
u = gco2u(o);
|
||||
u->len = s;
|
||||
u->nuvalue = nuvalue;
|
||||
|
||||
@@ -19,7 +19,11 @@
|
||||
#define MEMERRMSG "not enough memory"
|
||||
|
||||
|
||||
#define sizelstring(l) (sizeof(TString) + ((l) + 1) * sizeof(char))
|
||||
/*
|
||||
** Size of a TString: Size of the header plus space for the string
|
||||
** itself (including final '\0').
|
||||
*/
|
||||
#define sizelstring(l) (offsetof(TString, contents) + ((l) + 1) * sizeof(char))
|
||||
|
||||
#define luaS_newliteral(L, s) (luaS_newlstr(L, "" s, \
|
||||
(sizeof(s)/sizeof(char))-1))
|
||||
@@ -28,13 +32,13 @@
|
||||
/*
|
||||
** test whether a string is a reserved word
|
||||
*/
|
||||
#define isreserved(s) ((s)->tt == LUA_TSHRSTR && (s)->extra > 0)
|
||||
#define isreserved(s) ((s)->tt == LUA_VSHRSTR && (s)->extra > 0)
|
||||
|
||||
|
||||
/*
|
||||
** equality for short strings, which are always internalized
|
||||
*/
|
||||
#define eqshrstr(a,b) check_exp((a)->tt == LUA_TSHRSTR, (a) == (b))
|
||||
#define eqshrstr(a,b) check_exp((a)->tt == LUA_VSHRSTR, (a) == (b))
|
||||
|
||||
|
||||
LUAI_FUNC unsigned int luaS_hash (const char *str, size_t l, unsigned int seed);
|
||||
|
||||
@@ -152,8 +152,9 @@ static int str_rep (lua_State *L) {
|
||||
const char *s = luaL_checklstring(L, 1, &l);
|
||||
lua_Integer n = luaL_checkinteger(L, 2);
|
||||
const char *sep = luaL_optlstring(L, 3, "", &lsep);
|
||||
if (n <= 0) lua_pushliteral(L, "");
|
||||
else if (l + lsep < l || l + lsep > MAXSIZE / n) /* may overflow? */
|
||||
if (n <= 0)
|
||||
lua_pushliteral(L, "");
|
||||
else if (l_unlikely(l + lsep < l || l + lsep > MAXSIZE / n))
|
||||
return luaL_error(L, "resulting string too large");
|
||||
else {
|
||||
size_t totallen = (size_t)n * l + (size_t)(n - 1) * lsep;
|
||||
@@ -181,7 +182,7 @@ static int str_byte (lua_State *L) {
|
||||
size_t pose = getendpos(L, 3, pi, l);
|
||||
int n, i;
|
||||
if (posi > pose) return 0; /* empty interval; return no values */
|
||||
if (pose - posi >= (size_t)INT_MAX) /* arithmetic overflow? */
|
||||
if (l_unlikely(pose - posi >= (size_t)INT_MAX)) /* arithmetic overflow? */
|
||||
return luaL_error(L, "string slice too long");
|
||||
n = (int)(pose - posi) + 1;
|
||||
luaL_checkstack(L, n, "string slice too long");
|
||||
@@ -206,22 +207,38 @@ static int str_char (lua_State *L) {
|
||||
}
|
||||
|
||||
|
||||
static int writer (lua_State *L, const void *b, size_t size, void *B) {
|
||||
(void)L;
|
||||
luaL_addlstring((luaL_Buffer *) B, (const char *)b, size);
|
||||
/*
|
||||
** Buffer to store the result of 'string.dump'. It must be initialized
|
||||
** after the call to 'lua_dump', to ensure that the function is on the
|
||||
** top of the stack when 'lua_dump' is called. ('luaL_buffinit' might
|
||||
** push stuff.)
|
||||
*/
|
||||
struct str_Writer {
|
||||
int init; /* true iff buffer has been initialized */
|
||||
luaL_Buffer B;
|
||||
};
|
||||
|
||||
|
||||
static int writer (lua_State *L, const void *b, size_t size, void *ud) {
|
||||
struct str_Writer *state = (struct str_Writer *)ud;
|
||||
if (!state->init) {
|
||||
state->init = 1;
|
||||
luaL_buffinit(L, &state->B);
|
||||
}
|
||||
luaL_addlstring(&state->B, (const char *)b, size);
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
static int str_dump (lua_State *L) {
|
||||
luaL_Buffer b;
|
||||
struct str_Writer state;
|
||||
int strip = lua_toboolean(L, 2);
|
||||
luaL_checktype(L, 1, LUA_TFUNCTION);
|
||||
lua_settop(L, 1);
|
||||
luaL_buffinit(L,&b);
|
||||
if (lua_dump(L, writer, &b, strip) != 0)
|
||||
lua_settop(L, 1); /* ensure function is on the top of the stack */
|
||||
state.init = 0;
|
||||
if (l_unlikely(lua_dump(L, writer, &state, strip) != 0))
|
||||
return luaL_error(L, "unable to dump given function");
|
||||
luaL_pushresult(&b);
|
||||
luaL_pushresult(&state.B);
|
||||
return 1;
|
||||
}
|
||||
|
||||
@@ -233,6 +250,17 @@ static int str_dump (lua_State *L) {
|
||||
** =======================================================
|
||||
*/
|
||||
|
||||
#if defined(LUA_NOCVTS2N) /* { */
|
||||
|
||||
/* no coercion from strings to numbers */
|
||||
|
||||
static const luaL_Reg stringmetamethods[] = {
|
||||
{"__index", NULL}, /* placeholder */
|
||||
{NULL, NULL}
|
||||
};
|
||||
|
||||
#else /* }{ */
|
||||
|
||||
static int tonum (lua_State *L, int arg) {
|
||||
if (lua_type(L, arg) == LUA_TNUMBER) { /* already a number? */
|
||||
lua_pushvalue(L, arg);
|
||||
@@ -248,7 +276,8 @@ static int tonum (lua_State *L, int arg) {
|
||||
|
||||
static void trymt (lua_State *L, const char *mtname) {
|
||||
lua_settop(L, 2); /* back to the original arguments */
|
||||
if (lua_type(L, 2) == LUA_TSTRING || !luaL_getmetafield(L, 2, mtname))
|
||||
if (l_unlikely(lua_type(L, 2) == LUA_TSTRING ||
|
||||
!luaL_getmetafield(L, 2, mtname)))
|
||||
luaL_error(L, "attempt to %s a '%s' with a '%s'", mtname + 2,
|
||||
luaL_typename(L, -2), luaL_typename(L, -1));
|
||||
lua_insert(L, -3); /* put metamethod before arguments */
|
||||
@@ -311,6 +340,8 @@ static const luaL_Reg stringmetamethods[] = {
|
||||
{NULL, NULL}
|
||||
};
|
||||
|
||||
#endif /* } */
|
||||
|
||||
/* }====================================================== */
|
||||
|
||||
/*
|
||||
@@ -354,7 +385,8 @@ static const char *match (MatchState *ms, const char *s, const char *p);
|
||||
|
||||
static int check_capture (MatchState *ms, int l) {
|
||||
l -= '1';
|
||||
if (l < 0 || l >= ms->level || ms->capture[l].len == CAP_UNFINISHED)
|
||||
if (l_unlikely(l < 0 || l >= ms->level ||
|
||||
ms->capture[l].len == CAP_UNFINISHED))
|
||||
return luaL_error(ms->L, "invalid capture index %%%d", l + 1);
|
||||
return l;
|
||||
}
|
||||
@@ -371,14 +403,14 @@ static int capture_to_close (MatchState *ms) {
|
||||
static const char *classend (MatchState *ms, const char *p) {
|
||||
switch (*p++) {
|
||||
case L_ESC: {
|
||||
if (p == ms->p_end)
|
||||
if (l_unlikely(p == ms->p_end))
|
||||
luaL_error(ms->L, "malformed pattern (ends with '%%')");
|
||||
return p+1;
|
||||
}
|
||||
case '[': {
|
||||
if (*p == '^') p++;
|
||||
do { /* look for a ']' */
|
||||
if (p == ms->p_end)
|
||||
if (l_unlikely(p == ms->p_end))
|
||||
luaL_error(ms->L, "malformed pattern (missing ']')");
|
||||
if (*(p++) == L_ESC && p < ms->p_end)
|
||||
p++; /* skip escapes (e.g. '%]') */
|
||||
@@ -453,7 +485,7 @@ static int singlematch (MatchState *ms, const char *s, const char *p,
|
||||
|
||||
static const char *matchbalance (MatchState *ms, const char *s,
|
||||
const char *p) {
|
||||
if (p >= ms->p_end - 1)
|
||||
if (l_unlikely(p >= ms->p_end - 1))
|
||||
luaL_error(ms->L, "malformed pattern (missing arguments to '%%b')");
|
||||
if (*s != *p) return NULL;
|
||||
else {
|
||||
@@ -536,7 +568,7 @@ static const char *match_capture (MatchState *ms, const char *s, int l) {
|
||||
|
||||
|
||||
static const char *match (MatchState *ms, const char *s, const char *p) {
|
||||
if (ms->matchdepth-- == 0)
|
||||
if (l_unlikely(ms->matchdepth-- == 0))
|
||||
luaL_error(ms->L, "pattern too complex");
|
||||
init: /* using goto's to optimize tail recursion */
|
||||
if (p != ms->p_end) { /* end of pattern? */
|
||||
@@ -570,7 +602,7 @@ static const char *match (MatchState *ms, const char *s, const char *p) {
|
||||
case 'f': { /* frontier? */
|
||||
const char *ep; char previous;
|
||||
p += 2;
|
||||
if (*p != '[')
|
||||
if (l_unlikely(*p != '['))
|
||||
luaL_error(ms->L, "missing '[' after '%%f' in pattern");
|
||||
ep = classend(ms, p); /* points to what is next */
|
||||
previous = (s == ms->src_init) ? '\0' : *(s - 1);
|
||||
@@ -670,7 +702,7 @@ static const char *lmemfind (const char *s1, size_t l1,
|
||||
static size_t get_onecapture (MatchState *ms, int i, const char *s,
|
||||
const char *e, const char **cap) {
|
||||
if (i >= ms->level) {
|
||||
if (i != 0)
|
||||
if (l_unlikely(i != 0))
|
||||
luaL_error(ms->L, "invalid capture index %%%d", i + 1);
|
||||
*cap = s;
|
||||
return e - s;
|
||||
@@ -678,7 +710,7 @@ static size_t get_onecapture (MatchState *ms, int i, const char *s,
|
||||
else {
|
||||
ptrdiff_t capl = ms->capture[i].len;
|
||||
*cap = ms->capture[i].init;
|
||||
if (capl == CAP_UNFINISHED)
|
||||
if (l_unlikely(capl == CAP_UNFINISHED))
|
||||
luaL_error(ms->L, "unfinished capture");
|
||||
else if (capl == CAP_POSITION)
|
||||
lua_pushinteger(ms->L, (ms->capture[i].init - ms->src_init) + 1);
|
||||
@@ -744,7 +776,7 @@ static int str_find_aux (lua_State *L, int find) {
|
||||
const char *p = luaL_checklstring(L, 2, &lp);
|
||||
size_t init = posrelatI(luaL_optinteger(L, 3, 1), ls) - 1;
|
||||
if (init > ls) { /* start after string's end? */
|
||||
lua_pushnil(L); /* cannot find anything */
|
||||
luaL_pushfail(L); /* cannot find anything */
|
||||
return 1;
|
||||
}
|
||||
/* explicit request or no special characters? */
|
||||
@@ -779,7 +811,7 @@ static int str_find_aux (lua_State *L, int find) {
|
||||
}
|
||||
} while (s1++ < ms.src_end && !anchor);
|
||||
}
|
||||
lua_pushnil(L); /* not found */
|
||||
luaL_pushfail(L); /* not found */
|
||||
return 1;
|
||||
}
|
||||
|
||||
@@ -897,7 +929,7 @@ static int add_value (MatchState *ms, luaL_Buffer *b, const char *s,
|
||||
luaL_addlstring(b, s, e - s); /* keep original text */
|
||||
return 0; /* no changes */
|
||||
}
|
||||
else if (!lua_isstring(L, -1))
|
||||
else if (l_unlikely(!lua_isstring(L, -1)))
|
||||
return luaL_error(L, "invalid replacement value (a %s)",
|
||||
luaL_typename(L, -1));
|
||||
else {
|
||||
@@ -975,7 +1007,7 @@ static int str_gsub (lua_State *L) {
|
||||
** to nibble boundaries by making what is left after that first digit a
|
||||
** multiple of 4.
|
||||
*/
|
||||
#define L_NBFD ((l_mathlim(MANT_DIG) - 1)%4 + 1)
|
||||
#define L_NBFD ((l_floatatt(MANT_DIG) - 1)%4 + 1)
|
||||
|
||||
|
||||
/*
|
||||
@@ -1029,7 +1061,7 @@ static int lua_number2strx (lua_State *L, char *buff, int sz,
|
||||
for (i = 0; i < n; i++)
|
||||
buff[i] = toupper(uchar(buff[i]));
|
||||
}
|
||||
else if (fmt[SIZELENMOD] != 'a')
|
||||
else if (l_unlikely(fmt[SIZELENMOD] != 'a'))
|
||||
return luaL_error(L, "modifiers for format '%%a'/'%%A' not implemented");
|
||||
return n;
|
||||
}
|
||||
@@ -1043,7 +1075,7 @@ static int lua_number2strx (lua_State *L, char *buff, int sz,
|
||||
** and '\0') + number of decimal digits to represent maxfloat (which
|
||||
** is maximum exponent + 1). (99+3+1, adding some extra, 110)
|
||||
*/
|
||||
#define MAX_ITEMF (110 + l_mathlim(MAX_10_EXP))
|
||||
#define MAX_ITEMF (110 + l_floatatt(MAX_10_EXP))
|
||||
|
||||
|
||||
/*
|
||||
@@ -1058,10 +1090,31 @@ static int lua_number2strx (lua_State *L, char *buff, int sz,
|
||||
|
||||
|
||||
/* valid flags in a format specification */
|
||||
#define FLAGS "-+ #0"
|
||||
#if !defined(L_FMTFLAGSF)
|
||||
|
||||
/* valid flags for a, A, e, E, f, F, g, and G conversions */
|
||||
#define L_FMTFLAGSF "-+#0 "
|
||||
|
||||
/* valid flags for o, x, and X conversions */
|
||||
#define L_FMTFLAGSX "-#0"
|
||||
|
||||
/* valid flags for d and i conversions */
|
||||
#define L_FMTFLAGSI "-+0 "
|
||||
|
||||
/* valid flags for u conversions */
|
||||
#define L_FMTFLAGSU "-0"
|
||||
|
||||
/* valid flags for c, p, and s conversions */
|
||||
#define L_FMTFLAGSC "-"
|
||||
|
||||
#endif
|
||||
|
||||
|
||||
/*
|
||||
** maximum size of each format specification (such as "%-099.99d")
|
||||
** Maximum size of each format specification (such as "%-099.99d"):
|
||||
** Initial '%', flags (up to 5), width (2), period, precision (2),
|
||||
** length modifier (8), conversion specifier, and final '\0', plus some
|
||||
** extra.
|
||||
*/
|
||||
#define MAX_FORMAT 32
|
||||
|
||||
@@ -1154,25 +1207,53 @@ static void addliteral (lua_State *L, luaL_Buffer *b, int arg) {
|
||||
}
|
||||
|
||||
|
||||
static const char *scanformat (lua_State *L, const char *strfrmt, char *form) {
|
||||
const char *p = strfrmt;
|
||||
while (*p != '\0' && strchr(FLAGS, *p) != NULL) p++; /* skip flags */
|
||||
if ((size_t)(p - strfrmt) >= sizeof(FLAGS)/sizeof(char))
|
||||
luaL_error(L, "invalid format (repeated flags)");
|
||||
if (isdigit(uchar(*p))) p++; /* skip width */
|
||||
if (isdigit(uchar(*p))) p++; /* (2 digits at most) */
|
||||
if (*p == '.') {
|
||||
p++;
|
||||
if (isdigit(uchar(*p))) p++; /* skip precision */
|
||||
if (isdigit(uchar(*p))) p++; /* (2 digits at most) */
|
||||
static const char *get2digits (const char *s) {
|
||||
if (isdigit(uchar(*s))) {
|
||||
s++;
|
||||
if (isdigit(uchar(*s))) s++; /* (2 digits at most) */
|
||||
}
|
||||
if (isdigit(uchar(*p)))
|
||||
luaL_error(L, "invalid format (width or precision too long)");
|
||||
return s;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** Check whether a conversion specification is valid. When called,
|
||||
** first character in 'form' must be '%' and last character must
|
||||
** be a valid conversion specifier. 'flags' are the accepted flags;
|
||||
** 'precision' signals whether to accept a precision.
|
||||
*/
|
||||
static void checkformat (lua_State *L, const char *form, const char *flags,
|
||||
int precision) {
|
||||
const char *spec = form + 1; /* skip '%' */
|
||||
spec += strspn(spec, flags); /* skip flags */
|
||||
if (*spec != '0') { /* a width cannot start with '0' */
|
||||
spec = get2digits(spec); /* skip width */
|
||||
if (*spec == '.' && precision) {
|
||||
spec++;
|
||||
spec = get2digits(spec); /* skip precision */
|
||||
}
|
||||
}
|
||||
if (!isalpha(uchar(*spec))) /* did not go to the end? */
|
||||
luaL_error(L, "invalid conversion specification: '%s'", form);
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** Get a conversion specification and copy it to 'form'.
|
||||
** Return the address of its last character.
|
||||
*/
|
||||
static const char *getformat (lua_State *L, const char *strfrmt,
|
||||
char *form) {
|
||||
/* spans flags, width, and precision ('0' is included as a flag) */
|
||||
size_t len = strspn(strfrmt, L_FMTFLAGSF "123456789.");
|
||||
len++; /* adds following character (should be the specifier) */
|
||||
/* still needs space for '%', '\0', plus a length modifier */
|
||||
if (len >= MAX_FORMAT - 10)
|
||||
luaL_error(L, "invalid format (too long)");
|
||||
*(form++) = '%';
|
||||
memcpy(form, strfrmt, ((p - strfrmt) + 1) * sizeof(char));
|
||||
form += (p - strfrmt) + 1;
|
||||
*form = '\0';
|
||||
return p;
|
||||
memcpy(form, strfrmt, len * sizeof(char));
|
||||
*(form + len) = '\0';
|
||||
return strfrmt + len - 1;
|
||||
}
|
||||
|
||||
|
||||
@@ -1195,6 +1276,7 @@ static int str_format (lua_State *L) {
|
||||
size_t sfl;
|
||||
const char *strfrmt = luaL_checklstring(L, arg, &sfl);
|
||||
const char *strfrmt_end = strfrmt+sfl;
|
||||
const char *flags;
|
||||
luaL_Buffer b;
|
||||
luaL_buffinit(L, &b);
|
||||
while (strfrmt < strfrmt_end) {
|
||||
@@ -1204,43 +1286,57 @@ static int str_format (lua_State *L) {
|
||||
luaL_addchar(&b, *strfrmt++); /* %% */
|
||||
else { /* format item */
|
||||
char form[MAX_FORMAT]; /* to store the format ('%...') */
|
||||
int maxitem = MAX_ITEM;
|
||||
char *buff = luaL_prepbuffsize(&b, maxitem); /* to put formatted item */
|
||||
int nb = 0; /* number of bytes in added item */
|
||||
int maxitem = MAX_ITEM; /* maximum length for the result */
|
||||
char *buff = luaL_prepbuffsize(&b, maxitem); /* to put result */
|
||||
int nb = 0; /* number of bytes in result */
|
||||
if (++arg > top)
|
||||
return luaL_argerror(L, arg, "no value");
|
||||
strfrmt = scanformat(L, strfrmt, form);
|
||||
strfrmt = getformat(L, strfrmt, form);
|
||||
switch (*strfrmt++) {
|
||||
case 'c': {
|
||||
checkformat(L, form, L_FMTFLAGSC, 0);
|
||||
nb = l_sprintf(buff, maxitem, form, (int)luaL_checkinteger(L, arg));
|
||||
break;
|
||||
}
|
||||
case 'd': case 'i':
|
||||
case 'o': case 'u': case 'x': case 'X': {
|
||||
flags = L_FMTFLAGSI;
|
||||
goto intcase;
|
||||
case 'u':
|
||||
flags = L_FMTFLAGSU;
|
||||
goto intcase;
|
||||
case 'o': case 'x': case 'X':
|
||||
flags = L_FMTFLAGSX;
|
||||
intcase: {
|
||||
lua_Integer n = luaL_checkinteger(L, arg);
|
||||
checkformat(L, form, flags, 1);
|
||||
addlenmod(form, LUA_INTEGER_FRMLEN);
|
||||
nb = l_sprintf(buff, maxitem, form, (LUAI_UACINT)n);
|
||||
break;
|
||||
}
|
||||
case 'a': case 'A':
|
||||
checkformat(L, form, L_FMTFLAGSF, 1);
|
||||
addlenmod(form, LUA_NUMBER_FRMLEN);
|
||||
nb = lua_number2strx(L, buff, maxitem, form,
|
||||
luaL_checknumber(L, arg));
|
||||
break;
|
||||
case 'e': case 'E': case 'f':
|
||||
case 'g': case 'G': {
|
||||
case 'f':
|
||||
maxitem = MAX_ITEMF; /* extra space for '%f' */
|
||||
buff = luaL_prepbuffsize(&b, maxitem);
|
||||
/* FALLTHROUGH */
|
||||
case 'e': case 'E': case 'g': case 'G': {
|
||||
lua_Number n = luaL_checknumber(L, arg);
|
||||
if (*(strfrmt - 1) == 'f' && l_mathop(fabs)(n) >= 1e100) {
|
||||
/* 'n' needs more than 99 digits */
|
||||
maxitem = MAX_ITEMF; /* extra space for '%f' */
|
||||
buff = luaL_prepbuffsize(&b, maxitem);
|
||||
}
|
||||
checkformat(L, form, L_FMTFLAGSF, 1);
|
||||
addlenmod(form, LUA_NUMBER_FRMLEN);
|
||||
nb = l_sprintf(buff, maxitem, form, (LUAI_UACNUMBER)n);
|
||||
break;
|
||||
}
|
||||
case 'p': {
|
||||
const void *p = lua_topointer(L, arg);
|
||||
checkformat(L, form, L_FMTFLAGSC, 0);
|
||||
if (p == NULL) { /* avoid calling 'printf' with argument NULL */
|
||||
p = "(null)"; /* result */
|
||||
form[strlen(form) - 1] = 's'; /* format it as a string */
|
||||
}
|
||||
nb = l_sprintf(buff, maxitem, form, p);
|
||||
break;
|
||||
}
|
||||
@@ -1257,7 +1353,8 @@ static int str_format (lua_State *L) {
|
||||
luaL_addvalue(&b); /* keep entire string */
|
||||
else {
|
||||
luaL_argcheck(L, l == strlen(s), arg, "string contains zeros");
|
||||
if (!strchr(form, '.') && l >= 100) {
|
||||
checkformat(L, form, L_FMTFLAGSC, 1);
|
||||
if (strchr(form, '.') == NULL && l >= 100) {
|
||||
/* no precision and string is too long to be formatted */
|
||||
luaL_addvalue(&b); /* keep entire string */
|
||||
}
|
||||
@@ -1315,26 +1412,6 @@ static const union {
|
||||
} nativeendian = {1};
|
||||
|
||||
|
||||
/* dummy structure to get native alignment requirements */
|
||||
struct cD {
|
||||
char c;
|
||||
union { double d; void *p; lua_Integer i; lua_Number n; } u;
|
||||
};
|
||||
|
||||
#define MAXALIGN (offsetof(struct cD, u))
|
||||
|
||||
|
||||
/*
|
||||
** Union for serializing floats
|
||||
*/
|
||||
typedef union Ftypes {
|
||||
float f;
|
||||
double d;
|
||||
lua_Number n;
|
||||
char buff[5 * sizeof(lua_Number)]; /* enough for any float type */
|
||||
} Ftypes;
|
||||
|
||||
|
||||
/*
|
||||
** information to pack/unpack stuff
|
||||
*/
|
||||
@@ -1351,7 +1428,9 @@ typedef struct Header {
|
||||
typedef enum KOption {
|
||||
Kint, /* signed integers */
|
||||
Kuint, /* unsigned integers */
|
||||
Kfloat, /* floating-point numbers */
|
||||
Kfloat, /* single-precision floating-point numbers */
|
||||
Knumber, /* Lua "native" floating-point numbers */
|
||||
Kdouble, /* double-precision floating-point numbers */
|
||||
Kchar, /* fixed-length strings */
|
||||
Kstring, /* strings with prefixed length */
|
||||
Kzstr, /* zero-terminated strings */
|
||||
@@ -1386,7 +1465,7 @@ 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)
|
||||
if (l_unlikely(sz > MAXINTSIZE || sz <= 0))
|
||||
return luaL_error(h->L, "integral size (%d) out of limits [1,%d]",
|
||||
sz, MAXINTSIZE);
|
||||
return sz;
|
||||
@@ -1407,6 +1486,8 @@ static void initheader (lua_State *L, Header *h) {
|
||||
** Read and classify next option. 'size' is filled with option's size.
|
||||
*/
|
||||
static KOption getoption (Header *h, const char **fmt, int *size) {
|
||||
/* dummy structure to get native alignment requirements */
|
||||
struct cD { char c; union { LUAI_MAXALIGN; } u; };
|
||||
int opt = *((*fmt)++);
|
||||
*size = 0; /* default */
|
||||
switch (opt) {
|
||||
@@ -1420,14 +1501,14 @@ static KOption getoption (Header *h, const char **fmt, int *size) {
|
||||
case 'J': *size = sizeof(lua_Integer); return Kuint;
|
||||
case 'T': *size = sizeof(size_t); return Kuint;
|
||||
case 'f': *size = sizeof(float); return Kfloat;
|
||||
case 'd': *size = sizeof(double); return Kfloat;
|
||||
case 'n': *size = sizeof(lua_Number); return Kfloat;
|
||||
case 'n': *size = sizeof(lua_Number); return Knumber;
|
||||
case 'd': *size = sizeof(double); return Kdouble;
|
||||
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);
|
||||
if (*size == -1)
|
||||
if (l_unlikely(*size == -1))
|
||||
luaL_error(h->L, "missing size for format option 'c'");
|
||||
return Kchar;
|
||||
case 'z': return Kzstr;
|
||||
@@ -1437,7 +1518,11 @@ static KOption getoption (Header *h, const char **fmt, int *size) {
|
||||
case '<': h->islittle = 1; break;
|
||||
case '>': h->islittle = 0; break;
|
||||
case '=': h->islittle = nativeendian.little; break;
|
||||
case '!': h->maxalign = getnumlimit(h, fmt, MAXALIGN); break;
|
||||
case '!': {
|
||||
const int maxalign = offsetof(struct cD, u);
|
||||
h->maxalign = getnumlimit(h, fmt, maxalign);
|
||||
break;
|
||||
}
|
||||
default: luaL_error(h->L, "invalid format option '%c'", opt);
|
||||
}
|
||||
return Knop;
|
||||
@@ -1466,7 +1551,7 @@ static KOption getdetails (Header *h, size_t totalsize,
|
||||
else {
|
||||
if (align > h->maxalign) /* enforce maximum alignment */
|
||||
align = h->maxalign;
|
||||
if ((align & (align - 1)) != 0) /* is 'align' not a power of 2? */
|
||||
if (l_unlikely((align & (align - 1)) != 0)) /* not a power of 2? */
|
||||
luaL_argerror(h->L, 1, "format asks for alignment not power of 2");
|
||||
*ntoalign = (align - (int)(totalsize & (align - 1))) & (align - 1);
|
||||
}
|
||||
@@ -1501,12 +1586,10 @@ static void packint (luaL_Buffer *b, lua_Unsigned n,
|
||||
** Copy 'size' bytes from 'src' to 'dest', correcting endianness if
|
||||
** given 'islittle' is different from native endianness.
|
||||
*/
|
||||
static void copywithendian (volatile char *dest, volatile const char *src,
|
||||
static void copywithendian (char *dest, const char *src,
|
||||
int size, int islittle) {
|
||||
if (islittle == nativeendian.little) {
|
||||
while (size-- != 0)
|
||||
*(dest++) = *(src++);
|
||||
}
|
||||
if (islittle == nativeendian.little)
|
||||
memcpy(dest, src, size);
|
||||
else {
|
||||
dest += size - 1;
|
||||
while (size-- != 0)
|
||||
@@ -1549,15 +1632,27 @@ static int str_pack (lua_State *L) {
|
||||
packint(&b, (lua_Unsigned)n, h.islittle, size, 0);
|
||||
break;
|
||||
}
|
||||
case Kfloat: { /* floating-point options */
|
||||
volatile Ftypes u;
|
||||
char *buff = luaL_prepbuffsize(&b, size);
|
||||
lua_Number n = luaL_checknumber(L, arg); /* get argument */
|
||||
if (size == sizeof(u.f)) u.f = (float)n; /* copy it into 'u' */
|
||||
else if (size == sizeof(u.d)) u.d = (double)n;
|
||||
else u.n = n;
|
||||
/* move 'u' to final result, correcting endianness if needed */
|
||||
copywithendian(buff, u.buff, size, h.islittle);
|
||||
case Kfloat: { /* C float */
|
||||
float f = (float)luaL_checknumber(L, arg); /* get argument */
|
||||
char *buff = luaL_prepbuffsize(&b, sizeof(f));
|
||||
/* move 'f' to final result, correcting endianness if needed */
|
||||
copywithendian(buff, (char *)&f, sizeof(f), h.islittle);
|
||||
luaL_addsize(&b, size);
|
||||
break;
|
||||
}
|
||||
case Knumber: { /* Lua float */
|
||||
lua_Number f = luaL_checknumber(L, arg); /* get argument */
|
||||
char *buff = luaL_prepbuffsize(&b, sizeof(f));
|
||||
/* move 'f' to final result, correcting endianness if needed */
|
||||
copywithendian(buff, (char *)&f, sizeof(f), h.islittle);
|
||||
luaL_addsize(&b, size);
|
||||
break;
|
||||
}
|
||||
case Kdouble: { /* C double */
|
||||
double f = (double)luaL_checknumber(L, arg); /* get argument */
|
||||
char *buff = luaL_prepbuffsize(&b, sizeof(f));
|
||||
/* move 'f' to final result, correcting endianness if needed */
|
||||
copywithendian(buff, (char *)&f, sizeof(f), h.islittle);
|
||||
luaL_addsize(&b, size);
|
||||
break;
|
||||
}
|
||||
@@ -1648,7 +1743,7 @@ static lua_Integer unpackint (lua_State *L, const char *str,
|
||||
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)
|
||||
if (l_unlikely((unsigned char)str[islittle ? i : size - 1 - i] != mask))
|
||||
luaL_error(L, "%d-byte integer does not fit into Lua Integer", size);
|
||||
}
|
||||
}
|
||||
@@ -1683,13 +1778,21 @@ static int str_unpack (lua_State *L) {
|
||||
break;
|
||||
}
|
||||
case Kfloat: {
|
||||
volatile Ftypes u;
|
||||
lua_Number num;
|
||||
copywithendian(u.buff, data + pos, size, h.islittle);
|
||||
if (size == sizeof(u.f)) num = (lua_Number)u.f;
|
||||
else if (size == sizeof(u.d)) num = (lua_Number)u.d;
|
||||
else num = u.n;
|
||||
lua_pushnumber(L, num);
|
||||
float f;
|
||||
copywithendian((char *)&f, data + pos, sizeof(f), h.islittle);
|
||||
lua_pushnumber(L, (lua_Number)f);
|
||||
break;
|
||||
}
|
||||
case Knumber: {
|
||||
lua_Number f;
|
||||
copywithendian((char *)&f, data + pos, sizeof(f), h.islittle);
|
||||
lua_pushnumber(L, f);
|
||||
break;
|
||||
}
|
||||
case Kdouble: {
|
||||
double f;
|
||||
copywithendian((char *)&f, data + pos, sizeof(f), h.islittle);
|
||||
lua_pushnumber(L, (lua_Number)f);
|
||||
break;
|
||||
}
|
||||
case Kchar: {
|
||||
@@ -1704,7 +1807,7 @@ static int str_unpack (lua_State *L) {
|
||||
break;
|
||||
}
|
||||
case Kzstr: {
|
||||
size_t len = (int)strlen(data + pos);
|
||||
size_t len = strlen(data + pos);
|
||||
luaL_argcheck(L, pos + len < ld, 2,
|
||||
"unfinished string for format 'z'");
|
||||
lua_pushlstring(L, data + pos, len);
|
||||
|
||||
@@ -68,18 +68,21 @@
|
||||
#define MAXHSIZE luaM_limitN(1u << MAXHBITS, Node)
|
||||
|
||||
|
||||
/*
|
||||
** When the original hash value is good, hashing by a power of 2
|
||||
** avoids the cost of '%'.
|
||||
*/
|
||||
#define hashpow2(t,n) (gnode(t, lmod((n), sizenode(t))))
|
||||
|
||||
/*
|
||||
** for other types, it is better to avoid modulo by power of 2, as
|
||||
** they can have many 2 factors.
|
||||
*/
|
||||
#define hashmod(t,n) (gnode(t, ((n) % ((sizenode(t)-1)|1))))
|
||||
|
||||
|
||||
#define hashstr(t,str) hashpow2(t, (str)->hash)
|
||||
#define hashboolean(t,p) hashpow2(t, p)
|
||||
#define hashint(t,i) hashpow2(t, i)
|
||||
|
||||
|
||||
/*
|
||||
** for some types, it is better to avoid modulus by power of 2, as
|
||||
** they tend to have many 2 factors.
|
||||
*/
|
||||
#define hashmod(t,n) (gnode(t, ((n) % ((sizenode(t)-1)|1))))
|
||||
|
||||
|
||||
#define hashpointer(t,p) hashmod(t, point2uint(p))
|
||||
@@ -88,14 +91,28 @@
|
||||
#define dummynode (&dummynode_)
|
||||
|
||||
static const Node dummynode_ = {
|
||||
{{NULL}, LUA_TEMPTY, /* value's value and type */
|
||||
LUA_TNIL, 0, {NULL}} /* key type, next, and key value */
|
||||
{{NULL}, LUA_VEMPTY, /* value's value and type */
|
||||
LUA_VNIL, 0, {NULL}} /* key type, next, and key value */
|
||||
};
|
||||
|
||||
|
||||
static const TValue absentkey = {ABSTKEYCONSTANT};
|
||||
|
||||
|
||||
/*
|
||||
** Hash for integers. To allow a good hash, use the remainder operator
|
||||
** ('%'). If integer fits as a non-negative int, compute an int
|
||||
** remainder, which is faster. Otherwise, use an unsigned-integer
|
||||
** remainder, which uses all bits and ensures a non-negative result.
|
||||
*/
|
||||
static Node *hashint (const Table *t, lua_Integer i) {
|
||||
lua_Unsigned ui = l_castS2U(i);
|
||||
if (ui <= (unsigned int)INT_MAX)
|
||||
return hashmod(t, cast_int(ui));
|
||||
else
|
||||
return hashmod(t, ui);
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** Hash for floating-point numbers.
|
||||
@@ -129,62 +146,89 @@ static int l_hashfloat (lua_Number n) {
|
||||
|
||||
/*
|
||||
** returns the 'main' position of an element in a table (that is,
|
||||
** the index of its hash value). The key comes broken (tag in 'ktt'
|
||||
** and value in 'vkl') so that we can call it on keys inserted into
|
||||
** nodes.
|
||||
** the index of its hash value).
|
||||
*/
|
||||
static Node *mainposition (const Table *t, int ktt, const Value *kvl) {
|
||||
switch (withvariant(ktt)) {
|
||||
case LUA_TNUMINT:
|
||||
return hashint(t, ivalueraw(*kvl));
|
||||
case LUA_TNUMFLT:
|
||||
return hashmod(t, l_hashfloat(fltvalueraw(*kvl)));
|
||||
case LUA_TSHRSTR:
|
||||
return hashstr(t, tsvalueraw(*kvl));
|
||||
case LUA_TLNGSTR:
|
||||
return hashpow2(t, luaS_hashlongstr(tsvalueraw(*kvl)));
|
||||
case LUA_TBOOLEAN:
|
||||
return hashboolean(t, bvalueraw(*kvl));
|
||||
case LUA_TLIGHTUSERDATA:
|
||||
return hashpointer(t, pvalueraw(*kvl));
|
||||
case LUA_TLCF:
|
||||
return hashpointer(t, fvalueraw(*kvl));
|
||||
default:
|
||||
return hashpointer(t, gcvalueraw(*kvl));
|
||||
static Node *mainpositionTV (const Table *t, const TValue *key) {
|
||||
switch (ttypetag(key)) {
|
||||
case LUA_VNUMINT: {
|
||||
lua_Integer i = ivalue(key);
|
||||
return hashint(t, i);
|
||||
}
|
||||
case LUA_VNUMFLT: {
|
||||
lua_Number n = fltvalue(key);
|
||||
return hashmod(t, l_hashfloat(n));
|
||||
}
|
||||
case LUA_VSHRSTR: {
|
||||
TString *ts = tsvalue(key);
|
||||
return hashstr(t, ts);
|
||||
}
|
||||
case LUA_VLNGSTR: {
|
||||
TString *ts = tsvalue(key);
|
||||
return hashpow2(t, luaS_hashlongstr(ts));
|
||||
}
|
||||
case LUA_VFALSE:
|
||||
return hashboolean(t, 0);
|
||||
case LUA_VTRUE:
|
||||
return hashboolean(t, 1);
|
||||
case LUA_VLIGHTUSERDATA: {
|
||||
void *p = pvalue(key);
|
||||
return hashpointer(t, p);
|
||||
}
|
||||
case LUA_VLCF: {
|
||||
lua_CFunction f = fvalue(key);
|
||||
return hashpointer(t, f);
|
||||
}
|
||||
default: {
|
||||
GCObject *o = gcvalue(key);
|
||||
return hashpointer(t, o);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
static Node *mainpositionTV (const Table *t, const TValue *key) {
|
||||
return mainposition(t, rawtt(key), valraw(key));
|
||||
l_sinline Node *mainpositionfromnode (const Table *t, Node *nd) {
|
||||
TValue key;
|
||||
getnodekey(cast(lua_State *, NULL), &key, nd);
|
||||
return mainpositionTV(t, &key);
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** Check whether key 'k1' is equal to the key in node 'n2'.
|
||||
** This equality is raw, so there are no metamethods. Floats
|
||||
** with integer values have been normalized, so integers cannot
|
||||
** be equal to floats. It is assumed that 'eqshrstr' is simply
|
||||
** pointer equality, so that short strings are handled in the
|
||||
** default case.
|
||||
** Check whether key 'k1' is equal to the key in node 'n2'. This
|
||||
** equality is raw, so there are no metamethods. Floats with integer
|
||||
** values have been normalized, so integers cannot be equal to
|
||||
** floats. It is assumed that 'eqshrstr' is simply pointer equality, so
|
||||
** that short strings are handled in the default case.
|
||||
** A true 'deadok' means to accept dead keys as equal to their original
|
||||
** values. All dead keys are compared in the default case, by pointer
|
||||
** identity. (Only collectable objects can produce dead keys.) Note that
|
||||
** dead long strings are also compared by identity.
|
||||
** Once a key is dead, its corresponding value may be collected, and
|
||||
** then another value can be created with the same address. If this
|
||||
** other value is given to 'next', 'equalkey' will signal a false
|
||||
** positive. In a regular traversal, this situation should never happen,
|
||||
** as all keys given to 'next' came from the table itself, and therefore
|
||||
** could not have been collected. Outside a regular traversal, we
|
||||
** have garbage in, garbage out. What is relevant is that this false
|
||||
** positive does not break anything. (In particular, 'next' will return
|
||||
** some other valid item on the table or nil.)
|
||||
*/
|
||||
static int equalkey (const TValue *k1, const Node *n2) {
|
||||
if (rawtt(k1) != keytt(n2)) /* not the same variants? */
|
||||
static int equalkey (const TValue *k1, const Node *n2, int deadok) {
|
||||
if ((rawtt(k1) != keytt(n2)) && /* not the same variants? */
|
||||
!(deadok && keyisdead(n2) && iscollectable(k1)))
|
||||
return 0; /* cannot be same key */
|
||||
switch (ttypetag(k1)) {
|
||||
case LUA_TNIL:
|
||||
switch (keytt(n2)) {
|
||||
case LUA_VNIL: case LUA_VFALSE: case LUA_VTRUE:
|
||||
return 1;
|
||||
case LUA_TNUMINT:
|
||||
case LUA_VNUMINT:
|
||||
return (ivalue(k1) == keyival(n2));
|
||||
case LUA_TNUMFLT:
|
||||
case LUA_VNUMFLT:
|
||||
return luai_numeq(fltvalue(k1), fltvalueraw(keyval(n2)));
|
||||
case LUA_TBOOLEAN:
|
||||
return bvalue(k1) == bvalueraw(keyval(n2));
|
||||
case LUA_TLIGHTUSERDATA:
|
||||
case LUA_VLIGHTUSERDATA:
|
||||
return pvalue(k1) == pvalueraw(keyval(n2));
|
||||
case LUA_TLCF:
|
||||
case LUA_VLCF:
|
||||
return fvalue(k1) == fvalueraw(keyval(n2));
|
||||
case LUA_TLNGSTR:
|
||||
case ctb(LUA_VLNGSTR):
|
||||
return luaS_eqlngstr(tsvalue(k1), keystrval(n2));
|
||||
default:
|
||||
return gcvalue(k1) == gcvalueraw(keyval(n2));
|
||||
@@ -248,11 +292,12 @@ static unsigned int setlimittosize (Table *t) {
|
||||
/*
|
||||
** "Generic" get version. (Not that generic: not valid for integers,
|
||||
** which may be in array part, nor for floats with integral values.)
|
||||
** See explanation about 'deadok' in function 'equalkey'.
|
||||
*/
|
||||
static const TValue *getgeneric (Table *t, const TValue *key) {
|
||||
static const TValue *getgeneric (Table *t, const TValue *key, int deadok) {
|
||||
Node *n = mainpositionTV(t, key);
|
||||
for (;;) { /* check whether 'key' is somewhere in the chain */
|
||||
if (equalkey(key, n))
|
||||
if (equalkey(key, n, deadok))
|
||||
return gval(n); /* that's it */
|
||||
else {
|
||||
int nx = gnext(n);
|
||||
@@ -289,8 +334,8 @@ static unsigned int findindex (lua_State *L, Table *t, TValue *key,
|
||||
if (i - 1u < asize) /* is 'key' inside array part? */
|
||||
return i; /* yes; that's the index */
|
||||
else {
|
||||
const TValue *n = getgeneric(t, key);
|
||||
if (unlikely(isabstkey(n)))
|
||||
const TValue *n = getgeneric(t, key, 1);
|
||||
if (l_unlikely(isabstkey(n)))
|
||||
luaG_runerror(L, "invalid key to 'next'"); /* key not found */
|
||||
i = cast_int(nodefromval(n) - gnode(t, 0)); /* key index in hash table */
|
||||
/* hash elements are numbered after array ones */
|
||||
@@ -468,7 +513,7 @@ static void reinsert (lua_State *L, Table *ot, Table *t) {
|
||||
already present in the table */
|
||||
TValue k;
|
||||
getnodekey(L, &k, old);
|
||||
setobjt2t(L, luaH_set(L, t, &k), gval(old));
|
||||
luaH_set(L, t, &k, gval(old));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -524,7 +569,7 @@ void luaH_resize (lua_State *L, Table *t, unsigned int newasize,
|
||||
}
|
||||
/* allocate new array */
|
||||
newarray = luaM_reallocvector(L, t->array, oldasize, newasize, TValue);
|
||||
if (unlikely(newarray == NULL && newasize > 0)) { /* allocation failed? */
|
||||
if (l_unlikely(newarray == NULL && newasize > 0)) { /* allocation failed? */
|
||||
freehash(L, &newt); /* release new hash part */
|
||||
luaM_error(L); /* raise error (with array unchanged) */
|
||||
}
|
||||
@@ -577,10 +622,10 @@ static void rehash (lua_State *L, Table *t, const TValue *ek) {
|
||||
|
||||
|
||||
Table *luaH_new (lua_State *L) {
|
||||
GCObject *o = luaC_newobj(L, LUA_TTABLE, sizeof(Table));
|
||||
GCObject *o = luaC_newobj(L, LUA_VTABLE, sizeof(Table));
|
||||
Table *t = gco2t(o);
|
||||
t->metatable = NULL;
|
||||
t->flags = cast_byte(~0);
|
||||
t->flags = cast_byte(maskflags); /* table has no metamethod fields */
|
||||
t->array = NULL;
|
||||
t->alimit = 0;
|
||||
setnodevector(L, t, 0);
|
||||
@@ -615,21 +660,23 @@ static Node *getfreepos (Table *t) {
|
||||
** put new key in its main position; otherwise (colliding node is in its main
|
||||
** position), new key goes to an empty position.
|
||||
*/
|
||||
TValue *luaH_newkey (lua_State *L, Table *t, const TValue *key) {
|
||||
void luaH_newkey (lua_State *L, Table *t, const TValue *key, TValue *value) {
|
||||
Node *mp;
|
||||
TValue aux;
|
||||
if (unlikely(ttisnil(key)))
|
||||
if (l_unlikely(ttisnil(key)))
|
||||
luaG_runerror(L, "table index is nil");
|
||||
else if (ttisfloat(key)) {
|
||||
lua_Number f = fltvalue(key);
|
||||
lua_Integer k;
|
||||
if (luaV_flttointeger(f, &k, 0)) { /* does key fit in an integer? */
|
||||
if (luaV_flttointeger(f, &k, F2Ieq)) { /* does key fit in an integer? */
|
||||
setivalue(&aux, k);
|
||||
key = &aux; /* insert it as an integer */
|
||||
}
|
||||
else if (unlikely(luai_numisnan(f)))
|
||||
else if (l_unlikely(luai_numisnan(f)))
|
||||
luaG_runerror(L, "table index is NaN");
|
||||
}
|
||||
if (ttisnil(value))
|
||||
return; /* do not insert nil values */
|
||||
mp = mainpositionTV(t, key);
|
||||
if (!isempty(gval(mp)) || isdummy(t)) { /* main position is taken? */
|
||||
Node *othern;
|
||||
@@ -637,10 +684,11 @@ TValue *luaH_newkey (lua_State *L, Table *t, const TValue *key) {
|
||||
if (f == NULL) { /* cannot find a free place? */
|
||||
rehash(L, t, key); /* grow table */
|
||||
/* whatever called 'newkey' takes care of TM cache */
|
||||
return luaH_set(L, t, key); /* insert key into grown table */
|
||||
luaH_set(L, t, key, value); /* insert key into grown table */
|
||||
return;
|
||||
}
|
||||
lua_assert(!isdummy(t));
|
||||
othern = mainposition(t, keytt(mp), &keyval(mp));
|
||||
othern = mainpositionfromnode(t, mp);
|
||||
if (othern != mp) { /* is colliding node out of its main position? */
|
||||
/* yes; move colliding node into free position */
|
||||
while (othern + gnext(othern) != mp) /* find previous */
|
||||
@@ -665,7 +713,7 @@ TValue *luaH_newkey (lua_State *L, Table *t, const TValue *key) {
|
||||
setnodekey(L, mp, key);
|
||||
luaC_barrierback(L, obj2gco(t), key);
|
||||
lua_assert(isempty(gval(mp)));
|
||||
return gval(mp);
|
||||
setobj2t(L, gval(mp), value);
|
||||
}
|
||||
|
||||
|
||||
@@ -707,7 +755,7 @@ const TValue *luaH_getint (Table *t, lua_Integer key) {
|
||||
*/
|
||||
const TValue *luaH_getshortstr (Table *t, TString *key) {
|
||||
Node *n = hashstr(t, key);
|
||||
lua_assert(key->tt == LUA_TSHRSTR);
|
||||
lua_assert(key->tt == LUA_VSHRSTR);
|
||||
for (;;) { /* check whether 'key' is somewhere in the chain */
|
||||
if (keyisshrstr(n) && eqshrstr(keystrval(n), key))
|
||||
return gval(n); /* that's it */
|
||||
@@ -722,12 +770,12 @@ const TValue *luaH_getshortstr (Table *t, TString *key) {
|
||||
|
||||
|
||||
const TValue *luaH_getstr (Table *t, TString *key) {
|
||||
if (key->tt == LUA_TSHRSTR)
|
||||
if (key->tt == LUA_VSHRSTR)
|
||||
return luaH_getshortstr(t, key);
|
||||
else { /* for long strings, use generic case */
|
||||
TValue ko;
|
||||
setsvalue(cast(lua_State *, NULL), &ko, key);
|
||||
return getgeneric(t, &ko);
|
||||
return getgeneric(t, &ko, 0);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -737,44 +785,55 @@ const TValue *luaH_getstr (Table *t, TString *key) {
|
||||
*/
|
||||
const TValue *luaH_get (Table *t, const TValue *key) {
|
||||
switch (ttypetag(key)) {
|
||||
case LUA_TSHRSTR: return luaH_getshortstr(t, tsvalue(key));
|
||||
case LUA_TNUMINT: return luaH_getint(t, ivalue(key));
|
||||
case LUA_TNIL: return &absentkey;
|
||||
case LUA_TNUMFLT: {
|
||||
case LUA_VSHRSTR: return luaH_getshortstr(t, tsvalue(key));
|
||||
case LUA_VNUMINT: return luaH_getint(t, ivalue(key));
|
||||
case LUA_VNIL: return &absentkey;
|
||||
case LUA_VNUMFLT: {
|
||||
lua_Integer k;
|
||||
if (luaV_flttointeger(fltvalue(key), &k, 0)) /* index is an integral? */
|
||||
if (luaV_flttointeger(fltvalue(key), &k, F2Ieq)) /* integral index? */
|
||||
return luaH_getint(t, k); /* use specialized version */
|
||||
/* else... */
|
||||
} /* FALLTHROUGH */
|
||||
default:
|
||||
return getgeneric(t, key);
|
||||
return getgeneric(t, key, 0);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** Finish a raw "set table" operation, where 'slot' is where the value
|
||||
** should have been (the result of a previous "get table").
|
||||
** Beware: when using this function you probably need to check a GC
|
||||
** barrier and invalidate the TM cache.
|
||||
*/
|
||||
void luaH_finishset (lua_State *L, Table *t, const TValue *key,
|
||||
const TValue *slot, TValue *value) {
|
||||
if (isabstkey(slot))
|
||||
luaH_newkey(L, t, key, value);
|
||||
else
|
||||
setobj2t(L, cast(TValue *, slot), value);
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** beware: when using this function you probably need to check a GC
|
||||
** barrier and invalidate the TM cache.
|
||||
*/
|
||||
TValue *luaH_set (lua_State *L, Table *t, const TValue *key) {
|
||||
const TValue *p = luaH_get(t, key);
|
||||
if (!isabstkey(p))
|
||||
return cast(TValue *, p);
|
||||
else return luaH_newkey(L, t, key);
|
||||
void luaH_set (lua_State *L, Table *t, const TValue *key, TValue *value) {
|
||||
const TValue *slot = luaH_get(t, key);
|
||||
luaH_finishset(L, t, key, slot, value);
|
||||
}
|
||||
|
||||
|
||||
void luaH_setint (lua_State *L, Table *t, lua_Integer key, TValue *value) {
|
||||
const TValue *p = luaH_getint(t, key);
|
||||
TValue *cell;
|
||||
if (!isabstkey(p))
|
||||
cell = cast(TValue *, p);
|
||||
else {
|
||||
if (isabstkey(p)) {
|
||||
TValue k;
|
||||
setivalue(&k, key);
|
||||
cell = luaH_newkey(L, t, &k);
|
||||
luaH_newkey(L, t, &k, value);
|
||||
}
|
||||
setobj2t(L, cell, value);
|
||||
else
|
||||
setobj2t(L, cast(TValue *, p), value);
|
||||
}
|
||||
|
||||
|
||||
@@ -833,39 +892,41 @@ static unsigned int binsearch (const TValue *array, unsigned int i,
|
||||
** and 'maxinteger' if t[maxinteger] is present.)
|
||||
** (In the next explanation, we use Lua indices, that is, with base 1.
|
||||
** The code itself uses base 0 when indexing the array part of the table.)
|
||||
** The code starts with 'limit', a position in the array part that may
|
||||
** be a boundary.
|
||||
** The code starts with 'limit = t->alimit', a position in the array
|
||||
** part that may be a boundary.
|
||||
**
|
||||
** (1) If 't[limit]' is empty, there must be a boundary before it.
|
||||
** As a common case (e.g., after 't[#t]=nil'), check whether 'hint-1'
|
||||
** As a common case (e.g., after 't[#t]=nil'), check whether 'limit-1'
|
||||
** is present. If so, it is a boundary. Otherwise, do a binary search
|
||||
** between 0 and limit to find a boundary. In both cases, try to
|
||||
** use this boundary as the new 'limit', as a hint for the next call.
|
||||
** use this boundary as the new 'alimit', as a hint for the next call.
|
||||
**
|
||||
** (2) If 't[limit]' is not empty and the array has more elements
|
||||
** after 'limit', try to find a boundary there. Again, try first
|
||||
** the special case (which should be quite frequent) where 'limit+1'
|
||||
** is empty, so that 'limit' is a boundary. Otherwise, check the
|
||||
** last element of the array part (set it as a new limit). If it is empty,
|
||||
** there must be a boundary between the old limit (present) and the new
|
||||
** limit (absent), which is found with a binary search. (This boundary
|
||||
** always can be a new limit.)
|
||||
** last element of the array part. If it is empty, there must be a
|
||||
** boundary between the old limit (present) and the last element
|
||||
** (absent), which is found with a binary search. (This boundary always
|
||||
** can be a new limit.)
|
||||
**
|
||||
** (3) The last case is when there are no elements in the array part
|
||||
** (limit == 0) or its last element (the new limit) is present.
|
||||
** In this case, must check the hash part. If there is no hash part,
|
||||
** the boundary is 0. Otherwise, if 'limit+1' is absent, 'limit' is
|
||||
** a boundary. Finally, if 'limit+1' is present, call 'hash_search'
|
||||
** to find a boundary in the hash part of the table. (In those
|
||||
** cases, the boundary is not inside the array part, and therefore
|
||||
** cannot be used as a new limit.)
|
||||
** In this case, must check the hash part. If there is no hash part
|
||||
** or 'limit+1' is absent, 'limit' is a boundary. Otherwise, call
|
||||
** 'hash_search' to find a boundary in the hash part of the table.
|
||||
** (In those cases, the boundary is not inside the array part, and
|
||||
** therefore cannot be used as a new limit.)
|
||||
*/
|
||||
lua_Unsigned luaH_getn (Table *t) {
|
||||
unsigned int limit = t->alimit;
|
||||
if (limit > 0 && isempty(&t->array[limit - 1])) {
|
||||
/* (1) there must be a boundary before 'limit' */
|
||||
if (limit > 0 && isempty(&t->array[limit - 1])) { /* (1)? */
|
||||
/* there must be a boundary before 'limit' */
|
||||
if (limit >= 2 && !isempty(&t->array[limit - 2])) {
|
||||
/* 'limit - 1' is a boundary; can it be a new limit? */
|
||||
if (ispow2realasize(t) && !ispow2(limit - 1)) {
|
||||
t->alimit = limit - 1;
|
||||
setnorealasize(t);
|
||||
setnorealasize(t); /* now 'alimit' is not the real size */
|
||||
}
|
||||
return limit - 1;
|
||||
}
|
||||
@@ -880,8 +941,8 @@ lua_Unsigned luaH_getn (Table *t) {
|
||||
}
|
||||
}
|
||||
/* 'limit' is zero or present in table */
|
||||
if (!limitequalsasize(t)) {
|
||||
/* (2) 'limit' > 0 and array has more elements after 'limit' */
|
||||
if (!limitequalsasize(t)) { /* (2)? */
|
||||
/* 'limit' > 0 and array has more elements after 'limit' */
|
||||
if (isempty(&t->array[limit])) /* 'limit + 1' is empty? */
|
||||
return limit; /* this is the boundary */
|
||||
/* else, try last element in the array */
|
||||
@@ -899,7 +960,7 @@ lua_Unsigned luaH_getn (Table *t) {
|
||||
lua_assert(limit == luaH_realasize(t) &&
|
||||
(limit == 0 || !isempty(&t->array[limit - 1])));
|
||||
if (isdummy(t) || isempty(luaH_getint(t, cast(lua_Integer, limit + 1))))
|
||||
return limit; /* 'limit + 1' is absent... */
|
||||
return limit; /* 'limit + 1' is absent */
|
||||
else /* 'limit + 1' is also present */
|
||||
return hash_search(t, limit);
|
||||
}
|
||||
@@ -908,6 +969,8 @@ lua_Unsigned luaH_getn (Table *t) {
|
||||
|
||||
#if defined(LUA_DEBUG)
|
||||
|
||||
/* export these functions for the test library */
|
||||
|
||||
Node *luaH_mainposition (const Table *t, const TValue *key) {
|
||||
return mainpositionTV(t, key);
|
||||
}
|
||||
|
||||
@@ -15,7 +15,12 @@
|
||||
#define gnext(n) ((n)->u.next)
|
||||
|
||||
|
||||
#define invalidateTMcache(t) ((t)->flags = 0)
|
||||
/*
|
||||
** Clear all bits of fast-access metamethods, which means that the table
|
||||
** may have any of these metamethods. (First access that fails after the
|
||||
** clearing will set the bit again.)
|
||||
*/
|
||||
#define invalidateTMcache(t) ((t)->flags &= ~maskflags)
|
||||
|
||||
|
||||
/* true when 't' is using 'dummynode' as its hash part */
|
||||
@@ -27,7 +32,7 @@
|
||||
|
||||
|
||||
/* returns the Node, given the value of a table entry */
|
||||
#define nodefromval(v) cast(Node *, (v))
|
||||
#define nodefromval(v) cast(Node *, (v))
|
||||
|
||||
|
||||
LUAI_FUNC const TValue *luaH_getint (Table *t, lua_Integer key);
|
||||
@@ -36,8 +41,12 @@ LUAI_FUNC void luaH_setint (lua_State *L, Table *t, lua_Integer key,
|
||||
LUAI_FUNC const TValue *luaH_getshortstr (Table *t, TString *key);
|
||||
LUAI_FUNC const TValue *luaH_getstr (Table *t, TString *key);
|
||||
LUAI_FUNC const TValue *luaH_get (Table *t, const TValue *key);
|
||||
LUAI_FUNC TValue *luaH_newkey (lua_State *L, Table *t, const TValue *key);
|
||||
LUAI_FUNC TValue *luaH_set (lua_State *L, Table *t, const TValue *key);
|
||||
LUAI_FUNC void luaH_newkey (lua_State *L, Table *t, const TValue *key,
|
||||
TValue *value);
|
||||
LUAI_FUNC void luaH_set (lua_State *L, Table *t, const TValue *key,
|
||||
TValue *value);
|
||||
LUAI_FUNC void luaH_finishset (lua_State *L, Table *t, const TValue *key,
|
||||
const TValue *slot, TValue *value);
|
||||
LUAI_FUNC Table *luaH_new (lua_State *L);
|
||||
LUAI_FUNC void luaH_resize (lua_State *L, Table *t, unsigned int nasize,
|
||||
unsigned int nhsize);
|
||||
|
||||
@@ -59,8 +59,9 @@ static void checktab (lua_State *L, int arg, int what) {
|
||||
|
||||
|
||||
static int tinsert (lua_State *L) {
|
||||
lua_Integer e = aux_getn(L, 1, TAB_RW) + 1; /* first empty element */
|
||||
lua_Integer pos; /* where to insert new element */
|
||||
lua_Integer e = aux_getn(L, 1, TAB_RW);
|
||||
e = luaL_intop(+, e, 1); /* first empty element */
|
||||
switch (lua_gettop(L)) {
|
||||
case 2: { /* called with only 2 arguments */
|
||||
pos = e; /* insert new element at the end */
|
||||
@@ -145,9 +146,9 @@ static int tmove (lua_State *L) {
|
||||
|
||||
static void addfield (lua_State *L, luaL_Buffer *b, lua_Integer i) {
|
||||
lua_geti(L, 1, i);
|
||||
if (!lua_isstring(L, -1))
|
||||
luaL_error(L, "invalid value (%s) at index %d in table for 'concat'",
|
||||
luaL_typename(L, -1), i);
|
||||
if (l_unlikely(!lua_isstring(L, -1)))
|
||||
luaL_error(L, "invalid value (%s) at index %I in table for 'concat'",
|
||||
luaL_typename(L, -1), (LUAI_UACINT)i);
|
||||
luaL_addvalue(b);
|
||||
}
|
||||
|
||||
@@ -196,7 +197,8 @@ static int tunpack (lua_State *L) {
|
||||
lua_Integer e = luaL_opt(L, luaL_checkinteger, 3, luaL_len(L, 1));
|
||||
if (i > e) return 0; /* empty range */
|
||||
n = (lua_Unsigned)e - i; /* number of elements minus 1 (avoid overflows) */
|
||||
if (n >= (unsigned int)INT_MAX || !lua_checkstack(L, (int)(++n)))
|
||||
if (l_unlikely(n >= (unsigned int)INT_MAX ||
|
||||
!lua_checkstack(L, (int)(++n))))
|
||||
return luaL_error(L, "too many results to unpack");
|
||||
for (; i < e; i++) { /* push arg[i..e - 1] (to avoid overflows) */
|
||||
lua_geti(L, 1, i);
|
||||
@@ -300,14 +302,14 @@ static IdxT partition (lua_State *L, IdxT lo, IdxT up) {
|
||||
for (;;) {
|
||||
/* next loop: repeat ++i while a[i] < P */
|
||||
while ((void)lua_geti(L, 1, ++i), sort_comp(L, -1, -2)) {
|
||||
if (i == up - 1) /* a[i] < P but a[up - 1] == P ?? */
|
||||
if (l_unlikely(i == up - 1)) /* a[i] < P but a[up - 1] == P ?? */
|
||||
luaL_error(L, "invalid order function for sorting");
|
||||
lua_pop(L, 1); /* remove a[i] */
|
||||
}
|
||||
/* after the loop, a[i] >= P and a[lo .. i - 1] < P */
|
||||
/* next loop: repeat --j while P < a[j] */
|
||||
while ((void)lua_geti(L, 1, --j), sort_comp(L, -3, -1)) {
|
||||
if (j < i) /* j < i but a[j] > P ?? */
|
||||
if (l_unlikely(j < i)) /* j < i but a[j] > P ?? */
|
||||
luaL_error(L, "invalid order function for sorting");
|
||||
lua_pop(L, 1); /* remove a[j] */
|
||||
}
|
||||
@@ -338,7 +340,7 @@ static IdxT choosePivot (IdxT lo, IdxT up, unsigned int rnd) {
|
||||
|
||||
|
||||
/*
|
||||
** QuickSort algorithm (recursive function)
|
||||
** Quicksort algorithm (recursive function)
|
||||
*/
|
||||
static void auxsort (lua_State *L, IdxT lo, IdxT up,
|
||||
unsigned int rnd) {
|
||||
|
||||
@@ -62,8 +62,10 @@ static void pushobject (lua_State *L, const TValue *o) {
|
||||
}
|
||||
|
||||
|
||||
static void badexit (const char *fmt, const char *s) {
|
||||
fprintf(stderr, fmt, s);
|
||||
static void badexit (const char *fmt, const char *s1, const char *s2) {
|
||||
fprintf(stderr, fmt, s1);
|
||||
if (s2)
|
||||
fprintf(stderr, "extra info: %s\n", s2);
|
||||
/* avoid assertion failures when exiting */
|
||||
l_memcontrol.numblocks = l_memcontrol.total = 0;
|
||||
exit(EXIT_FAILURE);
|
||||
@@ -71,40 +73,83 @@ static void badexit (const char *fmt, const char *s) {
|
||||
|
||||
|
||||
static int tpanic (lua_State *L) {
|
||||
const char *msg = lua_tostring(L, -1);
|
||||
if (msg == NULL) msg = "error object is not a string";
|
||||
return (badexit("PANIC: unprotected error in call to Lua API (%s)\n",
|
||||
lua_tostring(L, -1)),
|
||||
msg, NULL),
|
||||
0); /* do not return to Lua */
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** Warning function for tests. Fist, it concatenates all parts of
|
||||
** a warning in buffer 'buff'. Then:
|
||||
** - messages starting with '#' are shown on standard output (used to
|
||||
** test explicit warnings);
|
||||
** - messages containing '@' are stored in global '_WARN' (used to test
|
||||
** errors that generate warnings);
|
||||
** Warning function for tests. First, it concatenates all parts of
|
||||
** a warning in buffer 'buff'. Then, it has three modes:
|
||||
** - 0.normal: messages starting with '#' are shown on standard output;
|
||||
** - other messages abort the tests (they represent real warning
|
||||
** conditions; the standard tests should not generate these conditions
|
||||
** unexpectedly).
|
||||
** unexpectedly);
|
||||
** - 1.allow: all messages are shown;
|
||||
** - 2.store: all warnings go to the global '_WARN';
|
||||
*/
|
||||
static void warnf (void *ud, const char *msg, int tocont) {
|
||||
lua_State *L = cast(lua_State *, ud);
|
||||
static char buff[200] = ""; /* should be enough for tests... */
|
||||
static int onoff = 0;
|
||||
static int mode = 0; /* start in normal mode */
|
||||
static int lasttocont = 0;
|
||||
if (!lasttocont && !tocont && *msg == '@') { /* control message? */
|
||||
if (buff[0] != '\0')
|
||||
badexit("Control warning during warning: %s\naborting...\n", msg, buff);
|
||||
if (strcmp(msg, "@off") == 0)
|
||||
onoff = 0;
|
||||
else if (strcmp(msg, "@on") == 0)
|
||||
onoff = 1;
|
||||
else if (strcmp(msg, "@normal") == 0)
|
||||
mode = 0;
|
||||
else if (strcmp(msg, "@allow") == 0)
|
||||
mode = 1;
|
||||
else if (strcmp(msg, "@store") == 0)
|
||||
mode = 2;
|
||||
else
|
||||
badexit("Invalid control warning in test mode: %s\naborting...\n",
|
||||
msg, NULL);
|
||||
return;
|
||||
}
|
||||
lasttocont = tocont;
|
||||
if (strlen(msg) >= sizeof(buff) - strlen(buff))
|
||||
badexit("%s", "warnf-buffer overflow");
|
||||
badexit("warnf-buffer overflow (%s)\n", msg, buff);
|
||||
strcat(buff, msg); /* add new message to current warning */
|
||||
if (!tocont) { /* message finished? */
|
||||
if (buff[0] == '#') /* expected warning? */
|
||||
printf("Expected Lua warning: %s\n", buff); /* print it */
|
||||
else if (strchr(buff, '@') != NULL) { /* warning for test purposes? */
|
||||
lua_State *L = cast(lua_State *, ud);
|
||||
lua_unlock(L);
|
||||
lua_pushstring(L, buff);
|
||||
lua_setglobal(L, "_WARN"); /* assign message to global '_WARN' */
|
||||
lua_lock(L);
|
||||
lua_unlock(L);
|
||||
luaL_checkstack(L, 1, "warn stack space");
|
||||
lua_getglobal(L, "_WARN");
|
||||
if (!lua_toboolean(L, -1))
|
||||
lua_pop(L, 1); /* ok, no previous unexpected warning */
|
||||
else {
|
||||
badexit("Unhandled warning in store mode: %s\naborting...\n",
|
||||
lua_tostring(L, -1), buff);
|
||||
}
|
||||
lua_lock(L);
|
||||
switch (mode) {
|
||||
case 0: { /* normal */
|
||||
if (buff[0] != '#' && onoff) /* unexpected warning? */
|
||||
badexit("Unexpected warning in test mode: %s\naborting...\n",
|
||||
buff, NULL);
|
||||
} /* FALLTHROUGH */
|
||||
case 1: { /* allow */
|
||||
if (onoff)
|
||||
fprintf(stderr, "Lua warning: %s\n", buff); /* print warning */
|
||||
break;
|
||||
}
|
||||
case 2: { /* store */
|
||||
lua_unlock(L);
|
||||
luaL_checkstack(L, 1, "warn stack space");
|
||||
lua_pushstring(L, buff);
|
||||
lua_setglobal(L, "_WARN"); /* assign message to global '_WARN' */
|
||||
lua_lock(L);
|
||||
break;
|
||||
}
|
||||
}
|
||||
else /* a real warning; should not happen during tests */
|
||||
badexit("Unexpected warning in test mode: %s\naborting...\n", buff);
|
||||
buff[0] = '\0'; /* prepare buffer for next warning */
|
||||
}
|
||||
}
|
||||
@@ -143,7 +188,8 @@ typedef union Header {
|
||||
|
||||
|
||||
Memcontrol l_memcontrol =
|
||||
{0UL, 0UL, 0UL, 0UL, (~0UL), {0UL, 0UL, 0UL, 0UL, 0UL, 0UL, 0UL, 0UL, 0UL}};
|
||||
{0, 0UL, 0UL, 0UL, 0UL, (~0UL),
|
||||
{0UL, 0UL, 0UL, 0UL, 0UL, 0UL, 0UL, 0UL, 0UL}};
|
||||
|
||||
|
||||
static void freeblock (Memcontrol *mc, Header *block) {
|
||||
@@ -182,6 +228,10 @@ void *debug_realloc (void *ud, void *b, size_t oldsize, size_t size) {
|
||||
freeblock(mc, block);
|
||||
return NULL;
|
||||
}
|
||||
if (mc->failnext) {
|
||||
mc->failnext = 0;
|
||||
return NULL; /* fake a single memory allocation error */
|
||||
}
|
||||
if (mc->countlimit != ~0UL && size != oldsize) { /* count limit in use? */
|
||||
if (mc->countlimit == 0)
|
||||
return NULL; /* fake a memory allocation error */
|
||||
@@ -224,11 +274,15 @@ void *debug_realloc (void *ud, void *b, size_t oldsize, size_t size) {
|
||||
|
||||
|
||||
/*
|
||||
** {======================================================
|
||||
** Functions to check memory consistency
|
||||
** =======================================================
|
||||
** {=====================================================================
|
||||
** Functions to check memory consistency.
|
||||
** Most of these checks are done through asserts, so this code does
|
||||
** not make sense with asserts off. For this reason, it uses 'assert'
|
||||
** directly, instead of 'lua_assert'.
|
||||
** ======================================================================
|
||||
*/
|
||||
|
||||
#include <assert.h>
|
||||
|
||||
/*
|
||||
** Check GC invariants. For incremental mode, a black object cannot
|
||||
@@ -261,11 +315,15 @@ static void printobj (global_State *g, GCObject *o) {
|
||||
ttypename(novariant(o->tt)), (void *)o,
|
||||
isdead(g,o) ? 'd' : isblack(o) ? 'b' : iswhite(o) ? 'w' : 'g',
|
||||
"ns01oTt"[getage(o)], o->marked);
|
||||
if (o->tt == LUA_TSHRSTR || o->tt == LUA_TLNGSTR)
|
||||
if (o->tt == LUA_VSHRSTR || o->tt == LUA_VLNGSTR)
|
||||
printf(" '%s'", getstr(gco2ts(o)));
|
||||
}
|
||||
|
||||
|
||||
void lua_printobj (lua_State *L, struct GCObject *o) {
|
||||
printobj(G(L), o);
|
||||
}
|
||||
|
||||
static int testobjref (global_State *g, GCObject *f, GCObject *t) {
|
||||
int r1 = testobjref1(g, f, t);
|
||||
if (!r1) {
|
||||
@@ -278,13 +336,23 @@ static int testobjref (global_State *g, GCObject *f, GCObject *t) {
|
||||
return r1;
|
||||
}
|
||||
|
||||
#define checkobjref(g,f,t) \
|
||||
{ if (t) lua_longassert(testobjref(g,f,obj2gco(t))); }
|
||||
|
||||
static void checkobjref (global_State *g, GCObject *f, GCObject *t) {
|
||||
assert(testobjref(g, f, t));
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** Version where 't' can be NULL. In that case, it should not apply the
|
||||
** macro 'obj2gco' over the object. ('t' may have several types, so this
|
||||
** definition must be a macro.) Most checks need this version, because
|
||||
** the check may run while an object is still being created.
|
||||
*/
|
||||
#define checkobjrefN(g,f,t) { if (t) checkobjref(g,f,obj2gco(t)); }
|
||||
|
||||
|
||||
static void checkvalref (global_State *g, GCObject *f, const TValue *t) {
|
||||
lua_assert(!iscollectable(t) ||
|
||||
(righttt(t) && testobjref(g, f, gcvalue(t))));
|
||||
assert(!iscollectable(t) || (righttt(t) && testobjref(g, f, gcvalue(t))));
|
||||
}
|
||||
|
||||
|
||||
@@ -293,14 +361,14 @@ static void checktable (global_State *g, Table *h) {
|
||||
unsigned int asize = luaH_realasize(h);
|
||||
Node *n, *limit = gnode(h, sizenode(h));
|
||||
GCObject *hgc = obj2gco(h);
|
||||
checkobjref(g, hgc, h->metatable);
|
||||
checkobjrefN(g, hgc, h->metatable);
|
||||
for (i = 0; i < asize; i++)
|
||||
checkvalref(g, hgc, &h->array[i]);
|
||||
for (n = gnode(h, 0); n < limit; n++) {
|
||||
if (!isempty(gval(n))) {
|
||||
TValue k;
|
||||
getnodekey(g->mainthread, &k, n);
|
||||
lua_assert(!keyisnil(n));
|
||||
assert(!keyisnil(n));
|
||||
checkvalref(g, hgc, &k);
|
||||
checkvalref(g, hgc, gval(n));
|
||||
}
|
||||
@@ -311,30 +379,26 @@ static void checktable (global_State *g, Table *h) {
|
||||
static void checkudata (global_State *g, Udata *u) {
|
||||
int i;
|
||||
GCObject *hgc = obj2gco(u);
|
||||
checkobjref(g, hgc, u->metatable);
|
||||
checkobjrefN(g, hgc, u->metatable);
|
||||
for (i = 0; i < u->nuvalue; i++)
|
||||
checkvalref(g, hgc, &u->uv[i].uv);
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** All marks are conditional because a GC may happen while the
|
||||
** prototype is still being created
|
||||
*/
|
||||
static void checkproto (global_State *g, Proto *f) {
|
||||
int i;
|
||||
GCObject *fgc = obj2gco(f);
|
||||
checkobjref(g, fgc, f->source);
|
||||
checkobjrefN(g, fgc, f->source);
|
||||
for (i=0; i<f->sizek; i++) {
|
||||
if (ttisstring(f->k + i))
|
||||
checkobjref(g, fgc, tsvalue(f->k + i));
|
||||
if (iscollectable(f->k + i))
|
||||
checkobjref(g, fgc, gcvalue(f->k + i));
|
||||
}
|
||||
for (i=0; i<f->sizeupvalues; i++)
|
||||
checkobjref(g, fgc, f->upvalues[i].name);
|
||||
checkobjrefN(g, fgc, f->upvalues[i].name);
|
||||
for (i=0; i<f->sizep; i++)
|
||||
checkobjref(g, fgc, f->p[i]);
|
||||
checkobjrefN(g, fgc, f->p[i]);
|
||||
for (i=0; i<f->sizelocvars; i++)
|
||||
checkobjref(g, fgc, f->locvars[i].varname);
|
||||
checkobjrefN(g, fgc, f->locvars[i].varname);
|
||||
}
|
||||
|
||||
|
||||
@@ -349,11 +413,11 @@ static void checkCclosure (global_State *g, CClosure *cl) {
|
||||
static void checkLclosure (global_State *g, LClosure *cl) {
|
||||
GCObject *clgc = obj2gco(cl);
|
||||
int i;
|
||||
checkobjref(g, clgc, cl->p);
|
||||
checkobjrefN(g, clgc, cl->p);
|
||||
for (i=0; i<cl->nupvalues; i++) {
|
||||
UpVal *uv = cl->upvals[i];
|
||||
if (uv) {
|
||||
checkobjref(g, clgc, uv);
|
||||
checkobjrefN(g, clgc, uv);
|
||||
if (!upisopen(uv))
|
||||
checkvalref(g, obj2gco(uv), uv->v);
|
||||
}
|
||||
@@ -376,58 +440,60 @@ static void checkstack (global_State *g, lua_State *L1) {
|
||||
StkId o;
|
||||
CallInfo *ci;
|
||||
UpVal *uv;
|
||||
lua_assert(!isdead(g, L1));
|
||||
assert(!isdead(g, L1));
|
||||
if (L1->stack == NULL) { /* incomplete thread? */
|
||||
assert(L1->openupval == NULL && L1->ci == NULL);
|
||||
return;
|
||||
}
|
||||
for (uv = L1->openupval; uv != NULL; uv = uv->u.open.next)
|
||||
lua_assert(upisopen(uv)); /* must be open */
|
||||
assert(upisopen(uv)); /* must be open */
|
||||
assert(L1->top <= L1->stack_last);
|
||||
assert(L1->tbclist <= L1->top);
|
||||
for (ci = L1->ci; ci != NULL; ci = ci->previous) {
|
||||
lua_assert(ci->top <= L1->stack_last);
|
||||
lua_assert(lua_checkpc(ci));
|
||||
assert(ci->top <= L1->stack_last);
|
||||
assert(lua_checkpc(ci));
|
||||
}
|
||||
if (L1->stack) { /* complete thread? */
|
||||
for (o = L1->stack; o < L1->stack_last + EXTRA_STACK; o++)
|
||||
checkliveness(L1, s2v(o)); /* entire stack must have valid values */
|
||||
}
|
||||
else lua_assert(L1->stacksize == 0);
|
||||
for (o = L1->stack; o < L1->stack_last; o++)
|
||||
checkliveness(L1, s2v(o)); /* entire stack must have valid values */
|
||||
}
|
||||
|
||||
|
||||
static void checkrefs (global_State *g, GCObject *o) {
|
||||
switch (o->tt) {
|
||||
case LUA_TUSERDATA: {
|
||||
case LUA_VUSERDATA: {
|
||||
checkudata(g, gco2u(o));
|
||||
break;
|
||||
}
|
||||
case LUA_TUPVAL:
|
||||
case LUA_TUPVALTBC: {
|
||||
case LUA_VUPVAL: {
|
||||
checkvalref(g, o, gco2upv(o)->v);
|
||||
break;
|
||||
}
|
||||
case LUA_TTABLE: {
|
||||
case LUA_VTABLE: {
|
||||
checktable(g, gco2t(o));
|
||||
break;
|
||||
}
|
||||
case LUA_TTHREAD: {
|
||||
case LUA_VTHREAD: {
|
||||
checkstack(g, gco2th(o));
|
||||
break;
|
||||
}
|
||||
case LUA_TLCL: {
|
||||
case LUA_VLCL: {
|
||||
checkLclosure(g, gco2lcl(o));
|
||||
break;
|
||||
}
|
||||
case LUA_TCCL: {
|
||||
case LUA_VCCL: {
|
||||
checkCclosure(g, gco2ccl(o));
|
||||
break;
|
||||
}
|
||||
case LUA_TPROTO: {
|
||||
case LUA_VPROTO: {
|
||||
checkproto(g, gco2p(o));
|
||||
break;
|
||||
}
|
||||
case LUA_TSHRSTR:
|
||||
case LUA_TLNGSTR: {
|
||||
lua_assert(!isgray(o)); /* strings are never gray */
|
||||
case LUA_VSHRSTR:
|
||||
case LUA_VLNGSTR: {
|
||||
assert(!isgray(o)); /* strings are never gray */
|
||||
break;
|
||||
}
|
||||
default: lua_assert(0);
|
||||
default: assert(0);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -435,7 +501,7 @@ static void checkrefs (global_State *g, GCObject *o) {
|
||||
/*
|
||||
** Check consistency of an object:
|
||||
** - Dead objects can only happen in the 'allgc' list during a sweep
|
||||
** phase (controled by the caller through 'maybedead').
|
||||
** phase (controlled by the caller through 'maybedead').
|
||||
** - During pause, all objects must be white.
|
||||
** - In generational mode:
|
||||
** * objects must be old enough for their lists ('listage').
|
||||
@@ -446,18 +512,18 @@ static void checkrefs (global_State *g, GCObject *o) {
|
||||
static void checkobject (global_State *g, GCObject *o, int maybedead,
|
||||
int listage) {
|
||||
if (isdead(g, o))
|
||||
lua_assert(maybedead);
|
||||
assert(maybedead);
|
||||
else {
|
||||
lua_assert(g->gcstate != GCSpause || iswhite(o));
|
||||
assert(g->gcstate != GCSpause || iswhite(o));
|
||||
if (g->gckind == KGC_GEN) { /* generational mode? */
|
||||
lua_assert(getage(o) >= listage);
|
||||
lua_assert(!iswhite(o) || !isold(o));
|
||||
assert(getage(o) >= listage);
|
||||
assert(!iswhite(o) || !isold(o));
|
||||
if (isold(o)) {
|
||||
lua_assert(isblack(o) ||
|
||||
assert(isblack(o) ||
|
||||
getage(o) == G_TOUCHED1 ||
|
||||
getage(o) == G_OLD0 ||
|
||||
o->tt == LUA_TTHREAD ||
|
||||
(o->tt == LUA_TUPVAL && upisopen(gco2upv(o))));
|
||||
o->tt == LUA_VTHREAD ||
|
||||
(o->tt == LUA_VUPVAL && upisopen(gco2upv(o))));
|
||||
}
|
||||
}
|
||||
checkrefs(g, o);
|
||||
@@ -465,53 +531,94 @@ static void checkobject (global_State *g, GCObject *o, int maybedead,
|
||||
}
|
||||
|
||||
|
||||
static void checkgraylist (global_State *g, GCObject *o) {
|
||||
static lu_mem checkgraylist (global_State *g, GCObject *o) {
|
||||
int total = 0; /* count number of elements in the list */
|
||||
((void)g); /* better to keep it available if we need to print an object */
|
||||
while (o) {
|
||||
lua_assert(isgray(o) || getage(o) == G_TOUCHED2);
|
||||
assert(!!isgray(o) ^ (getage(o) == G_TOUCHED2));
|
||||
assert(!testbit(o->marked, TESTBIT));
|
||||
if (keepinvariant(g))
|
||||
l_setbit(o->marked, TESTBIT); /* mark that object is in a gray list */
|
||||
total++;
|
||||
switch (o->tt) {
|
||||
case LUA_TTABLE: o = gco2t(o)->gclist; break;
|
||||
case LUA_TLCL: o = gco2lcl(o)->gclist; break;
|
||||
case LUA_TCCL: o = gco2ccl(o)->gclist; break;
|
||||
case LUA_TTHREAD: o = gco2th(o)->gclist; break;
|
||||
case LUA_TPROTO: o = gco2p(o)->gclist; break;
|
||||
default: lua_assert(0); /* other objects cannot be in a gray list */
|
||||
case LUA_VTABLE: o = gco2t(o)->gclist; break;
|
||||
case LUA_VLCL: o = gco2lcl(o)->gclist; break;
|
||||
case LUA_VCCL: o = gco2ccl(o)->gclist; break;
|
||||
case LUA_VTHREAD: o = gco2th(o)->gclist; break;
|
||||
case LUA_VPROTO: o = gco2p(o)->gclist; break;
|
||||
case LUA_VUSERDATA:
|
||||
assert(gco2u(o)->nuvalue > 0);
|
||||
o = gco2u(o)->gclist;
|
||||
break;
|
||||
default: assert(0); /* other objects cannot be in a gray list */
|
||||
}
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** Check objects in gray lists.
|
||||
*/
|
||||
static void checkgrays (global_State *g) {
|
||||
if (!keepinvariant(g)) return;
|
||||
checkgraylist(g, g->gray);
|
||||
checkgraylist(g, g->grayagain);
|
||||
checkgraylist(g, g->weak);
|
||||
checkgraylist(g, g->ephemeron);
|
||||
static lu_mem checkgrays (global_State *g) {
|
||||
int total = 0; /* count number of elements in all lists */
|
||||
if (!keepinvariant(g)) return total;
|
||||
total += checkgraylist(g, g->gray);
|
||||
total += checkgraylist(g, g->grayagain);
|
||||
total += checkgraylist(g, g->weak);
|
||||
total += checkgraylist(g, g->allweak);
|
||||
total += checkgraylist(g, g->ephemeron);
|
||||
return total;
|
||||
}
|
||||
|
||||
|
||||
static void checklist (global_State *g, int maybedead, int tof,
|
||||
/*
|
||||
** Check whether 'o' should be in a gray list. If so, increment
|
||||
** 'count' and check its TESTBIT. (It must have been previously set by
|
||||
** 'checkgraylist'.)
|
||||
*/
|
||||
static void incifingray (global_State *g, GCObject *o, lu_mem *count) {
|
||||
if (!keepinvariant(g))
|
||||
return; /* gray lists not being kept in these phases */
|
||||
if (o->tt == LUA_VUPVAL) {
|
||||
/* only open upvalues can be gray */
|
||||
assert(!isgray(o) || upisopen(gco2upv(o)));
|
||||
return; /* upvalues are never in gray lists */
|
||||
}
|
||||
/* these are the ones that must be in gray lists */
|
||||
if (isgray(o) || getage(o) == G_TOUCHED2) {
|
||||
(*count)++;
|
||||
assert(testbit(o->marked, TESTBIT));
|
||||
resetbit(o->marked, TESTBIT); /* prepare for next cycle */
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
static lu_mem checklist (global_State *g, int maybedead, int tof,
|
||||
GCObject *newl, GCObject *survival, GCObject *old, GCObject *reallyold) {
|
||||
GCObject *o;
|
||||
lu_mem total = 0; /* number of object that should be in gray lists */
|
||||
for (o = newl; o != survival; o = o->next) {
|
||||
checkobject(g, o, maybedead, G_NEW);
|
||||
lua_assert(!tof == !tofinalize(o));
|
||||
incifingray(g, o, &total);
|
||||
assert(!tof == !tofinalize(o));
|
||||
}
|
||||
for (o = survival; o != old; o = o->next) {
|
||||
checkobject(g, o, 0, G_SURVIVAL);
|
||||
lua_assert(!tof == !tofinalize(o));
|
||||
incifingray(g, o, &total);
|
||||
assert(!tof == !tofinalize(o));
|
||||
}
|
||||
for (o = old; o != reallyold; o = o->next) {
|
||||
checkobject(g, o, 0, G_OLD1);
|
||||
lua_assert(!tof == !tofinalize(o));
|
||||
incifingray(g, o, &total);
|
||||
assert(!tof == !tofinalize(o));
|
||||
}
|
||||
for (o = reallyold; o != NULL; o = o->next) {
|
||||
checkobject(g, o, 0, G_OLD);
|
||||
lua_assert(!tof == !tofinalize(o));
|
||||
incifingray(g, o, &total);
|
||||
assert(!tof == !tofinalize(o));
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
|
||||
@@ -519,32 +626,39 @@ int lua_checkmemory (lua_State *L) {
|
||||
global_State *g = G(L);
|
||||
GCObject *o;
|
||||
int maybedead;
|
||||
lu_mem totalin; /* total of objects that are in gray lists */
|
||||
lu_mem totalshould; /* total of objects that should be in gray lists */
|
||||
if (keepinvariant(g)) {
|
||||
lua_assert(!iswhite(g->mainthread));
|
||||
lua_assert(!iswhite(gcvalue(&g->l_registry)));
|
||||
assert(!iswhite(g->mainthread));
|
||||
assert(!iswhite(gcvalue(&g->l_registry)));
|
||||
}
|
||||
lua_assert(!isdead(g, gcvalue(&g->l_registry)));
|
||||
lua_assert(g->sweepgc == NULL || issweepphase(g));
|
||||
checkgrays(g);
|
||||
assert(!isdead(g, gcvalue(&g->l_registry)));
|
||||
assert(g->sweepgc == NULL || issweepphase(g));
|
||||
totalin = checkgrays(g);
|
||||
|
||||
/* check 'fixedgc' list */
|
||||
for (o = g->fixedgc; o != NULL; o = o->next) {
|
||||
lua_assert(o->tt == LUA_TSHRSTR && isgray(o) && getage(o) == G_OLD);
|
||||
assert(o->tt == LUA_VSHRSTR && isgray(o) && getage(o) == G_OLD);
|
||||
}
|
||||
|
||||
/* check 'allgc' list */
|
||||
maybedead = (GCSatomic < g->gcstate && g->gcstate <= GCSswpallgc);
|
||||
checklist(g, maybedead, 0, g->allgc, g->survival, g->old, g->reallyold);
|
||||
totalshould = checklist(g, maybedead, 0, g->allgc,
|
||||
g->survival, g->old1, g->reallyold);
|
||||
|
||||
/* check 'finobj' list */
|
||||
checklist(g, 0, 1, g->finobj, g->finobjsur, g->finobjold, g->finobjrold);
|
||||
totalshould += checklist(g, 0, 1, g->finobj,
|
||||
g->finobjsur, g->finobjold1, g->finobjrold);
|
||||
|
||||
/* check 'tobefnz' list */
|
||||
for (o = g->tobefnz; o != NULL; o = o->next) {
|
||||
checkobject(g, o, 0, G_NEW);
|
||||
lua_assert(tofinalize(o));
|
||||
lua_assert(o->tt == LUA_TUSERDATA || o->tt == LUA_TTABLE);
|
||||
incifingray(g, o, &totalshould);
|
||||
assert(tofinalize(o));
|
||||
assert(o->tt == LUA_VUSERDATA || o->tt == LUA_VTABLE);
|
||||
}
|
||||
if (keepinvariant(g))
|
||||
assert(totalin == totalshould);
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -700,11 +814,12 @@ static int listlocals (lua_State *L) {
|
||||
static void printstack (lua_State *L) {
|
||||
int i;
|
||||
int n = lua_gettop(L);
|
||||
printf("stack: >>\n");
|
||||
for (i = 1; i <= n; i++) {
|
||||
printf("%3d: %s\n", i, luaL_tolstring(L, i, NULL));
|
||||
lua_pop(L, 1);
|
||||
}
|
||||
printf("\n");
|
||||
printf("<<\n");
|
||||
}
|
||||
|
||||
|
||||
@@ -742,7 +857,7 @@ static int mem_query (lua_State *L) {
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
return luaL_error(L, "unkown type '%s'", t);
|
||||
return luaL_error(L, "unknown type '%s'", t);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -754,7 +869,14 @@ static int alloc_count (lua_State *L) {
|
||||
l_memcontrol.countlimit = luaL_checkinteger(L, 1);
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
|
||||
static int alloc_failnext (lua_State *L) {
|
||||
UNUSED(L);
|
||||
l_memcontrol.failnext = 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
static int settrick (lua_State *L) {
|
||||
if (ttisnil(obj_at(L, 1)))
|
||||
@@ -859,7 +981,7 @@ static int hash_query (lua_State *L) {
|
||||
static int stacklevel (lua_State *L) {
|
||||
unsigned long a = 0;
|
||||
lua_pushinteger(L, (L->top - L->stack));
|
||||
lua_pushinteger(L, (L->stack_last - L->stack));
|
||||
lua_pushinteger(L, stacksize(L));
|
||||
lua_pushinteger(L, L->nCcalls);
|
||||
lua_pushinteger(L, L->nci);
|
||||
lua_pushinteger(L, (unsigned long)&a);
|
||||
@@ -933,6 +1055,7 @@ static int tref (lua_State *L) {
|
||||
luaL_checkany(L, 1);
|
||||
lua_pushvalue(L, 1);
|
||||
lua_pushinteger(L, luaL_ref(L, LUA_REGISTRYINDEX));
|
||||
(void)level; /* to avoid warnings */
|
||||
lua_assert(lua_gettop(L) == level+1); /* +1 for result */
|
||||
return 1;
|
||||
}
|
||||
@@ -940,6 +1063,7 @@ static int tref (lua_State *L) {
|
||||
static int getref (lua_State *L) {
|
||||
int level = lua_gettop(L);
|
||||
lua_rawgeti(L, LUA_REGISTRYINDEX, luaL_checkinteger(L, 1));
|
||||
(void)level; /* to avoid warnings */
|
||||
lua_assert(lua_gettop(L) == level+1);
|
||||
return 1;
|
||||
}
|
||||
@@ -947,6 +1071,7 @@ static int getref (lua_State *L) {
|
||||
static int unref (lua_State *L) {
|
||||
int level = lua_gettop(L);
|
||||
luaL_unref(L, LUA_REGISTRYINDEX, cast_int(luaL_checkinteger(L, 1)));
|
||||
(void)level; /* to avoid warnings */
|
||||
lua_assert(lua_gettop(L) == level);
|
||||
return 0;
|
||||
}
|
||||
@@ -1103,14 +1228,6 @@ static int doremote (lua_State *L) {
|
||||
}
|
||||
|
||||
|
||||
static int int2fb_aux (lua_State *L) {
|
||||
int b = luaO_int2fb((unsigned int)luaL_checkinteger(L, 1));
|
||||
lua_pushinteger(L, b);
|
||||
lua_pushinteger(L, (unsigned int)luaO_fb2int(b));
|
||||
return 2;
|
||||
}
|
||||
|
||||
|
||||
static int log2_aux (lua_State *L) {
|
||||
unsigned int x = (unsigned int)luaL_checkinteger(L, 1);
|
||||
lua_pushinteger(L, luaO_ceillog2(x));
|
||||
@@ -1242,10 +1359,19 @@ static int getindex_aux (lua_State *L, lua_State *L1, const char **pc) {
|
||||
}
|
||||
|
||||
|
||||
static void pushcode (lua_State *L, int code) {
|
||||
static const char *const codes[] = {"OK", "YIELD", "ERRRUN",
|
||||
"ERRSYNTAX", MEMERRMSG, "ERRGCMM", "ERRERR"};
|
||||
lua_pushstring(L, codes[code]);
|
||||
static const char *const statcodes[] = {"OK", "YIELD", "ERRRUN",
|
||||
"ERRSYNTAX", MEMERRMSG, "ERRGCMM", "ERRERR"};
|
||||
|
||||
/*
|
||||
** Avoid these stat codes from being collected, to avoid possible
|
||||
** memory error when pushing them.
|
||||
*/
|
||||
static void regcodes (lua_State *L) {
|
||||
unsigned int i;
|
||||
for (i = 0; i < sizeof(statcodes) / sizeof(statcodes[0]); i++) {
|
||||
lua_pushboolean(L, 1);
|
||||
lua_setfield(L, LUA_REGISTRYINDEX, statcodes[i]);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1468,7 +1594,7 @@ static int runC (lua_State *L, lua_State *L1, const char *pc) {
|
||||
lua_pushnumber(L1, (lua_Number)getnum);
|
||||
}
|
||||
else if EQ("pushstatus") {
|
||||
pushcode(L1, status);
|
||||
lua_pushstring(L1, statcodes[status]);
|
||||
}
|
||||
else if EQ("pushstring") {
|
||||
lua_pushstring(L1, getstring);
|
||||
@@ -1488,6 +1614,10 @@ static int runC (lua_State *L, lua_State *L1, const char *pc) {
|
||||
else if EQ("pushfstringP") {
|
||||
lua_pushfstring(L1, lua_tostring(L, -2), lua_topointer(L, -1));
|
||||
}
|
||||
else if EQ("rawget") {
|
||||
int t = getindex;
|
||||
lua_rawget(L1, t);
|
||||
}
|
||||
else if EQ("rawgeti") {
|
||||
int t = getindex;
|
||||
lua_rawgeti(L1, t, getnum);
|
||||
@@ -1496,6 +1626,14 @@ static int runC (lua_State *L, lua_State *L1, const char *pc) {
|
||||
int t = getindex;
|
||||
lua_rawgetp(L1, t, cast_voidp(cast_sizet(getnum)));
|
||||
}
|
||||
else if EQ("rawset") {
|
||||
int t = getindex;
|
||||
lua_rawset(L1, t);
|
||||
}
|
||||
else if EQ("rawseti") {
|
||||
int t = getindex;
|
||||
lua_rawseti(L1, t, getnum);
|
||||
}
|
||||
else if EQ("rawsetp") {
|
||||
int t = getindex;
|
||||
lua_rawsetp(L1, t, cast_voidp(cast_sizet(getnum)));
|
||||
@@ -1538,6 +1676,10 @@ static int runC (lua_State *L, lua_State *L1, const char *pc) {
|
||||
const char *s = getstring;
|
||||
lua_setfield(L1, t, s);
|
||||
}
|
||||
else if EQ("seti") {
|
||||
int t = getindex;
|
||||
lua_seti(L1, t, getnum);
|
||||
}
|
||||
else if EQ("setglobal") {
|
||||
const char *s = getstring;
|
||||
lua_setglobal(L1, s);
|
||||
@@ -1565,6 +1707,9 @@ static int runC (lua_State *L, lua_State *L1, const char *pc) {
|
||||
else if EQ("error") {
|
||||
lua_error(L1);
|
||||
}
|
||||
else if EQ("abort") {
|
||||
abort();
|
||||
}
|
||||
else if EQ("throw") {
|
||||
#if defined(__cplusplus)
|
||||
static struct X { int x; } x;
|
||||
@@ -1595,8 +1740,12 @@ static struct X { int x; } x;
|
||||
else if EQ("tostring") {
|
||||
const char *s = lua_tostring(L1, getindex);
|
||||
const char *s1 = lua_pushstring(L1, s);
|
||||
(void)s1; /* to avoid warnings */
|
||||
lua_longassert((s == NULL && s1 == NULL) || strcmp(s, s1) == 0);
|
||||
}
|
||||
else if EQ("Ltolstring") {
|
||||
luaL_tolstring(L1, getindex, NULL);
|
||||
}
|
||||
else if EQ("type") {
|
||||
lua_pushstring(L1, luaL_typename(L1, getnum));
|
||||
}
|
||||
@@ -1609,6 +1758,9 @@ static struct X { int x; } x;
|
||||
if (n == 0) n = lua_gettop(fs);
|
||||
lua_xmove(fs, ts, n);
|
||||
}
|
||||
else if EQ("isyieldable") {
|
||||
lua_pushboolean(L1, lua_isyieldable(lua_tothread(L1, getindex)));
|
||||
}
|
||||
else if EQ("yield") {
|
||||
return lua_yield(L1, getnum);
|
||||
}
|
||||
@@ -1620,6 +1772,9 @@ static struct X { int x; } x;
|
||||
else if EQ("toclose") {
|
||||
lua_toclose(L1, getnum);
|
||||
}
|
||||
else if EQ("closeslot") {
|
||||
lua_closeslot(L1, getnum);
|
||||
}
|
||||
else luaL_error(L, "unknown instruction %s", buff);
|
||||
}
|
||||
return 0;
|
||||
@@ -1651,7 +1806,7 @@ static int Cfunc (lua_State *L) {
|
||||
|
||||
|
||||
static int Cfunck (lua_State *L, int status, lua_KContext ctx) {
|
||||
pushcode(L, status);
|
||||
lua_pushstring(L, statcodes[status]);
|
||||
lua_setglobal(L, "status");
|
||||
lua_pushinteger(L, ctx);
|
||||
lua_setglobal(L, "ctx");
|
||||
@@ -1764,7 +1919,6 @@ static const struct luaL_Reg tests_funcs[] = {
|
||||
{"pobj", gc_printobj},
|
||||
{"getref", getref},
|
||||
{"hash", hash_query},
|
||||
{"int2fb", int2fb_aux},
|
||||
{"log2", log2_aux},
|
||||
{"limits", get_limits},
|
||||
{"listcode", listcode},
|
||||
@@ -1789,6 +1943,7 @@ static const struct luaL_Reg tests_funcs[] = {
|
||||
{"makeCfunc", makeCfunc},
|
||||
{"totalmem", mem_query},
|
||||
{"alloccount", alloc_count},
|
||||
{"allocfailnext", alloc_failnext},
|
||||
{"trick", settrick},
|
||||
{"udataval", udataval},
|
||||
{"unref", unref},
|
||||
@@ -1805,12 +1960,15 @@ static void checkfinalmem (void) {
|
||||
|
||||
int luaB_opentests (lua_State *L) {
|
||||
void *ud;
|
||||
lua_Alloc f = lua_getallocf(L, &ud);
|
||||
lua_atpanic(L, &tpanic);
|
||||
lua_setwarnf(L, &warnf, L);
|
||||
lua_pushboolean(L, 0);
|
||||
lua_setglobal(L, "_WARN"); /* _WARN = false */
|
||||
regcodes(L);
|
||||
atexit(checkfinalmem);
|
||||
lua_assert(lua_getallocf(L, &ud) == debug_realloc);
|
||||
lua_assert(ud == cast_voidp(&l_memcontrol));
|
||||
lua_setallocf(L, lua_getallocf(L, NULL), ud);
|
||||
lua_assert(f == debug_realloc && ud == cast_voidp(&l_memcontrol));
|
||||
lua_setallocf(L, f, ud); /* exercise this function */
|
||||
luaL_newlib(L, tests_funcs);
|
||||
return 1;
|
||||
}
|
||||
|
||||
@@ -20,19 +20,9 @@
|
||||
|
||||
|
||||
/* turn on assertions */
|
||||
#undef NDEBUG
|
||||
#include <assert.h>
|
||||
#define lua_assert(c) assert(c)
|
||||
#define LUAI_ASSERT
|
||||
|
||||
|
||||
/* include opcode names */
|
||||
#define LUAI_DEFOPNAMES
|
||||
|
||||
|
||||
/* compiled with -O0, Lua uses a lot of C stack space... */
|
||||
#undef LUAI_MAXCSTACK
|
||||
#define LUAI_MAXCSTACK 400
|
||||
|
||||
/* to avoid warnings, and to make sure value is really unused */
|
||||
#define UNUSED(x) (x=0, (void)(x))
|
||||
|
||||
@@ -56,12 +46,13 @@
|
||||
|
||||
/* memory-allocator control variables */
|
||||
typedef struct Memcontrol {
|
||||
int failnext;
|
||||
unsigned long numblocks;
|
||||
unsigned long total;
|
||||
unsigned long maxmem;
|
||||
unsigned long memlimit;
|
||||
unsigned long countlimit;
|
||||
unsigned long objcount[LUA_NUMTAGS];
|
||||
unsigned long objcount[LUA_NUMTYPES];
|
||||
} Memcontrol;
|
||||
|
||||
LUA_API Memcontrol l_memcontrol;
|
||||
@@ -77,7 +68,13 @@ extern void *l_Trick;
|
||||
/*
|
||||
** Function to traverse and check all memory used by Lua
|
||||
*/
|
||||
int lua_checkmemory (lua_State *L);
|
||||
LUAI_FUNC int lua_checkmemory (lua_State *L);
|
||||
|
||||
/*
|
||||
** Function to print an object GC-friendly
|
||||
*/
|
||||
struct GCObject;
|
||||
LUAI_FUNC void lua_printobj (lua_State *L, struct GCObject *o);
|
||||
|
||||
|
||||
/* test for lock/unlock */
|
||||
@@ -121,18 +118,27 @@ LUA_API void *debug_realloc (void *ud, void *block,
|
||||
#define MINSTRTABSIZE 2
|
||||
#define MAXIWTHABS 3
|
||||
|
||||
#define STRCACHE_N 23
|
||||
#define STRCACHE_M 5
|
||||
|
||||
#undef LUAI_USER_ALIGNMENT_T
|
||||
#define LUAI_USER_ALIGNMENT_T union { char b[sizeof(void*) * 8]; }
|
||||
|
||||
|
||||
/* make stack-overflow tests run faster */
|
||||
#undef LUAI_MAXSTACK
|
||||
#define LUAI_MAXSTACK 50000
|
||||
|
||||
|
||||
#undef LUAI_USER_ALIGNMENT_T
|
||||
#define LUAI_USER_ALIGNMENT_T union { char b[sizeof(void*) * 8]; }
|
||||
/* test mode uses more stack space */
|
||||
#undef LUAI_MAXCCALLS
|
||||
#define LUAI_MAXCCALLS 180
|
||||
|
||||
|
||||
#define STRCACHE_N 23
|
||||
#define STRCACHE_M 5
|
||||
/* force Lua to use its own implementations */
|
||||
#undef lua_strx2number
|
||||
#undef lua_number2strx
|
||||
|
||||
|
||||
#endif
|
||||
|
||||
|
||||
@@ -27,7 +27,7 @@
|
||||
|
||||
static const char udatatypename[] = "userdata";
|
||||
|
||||
LUAI_DDEF const char *const luaT_typenames_[LUA_TOTALTAGS] = {
|
||||
LUAI_DDEF const char *const luaT_typenames_[LUA_TOTALTYPES] = {
|
||||
"no value",
|
||||
"nil", "boolean", udatatypename, "number",
|
||||
"string", "table", "function", udatatypename, "thread",
|
||||
@@ -147,11 +147,8 @@ static int callbinTM (lua_State *L, const TValue *p1, const TValue *p2,
|
||||
|
||||
void luaT_trybinTM (lua_State *L, const TValue *p1, const TValue *p2,
|
||||
StkId res, TMS event) {
|
||||
if (!callbinTM(L, p1, p2, res, event)) {
|
||||
if (l_unlikely(!callbinTM(L, p1, p2, res, event))) {
|
||||
switch (event) {
|
||||
case TM_CONCAT:
|
||||
luaG_concaterror(L, p1, p2);
|
||||
/* call never returns, but to avoid warnings: *//* FALLTHROUGH */
|
||||
case TM_BAND: case TM_BOR: case TM_BXOR:
|
||||
case TM_SHL: case TM_SHR: case TM_BNOT: {
|
||||
if (ttisnumber(p1) && ttisnumber(p2))
|
||||
@@ -167,9 +164,17 @@ void luaT_trybinTM (lua_State *L, const TValue *p1, const TValue *p2,
|
||||
}
|
||||
|
||||
|
||||
void luaT_tryconcatTM (lua_State *L) {
|
||||
StkId top = L->top;
|
||||
if (l_unlikely(!callbinTM(L, s2v(top - 2), s2v(top - 1), top - 2,
|
||||
TM_CONCAT)))
|
||||
luaG_concaterror(L, s2v(top - 2), s2v(top - 1));
|
||||
}
|
||||
|
||||
|
||||
void luaT_trybinassocTM (lua_State *L, const TValue *p1, const TValue *p2,
|
||||
StkId res, int inv, TMS event) {
|
||||
if (inv)
|
||||
int flip, StkId res, TMS event) {
|
||||
if (flip)
|
||||
luaT_trybinTM(L, p2, p1, res, event);
|
||||
else
|
||||
luaT_trybinTM(L, p1, p2, res, event);
|
||||
@@ -177,13 +182,22 @@ void luaT_trybinassocTM (lua_State *L, const TValue *p1, const TValue *p2,
|
||||
|
||||
|
||||
void luaT_trybiniTM (lua_State *L, const TValue *p1, lua_Integer i2,
|
||||
int inv, StkId res, TMS event) {
|
||||
int flip, StkId res, TMS event) {
|
||||
TValue aux;
|
||||
setivalue(&aux, i2);
|
||||
luaT_trybinassocTM(L, p1, &aux, res, inv, event);
|
||||
luaT_trybinassocTM(L, p1, &aux, flip, res, event);
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** Calls an order tag method.
|
||||
** For lessequal, LUA_COMPAT_LT_LE keeps compatibility with old
|
||||
** behavior: if there is no '__le', try '__lt', based on l <= r iff
|
||||
** !(r < l) (assuming a total order). If the metamethod yields during
|
||||
** this substitution, the continuation has to know about it (to negate
|
||||
** the result of r<l); bit CIST_LEQ in the call status keeps that
|
||||
** information.
|
||||
*/
|
||||
int luaT_callorderTM (lua_State *L, const TValue *p1, const TValue *p2,
|
||||
TMS event) {
|
||||
if (callbinTM(L, p1, p2, L->top, event)) /* try original event */
|
||||
@@ -205,14 +219,14 @@ int luaT_callorderTM (lua_State *L, const TValue *p1, const TValue *p2,
|
||||
|
||||
|
||||
int luaT_callorderiTM (lua_State *L, const TValue *p1, int v2,
|
||||
int inv, int isfloat, TMS event) {
|
||||
int flip, int isfloat, TMS event) {
|
||||
TValue aux; const TValue *p2;
|
||||
if (isfloat) {
|
||||
setfltvalue(&aux, cast_num(v2));
|
||||
}
|
||||
else
|
||||
setivalue(&aux, v2);
|
||||
if (inv) { /* arguments were exchanged? */
|
||||
if (flip) { /* arguments were exchanged? */
|
||||
p2 = p1; p1 = &aux; /* correct them */
|
||||
}
|
||||
else
|
||||
@@ -227,7 +241,7 @@ void luaT_adjustvarargs (lua_State *L, int nfixparams, CallInfo *ci,
|
||||
int actual = cast_int(L->top - ci->func) - 1; /* number of arguments */
|
||||
int nextra = actual - nfixparams; /* number of extra arguments */
|
||||
ci->u.l.nextraargs = nextra;
|
||||
checkstackGC(L, p->maxstacksize + 1);
|
||||
luaD_checkstack(L, p->maxstacksize + 1);
|
||||
/* copy function to the top of the stack */
|
||||
setobjs2s(L, L->top++, ci->func);
|
||||
/* move fixed parameters to the top of the stack */
|
||||
@@ -246,7 +260,7 @@ void luaT_getvarargs (lua_State *L, CallInfo *ci, StkId where, int wanted) {
|
||||
int nextra = ci->u.l.nextraargs;
|
||||
if (wanted < 0) {
|
||||
wanted = nextra; /* get all extra arguments available */
|
||||
checkstackp(L, nextra, where); /* ensure stack space */
|
||||
checkstackGCp(L, nextra, where); /* ensure stack space */
|
||||
L->top = where + nextra; /* next instruction will need top */
|
||||
}
|
||||
for (i = 0; i < wanted && i < nextra; i++)
|
||||
|
||||
@@ -45,6 +45,15 @@ typedef enum {
|
||||
} TMS;
|
||||
|
||||
|
||||
/*
|
||||
** Mask with 1 in all fast-access methods. A 1 in any of these bits
|
||||
** in the flag of a (meta)table means the metatable does not have the
|
||||
** corresponding metamethod field. (Bit 7 of the flag is used for
|
||||
** 'isrealasize'.)
|
||||
*/
|
||||
#define maskflags (~(~0u << (TM_EQ + 1)))
|
||||
|
||||
|
||||
/*
|
||||
** Test whether there is no tagmethod.
|
||||
** (Because tagmethods use raw accesses, the result may be an "empty" nil.)
|
||||
@@ -59,7 +68,7 @@ typedef enum {
|
||||
|
||||
#define ttypename(x) luaT_typenames_[(x) + 1]
|
||||
|
||||
LUAI_DDEC(const char *const luaT_typenames_[LUA_TOTALTAGS];)
|
||||
LUAI_DDEC(const char *const luaT_typenames_[LUA_TOTALTYPES];)
|
||||
|
||||
|
||||
LUAI_FUNC const char *luaT_objtypename (lua_State *L, const TValue *o);
|
||||
@@ -75,8 +84,9 @@ LUAI_FUNC void luaT_callTMres (lua_State *L, const TValue *f,
|
||||
const TValue *p1, const TValue *p2, StkId p3);
|
||||
LUAI_FUNC void luaT_trybinTM (lua_State *L, const TValue *p1, const TValue *p2,
|
||||
StkId res, TMS event);
|
||||
LUAI_FUNC void luaT_tryconcatTM (lua_State *L);
|
||||
LUAI_FUNC void luaT_trybinassocTM (lua_State *L, const TValue *p1,
|
||||
const TValue *p2, StkId res, int inv, TMS event);
|
||||
const TValue *p2, int inv, StkId res, TMS event);
|
||||
LUAI_FUNC void luaT_trybiniTM (lua_State *L, const TValue *p1, lua_Integer i2,
|
||||
int inv, StkId res, TMS event);
|
||||
LUAI_FUNC int luaT_callorderTM (lua_State *L, const TValue *p1,
|
||||
|
||||
@@ -37,6 +37,26 @@ static lua_State *globalL = NULL;
|
||||
static const char *progname = LUA_PROGNAME;
|
||||
|
||||
|
||||
#if defined(LUA_USE_POSIX) /* { */
|
||||
|
||||
/*
|
||||
** Use 'sigaction' when available.
|
||||
*/
|
||||
static void setsignal (int sig, void (*handler)(int)) {
|
||||
struct sigaction sa;
|
||||
sa.sa_handler = handler;
|
||||
sa.sa_flags = 0;
|
||||
sigemptyset(&sa.sa_mask); /* do not mask any signal */
|
||||
sigaction(sig, &sa, NULL);
|
||||
}
|
||||
|
||||
#else /* }{ */
|
||||
|
||||
#define setsignal signal
|
||||
|
||||
#endif /* } */
|
||||
|
||||
|
||||
/*
|
||||
** Hook set by signal function to stop the interpreter.
|
||||
*/
|
||||
@@ -54,8 +74,9 @@ static void lstop (lua_State *L, lua_Debug *ar) {
|
||||
** interpreter.
|
||||
*/
|
||||
static void laction (int i) {
|
||||
signal(i, SIG_DFL); /* if another SIGINT happens, terminate process */
|
||||
lua_sethook(globalL, lstop, LUA_MASKCALL | LUA_MASKRET | LUA_MASKCOUNT, 1);
|
||||
int flag = LUA_MASKCALL | LUA_MASKRET | LUA_MASKLINE | LUA_MASKCOUNT;
|
||||
setsignal(i, SIG_DFL); /* if another SIGINT happens, terminate process */
|
||||
lua_sethook(globalL, lstop, flag, 1);
|
||||
}
|
||||
|
||||
|
||||
@@ -68,13 +89,15 @@ static void print_usage (const char *badoption) {
|
||||
lua_writestringerror(
|
||||
"usage: %s [options] [script [args]]\n"
|
||||
"Available options are:\n"
|
||||
" -e stat execute string 'stat'\n"
|
||||
" -i enter interactive mode after executing 'script'\n"
|
||||
" -l name require library 'name' into global 'name'\n"
|
||||
" -v show version information\n"
|
||||
" -E ignore environment variables\n"
|
||||
" -- stop handling options\n"
|
||||
" - stop handling options and execute stdin\n"
|
||||
" -e stat execute string 'stat'\n"
|
||||
" -i enter interactive mode after executing 'script'\n"
|
||||
" -l mod require library 'mod' into global 'mod'\n"
|
||||
" -l g=mod require library 'mod' into global 'g'\n"
|
||||
" -v show version information\n"
|
||||
" -E ignore environment variables\n"
|
||||
" -W turn warnings on\n"
|
||||
" -- stop handling options\n"
|
||||
" - stop handling options and execute stdin\n"
|
||||
,
|
||||
progname);
|
||||
}
|
||||
@@ -133,9 +156,9 @@ static int docall (lua_State *L, int narg, int nres) {
|
||||
lua_pushcfunction(L, msghandler); /* push message handler */
|
||||
lua_insert(L, base); /* put it under function and args */
|
||||
globalL = L; /* to be available to 'laction' */
|
||||
signal(SIGINT, laction); /* set C-signal handler */
|
||||
setsignal(SIGINT, laction); /* set C-signal handler */
|
||||
status = lua_pcall(L, narg, nres, base);
|
||||
signal(SIGINT, SIG_DFL); /* reset C-signal handler */
|
||||
setsignal(SIGINT, SIG_DFL); /* reset C-signal handler */
|
||||
lua_remove(L, base); /* remove message handler from the stack */
|
||||
return status;
|
||||
}
|
||||
@@ -185,16 +208,22 @@ static int dostring (lua_State *L, const char *s, const char *name) {
|
||||
|
||||
|
||||
/*
|
||||
** Calls 'require(name)' and stores the result in a global variable
|
||||
** with the given name.
|
||||
** Receives 'globname[=modname]' and runs 'globname = require(modname)'.
|
||||
*/
|
||||
static int dolibrary (lua_State *L, const char *name) {
|
||||
static int dolibrary (lua_State *L, char *globname) {
|
||||
int status;
|
||||
char *modname = strchr(globname, '=');
|
||||
if (modname == NULL) /* no explicit name? */
|
||||
modname = globname; /* module name is equal to global name */
|
||||
else {
|
||||
*modname = '\0'; /* global name ends here */
|
||||
modname++; /* module name starts after the '=' */
|
||||
}
|
||||
lua_getglobal(L, "require");
|
||||
lua_pushstring(L, name);
|
||||
status = docall(L, 1, 1); /* call 'require(name)' */
|
||||
lua_pushstring(L, modname);
|
||||
status = docall(L, 1, 1); /* call 'require(modname)' */
|
||||
if (status == LUA_OK)
|
||||
lua_setglobal(L, name); /* global[name] = require return */
|
||||
lua_setglobal(L, globname); /* globname = require(modname) */
|
||||
return report(L, status);
|
||||
}
|
||||
|
||||
@@ -259,14 +288,18 @@ static int collectargs (char **argv, int *first) {
|
||||
case '\0': /* '-' */
|
||||
return args; /* script "name" is '-' */
|
||||
case 'E':
|
||||
if (argv[i][2] != '\0') /* extra characters after 1st? */
|
||||
if (argv[i][2] != '\0') /* extra characters? */
|
||||
return has_error; /* invalid option */
|
||||
args |= has_E;
|
||||
break;
|
||||
case 'W':
|
||||
if (argv[i][2] != '\0') /* extra characters? */
|
||||
return has_error; /* invalid option */
|
||||
break;
|
||||
case 'i':
|
||||
args |= has_i; /* (-i implies -v) *//* FALLTHROUGH */
|
||||
case 'v':
|
||||
if (argv[i][2] != '\0') /* extra characters after 1st? */
|
||||
if (argv[i][2] != '\0') /* extra characters? */
|
||||
return has_error; /* invalid option */
|
||||
args |= has_v;
|
||||
break;
|
||||
@@ -289,7 +322,8 @@ static int collectargs (char **argv, int *first) {
|
||||
|
||||
|
||||
/*
|
||||
** Processes options 'e' and 'l', which involve running Lua code.
|
||||
** Processes options 'e' and 'l', which involve running Lua code, and
|
||||
** 'W', which also affects the state.
|
||||
** Returns 0 if some code raises an error.
|
||||
*/
|
||||
static int runargs (lua_State *L, char **argv, int n) {
|
||||
@@ -297,15 +331,21 @@ static int runargs (lua_State *L, char **argv, int n) {
|
||||
for (i = 1; i < n; i++) {
|
||||
int option = argv[i][1];
|
||||
lua_assert(argv[i][0] == '-'); /* already checked */
|
||||
if (option == 'e' || option == 'l') {
|
||||
int status;
|
||||
const char *extra = argv[i] + 2; /* both options need an argument */
|
||||
if (*extra == '\0') extra = argv[++i];
|
||||
lua_assert(extra != NULL);
|
||||
status = (option == 'e')
|
||||
? dostring(L, extra, "=(command line)")
|
||||
: dolibrary(L, extra);
|
||||
if (status != LUA_OK) return 0;
|
||||
switch (option) {
|
||||
case 'e': case 'l': {
|
||||
int status;
|
||||
char *extra = argv[i] + 2; /* both options need an argument */
|
||||
if (*extra == '\0') extra = argv[++i];
|
||||
lua_assert(extra != NULL);
|
||||
status = (option == 'e')
|
||||
? dostring(L, extra, "=(command line)")
|
||||
: dolibrary(L, extra);
|
||||
if (status != LUA_OK) return 0;
|
||||
break;
|
||||
}
|
||||
case 'W':
|
||||
lua_warning(L, "@on", 0); /* warnings on */
|
||||
break;
|
||||
}
|
||||
}
|
||||
return 1;
|
||||
@@ -403,14 +443,18 @@ static int handle_luainit (lua_State *L) {
|
||||
|
||||
|
||||
/*
|
||||
** Returns the string to be used as a prompt by the interpreter.
|
||||
** Return the string to be used as a prompt by the interpreter. Leave
|
||||
** the string (or nil, if using the default value) on the stack, to keep
|
||||
** it anchored.
|
||||
*/
|
||||
static const char *get_prompt (lua_State *L, int firstline) {
|
||||
const char *p;
|
||||
lua_getglobal(L, firstline ? "_PROMPT" : "_PROMPT2");
|
||||
p = lua_tostring(L, -1);
|
||||
if (p == NULL) p = (firstline ? LUA_PROMPT : LUA_PROMPT2);
|
||||
return p;
|
||||
if (lua_getglobal(L, firstline ? "_PROMPT" : "_PROMPT2") == LUA_TNIL)
|
||||
return (firstline ? LUA_PROMPT : LUA_PROMPT2); /* use the default */
|
||||
else { /* apply 'tostring' over the value */
|
||||
const char *p = luaL_tolstring(L, -1, NULL);
|
||||
lua_remove(L, -2); /* remove original value */
|
||||
return p;
|
||||
}
|
||||
}
|
||||
|
||||
/* mark in error messages for incomplete statements */
|
||||
|
||||
@@ -18,14 +18,14 @@
|
||||
|
||||
#define LUA_VERSION_MAJOR "5"
|
||||
#define LUA_VERSION_MINOR "4"
|
||||
#define LUA_VERSION_RELEASE "0"
|
||||
#define LUA_VERSION_RELEASE "4"
|
||||
|
||||
#define LUA_VERSION_NUM 504
|
||||
#define LUA_VERSION_RELEASE_NUM (LUA_VERSION_NUM * 100 + 0)
|
||||
#define LUA_VERSION_RELEASE_NUM (LUA_VERSION_NUM * 100 + 4)
|
||||
|
||||
#define LUA_VERSION "Lua " LUA_VERSION_MAJOR "." LUA_VERSION_MINOR
|
||||
#define LUA_RELEASE LUA_VERSION "." LUA_VERSION_RELEASE
|
||||
#define LUA_COPYRIGHT LUA_RELEASE " Copyright (C) 1994-2019 Lua.org, PUC-Rio"
|
||||
#define LUA_COPYRIGHT LUA_RELEASE " Copyright (C) 1994-2022 Lua.org, PUC-Rio"
|
||||
#define LUA_AUTHORS "R. Ierusalimschy, L. H. de Figueiredo, W. Celes"
|
||||
|
||||
|
||||
@@ -72,7 +72,7 @@ typedef struct lua_State lua_State;
|
||||
#define LUA_TUSERDATA 7
|
||||
#define LUA_TTHREAD 8
|
||||
|
||||
#define LUA_NUMTAGS 9
|
||||
#define LUA_NUMTYPES 9
|
||||
|
||||
|
||||
|
||||
@@ -347,7 +347,8 @@ LUA_API size_t (lua_stringtonumber) (lua_State *L, const char *s);
|
||||
LUA_API lua_Alloc (lua_getallocf) (lua_State *L, void **ud);
|
||||
LUA_API void (lua_setallocf) (lua_State *L, lua_Alloc f, void *ud);
|
||||
|
||||
LUA_API void (lua_toclose) (lua_State *L, int idx);
|
||||
LUA_API void (lua_toclose) (lua_State *L, int idx);
|
||||
LUA_API void (lua_closeslot) (lua_State *L, int idx);
|
||||
|
||||
|
||||
/*
|
||||
@@ -412,6 +413,8 @@ LUA_API void (lua_toclose) (lua_State *L, int idx);
|
||||
#define lua_getuservalue(L,idx) lua_getiuservalue(L,idx,1)
|
||||
#define lua_setuservalue(L,idx) lua_setiuservalue(L,idx,1)
|
||||
|
||||
#define LUA_NUMTAGS LUA_NUMTYPES
|
||||
|
||||
/* }============================================================== */
|
||||
|
||||
/*
|
||||
@@ -462,6 +465,7 @@ LUA_API lua_Hook (lua_gethook) (lua_State *L);
|
||||
LUA_API int (lua_gethookmask) (lua_State *L);
|
||||
LUA_API int (lua_gethookcount) (lua_State *L);
|
||||
|
||||
LUA_API int (lua_setcstacklimit) (lua_State *L, unsigned int limit);
|
||||
|
||||
struct lua_Debug {
|
||||
int event;
|
||||
@@ -488,7 +492,7 @@ struct lua_Debug {
|
||||
|
||||
|
||||
/******************************************************************************
|
||||
* Copyright (C) 1994-2019 Lua.org, PUC-Rio.
|
||||
* Copyright (C) 1994-2022 Lua.org, PUC-Rio.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining
|
||||
* a copy of this software and associated documentation files (the
|
||||
|
||||
@@ -16,13 +16,13 @@
|
||||
** ===================================================================
|
||||
** General Configuration File for Lua
|
||||
**
|
||||
** Some definitions here can be changed externally, through the
|
||||
** compiler (e.g., with '-D' options). Those are protected by
|
||||
** '#if !defined' guards. However, several other definitions should
|
||||
** be changed directly here, either because they affect the Lua
|
||||
** ABI (by making the changes here, you ensure that all software
|
||||
** connected to Lua, such as C libraries, will be compiled with the
|
||||
** same configuration); or because they are seldom changed.
|
||||
** Some definitions here can be changed externally, through the compiler
|
||||
** (e.g., with '-D' options): They are commented out or protected
|
||||
** by '#if !defined' guards. However, several other definitions
|
||||
** should be changed directly here, either because they affect the
|
||||
** Lua ABI (by making the changes here, you ensure that all software
|
||||
** connected to Lua, such as C libraries, will be compiled with the same
|
||||
** configuration); or because they are seldom changed.
|
||||
**
|
||||
** Search for "@@" to find all configurable definitions.
|
||||
** ===================================================================
|
||||
@@ -36,21 +36,6 @@
|
||||
** =====================================================================
|
||||
*/
|
||||
|
||||
/*
|
||||
@@ LUAI_MAXCSTACK defines the maximum depth for nested calls and
|
||||
** also limits the maximum depth of other recursive algorithms in
|
||||
** the implementation, such as syntactic analysis. A value too
|
||||
** large may allow the interpreter to crash (C-stack overflow).
|
||||
** The default value seems ok for regular machines, but may be
|
||||
** too high for restricted hardware.
|
||||
** The test file 'cstack.lua' may help finding a good limit.
|
||||
** (It will crash with a limit too high.)
|
||||
*/
|
||||
#if !defined(LUAI_MAXCSTACK)
|
||||
#define LUAI_MAXCSTACK 2200
|
||||
#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
|
||||
@@ -96,26 +81,12 @@
|
||||
|
||||
/*
|
||||
** {==================================================================
|
||||
** Configuration for Number types.
|
||||
** Configuration for Number types. These options should not be
|
||||
** set externally, because any other code connected to Lua must
|
||||
** use the same configuration.
|
||||
** ===================================================================
|
||||
*/
|
||||
|
||||
/*
|
||||
@@ LUA_32BITS enables Lua with 32-bit integers and 32-bit floats.
|
||||
*/
|
||||
/* #define LUA_32BITS */
|
||||
|
||||
|
||||
/*
|
||||
@@ LUA_C89_NUMBERS ensures that Lua uses the largest types available for
|
||||
** C89 ('long' and 'double'); Windows always has '__int64', so it does
|
||||
** not need to use this case.
|
||||
*/
|
||||
#if defined(LUA_USE_C89) && !defined(LUA_USE_WINDOWS)
|
||||
#define LUA_C89_NUMBERS
|
||||
#endif
|
||||
|
||||
|
||||
/*
|
||||
@@ LUA_INT_TYPE defines the type for Lua integers.
|
||||
@@ LUA_FLOAT_TYPE defines the type for Lua floats.
|
||||
@@ -136,7 +107,31 @@
|
||||
#define LUA_FLOAT_DOUBLE 2
|
||||
#define LUA_FLOAT_LONGDOUBLE 3
|
||||
|
||||
#if defined(LUA_32BITS) /* { */
|
||||
|
||||
/* Default configuration ('long long' and 'double', for 64-bit Lua) */
|
||||
#define LUA_INT_DEFAULT LUA_INT_LONGLONG
|
||||
#define LUA_FLOAT_DEFAULT LUA_FLOAT_DOUBLE
|
||||
|
||||
|
||||
/*
|
||||
@@ LUA_32BITS enables Lua with 32-bit integers and 32-bit floats.
|
||||
*/
|
||||
#define LUA_32BITS 0
|
||||
|
||||
|
||||
/*
|
||||
@@ LUA_C89_NUMBERS ensures that Lua uses the largest types available for
|
||||
** C89 ('long' and 'double'); Windows always has '__int64', so it does
|
||||
** not need to use this case.
|
||||
*/
|
||||
#if defined(LUA_USE_C89) && !defined(LUA_USE_WINDOWS)
|
||||
#define LUA_C89_NUMBERS 1
|
||||
#else
|
||||
#define LUA_C89_NUMBERS 0
|
||||
#endif
|
||||
|
||||
|
||||
#if LUA_32BITS /* { */
|
||||
/*
|
||||
** 32-bit integers and 'float'
|
||||
*/
|
||||
@@ -147,27 +142,22 @@
|
||||
#endif
|
||||
#define LUA_FLOAT_TYPE LUA_FLOAT_FLOAT
|
||||
|
||||
#elif defined(LUA_C89_NUMBERS) /* }{ */
|
||||
#elif LUA_C89_NUMBERS /* }{ */
|
||||
/*
|
||||
** largest types available for C89 ('long' and 'double')
|
||||
*/
|
||||
#define LUA_INT_TYPE LUA_INT_LONG
|
||||
#define LUA_FLOAT_TYPE LUA_FLOAT_DOUBLE
|
||||
|
||||
#else /* }{ */
|
||||
/* use defaults */
|
||||
|
||||
#define LUA_INT_TYPE LUA_INT_DEFAULT
|
||||
#define LUA_FLOAT_TYPE LUA_FLOAT_DEFAULT
|
||||
|
||||
#endif /* } */
|
||||
|
||||
|
||||
/*
|
||||
** default configuration for 64-bit Lua ('long long' and 'double')
|
||||
*/
|
||||
#if !defined(LUA_INT_TYPE)
|
||||
#define LUA_INT_TYPE LUA_INT_LONGLONG
|
||||
#endif
|
||||
|
||||
#if !defined(LUA_FLOAT_TYPE)
|
||||
#define LUA_FLOAT_TYPE LUA_FLOAT_DOUBLE
|
||||
#endif
|
||||
|
||||
/* }================================================================== */
|
||||
|
||||
|
||||
@@ -388,17 +378,16 @@
|
||||
|
||||
/*
|
||||
** {==================================================================
|
||||
** Configuration for Numbers.
|
||||
** Configuration for Numbers (low-level part).
|
||||
** Change these definitions if no predefined LUA_FLOAT_* / LUA_INT_*
|
||||
** satisfy your needs.
|
||||
** ===================================================================
|
||||
*/
|
||||
|
||||
/*
|
||||
@@ LUA_NUMBER is the floating-point type used by Lua.
|
||||
@@ LUAI_UACNUMBER is the result of a 'default argument promotion'
|
||||
@@ over a floating number.
|
||||
@@ l_mathlim(x) corrects limit name 'x' to the proper float type
|
||||
@@ l_floatatt(x) corrects float attribute 'x' to the proper float type
|
||||
** by prefixing it with one of FLT/DBL/LDBL.
|
||||
@@ LUA_NUMBER_FRMLEN is the length modifier for writing floats.
|
||||
@@ LUA_NUMBER_FMT is the format for writing floats.
|
||||
@@ -437,7 +426,7 @@
|
||||
|
||||
#define LUA_NUMBER float
|
||||
|
||||
#define l_mathlim(n) (FLT_##n)
|
||||
#define l_floatatt(n) (FLT_##n)
|
||||
|
||||
#define LUAI_UACNUMBER double
|
||||
|
||||
@@ -453,7 +442,7 @@
|
||||
|
||||
#define LUA_NUMBER long double
|
||||
|
||||
#define l_mathlim(n) (LDBL_##n)
|
||||
#define l_floatatt(n) (LDBL_##n)
|
||||
|
||||
#define LUAI_UACNUMBER long double
|
||||
|
||||
@@ -468,7 +457,7 @@
|
||||
|
||||
#define LUA_NUMBER double
|
||||
|
||||
#define l_mathlim(n) (DBL_##n)
|
||||
#define l_floatatt(n) (DBL_##n)
|
||||
|
||||
#define LUAI_UACNUMBER double
|
||||
|
||||
@@ -488,18 +477,14 @@
|
||||
|
||||
|
||||
/*
|
||||
@@ LUA_INTEGER is the integer type used by Lua.
|
||||
**
|
||||
@@ LUA_UNSIGNED is the unsigned version of LUA_INTEGER.
|
||||
**
|
||||
@@ LUAI_UACINT is the result of a 'default argument promotion'
|
||||
@@ over a lUA_INTEGER.
|
||||
@@ over a LUA_INTEGER.
|
||||
@@ LUA_INTEGER_FRMLEN is the length modifier for reading/writing integers.
|
||||
@@ LUA_INTEGER_FMT is the format for writing integers.
|
||||
@@ LUA_MAXINTEGER is the maximum value for a LUA_INTEGER.
|
||||
@@ LUA_MININTEGER is the minimum value for a LUA_INTEGER.
|
||||
@@ LUA_MAXUNSIGNED is the maximum value for a LUA_UNSIGNED.
|
||||
@@ LUA_UNSIGNEDBITS is the number of bits in a LUA_UNSIGNED.
|
||||
@@ lua_integer2str converts an integer to a string.
|
||||
*/
|
||||
|
||||
@@ -520,9 +505,6 @@
|
||||
#define LUA_UNSIGNED unsigned LUAI_UACINT
|
||||
|
||||
|
||||
#define LUA_UNSIGNEDBITS (sizeof(LUA_UNSIGNED) * CHAR_BIT)
|
||||
|
||||
|
||||
/* now the variable definitions */
|
||||
|
||||
#if LUA_INT_TYPE == LUA_INT_INT /* { int */
|
||||
@@ -674,6 +656,34 @@
|
||||
#define lua_getlocaledecpoint() (localeconv()->decimal_point[0])
|
||||
#endif
|
||||
|
||||
|
||||
/*
|
||||
** macros to improve jump prediction, used mostly for error handling
|
||||
** and debug facilities. (Some macros in the Lua API use these macros.
|
||||
** Define LUA_NOBUILTIN if you do not want '__builtin_expect' in your
|
||||
** code.)
|
||||
*/
|
||||
#if !defined(luai_likely)
|
||||
|
||||
#if defined(__GNUC__) && !defined(LUA_NOBUILTIN)
|
||||
#define luai_likely(x) (__builtin_expect(((x) != 0), 1))
|
||||
#define luai_unlikely(x) (__builtin_expect(((x) != 0), 0))
|
||||
#else
|
||||
#define luai_likely(x) (x)
|
||||
#define luai_unlikely(x) (x)
|
||||
#endif
|
||||
|
||||
#endif
|
||||
|
||||
|
||||
#if defined(LUA_CORE) || defined(LUA_LIB)
|
||||
/* shorter names for Lua's own use */
|
||||
#define l_likely(x) luai_likely(x)
|
||||
#define l_unlikely(x) luai_unlikely(x)
|
||||
#endif
|
||||
|
||||
|
||||
|
||||
/* }================================================================== */
|
||||
|
||||
|
||||
|
||||
@@ -49,10 +49,4 @@ LUAMOD_API int (luaopen_package) (lua_State *L);
|
||||
LUALIB_API void (luaL_openlibs) (lua_State *L);
|
||||
|
||||
|
||||
|
||||
#if !defined(lua_assert)
|
||||
#define lua_assert(x) ((void)0)
|
||||
#endif
|
||||
|
||||
|
||||
#endif
|
||||
|
||||
@@ -26,7 +26,7 @@
|
||||
|
||||
|
||||
#if !defined(luai_verifycode)
|
||||
#define luai_verifycode(L,b,f) /* empty */
|
||||
#define luai_verifycode(L,f) /* empty */
|
||||
#endif
|
||||
|
||||
|
||||
@@ -44,21 +44,21 @@ static l_noret error (LoadState *S, const char *why) {
|
||||
|
||||
|
||||
/*
|
||||
** All high-level loads go through LoadVector; you can change it to
|
||||
** All high-level loads go through loadVector; you can change it to
|
||||
** adapt to the endianness of the input
|
||||
*/
|
||||
#define LoadVector(S,b,n) LoadBlock(S,b,(n)*sizeof((b)[0]))
|
||||
#define loadVector(S,b,n) loadBlock(S,b,(n)*sizeof((b)[0]))
|
||||
|
||||
static void LoadBlock (LoadState *S, void *b, size_t size) {
|
||||
static void loadBlock (LoadState *S, void *b, size_t size) {
|
||||
if (luaZ_read(S->Z, b, size) != 0)
|
||||
error(S, "truncated chunk");
|
||||
}
|
||||
|
||||
|
||||
#define LoadVar(S,x) LoadVector(S,&x,1)
|
||||
#define loadVar(S,x) loadVector(S,&x,1)
|
||||
|
||||
|
||||
static lu_byte LoadByte (LoadState *S) {
|
||||
static lu_byte loadByte (LoadState *S) {
|
||||
int b = zgetc(S->Z);
|
||||
if (b == EOZ)
|
||||
error(S, "truncated chunk");
|
||||
@@ -66,12 +66,12 @@ static lu_byte LoadByte (LoadState *S) {
|
||||
}
|
||||
|
||||
|
||||
static size_t LoadUnsigned (LoadState *S, size_t limit) {
|
||||
static size_t loadUnsigned (LoadState *S, size_t limit) {
|
||||
size_t x = 0;
|
||||
int b;
|
||||
limit >>= 7;
|
||||
do {
|
||||
b = LoadByte(S);
|
||||
b = loadByte(S);
|
||||
if (x >= limit)
|
||||
error(S, "integer overflow");
|
||||
x = (x << 7) | (b & 0x7f);
|
||||
@@ -80,98 +80,107 @@ static size_t LoadUnsigned (LoadState *S, size_t limit) {
|
||||
}
|
||||
|
||||
|
||||
static size_t LoadSize (LoadState *S) {
|
||||
return LoadUnsigned(S, ~(size_t)0);
|
||||
static size_t loadSize (LoadState *S) {
|
||||
return loadUnsigned(S, ~(size_t)0);
|
||||
}
|
||||
|
||||
|
||||
static int LoadInt (LoadState *S) {
|
||||
return cast_int(LoadUnsigned(S, INT_MAX));
|
||||
static int loadInt (LoadState *S) {
|
||||
return cast_int(loadUnsigned(S, INT_MAX));
|
||||
}
|
||||
|
||||
|
||||
static lua_Number LoadNumber (LoadState *S) {
|
||||
static lua_Number loadNumber (LoadState *S) {
|
||||
lua_Number x;
|
||||
LoadVar(S, x);
|
||||
loadVar(S, x);
|
||||
return x;
|
||||
}
|
||||
|
||||
|
||||
static lua_Integer LoadInteger (LoadState *S) {
|
||||
static lua_Integer loadInteger (LoadState *S) {
|
||||
lua_Integer x;
|
||||
LoadVar(S, x);
|
||||
loadVar(S, x);
|
||||
return x;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** Load a nullable string
|
||||
** Load a nullable string into prototype 'p'.
|
||||
*/
|
||||
static TString *LoadStringN (LoadState *S) {
|
||||
size_t size = LoadSize(S);
|
||||
if (size == 0)
|
||||
static TString *loadStringN (LoadState *S, Proto *p) {
|
||||
lua_State *L = S->L;
|
||||
TString *ts;
|
||||
size_t size = loadSize(S);
|
||||
if (size == 0) /* no string? */
|
||||
return NULL;
|
||||
else if (--size <= LUAI_MAXSHORTLEN) { /* short string? */
|
||||
char buff[LUAI_MAXSHORTLEN];
|
||||
LoadVector(S, buff, size);
|
||||
return luaS_newlstr(S->L, buff, size);
|
||||
loadVector(S, buff, size); /* load string into buffer */
|
||||
ts = luaS_newlstr(L, buff, size); /* create string */
|
||||
}
|
||||
else { /* long string */
|
||||
TString *ts = luaS_createlngstrobj(S->L, size);
|
||||
LoadVector(S, getstr(ts), size); /* load directly in final place */
|
||||
return ts;
|
||||
ts = luaS_createlngstrobj(L, size); /* create string */
|
||||
setsvalue2s(L, L->top, ts); /* anchor it ('loadVector' can GC) */
|
||||
luaD_inctop(L);
|
||||
loadVector(S, getstr(ts), size); /* load directly in final place */
|
||||
L->top--; /* pop string */
|
||||
}
|
||||
luaC_objbarrier(L, p, ts);
|
||||
return ts;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** Load a non-nullable string.
|
||||
** Load a non-nullable string into prototype 'p'.
|
||||
*/
|
||||
static TString *LoadString (LoadState *S) {
|
||||
TString *st = LoadStringN(S);
|
||||
static TString *loadString (LoadState *S, Proto *p) {
|
||||
TString *st = loadStringN(S, p);
|
||||
if (st == NULL)
|
||||
error(S, "bad format for constant string");
|
||||
return st;
|
||||
}
|
||||
|
||||
|
||||
static void LoadCode (LoadState *S, Proto *f) {
|
||||
int n = LoadInt(S);
|
||||
static void loadCode (LoadState *S, Proto *f) {
|
||||
int n = loadInt(S);
|
||||
f->code = luaM_newvectorchecked(S->L, n, Instruction);
|
||||
f->sizecode = n;
|
||||
LoadVector(S, f->code, n);
|
||||
loadVector(S, f->code, n);
|
||||
}
|
||||
|
||||
|
||||
static void LoadFunction(LoadState *S, Proto *f, TString *psource);
|
||||
static void loadFunction(LoadState *S, Proto *f, TString *psource);
|
||||
|
||||
|
||||
static void LoadConstants (LoadState *S, Proto *f) {
|
||||
static void loadConstants (LoadState *S, Proto *f) {
|
||||
int i;
|
||||
int n = LoadInt(S);
|
||||
int n = loadInt(S);
|
||||
f->k = luaM_newvectorchecked(S->L, n, TValue);
|
||||
f->sizek = n;
|
||||
for (i = 0; i < n; i++)
|
||||
setnilvalue(&f->k[i]);
|
||||
for (i = 0; i < n; i++) {
|
||||
TValue *o = &f->k[i];
|
||||
int t = LoadByte(S);
|
||||
int t = loadByte(S);
|
||||
switch (t) {
|
||||
case LUA_TNIL:
|
||||
case LUA_VNIL:
|
||||
setnilvalue(o);
|
||||
break;
|
||||
case LUA_TBOOLEAN:
|
||||
setbvalue(o, LoadByte(S));
|
||||
case LUA_VFALSE:
|
||||
setbfvalue(o);
|
||||
break;
|
||||
case LUA_TNUMFLT:
|
||||
setfltvalue(o, LoadNumber(S));
|
||||
case LUA_VTRUE:
|
||||
setbtvalue(o);
|
||||
break;
|
||||
case LUA_TNUMINT:
|
||||
setivalue(o, LoadInteger(S));
|
||||
case LUA_VNUMFLT:
|
||||
setfltvalue(o, loadNumber(S));
|
||||
break;
|
||||
case LUA_TSHRSTR:
|
||||
case LUA_TLNGSTR:
|
||||
setsvalue2n(S->L, o, LoadString(S));
|
||||
case LUA_VNUMINT:
|
||||
setivalue(o, loadInteger(S));
|
||||
break;
|
||||
case LUA_VSHRSTR:
|
||||
case LUA_VLNGSTR:
|
||||
setsvalue2n(S->L, o, loadString(S, f));
|
||||
break;
|
||||
default: lua_assert(0);
|
||||
}
|
||||
@@ -179,91 +188,99 @@ static void LoadConstants (LoadState *S, Proto *f) {
|
||||
}
|
||||
|
||||
|
||||
static void LoadProtos (LoadState *S, Proto *f) {
|
||||
static void loadProtos (LoadState *S, Proto *f) {
|
||||
int i;
|
||||
int n = LoadInt(S);
|
||||
int n = loadInt(S);
|
||||
f->p = luaM_newvectorchecked(S->L, n, Proto *);
|
||||
f->sizep = n;
|
||||
for (i = 0; i < n; i++)
|
||||
f->p[i] = NULL;
|
||||
for (i = 0; i < n; i++) {
|
||||
f->p[i] = luaF_newproto(S->L);
|
||||
LoadFunction(S, f->p[i], f->source);
|
||||
luaC_objbarrier(S->L, f, f->p[i]);
|
||||
loadFunction(S, f->p[i], f->source);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
static void LoadUpvalues (LoadState *S, Proto *f) {
|
||||
/*
|
||||
** Load the upvalues for a function. The names must be filled first,
|
||||
** because the filling of the other fields can raise read errors and
|
||||
** the creation of the error message can call an emergency collection;
|
||||
** in that case all prototypes must be consistent for the GC.
|
||||
*/
|
||||
static void loadUpvalues (LoadState *S, Proto *f) {
|
||||
int i, n;
|
||||
n = LoadInt(S);
|
||||
n = loadInt(S);
|
||||
f->upvalues = luaM_newvectorchecked(S->L, n, Upvaldesc);
|
||||
f->sizeupvalues = n;
|
||||
for (i = 0; i < n; i++)
|
||||
for (i = 0; i < n; i++) /* make array valid for GC */
|
||||
f->upvalues[i].name = NULL;
|
||||
for (i = 0; i < n; i++) {
|
||||
f->upvalues[i].instack = LoadByte(S);
|
||||
f->upvalues[i].idx = LoadByte(S);
|
||||
for (i = 0; i < n; i++) { /* following calls can raise errors */
|
||||
f->upvalues[i].instack = loadByte(S);
|
||||
f->upvalues[i].idx = loadByte(S);
|
||||
f->upvalues[i].kind = loadByte(S);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
static void LoadDebug (LoadState *S, Proto *f) {
|
||||
static void loadDebug (LoadState *S, Proto *f) {
|
||||
int i, n;
|
||||
n = LoadInt(S);
|
||||
n = loadInt(S);
|
||||
f->lineinfo = luaM_newvectorchecked(S->L, n, ls_byte);
|
||||
f->sizelineinfo = n;
|
||||
LoadVector(S, f->lineinfo, n);
|
||||
n = LoadInt(S);
|
||||
loadVector(S, f->lineinfo, n);
|
||||
n = loadInt(S);
|
||||
f->abslineinfo = luaM_newvectorchecked(S->L, n, AbsLineInfo);
|
||||
f->sizeabslineinfo = n;
|
||||
for (i = 0; i < n; i++) {
|
||||
f->abslineinfo[i].pc = LoadInt(S);
|
||||
f->abslineinfo[i].line = LoadInt(S);
|
||||
f->abslineinfo[i].pc = loadInt(S);
|
||||
f->abslineinfo[i].line = loadInt(S);
|
||||
}
|
||||
n = LoadInt(S);
|
||||
n = loadInt(S);
|
||||
f->locvars = luaM_newvectorchecked(S->L, n, LocVar);
|
||||
f->sizelocvars = n;
|
||||
for (i = 0; i < n; i++)
|
||||
f->locvars[i].varname = NULL;
|
||||
for (i = 0; i < n; i++) {
|
||||
f->locvars[i].varname = LoadStringN(S);
|
||||
f->locvars[i].startpc = LoadInt(S);
|
||||
f->locvars[i].endpc = LoadInt(S);
|
||||
f->locvars[i].varname = loadStringN(S, f);
|
||||
f->locvars[i].startpc = loadInt(S);
|
||||
f->locvars[i].endpc = loadInt(S);
|
||||
}
|
||||
n = LoadInt(S);
|
||||
n = loadInt(S);
|
||||
for (i = 0; i < n; i++)
|
||||
f->upvalues[i].name = LoadStringN(S);
|
||||
f->upvalues[i].name = loadStringN(S, f);
|
||||
}
|
||||
|
||||
|
||||
static void LoadFunction (LoadState *S, Proto *f, TString *psource) {
|
||||
f->source = LoadStringN(S);
|
||||
static void loadFunction (LoadState *S, Proto *f, TString *psource) {
|
||||
f->source = loadStringN(S, f);
|
||||
if (f->source == NULL) /* no source in dump? */
|
||||
f->source = psource; /* reuse parent's source */
|
||||
f->linedefined = LoadInt(S);
|
||||
f->lastlinedefined = LoadInt(S);
|
||||
f->numparams = LoadByte(S);
|
||||
f->is_vararg = LoadByte(S);
|
||||
f->maxstacksize = LoadByte(S);
|
||||
LoadCode(S, f);
|
||||
LoadConstants(S, f);
|
||||
LoadUpvalues(S, f);
|
||||
LoadProtos(S, f);
|
||||
LoadDebug(S, f);
|
||||
f->linedefined = loadInt(S);
|
||||
f->lastlinedefined = loadInt(S);
|
||||
f->numparams = loadByte(S);
|
||||
f->is_vararg = loadByte(S);
|
||||
f->maxstacksize = loadByte(S);
|
||||
loadCode(S, f);
|
||||
loadConstants(S, f);
|
||||
loadUpvalues(S, f);
|
||||
loadProtos(S, f);
|
||||
loadDebug(S, f);
|
||||
}
|
||||
|
||||
|
||||
static void checkliteral (LoadState *S, const char *s, const char *msg) {
|
||||
char buff[sizeof(LUA_SIGNATURE) + sizeof(LUAC_DATA)]; /* larger than both */
|
||||
size_t len = strlen(s);
|
||||
LoadVector(S, buff, len);
|
||||
loadVector(S, buff, len);
|
||||
if (memcmp(s, buff, len) != 0)
|
||||
error(S, msg);
|
||||
}
|
||||
|
||||
|
||||
static void fchecksize (LoadState *S, size_t size, const char *tname) {
|
||||
if (LoadByte(S) != size)
|
||||
if (loadByte(S) != size)
|
||||
error(S, luaO_pushfstring(S->L, "%s size mismatch", tname));
|
||||
}
|
||||
|
||||
@@ -273,23 +290,23 @@ static void fchecksize (LoadState *S, size_t size, const char *tname) {
|
||||
static void checkHeader (LoadState *S) {
|
||||
/* skip 1st char (already read and checked) */
|
||||
checkliteral(S, &LUA_SIGNATURE[1], "not a binary chunk");
|
||||
if (LoadInt(S) != LUAC_VERSION)
|
||||
if (loadByte(S) != LUAC_VERSION)
|
||||
error(S, "version mismatch");
|
||||
if (LoadByte(S) != LUAC_FORMAT)
|
||||
if (loadByte(S) != LUAC_FORMAT)
|
||||
error(S, "format mismatch");
|
||||
checkliteral(S, LUAC_DATA, "corrupted chunk");
|
||||
checksize(S, Instruction);
|
||||
checksize(S, lua_Integer);
|
||||
checksize(S, lua_Number);
|
||||
if (LoadInteger(S) != LUAC_INT)
|
||||
if (loadInteger(S) != LUAC_INT)
|
||||
error(S, "integer format mismatch");
|
||||
if (LoadNumber(S) != LUAC_NUM)
|
||||
if (loadNumber(S) != LUAC_NUM)
|
||||
error(S, "float format mismatch");
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** load precompiled chunk
|
||||
** Load precompiled chunk.
|
||||
*/
|
||||
LClosure *luaU_undump(lua_State *L, ZIO *Z, const char *name) {
|
||||
LoadState S;
|
||||
@@ -303,13 +320,14 @@ LClosure *luaU_undump(lua_State *L, ZIO *Z, const char *name) {
|
||||
S.L = L;
|
||||
S.Z = Z;
|
||||
checkHeader(&S);
|
||||
cl = luaF_newLclosure(L, LoadByte(&S));
|
||||
cl = luaF_newLclosure(L, loadByte(&S));
|
||||
setclLvalue2s(L, L->top, cl);
|
||||
luaD_inctop(L);
|
||||
cl->p = luaF_newproto(L);
|
||||
LoadFunction(&S, cl->p, NULL);
|
||||
luaC_objbarrier(L, cl, cl->p);
|
||||
loadFunction(&S, cl->p, NULL);
|
||||
lua_assert(cl->nupvalues == cl->p->sizeupvalues);
|
||||
luai_verifycode(L, buff, cl->p);
|
||||
luai_verifycode(L, cl->p);
|
||||
return cl;
|
||||
}
|
||||
|
||||
|
||||
@@ -18,7 +18,12 @@
|
||||
#define LUAC_INT 0x5678
|
||||
#define LUAC_NUM cast_num(370.5)
|
||||
|
||||
#define LUAC_VERSION LUA_VERSION_NUM
|
||||
/*
|
||||
** Encode major-minor version in one byte, one nibble for each
|
||||
*/
|
||||
#define MYINT(s) (s[0]-'0') /* assume one-digit numerals */
|
||||
#define LUAC_VERSION (MYINT(LUA_VERSION_MAJOR)*16+MYINT(LUA_VERSION_MINOR))
|
||||
|
||||
#define LUAC_FORMAT 0 /* this is the official format */
|
||||
|
||||
/* load one chunk; from lundump.c */
|
||||
|
||||
+12
-15
@@ -29,7 +29,7 @@
|
||||
** Integer type for decoded UTF-8 values; MAXUTF needs 31 bits.
|
||||
*/
|
||||
#if (UINT_MAX >> 30) >= 1
|
||||
typedef unsigned int utfint;
|
||||
typedef unsigned int utfint;
|
||||
#else
|
||||
typedef unsigned long utfint;
|
||||
#endif
|
||||
@@ -97,13 +97,13 @@ static int utflen (lua_State *L) {
|
||||
lua_Integer posj = u_posrelat(luaL_optinteger(L, 3, -1), len);
|
||||
int lax = lua_toboolean(L, 4);
|
||||
luaL_argcheck(L, 1 <= posi && --posi <= (lua_Integer)len, 2,
|
||||
"initial position out of string");
|
||||
"initial position out of bounds");
|
||||
luaL_argcheck(L, --posj < (lua_Integer)len, 3,
|
||||
"final position out of string");
|
||||
"final position out of bounds");
|
||||
while (posi <= posj) {
|
||||
const char *s1 = utf8_decode(s + posi, NULL, !lax);
|
||||
if (s1 == NULL) { /* conversion error? */
|
||||
lua_pushnil(L); /* return nil ... */
|
||||
luaL_pushfail(L); /* return fail ... */
|
||||
lua_pushinteger(L, posi + 1); /* ... and current position */
|
||||
return 2;
|
||||
}
|
||||
@@ -127,8 +127,8 @@ static int codepoint (lua_State *L) {
|
||||
int lax = lua_toboolean(L, 4);
|
||||
int n;
|
||||
const char *se;
|
||||
luaL_argcheck(L, posi >= 1, 2, "out of range");
|
||||
luaL_argcheck(L, pose <= (lua_Integer)len, 3, "out of range");
|
||||
luaL_argcheck(L, posi >= 1, 2, "out of bounds");
|
||||
luaL_argcheck(L, pose <= (lua_Integer)len, 3, "out of bounds");
|
||||
if (posi > pose) return 0; /* empty interval; return no values */
|
||||
if (pose - posi >= INT_MAX) /* (lua_Integer -> int) overflow? */
|
||||
return luaL_error(L, "string slice too long");
|
||||
@@ -187,7 +187,7 @@ static int byteoffset (lua_State *L) {
|
||||
lua_Integer posi = (n >= 0) ? 1 : len + 1;
|
||||
posi = u_posrelat(luaL_optinteger(L, 3, posi), len);
|
||||
luaL_argcheck(L, 1 <= posi && --posi <= (lua_Integer)len, 3,
|
||||
"position out of range");
|
||||
"position out of bounds");
|
||||
if (n == 0) {
|
||||
/* find beginning of current byte sequence */
|
||||
while (posi > 0 && iscont(s + posi)) posi--;
|
||||
@@ -216,7 +216,7 @@ static int byteoffset (lua_State *L) {
|
||||
if (n == 0) /* did it find given character? */
|
||||
lua_pushinteger(L, posi + 1);
|
||||
else /* no such character */
|
||||
lua_pushnil(L);
|
||||
luaL_pushfail(L);
|
||||
return 1;
|
||||
}
|
||||
|
||||
@@ -224,14 +224,11 @@ static int byteoffset (lua_State *L) {
|
||||
static int iter_aux (lua_State *L, int strict) {
|
||||
size_t len;
|
||||
const char *s = luaL_checklstring(L, 1, &len);
|
||||
lua_Integer n = lua_tointeger(L, 2) - 1;
|
||||
if (n < 0) /* first iteration? */
|
||||
n = 0; /* start from here */
|
||||
else if (n < (lua_Integer)len) {
|
||||
n++; /* skip current byte */
|
||||
while (iscont(s + n)) n++; /* and its continuations */
|
||||
lua_Unsigned n = (lua_Unsigned)lua_tointeger(L, 2);
|
||||
if (n < len) {
|
||||
while (iscont(s + n)) n++; /* skip continuation bytes */
|
||||
}
|
||||
if (n >= (lua_Integer)len)
|
||||
if (n >= len) /* (also handles original 'n' being negative) */
|
||||
return 0; /* no more codepoints */
|
||||
else {
|
||||
utfint code;
|
||||
|
||||
@@ -33,10 +33,20 @@
|
||||
** integral values)
|
||||
*/
|
||||
#if !defined(LUA_FLOORN2I)
|
||||
#define LUA_FLOORN2I 0
|
||||
#define LUA_FLOORN2I F2Ieq
|
||||
#endif
|
||||
|
||||
|
||||
/*
|
||||
** Rounding modes for float->integer coercion
|
||||
*/
|
||||
typedef enum {
|
||||
F2Ieq, /* no rounding; accepts only integral values */
|
||||
F2Ifloor, /* takes the floor of the number */
|
||||
F2Iceil /* takes the ceil of the number */
|
||||
} F2Imod;
|
||||
|
||||
|
||||
/* convert an object to a float (including string coercion) */
|
||||
#define tonumber(o,n) \
|
||||
(ttisfloat(o) ? (*(n) = fltvalue(o), 1) : luaV_tonumber_(o,n))
|
||||
@@ -50,12 +60,14 @@
|
||||
|
||||
/* convert an object to an integer (including string coercion) */
|
||||
#define tointeger(o,i) \
|
||||
(ttisinteger(o) ? (*(i) = ivalue(o), 1) : luaV_tointeger(o,i,LUA_FLOORN2I))
|
||||
(l_likely(ttisinteger(o)) ? (*(i) = ivalue(o), 1) \
|
||||
: luaV_tointeger(o,i,LUA_FLOORN2I))
|
||||
|
||||
|
||||
/* convert an object to an integer (without string coercion) */
|
||||
#define tointegerns(o,i) \
|
||||
(ttisinteger(o) ? (*(i) = ivalue(o), 1) : luaV_tointegerns(o,i,LUA_FLOORN2I))
|
||||
(l_likely(ttisinteger(o)) ? (*(i) = ivalue(o), 1) \
|
||||
: luaV_tointegerns(o,i,LUA_FLOORN2I))
|
||||
|
||||
|
||||
#define intop(op,v1,v2) l_castU2S(l_castS2U(v1) op l_castS2U(v2))
|
||||
@@ -104,9 +116,10 @@ LUAI_FUNC int luaV_equalobj (lua_State *L, const TValue *t1, const TValue *t2);
|
||||
LUAI_FUNC int luaV_lessthan (lua_State *L, const TValue *l, const TValue *r);
|
||||
LUAI_FUNC int luaV_lessequal (lua_State *L, const TValue *l, const TValue *r);
|
||||
LUAI_FUNC int luaV_tonumber_ (const TValue *obj, lua_Number *n);
|
||||
LUAI_FUNC int luaV_tointeger (const TValue *obj, lua_Integer *p, int mode);
|
||||
LUAI_FUNC int luaV_tointegerns (const TValue *obj, lua_Integer *p, int mode);
|
||||
LUAI_FUNC int luaV_flttointeger (lua_Number n, lua_Integer *p, int mode);
|
||||
LUAI_FUNC int luaV_tointeger (const TValue *obj, lua_Integer *p, F2Imod mode);
|
||||
LUAI_FUNC int luaV_tointegerns (const TValue *obj, lua_Integer *p,
|
||||
F2Imod mode);
|
||||
LUAI_FUNC int luaV_flttointeger (lua_Number n, lua_Integer *p, F2Imod mode);
|
||||
LUAI_FUNC void luaV_finishget (lua_State *L, const TValue *t, TValue *key,
|
||||
StkId val, const TValue *slot);
|
||||
LUAI_FUNC void luaV_finishset (lua_State *L, const TValue *t, TValue *key,
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
# makefile for building Lua
|
||||
# see INSTALL for installation instructions
|
||||
# see ../Makefile and luaconf.h for further customization
|
||||
# Developer's makefile for building Lua
|
||||
# see luaconf.h for further customization
|
||||
|
||||
# == CHANGE THE SETTINGS BELOW TO SUIT YOUR ENVIRONMENT =======================
|
||||
|
||||
# Warnings valid for both C and C++
|
||||
CWARNSCPP= \
|
||||
-Wfatal-errors \
|
||||
-Wextra \
|
||||
-Wshadow \
|
||||
-Wsign-compare \
|
||||
@@ -14,19 +14,24 @@ CWARNSCPP= \
|
||||
-Wredundant-decls \
|
||||
-Wdisabled-optimization \
|
||||
-Wdouble-promotion \
|
||||
#-Wno-aggressive-loop-optimizations \
|
||||
#-Wlogical-op \
|
||||
#-Wfatal-errors \
|
||||
#-Wstrict-aliasing=3 \
|
||||
-Wmissing-declarations \
|
||||
# the next warnings might be useful sometimes,
|
||||
# but usually they generate too much noise
|
||||
# -Werror \
|
||||
# -pedantic # warns if we use jump tables \
|
||||
# the next warnings generate too much noise, so they are disabled
|
||||
# -Wconversion -Wno-sign-conversion \
|
||||
# -Wconversion \
|
||||
# -Wsign-conversion \
|
||||
# -Wstrict-overflow=2 \
|
||||
# -Wformat=2 \
|
||||
# -Wcast-qual \
|
||||
|
||||
|
||||
# Warnings for gcc, not valid for clang
|
||||
CWARNGCC= \
|
||||
-Wlogical-op \
|
||||
-Wno-aggressive-loop-optimizations \
|
||||
|
||||
|
||||
# The next warnings are neither valid nor needed for C++
|
||||
CWARNSC= -Wdeclaration-after-statement \
|
||||
-Wmissing-prototypes \
|
||||
@@ -36,20 +41,28 @@ CWARNSC= -Wdeclaration-after-statement \
|
||||
-Wold-style-definition \
|
||||
|
||||
|
||||
CWARNS= $(CWARNSCPP) $(CWARNSC)
|
||||
CWARNS= $(CWARNSCPP) $(CWARNSC) $(CWARNGCC)
|
||||
|
||||
# Some useful compiler options for internal tests:
|
||||
# -DLUAI_ASSERT turns on all assertions inside Lua.
|
||||
# -DHARDSTACKTESTS forces a reallocation of the stack at every point where
|
||||
# the stack can be reallocated.
|
||||
# -DHARDMEMTESTS forces a full collection at all points where the collector
|
||||
# can run.
|
||||
# -DEMERGENCYGCTESTS forces an emergency collection at every single allocation.
|
||||
# -DEXTERNMEMCHECK removes internal consistency checking of blocks being
|
||||
# deallocated (useful when an external tool like valgrind does the check).
|
||||
# -DMAXINDEXRK=k limits range of constants in RK instruction operands.
|
||||
# -DLUA_COMPAT_5_3
|
||||
|
||||
# -DEXTERNMEMCHECK -DHARDSTACKTESTS -DHARDMEMTESTS -DTRACEMEM='"tempmem"'
|
||||
# -DMAXINDEXRK=1 -DLUA_COMPAT_5_3
|
||||
# -g -DLUA_USER_H='"ltests.h"'
|
||||
# -pg -malign-double
|
||||
# -DLUA_USE_CTYPE -DLUA_USE_APICHECK
|
||||
# ('-ftrapv' for runtime checks of integer overflows)
|
||||
# -fsanitize=undefined -ftrapv -fno-inline
|
||||
TESTS= -DLUA_USER_H='"ltests.h"' -O0
|
||||
# TESTS= -DLUA_USER_H='"ltests.h"' -O0 -g
|
||||
|
||||
|
||||
# LOCAL = $(TESTS) $(CWARNS) -g
|
||||
LOCAL = $(TESTS) $(CWARNS)
|
||||
|
||||
|
||||
# enable Linux goodies
|
||||
@@ -82,11 +95,9 @@ LIB_O= lbaselib.o ldblib.o liolib.o lmathlib.o loslib.o ltablib.o lstrlib.o \
|
||||
LUA_T= lua
|
||||
LUA_O= lua.o
|
||||
|
||||
# LUAC_T= luac
|
||||
# LUAC_O= luac.o print.o
|
||||
|
||||
ALL_T= $(CORE_T) $(LUA_T) $(LUAC_T)
|
||||
ALL_O= $(CORE_O) $(LUA_O) $(LUAC_O) $(AUX_O) $(LIB_O)
|
||||
ALL_T= $(CORE_T) $(LUA_T)
|
||||
ALL_O= $(CORE_O) $(LUA_O) $(AUX_O) $(LIB_O)
|
||||
ALL_A= $(CORE_T)
|
||||
|
||||
all: $(ALL_T)
|
||||
@@ -103,11 +114,8 @@ $(CORE_T): $(CORE_O) $(AUX_O) $(LIB_O)
|
||||
$(LUA_T): $(LUA_O) $(CORE_T)
|
||||
$(CC) -o $@ $(MYLDFLAGS) $(LUA_O) $(CORE_T) $(LIBS) $(MYLIBS) $(DL)
|
||||
|
||||
$(LUAC_T): $(LUAC_O) $(CORE_T)
|
||||
$(CC) -o $@ $(MYLDFLAGS) $(LUAC_O) $(CORE_T) $(LIBS) $(MYLIBS)
|
||||
|
||||
clean:
|
||||
rcsclean -u
|
||||
$(RM) $(ALL_T) $(ALL_O)
|
||||
|
||||
depend:
|
||||
|
||||
+2
-1
@@ -30,7 +30,7 @@ by Roberto Ierusalimschy, Luiz Henrique de Figueiredo, Waldemar Celes
|
||||
<p>
|
||||
<small>
|
||||
<a href="http://www.lua.org/copyright.html">Copyright</a>
|
||||
© 2019 Lua.org, PUC-Rio. All rights reserved.
|
||||
© 2022 Lua.org, PUC-Rio. All rights reserved.
|
||||
</small>
|
||||
<hr>
|
||||
|
||||
@@ -324,6 +324,7 @@ N = function (s) return (string.gsub(s, " ", " ")) end,
|
||||
NE = id, -- tag"foreignphrase",
|
||||
num = id,
|
||||
["nil"] = fixed(Tag.b"nil"),
|
||||
fail = fixed(Tag.b"fail"),
|
||||
Open = fixed"{",
|
||||
part = section("h1", true),
|
||||
Pat = compose(verbfixed, prepos("'", "'")),
|
||||
|
||||
+745
-442
File diff suppressed because it is too large
Load Diff
+31
-17
@@ -5,8 +5,8 @@
|
||||
|
||||
local version = "Lua 5.4"
|
||||
if _VERSION ~= version then
|
||||
warn("This test suite is for ", version,
|
||||
", not for ", _VERSION, "\nExiting tests")
|
||||
io.stderr:write("This test suite is for ", version,
|
||||
", not for ", _VERSION, "\nExiting tests")
|
||||
return
|
||||
end
|
||||
|
||||
@@ -37,8 +37,6 @@ end
|
||||
-- tests should require debug when needed
|
||||
debug = nil
|
||||
|
||||
require"bwcoercion"
|
||||
|
||||
|
||||
if usertests then
|
||||
T = nil -- no "internal" tests for user tests
|
||||
@@ -46,7 +44,6 @@ else
|
||||
T = rawget(_G, "T") -- avoid problems with 'strict' module
|
||||
end
|
||||
|
||||
math.randomseed(0)
|
||||
|
||||
--[=[
|
||||
example of a long [comment],
|
||||
@@ -54,6 +51,14 @@ math.randomseed(0)
|
||||
|
||||
]=]
|
||||
|
||||
print("\n\tStarting Tests")
|
||||
|
||||
do
|
||||
-- set random seed
|
||||
local random_x, random_y = math.randomseed()
|
||||
print(string.format("random seeds: %d, %d", random_x, random_y))
|
||||
end
|
||||
|
||||
print("current path:\n****" .. package.path .. "****\n")
|
||||
|
||||
|
||||
@@ -95,6 +100,8 @@ local function F (m)
|
||||
end
|
||||
end
|
||||
|
||||
local Cstacklevel
|
||||
|
||||
local showmem
|
||||
if not T then
|
||||
local max = 0
|
||||
@@ -104,6 +111,7 @@ if not T then
|
||||
print(format(" ---- total memory: %s, max memory: %s ----\n",
|
||||
F(m), F(max)))
|
||||
end
|
||||
Cstacklevel = function () return 0 end -- no info about stack level
|
||||
else
|
||||
showmem = function ()
|
||||
T.checkmemory()
|
||||
@@ -117,9 +125,16 @@ else
|
||||
T.totalmem"string", T.totalmem"table", T.totalmem"function",
|
||||
T.totalmem"userdata", T.totalmem"thread"))
|
||||
end
|
||||
|
||||
Cstacklevel = function ()
|
||||
local _, _, ncalls = T.stacklevel()
|
||||
return ncalls -- number of C calls
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
local Cstack = Cstacklevel()
|
||||
|
||||
--
|
||||
-- redefine dofile to run files through dump/undump
|
||||
--
|
||||
@@ -139,18 +154,8 @@ end
|
||||
|
||||
dofile('main.lua')
|
||||
|
||||
do
|
||||
local next, setmetatable, stderr = next, setmetatable, io.stderr
|
||||
-- track collections
|
||||
local mt = {}
|
||||
-- each time a table is collected, remark it for finalization
|
||||
-- on next cycle
|
||||
mt.__gc = function (o)
|
||||
stderr:write'.' -- mark progress
|
||||
local n = setmetatable(o, mt) -- remark it
|
||||
end
|
||||
local n = setmetatable({}, mt) -- create object
|
||||
end
|
||||
-- trace GC cycles
|
||||
require"tracegc".start()
|
||||
|
||||
report"gc.lua"
|
||||
local f = assert(loadfile('gc.lua'))
|
||||
@@ -195,7 +200,12 @@ if #msgs > 0 then
|
||||
end
|
||||
|
||||
print("(there should be two warnings now)")
|
||||
warn("@on")
|
||||
warn("#This is ", "an expected", " warning")
|
||||
warn("@off")
|
||||
warn("******** THIS WARNING SHOULD NOT APPEAR **********")
|
||||
warn("******** THIS WARNING ALSO SHOULD NOT APPEAR **********")
|
||||
warn("@on")
|
||||
warn("#This is", " another one")
|
||||
|
||||
-- no test module should define 'debug'
|
||||
@@ -211,6 +221,10 @@ debug.sethook(function (a) assert(type(a) == 'string') end, "cr")
|
||||
-- to survive outside block
|
||||
_G.showmem = showmem
|
||||
|
||||
|
||||
assert(Cstack == Cstacklevel(),
|
||||
"should be at the same C-stack level it was when started the tests")
|
||||
|
||||
end --)
|
||||
|
||||
local _G, showmem, print, format, clock, time, difftime,
|
||||
|
||||
+188
-38
@@ -11,6 +11,9 @@ local debug = require "debug"
|
||||
local pack = table.pack
|
||||
|
||||
|
||||
-- standard error message for memory errors
|
||||
local MEMERRMSG = "not enough memory"
|
||||
|
||||
function tcheck (t1, t2)
|
||||
assert(t1.n == (t2.n or #t2) + 1)
|
||||
for i = 2, t1.n do assert(t1[i] == t2[i - 1]) end
|
||||
@@ -241,6 +244,23 @@ assert(a == 20 and b == false)
|
||||
a,b = T.testC("compare LE 5 -6, return 2", a1, 2, 2, a1, 2, 20)
|
||||
assert(a == 20 and b == true)
|
||||
|
||||
|
||||
do -- testing lessthan and lessequal with metamethods
|
||||
local mt = {__lt = function (a,b) return a[1] < b[1] end,
|
||||
__le = function (a,b) return a[1] <= b[1] end,
|
||||
__eq = function (a,b) return a[1] == b[1] end}
|
||||
local function O (x)
|
||||
return setmetatable({x}, mt)
|
||||
end
|
||||
|
||||
local a, b = T.testC("compare LT 2 3; pushint 10; return 2", O(1), O(2))
|
||||
assert(a == true and b == 10)
|
||||
local a, b = T.testC("compare LE 2 3; pushint 10; return 2", O(3), O(2))
|
||||
assert(a == false and b == 10)
|
||||
local a, b = T.testC("compare EQ 2 3; pushint 10; return 2", O(3), O(3))
|
||||
assert(a == true and b == 10)
|
||||
end
|
||||
|
||||
-- testing length
|
||||
local t = setmetatable({x = 20}, {__len = function (t) return t.x end})
|
||||
a,b,c = T.testC([[
|
||||
@@ -354,8 +374,11 @@ assert(to("topointer", nil) == null)
|
||||
assert(to("topointer", "abc") ~= null)
|
||||
assert(to("topointer", string.rep("x", 10)) ==
|
||||
to("topointer", string.rep("x", 10))) -- short strings
|
||||
assert(to("topointer", string.rep("x", 300)) ~=
|
||||
to("topointer", string.rep("x", 300))) -- long strings
|
||||
do -- long strings
|
||||
local s1 = string.rep("x", 300)
|
||||
local s2 = string.rep("x", 300)
|
||||
assert(to("topointer", s1) ~= to("topointer", s2))
|
||||
end
|
||||
assert(to("topointer", T.pushuserdata(20)) ~= null)
|
||||
assert(to("topointer", io.read) ~= null) -- light C function
|
||||
assert(to("topointer", hfunc) ~= null) -- "heavy" C function
|
||||
@@ -388,7 +411,7 @@ do
|
||||
|
||||
-- memory error
|
||||
T.totalmem(T.totalmem()+10000) -- set low memory limit (+10k)
|
||||
assert(T.checkpanic("newuserdata 20000") == "not enough memory")
|
||||
assert(T.checkpanic("newuserdata 20000") == MEMERRMSG)
|
||||
T.totalmem(0) -- restore high limit
|
||||
|
||||
-- stack error
|
||||
@@ -484,10 +507,12 @@ function checkerrnopro (code, msg)
|
||||
end
|
||||
|
||||
if not _soft then
|
||||
collectgarbage("stop") -- avoid __gc with full stack
|
||||
checkerrnopro("pushnum 3; call 0 0", "attempt to call")
|
||||
print"testing stack overflow in unprotected thread"
|
||||
function f () f() end
|
||||
checkerrnopro("getglobal 'f'; call 0 0;", "stack overflow")
|
||||
collectgarbage("restart")
|
||||
end
|
||||
print"+"
|
||||
|
||||
@@ -496,9 +521,57 @@ print"+"
|
||||
|
||||
do -- getp/setp
|
||||
local a = {}
|
||||
T.testC("rawsetp 2 1", a, 20)
|
||||
local a1 = T.testC("rawsetp 2 1; return 1", a, 20)
|
||||
assert(a == a1)
|
||||
assert(a[T.pushuserdata(1)] == 20)
|
||||
assert(T.testC("rawgetp 2 1; return 1", a) == 20)
|
||||
local a1, res = T.testC("rawgetp -1 1; return 2", a)
|
||||
assert(a == a1 and res == 20)
|
||||
end
|
||||
|
||||
|
||||
do -- using the table itself as index
|
||||
local a = {}
|
||||
a[a] = 10
|
||||
local prog = "gettable -1; return *"
|
||||
local res = {T.testC(prog, a)}
|
||||
assert(#res == 2 and res[1] == prog and res[2] == 10)
|
||||
|
||||
local prog = "settable -2; return *"
|
||||
local res = {T.testC(prog, a, 20)}
|
||||
assert(a[a] == 20)
|
||||
assert(#res == 1 and res[1] == prog)
|
||||
|
||||
-- raw
|
||||
a[a] = 10
|
||||
local prog = "rawget -1; return *"
|
||||
local res = {T.testC(prog, a)}
|
||||
assert(#res == 2 and res[1] == prog and res[2] == 10)
|
||||
|
||||
local prog = "rawset -2; return *"
|
||||
local res = {T.testC(prog, a, 20)}
|
||||
assert(a[a] == 20)
|
||||
assert(#res == 1 and res[1] == prog)
|
||||
|
||||
-- using the table as the value to set
|
||||
local prog = "rawset -1; return *"
|
||||
local res = {T.testC(prog, 30, a)}
|
||||
assert(a[30] == a)
|
||||
assert(#res == 1 and res[1] == prog)
|
||||
|
||||
local prog = "settable -1; return *"
|
||||
local res = {T.testC(prog, 40, a)}
|
||||
assert(a[40] == a)
|
||||
assert(#res == 1 and res[1] == prog)
|
||||
|
||||
local prog = "rawseti -1 100; return *"
|
||||
local res = {T.testC(prog, a)}
|
||||
assert(a[100] == a)
|
||||
assert(#res == 1 and res[1] == prog)
|
||||
|
||||
local prog = "seti -1 200; return *"
|
||||
local res = {T.testC(prog, a)}
|
||||
assert(a[200] == a)
|
||||
assert(#res == 1 and res[1] == prog)
|
||||
end
|
||||
|
||||
a = {x=0, y=12}
|
||||
@@ -632,7 +705,7 @@ for k, v in ipairs(t) do
|
||||
assert(v1 == v and p)
|
||||
end
|
||||
|
||||
assert(debug.getuservalue(4) == nil)
|
||||
assert(not debug.getuservalue(4))
|
||||
|
||||
debug.setuservalue(b, function () return 10 end, 10)
|
||||
collectgarbage() -- function should not be collected
|
||||
@@ -731,15 +804,14 @@ F = function (x)
|
||||
d = nil
|
||||
assert(debug.getmetatable(x).__gc == F)
|
||||
assert(load("table.insert({}, {})"))() -- create more garbage
|
||||
collectgarbage() -- force a GC during GC
|
||||
assert(debug.getmetatable(x).__gc == F) -- previous GC did not mess this?
|
||||
assert(not collectgarbage()) -- GC during GC (no op)
|
||||
local dummy = {} -- create more garbage during GC
|
||||
if A ~= nil then
|
||||
assert(type(A) == "userdata")
|
||||
assert(T.udataval(A) == B)
|
||||
debug.getmetatable(A) -- just acess it
|
||||
debug.getmetatable(A) -- just access it
|
||||
end
|
||||
A = x -- ressucita userdata
|
||||
A = x -- ressurect userdata
|
||||
B = udval
|
||||
return 1,2,3
|
||||
end
|
||||
@@ -911,6 +983,7 @@ assert(t[7] == nil)
|
||||
|
||||
-------------------------------------------------------------------------
|
||||
do -- testing errors during GC
|
||||
warn("@off")
|
||||
collectgarbage("stop")
|
||||
local a = {}
|
||||
for i=1,20 do
|
||||
@@ -928,6 +1001,7 @@ do -- testing errors during GC
|
||||
collectgarbage()
|
||||
assert(A == 10) -- number of normal collections
|
||||
collectgarbage("restart")
|
||||
warn("@on")
|
||||
end
|
||||
-------------------------------------------------------------------------
|
||||
-- test for userdata vals
|
||||
@@ -1030,7 +1104,7 @@ do
|
||||
assert(type(a[1]) == "string" and a[2][1] == 11)
|
||||
assert(#openresource == 0) -- was closed
|
||||
|
||||
-- error
|
||||
-- closing by error
|
||||
local a, b = pcall(T.makeCfunc[[
|
||||
call 0 1 # create resource
|
||||
toclose -1 # mark it to be closed
|
||||
@@ -1039,26 +1113,62 @@ do
|
||||
assert(a == false and b[1] == 11)
|
||||
assert(#openresource == 0) -- was closed
|
||||
|
||||
-- non-closable value
|
||||
local a, b = pcall(T.makeCfunc[[
|
||||
newtable # create non-closable object
|
||||
toclose -1 # mark it to be closed (should raise an error)
|
||||
abort # will not be executed
|
||||
]])
|
||||
assert(a == false and
|
||||
string.find(b, "non%-closable value"))
|
||||
|
||||
local function check (n)
|
||||
assert(#openresource == n)
|
||||
end
|
||||
|
||||
-- closing resources with 'settop'
|
||||
-- closing resources with 'closeslot'
|
||||
_ENV.xxx = true
|
||||
local a = T.testC([[
|
||||
pushvalue 2
|
||||
call 0 1 # create resource
|
||||
pushvalue 2 # stack: S, NR, CH, NR
|
||||
call 0 1 # create resource; stack: S, NR, CH, R
|
||||
toclose -1 # mark it to be closed
|
||||
pushvalue 2
|
||||
call 0 1 # create another resource
|
||||
pushvalue 2 # stack: S, NR, CH, R, NR
|
||||
call 0 1 # create another resource; stack: S, NR, CH, R, R
|
||||
toclose -1 # mark it to be closed
|
||||
pushvalue 3
|
||||
pushvalue 3 # stack: S, NR, CH, R, R, CH
|
||||
pushint 2 # there should be two open resources
|
||||
call 1 0
|
||||
pop 1 # pop second resource from the stack
|
||||
pushvalue 3
|
||||
call 1 0 # stack: S, NR, CH, R, R
|
||||
closeslot -1 # close second resource
|
||||
pushvalue 3 # stack: S, NR, CH, R, R, CH
|
||||
pushint 1 # there should be one open resource
|
||||
call 1 0
|
||||
pop 1 # pop second resource from the stack
|
||||
call 1 0 # stack: S, NR, CH, R, R
|
||||
closeslot 4
|
||||
setglobal "xxx" # previous op. erased the slot
|
||||
pop 1 # pop other resource from the stack
|
||||
pushint *
|
||||
return 1 # return stack size
|
||||
]], newresource, check)
|
||||
assert(a == 3 and _ENV.xxx == nil) -- no extra items left in the stack
|
||||
|
||||
-- closing resources with 'pop'
|
||||
local a = T.testC([[
|
||||
pushvalue 2 # stack: S, NR, CH, NR
|
||||
call 0 1 # create resource; stack: S, NR, CH, R
|
||||
toclose -1 # mark it to be closed
|
||||
pushvalue 2 # stack: S, NR, CH, R, NR
|
||||
call 0 1 # create another resource; stack: S, NR, CH, R, R
|
||||
toclose -1 # mark it to be closed
|
||||
pushvalue 3 # stack: S, NR, CH, R, R, CH
|
||||
pushint 2 # there should be two open resources
|
||||
call 1 0 # stack: S, NR, CH, R, R
|
||||
pop 1 # pop second resource
|
||||
pushvalue 3 # stack: S, NR, CH, R, CH
|
||||
pushint 1 # there should be one open resource
|
||||
call 1 0 # stack: S, NR, CH, R
|
||||
pop 1 # pop other resource from the stack
|
||||
pushvalue 3 # stack: S, NR, CH, CH
|
||||
pushint 0 # there should be no open resources
|
||||
call 1 0 # stack: S, NR, CH
|
||||
pushint *
|
||||
return 1 # return stack size
|
||||
]], newresource, check)
|
||||
@@ -1074,40 +1184,74 @@ do
|
||||
end
|
||||
|
||||
|
||||
-------------------------------------------------------------------------
|
||||
-- testing memory limits
|
||||
-------------------------------------------------------------------------
|
||||
--[[
|
||||
** {==================================================================
|
||||
** Testing memory limits
|
||||
** ===================================================================
|
||||
--]]
|
||||
|
||||
print("memory-allocation errors")
|
||||
|
||||
checkerr("block too big", T.newuserdata, math.maxinteger)
|
||||
collectgarbage()
|
||||
local f = load"local a={}; for i=1,100000 do a[i]=i end"
|
||||
T.alloccount(10)
|
||||
checkerr("not enough memory", f)
|
||||
checkerr(MEMERRMSG, f)
|
||||
T.alloccount() -- remove limit
|
||||
|
||||
|
||||
-- test memory errors; increase limit for maximum memory by steps,
|
||||
-- o that we get memory errors in all allocations of a given
|
||||
-- task, until there is enough memory to complete the task without
|
||||
-- errors.
|
||||
function testbytes (s, f)
|
||||
collectgarbage()
|
||||
local M = T.totalmem()
|
||||
local oldM = M
|
||||
local a,b = nil
|
||||
while true do
|
||||
collectgarbage(); collectgarbage()
|
||||
T.totalmem(M)
|
||||
a, b = T.testC("pcall 0 1 0; pushstatus; return 2", f)
|
||||
T.totalmem(0) -- remove limit
|
||||
if a and b == "OK" then break end -- stop when no more errors
|
||||
if b ~= "OK" and b ~= MEMERRMSG then -- not a memory error?
|
||||
error(a, 0) -- propagate it
|
||||
end
|
||||
M = M + 7 -- increase memory limit
|
||||
end
|
||||
print(string.format("minimum memory for %s: %d bytes", s, M - oldM))
|
||||
return a
|
||||
end
|
||||
|
||||
-- test memory errors; increase limit for number of allocations one
|
||||
-- by one, so that we get memory errors in all allocations of a given
|
||||
-- task, until there is enough allocations to complete the task without
|
||||
-- errors.
|
||||
|
||||
function testamem (s, f)
|
||||
collectgarbage(); collectgarbage()
|
||||
function testalloc (s, f)
|
||||
collectgarbage()
|
||||
local M = 0
|
||||
local a,b = nil
|
||||
while true do
|
||||
collectgarbage(); collectgarbage()
|
||||
T.alloccount(M)
|
||||
a, b = pcall(f)
|
||||
a, b = T.testC("pcall 0 1 0; pushstatus; return 2", f)
|
||||
T.alloccount() -- remove limit
|
||||
if a and b then break end -- stop when no more errors
|
||||
if not a and not -- `real' error?
|
||||
(string.find(b, "memory") or string.find(b, "overflow")) then
|
||||
error(b, 0) -- propagate it
|
||||
if a and b == "OK" then break end -- stop when no more errors
|
||||
if b ~= "OK" and b ~= MEMERRMSG then -- not a memory error?
|
||||
error(a, 0) -- propagate it
|
||||
end
|
||||
M = M + 1 -- increase allocation limit
|
||||
end
|
||||
print(string.format("limit for %s: %d allocations", s, M))
|
||||
return b
|
||||
print(string.format("minimum allocations for %s: %d allocations", s, M))
|
||||
return a
|
||||
end
|
||||
|
||||
|
||||
local function testamem (s, f)
|
||||
testalloc(s, f)
|
||||
return testbytes(s, f)
|
||||
end
|
||||
|
||||
|
||||
@@ -1117,8 +1261,11 @@ assert(b == 10)
|
||||
|
||||
-- testing memory errors when creating a new state
|
||||
|
||||
b = testamem("state creation", T.newstate)
|
||||
T.closestate(b); -- close new state
|
||||
testamem("state creation", function ()
|
||||
local st = T.newstate()
|
||||
if st then T.closestate(st) end -- close new state
|
||||
return st
|
||||
end)
|
||||
|
||||
testamem("empty-table creation", function ()
|
||||
return {}
|
||||
@@ -1137,7 +1284,7 @@ end)
|
||||
testamem("to-be-closed variables", function()
|
||||
local flag
|
||||
do
|
||||
local <toclose> x =
|
||||
local x <close> =
|
||||
setmetatable({}, {__close = function () flag = true end})
|
||||
flag = false
|
||||
local x = {}
|
||||
@@ -1266,6 +1413,9 @@ testamem("growing stack", function ()
|
||||
return foo(100)
|
||||
end)
|
||||
|
||||
-- }==================================================================
|
||||
|
||||
|
||||
do -- testing failing in 'lua_checkstack'
|
||||
local res = T.testC([[rawcheckstack 500000; return 1]])
|
||||
assert(res == false)
|
||||
|
||||
+24
-1
@@ -28,7 +28,7 @@ do
|
||||
local path = table.concat(t, ";")
|
||||
-- use that path in a search
|
||||
local s, err = package.searchpath("xuxu", path)
|
||||
-- search fails; check that message has an occurence of
|
||||
-- search fails; check that message has an occurrence of
|
||||
-- '??????????' with ? replaced by xuxu and at least 'max' lines
|
||||
assert(not s and
|
||||
string.find(err, string.rep("xuxu", 10)) and
|
||||
@@ -47,6 +47,29 @@ do
|
||||
package.path = oldpath
|
||||
end
|
||||
|
||||
|
||||
do print"testing 'require' message"
|
||||
local oldpath = package.path
|
||||
local oldcpath = package.cpath
|
||||
|
||||
package.path = "?.lua;?/?"
|
||||
package.cpath = "?.so;?/init"
|
||||
|
||||
local st, msg = pcall(require, 'XXX')
|
||||
|
||||
local expected = [[module 'XXX' not found:
|
||||
no field package.preload['XXX']
|
||||
no file 'XXX.lua'
|
||||
no file 'XXX/XXX'
|
||||
no file 'XXX.so'
|
||||
no file 'XXX/init']]
|
||||
|
||||
assert(msg == expected)
|
||||
|
||||
package.path = oldpath
|
||||
package.cpath = oldcpath
|
||||
end
|
||||
|
||||
print('+')
|
||||
|
||||
|
||||
|
||||
+1
-1
@@ -66,7 +66,7 @@ assert(repstrings * ssize > 2.0^32) -- it should be larger than maximum size
|
||||
|
||||
local longs = string.rep("\0", ssize) -- create one long string
|
||||
|
||||
-- create function to concatentate 'repstrings' copies of its argument
|
||||
-- create function to concatenate 'repstrings' copies of its argument
|
||||
local rep = assert(load(
|
||||
"local a = ...; return " .. string.rep("a", repstrings, "..")))
|
||||
|
||||
|
||||
+8
-3
@@ -45,6 +45,11 @@ assert(-1 >> numbits == 0 and
|
||||
-1 << numbits == 0 and
|
||||
-1 << -numbits == 0)
|
||||
|
||||
assert(1 >> math.mininteger == 0)
|
||||
assert(1 >> math.maxinteger == 0)
|
||||
assert(1 << math.mininteger == 0)
|
||||
assert(1 << math.maxinteger == 0)
|
||||
|
||||
assert((2^30 - 1) << 2^30 == 0)
|
||||
assert((2^30 - 1) >> 2^30 == 0)
|
||||
|
||||
@@ -60,9 +65,9 @@ assert("1234.0" << "5.0" == 1234 * 32)
|
||||
assert("0xffff.0" ~ "0xAAAA" == 0x5555)
|
||||
assert(~"0x0.000p4" == -1)
|
||||
|
||||
assert("7" .. 3 << 1 == 146)
|
||||
assert(10 >> 1 .. "9" == 0)
|
||||
assert(10 | 1 .. "9" == 27)
|
||||
assert(("7" .. 3) << 1 == 146)
|
||||
assert(0xffffffff >> (1 .. "9") == 0x1fff)
|
||||
assert(10 | (1 .. "9") == 27)
|
||||
|
||||
do
|
||||
local st, msg = pcall(function () return 4 & "a" end)
|
||||
|
||||
+72
-9
@@ -107,7 +107,9 @@ end
|
||||
deep(10)
|
||||
deep(180)
|
||||
|
||||
-- testing tail calls
|
||||
|
||||
print"testing tail calls"
|
||||
|
||||
function deep (n) if n>0 then return deep(n-1) else return 101 end end
|
||||
assert(deep(30000) == 101)
|
||||
a = {}
|
||||
@@ -148,9 +150,47 @@ do -- tail calls x varargs
|
||||
assert(X == 10 and Y == 20 and #A == 1 and A[1] == 30)
|
||||
end
|
||||
|
||||
|
||||
|
||||
do -- tail calls x chain of __call
|
||||
local n = 10000 -- depth
|
||||
|
||||
local function foo ()
|
||||
if n == 0 then return 1023
|
||||
else n = n - 1; return foo()
|
||||
end
|
||||
end
|
||||
|
||||
-- build a chain of __call metamethods ending in function 'foo'
|
||||
for i = 1, 100 do
|
||||
foo = setmetatable({}, {__call = foo})
|
||||
end
|
||||
|
||||
-- call the first one as a tail call in a new coroutine
|
||||
-- (to ensure stack is not preallocated)
|
||||
assert(coroutine.wrap(function() return foo() end)() == 1023)
|
||||
end
|
||||
|
||||
print('+')
|
||||
|
||||
|
||||
do -- testing chains of '__call'
|
||||
local N = 20
|
||||
local u = table.pack
|
||||
for i = 1, N do
|
||||
u = setmetatable({i}, {__call = u})
|
||||
end
|
||||
|
||||
local Res = u("a", "b", "c")
|
||||
|
||||
assert(Res.n == N + 3)
|
||||
for i = 1, N do
|
||||
assert(Res[i][1] == i)
|
||||
end
|
||||
assert(Res[N + 1] == "a" and Res[N + 2] == "b" and Res[N + 3] == "c")
|
||||
end
|
||||
|
||||
|
||||
a = nil
|
||||
(function (x) a=x end)(23)
|
||||
assert(a == 23 and (function (x) return x*2 end)(20) == 40)
|
||||
@@ -277,6 +317,16 @@ f = load(string.dump(function () return 1 end), nil, "b", {})
|
||||
assert(type(f) == "function" and f() == 1)
|
||||
|
||||
|
||||
do -- another bug (in 5.4.0)
|
||||
-- loading a binary long string interrupted by GC cycles
|
||||
local f = string.dump(function ()
|
||||
return '01234567890123456789012345678901234567890123456789'
|
||||
end)
|
||||
f = load(read1(f))
|
||||
assert(f() == '01234567890123456789012345678901234567890123456789')
|
||||
end
|
||||
|
||||
|
||||
x = string.dump(load("x = 1; return x"))
|
||||
a = assert(load(read1(x), nil, "b"))
|
||||
assert(a() == 1 and _G.x == 1)
|
||||
@@ -318,8 +368,12 @@ x = [[
|
||||
end
|
||||
end
|
||||
]]
|
||||
a = assert(load(read1(x), "read", "t"))
|
||||
assert(a()(2)(3)(10) == 15)
|
||||
|
||||
a = assert(load(read1(x)))
|
||||
-- repeat the test loading a binary chunk
|
||||
x = string.dump(a)
|
||||
a = assert(load(read1(x), "read", "b"))
|
||||
assert(a()(2)(3)(10) == 15)
|
||||
|
||||
|
||||
@@ -382,20 +436,30 @@ assert((function (a) return a end)() == nil)
|
||||
|
||||
print("testing binary chunks")
|
||||
do
|
||||
local header = string.pack("c4BBBc6BBBj",
|
||||
local header = string.pack("c4BBc6BBB",
|
||||
"\27Lua", -- signature
|
||||
(504 >> 7) & 0x7f, (504 & 0x7f) | 0x80, -- version 5.4 (504)
|
||||
0x54, -- version 5.4 (0x54)
|
||||
0, -- format
|
||||
"\x19\x93\r\n\x1a\n", -- data
|
||||
4, -- size of instruction
|
||||
string.packsize("j"), -- sizeof(lua integer)
|
||||
string.packsize("n"), -- sizeof(lua number)
|
||||
0x5678 -- LUAC_INT
|
||||
-- LUAC_NUM may not have a unique binary representation (padding...)
|
||||
string.packsize("n") -- sizeof(lua number)
|
||||
)
|
||||
local c = string.dump(function () local a = 1; local b = 3; return a+b*3 end)
|
||||
local c = string.dump(function ()
|
||||
local a = 1; local b = 3;
|
||||
local f = function () return a + b + _ENV.c; end -- upvalues
|
||||
local s1 = "a constant"
|
||||
local s2 = "another constant"
|
||||
return a + b * 3
|
||||
end)
|
||||
|
||||
assert(assert(load(c))() == 10)
|
||||
|
||||
-- check header
|
||||
assert(string.sub(c, 1, #header) == header)
|
||||
-- check LUAC_INT and LUAC_NUM
|
||||
local ci, cn = string.unpack("jn", c, #header + 1)
|
||||
assert(ci == 0x5678 and cn == 370.5)
|
||||
|
||||
-- corrupted header
|
||||
for i = 1, #header do
|
||||
@@ -411,7 +475,6 @@ do
|
||||
local st, msg = load(string.sub(c, 1, i))
|
||||
assert(not st and string.find(msg, "truncated"))
|
||||
end
|
||||
assert(assert(load(c))() == 10)
|
||||
end
|
||||
|
||||
print('OK')
|
||||
|
||||
+1
-1
@@ -242,7 +242,7 @@ end
|
||||
|
||||
assert(debug.upvalueid(foo1, 1))
|
||||
assert(debug.upvalueid(foo1, 2))
|
||||
assert(not pcall(debug.upvalueid, foo1, 3))
|
||||
assert(not debug.upvalueid(foo1, 3))
|
||||
assert(debug.upvalueid(foo1, 1) == debug.upvalueid(foo2, 2))
|
||||
assert(debug.upvalueid(foo1, 2) == debug.upvalueid(foo2, 1))
|
||||
assert(debug.upvalueid(foo3, 1))
|
||||
|
||||
+149
-84
@@ -7,6 +7,23 @@ if T==nil then
|
||||
end
|
||||
print "testing code generation and optimizations"
|
||||
|
||||
-- to test constant propagation
|
||||
local k0aux <const> = 0
|
||||
local k0 <const> = k0aux
|
||||
local k1 <const> = 1
|
||||
local k3 <const> = 3
|
||||
local k6 <const> = k3 + (k3 << k0)
|
||||
local kFF0 <const> = 0xFF0
|
||||
local k3_78 <const> = 3.78
|
||||
local x, k3_78_4 <const> = 10, k3_78 / 4
|
||||
assert(x == 10)
|
||||
|
||||
local kx <const> = "x"
|
||||
|
||||
local kTrue <const> = true
|
||||
local kFalse <const> = false
|
||||
|
||||
local kNil <const> = nil
|
||||
|
||||
-- this code gave an error for the code checker
|
||||
do
|
||||
@@ -27,17 +44,45 @@ end
|
||||
|
||||
local function foo ()
|
||||
local a
|
||||
a = 3;
|
||||
a = k3;
|
||||
a = 0; a = 0.0; a = -7 + 7
|
||||
a = 3.78/4; a = 3.78/4
|
||||
a = -3.78/4; a = 3.78/4; a = -3.78/4
|
||||
a = k3_78/4; a = k3_78_4
|
||||
a = -k3_78/4; a = k3_78/4; a = -3.78/4
|
||||
a = -3.79/4; a = 0.0; a = -0;
|
||||
a = 3; a = 3.0; a = 3; a = 3.0
|
||||
a = k3; a = 3.0; a = 3; a = 3.0
|
||||
end
|
||||
|
||||
checkKlist(foo, {3.78/4, -3.78/4, -3.79/4})
|
||||
|
||||
|
||||
foo = function (f, a)
|
||||
f(100 * 1000)
|
||||
f(100.0 * 1000)
|
||||
f(-100 * 1000)
|
||||
f(-100 * 1000.0)
|
||||
f(100000)
|
||||
f(100000.0)
|
||||
f(-100000)
|
||||
f(-100000.0)
|
||||
end
|
||||
|
||||
checkKlist(foo, {100000, 100000.0, -100000, -100000.0})
|
||||
|
||||
|
||||
-- floats x integers
|
||||
foo = function (t, a)
|
||||
t[a] = 1; t[a] = 1.0
|
||||
t[a] = 1; t[a] = 1.0
|
||||
t[a] = 2; t[a] = 2.0
|
||||
t[a] = 0; t[a] = 0.0
|
||||
t[a] = 1; t[a] = 1.0
|
||||
t[a] = 2; t[a] = 2.0
|
||||
t[a] = 0; t[a] = 0.0
|
||||
end
|
||||
|
||||
checkKlist(foo, {1, 1.0, 2, 2.0, 0, 0.0})
|
||||
|
||||
|
||||
-- testing opcodes
|
||||
|
||||
-- check that 'f' opcodes match '...'
|
||||
@@ -77,19 +122,22 @@ end
|
||||
-- some basic instructions
|
||||
check(function () -- function does not create upvalues
|
||||
(function () end){f()}
|
||||
end, 'CLOSURE', 'NEWTABLE', 'GETTABUP', 'CALL', 'SETLIST', 'CALL', 'RETURN0')
|
||||
end, 'CLOSURE', 'NEWTABLE', 'EXTRAARG', 'GETTABUP', 'CALL',
|
||||
'SETLIST', 'CALL', 'RETURN0')
|
||||
|
||||
check(function (x) -- function creates upvalues
|
||||
(function () return x end){f()}
|
||||
end, 'CLOSURE', 'NEWTABLE', 'GETTABUP', 'CALL', 'SETLIST', 'CALL', 'RETURN')
|
||||
end, 'CLOSURE', 'NEWTABLE', 'EXTRAARG', 'GETTABUP', 'CALL',
|
||||
'SETLIST', 'CALL', 'RETURN')
|
||||
|
||||
|
||||
-- sequence of LOADNILs
|
||||
check(function ()
|
||||
local kNil <const> = nil
|
||||
local a,b,c
|
||||
local d; local e;
|
||||
local f,g,h;
|
||||
d = nil; d=nil; b=nil; a=nil; c=nil;
|
||||
d = nil; d=nil; b=nil; a=kNil; c=nil;
|
||||
end, 'LOADNIL', 'RETURN0')
|
||||
|
||||
check(function ()
|
||||
@@ -109,7 +157,7 @@ check (function (a,b,c) return a end, 'RETURN1')
|
||||
|
||||
|
||||
-- infinite loops
|
||||
check(function () while true do local a = -1 end end,
|
||||
check(function () while kTrue do local a = -1 end end,
|
||||
'LOADI', 'JMP', 'RETURN0')
|
||||
|
||||
check(function () while 1 do local a = -1 end end,
|
||||
@@ -124,10 +172,10 @@ check(function (a,b,c,d) return a..b..c..d end,
|
||||
'MOVE', 'MOVE', 'MOVE', 'MOVE', 'CONCAT', 'RETURN1')
|
||||
|
||||
-- not
|
||||
check(function () return not not nil end, 'LOADBOOL', 'RETURN1')
|
||||
check(function () return not not false end, 'LOADBOOL', 'RETURN1')
|
||||
check(function () return not not true end, 'LOADBOOL', 'RETURN1')
|
||||
check(function () return not not 1 end, 'LOADBOOL', 'RETURN1')
|
||||
check(function () return not not nil end, 'LOADFALSE', 'RETURN1')
|
||||
check(function () return not not kFalse end, 'LOADFALSE', 'RETURN1')
|
||||
check(function () return not not true end, 'LOADTRUE', 'RETURN1')
|
||||
check(function () return not not k3 end, 'LOADTRUE', 'RETURN1')
|
||||
|
||||
-- direct access to locals
|
||||
check(function ()
|
||||
@@ -136,15 +184,16 @@ check(function ()
|
||||
c.x, a[b] = -((a + d/b - a[b]) ^ a.x), b
|
||||
end,
|
||||
'LOADNIL',
|
||||
'MUL',
|
||||
'DIV', 'ADD', 'GETTABLE', 'SUB', 'GETFIELD', 'POW',
|
||||
'UNM', 'SETTABLE', 'SETFIELD', 'RETURN0')
|
||||
'MUL', 'MMBIN',
|
||||
'DIV', 'MMBIN', 'ADD', 'MMBIN', 'GETTABLE', 'SUB', 'MMBIN',
|
||||
'GETFIELD', 'POW', 'MMBIN', 'UNM', 'SETTABLE', 'SETFIELD', 'RETURN0')
|
||||
|
||||
|
||||
-- direct access to constants
|
||||
check(function ()
|
||||
local a,b
|
||||
a.x = 3.2
|
||||
local c = kNil
|
||||
a[kx] = 3.2
|
||||
a.x = b
|
||||
a[b] = 'x'
|
||||
end,
|
||||
@@ -152,8 +201,9 @@ end,
|
||||
|
||||
-- "get/set table" with numeric indices
|
||||
check(function (a)
|
||||
local k255 <const> = 255
|
||||
a[1] = a[100]
|
||||
a[255] = a[256]
|
||||
a[k255] = a[256]
|
||||
a[256] = 5
|
||||
end,
|
||||
'GETI', 'SETI',
|
||||
@@ -166,13 +216,13 @@ check(function ()
|
||||
b = a/a
|
||||
b = 5-4
|
||||
end,
|
||||
'LOADNIL', 'SUB', 'DIV', 'LOADI', 'RETURN0')
|
||||
'LOADNIL', 'SUB', 'MMBIN', 'DIV', 'MMBIN', 'LOADI', 'RETURN0')
|
||||
|
||||
check(function ()
|
||||
local a,b
|
||||
a[true] = false
|
||||
a[kTrue] = false
|
||||
end,
|
||||
'LOADNIL', 'LOADBOOL', 'SETTABLE', 'RETURN0')
|
||||
'LOADNIL', 'LOADTRUE', 'SETTABLE', 'RETURN0')
|
||||
|
||||
|
||||
-- equalities
|
||||
@@ -238,68 +288,81 @@ local function checkF (func, val)
|
||||
end
|
||||
|
||||
checkF(function () return 0.0 end, 0.0)
|
||||
checkI(function () return 0 end, 0)
|
||||
checkI(function () return -0//1 end, 0)
|
||||
checkI(function () return k0 end, 0)
|
||||
checkI(function () return -k0//1 end, 0)
|
||||
checkK(function () return 3^-1 end, 1/3)
|
||||
checkK(function () return (1 + 1)^(50 + 50) end, 2^100)
|
||||
checkK(function () return (-2)^(31 - 2) end, -0x20000000 + 0.0)
|
||||
checkF(function () return (-3^0 + 5) // 3.0 end, 1.0)
|
||||
checkI(function () return -3 % 5 end, 2)
|
||||
checkF(function () return (-k3^0 + 5) // 3.0 end, 1.0)
|
||||
checkI(function () return -k3 % 5 end, 2)
|
||||
checkF(function () return -((2.0^8 + -(-1)) % 8)/2 * 4 - 3 end, -5.0)
|
||||
checkF(function () return -((2^8 + -(-1)) % 8)//2 * 4 - 3 end, -7.0)
|
||||
checkI(function () return 0xF0.0 | 0xCC.0 ~ 0xAA & 0xFD end, 0xF4)
|
||||
checkI(function () return ~(~0xFF0 | 0xFF0) end, 0)
|
||||
checkI(function () return ~(~kFF0 | kFF0) end, 0)
|
||||
checkI(function () return ~~-1024.0 end, -1024)
|
||||
checkI(function () return ((100 << 6) << -4) >> 2 end, 100)
|
||||
checkI(function () return ((100 << k6) << -4) >> 2 end, 100)
|
||||
|
||||
-- borders around MAXARG_sBx ((((1 << 17) - 1) >> 1) == 65535)
|
||||
local a = 17; local sbx = ((1 << a) - 1) >> 1 -- avoid folding
|
||||
checkI(function () return 65535 end, sbx)
|
||||
checkI(function () return -65535 end, -sbx)
|
||||
checkI(function () return 65536 end, sbx + 1)
|
||||
checkK(function () return 65537 end, sbx + 2)
|
||||
checkK(function () return -65536 end, -(sbx + 1))
|
||||
local border <const> = 65535
|
||||
checkI(function () return border end, sbx)
|
||||
checkI(function () return -border end, -sbx)
|
||||
checkI(function () return border + 1 end, sbx + 1)
|
||||
checkK(function () return border + 2 end, sbx + 2)
|
||||
checkK(function () return -(border + 1) end, -(sbx + 1))
|
||||
|
||||
checkF(function () return 65535.0 end, sbx + 0.0)
|
||||
checkF(function () return -65535.0 end, -sbx + 0.0)
|
||||
checkF(function () return 65536.0 end, (sbx + 1.0))
|
||||
checkK(function () return 65537.0 end, (sbx + 2.0))
|
||||
checkK(function () return -65536.0 end, -(sbx + 1.0))
|
||||
local border <const> = 65535.0
|
||||
checkF(function () return border end, sbx + 0.0)
|
||||
checkF(function () return -border end, -sbx + 0.0)
|
||||
checkF(function () return border + 1 end, (sbx + 1.0))
|
||||
checkK(function () return border + 2 end, (sbx + 2.0))
|
||||
checkK(function () return -(border + 1) end, -(sbx + 1.0))
|
||||
|
||||
|
||||
-- immediate operands
|
||||
checkR(function (x) return x + 1 end, 10, 11, 'ADDI', 'RETURN1')
|
||||
checkR(function (x) return 128 + x end, 0.0, 128.0, 'ADDI', 'RETURN1')
|
||||
checkR(function (x) return x * -127 end, -1.0, 127.0, 'MULI', 'RETURN1')
|
||||
checkR(function (x) return 20 * x end, 2, 40, 'MULI', 'RETURN1')
|
||||
checkR(function (x) return x ^ -2 end, 2, 0.25, 'POWI', 'RETURN1')
|
||||
checkR(function (x) return x / 40 end, 40, 1.0, 'DIVI', 'RETURN1')
|
||||
checkR(function (x) return x // 1 end, 10.0, 10.0, 'IDIVI', 'RETURN1')
|
||||
checkR(function (x) return x % (100 - 10) end, 91, 1, 'MODI', 'RETURN1')
|
||||
checkR(function (x) return 1 << x end, 3, 8, 'SHLI', 'RETURN1')
|
||||
checkR(function (x) return x << 2 end, 10, 40, 'SHRI', 'RETURN1')
|
||||
checkR(function (x) return x >> 2 end, 8, 2, 'SHRI', 'RETURN1')
|
||||
checkR(function (x) return x & 1 end, 9, 1, 'BANDK', 'RETURN1')
|
||||
checkR(function (x) return 10 | x end, 1, 11, 'BORK', 'RETURN1')
|
||||
checkR(function (x) return -10 ~ x end, -1, 9, 'BXORK', 'RETURN1')
|
||||
checkR(function (x) return x + k1 end, 10, 11, 'ADDI', 'MMBINI', 'RETURN1')
|
||||
checkR(function (x) return x - 127 end, 10, -117, 'ADDI', 'MMBINI', 'RETURN1')
|
||||
checkR(function (x) return 128 + x end, 0.0, 128.0,
|
||||
'ADDI', 'MMBINI', 'RETURN1')
|
||||
checkR(function (x) return x * -127 end, -1.0, 127.0,
|
||||
'MULK', 'MMBINK', 'RETURN1')
|
||||
checkR(function (x) return 20 * x end, 2, 40, 'MULK', 'MMBINK', 'RETURN1')
|
||||
checkR(function (x) return x ^ -2 end, 2, 0.25, 'POWK', 'MMBINK', 'RETURN1')
|
||||
checkR(function (x) return x / 40 end, 40, 1.0, 'DIVK', 'MMBINK', 'RETURN1')
|
||||
checkR(function (x) return x // 1 end, 10.0, 10.0,
|
||||
'IDIVK', 'MMBINK', 'RETURN1')
|
||||
checkR(function (x) return x % (100 - 10) end, 91, 1,
|
||||
'MODK', 'MMBINK', 'RETURN1')
|
||||
checkR(function (x) return k1 << x end, 3, 8, 'SHLI', 'MMBINI', 'RETURN1')
|
||||
checkR(function (x) return x << 127 end, 10, 0, 'SHRI', 'MMBINI', 'RETURN1')
|
||||
checkR(function (x) return x << -127 end, 10, 0, 'SHRI', 'MMBINI', 'RETURN1')
|
||||
checkR(function (x) return x >> 128 end, 8, 0, 'SHRI', 'MMBINI', 'RETURN1')
|
||||
checkR(function (x) return x >> -127 end, 8, 0, 'SHRI', 'MMBINI', 'RETURN1')
|
||||
checkR(function (x) return x & 1 end, 9, 1, 'BANDK', 'MMBINK', 'RETURN1')
|
||||
checkR(function (x) return 10 | x end, 1, 11, 'BORK', 'MMBINK', 'RETURN1')
|
||||
checkR(function (x) return -10 ~ x end, -1, 9, 'BXORK', 'MMBINK', 'RETURN1')
|
||||
|
||||
-- K operands in arithmetic operations
|
||||
checkR(function (x) return x + 0.0 end, 1, 1.0, 'ADDK', 'RETURN1')
|
||||
-- check(function (x) return 128 + x end, 'ADDK', 'RETURN1')
|
||||
checkR(function (x) return x * -10000 end, 2, -20000, 'MULK', 'RETURN1')
|
||||
-- check(function (x) return 20 * x end, 'MULK', 'RETURN1')
|
||||
checkR(function (x) return x ^ 0.5 end, 4, 2.0, 'POWK', 'RETURN1')
|
||||
checkR(function (x) return x / 2.0 end, 4, 2.0, 'DIVK', 'RETURN1')
|
||||
checkR(function (x) return x // 10000 end, 10000, 1, 'IDIVK', 'RETURN1')
|
||||
checkR(function (x) return x % (100.0 - 10) end, 91, 1.0, 'MODK', 'RETURN1')
|
||||
checkR(function (x) return x + 0.0 end, 1, 1.0, 'ADDK', 'MMBINK', 'RETURN1')
|
||||
-- check(function (x) return 128 + x end, 'ADDK', 'MMBINK', 'RETURN1')
|
||||
checkR(function (x) return x * -10000 end, 2, -20000,
|
||||
'MULK', 'MMBINK', 'RETURN1')
|
||||
-- check(function (x) return 20 * x end, 'MULK', 'MMBINK', 'RETURN1')
|
||||
checkR(function (x) return x ^ 0.5 end, 4, 2.0, 'POWK', 'MMBINK', 'RETURN1')
|
||||
checkR(function (x) return x / 2.0 end, 4, 2.0, 'DIVK', 'MMBINK', 'RETURN1')
|
||||
checkR(function (x) return x // 10000 end, 10000, 1,
|
||||
'IDIVK', 'MMBINK', 'RETURN1')
|
||||
checkR(function (x) return x % (100.0 - 10) end, 91, 1.0,
|
||||
'MODK', 'MMBINK', 'RETURN1')
|
||||
|
||||
-- no foldings (and immediate operands)
|
||||
check(function () return -0.0 end, 'LOADF', 'UNM', 'RETURN1')
|
||||
check(function () return 3/0 end, 'LOADI', 'DIVI', 'RETURN1')
|
||||
check(function () return 0%0 end, 'LOADI', 'MODI', 'RETURN1')
|
||||
check(function () return -4//0 end, 'LOADI', 'IDIVI', 'RETURN1')
|
||||
check(function (x) return x >> 2.0 end, 'LOADF', 'SHR', 'RETURN1')
|
||||
check(function (x) return x & 2.0 end, 'LOADF', 'BAND', 'RETURN1')
|
||||
check(function () return k3/0 end, 'LOADI', 'DIVK', 'MMBINK', 'RETURN1')
|
||||
check(function () return 0%0 end, 'LOADI', 'MODK', 'MMBINK', 'RETURN1')
|
||||
check(function () return -4//0 end, 'LOADI', 'IDIVK', 'MMBINK', 'RETURN1')
|
||||
check(function (x) return x >> 2.0 end, 'LOADF', 'SHR', 'MMBIN', 'RETURN1')
|
||||
check(function (x) return x << 128 end, 'LOADI', 'SHL', 'MMBIN', 'RETURN1')
|
||||
check(function (x) return x & 2.0 end, 'LOADF', 'BAND', 'MMBIN', 'RETURN1')
|
||||
|
||||
-- basic 'for' loops
|
||||
check(function () for i = -10, 10.5 do end end,
|
||||
@@ -335,7 +398,7 @@ end,
|
||||
|
||||
do -- tests for table access in upvalues
|
||||
local t
|
||||
check(function () t.x = t.y end, 'GETTABUP', 'SETTABUP')
|
||||
check(function () t[kx] = t.y end, 'GETTABUP', 'SETTABUP')
|
||||
check(function (a) t[a()] = t[a()] end,
|
||||
'MOVE', 'CALL', 'GETUPVAL', 'MOVE', 'CALL',
|
||||
'GETUPVAL', 'GETTABLE', 'SETTABLE')
|
||||
@@ -355,30 +418,32 @@ check(function (a, b)
|
||||
if b then break else a = a + 1 end
|
||||
end
|
||||
end,
|
||||
'TEST', 'JMP', 'TEST', 'JMP', 'ADDI', 'JMP', 'RETURN0')
|
||||
'TEST', 'JMP', 'TEST', 'JMP', 'ADDI', 'MMBINI', 'JMP', 'RETURN0')
|
||||
|
||||
checkequal(
|
||||
function (a) while a < 10 do a = a + 1 end end,
|
||||
function (a)
|
||||
::loop::
|
||||
if not (a < 10) then goto exit end
|
||||
a = a + 1
|
||||
goto loop
|
||||
::exit::
|
||||
end
|
||||
)
|
||||
checkequal(function () return 6 or true or nil end,
|
||||
function () return k6 or kTrue or kNil end)
|
||||
|
||||
checkequal(
|
||||
function (a) repeat local x = a + 1; a = x until a > 0 end,
|
||||
function (a)
|
||||
::loop:: do
|
||||
local x = a + 1
|
||||
a = x
|
||||
checkequal(function () return 6 and true or nil end,
|
||||
function () return k6 and kTrue or kNil end)
|
||||
|
||||
|
||||
do -- string constants
|
||||
local k0 <const> = "00000000000000000000000000000000000000000000000000"
|
||||
local function f1 ()
|
||||
local k <const> = k0
|
||||
return function ()
|
||||
return function () return k end
|
||||
end
|
||||
end
|
||||
if not (a > 0) then goto loop end
|
||||
end
|
||||
)
|
||||
|
||||
local f2 = f1()
|
||||
local f3 = f2()
|
||||
assert(f3() == k0)
|
||||
checkK(f3, k0)
|
||||
-- string is not needed by other functions
|
||||
assert(T.listk(f1)[1] == nil)
|
||||
assert(T.listk(f2)[1] == nil)
|
||||
end
|
||||
|
||||
print 'OK'
|
||||
|
||||
|
||||
+27
-9
@@ -211,15 +211,15 @@ assert(a==1 and b==nil)
|
||||
print'+';
|
||||
|
||||
do -- testing constants
|
||||
local <const> prog = [[local <XXX> x = 10]]
|
||||
local prog <const> = [[local x <XXX> = 10]]
|
||||
checkload(prog, "unknown attribute 'XXX'")
|
||||
|
||||
checkload([[local <const> xxx = 20; xxx = 10]],
|
||||
checkload([[local xxx <const> = 20; xxx = 10]],
|
||||
":1: attempt to assign to const variable 'xxx'")
|
||||
|
||||
checkload([[
|
||||
local xx;
|
||||
local <const> xxx = 20;
|
||||
local xxx <const> = 20;
|
||||
local yyy;
|
||||
local function foo ()
|
||||
local abc = xx + yyy + xxx;
|
||||
@@ -228,7 +228,7 @@ do -- testing constants
|
||||
]], ":6: attempt to assign to const variable 'xxx'")
|
||||
|
||||
checkload([[
|
||||
local <toclose> x = nil
|
||||
local x <close> = nil
|
||||
x = io.open()
|
||||
]], ":2: attempt to assign to const variable 'x'")
|
||||
end
|
||||
@@ -287,7 +287,7 @@ a,b = F(nil)==nil; assert(a == true and b == nil)
|
||||
------------------------------------------------------------------
|
||||
|
||||
-- sometimes will be 0, sometimes will not...
|
||||
_ENV.GLOB1 = math.floor(os.time()) % 2
|
||||
_ENV.GLOB1 = math.random(0, 1)
|
||||
|
||||
-- basic expressions with their respective values
|
||||
local basiccases = {
|
||||
@@ -298,16 +298,36 @@ local basiccases = {
|
||||
{"(0==_ENV.GLOB1)", 0 == _ENV.GLOB1},
|
||||
}
|
||||
|
||||
local prog
|
||||
|
||||
if _ENV.GLOB1 == 0 then
|
||||
basiccases[2][1] = "F" -- constant false
|
||||
|
||||
prog = [[
|
||||
local F <const> = false
|
||||
if %s then IX = true end
|
||||
return %s
|
||||
]]
|
||||
else
|
||||
basiccases[4][1] = "k10" -- constant 10
|
||||
|
||||
prog = [[
|
||||
local k10 <const> = 10
|
||||
if %s then IX = true end
|
||||
return %s
|
||||
]]
|
||||
end
|
||||
|
||||
print('testing short-circuit optimizations (' .. _ENV.GLOB1 .. ')')
|
||||
|
||||
|
||||
-- operators with their respective values
|
||||
local <const> binops = {
|
||||
local binops <const> = {
|
||||
{" and ", function (a,b) if not a then return a else return b end end},
|
||||
{" or ", function (a,b) if a then return a else return b end end},
|
||||
}
|
||||
|
||||
local <const> cases = {}
|
||||
local cases <const> = {}
|
||||
|
||||
-- creates all combinations of '(cases[i] op cases[n-i])' plus
|
||||
-- 'not(cases[i] op cases[n-i])' (syntax + value)
|
||||
@@ -337,8 +357,6 @@ cases[1] = basiccases
|
||||
for i = 2, level do cases[i] = createcases(i) end
|
||||
print("+")
|
||||
|
||||
local prog = [[if %s then IX = true end; return %s]]
|
||||
|
||||
local i = 0
|
||||
for n = 1, level do
|
||||
for _, v in pairs(cases[n]) do
|
||||
|
||||
+173
-15
@@ -123,13 +123,23 @@ assert(#a == 22 and a[#a] == 79)
|
||||
x, a = nil
|
||||
|
||||
|
||||
-- coroutine closing
|
||||
print("to-be-closed variables in coroutines")
|
||||
|
||||
local function func2close (f)
|
||||
return setmetatable({}, {__close = f})
|
||||
end
|
||||
|
||||
do
|
||||
-- ok to close a dead coroutine
|
||||
local co = coroutine.create(print)
|
||||
assert(coroutine.resume(co, "testing 'coroutine.close'"))
|
||||
assert(coroutine.status(co) == "dead")
|
||||
assert(coroutine.close(co))
|
||||
local st, msg = coroutine.close(co)
|
||||
assert(st and msg == nil)
|
||||
-- also ok to close it again
|
||||
st, msg = coroutine.close(co)
|
||||
assert(st and msg == nil)
|
||||
|
||||
|
||||
-- cannot close the running coroutine
|
||||
local st, msg = pcall(coroutine.close, coroutine.running())
|
||||
@@ -143,15 +153,37 @@ do
|
||||
assert(not st and string.find(msg, "normal"))
|
||||
end))()
|
||||
|
||||
-- cannot close a coroutine while closing it
|
||||
do
|
||||
local co
|
||||
co = coroutine.create(
|
||||
function()
|
||||
local x <close> = func2close(function()
|
||||
coroutine.close(co) -- try to close it again
|
||||
end)
|
||||
coroutine.yield(20)
|
||||
end)
|
||||
local st, msg = coroutine.resume(co)
|
||||
assert(st and msg == 20)
|
||||
st, msg = coroutine.close(co)
|
||||
assert(not st and string.find(msg, "running coroutine"))
|
||||
end
|
||||
|
||||
-- to-be-closed variables in coroutines
|
||||
local X
|
||||
|
||||
local function func2close (f)
|
||||
return setmetatable({}, {__close = f})
|
||||
end
|
||||
-- closing a coroutine after an error
|
||||
local co = coroutine.create(error)
|
||||
local st, msg = coroutine.resume(co, 100)
|
||||
assert(not st and msg == 100)
|
||||
st, msg = coroutine.close(co)
|
||||
assert(not st and msg == 100)
|
||||
-- after closing, no more errors
|
||||
st, msg = coroutine.close(co)
|
||||
assert(st and msg == nil)
|
||||
|
||||
co = coroutine.create(function ()
|
||||
local <toclose> x = func2close(function (self, err)
|
||||
local x <close> = func2close(function (self, err)
|
||||
assert(err == nil); X = false
|
||||
end)
|
||||
X = true
|
||||
@@ -165,12 +197,12 @@ do
|
||||
-- error closing a coroutine
|
||||
local x = 0
|
||||
co = coroutine.create(function()
|
||||
local <toclose> y = func2close(function (self,err)
|
||||
if (err ~= 111) then os.exit(false) end -- should not happen
|
||||
local y <close> = func2close(function (self,err)
|
||||
assert(err == 111)
|
||||
x = 200
|
||||
error(200)
|
||||
end)
|
||||
local <toclose> x = func2close(function (self, err)
|
||||
local x <close> = func2close(function (self, err)
|
||||
assert(err == nil); error(111)
|
||||
end)
|
||||
coroutine.yield()
|
||||
@@ -178,9 +210,66 @@ do
|
||||
coroutine.resume(co)
|
||||
assert(x == 0)
|
||||
local st, msg = coroutine.close(co)
|
||||
assert(st == false and coroutine.status(co) == "dead" and msg == 111)
|
||||
assert(st == false and coroutine.status(co) == "dead" and msg == 200)
|
||||
assert(x == 200)
|
||||
-- after closing, no more errors
|
||||
st, msg = coroutine.close(co)
|
||||
assert(st and msg == nil)
|
||||
end
|
||||
|
||||
do
|
||||
-- <close> versus pcall in coroutines
|
||||
local X = false
|
||||
local Y = false
|
||||
function foo ()
|
||||
local x <close> = func2close(function (self, err)
|
||||
Y = debug.getinfo(2)
|
||||
X = err
|
||||
end)
|
||||
error(43)
|
||||
end
|
||||
co = coroutine.create(function () return pcall(foo) end)
|
||||
local st1, st2, err = coroutine.resume(co)
|
||||
assert(st1 and not st2 and err == 43)
|
||||
assert(X == 43 and Y.what == "C")
|
||||
|
||||
-- recovering from errors in __close metamethods
|
||||
local track = {}
|
||||
|
||||
local function h (o)
|
||||
local hv <close> = o
|
||||
return 1
|
||||
end
|
||||
|
||||
local function foo ()
|
||||
local x <close> = func2close(function(_,msg)
|
||||
track[#track + 1] = msg or false
|
||||
error(20)
|
||||
end)
|
||||
local y <close> = func2close(function(_,msg)
|
||||
track[#track + 1] = msg or false
|
||||
return 1000
|
||||
end)
|
||||
local z <close> = func2close(function(_,msg)
|
||||
track[#track + 1] = msg or false
|
||||
error(10)
|
||||
end)
|
||||
coroutine.yield(1)
|
||||
h(func2close(function(_,msg)
|
||||
track[#track + 1] = msg or false
|
||||
error(2)
|
||||
end))
|
||||
end
|
||||
|
||||
local co = coroutine.create(pcall)
|
||||
|
||||
local st, res = coroutine.resume(co, foo) -- call 'foo' protected
|
||||
assert(st and res == 1) -- yield 1
|
||||
local st, res1, res2 = coroutine.resume(co) -- continue
|
||||
assert(coroutine.status(co) == "dead")
|
||||
assert(st and not res1 and res2 == 20) -- last error (20)
|
||||
assert(track[1] == false and track[2] == 2 and track[3] == 10 and
|
||||
track[4] == 10)
|
||||
end
|
||||
|
||||
|
||||
@@ -356,7 +445,7 @@ do
|
||||
|
||||
local X = false
|
||||
A = coroutine.wrap(function()
|
||||
local <toclose> _ = setmetatable({}, {__close = function () X = true end})
|
||||
local _ <close> = func2close(function () X = true end)
|
||||
return pcall(A, 1)
|
||||
end)
|
||||
st, res = A()
|
||||
@@ -364,6 +453,22 @@ do
|
||||
end
|
||||
|
||||
|
||||
-- bug in 5.4.1
|
||||
do
|
||||
-- coroutine ran close metamethods with invalid status during a
|
||||
-- reset.
|
||||
local co
|
||||
co = coroutine.wrap(function()
|
||||
local x <close> = func2close(function() return pcall(co) end)
|
||||
error(111)
|
||||
end)
|
||||
local st, errobj = pcall(co)
|
||||
assert(not st and errobj == 111)
|
||||
st, errobj = pcall(co)
|
||||
assert(not st and string.find(errobj, "dead coroutine"))
|
||||
end
|
||||
|
||||
|
||||
-- attempt to resume 'normal' coroutine
|
||||
local co1, co2
|
||||
co1 = coroutine.create(function () return co2() end)
|
||||
@@ -398,7 +503,8 @@ assert(_G.f() == 12)
|
||||
|
||||
|
||||
if not T then
|
||||
(Message or print)('\n >>> testC not active: skipping yield/hook tests <<<\n')
|
||||
(Message or print)
|
||||
('\n >>> testC not active: skipping coroutine API tests <<<\n')
|
||||
else
|
||||
print "testing yields inside hooks"
|
||||
|
||||
@@ -426,10 +532,36 @@ else
|
||||
while A==0 or B==0 do -- A ~= 0 when 'x' finishes (similar for 'B','y')
|
||||
if A==0 then turn = "A"; assert(T.resume(x)) end
|
||||
if B==0 then turn = "B"; assert(T.resume(y)) end
|
||||
|
||||
-- check that traceback works correctly after yields inside hooks
|
||||
debug.traceback(x)
|
||||
debug.traceback(y)
|
||||
end
|
||||
|
||||
assert(B // A == 7) -- fact(7) // fact(6)
|
||||
|
||||
do -- hooks vs. multiple values
|
||||
local done
|
||||
local function test (n)
|
||||
done = false
|
||||
return coroutine.wrap(function ()
|
||||
local a = {}
|
||||
for i = 1, n do a[i] = i end
|
||||
-- 'pushint' just to perturb the stack
|
||||
T.sethook("pushint 10; yield 0", "", 1) -- yield at each op.
|
||||
local a1 = {table.unpack(a)} -- must keep top between ops.
|
||||
assert(#a1 == n)
|
||||
for i = 1, n do assert(a[i] == i) end
|
||||
done = true
|
||||
end)
|
||||
end
|
||||
-- arguments to the coroutine are just to perturb its stack
|
||||
local co = test(0); while not done do co(30) end
|
||||
co = test(1); while not done do co(20, 10) end
|
||||
co = test(3); while not done do co() end
|
||||
co = test(100); while not done do co() end
|
||||
end
|
||||
|
||||
local line = debug.getinfo(1, "l").currentline + 2 -- get line number
|
||||
local function foo ()
|
||||
local x = 10 --<< this line is 'line'
|
||||
@@ -551,8 +683,17 @@ else
|
||||
c == "ERRRUN" and d == 4)
|
||||
|
||||
|
||||
-- using a main thread as a coroutine
|
||||
-- using a main thread as a coroutine (dubious use!)
|
||||
local state = T.newstate()
|
||||
|
||||
-- check that yielddable is working correctly
|
||||
assert(T.testC(state, "newthread; isyieldable -1; remove 1; return 1"))
|
||||
|
||||
-- main thread is not yieldable
|
||||
assert(not T.testC(state, "rawgeti R 1; isyieldable -1; remove 1; return 1"))
|
||||
|
||||
T.testC(state, "settop 0")
|
||||
|
||||
T.loadlib(state)
|
||||
|
||||
assert(T.doremote(state, [[
|
||||
@@ -711,6 +852,17 @@ assert(run(function () return a / b end, {"div"}) == 10/12)
|
||||
assert(run(function () return a % b end, {"mod"}) == 10)
|
||||
assert(run(function () return a // b end, {"idiv"}) == 0)
|
||||
|
||||
-- repeat tests with larger constants (to use 'K' opcodes)
|
||||
local a1000 = new(1000)
|
||||
|
||||
assert(run(function () return a1000 + 1000 end, {"add"}) == 2000)
|
||||
assert(run(function () return a1000 - 25000 end, {"sub"}) == -24000)
|
||||
assert(run(function () return 2000 * a end, {"mul"}) == 20000)
|
||||
assert(run(function () return a1000 / 1000 end, {"div"}) == 1)
|
||||
assert(run(function () return a1000 % 600 end, {"mod"}) == 400)
|
||||
assert(run(function () return a1000 // 500 end, {"idiv"}) == 2)
|
||||
|
||||
|
||||
|
||||
assert(run(function () return a % b end, {"mod"}) == 10)
|
||||
|
||||
@@ -723,6 +875,12 @@ assert(run(function () return a >> b end, {"shr"}) == 10 >> 12)
|
||||
assert(run(function () return 10 & b end, {"band"}) == 10 & 12)
|
||||
assert(run(function () return a | 2 end, {"bor"}) == 10 | 2)
|
||||
assert(run(function () return a ~ 2 end, {"bxor"}) == 10 ~ 2)
|
||||
assert(run(function () return a >> 2 end, {"shr"}) == 10 >> 2)
|
||||
assert(run(function () return 1 >> a end, {"shr"}) == 1 >> 10)
|
||||
assert(run(function () return a << 2 end, {"shl"}) == 10 << 2)
|
||||
assert(run(function () return 1 << a end, {"shl"}) == 1 << 10)
|
||||
assert(run(function () return 2 ~ a end, {"bxor"}) == 2 ~ 10)
|
||||
|
||||
|
||||
assert(run(function () return a..b end, {"concat"}) == "1012")
|
||||
|
||||
@@ -733,7 +891,7 @@ assert(run(function() return "a" .. "b" .. a .. "c" .. c .. b .. "x" end,
|
||||
{"concat", "concat", "concat"}) == "ab10chello12x")
|
||||
|
||||
|
||||
do -- a few more tests for comparsion operators
|
||||
do -- a few more tests for comparison operators
|
||||
local mt1 = {
|
||||
__le = function (a,b)
|
||||
coroutine.yield(10)
|
||||
@@ -805,7 +963,7 @@ assert(run(function ()
|
||||
-- tests for coroutine API
|
||||
if T==nil then
|
||||
(Message or print)('\n >>> testC not active: skipping coroutine API tests <<<\n')
|
||||
return
|
||||
print "OK"; return
|
||||
end
|
||||
|
||||
print('testing coroutine API')
|
||||
|
||||
+123
-34
@@ -1,47 +1,33 @@
|
||||
-- $Id: testes/cstack.lua $
|
||||
-- See Copyright Notice in file all.lua
|
||||
|
||||
print"testing C-stack overflow detection"
|
||||
|
||||
local tracegc = require"tracegc"
|
||||
|
||||
print"testing stack overflow detection"
|
||||
|
||||
-- Segmentation faults in these tests probably result from a C-stack
|
||||
-- overflow. To avoid these errors, recompile Lua with a smaller
|
||||
-- value for the constant 'LUAI_MAXCCALLS' or else ensure a larger
|
||||
-- stack for the program.
|
||||
-- overflow. To avoid these errors, you should set a smaller limit for
|
||||
-- the use of C stack by Lua, by changing the constant 'LUAI_MAXCCALLS'.
|
||||
-- Alternatively, you can ensure a larger stack for the program.
|
||||
|
||||
|
||||
local function checkerror (msg, f, ...)
|
||||
local s, err = pcall(f, ...)
|
||||
assert(not s and string.find(err, msg))
|
||||
end
|
||||
|
||||
local count
|
||||
local back = string.rep("\b", 8)
|
||||
local function progress ()
|
||||
count = count + 1
|
||||
local n = string.format("%-8d", count)
|
||||
io.stderr:write(back, n)
|
||||
end
|
||||
|
||||
|
||||
do print("testing simple recursion:")
|
||||
count = 0
|
||||
local function foo ()
|
||||
progress()
|
||||
foo()
|
||||
end
|
||||
checkerror("stack overflow", foo)
|
||||
print("\tfinal count: ", count)
|
||||
end
|
||||
|
||||
|
||||
do print("testing stack overflow in message handling")
|
||||
count = 0
|
||||
local count = 0
|
||||
local function loop (x, y, z)
|
||||
progress()
|
||||
count = count + 1
|
||||
return 1 + loop(x, y, z)
|
||||
end
|
||||
tracegc.stop() -- __gc should not be called with a full stack
|
||||
local res, msg = xpcall(loop, loop)
|
||||
tracegc.start()
|
||||
assert(msg == "error in error handling")
|
||||
print("\tfinal count: ", count)
|
||||
print("final count: ", count)
|
||||
end
|
||||
|
||||
|
||||
@@ -54,29 +40,132 @@ do print("testing recursion inside pattern matching")
|
||||
end
|
||||
local m = f(80)
|
||||
assert(#m == 80)
|
||||
checkerror("too complex", f, 200000)
|
||||
checkerror("too complex", f, 2000)
|
||||
end
|
||||
|
||||
|
||||
do print("testing stack-overflow in recursive 'gsub'")
|
||||
count = 0
|
||||
local count = 0
|
||||
local function foo ()
|
||||
progress()
|
||||
count = count + 1
|
||||
string.gsub("a", ".", foo)
|
||||
end
|
||||
checkerror("stack overflow", foo)
|
||||
print("\tfinal count: ", count)
|
||||
print("final count: ", count)
|
||||
|
||||
print("testing stack-overflow in recursive 'gsub' with metatables")
|
||||
count = 0
|
||||
local count = 0
|
||||
local t = setmetatable({}, {__index = foo})
|
||||
foo = function ()
|
||||
count = count + 1
|
||||
progress(count)
|
||||
string.gsub("a", ".", t)
|
||||
end
|
||||
checkerror("stack overflow", foo)
|
||||
print("\tfinal count: ", count)
|
||||
print("final count: ", count)
|
||||
end
|
||||
|
||||
|
||||
do -- bug in 5.4.0
|
||||
print("testing limits in coroutines inside deep calls")
|
||||
local count = 0
|
||||
local lim = 1000
|
||||
local function stack (n)
|
||||
if n > 0 then return stack(n - 1) + 1
|
||||
else coroutine.wrap(function ()
|
||||
count = count + 1
|
||||
stack(lim)
|
||||
end)()
|
||||
end
|
||||
end
|
||||
|
||||
local st, msg = xpcall(stack, function () return "ok" end, lim)
|
||||
assert(not st and msg == "ok")
|
||||
print("final count: ", count)
|
||||
end
|
||||
|
||||
|
||||
do
|
||||
print("nesting of resuming yielded coroutines")
|
||||
local count = 0
|
||||
|
||||
local function body ()
|
||||
coroutine.yield()
|
||||
local f = coroutine.wrap(body)
|
||||
f(); -- start new coroutine (will stop in previous yield)
|
||||
count = count + 1
|
||||
f() -- call it recursively
|
||||
end
|
||||
|
||||
local f = coroutine.wrap(body)
|
||||
f()
|
||||
assert(not pcall(f))
|
||||
print("final count: ", count)
|
||||
end
|
||||
|
||||
|
||||
do -- bug in 5.4.2
|
||||
print("nesting coroutines running after recoverable errors")
|
||||
local count = 0
|
||||
local function foo()
|
||||
count = count + 1
|
||||
pcall(1) -- create an error
|
||||
-- running now inside 'precover' ("protected recover")
|
||||
coroutine.wrap(foo)() -- call another coroutine
|
||||
end
|
||||
checkerror("C stack overflow", foo)
|
||||
print("final count: ", count)
|
||||
end
|
||||
|
||||
|
||||
if T then
|
||||
print("testing stack recovery")
|
||||
local N = 0 -- trace number of calls
|
||||
local LIM = -1 -- will store N just before stack overflow
|
||||
|
||||
-- trace stack size; after stack overflow, it should be
|
||||
-- the maximum allowed stack size.
|
||||
local stack1
|
||||
local dummy
|
||||
|
||||
local function err(msg)
|
||||
assert(string.find(msg, "stack overflow"))
|
||||
local _, stacknow = T.stacklevel()
|
||||
assert(stacknow == stack1 + 200)
|
||||
end
|
||||
|
||||
-- When LIM==-1, the 'if' is not executed, so this function only
|
||||
-- counts and stores the stack limits up to overflow. Then, LIM
|
||||
-- becomes N, and then the 'if' code is run when the stack is
|
||||
-- full. Then, there is a stack overflow inside 'xpcall', after which
|
||||
-- the stack must have been restored back to its maximum normal size.
|
||||
local function f()
|
||||
dummy, stack1 = T.stacklevel()
|
||||
if N == LIM then
|
||||
xpcall(f, err)
|
||||
local _, stacknow = T.stacklevel()
|
||||
assert(stacknow == stack1)
|
||||
return
|
||||
end
|
||||
N = N + 1
|
||||
f()
|
||||
end
|
||||
|
||||
local topB, sizeB -- top and size Before overflow
|
||||
local topA, sizeA -- top and size After overflow
|
||||
topB, sizeB = T.stacklevel()
|
||||
tracegc.stop() -- __gc should not be called with a full stack
|
||||
xpcall(f, err)
|
||||
tracegc.start()
|
||||
topA, sizeA = T.stacklevel()
|
||||
-- sizes should be comparable
|
||||
assert(topA == topB and sizeA < sizeB * 2)
|
||||
print(string.format("maximum stack size: %d", stack1))
|
||||
LIM = N -- will stop recursion at maximum level
|
||||
N = 0 -- to count again
|
||||
tracegc.stop() -- __gc should not be called with a full stack
|
||||
f()
|
||||
tracegc.start()
|
||||
print"+"
|
||||
end
|
||||
|
||||
print'OK'
|
||||
|
||||
+90
-9
@@ -31,6 +31,7 @@ end
|
||||
|
||||
do
|
||||
assert(not pcall(debug.getinfo, print, "X")) -- invalid option
|
||||
assert(not pcall(debug.getinfo, 0, ">")) -- invalid option
|
||||
assert(not debug.getinfo(1000)) -- out of range level
|
||||
assert(not debug.getinfo(-1)) -- out of range level
|
||||
local a = debug.getinfo(print)
|
||||
@@ -119,6 +120,16 @@ else
|
||||
end
|
||||
]], {2,3,4,7})
|
||||
|
||||
test([[
|
||||
local function foo()
|
||||
end
|
||||
foo()
|
||||
A = 1
|
||||
A = 2
|
||||
A = 3
|
||||
]], {2, 3, 2, 4, 5, 6})
|
||||
|
||||
|
||||
test([[--
|
||||
if nil then
|
||||
a=1
|
||||
@@ -184,6 +195,49 @@ do -- testing line info/trace with large gaps in source
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
do -- testing active lines
|
||||
local function checkactivelines (f, lines)
|
||||
local t = debug.getinfo(f, "SL")
|
||||
for _, l in pairs(lines) do
|
||||
l = l + t.linedefined
|
||||
assert(t.activelines[l])
|
||||
t.activelines[l] = undef
|
||||
end
|
||||
assert(next(t.activelines) == nil) -- no extra lines
|
||||
end
|
||||
|
||||
checkactivelines(function (...) -- vararg function
|
||||
-- 1st line is empty
|
||||
-- 2nd line is empty
|
||||
-- 3th line is empty
|
||||
local a = 20
|
||||
-- 5th line is empty
|
||||
local b = 30
|
||||
-- 7th line is empty
|
||||
end, {4, 6, 8})
|
||||
|
||||
checkactivelines(function (a)
|
||||
-- 1st line is empty
|
||||
-- 2nd line is empty
|
||||
local a = 20
|
||||
local b = 30
|
||||
-- 5th line is empty
|
||||
end, {3, 4, 6})
|
||||
|
||||
checkactivelines(function (a, b, ...) end, {0})
|
||||
|
||||
checkactivelines(function (a, b)
|
||||
end, {1})
|
||||
|
||||
for _, n in pairs{0, 1, 2, 10, 50, 100, 1000, 10000} do
|
||||
checkactivelines(
|
||||
load(string.format("%s return 1", string.rep("\n", n))),
|
||||
{n + 1})
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
print'+'
|
||||
|
||||
-- invalid levels in [gs]etlocal
|
||||
@@ -255,6 +309,10 @@ do -- test hook presence in debug info
|
||||
end
|
||||
|
||||
|
||||
-- hook table has weak keys
|
||||
assert(getmetatable(debug.getregistry()._HOOKKEY).__mode == 'k')
|
||||
|
||||
|
||||
a = {}; L = nil
|
||||
local glob = 1
|
||||
local oldglob = glob
|
||||
@@ -347,12 +405,12 @@ assert(g(0,0) == 30)
|
||||
|
||||
|
||||
debug.sethook(nil);
|
||||
assert(debug.gethook() == nil)
|
||||
assert(not debug.gethook())
|
||||
|
||||
|
||||
-- minimal tests for setuservalue/getuservalue
|
||||
do
|
||||
assert(debug.setuservalue(io.stdin, 10) == nil)
|
||||
assert(not debug.setuservalue(io.stdin, 10))
|
||||
local a, b = debug.getuservalue(io.stdin, 10)
|
||||
assert(a == nil and not b)
|
||||
end
|
||||
@@ -410,7 +468,7 @@ end, "c")
|
||||
a:f(1,2,3,4,5)
|
||||
assert(X.self == a and X.a == 1 and X.b == 2 and X.c == nil)
|
||||
assert(XX == 12)
|
||||
assert(debug.gethook() == nil)
|
||||
assert(not debug.gethook())
|
||||
|
||||
|
||||
-- testing access to local variables in return hook (bug in 5.2)
|
||||
@@ -645,6 +703,11 @@ t = debug.getinfo(1) -- main
|
||||
assert(t.isvararg == true and t.nparams == 0 and t.nups == 1 and
|
||||
debug.getupvalue(t.func, 1) == "_ENV")
|
||||
|
||||
t = debug.getinfo(math.sin) -- C function
|
||||
assert(t.isvararg == true and t.nparams == 0 and t.nups == 0)
|
||||
|
||||
t = debug.getinfo(string.gmatch("abc", "a")) -- C closure
|
||||
assert(t.isvararg == true and t.nparams == 0 and t.nups > 0)
|
||||
|
||||
|
||||
|
||||
@@ -802,11 +865,12 @@ assert(a+3 == "add" and 3-a == "sub" and a*3 == "mul" and
|
||||
-a == "unm" and #a == "len" and a&3 == "band")
|
||||
assert(a + 30000 == "add" and a - 3.0 == "sub" and a * 3.0 == "mul" and
|
||||
-a == "unm" and #a == "len" and a & 3 == "band")
|
||||
assert(a|3 == "bor" and 3~a == "bxor" and a<<3 == "shift" and
|
||||
a>>1 == "shift")
|
||||
assert(a|3 == "bor" and 3~a == "bxor" and a<<3 == "shl" and a>>1 == "shr")
|
||||
assert (a==b and a.op == "eq")
|
||||
assert (a>=b and a.op == "order")
|
||||
assert (a>b and a.op == "order")
|
||||
assert (a>=b and a.op == "le")
|
||||
assert ("x">=a and a.op == "le")
|
||||
assert (a>b and a.op == "lt")
|
||||
assert (a>10 and a.op == "lt")
|
||||
assert(~a == "bnot")
|
||||
|
||||
do -- testing for-iterator name
|
||||
@@ -823,7 +887,7 @@ do -- testing debug info for finalizers
|
||||
|
||||
-- create a piece of garbage with a finalizer
|
||||
setmetatable({}, {__gc = function ()
|
||||
local t = debug.getinfo(2) -- get callee information
|
||||
local t = debug.getinfo(1) -- get function information
|
||||
assert(t.namewhat == "metamethod")
|
||||
name = t.name
|
||||
end})
|
||||
@@ -876,7 +940,7 @@ end
|
||||
|
||||
|
||||
print("testing debug functions on chunk without debug info")
|
||||
prog = [[-- program to be loaded without debug information
|
||||
prog = [[-- program to be loaded without debug information (strip)
|
||||
local debug = require'debug'
|
||||
local a = 12 -- a local variable
|
||||
|
||||
@@ -919,6 +983,23 @@ local f = assert(load(string.dump(load(prog), true)))
|
||||
|
||||
assert(f() == 13)
|
||||
|
||||
do -- bug in 5.4.0: line hooks in stripped code
|
||||
local function foo ()
|
||||
local a = 1
|
||||
local b = 2
|
||||
return b
|
||||
end
|
||||
|
||||
local s = load(string.dump(foo, true))
|
||||
local line = true
|
||||
debug.sethook(function (e, l)
|
||||
assert(e == "line")
|
||||
line = l
|
||||
end, "l")
|
||||
assert(s() == 2); debug.sethook(nil)
|
||||
assert(line == nil) -- hook called withoug debug info for 1st instruction
|
||||
end
|
||||
|
||||
do -- tests for 'source' in binary dumps
|
||||
local prog = [[
|
||||
return function (x)
|
||||
|
||||
+99
-23
@@ -18,14 +18,15 @@ end
|
||||
|
||||
local function doit (s)
|
||||
local f, msg = load(s)
|
||||
if f == nil then return msg end
|
||||
if not f then return msg end
|
||||
local cond, msg = pcall(f)
|
||||
return (not cond) and msg
|
||||
end
|
||||
|
||||
|
||||
local function checkmessage (prog, msg)
|
||||
local function checkmessage (prog, msg, debug)
|
||||
local m = doit(prog)
|
||||
if debug then print(m, msg) end
|
||||
assert(string.find(m, msg, 1, true))
|
||||
end
|
||||
|
||||
@@ -67,6 +68,27 @@ checksyntax([[
|
||||
]], "'}' expected (to close '{' at line 1)", "<eof>", 3)
|
||||
|
||||
|
||||
do -- testing errors in goto/break
|
||||
local function checksyntax (prog, msg, line)
|
||||
local st, err = load(prog)
|
||||
assert(string.find(err, "line " .. line))
|
||||
assert(string.find(err, msg, 1, true))
|
||||
end
|
||||
|
||||
checksyntax([[
|
||||
::A:: a = 1
|
||||
::A::
|
||||
]], "label 'A' already defined", 1)
|
||||
|
||||
checksyntax([[
|
||||
a = 1
|
||||
goto A
|
||||
do ::A:: end
|
||||
]], "no visible label 'A'", 2)
|
||||
|
||||
end
|
||||
|
||||
|
||||
if not T then
|
||||
(Message or print)
|
||||
('\n >>> testC not active: skipping memory message test <<<\n')
|
||||
@@ -99,6 +121,17 @@ assert(not string.find(doit"a={13}; local bbbb=1; a[bbbb](3)", "'bbbb'"))
|
||||
checkmessage("a={13}; local bbbb=1; a[bbbb](3)", "number")
|
||||
checkmessage("a=(1)..{}", "a table value")
|
||||
|
||||
-- calls
|
||||
checkmessage("local a; a(13)", "local 'a'")
|
||||
checkmessage([[
|
||||
local a = setmetatable({}, {__add = 34})
|
||||
a = a + 1
|
||||
]], "metamethod 'add'")
|
||||
checkmessage([[
|
||||
local a = setmetatable({}, {__lt = {}})
|
||||
a = a > a
|
||||
]], "metamethod 'lt'")
|
||||
|
||||
-- tail calls
|
||||
checkmessage("local a={}; return a.bbbb(3)", "field 'bbbb'")
|
||||
checkmessage("a={}; do local a=1 end; return a:bbbb(3)", "method 'bbbb'")
|
||||
@@ -158,6 +191,13 @@ checkmessage("a = 24 // 0", "divide by zero")
|
||||
checkmessage("a = 1 % 0", "'n%0'")
|
||||
|
||||
|
||||
-- type error for an object which is neither in an upvalue nor a register.
|
||||
-- The following code will try to index the value 10 that is stored in
|
||||
-- the metatable, without moving it to a register.
|
||||
checkmessage("local a = setmetatable({}, {__index = 10}).x",
|
||||
"attempt to index a number value")
|
||||
|
||||
|
||||
-- numeric for loops
|
||||
checkmessage("for i = {}, 10 do end", "table")
|
||||
checkmessage("for i = io.stdin, 10 do end", "FILE")
|
||||
@@ -188,6 +228,22 @@ do -- named objects (field '__name')
|
||||
checkmessage("return {} < XX", "table with My Type")
|
||||
checkmessage("return XX < io.stdin", "My Type with FILE*")
|
||||
_G.XX = nil
|
||||
|
||||
if T then -- extra tests for 'luaL_tolstring'
|
||||
-- bug in 5.4.3; 'luaL_tolstring' with negative indices
|
||||
local x = setmetatable({}, {__name="TABLE"})
|
||||
assert(T.testC("Ltolstring -1; return 1", x) == tostring(x))
|
||||
|
||||
local a, b = T.testC("pushint 10; Ltolstring -2; return 2", x)
|
||||
assert(a == 10 and b == tostring(x))
|
||||
|
||||
setmetatable(x, {__tostring=function (o)
|
||||
assert(o == x)
|
||||
return "ABC"
|
||||
end})
|
||||
local a, b, c = T.testC("pushint 10; Ltolstring -2; return 3", x)
|
||||
assert(a == x and b == 10 and c == "ABC")
|
||||
end
|
||||
end
|
||||
|
||||
-- global functions
|
||||
@@ -249,7 +305,7 @@ end]], "global 'insert'")
|
||||
|
||||
checkmessage([[ -- tail call
|
||||
return math.sin("a")
|
||||
]], "'sin'")
|
||||
]], "sin")
|
||||
|
||||
checkmessage([[collectgarbage("nooption")]], "invalid option")
|
||||
|
||||
@@ -312,8 +368,8 @@ end
|
||||
|
||||
local function lineerror (s, l)
|
||||
local err,msg = pcall(load(s))
|
||||
local line = string.match(msg, ":(%d+):")
|
||||
assert(tonumber(line) == l)
|
||||
local line = tonumber(string.match(msg, ":(%d+):"))
|
||||
assert(line == l or (not line and not l))
|
||||
end
|
||||
|
||||
lineerror("local a\n for i=1,'a' do \n print(i) \n end", 2)
|
||||
@@ -359,7 +415,7 @@ local p = [[
|
||||
g()
|
||||
]]
|
||||
X=3;lineerror((p), 3)
|
||||
X=0;lineerror((p), nil)
|
||||
X=0;lineerror((p), false)
|
||||
X=1;lineerror((p), 2)
|
||||
X=2;lineerror((p), 1)
|
||||
|
||||
@@ -380,31 +436,47 @@ if not b then
|
||||
end
|
||||
end]], 5)
|
||||
|
||||
do
|
||||
-- Force a negative estimate for base line. Error in instruction 2
|
||||
-- (after VARARGPREP, GETGLOBAL), with first absolute line information
|
||||
-- (forced by too many lines) in instruction 0.
|
||||
local s = string.format("%s return __A.x", string.rep("\n", 300))
|
||||
lineerror(s, 301)
|
||||
end
|
||||
|
||||
|
||||
if not _soft then
|
||||
-- several tests that exaust the Lua stack
|
||||
collectgarbage()
|
||||
print"testing stack overflow"
|
||||
C = 0
|
||||
local l = debug.getinfo(1, "l").currentline; function y () C=C+1; y() end
|
||||
-- get line where stack overflow will happen
|
||||
local l = debug.getinfo(1, "l").currentline + 1
|
||||
local function auxy () C=C+1; auxy() end -- produce a stack overflow
|
||||
function y ()
|
||||
collectgarbage("stop") -- avoid running finalizers without stack space
|
||||
auxy()
|
||||
collectgarbage("restart")
|
||||
end
|
||||
|
||||
local function checkstackmessage (m)
|
||||
print("(expected stack overflow after " .. C .. " calls)")
|
||||
C = 0 -- prepare next count
|
||||
return (string.find(m, "stack overflow"))
|
||||
end
|
||||
-- repeated stack overflows (to check stack recovery)
|
||||
assert(checkstackmessage(doit('y()')))
|
||||
print('+')
|
||||
assert(checkstackmessage(doit('y()')))
|
||||
print('+')
|
||||
assert(checkstackmessage(doit('y()')))
|
||||
print('+')
|
||||
|
||||
|
||||
-- error lines in stack overflow
|
||||
C = 0
|
||||
local l1
|
||||
local function g(x)
|
||||
l1 = debug.getinfo(x, "l").currentline; y()
|
||||
l1 = debug.getinfo(x, "l").currentline + 2
|
||||
collectgarbage("stop") -- avoid running finalizers without stack space
|
||||
auxy()
|
||||
collectgarbage("restart")
|
||||
end
|
||||
local _, stackmsg = xpcall(g, debug.traceback, 1)
|
||||
print('+')
|
||||
@@ -510,7 +582,7 @@ checksyntax("a\1a = 1", "", "<\\1>", 1)
|
||||
checksyntax("\255a = 1", "", "<\\255>", 1)
|
||||
|
||||
doit('I = load("a=9+"); a=3')
|
||||
assert(a==3 and I == nil)
|
||||
assert(a==3 and not I)
|
||||
print('+')
|
||||
|
||||
lim = 1000
|
||||
@@ -523,25 +595,29 @@ end
|
||||
|
||||
-- testing syntax limits
|
||||
|
||||
local function testrep (init, rep, close, repc)
|
||||
local function testrep (init, rep, close, repc, finalresult)
|
||||
local s = init .. string.rep(rep, 100) .. close .. string.rep(repc, 100)
|
||||
assert(load(s)) -- 100 levels is OK
|
||||
s = init .. string.rep(rep, 10000)
|
||||
local res, msg = load(s) -- 10000 levels not ok
|
||||
assert(not res and (string.find(msg, "too many registers") or
|
||||
string.find(msg, "stack overflow")))
|
||||
local res, msg = load(s)
|
||||
assert(res) -- 100 levels is OK
|
||||
if (finalresult) then
|
||||
assert(res() == finalresult)
|
||||
end
|
||||
s = init .. string.rep(rep, 500)
|
||||
local res, msg = load(s) -- 500 levels not ok
|
||||
assert(not res and (string.find(msg, "too many") or
|
||||
string.find(msg, "overflow")))
|
||||
end
|
||||
|
||||
testrep("local a; a", ",a", "= 1", ",1") -- multiple assignment
|
||||
testrep("local a; a=", "{", "0", "}")
|
||||
testrep("local a; a=", "(", "2", ")")
|
||||
testrep("local a; ", "a(", "2", ")")
|
||||
testrep("return ", "(", "2", ")", 2)
|
||||
testrep("local function a (x) return x end; return ", "a(", "2.2", ")", 2.2)
|
||||
testrep("", "do ", "", " end")
|
||||
testrep("", "while a do ", "", " end")
|
||||
testrep("local a; ", "if a then else ", "", " end")
|
||||
testrep("", "function foo () ", "", " end")
|
||||
testrep("local a; a=", "a..", "a", "")
|
||||
testrep("local a; a=", "a^", "a", "")
|
||||
testrep("local a = ''; return ", "a..", "'a'", "", "a")
|
||||
testrep("local a = 1; return ", "a^", "a", "", 1)
|
||||
|
||||
checkmessage("a = f(x" .. string.rep(",x", 260) .. ")", "too many registers")
|
||||
|
||||
|
||||
+26
-3
@@ -182,7 +182,7 @@ assert(~a == a); checkcap{"bnot", a, a}
|
||||
assert(a << 3 == a); checkcap{"shl", a, 3}
|
||||
assert(1.5 >> a == 1.5); checkcap{"shr", 1.5, a}
|
||||
|
||||
-- for comparsion operators, all results are true
|
||||
-- for comparison operators, all results are true
|
||||
assert(5.0 > a); checkcap{"lt", a, 5.0}
|
||||
assert(a >= 10); checkcap{"le", 10, a}
|
||||
assert(a <= -10.0); checkcap{"le", a, -10.0}
|
||||
@@ -217,9 +217,16 @@ t.__le = function (a,b,c)
|
||||
return a<=b, "dummy"
|
||||
end
|
||||
|
||||
t.__eq = function (a,b,c)
|
||||
assert(c == nil)
|
||||
if type(a) == 'table' then a = a.x end
|
||||
if type(b) == 'table' then b = b.x end
|
||||
return a == b, "dummy"
|
||||
end
|
||||
|
||||
function Op(x) return setmetatable({x=x}, t) end
|
||||
|
||||
local function test ()
|
||||
local function test (a, b, c)
|
||||
assert(not(Op(1)<Op(1)) and (Op(1)<Op(2)) and not(Op(2)<Op(1)))
|
||||
assert(not(1 < Op(1)) and (Op(1) < 2) and not(2 < Op(1)))
|
||||
assert(not(Op('a')<Op('a')) and (Op('a')<Op('b')) and not(Op('b')<Op('a')))
|
||||
@@ -232,9 +239,13 @@ local function test ()
|
||||
assert((1 >= Op(1)) and not(1 >= Op(2)) and (Op(2) >= 1))
|
||||
assert((Op('a')>=Op('a')) and not(Op('a')>=Op('b')) and (Op('b')>=Op('a')))
|
||||
assert(('a' >= Op('a')) and not(Op('a') >= 'b') and (Op('b') >= Op('a')))
|
||||
assert(Op(1) == Op(1) and Op(1) ~= Op(2))
|
||||
assert(Op('a') == Op('a') and Op('a') ~= Op('b'))
|
||||
assert(a == a and a ~= b)
|
||||
assert(Op(3) == c)
|
||||
end
|
||||
|
||||
test()
|
||||
test(Op(1), Op(2), Op(3))
|
||||
|
||||
|
||||
-- test `partial order'
|
||||
@@ -294,6 +305,17 @@ t[Set{1,3,5}] = 1
|
||||
assert(t[Set{1,3,5}] == undef)
|
||||
|
||||
|
||||
do -- test invalidating flags
|
||||
local mt = {__eq = true}
|
||||
local a = setmetatable({10}, mt)
|
||||
local b = setmetatable({10}, mt)
|
||||
mt.__eq = nil
|
||||
assert(a ~= b) -- no metamethod
|
||||
mt.__eq = function (x,y) return x[1] == y[1] end
|
||||
assert(a == b) -- must use metamethod now
|
||||
end
|
||||
|
||||
|
||||
if not T then
|
||||
(Message or print)('\n >>> testC not active: skipping tests for \z
|
||||
userdata <<<\n')
|
||||
@@ -314,6 +336,7 @@ else
|
||||
assert(u1 == u3 and u3 == u1 and u1 ~= u2)
|
||||
assert(u2 == u1 and u2 == u3 and u3 == u2)
|
||||
assert(u2 ~= {}) -- different types cannot be equal
|
||||
assert(rawequal(u1, u1) and not rawequal(u1, u3))
|
||||
|
||||
local mirror = {}
|
||||
debug.setmetatable(u3, {__index = mirror, __newindex = mirror})
|
||||
|
||||
+94
-38
@@ -125,7 +125,7 @@ do
|
||||
-- closing file by scope
|
||||
local F = nil
|
||||
do
|
||||
local <toclose> f = assert(io.open(file, "w"))
|
||||
local f <close> = assert(io.open(file, "w"))
|
||||
F = f
|
||||
end
|
||||
assert(tostring(F) == "file (closed)")
|
||||
@@ -135,7 +135,7 @@ assert(os.remove(file))
|
||||
|
||||
do
|
||||
-- test writing/reading numbers
|
||||
local <toclose> f = assert(io.open(file, "w"))
|
||||
local f <close> = assert(io.open(file, "w"))
|
||||
f:write(maxint, '\n')
|
||||
f:write(string.format("0X%x\n", maxint))
|
||||
f:write("0xABCp-3", '\n')
|
||||
@@ -144,7 +144,7 @@ do
|
||||
f:write(string.format("0x%X\n", -maxint))
|
||||
f:write("-0xABCp-3", '\n')
|
||||
assert(f:close())
|
||||
local <toclose> f = assert(io.open(file, "r"))
|
||||
local f <close> = assert(io.open(file, "r"))
|
||||
assert(f:read("n") == maxint)
|
||||
assert(f:read("n") == maxint)
|
||||
assert(f:read("n") == 0xABCp-3)
|
||||
@@ -158,7 +158,7 @@ assert(os.remove(file))
|
||||
|
||||
-- testing multiple arguments to io.read
|
||||
do
|
||||
local <toclose> f = assert(io.open(file, "w"))
|
||||
local f <close> = assert(io.open(file, "w"))
|
||||
f:write[[
|
||||
a line
|
||||
another line
|
||||
@@ -170,21 +170,21 @@ three
|
||||
]]
|
||||
local l1, l2, l3, l4, n1, n2, c, dummy
|
||||
assert(f:close())
|
||||
local <toclose> f = assert(io.open(file, "r"))
|
||||
local f <close> = assert(io.open(file, "r"))
|
||||
l1, l2, n1, n2, dummy = f:read("l", "L", "n", "n")
|
||||
assert(l1 == "a line" and l2 == "another line\n" and
|
||||
n1 == 1234 and n2 == 3.45 and dummy == nil)
|
||||
assert(f:close())
|
||||
local <toclose> f = assert(io.open(file, "r"))
|
||||
local f <close> = assert(io.open(file, "r"))
|
||||
l1, l2, n1, n2, c, l3, l4, dummy = f:read(7, "l", "n", "n", 1, "l", "l")
|
||||
assert(l1 == "a line\n" and l2 == "another line" and c == '\n' and
|
||||
n1 == 1234 and n2 == 3.45 and l3 == "one" and l4 == "two"
|
||||
and dummy == nil)
|
||||
assert(f:close())
|
||||
local <toclose> f = assert(io.open(file, "r"))
|
||||
local f <close> = assert(io.open(file, "r"))
|
||||
-- second item failing
|
||||
l1, n1, n2, dummy = f:read("l", "n", "n", "l")
|
||||
assert(l1 == "a line" and n1 == nil)
|
||||
assert(l1 == "a line" and not n1)
|
||||
end
|
||||
assert(os.remove(file))
|
||||
|
||||
@@ -228,7 +228,7 @@ assert(f:read("n") == 0Xdeadbeefdeadbeef); assert(f:read(2) == "x\n")
|
||||
assert(f:read("n") == 0x1.13aP3); assert(f:read(1) == "e")
|
||||
|
||||
do -- attempt to read too long number
|
||||
assert(f:read("n") == nil) -- fails
|
||||
assert(not f:read("n")) -- fails
|
||||
local s = f:read("L") -- read rest of line
|
||||
assert(string.find(s, "^00*\n$")) -- lots of 0's left
|
||||
end
|
||||
@@ -314,13 +314,13 @@ assert(io.read() == "fourth_line")
|
||||
assert(io.read() == "") -- empty line
|
||||
assert(io.read('n') == 3450)
|
||||
assert(io.read(1) == '\n')
|
||||
assert(io.read(0) == nil) -- end of file
|
||||
assert(io.read(1) == nil) -- end of file
|
||||
assert(io.read(30000) == nil) -- end of file
|
||||
assert(not io.read(0)) -- end of file
|
||||
assert(not io.read(1)) -- end of file
|
||||
assert(not io.read(30000)) -- end of file
|
||||
assert(({io.read(1)})[2] == undef)
|
||||
assert(io.read() == nil) -- end of file
|
||||
assert(not io.read()) -- end of file
|
||||
assert(({io.read()})[2] == undef)
|
||||
assert(io.read('n') == nil) -- end of file
|
||||
assert(not io.read('n')) -- end of file
|
||||
assert(({io.read('n')})[2] == undef)
|
||||
assert(io.read('a') == '') -- end of file (OK for 'a')
|
||||
assert(io.read('a') == '') -- end of file (OK for 'a')
|
||||
@@ -356,7 +356,7 @@ assert(io.read(string.len(t)) == t)
|
||||
assert(io.read(1) == ' ')
|
||||
assert(io.read(0))
|
||||
assert(io.read('a') == ';end of file\n')
|
||||
assert(io.read(0) == nil)
|
||||
assert(not io.read(0))
|
||||
assert(io.close(io.input()))
|
||||
|
||||
|
||||
@@ -364,7 +364,7 @@ assert(io.close(io.input()))
|
||||
do
|
||||
local function ismsg (m)
|
||||
-- error message is not a code number
|
||||
return (type(m) == "string" and tonumber(m) == nil)
|
||||
return (type(m) == "string" and not tonumber(m))
|
||||
end
|
||||
|
||||
-- read
|
||||
@@ -393,7 +393,7 @@ assert(io.read"L" == "\n")
|
||||
assert(io.read"L" == "\n")
|
||||
assert(io.read"L" == "line\n")
|
||||
assert(io.read"L" == "other")
|
||||
assert(io.read"L" == nil)
|
||||
assert(not io.read"L")
|
||||
io.input():close()
|
||||
|
||||
local f = assert(io.open(file))
|
||||
@@ -427,10 +427,12 @@ do -- testing closing file in line iteration
|
||||
-- get the to-be-closed variable from a loop
|
||||
local function gettoclose (lv)
|
||||
lv = lv + 1
|
||||
for i = 1, math.maxinteger do
|
||||
local stvar = 0 -- to-be-closed is 4th state variable in the loop
|
||||
for i = 1, 1000 do
|
||||
local n, v = debug.getlocal(lv, i)
|
||||
if n == "(for toclose)" then
|
||||
return v
|
||||
if n == "(for state)" then
|
||||
stvar = stvar + 1
|
||||
if stvar == 4 then return v end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -460,7 +462,7 @@ end
|
||||
-- test for multipe arguments in 'lines'
|
||||
io.output(file); io.write"0123456789\n":close()
|
||||
for a,b in io.lines(file, 1, 1) do
|
||||
if a == "\n" then assert(b == nil)
|
||||
if a == "\n" then assert(not b)
|
||||
else assert(tonumber(a) == tonumber(b) - 1)
|
||||
end
|
||||
end
|
||||
@@ -471,13 +473,13 @@ end
|
||||
|
||||
for a,b,c in io.lines(file, "a", 0, 1) do
|
||||
if a == "" then break end
|
||||
assert(a == "0123456789\n" and b == nil and c == nil)
|
||||
assert(a == "0123456789\n" and not b and not c)
|
||||
end
|
||||
collectgarbage() -- to close file in previous iteration
|
||||
|
||||
io.output(file); io.write"00\n10\n20\n30\n40\n":close()
|
||||
for a, b in io.lines(file, "n", "n") do
|
||||
if a == 40 then assert(b == nil)
|
||||
if a == 40 then assert(not b)
|
||||
else assert(a == b - 10)
|
||||
end
|
||||
end
|
||||
@@ -652,7 +654,7 @@ and the rest of the file
|
||||
io.input(file)
|
||||
local _,a,b,c,d,e,h,__ = io.read(1, 'n', 'n', 'l', 'l', 'l', 'a', 10)
|
||||
assert(io.close(io.input()))
|
||||
assert(_ == ' ' and __ == nil)
|
||||
assert(_ == ' ' and not __)
|
||||
assert(type(a) == 'number' and a==123.4 and b==-56e-2)
|
||||
assert(d=='second line' and e=='third line')
|
||||
assert(h==[[
|
||||
@@ -704,7 +706,7 @@ if not _soft then
|
||||
io.input():seek('set', 0)
|
||||
y = io.read() -- huge line
|
||||
assert(x == y..'\n'..io.read())
|
||||
assert(io.read() == nil)
|
||||
assert(not io.read())
|
||||
io.close(io.input())
|
||||
assert(os.remove(file))
|
||||
x = nil; y = nil
|
||||
@@ -719,6 +721,21 @@ if not _port then
|
||||
progname = '"' .. arg[i + 1] .. '"'
|
||||
end
|
||||
print("testing popen/pclose and execute")
|
||||
-- invalid mode for popen
|
||||
checkerr("invalid mode", io.popen, "cat", "")
|
||||
checkerr("invalid mode", io.popen, "cat", "r+")
|
||||
checkerr("invalid mode", io.popen, "cat", "rw")
|
||||
do -- basic tests for popen
|
||||
local file = os.tmpname()
|
||||
local f = assert(io.popen("cat - > " .. file, "w"))
|
||||
f:write("a line")
|
||||
assert(f:close())
|
||||
local f = assert(io.popen("cat - < " .. file, "r"))
|
||||
assert(f:read("a") == "a line")
|
||||
assert(f:close())
|
||||
assert(os.remove(file))
|
||||
end
|
||||
|
||||
local tests = {
|
||||
-- command, what, code
|
||||
{"ls > /dev/null", "ok"},
|
||||
@@ -773,11 +790,24 @@ assert(os.date(string.rep("%d", 1000), t) ==
|
||||
string.rep(os.date("%d", t), 1000))
|
||||
assert(os.date(string.rep("%", 200)) == string.rep("%", 100))
|
||||
|
||||
local t = os.time()
|
||||
D = os.date("*t", t)
|
||||
load(os.date([[assert(D.year==%Y and D.month==%m and D.day==%d and
|
||||
D.hour==%H and D.min==%M and D.sec==%S and
|
||||
D.wday==%w+1 and D.yday==%j)]], t))()
|
||||
local function checkDateTable (t)
|
||||
_G.D = os.date("*t", t)
|
||||
assert(os.time(D) == t)
|
||||
load(os.date([[assert(D.year==%Y and D.month==%m and D.day==%d and
|
||||
D.hour==%H and D.min==%M and D.sec==%S and
|
||||
D.wday==%w+1 and D.yday==%j)]], t))()
|
||||
_G.D = nil
|
||||
end
|
||||
|
||||
checkDateTable(os.time())
|
||||
if not _port then
|
||||
-- assume that time_t can represent these values
|
||||
checkDateTable(0)
|
||||
checkDateTable(1)
|
||||
checkDateTable(1000)
|
||||
checkDateTable(0x7fffffff)
|
||||
checkDateTable(0x80000000)
|
||||
end
|
||||
|
||||
checkerr("invalid conversion specifier", os.date, "%")
|
||||
checkerr("invalid conversion specifier", os.date, "%9")
|
||||
@@ -791,11 +821,24 @@ checkerr("not an integer", os.time, {year=1000, month=1, day=1, hour=1.5})
|
||||
|
||||
checkerr("missing", os.time, {hour = 12}) -- missing date
|
||||
|
||||
|
||||
if string.packsize("i") == 4 then -- 4-byte ints
|
||||
checkerr("field 'year' is out-of-bound", os.time,
|
||||
{year = -(1 << 31) + 1899, month = 1, day = 1})
|
||||
end
|
||||
|
||||
if not _port then
|
||||
-- test Posix-specific modifiers
|
||||
assert(type(os.date("%Ex")) == 'string')
|
||||
assert(type(os.date("%Oy")) == 'string')
|
||||
|
||||
-- test large dates (assume at least 4-byte ints and time_t)
|
||||
local t0 = os.time{year = 1970, month = 1, day = 0}
|
||||
local t1 = os.time{year = 1970, month = 1, day = 0, sec = (1 << 31) - 1}
|
||||
assert(t1 - t0 == (1 << 31) - 1)
|
||||
t0 = os.time{year = 1970, month = 1, day = 1}
|
||||
t1 = os.time{year = 1970, month = 1, day = 1, sec = -(1 << 31)}
|
||||
assert(t1 - t0 == -(1 << 31))
|
||||
|
||||
-- test out-of-range dates (at least for Unix)
|
||||
if maxint >= 2^62 then -- cannot do these tests in Small Lua
|
||||
@@ -810,25 +853,37 @@ if not _port then
|
||||
-- time_t has 8 bytes; an int year cannot represent a huge time
|
||||
print(" 8-byte time_t")
|
||||
checkerr("cannot be represented", os.date, "%Y", 2^60)
|
||||
-- it should have no problems with year 4000
|
||||
assert(tonumber(os.time{year=4000, month=1, day=1}))
|
||||
|
||||
-- this is the maximum year
|
||||
assert(tonumber(os.time
|
||||
{year=(1 << 31) + 1899, month=12, day=31, hour=23, min=59, sec=59}))
|
||||
|
||||
-- this is too much
|
||||
checkerr("represented", os.time,
|
||||
{year=(1 << 31) + 1899, month=12, day=31, hour=23, min=59, sec=60})
|
||||
end
|
||||
|
||||
-- internal 'int' fields cannot hold these values
|
||||
checkerr("field 'day' is out-of-bound", os.time,
|
||||
{year = 0, month = 1, day = 2^32})
|
||||
|
||||
checkerr("field 'month' is out-of-bound", os.time,
|
||||
{year = 0, month = -((1 << 31) + 1), day = 1})
|
||||
|
||||
checkerr("field 'year' is out-of-bound", os.time,
|
||||
{year = (1 << 31) + 1900, month = 1, day = 1})
|
||||
|
||||
else -- 8-byte ints
|
||||
-- assume time_t has 8 bytes too
|
||||
print(" 8-byte time_t")
|
||||
assert(tonumber(os.date("%Y", 2^60)))
|
||||
|
||||
-- but still cannot represent a huge year
|
||||
checkerr("cannot be represented", os.time, {year=2^60, month=1, day=1})
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
D = os.date("!*t", t)
|
||||
load(os.date([[!assert(D.year==%Y and D.month==%m and D.day==%d and
|
||||
D.hour==%H and D.min==%M and D.sec==%S and
|
||||
D.wday==%w+1 and D.yday==%j)]], t))()
|
||||
|
||||
do
|
||||
local D = os.date("*t")
|
||||
local t = os.time(D)
|
||||
@@ -842,6 +897,7 @@ do
|
||||
assert(t == t1) -- if isdst is absent uses correct default
|
||||
end
|
||||
|
||||
local D = os.date("*t")
|
||||
t = os.time(D)
|
||||
D.year = D.year-1;
|
||||
local t1 = os.time(D)
|
||||
|
||||
+28
-20
@@ -99,35 +99,28 @@ local function GC() GC1(); GC2() end
|
||||
do
|
||||
print("creating many objects")
|
||||
|
||||
local contCreate = 0
|
||||
|
||||
local limit = 5000
|
||||
|
||||
while contCreate <= limit do
|
||||
for i = 1, limit do
|
||||
local a = {}; a = nil
|
||||
contCreate = contCreate+1
|
||||
end
|
||||
|
||||
local a = "a"
|
||||
|
||||
contCreate = 0
|
||||
while contCreate <= limit do
|
||||
a = contCreate .. "b";
|
||||
for i = 1, limit do
|
||||
a = i .. "b";
|
||||
a = string.gsub(a, '(%d%d*)', "%1 %1")
|
||||
a = "a"
|
||||
contCreate = contCreate+1
|
||||
end
|
||||
|
||||
|
||||
contCreate = 0
|
||||
|
||||
a = {}
|
||||
|
||||
function a:test ()
|
||||
while contCreate <= limit do
|
||||
load(string.format("function temp(a) return 'a%d' end", contCreate), "")()
|
||||
assert(temp() == string.format('a%d', contCreate))
|
||||
contCreate = contCreate+1
|
||||
for i = 1, limit do
|
||||
load(string.format("function temp(a) return 'a%d' end", i), "")()
|
||||
assert(temp() == string.format('a%d', i))
|
||||
end
|
||||
end
|
||||
|
||||
@@ -166,9 +159,8 @@ print('long strings')
|
||||
x = "01234567890123456789012345678901234567890123456789012345678901234567890123456789"
|
||||
assert(string.len(x)==80)
|
||||
s = ''
|
||||
n = 0
|
||||
k = math.min(300, (math.maxinteger // 80) // 2)
|
||||
while n < k do s = s..x; n=n+1; j=tostring(n) end
|
||||
for n = 1, k do s = s..x; j=tostring(n) end
|
||||
assert(string.len(s) == k*80)
|
||||
s = string.sub(s, 1, 10000)
|
||||
s, i = string.gsub(s, '(%d%d%d%d)', '')
|
||||
@@ -377,9 +369,10 @@ if T then
|
||||
s[n] = i
|
||||
end
|
||||
|
||||
warn("@on"); warn("@store")
|
||||
collectgarbage()
|
||||
assert(string.find(_WARN, "error in __gc metamethod"))
|
||||
assert(string.match(_WARN, "@(.-)@") == "expected")
|
||||
assert(string.find(_WARN, "error in __gc"))
|
||||
assert(string.match(_WARN, "@(.-)@") == "expected"); _WARN = false
|
||||
for i = 8, 10 do assert(s[i]) end
|
||||
|
||||
for i = 1, 5 do
|
||||
@@ -391,6 +384,7 @@ if T then
|
||||
for i = 1, 10 do assert(s[i]) end
|
||||
|
||||
getmetatable(u).__gc = nil
|
||||
warn("@normal")
|
||||
|
||||
end
|
||||
print '+'
|
||||
@@ -483,9 +477,12 @@ end
|
||||
|
||||
-- errors during collection
|
||||
if T then
|
||||
warn("@store")
|
||||
u = setmetatable({}, {__gc = function () error "@expected error" end})
|
||||
u = nil
|
||||
collectgarbage()
|
||||
assert(string.find(_WARN, "@expected error")); _WARN = false
|
||||
warn("@normal")
|
||||
end
|
||||
|
||||
|
||||
@@ -643,7 +640,7 @@ do
|
||||
assert(getmetatable(o) == tt)
|
||||
-- create new objects during GC
|
||||
local a = 'xuxu'..(10+3)..'joao', {}
|
||||
___Glob = o -- ressurect object!
|
||||
___Glob = o -- ressurrect object!
|
||||
setmetatable({}, tt) -- creates a new one with same metatable
|
||||
print(">>> closing state " .. "<<<\n")
|
||||
end
|
||||
@@ -653,20 +650,21 @@ end
|
||||
|
||||
-- create several objects to raise errors when collected while closing state
|
||||
if T then
|
||||
local error, assert, find = error, assert, string.find
|
||||
local error, assert, find, warn = error, assert, string.find, warn
|
||||
local n = 0
|
||||
local lastmsg
|
||||
local mt = {__gc = function (o)
|
||||
n = n + 1
|
||||
assert(n == o[1])
|
||||
if n == 1 then
|
||||
_WARN = nil
|
||||
_WARN = false
|
||||
elseif n == 2 then
|
||||
assert(find(_WARN, "@expected warning"))
|
||||
lastmsg = _WARN -- get message from previous error (first 'o')
|
||||
else
|
||||
assert(lastmsg == _WARN) -- subsequent error messages are equal
|
||||
end
|
||||
warn("@store"); _WARN = false
|
||||
error"@expected warning"
|
||||
end}
|
||||
for i = 10, 1, -1 do
|
||||
@@ -678,6 +676,16 @@ end
|
||||
-- just to make sure
|
||||
assert(collectgarbage'isrunning')
|
||||
|
||||
do -- check that the collector is not reentrant in incremental mode
|
||||
local res = true
|
||||
setmetatable({}, {__gc = function ()
|
||||
res = collectgarbage()
|
||||
end})
|
||||
collectgarbage()
|
||||
assert(not res)
|
||||
end
|
||||
|
||||
|
||||
collectgarbage(oldmode)
|
||||
|
||||
print('OK')
|
||||
|
||||
@@ -37,6 +37,92 @@ do
|
||||
end
|
||||
|
||||
|
||||
do
|
||||
-- ensure that 'firstold1' is corrected when object is removed from
|
||||
-- the 'allgc' list
|
||||
local function foo () end
|
||||
local old = {10}
|
||||
collectgarbage() -- make 'old' old
|
||||
assert(not T or T.gcage(old) == "old")
|
||||
setmetatable(old, {}) -- new table becomes OLD0 (barrier)
|
||||
assert(not T or T.gcage(getmetatable(old)) == "old0")
|
||||
collectgarbage("step", 0) -- new table becomes OLD1 and firstold1
|
||||
assert(not T or T.gcage(getmetatable(old)) == "old1")
|
||||
setmetatable(getmetatable(old), {__gc = foo}) -- get it out of allgc list
|
||||
collectgarbage("step", 0) -- should not seg. fault
|
||||
end
|
||||
|
||||
|
||||
do -- bug in 5.4.0
|
||||
-- When an object aged OLD1 is finalized, it is moved from the list
|
||||
-- 'finobj' to the *beginning* of the list 'allgc', but that part of the
|
||||
-- list was not being visited by 'markold'.
|
||||
local A = {}
|
||||
A[1] = false -- old anchor for object
|
||||
|
||||
-- obj finalizer
|
||||
local function gcf (obj)
|
||||
A[1] = obj -- anchor object
|
||||
assert(not T or T.gcage(obj) == "old1")
|
||||
obj = nil -- remove it from the stack
|
||||
collectgarbage("step", 0) -- do a young collection
|
||||
print(getmetatable(A[1]).x) -- metatable was collected
|
||||
end
|
||||
|
||||
collectgarbage() -- make A old
|
||||
local obj = {} -- create a new object
|
||||
collectgarbage("step", 0) -- make it a survival
|
||||
assert(not T or T.gcage(obj) == "survival")
|
||||
setmetatable(obj, {__gc = gcf, x = "+"}) -- create its metatable
|
||||
assert(not T or T.gcage(getmetatable(obj)) == "new")
|
||||
obj = nil -- clear object
|
||||
collectgarbage("step", 0) -- will call obj's finalizer
|
||||
end
|
||||
|
||||
|
||||
do -- another bug in 5.4.0
|
||||
local old = {10}
|
||||
collectgarbage() -- make 'old' old
|
||||
local co = coroutine.create(
|
||||
function ()
|
||||
local x = nil
|
||||
local f = function ()
|
||||
return x[1]
|
||||
end
|
||||
x = coroutine.yield(f)
|
||||
coroutine.yield()
|
||||
end
|
||||
)
|
||||
local _, f = coroutine.resume(co) -- create closure over 'x' in coroutine
|
||||
collectgarbage("step", 0) -- make upvalue a survival
|
||||
old[1] = {"hello"} -- 'old' go to grayagain as 'touched1'
|
||||
coroutine.resume(co, {123}) -- its value will be new
|
||||
co = nil
|
||||
collectgarbage("step", 0) -- hit the barrier
|
||||
assert(f() == 123 and old[1][1] == "hello")
|
||||
collectgarbage("step", 0) -- run the collector once more
|
||||
-- make sure old[1] was not collected
|
||||
assert(f() == 123 and old[1][1] == "hello")
|
||||
end
|
||||
|
||||
|
||||
do -- bug introduced in commit 9cf3299fa
|
||||
local t = setmetatable({}, {__mode = "kv"}) -- all-weak table
|
||||
collectgarbage() -- full collection
|
||||
assert(not T or T.gcage(t) == "old")
|
||||
t[1] = {10}
|
||||
assert(not T or (T.gcage(t) == "touched1" and T.gccolor(t) == "gray"))
|
||||
collectgarbage("step", 0) -- minor collection
|
||||
assert(not T or (T.gcage(t) == "touched2" and T.gccolor(t) == "black"))
|
||||
collectgarbage("step", 0) -- minor collection
|
||||
assert(not T or T.gcage(t) == "old") -- t should be black, but it was gray
|
||||
t[1] = {10} -- no barrier here, so t was still old
|
||||
collectgarbage("step", 0) -- minor collection
|
||||
-- t, being old, is ignored by the collection, so it is not cleared
|
||||
assert(t[1] == nil) -- fails with the bug
|
||||
end
|
||||
|
||||
|
||||
if T == nil then
|
||||
(Message or print)('\n >>> testC not active: \z
|
||||
skipping some generational tests <<<\n')
|
||||
@@ -72,6 +158,9 @@ do
|
||||
assert(debug.getuservalue(U).x[1] == 234)
|
||||
end
|
||||
|
||||
-- just to make sure
|
||||
assert(collectgarbage'isrunning')
|
||||
|
||||
|
||||
|
||||
-- just to make sure
|
||||
|
||||
+1
-1
@@ -258,7 +258,7 @@ do
|
||||
::L2:: goto L3
|
||||
|
||||
::L1:: do
|
||||
local <toclose> a = setmetatable({}, {__close = function () X = true end})
|
||||
local a <close> = setmetatable({}, {__close = function () X = true end})
|
||||
assert(X == nil)
|
||||
if a then goto L2 end -- jumping back out of scope of 'a'
|
||||
end
|
||||
|
||||
@@ -11,17 +11,17 @@ CFLAGS = -Wall -std=gnu99 -O2 -I$(LUA_DIR) -fPIC -shared
|
||||
all: lib1.so lib11.so lib2.so lib21.so lib2-v2.so
|
||||
touch all
|
||||
|
||||
lib1.so: lib1.c $(LUA_DIR)/luaconf.h $(LUA_DIR)/ltests.h
|
||||
lib1.so: lib1.c $(LUA_DIR)/luaconf.h
|
||||
$(CC) $(CFLAGS) -o lib1.so lib1.c
|
||||
|
||||
lib11.so: lib11.c $(LUA_DIR)/luaconf.h $(LUA_DIR)/ltests.h
|
||||
lib11.so: lib11.c $(LUA_DIR)/luaconf.h
|
||||
$(CC) $(CFLAGS) -o lib11.so lib11.c
|
||||
|
||||
lib2.so: lib2.c $(LUA_DIR)/luaconf.h $(LUA_DIR)/ltests.h
|
||||
lib2.so: lib2.c $(LUA_DIR)/luaconf.h
|
||||
$(CC) $(CFLAGS) -o lib2.so lib2.c
|
||||
|
||||
lib21.so: lib21.c $(LUA_DIR)/luaconf.h $(LUA_DIR)/ltests.h
|
||||
lib21.so: lib21.c $(LUA_DIR)/luaconf.h
|
||||
$(CC) $(CFLAGS) -o lib21.so lib21.c
|
||||
|
||||
lib2-v2.so: lib21.c $(LUA_DIR)/luaconf.h $(LUA_DIR)/ltests.h
|
||||
lib2-v2.so: lib21.c $(LUA_DIR)/luaconf.h
|
||||
$(CC) $(CFLAGS) -o lib2-v2.so lib22.c
|
||||
|
||||
+25
-1
@@ -208,6 +208,30 @@ a = nil
|
||||
b = nil
|
||||
|
||||
|
||||
do -- reuse of long strings
|
||||
|
||||
-- get the address of a string
|
||||
local function getadd (s) return string.format("%p", s) end
|
||||
|
||||
local s1 <const> = "01234567890123456789012345678901234567890123456789"
|
||||
local s2 <const> = "01234567890123456789012345678901234567890123456789"
|
||||
local s3 = "01234567890123456789012345678901234567890123456789"
|
||||
local function foo() return s1 end
|
||||
local function foo1() return s3 end
|
||||
local function foo2()
|
||||
return "01234567890123456789012345678901234567890123456789"
|
||||
end
|
||||
local a1 = getadd(s1)
|
||||
assert(a1 == getadd(s2))
|
||||
assert(a1 == getadd(foo()))
|
||||
assert(a1 == getadd(foo1()))
|
||||
assert(a1 == getadd(foo2()))
|
||||
|
||||
local sd = "0123456789" .. "0123456789012345678901234567890123456789"
|
||||
assert(sd == s1 and getadd(sd) ~= a1)
|
||||
end
|
||||
|
||||
|
||||
-- testing line ends
|
||||
prog = [[
|
||||
a = 1 -- a comment
|
||||
@@ -281,7 +305,7 @@ if os.setlocale("pt_BR") or os.setlocale("ptb") then
|
||||
|
||||
assert(" 0x.1 " + " 0x,1" + "-0X.1\t" == 0x0.1)
|
||||
|
||||
assert(tonumber"inf" == nil and tonumber"NAN" == nil)
|
||||
assert(not tonumber"inf" and not tonumber"NAN")
|
||||
|
||||
assert(assert(load(string.format("return %q", 4.51)))() == 4.51)
|
||||
|
||||
|
||||
+694
-105
File diff suppressed because it is too large
Load Diff
+114
-8
@@ -43,6 +43,8 @@ local function getoutput ()
|
||||
end
|
||||
|
||||
local function checkprogout (s)
|
||||
-- expected result must end with new line
|
||||
assert(string.sub(s, -1) == "\n")
|
||||
local t = getoutput()
|
||||
for line in string.gmatch(s, ".-\n") do
|
||||
assert(string.find(t, line, 1, true))
|
||||
@@ -188,6 +190,11 @@ prepfile(("print(a); print(_G['%s'].x)"):format(prog), otherprog)
|
||||
RUN('env LUA_PATH="?;;" lua -l %s -l%s -lstring -l io %s > %s', prog, otherprog, otherprog, out)
|
||||
checkout("1\n2\n15\n2\n15\n")
|
||||
|
||||
-- test explicit global names in -l
|
||||
prepfile("print(str.upper'alo alo', m.max(10, 20))")
|
||||
RUN("lua -l 'str=string' '-lm=math' -e 'print(m.sin(0))' %s > %s", prog, out)
|
||||
checkout("0.0\nALO ALO\t20\n")
|
||||
|
||||
-- test 'arg' table
|
||||
local a = [[
|
||||
assert(#arg == 3 and arg[1] == 'a' and
|
||||
@@ -219,6 +226,70 @@ assert(string.find(getoutput(), "error calling 'print'"))
|
||||
RUN('echo "io.stderr:write(1000)\ncont" | lua -e "require\'debug\'.debug()" 2> %s', out)
|
||||
checkout("lua_debug> 1000lua_debug> ")
|
||||
|
||||
|
||||
print("testing warnings")
|
||||
|
||||
-- no warnings by default
|
||||
RUN('echo "io.stderr:write(1); warn[[XXX]]" | lua 2> %s', out)
|
||||
checkout("1")
|
||||
|
||||
prepfile[[
|
||||
warn("@allow") -- unknown control, ignored
|
||||
warn("@off", "XXX", "@off") -- these are not control messages
|
||||
warn("@off") -- this one is
|
||||
warn("@on", "YYY", "@on") -- not control, but warn is off
|
||||
warn("@off") -- keep it off
|
||||
warn("@on") -- restart warnings
|
||||
warn("", "@on") -- again, no control, real warning
|
||||
warn("@on") -- keep it "started"
|
||||
warn("Z", "Z", "Z") -- common warning
|
||||
]]
|
||||
RUN('lua -W %s 2> %s', prog, out)
|
||||
checkout[[
|
||||
Lua warning: @offXXX@off
|
||||
Lua warning: @on
|
||||
Lua warning: ZZZ
|
||||
]]
|
||||
|
||||
prepfile[[
|
||||
warn("@allow")
|
||||
-- create two objects to be finalized when closing state
|
||||
-- the errors in the finalizers must generate warnings
|
||||
u1 = setmetatable({}, {__gc = function () error("XYZ") end})
|
||||
u2 = setmetatable({}, {__gc = function () error("ZYX") end})
|
||||
]]
|
||||
RUN('lua -W %s 2> %s', prog, out)
|
||||
checkprogout("ZYX)\nXYZ)\n")
|
||||
|
||||
-- bug since 5.2: finalizer called when closing a state could
|
||||
-- subvert finalization order
|
||||
prepfile[[
|
||||
-- should be called last
|
||||
print("creating 1")
|
||||
setmetatable({}, {__gc = function () print(1) end})
|
||||
|
||||
print("creating 2")
|
||||
setmetatable({}, {__gc = function ()
|
||||
print("2")
|
||||
print("creating 3")
|
||||
-- this finalizer should not be called, as object will be
|
||||
-- created after 'lua_close' has been called
|
||||
setmetatable({}, {__gc = function () print(3) end})
|
||||
print(collectgarbage()) -- cannot call collector here
|
||||
os.exit(0, true)
|
||||
end})
|
||||
]]
|
||||
RUN('lua -W %s > %s', prog, out)
|
||||
checkout[[
|
||||
creating 1
|
||||
creating 2
|
||||
2
|
||||
creating 3
|
||||
nil
|
||||
1
|
||||
]]
|
||||
|
||||
|
||||
-- test many arguments
|
||||
prepfile[[print(({...})[30])]]
|
||||
RUN('lua %s %s > %s', prog, string.rep(" a", 30), out)
|
||||
@@ -249,6 +320,33 @@ RUN([[lua "-e_PROMPT='%s'" -i < %s > %s]], prompt, prog, out)
|
||||
local t = getoutput()
|
||||
assert(string.find(t, prompt .. ".*" .. prompt .. ".*" .. prompt))
|
||||
|
||||
-- using the prompt default
|
||||
prepfile[[ --
|
||||
a = 2
|
||||
]]
|
||||
RUN([[lua -i < %s > %s]], prog, out)
|
||||
local t = getoutput()
|
||||
prompt = "> " -- the default
|
||||
assert(string.find(t, prompt .. ".*" .. prompt .. ".*" .. prompt))
|
||||
|
||||
|
||||
-- non-string prompt
|
||||
prompt =
|
||||
"local C = 0;\z
|
||||
_PROMPT=setmetatable({},{__tostring = function () \z
|
||||
C = C + 1; return C end})"
|
||||
prepfile[[ --
|
||||
a = 2
|
||||
]]
|
||||
RUN([[lua -e "%s" -i < %s > %s]], prompt, prog, out)
|
||||
local t = getoutput()
|
||||
assert(string.find(t, [[
|
||||
1 --
|
||||
2a = 2
|
||||
3
|
||||
]], 1, true))
|
||||
|
||||
|
||||
-- test for error objects
|
||||
prepfile[[
|
||||
debug = require "debug"
|
||||
@@ -292,7 +390,7 @@ debug = require"debug"
|
||||
print(debug.getinfo(1).currentline)
|
||||
]]
|
||||
RUN('lua %s > %s', prog, out)
|
||||
checkprogout('3')
|
||||
checkprogout('3\n')
|
||||
|
||||
-- close Lua with an open file
|
||||
prepfile(string.format([[io.output(%q); io.write('alo')]], out))
|
||||
@@ -320,15 +418,16 @@ NoRun("", "lua %s", prog) -- no message
|
||||
|
||||
-- to-be-closed variables in main chunk
|
||||
prepfile[[
|
||||
local <toclose> x = function (err)
|
||||
assert(err == 120)
|
||||
print("Ok")
|
||||
end
|
||||
local <toclose> e1 = function () error(120) end
|
||||
local x <close> = setmetatable({},
|
||||
{__close = function (self, err)
|
||||
assert(err == nil)
|
||||
print("Ok")
|
||||
end})
|
||||
local e1 <close> = setmetatable({}, {__close = function () print(120) end})
|
||||
os.exit(true, true)
|
||||
]]
|
||||
RUN('lua %s > %s', prog, out)
|
||||
checkprogout("Ok")
|
||||
checkprogout("120\nOk\n")
|
||||
|
||||
|
||||
-- remove temporary files
|
||||
@@ -352,8 +451,15 @@ if T then -- test library?
|
||||
NoRun("not enough memory", "env MEMLIMIT=100 lua")
|
||||
|
||||
-- testing 'warn'
|
||||
warn("@store")
|
||||
warn("@123", "456", "789")
|
||||
assert(_WARN == "@123456789")
|
||||
assert(_WARN == "@123456789"); _WARN = false
|
||||
|
||||
warn("zip", "", " ", "zap")
|
||||
assert(_WARN == "zip zap"); _WARN = false
|
||||
warn("ZIP", "", " ", "ZAP")
|
||||
assert(_WARN == "ZIP ZAP"); _WARN = false
|
||||
warn("@normal")
|
||||
end
|
||||
|
||||
do
|
||||
|
||||
+79
-63
@@ -3,10 +3,10 @@
|
||||
|
||||
print("testing numbers and math lib")
|
||||
|
||||
local <const> minint = math.mininteger
|
||||
local <const> maxint = math.maxinteger
|
||||
local minint <const> = math.mininteger
|
||||
local maxint <const> = math.maxinteger
|
||||
|
||||
local <const> intbits = math.floor(math.log(maxint, 2) + 0.5) + 1
|
||||
local intbits <const> = math.floor(math.log(maxint, 2) + 0.5) + 1
|
||||
assert((1 << intbits) == 0)
|
||||
|
||||
assert(minint == 1 << (intbits - 1))
|
||||
@@ -39,7 +39,7 @@ do
|
||||
end
|
||||
|
||||
assert(math.type(0) == "integer" and math.type(0.0) == "float"
|
||||
and math.type("10") == nil)
|
||||
and not math.type("10"))
|
||||
|
||||
|
||||
local function checkerror (msg, f, ...)
|
||||
@@ -270,7 +270,7 @@ else
|
||||
end
|
||||
|
||||
do
|
||||
local NaN = 0/0
|
||||
local NaN <const> = 0/0
|
||||
assert(not (NaN < 0))
|
||||
assert(not (NaN > minint))
|
||||
assert(not (NaN <= -9))
|
||||
@@ -381,17 +381,17 @@ assert(tonumber(1/0) == 1/0)
|
||||
|
||||
-- 'tonumber' with strings
|
||||
assert(tonumber("0") == 0)
|
||||
assert(tonumber("") == nil)
|
||||
assert(tonumber(" ") == nil)
|
||||
assert(tonumber("-") == nil)
|
||||
assert(tonumber(" -0x ") == nil)
|
||||
assert(tonumber{} == nil)
|
||||
assert(not tonumber(""))
|
||||
assert(not tonumber(" "))
|
||||
assert(not tonumber("-"))
|
||||
assert(not tonumber(" -0x "))
|
||||
assert(not tonumber{})
|
||||
assert(tonumber'+0.01' == 1/100 and tonumber'+.01' == 0.01 and
|
||||
tonumber'.01' == 0.01 and tonumber'-1.' == -1 and
|
||||
tonumber'+1.' == 1)
|
||||
assert(tonumber'+ 0.01' == nil and tonumber'+.e1' == nil and
|
||||
tonumber'1e' == nil and tonumber'1.0e+' == nil and
|
||||
tonumber'.' == nil)
|
||||
assert(not tonumber'+ 0.01' and not tonumber'+.e1' and
|
||||
not tonumber'1e' and not tonumber'1.0e+' and
|
||||
not tonumber'.')
|
||||
assert(tonumber('-012') == -010-2)
|
||||
assert(tonumber('-1.2e2') == - - -120)
|
||||
|
||||
@@ -445,45 +445,45 @@ local function f (...)
|
||||
end
|
||||
end
|
||||
|
||||
assert(f(tonumber('fFfa', 15)) == nil)
|
||||
assert(f(tonumber('099', 8)) == nil)
|
||||
assert(f(tonumber('1\0', 2)) == nil)
|
||||
assert(f(tonumber('', 8)) == nil)
|
||||
assert(f(tonumber(' ', 9)) == nil)
|
||||
assert(f(tonumber(' ', 9)) == nil)
|
||||
assert(f(tonumber('0xf', 10)) == nil)
|
||||
assert(not f(tonumber('fFfa', 15)))
|
||||
assert(not f(tonumber('099', 8)))
|
||||
assert(not f(tonumber('1\0', 2)))
|
||||
assert(not f(tonumber('', 8)))
|
||||
assert(not f(tonumber(' ', 9)))
|
||||
assert(not f(tonumber(' ', 9)))
|
||||
assert(not f(tonumber('0xf', 10)))
|
||||
|
||||
assert(f(tonumber('inf')) == nil)
|
||||
assert(f(tonumber(' INF ')) == nil)
|
||||
assert(f(tonumber('Nan')) == nil)
|
||||
assert(f(tonumber('nan')) == nil)
|
||||
assert(not f(tonumber('inf')))
|
||||
assert(not f(tonumber(' INF ')))
|
||||
assert(not f(tonumber('Nan')))
|
||||
assert(not f(tonumber('nan')))
|
||||
|
||||
assert(f(tonumber(' ')) == nil)
|
||||
assert(f(tonumber('')) == nil)
|
||||
assert(f(tonumber('1 a')) == nil)
|
||||
assert(f(tonumber('1 a', 2)) == nil)
|
||||
assert(f(tonumber('1\0')) == nil)
|
||||
assert(f(tonumber('1 \0')) == nil)
|
||||
assert(f(tonumber('1\0 ')) == nil)
|
||||
assert(f(tonumber('e1')) == nil)
|
||||
assert(f(tonumber('e 1')) == nil)
|
||||
assert(f(tonumber(' 3.4.5 ')) == nil)
|
||||
assert(not f(tonumber(' ')))
|
||||
assert(not f(tonumber('')))
|
||||
assert(not f(tonumber('1 a')))
|
||||
assert(not f(tonumber('1 a', 2)))
|
||||
assert(not f(tonumber('1\0')))
|
||||
assert(not f(tonumber('1 \0')))
|
||||
assert(not f(tonumber('1\0 ')))
|
||||
assert(not f(tonumber('e1')))
|
||||
assert(not f(tonumber('e 1')))
|
||||
assert(not f(tonumber(' 3.4.5 ')))
|
||||
|
||||
|
||||
-- testing 'tonumber' for invalid hexadecimal formats
|
||||
|
||||
assert(tonumber('0x') == nil)
|
||||
assert(tonumber('x') == nil)
|
||||
assert(tonumber('x3') == nil)
|
||||
assert(tonumber('0x3.3.3') == nil) -- two decimal points
|
||||
assert(tonumber('00x2') == nil)
|
||||
assert(tonumber('0x 2') == nil)
|
||||
assert(tonumber('0 x2') == nil)
|
||||
assert(tonumber('23x') == nil)
|
||||
assert(tonumber('- 0xaa') == nil)
|
||||
assert(tonumber('-0xaaP ') == nil) -- no exponent
|
||||
assert(tonumber('0x0.51p') == nil)
|
||||
assert(tonumber('0x5p+-2') == nil)
|
||||
assert(not tonumber('0x'))
|
||||
assert(not tonumber('x'))
|
||||
assert(not tonumber('x3'))
|
||||
assert(not tonumber('0x3.3.3')) -- two decimal points
|
||||
assert(not tonumber('00x2'))
|
||||
assert(not tonumber('0x 2'))
|
||||
assert(not tonumber('0 x2'))
|
||||
assert(not tonumber('23x'))
|
||||
assert(not tonumber('- 0xaa'))
|
||||
assert(not tonumber('-0xaaP ')) -- no exponent
|
||||
assert(not tonumber('0x0.51p'))
|
||||
assert(not tonumber('0x5p+-2'))
|
||||
|
||||
|
||||
-- testing hexadecimal numerals
|
||||
@@ -705,19 +705,19 @@ do -- testing floor & ceil
|
||||
assert(eqT(math.tointeger(maxint), maxint))
|
||||
assert(eqT(math.tointeger(maxint .. ""), maxint))
|
||||
assert(eqT(math.tointeger(minint + 0.0), minint))
|
||||
assert(math.tointeger(0.0 - minint) == nil)
|
||||
assert(math.tointeger(math.pi) == nil)
|
||||
assert(math.tointeger(-math.pi) == nil)
|
||||
assert(not math.tointeger(0.0 - minint))
|
||||
assert(not math.tointeger(math.pi))
|
||||
assert(not math.tointeger(-math.pi))
|
||||
assert(math.floor(math.huge) == math.huge)
|
||||
assert(math.ceil(math.huge) == math.huge)
|
||||
assert(math.tointeger(math.huge) == nil)
|
||||
assert(not math.tointeger(math.huge))
|
||||
assert(math.floor(-math.huge) == -math.huge)
|
||||
assert(math.ceil(-math.huge) == -math.huge)
|
||||
assert(math.tointeger(-math.huge) == nil)
|
||||
assert(not math.tointeger(-math.huge))
|
||||
assert(math.tointeger("34.0") == 34)
|
||||
assert(math.tointeger("34.3") == nil)
|
||||
assert(math.tointeger({}) == nil)
|
||||
assert(math.tointeger(0/0) == nil) -- NaN
|
||||
assert(not math.tointeger("34.3"))
|
||||
assert(not math.tointeger({}))
|
||||
assert(not math.tointeger(0/0)) -- NaN
|
||||
end
|
||||
|
||||
|
||||
@@ -758,7 +758,7 @@ do -- testing max/min
|
||||
assert(eqT(math.min(maxint, maxint - 1), maxint - 1))
|
||||
assert(eqT(math.min(maxint - 2, maxint, maxint - 1), maxint - 2))
|
||||
end
|
||||
-- testing implicit convertions
|
||||
-- testing implicit conversions
|
||||
|
||||
local a,b = '10', '20'
|
||||
assert(a*b == 200 and a+b == 30 and a-b == -10 and a/b == 0.5 and -b == -20)
|
||||
@@ -767,7 +767,8 @@ assert(a == '10' and b == '20')
|
||||
|
||||
do
|
||||
print("testing -0 and NaN")
|
||||
local mz, z = -0.0, 0.0
|
||||
local mz <const> = -0.0
|
||||
local z <const> = 0.0
|
||||
assert(mz == z)
|
||||
assert(1/mz < 0 and 0 < 1/z)
|
||||
local a = {[mz] = 1}
|
||||
@@ -775,17 +776,18 @@ do
|
||||
a[z] = 2
|
||||
assert(a[z] == 2 and a[mz] == 2)
|
||||
local inf = math.huge * 2 + 1
|
||||
mz, z = -1/inf, 1/inf
|
||||
local mz <const> = -1/inf
|
||||
local z <const> = 1/inf
|
||||
assert(mz == z)
|
||||
assert(1/mz < 0 and 0 < 1/z)
|
||||
local NaN = inf - inf
|
||||
local NaN <const> = inf - inf
|
||||
assert(NaN ~= NaN)
|
||||
assert(not (NaN < NaN))
|
||||
assert(not (NaN <= NaN))
|
||||
assert(not (NaN > NaN))
|
||||
assert(not (NaN >= NaN))
|
||||
assert(not (0 < NaN) and not (NaN < 0))
|
||||
local NaN1 = 0/0
|
||||
local NaN1 <const> = 0/0
|
||||
assert(NaN ~= NaN1 and not (NaN <= NaN1) and not (NaN1 <= NaN))
|
||||
local a = {}
|
||||
assert(not pcall(rawset, a, NaN, 1))
|
||||
@@ -813,9 +815,9 @@ end
|
||||
-- low-level!! For the current implementation of random in Lua,
|
||||
-- the first call after seed 1007 should return 0x7a7040a5a323c9d6
|
||||
do
|
||||
-- all computations assume at most 32-bit integers
|
||||
local h = 0x7a7040a5 -- higher half
|
||||
local l = 0xa323c9d6 -- lower half
|
||||
-- all computations should work with 32-bit integers
|
||||
local h <const> = 0x7a7040a5 -- higher half
|
||||
local l <const> = 0xa323c9d6 -- lower half
|
||||
|
||||
math.randomseed(1007)
|
||||
-- get the low 'intbits' of the 64-bit expected result
|
||||
@@ -838,7 +840,17 @@ do
|
||||
assert(rand * 2^floatbits == res)
|
||||
end
|
||||
|
||||
math.randomseed()
|
||||
do
|
||||
-- testing return of 'randomseed'
|
||||
local x, y = math.randomseed()
|
||||
local res = math.random(0)
|
||||
x, y = math.randomseed(x, y) -- should repeat the state
|
||||
assert(math.random(0) == res)
|
||||
math.randomseed(x, y) -- again should repeat the state
|
||||
assert(math.random(0) == res)
|
||||
-- keep the random seed for following tests
|
||||
print(string.format("random seeds: %d, %d", x, y))
|
||||
end
|
||||
|
||||
do -- test random for floats
|
||||
local randbits = math.min(floatbits, 64) -- at most 64 random bits
|
||||
@@ -949,7 +961,10 @@ do
|
||||
aux(-10,0)
|
||||
aux(1, 6)
|
||||
aux(1, 2)
|
||||
aux(1, 13)
|
||||
aux(1, 31)
|
||||
aux(1, 32)
|
||||
aux(1, 33)
|
||||
aux(-10, 10)
|
||||
aux(-10,-10) -- unit set
|
||||
aux(minint, minint) -- unit set
|
||||
@@ -987,6 +1002,7 @@ do
|
||||
end
|
||||
aux(0, maxint)
|
||||
aux(1, maxint)
|
||||
aux(3, maxint // 3)
|
||||
aux(minint, -1)
|
||||
aux(minint // 2, maxint // 2)
|
||||
aux(minint, maxint)
|
||||
|
||||
+107
-40
@@ -43,39 +43,27 @@ assert(i == 4)
|
||||
assert(type(ipairs{}) == 'function' and ipairs{} == ipairs{})
|
||||
|
||||
|
||||
do -- overflow (must wrap-around)
|
||||
local f = ipairs{}
|
||||
local k, v = f({[math.mininteger] = 10}, math.maxinteger)
|
||||
assert(k == math.mininteger and v == 10)
|
||||
k, v = f({[math.mininteger] = 10}, k)
|
||||
assert(k == nil)
|
||||
end
|
||||
|
||||
if not T then
|
||||
(Message or print)
|
||||
('\n >>> testC not active: skipping tests for table sizes <<<\n')
|
||||
else --[
|
||||
-- testing table sizes
|
||||
|
||||
local function log2 (x) return math.log(x, 2) end
|
||||
|
||||
local function mp2 (n) -- minimum power of 2 >= n
|
||||
local mp = 2^math.ceil(log2(n))
|
||||
local mp = 2^math.ceil(math.log(n, 2))
|
||||
assert(n == 0 or (mp/2 < n and n <= mp))
|
||||
return mp
|
||||
end
|
||||
|
||||
local function fb (n)
|
||||
local r, nn = T.int2fb(n)
|
||||
assert(r < 256)
|
||||
return nn
|
||||
end
|
||||
|
||||
-- test fb function
|
||||
for a = 1, 10000 do -- all numbers up to 10^4
|
||||
local n = fb(a)
|
||||
assert(a <= n and n <= a*1.125)
|
||||
end
|
||||
local a = 1024 -- plus a few up to 2 ^30
|
||||
local lim = 2^30
|
||||
while a < lim do
|
||||
local n = fb(a)
|
||||
assert(a <= n and n <= a*1.125)
|
||||
a = math.ceil(a*1.3)
|
||||
end
|
||||
|
||||
|
||||
local function check (t, na, nh)
|
||||
local a, h = T.querytab(t)
|
||||
@@ -95,30 +83,46 @@ end
|
||||
|
||||
|
||||
-- testing constructor sizes
|
||||
local lim = 40
|
||||
local s = 'return {'
|
||||
for i=1,lim do
|
||||
s = s..i..','
|
||||
local s = s
|
||||
for k=0,lim do
|
||||
local t = load(s..'}', '')()
|
||||
assert(#t == i)
|
||||
check(t, fb(i), mp2(k))
|
||||
s = string.format('%sa%d=%d,', s, k, k)
|
||||
local sizes = {0, 1, 2, 3, 4, 5, 7, 8, 9, 15, 16, 17,
|
||||
30, 31, 32, 33, 34, 254, 255, 256, 500, 1000}
|
||||
|
||||
for _, sa in ipairs(sizes) do -- 'sa' is size of the array part
|
||||
local arr = {"return {"}
|
||||
for i = 1, sa do arr[1 + i] = "1," end -- build array part
|
||||
for _, sh in ipairs(sizes) do -- 'sh' is size of the hash part
|
||||
for j = 1, sh do -- build hash part
|
||||
arr[1 + sa + j] = string.format('k%x=%d,', j, j)
|
||||
end
|
||||
arr[1 + sa + sh + 1] = "}"
|
||||
local prog = table.concat(arr)
|
||||
local f = assert(load(prog))
|
||||
collectgarbage("stop")
|
||||
f() -- call once to ensure stack space
|
||||
-- make sure table is not resized after being created
|
||||
if sa == 0 or sh == 0 then
|
||||
T.alloccount(2); -- header + array or hash part
|
||||
else
|
||||
T.alloccount(3); -- header + array part + hash part
|
||||
end
|
||||
local t = f()
|
||||
T.alloccount();
|
||||
collectgarbage("restart")
|
||||
assert(#t == sa)
|
||||
check(t, sa, mp2(sh))
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
-- tests with unknown number of elements
|
||||
local a = {}
|
||||
for i=1,lim do a[i] = i end -- build auxiliary table
|
||||
for k=0,lim do
|
||||
local a = {table.unpack(a,1,k)}
|
||||
assert(#a == k)
|
||||
check(a, k, 0)
|
||||
a = {1,2,3,table.unpack(a,1,k)}
|
||||
check(a, k+3, 0)
|
||||
assert(#a == k + 3)
|
||||
for i=1,sizes[#sizes] do a[i] = i end -- build auxiliary table
|
||||
for k in ipairs(sizes) do
|
||||
local t = {table.unpack(a,1,k)}
|
||||
assert(#t == k)
|
||||
check(t, k, 0)
|
||||
t = {1,2,3,table.unpack(a,1,k)}
|
||||
check(t, k+3, 0)
|
||||
assert(#t == k + 3)
|
||||
end
|
||||
|
||||
|
||||
@@ -363,6 +367,38 @@ end
|
||||
assert(n == 5)
|
||||
|
||||
|
||||
do
|
||||
print("testing next x GC of deleted keys")
|
||||
-- bug in 5.4.1
|
||||
local co = coroutine.wrap(function (t)
|
||||
for k, v in pairs(t) do
|
||||
local k1 = next(t) -- all previous keys were deleted
|
||||
assert(k == k1) -- current key is the first in the table
|
||||
t[k] = nil
|
||||
local expected = (type(k) == "table" and k[1] or
|
||||
type(k) == "function" and k() or
|
||||
string.sub(k, 1, 1))
|
||||
assert(expected == v)
|
||||
coroutine.yield(v)
|
||||
end
|
||||
end)
|
||||
local t = {}
|
||||
t[{1}] = 1 -- add several unanchored, collectable keys
|
||||
t[{2}] = 2
|
||||
t[string.rep("a", 50)] = "a" -- long string
|
||||
t[string.rep("b", 50)] = "b"
|
||||
t[{3}] = 3
|
||||
t[string.rep("c", 10)] = "c" -- short string
|
||||
t[function () return 10 end] = 10
|
||||
local count = 7
|
||||
while co(t) do
|
||||
collectgarbage("collect") -- collect dead keys
|
||||
count = count - 1
|
||||
end
|
||||
assert(count == 0 and next(t) == nil) -- traversed the whole table
|
||||
end
|
||||
|
||||
|
||||
local function test (a)
|
||||
assert(not pcall(table.insert, a, 2, 20));
|
||||
table.insert(a, 10); table.insert(a, 2, 20);
|
||||
@@ -471,6 +507,15 @@ do -- testing table library with metamethods
|
||||
end
|
||||
|
||||
|
||||
do -- testing overflow in table.insert (must wrap-around)
|
||||
|
||||
local t = setmetatable({},
|
||||
{__len = function () return math.maxinteger end})
|
||||
table.insert(t, 20)
|
||||
local k, v = next(t)
|
||||
assert(k == math.mininteger and v == 20)
|
||||
end
|
||||
|
||||
if not T then
|
||||
(Message or print)
|
||||
('\n >>> testC not active: skipping tests for table library on non-tables <<<\n')
|
||||
@@ -677,7 +722,8 @@ collectgarbage()
|
||||
|
||||
local function f (n, p)
|
||||
local t = {}; for i=1,p do t[i] = i*10 end
|
||||
return function (_,n)
|
||||
return function (_, n, ...)
|
||||
assert(select("#", ...) == 0) -- no extra arguments
|
||||
if n > 0 then
|
||||
n = n-1
|
||||
return n, table.unpack(t)
|
||||
@@ -735,4 +781,25 @@ for k,v in ipairs(a) do
|
||||
end
|
||||
assert(i == a.n)
|
||||
|
||||
|
||||
-- testing yield inside __pairs
|
||||
do
|
||||
local t = setmetatable({10, 20, 30}, {__pairs = function (t)
|
||||
local inc = coroutine.yield()
|
||||
return function (t, i)
|
||||
if i > 1 then return i - inc, t[i - inc] else return nil end
|
||||
end, t, #t + 1
|
||||
end})
|
||||
|
||||
local res = {}
|
||||
local co = coroutine.wrap(function ()
|
||||
for i,p in pairs(t) do res[#res + 1] = p end
|
||||
end)
|
||||
|
||||
co() -- start coroutine
|
||||
co(1) -- continue after yield
|
||||
assert(res[1] == 30 and res[2] == 20 and res[3] == 10 and #res == 3)
|
||||
|
||||
end
|
||||
|
||||
print"OK"
|
||||
|
||||
Executable
+55
@@ -0,0 +1,55 @@
|
||||
NAME=$1"-tests"
|
||||
|
||||
ln -s . $NAME
|
||||
ln -s .. ltests
|
||||
|
||||
tar --create --gzip --no-recursion --file=$NAME.tar.gz \
|
||||
$NAME/all.lua \
|
||||
$NAME/api.lua \
|
||||
$NAME/attrib.lua \
|
||||
$NAME/big.lua \
|
||||
$NAME/bitwise.lua \
|
||||
$NAME/bwcoercion.lua \
|
||||
$NAME/calls.lua \
|
||||
$NAME/closure.lua \
|
||||
$NAME/code.lua \
|
||||
$NAME/constructs.lua \
|
||||
$NAME/coroutine.lua \
|
||||
$NAME/cstack.lua \
|
||||
$NAME/db.lua \
|
||||
$NAME/errors.lua \
|
||||
$NAME/events.lua \
|
||||
$NAME/files.lua \
|
||||
$NAME/gc.lua \
|
||||
$NAME/gengc.lua \
|
||||
$NAME/goto.lua \
|
||||
$NAME/heavy.lua \
|
||||
$NAME/literals.lua \
|
||||
$NAME/locals.lua \
|
||||
$NAME/main.lua \
|
||||
$NAME/math.lua \
|
||||
$NAME/nextvar.lua \
|
||||
$NAME/pm.lua \
|
||||
$NAME/sort.lua \
|
||||
$NAME/strings.lua \
|
||||
$NAME/tpack.lua \
|
||||
$NAME/tracegc.lua \
|
||||
$NAME/utf8.lua \
|
||||
$NAME/vararg.lua \
|
||||
$NAME/verybig.lua \
|
||||
$NAME/libs/makefile \
|
||||
$NAME/libs/P1 \
|
||||
$NAME/libs/lib1.c \
|
||||
$NAME/libs/lib11.c \
|
||||
$NAME/libs/lib2.c \
|
||||
$NAME/libs/lib21.c \
|
||||
$NAME/libs/lib22.c \
|
||||
$NAME/ltests/ltests.h \
|
||||
$NAME/ltests/ltests.c
|
||||
|
||||
\rm -I $NAME
|
||||
\rm -I ltests
|
||||
|
||||
echo ${NAME}.tar.gz" created"
|
||||
|
||||
|
||||
+11
-11
@@ -28,10 +28,10 @@ a,b = string.find('a\0a\0a\0a\0\0ab', '\0ab', 2); -- finds at the end
|
||||
assert(a == 9 and b == 11);
|
||||
a,b = string.find('a\0a\0a\0a\0\0ab', 'b') -- last position
|
||||
assert(a == 11 and b == 11)
|
||||
assert(string.find('a\0a\0a\0a\0\0ab', 'b\0') == nil) -- check ending
|
||||
assert(string.find('', '\0') == nil)
|
||||
assert(not string.find('a\0a\0a\0a\0\0ab', 'b\0')) -- check ending
|
||||
assert(not string.find('', '\0'))
|
||||
assert(string.find('alo123alo', '12') == 4)
|
||||
assert(string.find('alo123alo', '^12') == nil)
|
||||
assert(not string.find('alo123alo', '^12'))
|
||||
|
||||
assert(string.match("aaab", ".*b") == "aaab")
|
||||
assert(string.match("aaa", ".*a") == "aaa")
|
||||
@@ -57,17 +57,17 @@ assert(f('aaa', 'ab*a') == 'aa')
|
||||
assert(f('aba', 'ab*a') == 'aba')
|
||||
assert(f('aaab', 'a+') == 'aaa')
|
||||
assert(f('aaa', '^.+$') == 'aaa')
|
||||
assert(f('aaa', 'b+') == nil)
|
||||
assert(f('aaa', 'ab+a') == nil)
|
||||
assert(not f('aaa', 'b+'))
|
||||
assert(not f('aaa', 'ab+a'))
|
||||
assert(f('aba', 'ab+a') == 'aba')
|
||||
assert(f('a$a', '.$') == 'a')
|
||||
assert(f('a$a', '.%$') == 'a$')
|
||||
assert(f('a$a', '.$.') == 'a$a')
|
||||
assert(f('a$a', '$$') == nil)
|
||||
assert(f('a$b', 'a$') == nil)
|
||||
assert(not f('a$a', '$$'))
|
||||
assert(not f('a$b', 'a$'))
|
||||
assert(f('a$a', '$') == '')
|
||||
assert(f('', 'b*') == '')
|
||||
assert(f('aaa', 'bb*') == nil)
|
||||
assert(not f('aaa', 'bb*'))
|
||||
assert(f('aaab', 'a-') == '')
|
||||
assert(f('aaa', '^.-$') == 'aaa')
|
||||
assert(f('aabaaabaaabaaaba', 'b.*b') == 'baaabaaabaaab')
|
||||
@@ -101,7 +101,7 @@ end
|
||||
assert(f1('alo alx 123 b\0o b\0o', '(..*) %1') == "b\0o b\0o")
|
||||
assert(f1('axz123= 4= 4 34', '(.+)=(.*)=%2 %1') == '3= 4= 4 3')
|
||||
assert(f1('=======', '^(=*)=%1$') == '=======')
|
||||
assert(string.match('==========', '^([=]*)=%1$') == nil)
|
||||
assert(not string.match('==========', '^([=]*)=%1$'))
|
||||
|
||||
local function range (i, j)
|
||||
if i <= j then
|
||||
@@ -135,7 +135,7 @@ print('+');
|
||||
assert(string.match("alo xyzK", "(%w+)K") == "xyz")
|
||||
assert(string.match("254 K", "(%d*)K") == "")
|
||||
assert(string.match("alo ", "(%w*)$") == "")
|
||||
assert(string.match("alo ", "(%w+)$") == nil)
|
||||
assert(not string.match("alo ", "(%w+)$"))
|
||||
assert(string.find("(álo)", "%(á") == 1)
|
||||
local a, b, c, d, e = string.match("âlo alo", "^(((.).).* (%w*))$")
|
||||
assert(a == 'âlo alo' and b == 'âl' and c == 'â' and d == 'alo' and e == nil)
|
||||
@@ -209,7 +209,7 @@ assert(s == r and t[1] == 1 and t[3] == 3 and t[7] == 4 and t[13] == 4)
|
||||
|
||||
|
||||
function isbalanced (s)
|
||||
return string.find(string.gsub(s, "%b()", ""), "[()]") == nil
|
||||
return not string.find(string.gsub(s, "%b()", ""), "[()]")
|
||||
end
|
||||
|
||||
assert(isbalanced("(9 ((8))(\0) 7) \0\0 a b ()(c)() a"))
|
||||
|
||||
+73
-23
@@ -3,8 +3,8 @@
|
||||
|
||||
print('testing strings and string library')
|
||||
|
||||
local <const> maxi = math.maxinteger
|
||||
local <const> mini = math.mininteger
|
||||
local maxi <const> = math.maxinteger
|
||||
local mini <const> = math.mininteger
|
||||
|
||||
|
||||
local function checkerror (msg, f, ...)
|
||||
@@ -56,13 +56,13 @@ a,b = string.find("123456789", "345")
|
||||
assert(string.sub("123456789", a, b) == "345")
|
||||
assert(string.find("1234567890123456789", "345", 3) == 3)
|
||||
assert(string.find("1234567890123456789", "345", 4) == 13)
|
||||
assert(string.find("1234567890123456789", "346", 4) == nil)
|
||||
assert(not string.find("1234567890123456789", "346", 4))
|
||||
assert(string.find("1234567890123456789", ".45", -9) == 13)
|
||||
assert(string.find("abcdefg", "\0", 5, 1) == nil)
|
||||
assert(not string.find("abcdefg", "\0", 5, 1))
|
||||
assert(string.find("", "") == 1)
|
||||
assert(string.find("", "", 1) == 1)
|
||||
assert(not string.find("", "", 2))
|
||||
assert(string.find('', 'aaa', 1) == nil)
|
||||
assert(not string.find('', 'aaa', 1))
|
||||
assert(('alo(.)alo'):find('(.)', 1, 1) == 4)
|
||||
|
||||
assert(string.len("") == 0)
|
||||
@@ -158,17 +158,38 @@ do -- tests for '%p' format
|
||||
-- not much to test, as C does not specify what '%p' does.
|
||||
-- ("The value of the pointer is converted to a sequence of printing
|
||||
-- characters, in an implementation-defined manner.")
|
||||
local null = string.format("%p", nil)
|
||||
assert(string.format("%p", {}) ~= null)
|
||||
local null = "(null)" -- nulls are formatted by Lua
|
||||
assert(string.format("%p", 4) == null)
|
||||
assert(string.format("%p", true) == null)
|
||||
assert(string.format("%p", nil) == null)
|
||||
assert(string.format("%p", {}) ~= null)
|
||||
assert(string.format("%p", print) ~= null)
|
||||
assert(string.format("%p", coroutine.running()) ~= null)
|
||||
assert(string.format("%p", {}) ~= string.format("%p", {}))
|
||||
assert(string.format("%p", string.rep("a", 10)) ==
|
||||
string.format("%p", string.rep("a", 10))) -- short strings
|
||||
assert(string.format("%p", string.rep("a", 300)) ~=
|
||||
string.format("%p", string.rep("a", 300))) -- long strings
|
||||
assert(string.format("%p", io.stdin) ~= null)
|
||||
assert(string.format("%p", io.stdin) == string.format("%p", io.stdin))
|
||||
assert(string.format("%p", print) == string.format("%p", print))
|
||||
assert(string.format("%p", print) ~= string.format("%p", assert))
|
||||
|
||||
assert(#string.format("%90p", {}) == 90)
|
||||
assert(#string.format("%-60p", {}) == 60)
|
||||
assert(string.format("%10p", false) == string.rep(" ", 10 - #null) .. null)
|
||||
assert(string.format("%-12p", 1.5) == null .. string.rep(" ", 12 - #null))
|
||||
|
||||
do
|
||||
local t1 = {}; local t2 = {}
|
||||
assert(string.format("%p", t1) ~= string.format("%p", t2))
|
||||
end
|
||||
|
||||
do -- short strings are internalized
|
||||
local s1 = string.rep("a", 10)
|
||||
local s2 = string.rep("aa", 5)
|
||||
assert(string.format("%p", s1) == string.format("%p", s2))
|
||||
end
|
||||
|
||||
do -- long strings aren't internalized
|
||||
local s1 = string.rep("a", 300); local s2 = string.rep("a", 300)
|
||||
assert(string.format("%p", s1) ~= string.format("%p", s2))
|
||||
end
|
||||
end
|
||||
|
||||
x = '"ílo"\n\\'
|
||||
@@ -181,13 +202,11 @@ assert(string.format("\0%c\0%c%x\0", string.byte("\xe4"), string.byte("b"), 140)
|
||||
"\0\xe4\0b8c\0")
|
||||
assert(string.format('') == "")
|
||||
assert(string.format("%c",34)..string.format("%c",48)..string.format("%c",90)..string.format("%c",100) ==
|
||||
string.format("%c%c%c%c", 34, 48, 90, 100))
|
||||
string.format("%1c%-c%-1c%c", 34, 48, 90, 100))
|
||||
assert(string.format("%s\0 is not \0%s", 'not be', 'be') == 'not be\0 is not \0be')
|
||||
assert(string.format("%%%d %010d", 10, 23) == "%10 0000000023")
|
||||
assert(tonumber(string.format("%f", 10.3)) == 10.3)
|
||||
x = string.format('"%-50s"', 'a')
|
||||
assert(#x == 52)
|
||||
assert(string.sub(x, 1, 4) == '"a ')
|
||||
assert(string.format('"%-50s"', 'a') == '"a' .. string.rep(' ', 49) .. '"')
|
||||
|
||||
assert(string.format("-%.20s.20s", string.rep("%", 2000)) ==
|
||||
"-"..string.rep("%", 20)..".20s")
|
||||
@@ -216,7 +235,6 @@ end
|
||||
|
||||
assert(string.format("\0%s\0", "\0\0\1") == "\0\0\0\1\0")
|
||||
checkerror("contains zeros", string.format, "%10s", "\0")
|
||||
checkerror("cannot have modifiers", string.format, "%10q", "1")
|
||||
|
||||
-- format x tostring
|
||||
assert(string.format("%s %s", nil, true) == "nil true")
|
||||
@@ -250,6 +268,12 @@ do -- longest number that can be formatted
|
||||
local s = string.format('%.99f', -(10^i))
|
||||
assert(string.len(s) >= i + 101)
|
||||
assert(tonumber(s) == -(10^i))
|
||||
|
||||
-- limit for floats
|
||||
assert(10^38 < math.huge)
|
||||
local s = string.format('%.99f', -(10^38))
|
||||
assert(string.len(s) >= 38 + 101)
|
||||
assert(tonumber(s) == -(10^38))
|
||||
end
|
||||
|
||||
|
||||
@@ -295,8 +319,8 @@ do print("testing 'format %a %A'")
|
||||
matchhexa(n)
|
||||
end
|
||||
|
||||
assert(string.find(string.format("%A", 0.0), "^0X0%.?0?P%+?0$"))
|
||||
assert(string.find(string.format("%a", -0.0), "^%-0x0%.?0?p%+?0$"))
|
||||
assert(string.find(string.format("%A", 0.0), "^0X0%.?0*P%+?0$"))
|
||||
assert(string.find(string.format("%a", -0.0), "^%-0x0%.?0*p%+?0$"))
|
||||
|
||||
if not _port then -- test inf, -inf, NaN, and -0.0
|
||||
assert(string.find(string.format("%a", 1/0), "^inf"))
|
||||
@@ -314,6 +338,21 @@ do print("testing 'format %a %A'")
|
||||
end
|
||||
|
||||
|
||||
-- testing some flags (all these results are required by ISO C)
|
||||
assert(string.format("%#12o", 10) == " 012")
|
||||
assert(string.format("%#10x", 100) == " 0x64")
|
||||
assert(string.format("%#-17X", 100) == "0X64 ")
|
||||
assert(string.format("%013i", -100) == "-000000000100")
|
||||
assert(string.format("%2.5d", -100) == "-00100")
|
||||
assert(string.format("%.u", 0) == "")
|
||||
assert(string.format("%+#014.0f", 100) == "+000000000100.")
|
||||
assert(string.format("% 1.0E", 100) == " 1E+02")
|
||||
assert(string.format("%-16c", 97) == "a ")
|
||||
assert(string.format("%+.3G", 1.5) == "+1.5")
|
||||
assert(string.format("% .1g", 2^10) == " 1e+03")
|
||||
assert(string.format("%.0s", "alo") == "")
|
||||
assert(string.format("%.s", "alo") == "")
|
||||
|
||||
-- errors in format
|
||||
|
||||
local function check (fmt, msg)
|
||||
@@ -321,19 +360,30 @@ local function check (fmt, msg)
|
||||
end
|
||||
|
||||
local aux = string.rep('0', 600)
|
||||
check("%100.3d", "too long")
|
||||
check("%100.3d", "invalid conversion")
|
||||
check("%1"..aux..".3d", "too long")
|
||||
check("%1.100d", "too long")
|
||||
check("%1.100d", "invalid conversion")
|
||||
check("%10.1"..aux.."004d", "too long")
|
||||
check("%t", "invalid conversion")
|
||||
check("%"..aux.."d", "repeated flags")
|
||||
check("%"..aux.."d", "too long")
|
||||
check("%d %d", "no value")
|
||||
check("%010c", "invalid conversion")
|
||||
check("%.10c", "invalid conversion")
|
||||
check("%0.34s", "invalid conversion")
|
||||
check("%#i", "invalid conversion")
|
||||
check("%3.1p", "invalid conversion")
|
||||
check("%0.s", "invalid conversion")
|
||||
check("%10q", "cannot have modifiers")
|
||||
check("%F", "invalid conversion") -- useless and not in C89
|
||||
|
||||
|
||||
assert(load("return 1\n--comment without ending EOL")() == 1)
|
||||
|
||||
|
||||
checkerror("table expected", table.concat, 3)
|
||||
checkerror("at index " .. maxi, table.concat, {}, " ", maxi, maxi)
|
||||
-- '%' escapes following minus signal
|
||||
checkerror("at index %" .. mini, table.concat, {}, " ", mini, mini)
|
||||
assert(table.concat{} == "")
|
||||
assert(table.concat({}, 'x') == "")
|
||||
assert(table.concat({'\0', '\0\1', '\0\1\2'}, '.\0.') == "\0.\0.\0\1.\0.\0\1\2")
|
||||
@@ -411,7 +461,7 @@ else
|
||||
|
||||
-- formats %U, %f, %I already tested elsewhere
|
||||
|
||||
local blen = 400 -- internal buffer length in 'luaO_pushfstring'
|
||||
local blen = 200 -- internal buffer length in 'luaO_pushfstring'
|
||||
|
||||
local function callpfs (op, fmt, n)
|
||||
local x = {T.testC("pushfstring" .. op .. "; return *", fmt, n)}
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
-- track collections
|
||||
|
||||
local M = {}
|
||||
|
||||
-- import list
|
||||
local setmetatable, stderr, collectgarbage =
|
||||
setmetatable, io.stderr, collectgarbage
|
||||
|
||||
_ENV = nil
|
||||
|
||||
local active = false
|
||||
|
||||
|
||||
-- each time a table is collected, remark it for finalization on next
|
||||
-- cycle
|
||||
local mt = {}
|
||||
function mt.__gc (o)
|
||||
stderr:write'.' -- mark progress
|
||||
if active then
|
||||
setmetatable(o, mt) -- remark object for finalization
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
function M.start ()
|
||||
if not active then
|
||||
active = true
|
||||
setmetatable({}, mt) -- create initial object
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
function M.stop ()
|
||||
if active then
|
||||
active = false
|
||||
collectgarbage() -- call finalizer for the last time
|
||||
end
|
||||
end
|
||||
|
||||
return M
|
||||
+17
-11
@@ -30,8 +30,8 @@ local function checksyntax (s, t)
|
||||
assert(assert(load(ts))() == s)
|
||||
end
|
||||
|
||||
assert(utf8.offset("alo", 5) == nil)
|
||||
assert(utf8.offset("alo", -4) == nil)
|
||||
assert(not utf8.offset("alo", 5))
|
||||
assert(not utf8.offset("alo", -4))
|
||||
|
||||
-- 'check' makes several tests over the validity of string 's'.
|
||||
-- 't' is the list of codepoints of 's'.
|
||||
@@ -112,20 +112,26 @@ do
|
||||
end
|
||||
errorcodes("ab\xff")
|
||||
errorcodes("\u{110000}")
|
||||
|
||||
-- calling interation function with invalid arguments
|
||||
local f = utf8.codes("")
|
||||
assert(f("", 2) == nil)
|
||||
assert(f("", -1) == nil)
|
||||
assert(f("", math.mininteger) == nil)
|
||||
end
|
||||
|
||||
-- error in initial position for offset
|
||||
checkerror("position out of range", utf8.offset, "abc", 1, 5)
|
||||
checkerror("position out of range", utf8.offset, "abc", 1, -4)
|
||||
checkerror("position out of range", utf8.offset, "", 1, 2)
|
||||
checkerror("position out of range", utf8.offset, "", 1, -1)
|
||||
checkerror("position out of bounds", utf8.offset, "abc", 1, 5)
|
||||
checkerror("position out of bounds", utf8.offset, "abc", 1, -4)
|
||||
checkerror("position out of bounds", utf8.offset, "", 1, 2)
|
||||
checkerror("position out of bounds", utf8.offset, "", 1, -1)
|
||||
checkerror("continuation byte", utf8.offset, "𦧺", 1, 2)
|
||||
checkerror("continuation byte", utf8.offset, "𦧺", 1, 2)
|
||||
checkerror("continuation byte", utf8.offset, "\x80", 1)
|
||||
|
||||
-- error in indices for len
|
||||
checkerror("out of string", utf8.len, "abc", 0, 2)
|
||||
checkerror("out of string", utf8.len, "abc", 1, 4)
|
||||
checkerror("out of bounds", utf8.len, "abc", 0, 2)
|
||||
checkerror("out of bounds", utf8.len, "abc", 1, 4)
|
||||
|
||||
|
||||
local s = "hello World"
|
||||
@@ -140,11 +146,11 @@ do
|
||||
local t = {utf8.codepoint(s,1,#s - 1)}
|
||||
assert(#t == 3 and t[1] == 225 and t[2] == 233 and t[3] == 237)
|
||||
checkerror("invalid UTF%-8 code", utf8.codepoint, s, 1, #s)
|
||||
checkerror("out of range", utf8.codepoint, s, #s + 1)
|
||||
checkerror("out of bounds", utf8.codepoint, s, #s + 1)
|
||||
t = {utf8.codepoint(s, 4, 3)}
|
||||
assert(#t == 0)
|
||||
checkerror("out of range", utf8.codepoint, s, -(#s + 1), 1)
|
||||
checkerror("out of range", utf8.codepoint, s, 1, #s + 1)
|
||||
checkerror("out of bounds", utf8.codepoint, s, -(#s + 1), 1)
|
||||
checkerror("out of bounds", utf8.codepoint, s, 1, #s + 1)
|
||||
-- surrogates
|
||||
assert(utf8.codepoint("\u{D7FF}") == 0xD800 - 1)
|
||||
assert(utf8.codepoint("\u{E000}") == 0xDFFF + 1)
|
||||
|
||||
Reference in New Issue
Block a user