trunk/src/lib/lua/lapi.c
| r30857 | r30858 | |
| 1 | 1 | /* |
| 2 | | ** $Id: lapi.c,v 2.171 2013/03/16 21:10:18 roberto Exp $ |
| 2 | ** $Id: lapi.c,v 2.171.1.1 2013/04/12 18:48:47 roberto Exp $ |
| 3 | 3 | ** Lua API |
| 4 | 4 | ** See Copyright Notice in lua.h |
| 5 | 5 | */ |
| r30857 | r30858 | |
| 30 | 30 | |
| 31 | 31 | |
| 32 | 32 | const char lua_ident[] = |
| 33 | | "$LuaVersion: " LUA_COPYRIGHT " $" |
| 34 | | "$LuaAuthors: " LUA_AUTHORS " $"; |
| 33 | "$LuaVersion: " LUA_COPYRIGHT " $" |
| 34 | "$LuaAuthors: " LUA_AUTHORS " $"; |
| 35 | 35 | |
| 36 | 36 | |
| 37 | 37 | /* value at a non-valid index */ |
| 38 | | #define NONVALIDVALUE cast(TValue *, luaO_nilobject) |
| 38 | #define NONVALIDVALUE cast(TValue *, luaO_nilobject) |
| 39 | 39 | |
| 40 | 40 | /* corresponding test */ |
| 41 | | #define isvalid(o) ((o) != luaO_nilobject) |
| 41 | #define isvalid(o) ((o) != luaO_nilobject) |
| 42 | 42 | |
| 43 | 43 | /* test for pseudo index */ |
| 44 | | #define ispseudo(i) ((i) <= LUA_REGISTRYINDEX) |
| 44 | #define ispseudo(i) ((i) <= LUA_REGISTRYINDEX) |
| 45 | 45 | |
| 46 | 46 | /* test for valid but not pseudo index */ |
| 47 | | #define isstackindex(i, o) (isvalid(o) && !ispseudo(i)) |
| 47 | #define isstackindex(i, o) (isvalid(o) && !ispseudo(i)) |
| 48 | 48 | |
| 49 | 49 | #define api_checkvalidindex(L, o) api_check(L, isvalid(o), "invalid index") |
| 50 | 50 | |
| r30857 | r30858 | |
| 53 | 53 | |
| 54 | 54 | |
| 55 | 55 | static TValue *index2addr (lua_State *L, int idx) { |
| 56 | | CallInfo *ci = L->ci; |
| 57 | | if (idx > 0) { |
| 58 | | TValue *o = ci->func + idx; |
| 59 | | api_check(L, idx <= ci->top - (ci->func + 1), "unacceptable index"); |
| 60 | | if (o >= L->top) return NONVALIDVALUE; |
| 61 | | else return o; |
| 62 | | } |
| 63 | | else if (!ispseudo(idx)) { /* negative index */ |
| 64 | | api_check(L, idx != 0 && -idx <= L->top - (ci->func + 1), "invalid index"); |
| 65 | | return L->top + idx; |
| 66 | | } |
| 67 | | else if (idx == LUA_REGISTRYINDEX) |
| 68 | | return &G(L)->l_registry; |
| 69 | | else { /* upvalues */ |
| 70 | | idx = LUA_REGISTRYINDEX - idx; |
| 71 | | api_check(L, idx <= MAXUPVAL + 1, "upvalue index too large"); |
| 72 | | if (ttislcf(ci->func)) /* light C function? */ |
| 73 | | return NONVALIDVALUE; /* it has no upvalues */ |
| 74 | | else { |
| 75 | | CClosure *func = clCvalue(ci->func); |
| 76 | | return (idx <= func->nupvalues) ? &func->upvalue[idx-1] : NONVALIDVALUE; |
| 77 | | } |
| 78 | | } |
| 56 | CallInfo *ci = L->ci; |
| 57 | if (idx > 0) { |
| 58 | TValue *o = ci->func + idx; |
| 59 | api_check(L, idx <= ci->top - (ci->func + 1), "unacceptable index"); |
| 60 | if (o >= L->top) return NONVALIDVALUE; |
| 61 | else return o; |
| 62 | } |
| 63 | else if (!ispseudo(idx)) { /* negative index */ |
| 64 | api_check(L, idx != 0 && -idx <= L->top - (ci->func + 1), "invalid index"); |
| 65 | return L->top + idx; |
| 66 | } |
| 67 | else if (idx == LUA_REGISTRYINDEX) |
| 68 | return &G(L)->l_registry; |
| 69 | else { /* upvalues */ |
| 70 | idx = LUA_REGISTRYINDEX - idx; |
| 71 | api_check(L, idx <= MAXUPVAL + 1, "upvalue index too large"); |
| 72 | if (ttislcf(ci->func)) /* light C function? */ |
| 73 | return NONVALIDVALUE; /* it has no upvalues */ |
| 74 | else { |
| 75 | CClosure *func = clCvalue(ci->func); |
| 76 | return (idx <= func->nupvalues) ? &func->upvalue[idx-1] : NONVALIDVALUE; |
| 77 | } |
| 78 | } |
| 79 | 79 | } |
| 80 | 80 | |
| 81 | 81 | |
| r30857 | r30858 | |
| 84 | 84 | ** capturing memory errors |
| 85 | 85 | */ |
| 86 | 86 | static void growstack (lua_State *L, void *ud) { |
| 87 | | int size = *(int *)ud; |
| 88 | | luaD_growstack(L, size); |
| 87 | int size = *(int *)ud; |
| 88 | luaD_growstack(L, size); |
| 89 | 89 | } |
| 90 | 90 | |
| 91 | 91 | |
| 92 | 92 | LUA_API int lua_checkstack (lua_State *L, int size) { |
| 93 | | int res; |
| 94 | | CallInfo *ci = L->ci; |
| 95 | | lua_lock(L); |
| 96 | | if (L->stack_last - L->top > size) /* stack large enough? */ |
| 97 | | res = 1; /* yes; check is OK */ |
| 98 | | else { /* no; need to grow stack */ |
| 99 | | int inuse = cast_int(L->top - L->stack) + EXTRA_STACK; |
| 100 | | if (inuse > LUAI_MAXSTACK - size) /* can grow without overflow? */ |
| 101 | | res = 0; /* no */ |
| 102 | | else /* try to grow stack */ |
| 103 | | res = (luaD_rawrunprotected(L, &growstack, &size) == LUA_OK); |
| 104 | | } |
| 105 | | if (res && ci->top < L->top + size) |
| 106 | | ci->top = L->top + size; /* adjust frame top */ |
| 107 | | lua_unlock(L); |
| 108 | | return res; |
| 93 | int res; |
| 94 | CallInfo *ci = L->ci; |
| 95 | lua_lock(L); |
| 96 | if (L->stack_last - L->top > size) /* stack large enough? */ |
| 97 | res = 1; /* yes; check is OK */ |
| 98 | else { /* no; need to grow stack */ |
| 99 | int inuse = cast_int(L->top - L->stack) + EXTRA_STACK; |
| 100 | if (inuse > LUAI_MAXSTACK - size) /* can grow without overflow? */ |
| 101 | res = 0; /* no */ |
| 102 | else /* try to grow stack */ |
| 103 | res = (luaD_rawrunprotected(L, &growstack, &size) == LUA_OK); |
| 104 | } |
| 105 | if (res && ci->top < L->top + size) |
| 106 | ci->top = L->top + size; /* adjust frame top */ |
| 107 | lua_unlock(L); |
| 108 | return res; |
| 109 | 109 | } |
| 110 | 110 | |
| 111 | 111 | |
| 112 | 112 | LUA_API void lua_xmove (lua_State *from, lua_State *to, int n) { |
| 113 | | int i; |
| 114 | | if (from == to) return; |
| 115 | | lua_lock(to); |
| 116 | | api_checknelems(from, n); |
| 117 | | api_check(from, G(from) == G(to), "moving among independent states"); |
| 118 | | api_check(from, to->ci->top - to->top >= n, "not enough elements to move"); |
| 119 | | from->top -= n; |
| 120 | | for (i = 0; i < n; i++) { |
| 121 | | setobj2s(to, to->top++, from->top + i); |
| 122 | | } |
| 123 | | lua_unlock(to); |
| 113 | int i; |
| 114 | if (from == to) return; |
| 115 | lua_lock(to); |
| 116 | api_checknelems(from, n); |
| 117 | api_check(from, G(from) == G(to), "moving among independent states"); |
| 118 | api_check(from, to->ci->top - to->top >= n, "not enough elements to move"); |
| 119 | from->top -= n; |
| 120 | for (i = 0; i < n; i++) { |
| 121 | setobj2s(to, to->top++, from->top + i); |
| 122 | } |
| 123 | lua_unlock(to); |
| 124 | 124 | } |
| 125 | 125 | |
| 126 | 126 | |
| 127 | 127 | LUA_API lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf) { |
| 128 | | lua_CFunction old; |
| 129 | | lua_lock(L); |
| 130 | | old = G(L)->panic; |
| 131 | | G(L)->panic = panicf; |
| 132 | | lua_unlock(L); |
| 133 | | return old; |
| 128 | lua_CFunction old; |
| 129 | lua_lock(L); |
| 130 | old = G(L)->panic; |
| 131 | G(L)->panic = panicf; |
| 132 | lua_unlock(L); |
| 133 | return old; |
| 134 | 134 | } |
| 135 | 135 | |
| 136 | 136 | |
| 137 | 137 | LUA_API const lua_Number *lua_version (lua_State *L) { |
| 138 | | static const lua_Number version = LUA_VERSION_NUM; |
| 139 | | if (L == NULL) return &version; |
| 140 | | else return G(L)->version; |
| 138 | static const lua_Number version = LUA_VERSION_NUM; |
| 139 | if (L == NULL) return &version; |
| 140 | else return G(L)->version; |
| 141 | 141 | } |
| 142 | 142 | |
| 143 | 143 | |
| r30857 | r30858 | |
| 151 | 151 | ** convert an acceptable stack index into an absolute index |
| 152 | 152 | */ |
| 153 | 153 | LUA_API int lua_absindex (lua_State *L, int idx) { |
| 154 | | return (idx > 0 || ispseudo(idx)) |
| 155 | | ? idx |
| 156 | | : cast_int(L->top - L->ci->func + idx); |
| 154 | return (idx > 0 || ispseudo(idx)) |
| 155 | ? idx |
| 156 | : cast_int(L->top - L->ci->func + idx); |
| 157 | 157 | } |
| 158 | 158 | |
| 159 | 159 | |
| 160 | 160 | LUA_API int lua_gettop (lua_State *L) { |
| 161 | | return cast_int(L->top - (L->ci->func + 1)); |
| 161 | return cast_int(L->top - (L->ci->func + 1)); |
| 162 | 162 | } |
| 163 | 163 | |
| 164 | 164 | |
| 165 | 165 | LUA_API void lua_settop (lua_State *L, int idx) { |
| 166 | | StkId func = L->ci->func; |
| 167 | | lua_lock(L); |
| 168 | | if (idx >= 0) { |
| 169 | | api_check(L, idx <= L->stack_last - (func + 1), "new top too large"); |
| 170 | | while (L->top < (func + 1) + idx) |
| 171 | | setnilvalue(L->top++); |
| 172 | | L->top = (func + 1) + idx; |
| 173 | | } |
| 174 | | else { |
| 175 | | api_check(L, -(idx+1) <= (L->top - (func + 1)), "invalid new top"); |
| 176 | | L->top += idx+1; /* `subtract' index (index is negative) */ |
| 177 | | } |
| 178 | | lua_unlock(L); |
| 166 | StkId func = L->ci->func; |
| 167 | lua_lock(L); |
| 168 | if (idx >= 0) { |
| 169 | api_check(L, idx <= L->stack_last - (func + 1), "new top too large"); |
| 170 | while (L->top < (func + 1) + idx) |
| 171 | setnilvalue(L->top++); |
| 172 | L->top = (func + 1) + idx; |
| 173 | } |
| 174 | else { |
| 175 | api_check(L, -(idx+1) <= (L->top - (func + 1)), "invalid new top"); |
| 176 | L->top += idx+1; /* `subtract' index (index is negative) */ |
| 177 | } |
| 178 | lua_unlock(L); |
| 179 | 179 | } |
| 180 | 180 | |
| 181 | 181 | |
| 182 | 182 | LUA_API void lua_remove (lua_State *L, int idx) { |
| 183 | | StkId p; |
| 184 | | lua_lock(L); |
| 185 | | p = index2addr(L, idx); |
| 186 | | api_checkstackindex(L, idx, p); |
| 187 | | while (++p < L->top) setobjs2s(L, p-1, p); |
| 188 | | L->top--; |
| 189 | | lua_unlock(L); |
| 183 | StkId p; |
| 184 | lua_lock(L); |
| 185 | p = index2addr(L, idx); |
| 186 | api_checkstackindex(L, idx, p); |
| 187 | while (++p < L->top) setobjs2s(L, p-1, p); |
| 188 | L->top--; |
| 189 | lua_unlock(L); |
| 190 | 190 | } |
| 191 | 191 | |
| 192 | 192 | |
| 193 | 193 | LUA_API void lua_insert (lua_State *L, int idx) { |
| 194 | | StkId p; |
| 195 | | StkId q; |
| 196 | | lua_lock(L); |
| 197 | | p = index2addr(L, idx); |
| 198 | | api_checkstackindex(L, idx, p); |
| 199 | | for (q = L->top; q > p; q--) /* use L->top as a temporary */ |
| 200 | | setobjs2s(L, q, q - 1); |
| 201 | | setobjs2s(L, p, L->top); |
| 202 | | lua_unlock(L); |
| 194 | StkId p; |
| 195 | StkId q; |
| 196 | lua_lock(L); |
| 197 | p = index2addr(L, idx); |
| 198 | api_checkstackindex(L, idx, p); |
| 199 | for (q = L->top; q > p; q--) /* use L->top as a temporary */ |
| 200 | setobjs2s(L, q, q - 1); |
| 201 | setobjs2s(L, p, L->top); |
| 202 | lua_unlock(L); |
| 203 | 203 | } |
| 204 | 204 | |
| 205 | 205 | |
| 206 | 206 | static void moveto (lua_State *L, TValue *fr, int idx) { |
| 207 | | TValue *to = index2addr(L, idx); |
| 208 | | api_checkvalidindex(L, to); |
| 209 | | setobj(L, to, fr); |
| 210 | | if (idx < LUA_REGISTRYINDEX) /* function upvalue? */ |
| 211 | | luaC_barrier(L, clCvalue(L->ci->func), fr); |
| 212 | | /* LUA_REGISTRYINDEX does not need gc barrier |
| 213 | | (collector revisits it before finishing collection) */ |
| 207 | TValue *to = index2addr(L, idx); |
| 208 | api_checkvalidindex(L, to); |
| 209 | setobj(L, to, fr); |
| 210 | if (idx < LUA_REGISTRYINDEX) /* function upvalue? */ |
| 211 | luaC_barrier(L, clCvalue(L->ci->func), fr); |
| 212 | /* LUA_REGISTRYINDEX does not need gc barrier |
| 213 | (collector revisits it before finishing collection) */ |
| 214 | 214 | } |
| 215 | 215 | |
| 216 | 216 | |
| 217 | 217 | LUA_API void lua_replace (lua_State *L, int idx) { |
| 218 | | lua_lock(L); |
| 219 | | api_checknelems(L, 1); |
| 220 | | moveto(L, L->top - 1, idx); |
| 221 | | L->top--; |
| 222 | | lua_unlock(L); |
| 218 | lua_lock(L); |
| 219 | api_checknelems(L, 1); |
| 220 | moveto(L, L->top - 1, idx); |
| 221 | L->top--; |
| 222 | lua_unlock(L); |
| 223 | 223 | } |
| 224 | 224 | |
| 225 | 225 | |
| 226 | 226 | LUA_API void lua_copy (lua_State *L, int fromidx, int toidx) { |
| 227 | | TValue *fr; |
| 228 | | lua_lock(L); |
| 229 | | fr = index2addr(L, fromidx); |
| 230 | | moveto(L, fr, toidx); |
| 231 | | lua_unlock(L); |
| 227 | TValue *fr; |
| 228 | lua_lock(L); |
| 229 | fr = index2addr(L, fromidx); |
| 230 | moveto(L, fr, toidx); |
| 231 | lua_unlock(L); |
| 232 | 232 | } |
| 233 | 233 | |
| 234 | 234 | |
| 235 | 235 | LUA_API void lua_pushvalue (lua_State *L, int idx) { |
| 236 | | lua_lock(L); |
| 237 | | setobj2s(L, L->top, index2addr(L, idx)); |
| 238 | | api_incr_top(L); |
| 239 | | lua_unlock(L); |
| 236 | lua_lock(L); |
| 237 | setobj2s(L, L->top, index2addr(L, idx)); |
| 238 | api_incr_top(L); |
| 239 | lua_unlock(L); |
| 240 | 240 | } |
| 241 | 241 | |
| 242 | 242 | |
| r30857 | r30858 | |
| 247 | 247 | |
| 248 | 248 | |
| 249 | 249 | LUA_API int lua_type (lua_State *L, int idx) { |
| 250 | | StkId o = index2addr(L, idx); |
| 251 | | return (isvalid(o) ? ttypenv(o) : LUA_TNONE); |
| 250 | StkId o = index2addr(L, idx); |
| 251 | return (isvalid(o) ? ttypenv(o) : LUA_TNONE); |
| 252 | 252 | } |
| 253 | 253 | |
| 254 | 254 | |
| 255 | 255 | LUA_API const char *lua_typename (lua_State *L, int t) { |
| 256 | | UNUSED(L); |
| 257 | | return ttypename(t); |
| 256 | UNUSED(L); |
| 257 | return ttypename(t); |
| 258 | 258 | } |
| 259 | 259 | |
| 260 | 260 | |
| 261 | 261 | LUA_API int lua_iscfunction (lua_State *L, int idx) { |
| 262 | | StkId o = index2addr(L, idx); |
| 263 | | return (ttislcf(o) || (ttisCclosure(o))); |
| 262 | StkId o = index2addr(L, idx); |
| 263 | return (ttislcf(o) || (ttisCclosure(o))); |
| 264 | 264 | } |
| 265 | 265 | |
| 266 | 266 | |
| 267 | 267 | LUA_API int lua_isnumber (lua_State *L, int idx) { |
| 268 | | TValue n; |
| 269 | | const TValue *o = index2addr(L, idx); |
| 270 | | return tonumber(o, &n); |
| 268 | TValue n; |
| 269 | const TValue *o = index2addr(L, idx); |
| 270 | return tonumber(o, &n); |
| 271 | 271 | } |
| 272 | 272 | |
| 273 | 273 | |
| 274 | 274 | LUA_API int lua_isstring (lua_State *L, int idx) { |
| 275 | | int t = lua_type(L, idx); |
| 276 | | return (t == LUA_TSTRING || t == LUA_TNUMBER); |
| 275 | int t = lua_type(L, idx); |
| 276 | return (t == LUA_TSTRING || t == LUA_TNUMBER); |
| 277 | 277 | } |
| 278 | 278 | |
| 279 | 279 | |
| 280 | 280 | LUA_API int lua_isuserdata (lua_State *L, int idx) { |
| 281 | | const TValue *o = index2addr(L, idx); |
| 282 | | return (ttisuserdata(o) || ttislightuserdata(o)); |
| 281 | const TValue *o = index2addr(L, idx); |
| 282 | return (ttisuserdata(o) || ttislightuserdata(o)); |
| 283 | 283 | } |
| 284 | 284 | |
| 285 | 285 | |
| 286 | 286 | LUA_API int lua_rawequal (lua_State *L, int index1, int index2) { |
| 287 | | StkId o1 = index2addr(L, index1); |
| 288 | | StkId o2 = index2addr(L, index2); |
| 289 | | return (isvalid(o1) && isvalid(o2)) ? luaV_rawequalobj(o1, o2) : 0; |
| 287 | StkId o1 = index2addr(L, index1); |
| 288 | StkId o2 = index2addr(L, index2); |
| 289 | return (isvalid(o1) && isvalid(o2)) ? luaV_rawequalobj(o1, o2) : 0; |
| 290 | 290 | } |
| 291 | 291 | |
| 292 | 292 | |
| 293 | 293 | LUA_API void lua_arith (lua_State *L, int op) { |
| 294 | | StkId o1; /* 1st operand */ |
| 295 | | StkId o2; /* 2nd operand */ |
| 296 | | lua_lock(L); |
| 297 | | if (op != LUA_OPUNM) /* all other operations expect two operands */ |
| 298 | | api_checknelems(L, 2); |
| 299 | | else { /* for unary minus, add fake 2nd operand */ |
| 300 | | api_checknelems(L, 1); |
| 301 | | setobjs2s(L, L->top, L->top - 1); |
| 302 | | L->top++; |
| 303 | | } |
| 304 | | o1 = L->top - 2; |
| 305 | | o2 = L->top - 1; |
| 306 | | if (ttisnumber(o1) && ttisnumber(o2)) { |
| 307 | | setnvalue(o1, luaO_arith(op, nvalue(o1), nvalue(o2))); |
| 308 | | } |
| 309 | | else |
| 310 | | luaV_arith(L, o1, o1, o2, cast(TMS, op - LUA_OPADD + TM_ADD)); |
| 311 | | L->top--; |
| 312 | | lua_unlock(L); |
| 294 | StkId o1; /* 1st operand */ |
| 295 | StkId o2; /* 2nd operand */ |
| 296 | lua_lock(L); |
| 297 | if (op != LUA_OPUNM) /* all other operations expect two operands */ |
| 298 | api_checknelems(L, 2); |
| 299 | else { /* for unary minus, add fake 2nd operand */ |
| 300 | api_checknelems(L, 1); |
| 301 | setobjs2s(L, L->top, L->top - 1); |
| 302 | L->top++; |
| 303 | } |
| 304 | o1 = L->top - 2; |
| 305 | o2 = L->top - 1; |
| 306 | if (ttisnumber(o1) && ttisnumber(o2)) { |
| 307 | setnvalue(o1, luaO_arith(op, nvalue(o1), nvalue(o2))); |
| 308 | } |
| 309 | else |
| 310 | luaV_arith(L, o1, o1, o2, cast(TMS, op - LUA_OPADD + TM_ADD)); |
| 311 | L->top--; |
| 312 | lua_unlock(L); |
| 313 | 313 | } |
| 314 | 314 | |
| 315 | 315 | |
| 316 | 316 | LUA_API int lua_compare (lua_State *L, int index1, int index2, int op) { |
| 317 | | StkId o1, o2; |
| 318 | | int i = 0; |
| 319 | | lua_lock(L); /* may call tag method */ |
| 320 | | o1 = index2addr(L, index1); |
| 321 | | o2 = index2addr(L, index2); |
| 322 | | if (isvalid(o1) && isvalid(o2)) { |
| 323 | | switch (op) { |
| 324 | | case LUA_OPEQ: i = equalobj(L, o1, o2); break; |
| 325 | | case LUA_OPLT: i = luaV_lessthan(L, o1, o2); break; |
| 326 | | case LUA_OPLE: i = luaV_lessequal(L, o1, o2); break; |
| 327 | | default: api_check(L, 0, "invalid option"); |
| 328 | | } |
| 329 | | } |
| 330 | | lua_unlock(L); |
| 331 | | return i; |
| 317 | StkId o1, o2; |
| 318 | int i = 0; |
| 319 | lua_lock(L); /* may call tag method */ |
| 320 | o1 = index2addr(L, index1); |
| 321 | o2 = index2addr(L, index2); |
| 322 | if (isvalid(o1) && isvalid(o2)) { |
| 323 | switch (op) { |
| 324 | case LUA_OPEQ: i = equalobj(L, o1, o2); break; |
| 325 | case LUA_OPLT: i = luaV_lessthan(L, o1, o2); break; |
| 326 | case LUA_OPLE: i = luaV_lessequal(L, o1, o2); break; |
| 327 | default: api_check(L, 0, "invalid option"); |
| 328 | } |
| 329 | } |
| 330 | lua_unlock(L); |
| 331 | return i; |
| 332 | 332 | } |
| 333 | 333 | |
| 334 | 334 | |
| 335 | 335 | LUA_API lua_Number lua_tonumberx (lua_State *L, int idx, int *isnum) { |
| 336 | | TValue n; |
| 337 | | const TValue *o = index2addr(L, idx); |
| 338 | | if (tonumber(o, &n)) { |
| 339 | | if (isnum) *isnum = 1; |
| 340 | | return nvalue(o); |
| 341 | | } |
| 342 | | else { |
| 343 | | if (isnum) *isnum = 0; |
| 344 | | return 0; |
| 345 | | } |
| 336 | TValue n; |
| 337 | const TValue *o = index2addr(L, idx); |
| 338 | if (tonumber(o, &n)) { |
| 339 | if (isnum) *isnum = 1; |
| 340 | return nvalue(o); |
| 341 | } |
| 342 | else { |
| 343 | if (isnum) *isnum = 0; |
| 344 | return 0; |
| 345 | } |
| 346 | 346 | } |
| 347 | 347 | |
| 348 | 348 | |
| 349 | 349 | LUA_API lua_Integer lua_tointegerx (lua_State *L, int idx, int *isnum) { |
| 350 | | TValue n; |
| 351 | | const TValue *o = index2addr(L, idx); |
| 352 | | if (tonumber(o, &n)) { |
| 353 | | lua_Integer res; |
| 354 | | lua_Number num = nvalue(o); |
| 355 | | lua_number2integer(res, num); |
| 356 | | if (isnum) *isnum = 1; |
| 357 | | return res; |
| 358 | | } |
| 359 | | else { |
| 360 | | if (isnum) *isnum = 0; |
| 361 | | return 0; |
| 362 | | } |
| 350 | TValue n; |
| 351 | const TValue *o = index2addr(L, idx); |
| 352 | if (tonumber(o, &n)) { |
| 353 | lua_Integer res; |
| 354 | lua_Number num = nvalue(o); |
| 355 | lua_number2integer(res, num); |
| 356 | if (isnum) *isnum = 1; |
| 357 | return res; |
| 358 | } |
| 359 | else { |
| 360 | if (isnum) *isnum = 0; |
| 361 | return 0; |
| 362 | } |
| 363 | 363 | } |
| 364 | 364 | |
| 365 | 365 | |
| 366 | 366 | LUA_API lua_Unsigned lua_tounsignedx (lua_State *L, int idx, int *isnum) { |
| 367 | | TValue n; |
| 368 | | const TValue *o = index2addr(L, idx); |
| 369 | | if (tonumber(o, &n)) { |
| 370 | | lua_Unsigned res; |
| 371 | | lua_Number num = nvalue(o); |
| 372 | | lua_number2unsigned(res, num); |
| 373 | | if (isnum) *isnum = 1; |
| 374 | | return res; |
| 375 | | } |
| 376 | | else { |
| 377 | | if (isnum) *isnum = 0; |
| 378 | | return 0; |
| 379 | | } |
| 367 | TValue n; |
| 368 | const TValue *o = index2addr(L, idx); |
| 369 | if (tonumber(o, &n)) { |
| 370 | lua_Unsigned res; |
| 371 | lua_Number num = nvalue(o); |
| 372 | lua_number2unsigned(res, num); |
| 373 | if (isnum) *isnum = 1; |
| 374 | return res; |
| 375 | } |
| 376 | else { |
| 377 | if (isnum) *isnum = 0; |
| 378 | return 0; |
| 379 | } |
| 380 | 380 | } |
| 381 | 381 | |
| 382 | 382 | |
| 383 | 383 | LUA_API int lua_toboolean (lua_State *L, int idx) { |
| 384 | | const TValue *o = index2addr(L, idx); |
| 385 | | return !l_isfalse(o); |
| 384 | const TValue *o = index2addr(L, idx); |
| 385 | return !l_isfalse(o); |
| 386 | 386 | } |
| 387 | 387 | |
| 388 | 388 | |
| 389 | 389 | LUA_API const char *lua_tolstring (lua_State *L, int idx, size_t *len) { |
| 390 | | StkId o = index2addr(L, idx); |
| 391 | | if (!ttisstring(o)) { |
| 392 | | lua_lock(L); /* `luaV_tostring' may create a new string */ |
| 393 | | if (!luaV_tostring(L, o)) { /* conversion failed? */ |
| 394 | | if (len != NULL) *len = 0; |
| 395 | | lua_unlock(L); |
| 396 | | return NULL; |
| 397 | | } |
| 398 | | luaC_checkGC(L); |
| 399 | | o = index2addr(L, idx); /* previous call may reallocate the stack */ |
| 400 | | lua_unlock(L); |
| 401 | | } |
| 402 | | if (len != NULL) *len = tsvalue(o)->len; |
| 403 | | return svalue(o); |
| 390 | StkId o = index2addr(L, idx); |
| 391 | if (!ttisstring(o)) { |
| 392 | lua_lock(L); /* `luaV_tostring' may create a new string */ |
| 393 | if (!luaV_tostring(L, o)) { /* conversion failed? */ |
| 394 | if (len != NULL) *len = 0; |
| 395 | lua_unlock(L); |
| 396 | return NULL; |
| 397 | } |
| 398 | luaC_checkGC(L); |
| 399 | o = index2addr(L, idx); /* previous call may reallocate the stack */ |
| 400 | lua_unlock(L); |
| 401 | } |
| 402 | if (len != NULL) *len = tsvalue(o)->len; |
| 403 | return svalue(o); |
| 404 | 404 | } |
| 405 | 405 | |
| 406 | 406 | |
| 407 | 407 | LUA_API size_t lua_rawlen (lua_State *L, int idx) { |
| 408 | | StkId o = index2addr(L, idx); |
| 409 | | switch (ttypenv(o)) { |
| 410 | | case LUA_TSTRING: return tsvalue(o)->len; |
| 411 | | case LUA_TUSERDATA: return uvalue(o)->len; |
| 412 | | case LUA_TTABLE: return luaH_getn(hvalue(o)); |
| 413 | | default: return 0; |
| 414 | | } |
| 408 | StkId o = index2addr(L, idx); |
| 409 | switch (ttypenv(o)) { |
| 410 | case LUA_TSTRING: return tsvalue(o)->len; |
| 411 | case LUA_TUSERDATA: return uvalue(o)->len; |
| 412 | case LUA_TTABLE: return luaH_getn(hvalue(o)); |
| 413 | default: return 0; |
| 414 | } |
| 415 | 415 | } |
| 416 | 416 | |
| 417 | 417 | |
| 418 | 418 | LUA_API lua_CFunction lua_tocfunction (lua_State *L, int idx) { |
| 419 | | StkId o = index2addr(L, idx); |
| 420 | | if (ttislcf(o)) return fvalue(o); |
| 421 | | else if (ttisCclosure(o)) |
| 422 | | return clCvalue(o)->f; |
| 423 | | else return NULL; /* not a C function */ |
| 419 | StkId o = index2addr(L, idx); |
| 420 | if (ttislcf(o)) return fvalue(o); |
| 421 | else if (ttisCclosure(o)) |
| 422 | return clCvalue(o)->f; |
| 423 | else return NULL; /* not a C function */ |
| 424 | 424 | } |
| 425 | 425 | |
| 426 | 426 | |
| 427 | 427 | LUA_API void *lua_touserdata (lua_State *L, int idx) { |
| 428 | | StkId o = index2addr(L, idx); |
| 429 | | switch (ttypenv(o)) { |
| 430 | | case LUA_TUSERDATA: return (rawuvalue(o) + 1); |
| 431 | | case LUA_TLIGHTUSERDATA: return pvalue(o); |
| 432 | | default: return NULL; |
| 433 | | } |
| 428 | StkId o = index2addr(L, idx); |
| 429 | switch (ttypenv(o)) { |
| 430 | case LUA_TUSERDATA: return (rawuvalue(o) + 1); |
| 431 | case LUA_TLIGHTUSERDATA: return pvalue(o); |
| 432 | default: return NULL; |
| 433 | } |
| 434 | 434 | } |
| 435 | 435 | |
| 436 | 436 | |
| 437 | 437 | LUA_API lua_State *lua_tothread (lua_State *L, int idx) { |
| 438 | | StkId o = index2addr(L, idx); |
| 439 | | return (!ttisthread(o)) ? NULL : thvalue(o); |
| 438 | StkId o = index2addr(L, idx); |
| 439 | return (!ttisthread(o)) ? NULL : thvalue(o); |
| 440 | 440 | } |
| 441 | 441 | |
| 442 | 442 | |
| 443 | 443 | LUA_API const void *lua_topointer (lua_State *L, int idx) { |
| 444 | | StkId o = index2addr(L, idx); |
| 445 | | switch (ttype(o)) { |
| 446 | | case LUA_TTABLE: return hvalue(o); |
| 447 | | case LUA_TLCL: return clLvalue(o); |
| 448 | | case LUA_TCCL: return clCvalue(o); |
| 449 | | case LUA_TLCF: return cast(void *, cast(size_t, fvalue(o))); |
| 450 | | case LUA_TTHREAD: return thvalue(o); |
| 451 | | case LUA_TUSERDATA: |
| 452 | | case LUA_TLIGHTUSERDATA: |
| 453 | | return lua_touserdata(L, idx); |
| 454 | | default: return NULL; |
| 455 | | } |
| 444 | StkId o = index2addr(L, idx); |
| 445 | switch (ttype(o)) { |
| 446 | case LUA_TTABLE: return hvalue(o); |
| 447 | case LUA_TLCL: return clLvalue(o); |
| 448 | case LUA_TCCL: return clCvalue(o); |
| 449 | case LUA_TLCF: return cast(void *, cast(size_t, fvalue(o))); |
| 450 | case LUA_TTHREAD: return thvalue(o); |
| 451 | case LUA_TUSERDATA: |
| 452 | case LUA_TLIGHTUSERDATA: |
| 453 | return lua_touserdata(L, idx); |
| 454 | default: return NULL; |
| 455 | } |
| 456 | 456 | } |
| 457 | 457 | |
| 458 | 458 | |
| r30857 | r30858 | |
| 463 | 463 | |
| 464 | 464 | |
| 465 | 465 | LUA_API void lua_pushnil (lua_State *L) { |
| 466 | | lua_lock(L); |
| 467 | | setnilvalue(L->top); |
| 468 | | api_incr_top(L); |
| 469 | | lua_unlock(L); |
| 466 | lua_lock(L); |
| 467 | setnilvalue(L->top); |
| 468 | api_incr_top(L); |
| 469 | lua_unlock(L); |
| 470 | 470 | } |
| 471 | 471 | |
| 472 | 472 | |
| 473 | 473 | LUA_API void lua_pushnumber (lua_State *L, lua_Number n) { |
| 474 | | lua_lock(L); |
| 475 | | setnvalue(L->top, n); |
| 476 | | luai_checknum(L, L->top, |
| 477 | | luaG_runerror(L, "C API - attempt to push a signaling NaN")); |
| 478 | | api_incr_top(L); |
| 479 | | lua_unlock(L); |
| 474 | lua_lock(L); |
| 475 | setnvalue(L->top, n); |
| 476 | luai_checknum(L, L->top, |
| 477 | luaG_runerror(L, "C API - attempt to push a signaling NaN")); |
| 478 | api_incr_top(L); |
| 479 | lua_unlock(L); |
| 480 | 480 | } |
| 481 | 481 | |
| 482 | 482 | |
| 483 | 483 | LUA_API void lua_pushinteger (lua_State *L, lua_Integer n) { |
| 484 | | lua_lock(L); |
| 485 | | setnvalue(L->top, cast_num(n)); |
| 486 | | api_incr_top(L); |
| 487 | | lua_unlock(L); |
| 484 | lua_lock(L); |
| 485 | setnvalue(L->top, cast_num(n)); |
| 486 | api_incr_top(L); |
| 487 | lua_unlock(L); |
| 488 | 488 | } |
| 489 | 489 | |
| 490 | 490 | |
| 491 | 491 | LUA_API void lua_pushunsigned (lua_State *L, lua_Unsigned u) { |
| 492 | | lua_Number n; |
| 493 | | lua_lock(L); |
| 494 | | n = lua_unsigned2number(u); |
| 495 | | setnvalue(L->top, n); |
| 496 | | api_incr_top(L); |
| 497 | | lua_unlock(L); |
| 492 | lua_Number n; |
| 493 | lua_lock(L); |
| 494 | n = lua_unsigned2number(u); |
| 495 | setnvalue(L->top, n); |
| 496 | api_incr_top(L); |
| 497 | lua_unlock(L); |
| 498 | 498 | } |
| 499 | 499 | |
| 500 | 500 | |
| 501 | 501 | LUA_API const char *lua_pushlstring (lua_State *L, const char *s, size_t len) { |
| 502 | | TString *ts; |
| 503 | | lua_lock(L); |
| 504 | | luaC_checkGC(L); |
| 505 | | ts = luaS_newlstr(L, s, len); |
| 506 | | setsvalue2s(L, L->top, ts); |
| 507 | | api_incr_top(L); |
| 508 | | lua_unlock(L); |
| 509 | | return getstr(ts); |
| 502 | TString *ts; |
| 503 | lua_lock(L); |
| 504 | luaC_checkGC(L); |
| 505 | ts = luaS_newlstr(L, s, len); |
| 506 | setsvalue2s(L, L->top, ts); |
| 507 | api_incr_top(L); |
| 508 | lua_unlock(L); |
| 509 | return getstr(ts); |
| 510 | 510 | } |
| 511 | 511 | |
| 512 | 512 | |
| 513 | 513 | LUA_API const char *lua_pushstring (lua_State *L, const char *s) { |
| 514 | | if (s == NULL) { |
| 515 | | lua_pushnil(L); |
| 516 | | return NULL; |
| 517 | | } |
| 518 | | else { |
| 519 | | TString *ts; |
| 520 | | lua_lock(L); |
| 521 | | luaC_checkGC(L); |
| 522 | | ts = luaS_new(L, s); |
| 523 | | setsvalue2s(L, L->top, ts); |
| 524 | | api_incr_top(L); |
| 525 | | lua_unlock(L); |
| 526 | | return getstr(ts); |
| 527 | | } |
| 514 | if (s == NULL) { |
| 515 | lua_pushnil(L); |
| 516 | return NULL; |
| 517 | } |
| 518 | else { |
| 519 | TString *ts; |
| 520 | lua_lock(L); |
| 521 | luaC_checkGC(L); |
| 522 | ts = luaS_new(L, s); |
| 523 | setsvalue2s(L, L->top, ts); |
| 524 | api_incr_top(L); |
| 525 | lua_unlock(L); |
| 526 | return getstr(ts); |
| 527 | } |
| 528 | 528 | } |
| 529 | 529 | |
| 530 | 530 | |
| 531 | 531 | LUA_API const char *lua_pushvfstring (lua_State *L, const char *fmt, |
| 532 | | va_list argp) { |
| 533 | | const char *ret; |
| 534 | | lua_lock(L); |
| 535 | | luaC_checkGC(L); |
| 536 | | ret = luaO_pushvfstring(L, fmt, argp); |
| 537 | | lua_unlock(L); |
| 538 | | return ret; |
| 532 | va_list argp) { |
| 533 | const char *ret; |
| 534 | lua_lock(L); |
| 535 | luaC_checkGC(L); |
| 536 | ret = luaO_pushvfstring(L, fmt, argp); |
| 537 | lua_unlock(L); |
| 538 | return ret; |
| 539 | 539 | } |
| 540 | 540 | |
| 541 | 541 | |
| 542 | 542 | LUA_API const char *lua_pushfstring (lua_State *L, const char *fmt, ...) { |
| 543 | | const char *ret; |
| 544 | | va_list argp; |
| 545 | | lua_lock(L); |
| 546 | | luaC_checkGC(L); |
| 547 | | va_start(argp, fmt); |
| 548 | | ret = luaO_pushvfstring(L, fmt, argp); |
| 549 | | va_end(argp); |
| 550 | | lua_unlock(L); |
| 551 | | return ret; |
| 543 | const char *ret; |
| 544 | va_list argp; |
| 545 | lua_lock(L); |
| 546 | luaC_checkGC(L); |
| 547 | va_start(argp, fmt); |
| 548 | ret = luaO_pushvfstring(L, fmt, argp); |
| 549 | va_end(argp); |
| 550 | lua_unlock(L); |
| 551 | return ret; |
| 552 | 552 | } |
| 553 | 553 | |
| 554 | 554 | |
| 555 | 555 | LUA_API void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n) { |
| 556 | | lua_lock(L); |
| 557 | | if (n == 0) { |
| 558 | | setfvalue(L->top, fn); |
| 559 | | } |
| 560 | | else { |
| 561 | | Closure *cl; |
| 562 | | api_checknelems(L, n); |
| 563 | | api_check(L, n <= MAXUPVAL, "upvalue index too large"); |
| 564 | | luaC_checkGC(L); |
| 565 | | cl = luaF_newCclosure(L, n); |
| 566 | | cl->c.f = fn; |
| 567 | | L->top -= n; |
| 568 | | while (n--) |
| 569 | | setobj2n(L, &cl->c.upvalue[n], L->top + n); |
| 570 | | setclCvalue(L, L->top, cl); |
| 571 | | } |
| 572 | | api_incr_top(L); |
| 573 | | lua_unlock(L); |
| 556 | lua_lock(L); |
| 557 | if (n == 0) { |
| 558 | setfvalue(L->top, fn); |
| 559 | } |
| 560 | else { |
| 561 | Closure *cl; |
| 562 | api_checknelems(L, n); |
| 563 | api_check(L, n <= MAXUPVAL, "upvalue index too large"); |
| 564 | luaC_checkGC(L); |
| 565 | cl = luaF_newCclosure(L, n); |
| 566 | cl->c.f = fn; |
| 567 | L->top -= n; |
| 568 | while (n--) |
| 569 | setobj2n(L, &cl->c.upvalue[n], L->top + n); |
| 570 | setclCvalue(L, L->top, cl); |
| 571 | } |
| 572 | api_incr_top(L); |
| 573 | lua_unlock(L); |
| 574 | 574 | } |
| 575 | 575 | |
| 576 | 576 | |
| 577 | 577 | LUA_API void lua_pushboolean (lua_State *L, int b) { |
| 578 | | lua_lock(L); |
| 579 | | setbvalue(L->top, (b != 0)); /* ensure that true is 1 */ |
| 580 | | api_incr_top(L); |
| 581 | | lua_unlock(L); |
| 578 | lua_lock(L); |
| 579 | setbvalue(L->top, (b != 0)); /* ensure that true is 1 */ |
| 580 | api_incr_top(L); |
| 581 | lua_unlock(L); |
| 582 | 582 | } |
| 583 | 583 | |
| 584 | 584 | |
| 585 | 585 | LUA_API void lua_pushlightuserdata (lua_State *L, void *p) { |
| 586 | | lua_lock(L); |
| 587 | | setpvalue(L->top, p); |
| 588 | | api_incr_top(L); |
| 589 | | lua_unlock(L); |
| 586 | lua_lock(L); |
| 587 | setpvalue(L->top, p); |
| 588 | api_incr_top(L); |
| 589 | lua_unlock(L); |
| 590 | 590 | } |
| 591 | 591 | |
| 592 | 592 | |
| 593 | 593 | LUA_API int lua_pushthread (lua_State *L) { |
| 594 | | lua_lock(L); |
| 595 | | setthvalue(L, L->top, L); |
| 596 | | api_incr_top(L); |
| 597 | | lua_unlock(L); |
| 598 | | return (G(L)->mainthread == L); |
| 594 | lua_lock(L); |
| 595 | setthvalue(L, L->top, L); |
| 596 | api_incr_top(L); |
| 597 | lua_unlock(L); |
| 598 | return (G(L)->mainthread == L); |
| 599 | 599 | } |
| 600 | 600 | |
| 601 | 601 | |
| r30857 | r30858 | |
| 606 | 606 | |
| 607 | 607 | |
| 608 | 608 | LUA_API void lua_getglobal (lua_State *L, const char *var) { |
| 609 | | Table *reg = hvalue(&G(L)->l_registry); |
| 610 | | const TValue *gt; /* global table */ |
| 611 | | lua_lock(L); |
| 612 | | gt = luaH_getint(reg, LUA_RIDX_GLOBALS); |
| 613 | | setsvalue2s(L, L->top++, luaS_new(L, var)); |
| 614 | | luaV_gettable(L, gt, L->top - 1, L->top - 1); |
| 615 | | lua_unlock(L); |
| 609 | Table *reg = hvalue(&G(L)->l_registry); |
| 610 | const TValue *gt; /* global table */ |
| 611 | lua_lock(L); |
| 612 | gt = luaH_getint(reg, LUA_RIDX_GLOBALS); |
| 613 | setsvalue2s(L, L->top++, luaS_new(L, var)); |
| 614 | luaV_gettable(L, gt, L->top - 1, L->top - 1); |
| 615 | lua_unlock(L); |
| 616 | 616 | } |
| 617 | 617 | |
| 618 | 618 | |
| 619 | 619 | LUA_API void lua_gettable (lua_State *L, int idx) { |
| 620 | | StkId t; |
| 621 | | lua_lock(L); |
| 622 | | t = index2addr(L, idx); |
| 623 | | luaV_gettable(L, t, L->top - 1, L->top - 1); |
| 624 | | lua_unlock(L); |
| 620 | StkId t; |
| 621 | lua_lock(L); |
| 622 | t = index2addr(L, idx); |
| 623 | luaV_gettable(L, t, L->top - 1, L->top - 1); |
| 624 | lua_unlock(L); |
| 625 | 625 | } |
| 626 | 626 | |
| 627 | 627 | |
| 628 | 628 | LUA_API void lua_getfield (lua_State *L, int idx, const char *k) { |
| 629 | | StkId t; |
| 630 | | lua_lock(L); |
| 631 | | t = index2addr(L, idx); |
| 632 | | setsvalue2s(L, L->top, luaS_new(L, k)); |
| 633 | | api_incr_top(L); |
| 634 | | luaV_gettable(L, t, L->top - 1, L->top - 1); |
| 635 | | lua_unlock(L); |
| 629 | StkId t; |
| 630 | lua_lock(L); |
| 631 | t = index2addr(L, idx); |
| 632 | setsvalue2s(L, L->top, luaS_new(L, k)); |
| 633 | api_incr_top(L); |
| 634 | luaV_gettable(L, t, L->top - 1, L->top - 1); |
| 635 | lua_unlock(L); |
| 636 | 636 | } |
| 637 | 637 | |
| 638 | 638 | |
| 639 | 639 | LUA_API void lua_rawget (lua_State *L, int idx) { |
| 640 | | StkId t; |
| 641 | | lua_lock(L); |
| 642 | | t = index2addr(L, idx); |
| 643 | | api_check(L, ttistable(t), "table expected"); |
| 644 | | setobj2s(L, L->top - 1, luaH_get(hvalue(t), L->top - 1)); |
| 645 | | lua_unlock(L); |
| 640 | StkId t; |
| 641 | lua_lock(L); |
| 642 | t = index2addr(L, idx); |
| 643 | api_check(L, ttistable(t), "table expected"); |
| 644 | setobj2s(L, L->top - 1, luaH_get(hvalue(t), L->top - 1)); |
| 645 | lua_unlock(L); |
| 646 | 646 | } |
| 647 | 647 | |
| 648 | 648 | |
| 649 | 649 | LUA_API void lua_rawgeti (lua_State *L, int idx, int n) { |
| 650 | | StkId t; |
| 651 | | lua_lock(L); |
| 652 | | t = index2addr(L, idx); |
| 653 | | api_check(L, ttistable(t), "table expected"); |
| 654 | | setobj2s(L, L->top, luaH_getint(hvalue(t), n)); |
| 655 | | api_incr_top(L); |
| 656 | | lua_unlock(L); |
| 650 | StkId t; |
| 651 | lua_lock(L); |
| 652 | t = index2addr(L, idx); |
| 653 | api_check(L, ttistable(t), "table expected"); |
| 654 | setobj2s(L, L->top, luaH_getint(hvalue(t), n)); |
| 655 | api_incr_top(L); |
| 656 | lua_unlock(L); |
| 657 | 657 | } |
| 658 | 658 | |
| 659 | 659 | |
| 660 | 660 | LUA_API void lua_rawgetp (lua_State *L, int idx, const void *p) { |
| 661 | | StkId t; |
| 662 | | TValue k; |
| 663 | | lua_lock(L); |
| 664 | | t = index2addr(L, idx); |
| 665 | | api_check(L, ttistable(t), "table expected"); |
| 666 | | setpvalue(&k, cast(void *, p)); |
| 667 | | setobj2s(L, L->top, luaH_get(hvalue(t), &k)); |
| 668 | | api_incr_top(L); |
| 669 | | lua_unlock(L); |
| 661 | StkId t; |
| 662 | TValue k; |
| 663 | lua_lock(L); |
| 664 | t = index2addr(L, idx); |
| 665 | api_check(L, ttistable(t), "table expected"); |
| 666 | setpvalue(&k, cast(void *, p)); |
| 667 | setobj2s(L, L->top, luaH_get(hvalue(t), &k)); |
| 668 | api_incr_top(L); |
| 669 | lua_unlock(L); |
| 670 | 670 | } |
| 671 | 671 | |
| 672 | 672 | |
| 673 | 673 | LUA_API void lua_createtable (lua_State *L, int narray, int nrec) { |
| 674 | | Table *t; |
| 675 | | lua_lock(L); |
| 676 | | luaC_checkGC(L); |
| 677 | | t = luaH_new(L); |
| 678 | | sethvalue(L, L->top, t); |
| 679 | | api_incr_top(L); |
| 680 | | if (narray > 0 || nrec > 0) |
| 681 | | luaH_resize(L, t, narray, nrec); |
| 682 | | lua_unlock(L); |
| 674 | Table *t; |
| 675 | lua_lock(L); |
| 676 | luaC_checkGC(L); |
| 677 | t = luaH_new(L); |
| 678 | sethvalue(L, L->top, t); |
| 679 | api_incr_top(L); |
| 680 | if (narray > 0 || nrec > 0) |
| 681 | luaH_resize(L, t, narray, nrec); |
| 682 | lua_unlock(L); |
| 683 | 683 | } |
| 684 | 684 | |
| 685 | 685 | |
| 686 | 686 | LUA_API int lua_getmetatable (lua_State *L, int objindex) { |
| 687 | | const TValue *obj; |
| 688 | | Table *mt = NULL; |
| 689 | | int res; |
| 690 | | lua_lock(L); |
| 691 | | obj = index2addr(L, objindex); |
| 692 | | switch (ttypenv(obj)) { |
| 693 | | case LUA_TTABLE: |
| 694 | | mt = hvalue(obj)->metatable; |
| 695 | | break; |
| 696 | | case LUA_TUSERDATA: |
| 697 | | mt = uvalue(obj)->metatable; |
| 698 | | break; |
| 699 | | default: |
| 700 | | mt = G(L)->mt[ttypenv(obj)]; |
| 701 | | break; |
| 702 | | } |
| 703 | | if (mt == NULL) |
| 704 | | res = 0; |
| 705 | | else { |
| 706 | | sethvalue(L, L->top, mt); |
| 707 | | api_incr_top(L); |
| 708 | | res = 1; |
| 709 | | } |
| 710 | | lua_unlock(L); |
| 711 | | return res; |
| 687 | const TValue *obj; |
| 688 | Table *mt = NULL; |
| 689 | int res; |
| 690 | lua_lock(L); |
| 691 | obj = index2addr(L, objindex); |
| 692 | switch (ttypenv(obj)) { |
| 693 | case LUA_TTABLE: |
| 694 | mt = hvalue(obj)->metatable; |
| 695 | break; |
| 696 | case LUA_TUSERDATA: |
| 697 | mt = uvalue(obj)->metatable; |
| 698 | break; |
| 699 | default: |
| 700 | mt = G(L)->mt[ttypenv(obj)]; |
| 701 | break; |
| 702 | } |
| 703 | if (mt == NULL) |
| 704 | res = 0; |
| 705 | else { |
| 706 | sethvalue(L, L->top, mt); |
| 707 | api_incr_top(L); |
| 708 | res = 1; |
| 709 | } |
| 710 | lua_unlock(L); |
| 711 | return res; |
| 712 | 712 | } |
| 713 | 713 | |
| 714 | 714 | |
| 715 | 715 | LUA_API void lua_getuservalue (lua_State *L, int idx) { |
| 716 | | StkId o; |
| 717 | | lua_lock(L); |
| 718 | | o = index2addr(L, idx); |
| 719 | | api_check(L, ttisuserdata(o), "userdata expected"); |
| 720 | | if (uvalue(o)->env) { |
| 721 | | sethvalue(L, L->top, uvalue(o)->env); |
| 722 | | } else |
| 723 | | setnilvalue(L->top); |
| 724 | | api_incr_top(L); |
| 725 | | lua_unlock(L); |
| 716 | StkId o; |
| 717 | lua_lock(L); |
| 718 | o = index2addr(L, idx); |
| 719 | api_check(L, ttisuserdata(o), "userdata expected"); |
| 720 | if (uvalue(o)->env) { |
| 721 | sethvalue(L, L->top, uvalue(o)->env); |
| 722 | } else |
| 723 | setnilvalue(L->top); |
| 724 | api_incr_top(L); |
| 725 | lua_unlock(L); |
| 726 | 726 | } |
| 727 | 727 | |
| 728 | 728 | |
| r30857 | r30858 | |
| 732 | 732 | |
| 733 | 733 | |
| 734 | 734 | LUA_API void lua_setglobal (lua_State *L, const char *var) { |
| 735 | | Table *reg = hvalue(&G(L)->l_registry); |
| 736 | | const TValue *gt; /* global table */ |
| 737 | | lua_lock(L); |
| 738 | | api_checknelems(L, 1); |
| 739 | | gt = luaH_getint(reg, LUA_RIDX_GLOBALS); |
| 740 | | setsvalue2s(L, L->top++, luaS_new(L, var)); |
| 741 | | luaV_settable(L, gt, L->top - 1, L->top - 2); |
| 742 | | L->top -= 2; /* pop value and key */ |
| 743 | | lua_unlock(L); |
| 735 | Table *reg = hvalue(&G(L)->l_registry); |
| 736 | const TValue *gt; /* global table */ |
| 737 | lua_lock(L); |
| 738 | api_checknelems(L, 1); |
| 739 | gt = luaH_getint(reg, LUA_RIDX_GLOBALS); |
| 740 | setsvalue2s(L, L->top++, luaS_new(L, var)); |
| 741 | luaV_settable(L, gt, L->top - 1, L->top - 2); |
| 742 | L->top -= 2; /* pop value and key */ |
| 743 | lua_unlock(L); |
| 744 | 744 | } |
| 745 | 745 | |
| 746 | 746 | |
| 747 | 747 | LUA_API void lua_settable (lua_State *L, int idx) { |
| 748 | | StkId t; |
| 749 | | lua_lock(L); |
| 750 | | api_checknelems(L, 2); |
| 751 | | t = index2addr(L, idx); |
| 752 | | luaV_settable(L, t, L->top - 2, L->top - 1); |
| 753 | | L->top -= 2; /* pop index and value */ |
| 754 | | lua_unlock(L); |
| 748 | StkId t; |
| 749 | lua_lock(L); |
| 750 | api_checknelems(L, 2); |
| 751 | t = index2addr(L, idx); |
| 752 | luaV_settable(L, t, L->top - 2, L->top - 1); |
| 753 | L->top -= 2; /* pop index and value */ |
| 754 | lua_unlock(L); |
| 755 | 755 | } |
| 756 | 756 | |
| 757 | 757 | |
| 758 | 758 | LUA_API void lua_setfield (lua_State *L, int idx, const char *k) { |
| 759 | | StkId t; |
| 760 | | lua_lock(L); |
| 761 | | api_checknelems(L, 1); |
| 762 | | t = index2addr(L, idx); |
| 763 | | setsvalue2s(L, L->top++, luaS_new(L, k)); |
| 764 | | luaV_settable(L, t, L->top - 1, L->top - 2); |
| 765 | | L->top -= 2; /* pop value and key */ |
| 766 | | lua_unlock(L); |
| 759 | StkId t; |
| 760 | lua_lock(L); |
| 761 | api_checknelems(L, 1); |
| 762 | t = index2addr(L, idx); |
| 763 | setsvalue2s(L, L->top++, luaS_new(L, k)); |
| 764 | luaV_settable(L, t, L->top - 1, L->top - 2); |
| 765 | L->top -= 2; /* pop value and key */ |
| 766 | lua_unlock(L); |
| 767 | 767 | } |
| 768 | 768 | |
| 769 | 769 | |
| 770 | 770 | LUA_API void lua_rawset (lua_State *L, int idx) { |
| 771 | | StkId t; |
| 772 | | lua_lock(L); |
| 773 | | api_checknelems(L, 2); |
| 774 | | t = index2addr(L, idx); |
| 775 | | api_check(L, ttistable(t), "table expected"); |
| 776 | | setobj2t(L, luaH_set(L, hvalue(t), L->top-2), L->top-1); |
| 777 | | invalidateTMcache(hvalue(t)); |
| 778 | | luaC_barrierback(L, gcvalue(t), L->top-1); |
| 779 | | L->top -= 2; |
| 780 | | lua_unlock(L); |
| 771 | StkId t; |
| 772 | lua_lock(L); |
| 773 | api_checknelems(L, 2); |
| 774 | t = index2addr(L, idx); |
| 775 | api_check(L, ttistable(t), "table expected"); |
| 776 | setobj2t(L, luaH_set(L, hvalue(t), L->top-2), L->top-1); |
| 777 | invalidateTMcache(hvalue(t)); |
| 778 | luaC_barrierback(L, gcvalue(t), L->top-1); |
| 779 | L->top -= 2; |
| 780 | lua_unlock(L); |
| 781 | 781 | } |
| 782 | 782 | |
| 783 | 783 | |
| 784 | 784 | LUA_API void lua_rawseti (lua_State *L, int idx, int n) { |
| 785 | | StkId t; |
| 786 | | lua_lock(L); |
| 787 | | api_checknelems(L, 1); |
| 788 | | t = index2addr(L, idx); |
| 789 | | api_check(L, ttistable(t), "table expected"); |
| 790 | | luaH_setint(L, hvalue(t), n, L->top - 1); |
| 791 | | luaC_barrierback(L, gcvalue(t), L->top-1); |
| 792 | | L->top--; |
| 793 | | lua_unlock(L); |
| 785 | StkId t; |
| 786 | lua_lock(L); |
| 787 | api_checknelems(L, 1); |
| 788 | t = index2addr(L, idx); |
| 789 | api_check(L, ttistable(t), "table expected"); |
| 790 | luaH_setint(L, hvalue(t), n, L->top - 1); |
| 791 | luaC_barrierback(L, gcvalue(t), L->top-1); |
| 792 | L->top--; |
| 793 | lua_unlock(L); |
| 794 | 794 | } |
| 795 | 795 | |
| 796 | 796 | |
| 797 | 797 | LUA_API void lua_rawsetp (lua_State *L, int idx, const void *p) { |
| 798 | | StkId t; |
| 799 | | TValue k; |
| 800 | | lua_lock(L); |
| 801 | | api_checknelems(L, 1); |
| 802 | | t = index2addr(L, idx); |
| 803 | | api_check(L, ttistable(t), "table expected"); |
| 804 | | setpvalue(&k, cast(void *, p)); |
| 805 | | setobj2t(L, luaH_set(L, hvalue(t), &k), L->top - 1); |
| 806 | | luaC_barrierback(L, gcvalue(t), L->top - 1); |
| 807 | | L->top--; |
| 808 | | lua_unlock(L); |
| 798 | StkId t; |
| 799 | TValue k; |
| 800 | lua_lock(L); |
| 801 | api_checknelems(L, 1); |
| 802 | t = index2addr(L, idx); |
| 803 | api_check(L, ttistable(t), "table expected"); |
| 804 | setpvalue(&k, cast(void *, p)); |
| 805 | setobj2t(L, luaH_set(L, hvalue(t), &k), L->top - 1); |
| 806 | luaC_barrierback(L, gcvalue(t), L->top - 1); |
| 807 | L->top--; |
| 808 | lua_unlock(L); |
| 809 | 809 | } |
| 810 | 810 | |
| 811 | 811 | |
| 812 | 812 | LUA_API int lua_setmetatable (lua_State *L, int objindex) { |
| 813 | | TValue *obj; |
| 814 | | Table *mt; |
| 815 | | lua_lock(L); |
| 816 | | api_checknelems(L, 1); |
| 817 | | obj = index2addr(L, objindex); |
| 818 | | if (ttisnil(L->top - 1)) |
| 819 | | mt = NULL; |
| 820 | | else { |
| 821 | | api_check(L, ttistable(L->top - 1), "table expected"); |
| 822 | | mt = hvalue(L->top - 1); |
| 823 | | } |
| 824 | | switch (ttypenv(obj)) { |
| 825 | | case LUA_TTABLE: { |
| 826 | | hvalue(obj)->metatable = mt; |
| 827 | | if (mt) { |
| 828 | | luaC_objbarrierback(L, gcvalue(obj), mt); |
| 829 | | luaC_checkfinalizer(L, gcvalue(obj), mt); |
| 830 | | } |
| 831 | | break; |
| 832 | | } |
| 833 | | case LUA_TUSERDATA: { |
| 834 | | uvalue(obj)->metatable = mt; |
| 835 | | if (mt) { |
| 836 | | luaC_objbarrier(L, rawuvalue(obj), mt); |
| 837 | | luaC_checkfinalizer(L, gcvalue(obj), mt); |
| 838 | | } |
| 839 | | break; |
| 840 | | } |
| 841 | | default: { |
| 842 | | G(L)->mt[ttypenv(obj)] = mt; |
| 843 | | break; |
| 844 | | } |
| 845 | | } |
| 846 | | L->top--; |
| 847 | | lua_unlock(L); |
| 848 | | return 1; |
| 813 | TValue *obj; |
| 814 | Table *mt; |
| 815 | lua_lock(L); |
| 816 | api_checknelems(L, 1); |
| 817 | obj = index2addr(L, objindex); |
| 818 | if (ttisnil(L->top - 1)) |
| 819 | mt = NULL; |
| 820 | else { |
| 821 | api_check(L, ttistable(L->top - 1), "table expected"); |
| 822 | mt = hvalue(L->top - 1); |
| 823 | } |
| 824 | switch (ttypenv(obj)) { |
| 825 | case LUA_TTABLE: { |
| 826 | hvalue(obj)->metatable = mt; |
| 827 | if (mt) { |
| 828 | luaC_objbarrierback(L, gcvalue(obj), mt); |
| 829 | luaC_checkfinalizer(L, gcvalue(obj), mt); |
| 830 | } |
| 831 | break; |
| 832 | } |
| 833 | case LUA_TUSERDATA: { |
| 834 | uvalue(obj)->metatable = mt; |
| 835 | if (mt) { |
| 836 | luaC_objbarrier(L, rawuvalue(obj), mt); |
| 837 | luaC_checkfinalizer(L, gcvalue(obj), mt); |
| 838 | } |
| 839 | break; |
| 840 | } |
| 841 | default: { |
| 842 | G(L)->mt[ttypenv(obj)] = mt; |
| 843 | break; |
| 844 | } |
| 845 | } |
| 846 | L->top--; |
| 847 | lua_unlock(L); |
| 848 | return 1; |
| 849 | 849 | } |
| 850 | 850 | |
| 851 | 851 | |
| 852 | 852 | LUA_API void lua_setuservalue (lua_State *L, int idx) { |
| 853 | | StkId o; |
| 854 | | lua_lock(L); |
| 855 | | api_checknelems(L, 1); |
| 856 | | o = index2addr(L, idx); |
| 857 | | api_check(L, ttisuserdata(o), "userdata expected"); |
| 858 | | if (ttisnil(L->top - 1)) |
| 859 | | uvalue(o)->env = NULL; |
| 860 | | else { |
| 861 | | api_check(L, ttistable(L->top - 1), "table expected"); |
| 862 | | uvalue(o)->env = hvalue(L->top - 1); |
| 863 | | luaC_objbarrier(L, gcvalue(o), hvalue(L->top - 1)); |
| 864 | | } |
| 865 | | L->top--; |
| 866 | | lua_unlock(L); |
| 853 | StkId o; |
| 854 | lua_lock(L); |
| 855 | api_checknelems(L, 1); |
| 856 | o = index2addr(L, idx); |
| 857 | api_check(L, ttisuserdata(o), "userdata expected"); |
| 858 | if (ttisnil(L->top - 1)) |
| 859 | uvalue(o)->env = NULL; |
| 860 | else { |
| 861 | api_check(L, ttistable(L->top - 1), "table expected"); |
| 862 | uvalue(o)->env = hvalue(L->top - 1); |
| 863 | luaC_objbarrier(L, gcvalue(o), hvalue(L->top - 1)); |
| 864 | } |
| 865 | L->top--; |
| 866 | lua_unlock(L); |
| 867 | 867 | } |
| 868 | 868 | |
| 869 | 869 | |
| r30857 | r30858 | |
| 873 | 873 | |
| 874 | 874 | |
| 875 | 875 | #define checkresults(L,na,nr) \ |
| 876 | | api_check(L, (nr) == LUA_MULTRET || (L->ci->top - L->top >= (nr) - (na)), \ |
| 876 | api_check(L, (nr) == LUA_MULTRET || (L->ci->top - L->top >= (nr) - (na)), \ |
| 877 | 877 | "results from function overflow current stack size") |
| 878 | 878 | |
| 879 | 879 | |
| 880 | 880 | LUA_API int lua_getctx (lua_State *L, int *ctx) { |
| 881 | | if (L->ci->callstatus & CIST_YIELDED) { |
| 882 | | if (ctx) *ctx = L->ci->u.c.ctx; |
| 883 | | return L->ci->u.c.status; |
| 884 | | } |
| 885 | | else return LUA_OK; |
| 881 | if (L->ci->callstatus & CIST_YIELDED) { |
| 882 | if (ctx) *ctx = L->ci->u.c.ctx; |
| 883 | return L->ci->u.c.status; |
| 884 | } |
| 885 | else return LUA_OK; |
| 886 | 886 | } |
| 887 | 887 | |
| 888 | 888 | |
| 889 | 889 | LUA_API void lua_callk (lua_State *L, int nargs, int nresults, int ctx, |
| 890 | | lua_CFunction k) { |
| 891 | | StkId func; |
| 892 | | lua_lock(L); |
| 893 | | api_check(L, k == NULL || !isLua(L->ci), |
| 894 | | "cannot use continuations inside hooks"); |
| 895 | | api_checknelems(L, nargs+1); |
| 896 | | api_check(L, L->status == LUA_OK, "cannot do calls on non-normal thread"); |
| 897 | | checkresults(L, nargs, nresults); |
| 898 | | func = L->top - (nargs+1); |
| 899 | | if (k != NULL && L->nny == 0) { /* need to prepare continuation? */ |
| 900 | | L->ci->u.c.k = k; /* save continuation */ |
| 901 | | L->ci->u.c.ctx = ctx; /* save context */ |
| 902 | | luaD_call(L, func, nresults, 1); /* do the call */ |
| 903 | | } |
| 904 | | else /* no continuation or no yieldable */ |
| 905 | | luaD_call(L, func, nresults, 0); /* just do the call */ |
| 906 | | adjustresults(L, nresults); |
| 907 | | lua_unlock(L); |
| 890 | lua_CFunction k) { |
| 891 | StkId func; |
| 892 | lua_lock(L); |
| 893 | api_check(L, k == NULL || !isLua(L->ci), |
| 894 | "cannot use continuations inside hooks"); |
| 895 | api_checknelems(L, nargs+1); |
| 896 | api_check(L, L->status == LUA_OK, "cannot do calls on non-normal thread"); |
| 897 | checkresults(L, nargs, nresults); |
| 898 | func = L->top - (nargs+1); |
| 899 | if (k != NULL && L->nny == 0) { /* need to prepare continuation? */ |
| 900 | L->ci->u.c.k = k; /* save continuation */ |
| 901 | L->ci->u.c.ctx = ctx; /* save context */ |
| 902 | luaD_call(L, func, nresults, 1); /* do the call */ |
| 903 | } |
| 904 | else /* no continuation or no yieldable */ |
| 905 | luaD_call(L, func, nresults, 0); /* just do the call */ |
| 906 | adjustresults(L, nresults); |
| 907 | lua_unlock(L); |
| 908 | 908 | } |
| 909 | 909 | |
| 910 | 910 | |
| r30857 | r30858 | |
| 913 | 913 | ** Execute a protected call. |
| 914 | 914 | */ |
| 915 | 915 | struct CallS { /* data to `f_call' */ |
| 916 | | StkId func; |
| 917 | | int nresults; |
| 916 | StkId func; |
| 917 | int nresults; |
| 918 | 918 | }; |
| 919 | 919 | |
| 920 | 920 | |
| 921 | 921 | static void f_call (lua_State *L, void *ud) { |
| 922 | | struct CallS *c = cast(struct CallS *, ud); |
| 923 | | luaD_call(L, c->func, c->nresults, 0); |
| 922 | struct CallS *c = cast(struct CallS *, ud); |
| 923 | luaD_call(L, c->func, c->nresults, 0); |
| 924 | 924 | } |
| 925 | 925 | |
| 926 | 926 | |
| 927 | 927 | |
| 928 | 928 | LUA_API int lua_pcallk (lua_State *L, int nargs, int nresults, int errfunc, |
| 929 | | int ctx, lua_CFunction k) { |
| 930 | | struct CallS c; |
| 931 | | int status; |
| 932 | | ptrdiff_t func; |
| 933 | | lua_lock(L); |
| 934 | | api_check(L, k == NULL || !isLua(L->ci), |
| 935 | | "cannot use continuations inside hooks"); |
| 936 | | api_checknelems(L, nargs+1); |
| 937 | | api_check(L, L->status == LUA_OK, "cannot do calls on non-normal thread"); |
| 938 | | checkresults(L, nargs, nresults); |
| 939 | | if (errfunc == 0) |
| 940 | | func = 0; |
| 941 | | else { |
| 942 | | StkId o = index2addr(L, errfunc); |
| 943 | | api_checkstackindex(L, errfunc, o); |
| 944 | | func = savestack(L, o); |
| 945 | | } |
| 946 | | c.func = L->top - (nargs+1); /* function to be called */ |
| 947 | | if (k == NULL || L->nny > 0) { /* no continuation or no yieldable? */ |
| 948 | | c.nresults = nresults; /* do a 'conventional' protected call */ |
| 949 | | status = luaD_pcall(L, f_call, &c, savestack(L, c.func), func); |
| 950 | | } |
| 951 | | else { /* prepare continuation (call is already protected by 'resume') */ |
| 952 | | CallInfo *ci = L->ci; |
| 953 | | ci->u.c.k = k; /* save continuation */ |
| 954 | | ci->u.c.ctx = ctx; /* save context */ |
| 955 | | /* save information for error recovery */ |
| 956 | | ci->extra = savestack(L, c.func); |
| 957 | | ci->u.c.old_allowhook = L->allowhook; |
| 958 | | ci->u.c.old_errfunc = L->errfunc; |
| 959 | | L->errfunc = func; |
| 960 | | /* mark that function may do error recovery */ |
| 961 | | ci->callstatus |= CIST_YPCALL; |
| 962 | | luaD_call(L, c.func, nresults, 1); /* do the call */ |
| 963 | | ci->callstatus &= ~CIST_YPCALL; |
| 964 | | L->errfunc = ci->u.c.old_errfunc; |
| 965 | | status = LUA_OK; /* if it is here, there were no errors */ |
| 966 | | } |
| 967 | | adjustresults(L, nresults); |
| 968 | | lua_unlock(L); |
| 969 | | return status; |
| 929 | int ctx, lua_CFunction k) { |
| 930 | struct CallS c; |
| 931 | int status; |
| 932 | ptrdiff_t func; |
| 933 | lua_lock(L); |
| 934 | api_check(L, k == NULL || !isLua(L->ci), |
| 935 | "cannot use continuations inside hooks"); |
| 936 | api_checknelems(L, nargs+1); |
| 937 | api_check(L, L->status == LUA_OK, "cannot do calls on non-normal thread"); |
| 938 | checkresults(L, nargs, nresults); |
| 939 | if (errfunc == 0) |
| 940 | func = 0; |
| 941 | else { |
| 942 | StkId o = index2addr(L, errfunc); |
| 943 | api_checkstackindex(L, errfunc, o); |
| 944 | func = savestack(L, o); |
| 945 | } |
| 946 | c.func = L->top - (nargs+1); /* function to be called */ |
| 947 | if (k == NULL || L->nny > 0) { /* no continuation or no yieldable? */ |
| 948 | c.nresults = nresults; /* do a 'conventional' protected call */ |
| 949 | status = luaD_pcall(L, f_call, &c, savestack(L, c.func), func); |
| 950 | } |
| 951 | else { /* prepare continuation (call is already protected by 'resume') */ |
| 952 | CallInfo *ci = L->ci; |
| 953 | ci->u.c.k = k; /* save continuation */ |
| 954 | ci->u.c.ctx = ctx; /* save context */ |
| 955 | /* save information for error recovery */ |
| 956 | ci->extra = savestack(L, c.func); |
| 957 | ci->u.c.old_allowhook = L->allowhook; |
| 958 | ci->u.c.old_errfunc = L->errfunc; |
| 959 | L->errfunc = func; |
| 960 | /* mark that function may do error recovery */ |
| 961 | ci->callstatus |= CIST_YPCALL; |
| 962 | luaD_call(L, c.func, nresults, 1); /* do the call */ |
| 963 | ci->callstatus &= ~CIST_YPCALL; |
| 964 | L->errfunc = ci->u.c.old_errfunc; |
| 965 | status = LUA_OK; /* if it is here, there were no errors */ |
| 966 | } |
| 967 | adjustresults(L, nresults); |
| 968 | lua_unlock(L); |
| 969 | return status; |
| 970 | 970 | } |
| 971 | 971 | |
| 972 | 972 | |
| 973 | 973 | LUA_API int lua_load (lua_State *L, lua_Reader reader, void *data, |
| 974 | | const char *chunkname, const char *mode) { |
| 975 | | ZIO z; |
| 976 | | int status; |
| 977 | | lua_lock(L); |
| 978 | | if (!chunkname) chunkname = "?"; |
| 979 | | luaZ_init(L, &z, reader, data); |
| 980 | | status = luaD_protectedparser(L, &z, chunkname, mode); |
| 981 | | if (status == LUA_OK) { /* no errors? */ |
| 982 | | LClosure *f = clLvalue(L->top - 1); /* get newly created function */ |
| 983 | | if (f->nupvalues == 1) { /* does it have one upvalue? */ |
| 984 | | /* get global table from registry */ |
| 985 | | Table *reg = hvalue(&G(L)->l_registry); |
| 986 | | const TValue *gt = luaH_getint(reg, LUA_RIDX_GLOBALS); |
| 987 | | /* set global table as 1st upvalue of 'f' (may be LUA_ENV) */ |
| 988 | | setobj(L, f->upvals[0]->v, gt); |
| 989 | | luaC_barrier(L, f->upvals[0], gt); |
| 990 | | } |
| 991 | | } |
| 992 | | lua_unlock(L); |
| 993 | | return status; |
| 974 | const char *chunkname, const char *mode) { |
| 975 | ZIO z; |
| 976 | int status; |
| 977 | lua_lock(L); |
| 978 | if (!chunkname) chunkname = "?"; |
| 979 | luaZ_init(L, &z, reader, data); |
| 980 | status = luaD_protectedparser(L, &z, chunkname, mode); |
| 981 | if (status == LUA_OK) { /* no errors? */ |
| 982 | LClosure *f = clLvalue(L->top - 1); /* get newly created function */ |
| 983 | if (f->nupvalues == 1) { /* does it have one upvalue? */ |
| 984 | /* get global table from registry */ |
| 985 | Table *reg = hvalue(&G(L)->l_registry); |
| 986 | const TValue *gt = luaH_getint(reg, LUA_RIDX_GLOBALS); |
| 987 | /* set global table as 1st upvalue of 'f' (may be LUA_ENV) */ |
| 988 | setobj(L, f->upvals[0]->v, gt); |
| 989 | luaC_barrier(L, f->upvals[0], gt); |
| 990 | } |
| 991 | } |
| 992 | lua_unlock(L); |
| 993 | return status; |
| 994 | 994 | } |
| 995 | 995 | |
| 996 | 996 | |
| 997 | 997 | LUA_API int lua_dump (lua_State *L, lua_Writer writer, void *data) { |
| 998 | | int status; |
| 999 | | TValue *o; |
| 1000 | | lua_lock(L); |
| 1001 | | api_checknelems(L, 1); |
| 1002 | | o = L->top - 1; |
| 1003 | | if (isLfunction(o)) |
| 1004 | | status = luaU_dump(L, getproto(o), writer, data, 0); |
| 1005 | | else |
| 1006 | | status = 1; |
| 1007 | | lua_unlock(L); |
| 1008 | | return status; |
| 998 | int status; |
| 999 | TValue *o; |
| 1000 | lua_lock(L); |
| 1001 | api_checknelems(L, 1); |
| 1002 | o = L->top - 1; |
| 1003 | if (isLfunction(o)) |
| 1004 | status = luaU_dump(L, getproto(o), writer, data, 0); |
| 1005 | else |
| 1006 | status = 1; |
| 1007 | lua_unlock(L); |
| 1008 | return status; |
| 1009 | 1009 | } |
| 1010 | 1010 | |
| 1011 | 1011 | |
| 1012 | 1012 | LUA_API int lua_status (lua_State *L) { |
| 1013 | | return L->status; |
| 1013 | return L->status; |
| 1014 | 1014 | } |
| 1015 | 1015 | |
| 1016 | 1016 | |
| r30857 | r30858 | |
| 1019 | 1019 | */ |
| 1020 | 1020 | |
| 1021 | 1021 | LUA_API int lua_gc (lua_State *L, int what, int data) { |
| 1022 | | int res = 0; |
| 1023 | | global_State *g; |
| 1024 | | lua_lock(L); |
| 1025 | | g = G(L); |
| 1026 | | switch (what) { |
| 1027 | | case LUA_GCSTOP: { |
| 1028 | | g->gcrunning = 0; |
| 1029 | | break; |
| 1030 | | } |
| 1031 | | case LUA_GCRESTART: { |
| 1032 | | luaE_setdebt(g, 0); |
| 1033 | | g->gcrunning = 1; |
| 1034 | | break; |
| 1035 | | } |
| 1036 | | case LUA_GCCOLLECT: { |
| 1037 | | luaC_fullgc(L, 0); |
| 1038 | | break; |
| 1039 | | } |
| 1040 | | case LUA_GCCOUNT: { |
| 1041 | | /* GC values are expressed in Kbytes: #bytes/2^10 */ |
| 1042 | | res = cast_int(gettotalbytes(g) >> 10); |
| 1043 | | break; |
| 1044 | | } |
| 1045 | | case LUA_GCCOUNTB: { |
| 1046 | | res = cast_int(gettotalbytes(g) & 0x3ff); |
| 1047 | | break; |
| 1048 | | } |
| 1049 | | case LUA_GCSTEP: { |
| 1050 | | if (g->gckind == KGC_GEN) { /* generational mode? */ |
| 1051 | | res = (g->GCestimate == 0); /* true if it will do major collection */ |
| 1052 | | luaC_forcestep(L); /* do a single step */ |
| 1053 | | } |
| 1054 | | else { |
| 1055 | | lu_mem debt = cast(lu_mem, data) * 1024 - GCSTEPSIZE; |
| 1056 | | if (g->gcrunning) |
| 1057 | | debt += g->GCdebt; /* include current debt */ |
| 1058 | | luaE_setdebt(g, debt); |
| 1059 | | luaC_forcestep(L); |
| 1060 | | if (g->gcstate == GCSpause) /* end of cycle? */ |
| 1061 | | res = 1; /* signal it */ |
| 1062 | | } |
| 1063 | | break; |
| 1064 | | } |
| 1065 | | case LUA_GCSETPAUSE: { |
| 1066 | | res = g->gcpause; |
| 1067 | | g->gcpause = data; |
| 1068 | | break; |
| 1069 | | } |
| 1070 | | case LUA_GCSETMAJORINC: { |
| 1071 | | res = g->gcmajorinc; |
| 1072 | | g->gcmajorinc = data; |
| 1073 | | break; |
| 1074 | | } |
| 1075 | | case LUA_GCSETSTEPMUL: { |
| 1076 | | res = g->gcstepmul; |
| 1077 | | g->gcstepmul = data; |
| 1078 | | break; |
| 1079 | | } |
| 1080 | | case LUA_GCISRUNNING: { |
| 1081 | | res = g->gcrunning; |
| 1082 | | break; |
| 1083 | | } |
| 1084 | | case LUA_GCGEN: { /* change collector to generational mode */ |
| 1085 | | luaC_changemode(L, KGC_GEN); |
| 1086 | | break; |
| 1087 | | } |
| 1088 | | case LUA_GCINC: { /* change collector to incremental mode */ |
| 1089 | | luaC_changemode(L, KGC_NORMAL); |
| 1090 | | break; |
| 1091 | | } |
| 1092 | | default: res = -1; /* invalid option */ |
| 1093 | | } |
| 1094 | | lua_unlock(L); |
| 1095 | | return res; |
| 1022 | int res = 0; |
| 1023 | global_State *g; |
| 1024 | lua_lock(L); |
| 1025 | g = G(L); |
| 1026 | switch (what) { |
| 1027 | case LUA_GCSTOP: { |
| 1028 | g->gcrunning = 0; |
| 1029 | break; |
| 1030 | } |
| 1031 | case LUA_GCRESTART: { |
| 1032 | luaE_setdebt(g, 0); |
| 1033 | g->gcrunning = 1; |
| 1034 | break; |
| 1035 | } |
| 1036 | case LUA_GCCOLLECT: { |
| 1037 | luaC_fullgc(L, 0); |
| 1038 | break; |
| 1039 | } |
| 1040 | case LUA_GCCOUNT: { |
| 1041 | /* GC values are expressed in Kbytes: #bytes/2^10 */ |
| 1042 | res = cast_int(gettotalbytes(g) >> 10); |
| 1043 | break; |
| 1044 | } |
| 1045 | case LUA_GCCOUNTB: { |
| 1046 | res = cast_int(gettotalbytes(g) & 0x3ff); |
| 1047 | break; |
| 1048 | } |
| 1049 | case LUA_GCSTEP: { |
| 1050 | if (g->gckind == KGC_GEN) { /* generational mode? */ |
| 1051 | res = (g->GCestimate == 0); /* true if it will do major collection */ |
| 1052 | luaC_forcestep(L); /* do a single step */ |
| 1053 | } |
| 1054 | else { |
| 1055 | lu_mem debt = cast(lu_mem, data) * 1024 - GCSTEPSIZE; |
| 1056 | if (g->gcrunning) |
| 1057 | debt += g->GCdebt; /* include current debt */ |
| 1058 | luaE_setdebt(g, debt); |
| 1059 | luaC_forcestep(L); |
| 1060 | if (g->gcstate == GCSpause) /* end of cycle? */ |
| 1061 | res = 1; /* signal it */ |
| 1062 | } |
| 1063 | break; |
| 1064 | } |
| 1065 | case LUA_GCSETPAUSE: { |
| 1066 | res = g->gcpause; |
| 1067 | g->gcpause = data; |
| 1068 | break; |
| 1069 | } |
| 1070 | case LUA_GCSETMAJORINC: { |
| 1071 | res = g->gcmajorinc; |
| 1072 | g->gcmajorinc = data; |
| 1073 | break; |
| 1074 | } |
| 1075 | case LUA_GCSETSTEPMUL: { |
| 1076 | res = g->gcstepmul; |
| 1077 | g->gcstepmul = data; |
| 1078 | break; |
| 1079 | } |
| 1080 | case LUA_GCISRUNNING: { |
| 1081 | res = g->gcrunning; |
| 1082 | break; |
| 1083 | } |
| 1084 | case LUA_GCGEN: { /* change collector to generational mode */ |
| 1085 | luaC_changemode(L, KGC_GEN); |
| 1086 | break; |
| 1087 | } |
| 1088 | case LUA_GCINC: { /* change collector to incremental mode */ |
| 1089 | luaC_changemode(L, KGC_NORMAL); |
| 1090 | break; |
| 1091 | } |
| 1092 | default: res = -1; /* invalid option */ |
| 1093 | } |
| 1094 | lua_unlock(L); |
| 1095 | return res; |
| 1096 | 1096 | } |
| 1097 | 1097 | |
| 1098 | 1098 | |
| r30857 | r30858 | |
| 1103 | 1103 | |
| 1104 | 1104 | |
| 1105 | 1105 | LUA_API int lua_error (lua_State *L) { |
| 1106 | | lua_lock(L); |
| 1107 | | api_checknelems(L, 1); |
| 1108 | | luaG_errormsg(L); |
| 1109 | | /* code unreachable; will unlock when control actually leaves the kernel */ |
| 1110 | | return 0; /* to avoid warnings */ |
| 1106 | lua_lock(L); |
| 1107 | api_checknelems(L, 1); |
| 1108 | luaG_errormsg(L); |
| 1109 | /* code unreachable; will unlock when control actually leaves the kernel */ |
| 1110 | return 0; /* to avoid warnings */ |
| 1111 | 1111 | } |
| 1112 | 1112 | |
| 1113 | 1113 | |
| 1114 | 1114 | LUA_API int lua_next (lua_State *L, int idx) { |
| 1115 | | StkId t; |
| 1116 | | int more; |
| 1117 | | lua_lock(L); |
| 1118 | | t = index2addr(L, idx); |
| 1119 | | api_check(L, ttistable(t), "table expected"); |
| 1120 | | more = luaH_next(L, hvalue(t), L->top - 1); |
| 1121 | | if (more) { |
| 1122 | | api_incr_top(L); |
| 1123 | | } |
| 1124 | | else /* no more elements */ |
| 1125 | | L->top -= 1; /* remove key */ |
| 1126 | | lua_unlock(L); |
| 1127 | | return more; |
| 1115 | StkId t; |
| 1116 | int more; |
| 1117 | lua_lock(L); |
| 1118 | t = index2addr(L, idx); |
| 1119 | api_check(L, ttistable(t), "table expected"); |
| 1120 | more = luaH_next(L, hvalue(t), L->top - 1); |
| 1121 | if (more) { |
| 1122 | api_incr_top(L); |
| 1123 | } |
| 1124 | else /* no more elements */ |
| 1125 | L->top -= 1; /* remove key */ |
| 1126 | lua_unlock(L); |
| 1127 | return more; |
| 1128 | 1128 | } |
| 1129 | 1129 | |
| 1130 | 1130 | |
| 1131 | 1131 | LUA_API void lua_concat (lua_State *L, int n) { |
| 1132 | | lua_lock(L); |
| 1133 | | api_checknelems(L, n); |
| 1134 | | if (n >= 2) { |
| 1135 | | luaC_checkGC(L); |
| 1136 | | luaV_concat(L, n); |
| 1137 | | } |
| 1138 | | else if (n == 0) { /* push empty string */ |
| 1139 | | setsvalue2s(L, L->top, luaS_newlstr(L, "", 0)); |
| 1140 | | api_incr_top(L); |
| 1141 | | } |
| 1142 | | /* else n == 1; nothing to do */ |
| 1143 | | lua_unlock(L); |
| 1132 | lua_lock(L); |
| 1133 | api_checknelems(L, n); |
| 1134 | if (n >= 2) { |
| 1135 | luaC_checkGC(L); |
| 1136 | luaV_concat(L, n); |
| 1137 | } |
| 1138 | else if (n == 0) { /* push empty string */ |
| 1139 | setsvalue2s(L, L->top, luaS_newlstr(L, "", 0)); |
| 1140 | api_incr_top(L); |
| 1141 | } |
| 1142 | /* else n == 1; nothing to do */ |
| 1143 | lua_unlock(L); |
| 1144 | 1144 | } |
| 1145 | 1145 | |
| 1146 | 1146 | |
| 1147 | 1147 | LUA_API void lua_len (lua_State *L, int idx) { |
| 1148 | | StkId t; |
| 1149 | | lua_lock(L); |
| 1150 | | t = index2addr(L, idx); |
| 1151 | | luaV_objlen(L, L->top, t); |
| 1152 | | api_incr_top(L); |
| 1153 | | lua_unlock(L); |
| 1148 | StkId t; |
| 1149 | lua_lock(L); |
| 1150 | t = index2addr(L, idx); |
| 1151 | luaV_objlen(L, L->top, t); |
| 1152 | api_incr_top(L); |
| 1153 | lua_unlock(L); |
| 1154 | 1154 | } |
| 1155 | 1155 | |
| 1156 | 1156 | |
| 1157 | 1157 | LUA_API lua_Alloc lua_getallocf (lua_State *L, void **ud) { |
| 1158 | | lua_Alloc f; |
| 1159 | | lua_lock(L); |
| 1160 | | if (ud) *ud = G(L)->ud; |
| 1161 | | f = G(L)->frealloc; |
| 1162 | | lua_unlock(L); |
| 1163 | | return f; |
| 1158 | lua_Alloc f; |
| 1159 | lua_lock(L); |
| 1160 | if (ud) *ud = G(L)->ud; |
| 1161 | f = G(L)->frealloc; |
| 1162 | lua_unlock(L); |
| 1163 | return f; |
| 1164 | 1164 | } |
| 1165 | 1165 | |
| 1166 | 1166 | |
| 1167 | 1167 | LUA_API void lua_setallocf (lua_State *L, lua_Alloc f, void *ud) { |
| 1168 | | lua_lock(L); |
| 1169 | | G(L)->ud = ud; |
| 1170 | | G(L)->frealloc = f; |
| 1171 | | lua_unlock(L); |
| 1168 | lua_lock(L); |
| 1169 | G(L)->ud = ud; |
| 1170 | G(L)->frealloc = f; |
| 1171 | lua_unlock(L); |
| 1172 | 1172 | } |
| 1173 | 1173 | |
| 1174 | 1174 | |
| 1175 | 1175 | LUA_API void *lua_newuserdata (lua_State *L, size_t size) { |
| 1176 | | Udata *u; |
| 1177 | | lua_lock(L); |
| 1178 | | luaC_checkGC(L); |
| 1179 | | u = luaS_newudata(L, size, NULL); |
| 1180 | | setuvalue(L, L->top, u); |
| 1181 | | api_incr_top(L); |
| 1182 | | lua_unlock(L); |
| 1183 | | return u + 1; |
| 1176 | Udata *u; |
| 1177 | lua_lock(L); |
| 1178 | luaC_checkGC(L); |
| 1179 | u = luaS_newudata(L, size, NULL); |
| 1180 | setuvalue(L, L->top, u); |
| 1181 | api_incr_top(L); |
| 1182 | lua_unlock(L); |
| 1183 | return u + 1; |
| 1184 | 1184 | } |
| 1185 | 1185 | |
| 1186 | 1186 | |
| 1187 | 1187 | |
| 1188 | 1188 | static const char *aux_upvalue (StkId fi, int n, TValue **val, |
| 1189 | | GCObject **owner) { |
| 1190 | | switch (ttype(fi)) { |
| 1191 | | case LUA_TCCL: { /* C closure */ |
| 1192 | | CClosure *f = clCvalue(fi); |
| 1193 | | if (!(1 <= n && n <= f->nupvalues)) return NULL; |
| 1194 | | *val = &f->upvalue[n-1]; |
| 1195 | | if (owner) *owner = obj2gco(f); |
| 1196 | | return ""; |
| 1197 | | } |
| 1198 | | case LUA_TLCL: { /* Lua closure */ |
| 1199 | | LClosure *f = clLvalue(fi); |
| 1200 | | TString *name; |
| 1201 | | Proto *p = f->p; |
| 1202 | | if (!(1 <= n && n <= p->sizeupvalues)) return NULL; |
| 1203 | | *val = f->upvals[n-1]->v; |
| 1204 | | if (owner) *owner = obj2gco(f->upvals[n - 1]); |
| 1205 | | name = p->upvalues[n-1].name; |
| 1206 | | return (name == NULL) ? "" : getstr(name); |
| 1207 | | } |
| 1208 | | default: return NULL; /* not a closure */ |
| 1209 | | } |
| 1189 | GCObject **owner) { |
| 1190 | switch (ttype(fi)) { |
| 1191 | case LUA_TCCL: { /* C closure */ |
| 1192 | CClosure *f = clCvalue(fi); |
| 1193 | if (!(1 <= n && n <= f->nupvalues)) return NULL; |
| 1194 | *val = &f->upvalue[n-1]; |
| 1195 | if (owner) *owner = obj2gco(f); |
| 1196 | return ""; |
| 1197 | } |
| 1198 | case LUA_TLCL: { /* Lua closure */ |
| 1199 | LClosure *f = clLvalue(fi); |
| 1200 | TString *name; |
| 1201 | Proto *p = f->p; |
| 1202 | if (!(1 <= n && n <= p->sizeupvalues)) return NULL; |
| 1203 | *val = f->upvals[n-1]->v; |
| 1204 | if (owner) *owner = obj2gco(f->upvals[n - 1]); |
| 1205 | name = p->upvalues[n-1].name; |
| 1206 | return (name == NULL) ? "" : getstr(name); |
| 1207 | } |
| 1208 | default: return NULL; /* not a closure */ |
| 1209 | } |
| 1210 | 1210 | } |
| 1211 | 1211 | |
| 1212 | 1212 | |
| 1213 | 1213 | LUA_API const char *lua_getupvalue (lua_State *L, int funcindex, int n) { |
| 1214 | | const char *name; |
| 1215 | | TValue *val = NULL; /* to avoid warnings */ |
| 1216 | | lua_lock(L); |
| 1217 | | name = aux_upvalue(index2addr(L, funcindex), n, &val, NULL); |
| 1218 | | if (name) { |
| 1219 | | setobj2s(L, L->top, val); |
| 1220 | | api_incr_top(L); |
| 1221 | | } |
| 1222 | | lua_unlock(L); |
| 1223 | | return name; |
| 1214 | const char *name; |
| 1215 | TValue *val = NULL; /* to avoid warnings */ |
| 1216 | lua_lock(L); |
| 1217 | name = aux_upvalue(index2addr(L, funcindex), n, &val, NULL); |
| 1218 | if (name) { |
| 1219 | setobj2s(L, L->top, val); |
| 1220 | api_incr_top(L); |
| 1221 | } |
| 1222 | lua_unlock(L); |
| 1223 | return name; |
| 1224 | 1224 | } |
| 1225 | 1225 | |
| 1226 | 1226 | |
| 1227 | 1227 | LUA_API const char *lua_setupvalue (lua_State *L, int funcindex, int n) { |
| 1228 | | const char *name; |
| 1229 | | TValue *val = NULL; /* to avoid warnings */ |
| 1230 | | GCObject *owner = NULL; /* to avoid warnings */ |
| 1231 | | StkId fi; |
| 1232 | | lua_lock(L); |
| 1233 | | fi = index2addr(L, funcindex); |
| 1234 | | api_checknelems(L, 1); |
| 1235 | | name = aux_upvalue(fi, n, &val, &owner); |
| 1236 | | if (name) { |
| 1237 | | L->top--; |
| 1238 | | setobj(L, val, L->top); |
| 1239 | | luaC_barrier(L, owner, L->top); |
| 1240 | | } |
| 1241 | | lua_unlock(L); |
| 1242 | | return name; |
| 1228 | const char *name; |
| 1229 | TValue *val = NULL; /* to avoid warnings */ |
| 1230 | GCObject *owner = NULL; /* to avoid warnings */ |
| 1231 | StkId fi; |
| 1232 | lua_lock(L); |
| 1233 | fi = index2addr(L, funcindex); |
| 1234 | api_checknelems(L, 1); |
| 1235 | name = aux_upvalue(fi, n, &val, &owner); |
| 1236 | if (name) { |
| 1237 | L->top--; |
| 1238 | setobj(L, val, L->top); |
| 1239 | luaC_barrier(L, owner, L->top); |
| 1240 | } |
| 1241 | lua_unlock(L); |
| 1242 | return name; |
| 1243 | 1243 | } |
| 1244 | 1244 | |
| 1245 | 1245 | |
| 1246 | 1246 | static UpVal **getupvalref (lua_State *L, int fidx, int n, LClosure **pf) { |
| 1247 | | LClosure *f; |
| 1248 | | StkId fi = index2addr(L, fidx); |
| 1249 | | api_check(L, ttisLclosure(fi), "Lua function expected"); |
| 1250 | | f = clLvalue(fi); |
| 1251 | | api_check(L, (1 <= n && n <= f->p->sizeupvalues), "invalid upvalue index"); |
| 1252 | | if (pf) *pf = f; |
| 1253 | | return &f->upvals[n - 1]; /* get its upvalue pointer */ |
| 1247 | LClosure *f; |
| 1248 | StkId fi = index2addr(L, fidx); |
| 1249 | api_check(L, ttisLclosure(fi), "Lua function expected"); |
| 1250 | f = clLvalue(fi); |
| 1251 | api_check(L, (1 <= n && n <= f->p->sizeupvalues), "invalid upvalue index"); |
| 1252 | if (pf) *pf = f; |
| 1253 | return &f->upvals[n - 1]; /* get its upvalue pointer */ |
| 1254 | 1254 | } |
| 1255 | 1255 | |
| 1256 | 1256 | |
| 1257 | 1257 | LUA_API void *lua_upvalueid (lua_State *L, int fidx, int n) { |
| 1258 | | StkId fi = index2addr(L, fidx); |
| 1259 | | switch (ttype(fi)) { |
| 1260 | | case LUA_TLCL: { /* lua closure */ |
| 1261 | | return *getupvalref(L, fidx, n, NULL); |
| 1262 | | } |
| 1263 | | case LUA_TCCL: { /* C closure */ |
| 1264 | | CClosure *f = clCvalue(fi); |
| 1265 | | api_check(L, 1 <= n && n <= f->nupvalues, "invalid upvalue index"); |
| 1266 | | return &f->upvalue[n - 1]; |
| 1267 | | } |
| 1268 | | default: { |
| 1269 | | api_check(L, 0, "closure expected"); |
| 1270 | | return NULL; |
| 1271 | | } |
| 1272 | | } |
| 1258 | StkId fi = index2addr(L, fidx); |
| 1259 | switch (ttype(fi)) { |
| 1260 | case LUA_TLCL: { /* lua closure */ |
| 1261 | return *getupvalref(L, fidx, n, NULL); |
| 1262 | } |
| 1263 | case LUA_TCCL: { /* C closure */ |
| 1264 | CClosure *f = clCvalue(fi); |
| 1265 | api_check(L, 1 <= n && n <= f->nupvalues, "invalid upvalue index"); |
| 1266 | return &f->upvalue[n - 1]; |
| 1267 | } |
| 1268 | default: { |
| 1269 | api_check(L, 0, "closure expected"); |
| 1270 | return NULL; |
| 1271 | } |
| 1272 | } |
| 1273 | 1273 | } |
| 1274 | 1274 | |
| 1275 | 1275 | |
| 1276 | 1276 | LUA_API void lua_upvaluejoin (lua_State *L, int fidx1, int n1, |
| 1277 | | int fidx2, int n2) { |
| 1278 | | LClosure *f1; |
| 1279 | | UpVal **up1 = getupvalref(L, fidx1, n1, &f1); |
| 1280 | | UpVal **up2 = getupvalref(L, fidx2, n2, NULL); |
| 1281 | | *up1 = *up2; |
| 1282 | | luaC_objbarrier(L, f1, *up2); |
| 1277 | int fidx2, int n2) { |
| 1278 | LClosure *f1; |
| 1279 | UpVal **up1 = getupvalref(L, fidx1, n1, &f1); |
| 1280 | UpVal **up2 = getupvalref(L, fidx2, n2, NULL); |
| 1281 | *up1 = *up2; |
| 1282 | luaC_objbarrier(L, f1, *up2); |
| 1283 | 1283 | } |
| 1284 | |
trunk/src/lib/lua/lcode.c
| r30857 | r30858 | |
| 1 | 1 | /* |
| 2 | | ** $Id: lcode.c,v 2.62 2012/08/16 17:34:28 roberto Exp $ |
| 2 | ** $Id: lcode.c,v 2.62.1.1 2013/04/12 18:48:47 roberto Exp $ |
| 3 | 3 | ** Code generator for Lua |
| 4 | 4 | ** See Copyright Notice in lua.h |
| 5 | 5 | */ |
| r30857 | r30858 | |
| 26 | 26 | #include "lvm.h" |
| 27 | 27 | |
| 28 | 28 | |
| 29 | | #define hasjumps(e) ((e)->t != (e)->f) |
| 29 | #define hasjumps(e) ((e)->t != (e)->f) |
| 30 | 30 | |
| 31 | 31 | |
| 32 | 32 | static int isnumeral(expdesc *e) { |
| 33 | | return (e->k == VKNUM && e->t == NO_JUMP && e->f == NO_JUMP); |
| 33 | return (e->k == VKNUM && e->t == NO_JUMP && e->f == NO_JUMP); |
| 34 | 34 | } |
| 35 | 35 | |
| 36 | 36 | |
| 37 | 37 | void luaK_nil (FuncState *fs, int from, int n) { |
| 38 | | Instruction *previous; |
| 39 | | int l = from + n - 1; /* last register to set nil */ |
| 40 | | if (fs->pc > fs->lasttarget) { /* no jumps to current position? */ |
| 41 | | previous = &fs->f->code[fs->pc-1]; |
| 42 | | if (GET_OPCODE(*previous) == OP_LOADNIL) { |
| 43 | | int pfrom = GETARG_A(*previous); |
| 44 | | int pl = pfrom + GETARG_B(*previous); |
| 45 | | if ((pfrom <= from && from <= pl + 1) || |
| 46 | | (from <= pfrom && pfrom <= l + 1)) { /* can connect both? */ |
| 47 | | if (pfrom < from) from = pfrom; /* from = min(from, pfrom) */ |
| 48 | | if (pl > l) l = pl; /* l = max(l, pl) */ |
| 49 | | SETARG_A(*previous, from); |
| 50 | | SETARG_B(*previous, l - from); |
| 51 | | return; |
| 52 | | } |
| 53 | | } /* else go through */ |
| 54 | | } |
| 55 | | luaK_codeABC(fs, OP_LOADNIL, from, n - 1, 0); /* else no optimization */ |
| 38 | Instruction *previous; |
| 39 | int l = from + n - 1; /* last register to set nil */ |
| 40 | if (fs->pc > fs->lasttarget) { /* no jumps to current position? */ |
| 41 | previous = &fs->f->code[fs->pc-1]; |
| 42 | if (GET_OPCODE(*previous) == OP_LOADNIL) { |
| 43 | int pfrom = GETARG_A(*previous); |
| 44 | int pl = pfrom + GETARG_B(*previous); |
| 45 | if ((pfrom <= from && from <= pl + 1) || |
| 46 | (from <= pfrom && pfrom <= l + 1)) { /* can connect both? */ |
| 47 | if (pfrom < from) from = pfrom; /* from = min(from, pfrom) */ |
| 48 | if (pl > l) l = pl; /* l = max(l, pl) */ |
| 49 | SETARG_A(*previous, from); |
| 50 | SETARG_B(*previous, l - from); |
| 51 | return; |
| 52 | } |
| 53 | } /* else go through */ |
| 54 | } |
| 55 | luaK_codeABC(fs, OP_LOADNIL, from, n - 1, 0); /* else no optimization */ |
| 56 | 56 | } |
| 57 | 57 | |
| 58 | 58 | |
| 59 | 59 | int luaK_jump (FuncState *fs) { |
| 60 | | int jpc = fs->jpc; /* save list of jumps to here */ |
| 61 | | int j; |
| 62 | | fs->jpc = NO_JUMP; |
| 63 | | j = luaK_codeAsBx(fs, OP_JMP, 0, NO_JUMP); |
| 64 | | luaK_concat(fs, &j, jpc); /* keep them on hold */ |
| 65 | | return j; |
| 60 | int jpc = fs->jpc; /* save list of jumps to here */ |
| 61 | int j; |
| 62 | fs->jpc = NO_JUMP; |
| 63 | j = luaK_codeAsBx(fs, OP_JMP, 0, NO_JUMP); |
| 64 | luaK_concat(fs, &j, jpc); /* keep them on hold */ |
| 65 | return j; |
| 66 | 66 | } |
| 67 | 67 | |
| 68 | 68 | |
| 69 | 69 | void luaK_ret (FuncState *fs, int first, int nret) { |
| 70 | | luaK_codeABC(fs, OP_RETURN, first, nret+1, 0); |
| 70 | luaK_codeABC(fs, OP_RETURN, first, nret+1, 0); |
| 71 | 71 | } |
| 72 | 72 | |
| 73 | 73 | |
| 74 | 74 | static int condjump (FuncState *fs, OpCode op, int A, int B, int C) { |
| 75 | | luaK_codeABC(fs, op, A, B, C); |
| 76 | | return luaK_jump(fs); |
| 75 | luaK_codeABC(fs, op, A, B, C); |
| 76 | return luaK_jump(fs); |
| 77 | 77 | } |
| 78 | 78 | |
| 79 | 79 | |
| 80 | 80 | static void fixjump (FuncState *fs, int pc, int dest) { |
| 81 | | Instruction *jmp = &fs->f->code[pc]; |
| 82 | | int offset = dest-(pc+1); |
| 83 | | lua_assert(dest != NO_JUMP); |
| 84 | | if (abs(offset) > MAXARG_sBx) |
| 85 | | luaX_syntaxerror(fs->ls, "control structure too long"); |
| 86 | | SETARG_sBx(*jmp, offset); |
| 81 | Instruction *jmp = &fs->f->code[pc]; |
| 82 | int offset = dest-(pc+1); |
| 83 | lua_assert(dest != NO_JUMP); |
| 84 | if (abs(offset) > MAXARG_sBx) |
| 85 | luaX_syntaxerror(fs->ls, "control structure too long"); |
| 86 | SETARG_sBx(*jmp, offset); |
| 87 | 87 | } |
| 88 | 88 | |
| 89 | 89 | |
| r30857 | r30858 | |
| 92 | 92 | ** optimizations with consecutive instructions not in the same basic block). |
| 93 | 93 | */ |
| 94 | 94 | int luaK_getlabel (FuncState *fs) { |
| 95 | | fs->lasttarget = fs->pc; |
| 96 | | return fs->pc; |
| 95 | fs->lasttarget = fs->pc; |
| 96 | return fs->pc; |
| 97 | 97 | } |
| 98 | 98 | |
| 99 | 99 | |
| 100 | 100 | static int getjump (FuncState *fs, int pc) { |
| 101 | | int offset = GETARG_sBx(fs->f->code[pc]); |
| 102 | | if (offset == NO_JUMP) /* point to itself represents end of list */ |
| 103 | | return NO_JUMP; /* end of list */ |
| 104 | | else |
| 105 | | return (pc+1)+offset; /* turn offset into absolute position */ |
| 101 | int offset = GETARG_sBx(fs->f->code[pc]); |
| 102 | if (offset == NO_JUMP) /* point to itself represents end of list */ |
| 103 | return NO_JUMP; /* end of list */ |
| 104 | else |
| 105 | return (pc+1)+offset; /* turn offset into absolute position */ |
| 106 | 106 | } |
| 107 | 107 | |
| 108 | 108 | |
| 109 | 109 | static Instruction *getjumpcontrol (FuncState *fs, int pc) { |
| 110 | | Instruction *pi = &fs->f->code[pc]; |
| 111 | | if (pc >= 1 && testTMode(GET_OPCODE(*(pi-1)))) |
| 112 | | return pi-1; |
| 113 | | else |
| 114 | | return pi; |
| 110 | Instruction *pi = &fs->f->code[pc]; |
| 111 | if (pc >= 1 && testTMode(GET_OPCODE(*(pi-1)))) |
| 112 | return pi-1; |
| 113 | else |
| 114 | return pi; |
| 115 | 115 | } |
| 116 | 116 | |
| 117 | 117 | |
| r30857 | r30858 | |
| 120 | 120 | ** (or produce an inverted value) |
| 121 | 121 | */ |
| 122 | 122 | static int need_value (FuncState *fs, int list) { |
| 123 | | for (; list != NO_JUMP; list = getjump(fs, list)) { |
| 124 | | Instruction i = *getjumpcontrol(fs, list); |
| 125 | | if (GET_OPCODE(i) != OP_TESTSET) return 1; |
| 126 | | } |
| 127 | | return 0; /* not found */ |
| 123 | for (; list != NO_JUMP; list = getjump(fs, list)) { |
| 124 | Instruction i = *getjumpcontrol(fs, list); |
| 125 | if (GET_OPCODE(i) != OP_TESTSET) return 1; |
| 126 | } |
| 127 | return 0; /* not found */ |
| 128 | 128 | } |
| 129 | 129 | |
| 130 | 130 | |
| 131 | 131 | static int patchtestreg (FuncState *fs, int node, int reg) { |
| 132 | | Instruction *i = getjumpcontrol(fs, node); |
| 133 | | if (GET_OPCODE(*i) != OP_TESTSET) |
| 134 | | return 0; /* cannot patch other instructions */ |
| 135 | | if (reg != NO_REG && reg != GETARG_B(*i)) |
| 136 | | SETARG_A(*i, reg); |
| 137 | | else /* no register to put value or register already has the value */ |
| 138 | | *i = CREATE_ABC(OP_TEST, GETARG_B(*i), 0, GETARG_C(*i)); |
| 132 | Instruction *i = getjumpcontrol(fs, node); |
| 133 | if (GET_OPCODE(*i) != OP_TESTSET) |
| 134 | return 0; /* cannot patch other instructions */ |
| 135 | if (reg != NO_REG && reg != GETARG_B(*i)) |
| 136 | SETARG_A(*i, reg); |
| 137 | else /* no register to put value or register already has the value */ |
| 138 | *i = CREATE_ABC(OP_TEST, GETARG_B(*i), 0, GETARG_C(*i)); |
| 139 | 139 | |
| 140 | | return 1; |
| 140 | return 1; |
| 141 | 141 | } |
| 142 | 142 | |
| 143 | 143 | |
| 144 | 144 | static void removevalues (FuncState *fs, int list) { |
| 145 | | for (; list != NO_JUMP; list = getjump(fs, list)) |
| 146 | | patchtestreg(fs, list, NO_REG); |
| 145 | for (; list != NO_JUMP; list = getjump(fs, list)) |
| 146 | patchtestreg(fs, list, NO_REG); |
| 147 | 147 | } |
| 148 | 148 | |
| 149 | 149 | |
| 150 | 150 | static void patchlistaux (FuncState *fs, int list, int vtarget, int reg, |
| 151 | | int dtarget) { |
| 152 | | while (list != NO_JUMP) { |
| 153 | | int next = getjump(fs, list); |
| 154 | | if (patchtestreg(fs, list, reg)) |
| 155 | | fixjump(fs, list, vtarget); |
| 156 | | else |
| 157 | | fixjump(fs, list, dtarget); /* jump to default target */ |
| 158 | | list = next; |
| 159 | | } |
| 151 | int dtarget) { |
| 152 | while (list != NO_JUMP) { |
| 153 | int next = getjump(fs, list); |
| 154 | if (patchtestreg(fs, list, reg)) |
| 155 | fixjump(fs, list, vtarget); |
| 156 | else |
| 157 | fixjump(fs, list, dtarget); /* jump to default target */ |
| 158 | list = next; |
| 159 | } |
| 160 | 160 | } |
| 161 | 161 | |
| 162 | 162 | |
| 163 | 163 | static void dischargejpc (FuncState *fs) { |
| 164 | | patchlistaux(fs, fs->jpc, fs->pc, NO_REG, fs->pc); |
| 165 | | fs->jpc = NO_JUMP; |
| 164 | patchlistaux(fs, fs->jpc, fs->pc, NO_REG, fs->pc); |
| 165 | fs->jpc = NO_JUMP; |
| 166 | 166 | } |
| 167 | 167 | |
| 168 | 168 | |
| 169 | 169 | void luaK_patchlist (FuncState *fs, int list, int target) { |
| 170 | | if (target == fs->pc) |
| 171 | | luaK_patchtohere(fs, list); |
| 172 | | else { |
| 173 | | lua_assert(target < fs->pc); |
| 174 | | patchlistaux(fs, list, target, NO_REG, target); |
| 175 | | } |
| 170 | if (target == fs->pc) |
| 171 | luaK_patchtohere(fs, list); |
| 172 | else { |
| 173 | lua_assert(target < fs->pc); |
| 174 | patchlistaux(fs, list, target, NO_REG, target); |
| 175 | } |
| 176 | 176 | } |
| 177 | 177 | |
| 178 | 178 | |
| 179 | 179 | LUAI_FUNC void luaK_patchclose (FuncState *fs, int list, int level) { |
| 180 | | level++; /* argument is +1 to reserve 0 as non-op */ |
| 181 | | while (list != NO_JUMP) { |
| 182 | | int next = getjump(fs, list); |
| 183 | | lua_assert(GET_OPCODE(fs->f->code[list]) == OP_JMP && |
| 184 | | (GETARG_A(fs->f->code[list]) == 0 || |
| 185 | | GETARG_A(fs->f->code[list]) >= level)); |
| 186 | | SETARG_A(fs->f->code[list], level); |
| 187 | | list = next; |
| 188 | | } |
| 180 | level++; /* argument is +1 to reserve 0 as non-op */ |
| 181 | while (list != NO_JUMP) { |
| 182 | int next = getjump(fs, list); |
| 183 | lua_assert(GET_OPCODE(fs->f->code[list]) == OP_JMP && |
| 184 | (GETARG_A(fs->f->code[list]) == 0 || |
| 185 | GETARG_A(fs->f->code[list]) >= level)); |
| 186 | SETARG_A(fs->f->code[list], level); |
| 187 | list = next; |
| 188 | } |
| 189 | 189 | } |
| 190 | 190 | |
| 191 | 191 | |
| 192 | 192 | void luaK_patchtohere (FuncState *fs, int list) { |
| 193 | | luaK_getlabel(fs); |
| 194 | | luaK_concat(fs, &fs->jpc, list); |
| 193 | luaK_getlabel(fs); |
| 194 | luaK_concat(fs, &fs->jpc, list); |
| 195 | 195 | } |
| 196 | 196 | |
| 197 | 197 | |
| 198 | 198 | void luaK_concat (FuncState *fs, int *l1, int l2) { |
| 199 | | if (l2 == NO_JUMP) return; |
| 200 | | else if (*l1 == NO_JUMP) |
| 201 | | *l1 = l2; |
| 202 | | else { |
| 203 | | int list = *l1; |
| 204 | | int next; |
| 205 | | while ((next = getjump(fs, list)) != NO_JUMP) /* find last element */ |
| 206 | | list = next; |
| 207 | | fixjump(fs, list, l2); |
| 208 | | } |
| 199 | if (l2 == NO_JUMP) return; |
| 200 | else if (*l1 == NO_JUMP) |
| 201 | *l1 = l2; |
| 202 | else { |
| 203 | int list = *l1; |
| 204 | int next; |
| 205 | while ((next = getjump(fs, list)) != NO_JUMP) /* find last element */ |
| 206 | list = next; |
| 207 | fixjump(fs, list, l2); |
| 208 | } |
| 209 | 209 | } |
| 210 | 210 | |
| 211 | 211 | |
| 212 | 212 | static int luaK_code (FuncState *fs, Instruction i) { |
| 213 | | Proto *f = fs->f; |
| 214 | | dischargejpc(fs); /* `pc' will change */ |
| 215 | | /* put new instruction in code array */ |
| 216 | | luaM_growvector(fs->ls->L, f->code, fs->pc, f->sizecode, Instruction, |
| 217 | | MAX_INT, "opcodes"); |
| 218 | | f->code[fs->pc] = i; |
| 219 | | /* save corresponding line information */ |
| 220 | | luaM_growvector(fs->ls->L, f->lineinfo, fs->pc, f->sizelineinfo, int, |
| 221 | | MAX_INT, "opcodes"); |
| 222 | | f->lineinfo[fs->pc] = fs->ls->lastline; |
| 223 | | return fs->pc++; |
| 213 | Proto *f = fs->f; |
| 214 | dischargejpc(fs); /* `pc' will change */ |
| 215 | /* put new instruction in code array */ |
| 216 | luaM_growvector(fs->ls->L, f->code, fs->pc, f->sizecode, Instruction, |
| 217 | MAX_INT, "opcodes"); |
| 218 | f->code[fs->pc] = i; |
| 219 | /* save corresponding line information */ |
| 220 | luaM_growvector(fs->ls->L, f->lineinfo, fs->pc, f->sizelineinfo, int, |
| 221 | MAX_INT, "opcodes"); |
| 222 | f->lineinfo[fs->pc] = fs->ls->lastline; |
| 223 | return fs->pc++; |
| 224 | 224 | } |
| 225 | 225 | |
| 226 | 226 | |
| 227 | 227 | int luaK_codeABC (FuncState *fs, OpCode o, int a, int b, int c) { |
| 228 | | lua_assert(getOpMode(o) == iABC); |
| 229 | | lua_assert(getBMode(o) != OpArgN || b == 0); |
| 230 | | lua_assert(getCMode(o) != OpArgN || c == 0); |
| 231 | | lua_assert(a <= MAXARG_A && b <= MAXARG_B && c <= MAXARG_C); |
| 232 | | return luaK_code(fs, CREATE_ABC(o, a, b, c)); |
| 228 | lua_assert(getOpMode(o) == iABC); |
| 229 | lua_assert(getBMode(o) != OpArgN || b == 0); |
| 230 | lua_assert(getCMode(o) != OpArgN || c == 0); |
| 231 | lua_assert(a <= MAXARG_A && b <= MAXARG_B && c <= MAXARG_C); |
| 232 | return luaK_code(fs, CREATE_ABC(o, a, b, c)); |
| 233 | 233 | } |
| 234 | 234 | |
| 235 | 235 | |
| 236 | 236 | int luaK_codeABx (FuncState *fs, OpCode o, int a, unsigned int bc) { |
| 237 | | lua_assert(getOpMode(o) == iABx || getOpMode(o) == iAsBx); |
| 238 | | lua_assert(getCMode(o) == OpArgN); |
| 239 | | lua_assert(a <= MAXARG_A && bc <= MAXARG_Bx); |
| 240 | | return luaK_code(fs, CREATE_ABx(o, a, bc)); |
| 237 | lua_assert(getOpMode(o) == iABx || getOpMode(o) == iAsBx); |
| 238 | lua_assert(getCMode(o) == OpArgN); |
| 239 | lua_assert(a <= MAXARG_A && bc <= MAXARG_Bx); |
| 240 | return luaK_code(fs, CREATE_ABx(o, a, bc)); |
| 241 | 241 | } |
| 242 | 242 | |
| 243 | 243 | |
| 244 | 244 | static int codeextraarg (FuncState *fs, int a) { |
| 245 | | lua_assert(a <= MAXARG_Ax); |
| 246 | | return luaK_code(fs, CREATE_Ax(OP_EXTRAARG, a)); |
| 245 | lua_assert(a <= MAXARG_Ax); |
| 246 | return luaK_code(fs, CREATE_Ax(OP_EXTRAARG, a)); |
| 247 | 247 | } |
| 248 | 248 | |
| 249 | 249 | |
| 250 | 250 | int luaK_codek (FuncState *fs, int reg, int k) { |
| 251 | | if (k <= MAXARG_Bx) |
| 252 | | return luaK_codeABx(fs, OP_LOADK, reg, k); |
| 253 | | else { |
| 254 | | int p = luaK_codeABx(fs, OP_LOADKX, reg, 0); |
| 255 | | codeextraarg(fs, k); |
| 256 | | return p; |
| 257 | | } |
| 251 | if (k <= MAXARG_Bx) |
| 252 | return luaK_codeABx(fs, OP_LOADK, reg, k); |
| 253 | else { |
| 254 | int p = luaK_codeABx(fs, OP_LOADKX, reg, 0); |
| 255 | codeextraarg(fs, k); |
| 256 | return p; |
| 257 | } |
| 258 | 258 | } |
| 259 | 259 | |
| 260 | 260 | |
| 261 | 261 | void luaK_checkstack (FuncState *fs, int n) { |
| 262 | | int newstack = fs->freereg + n; |
| 263 | | if (newstack > fs->f->maxstacksize) { |
| 264 | | if (newstack >= MAXSTACK) |
| 265 | | luaX_syntaxerror(fs->ls, "function or expression too complex"); |
| 266 | | fs->f->maxstacksize = cast_byte(newstack); |
| 267 | | } |
| 262 | int newstack = fs->freereg + n; |
| 263 | if (newstack > fs->f->maxstacksize) { |
| 264 | if (newstack >= MAXSTACK) |
| 265 | luaX_syntaxerror(fs->ls, "function or expression too complex"); |
| 266 | fs->f->maxstacksize = cast_byte(newstack); |
| 267 | } |
| 268 | 268 | } |
| 269 | 269 | |
| 270 | 270 | |
| 271 | 271 | void luaK_reserveregs (FuncState *fs, int n) { |
| 272 | | luaK_checkstack(fs, n); |
| 273 | | fs->freereg += n; |
| 272 | luaK_checkstack(fs, n); |
| 273 | fs->freereg += n; |
| 274 | 274 | } |
| 275 | 275 | |
| 276 | 276 | |
| 277 | 277 | static void freereg (FuncState *fs, int reg) { |
| 278 | | if (!ISK(reg) && reg >= fs->nactvar) { |
| 279 | | fs->freereg--; |
| 280 | | lua_assert(reg == fs->freereg); |
| 281 | | } |
| 278 | if (!ISK(reg) && reg >= fs->nactvar) { |
| 279 | fs->freereg--; |
| 280 | lua_assert(reg == fs->freereg); |
| 281 | } |
| 282 | 282 | } |
| 283 | 283 | |
| 284 | 284 | |
| 285 | 285 | static void freeexp (FuncState *fs, expdesc *e) { |
| 286 | | if (e->k == VNONRELOC) |
| 287 | | freereg(fs, e->u.info); |
| 286 | if (e->k == VNONRELOC) |
| 287 | freereg(fs, e->u.info); |
| 288 | 288 | } |
| 289 | 289 | |
| 290 | 290 | |
| 291 | 291 | static int addk (FuncState *fs, TValue *key, TValue *v) { |
| 292 | | lua_State *L = fs->ls->L; |
| 293 | | TValue *idx = luaH_set(L, fs->h, key); |
| 294 | | Proto *f = fs->f; |
| 295 | | int k, oldsize; |
| 296 | | if (ttisnumber(idx)) { |
| 297 | | lua_Number n = nvalue(idx); |
| 298 | | lua_number2int(k, n); |
| 299 | | if (luaV_rawequalobj(&f->k[k], v)) |
| 300 | | return k; |
| 301 | | /* else may be a collision (e.g., between 0.0 and "\0\0\0\0\0\0\0\0"); |
| 302 | | go through and create a new entry for this value */ |
| 303 | | } |
| 304 | | /* constant not found; create a new entry */ |
| 305 | | oldsize = f->sizek; |
| 306 | | k = fs->nk; |
| 307 | | /* numerical value does not need GC barrier; |
| 308 | | table has no metatable, so it does not need to invalidate cache */ |
| 309 | | setnvalue(idx, cast_num(k)); |
| 310 | | luaM_growvector(L, f->k, k, f->sizek, TValue, MAXARG_Ax, "constants"); |
| 311 | | while (oldsize < f->sizek) setnilvalue(&f->k[oldsize++]); |
| 312 | | setobj(L, &f->k[k], v); |
| 313 | | fs->nk++; |
| 314 | | luaC_barrier(L, f, v); |
| 315 | | return k; |
| 292 | lua_State *L = fs->ls->L; |
| 293 | TValue *idx = luaH_set(L, fs->h, key); |
| 294 | Proto *f = fs->f; |
| 295 | int k, oldsize; |
| 296 | if (ttisnumber(idx)) { |
| 297 | lua_Number n = nvalue(idx); |
| 298 | lua_number2int(k, n); |
| 299 | if (luaV_rawequalobj(&f->k[k], v)) |
| 300 | return k; |
| 301 | /* else may be a collision (e.g., between 0.0 and "\0\0\0\0\0\0\0\0"); |
| 302 | go through and create a new entry for this value */ |
| 303 | } |
| 304 | /* constant not found; create a new entry */ |
| 305 | oldsize = f->sizek; |
| 306 | k = fs->nk; |
| 307 | /* numerical value does not need GC barrier; |
| 308 | table has no metatable, so it does not need to invalidate cache */ |
| 309 | setnvalue(idx, cast_num(k)); |
| 310 | luaM_growvector(L, f->k, k, f->sizek, TValue, MAXARG_Ax, "constants"); |
| 311 | while (oldsize < f->sizek) setnilvalue(&f->k[oldsize++]); |
| 312 | setobj(L, &f->k[k], v); |
| 313 | fs->nk++; |
| 314 | luaC_barrier(L, f, v); |
| 315 | return k; |
| 316 | 316 | } |
| 317 | 317 | |
| 318 | 318 | |
| 319 | 319 | int luaK_stringK (FuncState *fs, TString *s) { |
| 320 | | TValue o; |
| 321 | | setsvalue(fs->ls->L, &o, s); |
| 322 | | return addk(fs, &o, &o); |
| 320 | TValue o; |
| 321 | setsvalue(fs->ls->L, &o, s); |
| 322 | return addk(fs, &o, &o); |
| 323 | 323 | } |
| 324 | 324 | |
| 325 | 325 | |
| 326 | 326 | int luaK_numberK (FuncState *fs, lua_Number r) { |
| 327 | | int n; |
| 328 | | lua_State *L = fs->ls->L; |
| 329 | | TValue o; |
| 330 | | setnvalue(&o, r); |
| 331 | | if (r == 0 || luai_numisnan(NULL, r)) { /* handle -0 and NaN */ |
| 332 | | /* use raw representation as key to avoid numeric problems */ |
| 333 | | setsvalue(L, L->top++, luaS_newlstr(L, (char *)&r, sizeof(r))); |
| 334 | | n = addk(fs, L->top - 1, &o); |
| 335 | | L->top--; |
| 336 | | } |
| 337 | | else |
| 338 | | n = addk(fs, &o, &o); /* regular case */ |
| 339 | | return n; |
| 327 | int n; |
| 328 | lua_State *L = fs->ls->L; |
| 329 | TValue o; |
| 330 | setnvalue(&o, r); |
| 331 | if (r == 0 || luai_numisnan(NULL, r)) { /* handle -0 and NaN */ |
| 332 | /* use raw representation as key to avoid numeric problems */ |
| 333 | setsvalue(L, L->top++, luaS_newlstr(L, (char *)&r, sizeof(r))); |
| 334 | n = addk(fs, L->top - 1, &o); |
| 335 | L->top--; |
| 336 | } |
| 337 | else |
| 338 | n = addk(fs, &o, &o); /* regular case */ |
| 339 | return n; |
| 340 | 340 | } |
| 341 | 341 | |
| 342 | 342 | |
| 343 | 343 | static int boolK (FuncState *fs, int b) { |
| 344 | | TValue o; |
| 345 | | setbvalue(&o, b); |
| 346 | | return addk(fs, &o, &o); |
| 344 | TValue o; |
| 345 | setbvalue(&o, b); |
| 346 | return addk(fs, &o, &o); |
| 347 | 347 | } |
| 348 | 348 | |
| 349 | 349 | |
| 350 | 350 | static int nilK (FuncState *fs) { |
| 351 | | TValue k, v; |
| 352 | | setnilvalue(&v); |
| 353 | | /* cannot use nil as key; instead use table itself to represent nil */ |
| 354 | | sethvalue(fs->ls->L, &k, fs->h); |
| 355 | | return addk(fs, &k, &v); |
| 351 | TValue k, v; |
| 352 | setnilvalue(&v); |
| 353 | /* cannot use nil as key; instead use table itself to represent nil */ |
| 354 | sethvalue(fs->ls->L, &k, fs->h); |
| 355 | return addk(fs, &k, &v); |
| 356 | 356 | } |
| 357 | 357 | |
| 358 | 358 | |
| 359 | 359 | void luaK_setreturns (FuncState *fs, expdesc *e, int nresults) { |
| 360 | | if (e->k == VCALL) { /* expression is an open function call? */ |
| 361 | | SETARG_C(getcode(fs, e), nresults+1); |
| 362 | | } |
| 363 | | else if (e->k == VVARARG) { |
| 364 | | SETARG_B(getcode(fs, e), nresults+1); |
| 365 | | SETARG_A(getcode(fs, e), fs->freereg); |
| 366 | | luaK_reserveregs(fs, 1); |
| 367 | | } |
| 360 | if (e->k == VCALL) { /* expression is an open function call? */ |
| 361 | SETARG_C(getcode(fs, e), nresults+1); |
| 362 | } |
| 363 | else if (e->k == VVARARG) { |
| 364 | SETARG_B(getcode(fs, e), nresults+1); |
| 365 | SETARG_A(getcode(fs, e), fs->freereg); |
| 366 | luaK_reserveregs(fs, 1); |
| 367 | } |
| 368 | 368 | } |
| 369 | 369 | |
| 370 | 370 | |
| 371 | 371 | void luaK_setoneret (FuncState *fs, expdesc *e) { |
| 372 | | if (e->k == VCALL) { /* expression is an open function call? */ |
| 373 | | e->k = VNONRELOC; |
| 374 | | e->u.info = GETARG_A(getcode(fs, e)); |
| 375 | | } |
| 376 | | else if (e->k == VVARARG) { |
| 377 | | SETARG_B(getcode(fs, e), 2); |
| 378 | | e->k = VRELOCABLE; /* can relocate its simple result */ |
| 379 | | } |
| 372 | if (e->k == VCALL) { /* expression is an open function call? */ |
| 373 | e->k = VNONRELOC; |
| 374 | e->u.info = GETARG_A(getcode(fs, e)); |
| 375 | } |
| 376 | else if (e->k == VVARARG) { |
| 377 | SETARG_B(getcode(fs, e), 2); |
| 378 | e->k = VRELOCABLE; /* can relocate its simple result */ |
| 379 | } |
| 380 | 380 | } |
| 381 | 381 | |
| 382 | 382 | |
| 383 | 383 | void luaK_dischargevars (FuncState *fs, expdesc *e) { |
| 384 | | switch (e->k) { |
| 385 | | case VLOCAL: { |
| 386 | | e->k = VNONRELOC; |
| 387 | | break; |
| 388 | | } |
| 389 | | case VUPVAL: { |
| 390 | | e->u.info = luaK_codeABC(fs, OP_GETUPVAL, 0, e->u.info, 0); |
| 391 | | e->k = VRELOCABLE; |
| 392 | | break; |
| 393 | | } |
| 394 | | case VINDEXED: { |
| 395 | | OpCode op = OP_GETTABUP; /* assume 't' is in an upvalue */ |
| 396 | | freereg(fs, e->u.ind.idx); |
| 397 | | if (e->u.ind.vt == VLOCAL) { /* 't' is in a register? */ |
| 398 | | freereg(fs, e->u.ind.t); |
| 399 | | op = OP_GETTABLE; |
| 400 | | } |
| 401 | | e->u.info = luaK_codeABC(fs, op, 0, e->u.ind.t, e->u.ind.idx); |
| 402 | | e->k = VRELOCABLE; |
| 403 | | break; |
| 404 | | } |
| 405 | | case VVARARG: |
| 406 | | case VCALL: { |
| 407 | | luaK_setoneret(fs, e); |
| 408 | | break; |
| 409 | | } |
| 410 | | default: break; /* there is one value available (somewhere) */ |
| 411 | | } |
| 384 | switch (e->k) { |
| 385 | case VLOCAL: { |
| 386 | e->k = VNONRELOC; |
| 387 | break; |
| 388 | } |
| 389 | case VUPVAL: { |
| 390 | e->u.info = luaK_codeABC(fs, OP_GETUPVAL, 0, e->u.info, 0); |
| 391 | e->k = VRELOCABLE; |
| 392 | break; |
| 393 | } |
| 394 | case VINDEXED: { |
| 395 | OpCode op = OP_GETTABUP; /* assume 't' is in an upvalue */ |
| 396 | freereg(fs, e->u.ind.idx); |
| 397 | if (e->u.ind.vt == VLOCAL) { /* 't' is in a register? */ |
| 398 | freereg(fs, e->u.ind.t); |
| 399 | op = OP_GETTABLE; |
| 400 | } |
| 401 | e->u.info = luaK_codeABC(fs, op, 0, e->u.ind.t, e->u.ind.idx); |
| 402 | e->k = VRELOCABLE; |
| 403 | break; |
| 404 | } |
| 405 | case VVARARG: |
| 406 | case VCALL: { |
| 407 | luaK_setoneret(fs, e); |
| 408 | break; |
| 409 | } |
| 410 | default: break; /* there is one value available (somewhere) */ |
| 411 | } |
| 412 | 412 | } |
| 413 | 413 | |
| 414 | 414 | |
| 415 | 415 | static int code_label (FuncState *fs, int A, int b, int jump) { |
| 416 | | luaK_getlabel(fs); /* those instructions may be jump targets */ |
| 417 | | return luaK_codeABC(fs, OP_LOADBOOL, A, b, jump); |
| 416 | luaK_getlabel(fs); /* those instructions may be jump targets */ |
| 417 | return luaK_codeABC(fs, OP_LOADBOOL, A, b, jump); |
| 418 | 418 | } |
| 419 | 419 | |
| 420 | 420 | |
| 421 | 421 | static void discharge2reg (FuncState *fs, expdesc *e, int reg) { |
| 422 | | luaK_dischargevars(fs, e); |
| 423 | | switch (e->k) { |
| 424 | | case VNIL: { |
| 425 | | luaK_nil(fs, reg, 1); |
| 426 | | break; |
| 427 | | } |
| 428 | | case VFALSE: case VTRUE: { |
| 429 | | luaK_codeABC(fs, OP_LOADBOOL, reg, e->k == VTRUE, 0); |
| 430 | | break; |
| 431 | | } |
| 432 | | case VK: { |
| 433 | | luaK_codek(fs, reg, e->u.info); |
| 434 | | break; |
| 435 | | } |
| 436 | | case VKNUM: { |
| 437 | | luaK_codek(fs, reg, luaK_numberK(fs, e->u.nval)); |
| 438 | | break; |
| 439 | | } |
| 440 | | case VRELOCABLE: { |
| 441 | | Instruction *pc = &getcode(fs, e); |
| 442 | | SETARG_A(*pc, reg); |
| 443 | | break; |
| 444 | | } |
| 445 | | case VNONRELOC: { |
| 446 | | if (reg != e->u.info) |
| 447 | | luaK_codeABC(fs, OP_MOVE, reg, e->u.info, 0); |
| 448 | | break; |
| 449 | | } |
| 450 | | default: { |
| 451 | | lua_assert(e->k == VVOID || e->k == VJMP); |
| 452 | | return; /* nothing to do... */ |
| 453 | | } |
| 454 | | } |
| 455 | | e->u.info = reg; |
| 456 | | e->k = VNONRELOC; |
| 422 | luaK_dischargevars(fs, e); |
| 423 | switch (e->k) { |
| 424 | case VNIL: { |
| 425 | luaK_nil(fs, reg, 1); |
| 426 | break; |
| 427 | } |
| 428 | case VFALSE: case VTRUE: { |
| 429 | luaK_codeABC(fs, OP_LOADBOOL, reg, e->k == VTRUE, 0); |
| 430 | break; |
| 431 | } |
| 432 | case VK: { |
| 433 | luaK_codek(fs, reg, e->u.info); |
| 434 | break; |
| 435 | } |
| 436 | case VKNUM: { |
| 437 | luaK_codek(fs, reg, luaK_numberK(fs, e->u.nval)); |
| 438 | break; |
| 439 | } |
| 440 | case VRELOCABLE: { |
| 441 | Instruction *pc = &getcode(fs, e); |
| 442 | SETARG_A(*pc, reg); |
| 443 | break; |
| 444 | } |
| 445 | case VNONRELOC: { |
| 446 | if (reg != e->u.info) |
| 447 | luaK_codeABC(fs, OP_MOVE, reg, e->u.info, 0); |
| 448 | break; |
| 449 | } |
| 450 | default: { |
| 451 | lua_assert(e->k == VVOID || e->k == VJMP); |
| 452 | return; /* nothing to do... */ |
| 453 | } |
| 454 | } |
| 455 | e->u.info = reg; |
| 456 | e->k = VNONRELOC; |
| 457 | 457 | } |
| 458 | 458 | |
| 459 | 459 | |
| 460 | 460 | static void discharge2anyreg (FuncState *fs, expdesc *e) { |
| 461 | | if (e->k != VNONRELOC) { |
| 462 | | luaK_reserveregs(fs, 1); |
| 463 | | discharge2reg(fs, e, fs->freereg-1); |
| 464 | | } |
| 461 | if (e->k != VNONRELOC) { |
| 462 | luaK_reserveregs(fs, 1); |
| 463 | discharge2reg(fs, e, fs->freereg-1); |
| 464 | } |
| 465 | 465 | } |
| 466 | 466 | |
| 467 | 467 | |
| 468 | 468 | static void exp2reg (FuncState *fs, expdesc *e, int reg) { |
| 469 | | discharge2reg(fs, e, reg); |
| 470 | | if (e->k == VJMP) |
| 471 | | luaK_concat(fs, &e->t, e->u.info); /* put this jump in `t' list */ |
| 472 | | if (hasjumps(e)) { |
| 473 | | int final; /* position after whole expression */ |
| 474 | | int p_f = NO_JUMP; /* position of an eventual LOAD false */ |
| 475 | | int p_t = NO_JUMP; /* position of an eventual LOAD true */ |
| 476 | | if (need_value(fs, e->t) || need_value(fs, e->f)) { |
| 477 | | int fj = (e->k == VJMP) ? NO_JUMP : luaK_jump(fs); |
| 478 | | p_f = code_label(fs, reg, 0, 1); |
| 479 | | p_t = code_label(fs, reg, 1, 0); |
| 480 | | luaK_patchtohere(fs, fj); |
| 481 | | } |
| 482 | | final = luaK_getlabel(fs); |
| 483 | | patchlistaux(fs, e->f, final, reg, p_f); |
| 484 | | patchlistaux(fs, e->t, final, reg, p_t); |
| 485 | | } |
| 486 | | e->f = e->t = NO_JUMP; |
| 487 | | e->u.info = reg; |
| 488 | | e->k = VNONRELOC; |
| 469 | discharge2reg(fs, e, reg); |
| 470 | if (e->k == VJMP) |
| 471 | luaK_concat(fs, &e->t, e->u.info); /* put this jump in `t' list */ |
| 472 | if (hasjumps(e)) { |
| 473 | int final; /* position after whole expression */ |
| 474 | int p_f = NO_JUMP; /* position of an eventual LOAD false */ |
| 475 | int p_t = NO_JUMP; /* position of an eventual LOAD true */ |
| 476 | if (need_value(fs, e->t) || need_value(fs, e->f)) { |
| 477 | int fj = (e->k == VJMP) ? NO_JUMP : luaK_jump(fs); |
| 478 | p_f = code_label(fs, reg, 0, 1); |
| 479 | p_t = code_label(fs, reg, 1, 0); |
| 480 | luaK_patchtohere(fs, fj); |
| 481 | } |
| 482 | final = luaK_getlabel(fs); |
| 483 | patchlistaux(fs, e->f, final, reg, p_f); |
| 484 | patchlistaux(fs, e->t, final, reg, p_t); |
| 485 | } |
| 486 | e->f = e->t = NO_JUMP; |
| 487 | e->u.info = reg; |
| 488 | e->k = VNONRELOC; |
| 489 | 489 | } |
| 490 | 490 | |
| 491 | 491 | |
| 492 | 492 | void luaK_exp2nextreg (FuncState *fs, expdesc *e) { |
| 493 | | luaK_dischargevars(fs, e); |
| 494 | | freeexp(fs, e); |
| 495 | | luaK_reserveregs(fs, 1); |
| 496 | | exp2reg(fs, e, fs->freereg - 1); |
| 493 | luaK_dischargevars(fs, e); |
| 494 | freeexp(fs, e); |
| 495 | luaK_reserveregs(fs, 1); |
| 496 | exp2reg(fs, e, fs->freereg - 1); |
| 497 | 497 | } |
| 498 | 498 | |
| 499 | 499 | |
| 500 | 500 | int luaK_exp2anyreg (FuncState *fs, expdesc *e) { |
| 501 | | luaK_dischargevars(fs, e); |
| 502 | | if (e->k == VNONRELOC) { |
| 503 | | if (!hasjumps(e)) return e->u.info; /* exp is already in a register */ |
| 504 | | if (e->u.info >= fs->nactvar) { /* reg. is not a local? */ |
| 505 | | exp2reg(fs, e, e->u.info); /* put value on it */ |
| 506 | | return e->u.info; |
| 507 | | } |
| 508 | | } |
| 509 | | luaK_exp2nextreg(fs, e); /* default */ |
| 510 | | return e->u.info; |
| 501 | luaK_dischargevars(fs, e); |
| 502 | if (e->k == VNONRELOC) { |
| 503 | if (!hasjumps(e)) return e->u.info; /* exp is already in a register */ |
| 504 | if (e->u.info >= fs->nactvar) { /* reg. is not a local? */ |
| 505 | exp2reg(fs, e, e->u.info); /* put value on it */ |
| 506 | return e->u.info; |
| 507 | } |
| 508 | } |
| 509 | luaK_exp2nextreg(fs, e); /* default */ |
| 510 | return e->u.info; |
| 511 | 511 | } |
| 512 | 512 | |
| 513 | 513 | |
| 514 | 514 | void luaK_exp2anyregup (FuncState *fs, expdesc *e) { |
| 515 | | if (e->k != VUPVAL || hasjumps(e)) |
| 516 | | luaK_exp2anyreg(fs, e); |
| 515 | if (e->k != VUPVAL || hasjumps(e)) |
| 516 | luaK_exp2anyreg(fs, e); |
| 517 | 517 | } |
| 518 | 518 | |
| 519 | 519 | |
| 520 | 520 | void luaK_exp2val (FuncState *fs, expdesc *e) { |
| 521 | | if (hasjumps(e)) |
| 522 | | luaK_exp2anyreg(fs, e); |
| 523 | | else |
| 524 | | luaK_dischargevars(fs, e); |
| 521 | if (hasjumps(e)) |
| 522 | luaK_exp2anyreg(fs, e); |
| 523 | else |
| 524 | luaK_dischargevars(fs, e); |
| 525 | 525 | } |
| 526 | 526 | |
| 527 | 527 | |
| 528 | 528 | int luaK_exp2RK (FuncState *fs, expdesc *e) { |
| 529 | | luaK_exp2val(fs, e); |
| 530 | | switch (e->k) { |
| 531 | | case VTRUE: |
| 532 | | case VFALSE: |
| 533 | | case VNIL: { |
| 534 | | if (fs->nk <= MAXINDEXRK) { /* constant fits in RK operand? */ |
| 535 | | e->u.info = (e->k == VNIL) ? nilK(fs) : boolK(fs, (e->k == VTRUE)); |
| 536 | | e->k = VK; |
| 537 | | return RKASK(e->u.info); |
| 538 | | } |
| 539 | | else break; |
| 540 | | } |
| 541 | | case VKNUM: { |
| 542 | | e->u.info = luaK_numberK(fs, e->u.nval); |
| 543 | | e->k = VK; |
| 544 | | /* go through */ |
| 545 | | } |
| 546 | | case VK: { |
| 547 | | if (e->u.info <= MAXINDEXRK) /* constant fits in argC? */ |
| 548 | | return RKASK(e->u.info); |
| 549 | | else break; |
| 550 | | } |
| 551 | | default: break; |
| 552 | | } |
| 553 | | /* not a constant in the right range: put it in a register */ |
| 554 | | return luaK_exp2anyreg(fs, e); |
| 529 | luaK_exp2val(fs, e); |
| 530 | switch (e->k) { |
| 531 | case VTRUE: |
| 532 | case VFALSE: |
| 533 | case VNIL: { |
| 534 | if (fs->nk <= MAXINDEXRK) { /* constant fits in RK operand? */ |
| 535 | e->u.info = (e->k == VNIL) ? nilK(fs) : boolK(fs, (e->k == VTRUE)); |
| 536 | e->k = VK; |
| 537 | return RKASK(e->u.info); |
| 538 | } |
| 539 | else break; |
| 540 | } |
| 541 | case VKNUM: { |
| 542 | e->u.info = luaK_numberK(fs, e->u.nval); |
| 543 | e->k = VK; |
| 544 | /* go through */ |
| 545 | } |
| 546 | case VK: { |
| 547 | if (e->u.info <= MAXINDEXRK) /* constant fits in argC? */ |
| 548 | return RKASK(e->u.info); |
| 549 | else break; |
| 550 | } |
| 551 | default: break; |
| 552 | } |
| 553 | /* not a constant in the right range: put it in a register */ |
| 554 | return luaK_exp2anyreg(fs, e); |
| 555 | 555 | } |
| 556 | 556 | |
| 557 | 557 | |
| 558 | 558 | void luaK_storevar (FuncState *fs, expdesc *var, expdesc *ex) { |
| 559 | | switch (var->k) { |
| 560 | | case VLOCAL: { |
| 561 | | freeexp(fs, ex); |
| 562 | | exp2reg(fs, ex, var->u.info); |
| 563 | | return; |
| 564 | | } |
| 565 | | case VUPVAL: { |
| 566 | | int e = luaK_exp2anyreg(fs, ex); |
| 567 | | luaK_codeABC(fs, OP_SETUPVAL, e, var->u.info, 0); |
| 568 | | break; |
| 569 | | } |
| 570 | | case VINDEXED: { |
| 571 | | OpCode op = (var->u.ind.vt == VLOCAL) ? OP_SETTABLE : OP_SETTABUP; |
| 572 | | int e = luaK_exp2RK(fs, ex); |
| 573 | | luaK_codeABC(fs, op, var->u.ind.t, var->u.ind.idx, e); |
| 574 | | break; |
| 575 | | } |
| 576 | | default: { |
| 577 | | lua_assert(0); /* invalid var kind to store */ |
| 578 | | break; |
| 579 | | } |
| 580 | | } |
| 581 | | freeexp(fs, ex); |
| 559 | switch (var->k) { |
| 560 | case VLOCAL: { |
| 561 | freeexp(fs, ex); |
| 562 | exp2reg(fs, ex, var->u.info); |
| 563 | return; |
| 564 | } |
| 565 | case VUPVAL: { |
| 566 | int e = luaK_exp2anyreg(fs, ex); |
| 567 | luaK_codeABC(fs, OP_SETUPVAL, e, var->u.info, 0); |
| 568 | break; |
| 569 | } |
| 570 | case VINDEXED: { |
| 571 | OpCode op = (var->u.ind.vt == VLOCAL) ? OP_SETTABLE : OP_SETTABUP; |
| 572 | int e = luaK_exp2RK(fs, ex); |
| 573 | luaK_codeABC(fs, op, var->u.ind.t, var->u.ind.idx, e); |
| 574 | break; |
| 575 | } |
| 576 | default: { |
| 577 | lua_assert(0); /* invalid var kind to store */ |
| 578 | break; |
| 579 | } |
| 580 | } |
| 581 | freeexp(fs, ex); |
| 582 | 582 | } |
| 583 | 583 | |
| 584 | 584 | |
| 585 | 585 | void luaK_self (FuncState *fs, expdesc *e, expdesc *key) { |
| 586 | | int ereg; |
| 587 | | luaK_exp2anyreg(fs, e); |
| 588 | | ereg = e->u.info; /* register where 'e' was placed */ |
| 589 | | freeexp(fs, e); |
| 590 | | e->u.info = fs->freereg; /* base register for op_self */ |
| 591 | | e->k = VNONRELOC; |
| 592 | | luaK_reserveregs(fs, 2); /* function and 'self' produced by op_self */ |
| 593 | | luaK_codeABC(fs, OP_SELF, e->u.info, ereg, luaK_exp2RK(fs, key)); |
| 594 | | freeexp(fs, key); |
| 586 | int ereg; |
| 587 | luaK_exp2anyreg(fs, e); |
| 588 | ereg = e->u.info; /* register where 'e' was placed */ |
| 589 | freeexp(fs, e); |
| 590 | e->u.info = fs->freereg; /* base register for op_self */ |
| 591 | e->k = VNONRELOC; |
| 592 | luaK_reserveregs(fs, 2); /* function and 'self' produced by op_self */ |
| 593 | luaK_codeABC(fs, OP_SELF, e->u.info, ereg, luaK_exp2RK(fs, key)); |
| 594 | freeexp(fs, key); |
| 595 | 595 | } |
| 596 | 596 | |
| 597 | 597 | |
| 598 | 598 | static void invertjump (FuncState *fs, expdesc *e) { |
| 599 | | Instruction *pc = getjumpcontrol(fs, e->u.info); |
| 600 | | lua_assert(testTMode(GET_OPCODE(*pc)) && GET_OPCODE(*pc) != OP_TESTSET && |
| 601 | | GET_OPCODE(*pc) != OP_TEST); |
| 602 | | SETARG_A(*pc, !(GETARG_A(*pc))); |
| 599 | Instruction *pc = getjumpcontrol(fs, e->u.info); |
| 600 | lua_assert(testTMode(GET_OPCODE(*pc)) && GET_OPCODE(*pc) != OP_TESTSET && |
| 601 | GET_OPCODE(*pc) != OP_TEST); |
| 602 | SETARG_A(*pc, !(GETARG_A(*pc))); |
| 603 | 603 | } |
| 604 | 604 | |
| 605 | 605 | |
| 606 | 606 | static int jumponcond (FuncState *fs, expdesc *e, int cond) { |
| 607 | | if (e->k == VRELOCABLE) { |
| 608 | | Instruction ie = getcode(fs, e); |
| 609 | | if (GET_OPCODE(ie) == OP_NOT) { |
| 610 | | fs->pc--; /* remove previous OP_NOT */ |
| 611 | | return condjump(fs, OP_TEST, GETARG_B(ie), 0, !cond); |
| 612 | | } |
| 613 | | /* else go through */ |
| 614 | | } |
| 615 | | discharge2anyreg(fs, e); |
| 616 | | freeexp(fs, e); |
| 617 | | return condjump(fs, OP_TESTSET, NO_REG, e->u.info, cond); |
| 607 | if (e->k == VRELOCABLE) { |
| 608 | Instruction ie = getcode(fs, e); |
| 609 | if (GET_OPCODE(ie) == OP_NOT) { |
| 610 | fs->pc--; /* remove previous OP_NOT */ |
| 611 | return condjump(fs, OP_TEST, GETARG_B(ie), 0, !cond); |
| 612 | } |
| 613 | /* else go through */ |
| 614 | } |
| 615 | discharge2anyreg(fs, e); |
| 616 | freeexp(fs, e); |
| 617 | return condjump(fs, OP_TESTSET, NO_REG, e->u.info, cond); |
| 618 | 618 | } |
| 619 | 619 | |
| 620 | 620 | |
| 621 | 621 | void luaK_goiftrue (FuncState *fs, expdesc *e) { |
| 622 | | int pc; /* pc of last jump */ |
| 623 | | luaK_dischargevars(fs, e); |
| 624 | | switch (e->k) { |
| 625 | | case VJMP: { |
| 626 | | invertjump(fs, e); |
| 627 | | pc = e->u.info; |
| 628 | | break; |
| 629 | | } |
| 630 | | case VK: case VKNUM: case VTRUE: { |
| 631 | | pc = NO_JUMP; /* always true; do nothing */ |
| 632 | | break; |
| 633 | | } |
| 634 | | default: { |
| 635 | | pc = jumponcond(fs, e, 0); |
| 636 | | break; |
| 637 | | } |
| 638 | | } |
| 639 | | luaK_concat(fs, &e->f, pc); /* insert last jump in `f' list */ |
| 640 | | luaK_patchtohere(fs, e->t); |
| 641 | | e->t = NO_JUMP; |
| 622 | int pc; /* pc of last jump */ |
| 623 | luaK_dischargevars(fs, e); |
| 624 | switch (e->k) { |
| 625 | case VJMP: { |
| 626 | invertjump(fs, e); |
| 627 | pc = e->u.info; |
| 628 | break; |
| 629 | } |
| 630 | case VK: case VKNUM: case VTRUE: { |
| 631 | pc = NO_JUMP; /* always true; do nothing */ |
| 632 | break; |
| 633 | } |
| 634 | default: { |
| 635 | pc = jumponcond(fs, e, 0); |
| 636 | break; |
| 637 | } |
| 638 | } |
| 639 | luaK_concat(fs, &e->f, pc); /* insert last jump in `f' list */ |
| 640 | luaK_patchtohere(fs, e->t); |
| 641 | e->t = NO_JUMP; |
| 642 | 642 | } |
| 643 | 643 | |
| 644 | 644 | |
| 645 | 645 | void luaK_goiffalse (FuncState *fs, expdesc *e) { |
| 646 | | int pc; /* pc of last jump */ |
| 647 | | luaK_dischargevars(fs, e); |
| 648 | | switch (e->k) { |
| 649 | | case VJMP: { |
| 650 | | pc = e->u.info; |
| 651 | | break; |
| 652 | | } |
| 653 | | case VNIL: case VFALSE: { |
| 654 | | pc = NO_JUMP; /* always false; do nothing */ |
| 655 | | break; |
| 656 | | } |
| 657 | | default: { |
| 658 | | pc = jumponcond(fs, e, 1); |
| 659 | | break; |
| 660 | | } |
| 661 | | } |
| 662 | | luaK_concat(fs, &e->t, pc); /* insert last jump in `t' list */ |
| 663 | | luaK_patchtohere(fs, e->f); |
| 664 | | e->f = NO_JUMP; |
| 646 | int pc; /* pc of last jump */ |
| 647 | luaK_dischargevars(fs, e); |
| 648 | switch (e->k) { |
| 649 | case VJMP: { |
| 650 | pc = e->u.info; |
| 651 | break; |
| 652 | } |
| 653 | case VNIL: case VFALSE: { |
| 654 | pc = NO_JUMP; /* always false; do nothing */ |
| 655 | break; |
| 656 | } |
| 657 | default: { |
| 658 | pc = jumponcond(fs, e, 1); |
| 659 | break; |
| 660 | } |
| 661 | } |
| 662 | luaK_concat(fs, &e->t, pc); /* insert last jump in `t' list */ |
| 663 | luaK_patchtohere(fs, e->f); |
| 664 | e->f = NO_JUMP; |
| 665 | 665 | } |
| 666 | 666 | |
| 667 | 667 | |
| 668 | 668 | static void codenot (FuncState *fs, expdesc *e) { |
| 669 | | luaK_dischargevars(fs, e); |
| 670 | | switch (e->k) { |
| 671 | | case VNIL: case VFALSE: { |
| 672 | | e->k = VTRUE; |
| 673 | | break; |
| 674 | | } |
| 675 | | case VK: case VKNUM: case VTRUE: { |
| 676 | | e->k = VFALSE; |
| 677 | | break; |
| 678 | | } |
| 679 | | case VJMP: { |
| 680 | | invertjump(fs, e); |
| 681 | | break; |
| 682 | | } |
| 683 | | case VRELOCABLE: |
| 684 | | case VNONRELOC: { |
| 685 | | discharge2anyreg(fs, e); |
| 686 | | freeexp(fs, e); |
| 687 | | e->u.info = luaK_codeABC(fs, OP_NOT, 0, e->u.info, 0); |
| 688 | | e->k = VRELOCABLE; |
| 689 | | break; |
| 690 | | } |
| 691 | | default: { |
| 692 | | lua_assert(0); /* cannot happen */ |
| 693 | | break; |
| 694 | | } |
| 695 | | } |
| 696 | | /* interchange true and false lists */ |
| 697 | | { int temp = e->f; e->f = e->t; e->t = temp; } |
| 698 | | removevalues(fs, e->f); |
| 699 | | removevalues(fs, e->t); |
| 669 | luaK_dischargevars(fs, e); |
| 670 | switch (e->k) { |
| 671 | case VNIL: case VFALSE: { |
| 672 | e->k = VTRUE; |
| 673 | break; |
| 674 | } |
| 675 | case VK: case VKNUM: case VTRUE: { |
| 676 | e->k = VFALSE; |
| 677 | break; |
| 678 | } |
| 679 | case VJMP: { |
| 680 | invertjump(fs, e); |
| 681 | break; |
| 682 | } |
| 683 | case VRELOCABLE: |
| 684 | case VNONRELOC: { |
| 685 | discharge2anyreg(fs, e); |
| 686 | freeexp(fs, e); |
| 687 | e->u.info = luaK_codeABC(fs, OP_NOT, 0, e->u.info, 0); |
| 688 | e->k = VRELOCABLE; |
| 689 | break; |
| 690 | } |
| 691 | default: { |
| 692 | lua_assert(0); /* cannot happen */ |
| 693 | break; |
| 694 | } |
| 695 | } |
| 696 | /* interchange true and false lists */ |
| 697 | { int temp = e->f; e->f = e->t; e->t = temp; } |
| 698 | removevalues(fs, e->f); |
| 699 | removevalues(fs, e->t); |
| 700 | 700 | } |
| 701 | 701 | |
| 702 | 702 | |
| 703 | 703 | void luaK_indexed (FuncState *fs, expdesc *t, expdesc *k) { |
| 704 | | lua_assert(!hasjumps(t)); |
| 705 | | t->u.ind.t = t->u.info; |
| 706 | | t->u.ind.idx = luaK_exp2RK(fs, k); |
| 707 | | t->u.ind.vt = (t->k == VUPVAL) ? VUPVAL |
| 708 | | : check_exp(vkisinreg(t->k), VLOCAL); |
| 709 | | t->k = VINDEXED; |
| 704 | lua_assert(!hasjumps(t)); |
| 705 | t->u.ind.t = t->u.info; |
| 706 | t->u.ind.idx = luaK_exp2RK(fs, k); |
| 707 | t->u.ind.vt = (t->k == VUPVAL) ? VUPVAL |
| 708 | : check_exp(vkisinreg(t->k), VLOCAL); |
| 709 | t->k = VINDEXED; |
| 710 | 710 | } |
| 711 | 711 | |
| 712 | 712 | |
| 713 | 713 | static int constfolding (OpCode op, expdesc *e1, expdesc *e2) { |
| 714 | | lua_Number r; |
| 715 | | if (!isnumeral(e1) || !isnumeral(e2)) return 0; |
| 716 | | if ((op == OP_DIV || op == OP_MOD) && e2->u.nval == 0) |
| 717 | | return 0; /* do not attempt to divide by 0 */ |
| 718 | | r = luaO_arith(op - OP_ADD + LUA_OPADD, e1->u.nval, e2->u.nval); |
| 719 | | e1->u.nval = r; |
| 720 | | return 1; |
| 714 | lua_Number r; |
| 715 | if (!isnumeral(e1) || !isnumeral(e2)) return 0; |
| 716 | if ((op == OP_DIV || op == OP_MOD) && e2->u.nval == 0) |
| 717 | return 0; /* do not attempt to divide by 0 */ |
| 718 | r = luaO_arith(op - OP_ADD + LUA_OPADD, e1->u.nval, e2->u.nval); |
| 719 | e1->u.nval = r; |
| 720 | return 1; |
| 721 | 721 | } |
| 722 | 722 | |
| 723 | 723 | |
| 724 | 724 | static void codearith (FuncState *fs, OpCode op, |
| 725 | | expdesc *e1, expdesc *e2, int line) { |
| 726 | | if (constfolding(op, e1, e2)) |
| 727 | | return; |
| 728 | | else { |
| 729 | | int o2 = (op != OP_UNM && op != OP_LEN) ? luaK_exp2RK(fs, e2) : 0; |
| 730 | | int o1 = luaK_exp2RK(fs, e1); |
| 731 | | if (o1 > o2) { |
| 732 | | freeexp(fs, e1); |
| 733 | | freeexp(fs, e2); |
| 734 | | } |
| 735 | | else { |
| 736 | | freeexp(fs, e2); |
| 737 | | freeexp(fs, e1); |
| 738 | | } |
| 739 | | e1->u.info = luaK_codeABC(fs, op, 0, o1, o2); |
| 740 | | e1->k = VRELOCABLE; |
| 741 | | luaK_fixline(fs, line); |
| 742 | | } |
| 725 | expdesc *e1, expdesc *e2, int line) { |
| 726 | if (constfolding(op, e1, e2)) |
| 727 | return; |
| 728 | else { |
| 729 | int o2 = (op != OP_UNM && op != OP_LEN) ? luaK_exp2RK(fs, e2) : 0; |
| 730 | int o1 = luaK_exp2RK(fs, e1); |
| 731 | if (o1 > o2) { |
| 732 | freeexp(fs, e1); |
| 733 | freeexp(fs, e2); |
| 734 | } |
| 735 | else { |
| 736 | freeexp(fs, e2); |
| 737 | freeexp(fs, e1); |
| 738 | } |
| 739 | e1->u.info = luaK_codeABC(fs, op, 0, o1, o2); |
| 740 | e1->k = VRELOCABLE; |
| 741 | luaK_fixline(fs, line); |
| 742 | } |
| 743 | 743 | } |
| 744 | 744 | |
| 745 | 745 | |
| 746 | 746 | static void codecomp (FuncState *fs, OpCode op, int cond, expdesc *e1, |
| 747 | | expdesc *e2) { |
| 748 | | int o1 = luaK_exp2RK(fs, e1); |
| 749 | | int o2 = luaK_exp2RK(fs, e2); |
| 750 | | freeexp(fs, e2); |
| 751 | | freeexp(fs, e1); |
| 752 | | if (cond == 0 && op != OP_EQ) { |
| 753 | | int temp; /* exchange args to replace by `<' or `<=' */ |
| 754 | | temp = o1; o1 = o2; o2 = temp; /* o1 <==> o2 */ |
| 755 | | cond = 1; |
| 756 | | } |
| 757 | | e1->u.info = condjump(fs, op, cond, o1, o2); |
| 758 | | e1->k = VJMP; |
| 747 | expdesc *e2) { |
| 748 | int o1 = luaK_exp2RK(fs, e1); |
| 749 | int o2 = luaK_exp2RK(fs, e2); |
| 750 | freeexp(fs, e2); |
| 751 | freeexp(fs, e1); |
| 752 | if (cond == 0 && op != OP_EQ) { |
| 753 | int temp; /* exchange args to replace by `<' or `<=' */ |
| 754 | temp = o1; o1 = o2; o2 = temp; /* o1 <==> o2 */ |
| 755 | cond = 1; |
| 756 | } |
| 757 | e1->u.info = condjump(fs, op, cond, o1, o2); |
| 758 | e1->k = VJMP; |
| 759 | 759 | } |
| 760 | 760 | |
| 761 | 761 | |
| 762 | 762 | void luaK_prefix (FuncState *fs, UnOpr op, expdesc *e, int line) { |
| 763 | | expdesc e2; |
| 764 | | e2.t = e2.f = NO_JUMP; e2.k = VKNUM; e2.u.nval = 0; |
| 765 | | switch (op) { |
| 766 | | case OPR_MINUS: { |
| 767 | | if (isnumeral(e)) /* minus constant? */ |
| 768 | | e->u.nval = luai_numunm(NULL, e->u.nval); /* fold it */ |
| 769 | | else { |
| 770 | | luaK_exp2anyreg(fs, e); |
| 771 | | codearith(fs, OP_UNM, e, &e2, line); |
| 772 | | } |
| 773 | | break; |
| 774 | | } |
| 775 | | case OPR_NOT: codenot(fs, e); break; |
| 776 | | case OPR_LEN: { |
| 777 | | luaK_exp2anyreg(fs, e); /* cannot operate on constants */ |
| 778 | | codearith(fs, OP_LEN, e, &e2, line); |
| 779 | | break; |
| 780 | | } |
| 781 | | default: lua_assert(0); |
| 782 | | } |
| 763 | expdesc e2; |
| 764 | e2.t = e2.f = NO_JUMP; e2.k = VKNUM; e2.u.nval = 0; |
| 765 | switch (op) { |
| 766 | case OPR_MINUS: { |
| 767 | if (isnumeral(e)) /* minus constant? */ |
| 768 | e->u.nval = luai_numunm(NULL, e->u.nval); /* fold it */ |
| 769 | else { |
| 770 | luaK_exp2anyreg(fs, e); |
| 771 | codearith(fs, OP_UNM, e, &e2, line); |
| 772 | } |
| 773 | break; |
| 774 | } |
| 775 | case OPR_NOT: codenot(fs, e); break; |
| 776 | case OPR_LEN: { |
| 777 | luaK_exp2anyreg(fs, e); /* cannot operate on constants */ |
| 778 | codearith(fs, OP_LEN, e, &e2, line); |
| 779 | break; |
| 780 | } |
| 781 | default: lua_assert(0); |
| 782 | } |
| 783 | 783 | } |
| 784 | 784 | |
| 785 | 785 | |
| 786 | 786 | void luaK_infix (FuncState *fs, BinOpr op, expdesc *v) { |
| 787 | | switch (op) { |
| 788 | | case OPR_AND: { |
| 789 | | luaK_goiftrue(fs, v); |
| 790 | | break; |
| 791 | | } |
| 792 | | case OPR_OR: { |
| 793 | | luaK_goiffalse(fs, v); |
| 794 | | break; |
| 795 | | } |
| 796 | | case OPR_CONCAT: { |
| 797 | | luaK_exp2nextreg(fs, v); /* operand must be on the `stack' */ |
| 798 | | break; |
| 799 | | } |
| 800 | | case OPR_ADD: case OPR_SUB: case OPR_MUL: case OPR_DIV: |
| 801 | | case OPR_MOD: case OPR_POW: { |
| 802 | | if (!isnumeral(v)) luaK_exp2RK(fs, v); |
| 803 | | break; |
| 804 | | } |
| 805 | | default: { |
| 806 | | luaK_exp2RK(fs, v); |
| 807 | | break; |
| 808 | | } |
| 809 | | } |
| 787 | switch (op) { |
| 788 | case OPR_AND: { |
| 789 | luaK_goiftrue(fs, v); |
| 790 | break; |
| 791 | } |
| 792 | case OPR_OR: { |
| 793 | luaK_goiffalse(fs, v); |
| 794 | break; |
| 795 | } |
| 796 | case OPR_CONCAT: { |
| 797 | luaK_exp2nextreg(fs, v); /* operand must be on the `stack' */ |
| 798 | break; |
| 799 | } |
| 800 | case OPR_ADD: case OPR_SUB: case OPR_MUL: case OPR_DIV: |
| 801 | case OPR_MOD: case OPR_POW: { |
| 802 | if (!isnumeral(v)) luaK_exp2RK(fs, v); |
| 803 | break; |
| 804 | } |
| 805 | default: { |
| 806 | luaK_exp2RK(fs, v); |
| 807 | break; |
| 808 | } |
| 809 | } |
| 810 | 810 | } |
| 811 | 811 | |
| 812 | 812 | |
| 813 | 813 | void luaK_posfix (FuncState *fs, BinOpr op, |
| 814 | | expdesc *e1, expdesc *e2, int line) { |
| 815 | | switch (op) { |
| 816 | | case OPR_AND: { |
| 817 | | lua_assert(e1->t == NO_JUMP); /* list must be closed */ |
| 818 | | luaK_dischargevars(fs, e2); |
| 819 | | luaK_concat(fs, &e2->f, e1->f); |
| 820 | | *e1 = *e2; |
| 821 | | break; |
| 822 | | } |
| 823 | | case OPR_OR: { |
| 824 | | lua_assert(e1->f == NO_JUMP); /* list must be closed */ |
| 825 | | luaK_dischargevars(fs, e2); |
| 826 | | luaK_concat(fs, &e2->t, e1->t); |
| 827 | | *e1 = *e2; |
| 828 | | break; |
| 829 | | } |
| 830 | | case OPR_CONCAT: { |
| 831 | | luaK_exp2val(fs, e2); |
| 832 | | if (e2->k == VRELOCABLE && GET_OPCODE(getcode(fs, e2)) == OP_CONCAT) { |
| 833 | | lua_assert(e1->u.info == GETARG_B(getcode(fs, e2))-1); |
| 834 | | freeexp(fs, e1); |
| 835 | | SETARG_B(getcode(fs, e2), e1->u.info); |
| 836 | | e1->k = VRELOCABLE; e1->u.info = e2->u.info; |
| 837 | | } |
| 838 | | else { |
| 839 | | luaK_exp2nextreg(fs, e2); /* operand must be on the 'stack' */ |
| 840 | | codearith(fs, OP_CONCAT, e1, e2, line); |
| 841 | | } |
| 842 | | break; |
| 843 | | } |
| 844 | | case OPR_ADD: case OPR_SUB: case OPR_MUL: case OPR_DIV: |
| 845 | | case OPR_MOD: case OPR_POW: { |
| 846 | | codearith(fs, cast(OpCode, op - OPR_ADD + OP_ADD), e1, e2, line); |
| 847 | | break; |
| 848 | | } |
| 849 | | case OPR_EQ: case OPR_LT: case OPR_LE: { |
| 850 | | codecomp(fs, cast(OpCode, op - OPR_EQ + OP_EQ), 1, e1, e2); |
| 851 | | break; |
| 852 | | } |
| 853 | | case OPR_NE: case OPR_GT: case OPR_GE: { |
| 854 | | codecomp(fs, cast(OpCode, op - OPR_NE + OP_EQ), 0, e1, e2); |
| 855 | | break; |
| 856 | | } |
| 857 | | default: lua_assert(0); |
| 858 | | } |
| 814 | expdesc *e1, expdesc *e2, int line) { |
| 815 | switch (op) { |
| 816 | case OPR_AND: { |
| 817 | lua_assert(e1->t == NO_JUMP); /* list must be closed */ |
| 818 | luaK_dischargevars(fs, e2); |
| 819 | luaK_concat(fs, &e2->f, e1->f); |
| 820 | *e1 = *e2; |
| 821 | break; |
| 822 | } |
| 823 | case OPR_OR: { |
| 824 | lua_assert(e1->f == NO_JUMP); /* list must be closed */ |
| 825 | luaK_dischargevars(fs, e2); |
| 826 | luaK_concat(fs, &e2->t, e1->t); |
| 827 | *e1 = *e2; |
| 828 | break; |
| 829 | } |
| 830 | case OPR_CONCAT: { |
| 831 | luaK_exp2val(fs, e2); |
| 832 | if (e2->k == VRELOCABLE && GET_OPCODE(getcode(fs, e2)) == OP_CONCAT) { |
| 833 | lua_assert(e1->u.info == GETARG_B(getcode(fs, e2))-1); |
| 834 | freeexp(fs, e1); |
| 835 | SETARG_B(getcode(fs, e2), e1->u.info); |
| 836 | e1->k = VRELOCABLE; e1->u.info = e2->u.info; |
| 837 | } |
| 838 | else { |
| 839 | luaK_exp2nextreg(fs, e2); /* operand must be on the 'stack' */ |
| 840 | codearith(fs, OP_CONCAT, e1, e2, line); |
| 841 | } |
| 842 | break; |
| 843 | } |
| 844 | case OPR_ADD: case OPR_SUB: case OPR_MUL: case OPR_DIV: |
| 845 | case OPR_MOD: case OPR_POW: { |
| 846 | codearith(fs, cast(OpCode, op - OPR_ADD + OP_ADD), e1, e2, line); |
| 847 | break; |
| 848 | } |
| 849 | case OPR_EQ: case OPR_LT: case OPR_LE: { |
| 850 | codecomp(fs, cast(OpCode, op - OPR_EQ + OP_EQ), 1, e1, e2); |
| 851 | break; |
| 852 | } |
| 853 | case OPR_NE: case OPR_GT: case OPR_GE: { |
| 854 | codecomp(fs, cast(OpCode, op - OPR_NE + OP_EQ), 0, e1, e2); |
| 855 | break; |
| 856 | } |
| 857 | default: lua_assert(0); |
| 858 | } |
| 859 | 859 | } |
| 860 | 860 | |
| 861 | 861 | |
| 862 | 862 | void luaK_fixline (FuncState *fs, int line) { |
| 863 | | fs->f->lineinfo[fs->pc - 1] = line; |
| 863 | fs->f->lineinfo[fs->pc - 1] = line; |
| 864 | 864 | } |
| 865 | 865 | |
| 866 | 866 | |
| 867 | 867 | void luaK_setlist (FuncState *fs, int base, int nelems, int tostore) { |
| 868 | | int c = (nelems - 1)/LFIELDS_PER_FLUSH + 1; |
| 869 | | int b = (tostore == LUA_MULTRET) ? 0 : tostore; |
| 870 | | lua_assert(tostore != 0); |
| 871 | | if (c <= MAXARG_C) |
| 872 | | luaK_codeABC(fs, OP_SETLIST, base, b, c); |
| 873 | | else if (c <= MAXARG_Ax) { |
| 874 | | luaK_codeABC(fs, OP_SETLIST, base, b, 0); |
| 875 | | codeextraarg(fs, c); |
| 876 | | } |
| 877 | | else |
| 878 | | luaX_syntaxerror(fs->ls, "constructor too long"); |
| 879 | | fs->freereg = base + 1; /* free registers with list values */ |
| 868 | int c = (nelems - 1)/LFIELDS_PER_FLUSH + 1; |
| 869 | int b = (tostore == LUA_MULTRET) ? 0 : tostore; |
| 870 | lua_assert(tostore != 0); |
| 871 | if (c <= MAXARG_C) |
| 872 | luaK_codeABC(fs, OP_SETLIST, base, b, c); |
| 873 | else if (c <= MAXARG_Ax) { |
| 874 | luaK_codeABC(fs, OP_SETLIST, base, b, 0); |
| 875 | codeextraarg(fs, c); |
| 876 | } |
| 877 | else |
| 878 | luaX_syntaxerror(fs->ls, "constructor too long"); |
| 879 | fs->freereg = base + 1; /* free registers with list values */ |
| 880 | 880 | } |
| 881 | |
trunk/src/lib/lua/lobject.h
| r30857 | r30858 | |
| 1 | 1 | /* |
| 2 | | ** $Id: lobject.h,v 2.71 2012/09/11 18:21:44 roberto Exp $ |
| 2 | ** $Id: lobject.h,v 2.71.1.1 2013/04/12 18:48:47 roberto Exp $ |
| 3 | 3 | ** Type definitions for Lua objects |
| 4 | 4 | ** See Copyright Notice in lua.h |
| 5 | 5 | */ |
| r30857 | r30858 | |
| 19 | 19 | /* |
| 20 | 20 | ** Extra tags for non-values |
| 21 | 21 | */ |
| 22 | | #define LUA_TPROTO LUA_NUMTAGS |
| 23 | | #define LUA_TUPVAL (LUA_NUMTAGS+1) |
| 24 | | #define LUA_TDEADKEY (LUA_NUMTAGS+2) |
| 22 | #define LUA_TPROTO LUA_NUMTAGS |
| 23 | #define LUA_TUPVAL (LUA_NUMTAGS+1) |
| 24 | #define LUA_TDEADKEY (LUA_NUMTAGS+2) |
| 25 | 25 | |
| 26 | 26 | /* |
| 27 | 27 | ** number of all possible tags (including LUA_TNONE but excluding DEADKEY) |
| 28 | 28 | */ |
| 29 | | #define LUA_TOTALTAGS (LUA_TUPVAL+2) |
| 29 | #define LUA_TOTALTAGS (LUA_TUPVAL+2) |
| 30 | 30 | |
| 31 | 31 | |
| 32 | 32 | /* |
| r30857 | r30858 | |
| 36 | 36 | ** bit 6: whether value is collectable |
| 37 | 37 | */ |
| 38 | 38 | |
| 39 | | #define VARBITS (3 << 4) |
| 39 | #define VARBITS (3 << 4) |
| 40 | 40 | |
| 41 | 41 | |
| 42 | 42 | /* |
| r30857 | r30858 | |
| 47 | 47 | */ |
| 48 | 48 | |
| 49 | 49 | /* Variant tags for functions */ |
| 50 | | #define LUA_TLCL (LUA_TFUNCTION | (0 << 4)) /* Lua closure */ |
| 51 | | #define LUA_TLCF (LUA_TFUNCTION | (1 << 4)) /* light C function */ |
| 52 | | #define LUA_TCCL (LUA_TFUNCTION | (2 << 4)) /* C closure */ |
| 50 | #define LUA_TLCL (LUA_TFUNCTION | (0 << 4)) /* Lua closure */ |
| 51 | #define LUA_TLCF (LUA_TFUNCTION | (1 << 4)) /* light C function */ |
| 52 | #define LUA_TCCL (LUA_TFUNCTION | (2 << 4)) /* C closure */ |
| 53 | 53 | |
| 54 | 54 | |
| 55 | 55 | /* Variant tags for strings */ |
| 56 | | #define LUA_TSHRSTR (LUA_TSTRING | (0 << 4)) /* short strings */ |
| 57 | | #define LUA_TLNGSTR (LUA_TSTRING | (1 << 4)) /* long strings */ |
| 56 | #define LUA_TSHRSTR (LUA_TSTRING | (0 << 4)) /* short strings */ |
| 57 | #define LUA_TLNGSTR (LUA_TSTRING | (1 << 4)) /* long strings */ |
| 58 | 58 | |
| 59 | 59 | |
| 60 | 60 | /* Bit mark for collectable types */ |
| 61 | | #define BIT_ISCOLLECTABLE (1 << 6) |
| 61 | #define BIT_ISCOLLECTABLE (1 << 6) |
| 62 | 62 | |
| 63 | 63 | /* mark a tag as collectable */ |
| 64 | | #define ctb(t) ((t) | BIT_ISCOLLECTABLE) |
| 64 | #define ctb(t) ((t) | BIT_ISCOLLECTABLE) |
| 65 | 65 | |
| 66 | 66 | |
| 67 | 67 | /* |
| r30857 | r30858 | |
| 74 | 74 | ** Common Header for all collectable objects (in macro form, to be |
| 75 | 75 | ** included in other objects) |
| 76 | 76 | */ |
| 77 | | #define CommonHeader GCObject *next; lu_byte tt; lu_byte marked |
| 77 | #define CommonHeader GCObject *next; lu_byte tt; lu_byte marked |
| 78 | 78 | |
| 79 | 79 | |
| 80 | 80 | /* |
| 81 | 81 | ** Common header in struct form |
| 82 | 82 | */ |
| 83 | 83 | typedef struct GCheader { |
| 84 | | CommonHeader; |
| 84 | CommonHeader; |
| 85 | 85 | } GCheader; |
| 86 | 86 | |
| 87 | 87 | |
| r30857 | r30858 | |
| 92 | 92 | typedef union Value Value; |
| 93 | 93 | |
| 94 | 94 | |
| 95 | | #define numfield lua_Number n; /* numbers */ |
| 95 | #define numfield lua_Number n; /* numbers */ |
| 96 | 96 | |
| 97 | 97 | |
| 98 | 98 | |
| r30857 | r30858 | |
| 101 | 101 | ** an actual value plus a tag with its type. |
| 102 | 102 | */ |
| 103 | 103 | |
| 104 | | #define TValuefields Value value_; int tt_ |
| 104 | #define TValuefields Value value_; int tt_ |
| 105 | 105 | |
| 106 | 106 | typedef struct lua_TValue TValue; |
| 107 | 107 | |
| 108 | 108 | |
| 109 | 109 | /* macro defining a nil value */ |
| 110 | | #define NILCONSTANT {NULL}, LUA_TNIL |
| 110 | #define NILCONSTANT {NULL}, LUA_TNIL |
| 111 | 111 | |
| 112 | 112 | |
| 113 | | #define val_(o) ((o)->value_) |
| 114 | | #define num_(o) (val_(o).n) |
| 113 | #define val_(o) ((o)->value_) |
| 114 | #define num_(o) (val_(o).n) |
| 115 | 115 | |
| 116 | 116 | |
| 117 | 117 | /* raw type tag of a TValue */ |
| 118 | | #define rttype(o) ((o)->tt_) |
| 118 | #define rttype(o) ((o)->tt_) |
| 119 | 119 | |
| 120 | 120 | /* tag with no variants (bits 0-3) */ |
| 121 | | #define novariant(x) ((x) & 0x0F) |
| 121 | #define novariant(x) ((x) & 0x0F) |
| 122 | 122 | |
| 123 | 123 | /* type tag of a TValue (bits 0-3 for tags + variant bits 4-5) */ |
| 124 | | #define ttype(o) (rttype(o) & 0x3F) |
| 124 | #define ttype(o) (rttype(o) & 0x3F) |
| 125 | 125 | |
| 126 | 126 | /* type tag of a TValue with no variants (bits 0-3) */ |
| 127 | | #define ttypenv(o) (novariant(rttype(o))) |
| 127 | #define ttypenv(o) (novariant(rttype(o))) |
| 128 | 128 | |
| 129 | 129 | |
| 130 | 130 | /* Macros to test type */ |
| 131 | | #define checktag(o,t) (rttype(o) == (t)) |
| 132 | | #define checktype(o,t) (ttypenv(o) == (t)) |
| 133 | | #define ttisnumber(o) checktag((o), LUA_TNUMBER) |
| 134 | | #define ttisnil(o) checktag((o), LUA_TNIL) |
| 135 | | #define ttisboolean(o) checktag((o), LUA_TBOOLEAN) |
| 136 | | #define ttislightuserdata(o) checktag((o), LUA_TLIGHTUSERDATA) |
| 137 | | #define ttisstring(o) checktype((o), LUA_TSTRING) |
| 138 | | #define ttisshrstring(o) checktag((o), ctb(LUA_TSHRSTR)) |
| 139 | | #define ttislngstring(o) checktag((o), ctb(LUA_TLNGSTR)) |
| 140 | | #define ttistable(o) checktag((o), ctb(LUA_TTABLE)) |
| 141 | | #define ttisfunction(o) checktype(o, LUA_TFUNCTION) |
| 142 | | #define ttisclosure(o) ((rttype(o) & 0x1F) == LUA_TFUNCTION) |
| 143 | | #define ttisCclosure(o) checktag((o), ctb(LUA_TCCL)) |
| 144 | | #define ttisLclosure(o) checktag((o), ctb(LUA_TLCL)) |
| 145 | | #define ttislcf(o) checktag((o), LUA_TLCF) |
| 146 | | #define ttisuserdata(o) checktag((o), ctb(LUA_TUSERDATA)) |
| 147 | | #define ttisthread(o) checktag((o), ctb(LUA_TTHREAD)) |
| 148 | | #define ttisdeadkey(o) checktag((o), LUA_TDEADKEY) |
| 131 | #define checktag(o,t) (rttype(o) == (t)) |
| 132 | #define checktype(o,t) (ttypenv(o) == (t)) |
| 133 | #define ttisnumber(o) checktag((o), LUA_TNUMBER) |
| 134 | #define ttisnil(o) checktag((o), LUA_TNIL) |
| 135 | #define ttisboolean(o) checktag((o), LUA_TBOOLEAN) |
| 136 | #define ttislightuserdata(o) checktag((o), LUA_TLIGHTUSERDATA) |
| 137 | #define ttisstring(o) checktype((o), LUA_TSTRING) |
| 138 | #define ttisshrstring(o) checktag((o), ctb(LUA_TSHRSTR)) |
| 139 | #define ttislngstring(o) checktag((o), ctb(LUA_TLNGSTR)) |
| 140 | #define ttistable(o) checktag((o), ctb(LUA_TTABLE)) |
| 141 | #define ttisfunction(o) checktype(o, LUA_TFUNCTION) |
| 142 | #define ttisclosure(o) ((rttype(o) & 0x1F) == LUA_TFUNCTION) |
| 143 | #define ttisCclosure(o) checktag((o), ctb(LUA_TCCL)) |
| 144 | #define ttisLclosure(o) checktag((o), ctb(LUA_TLCL)) |
| 145 | #define ttislcf(o) checktag((o), LUA_TLCF) |
| 146 | #define ttisuserdata(o) checktag((o), ctb(LUA_TUSERDATA)) |
| 147 | #define ttisthread(o) checktag((o), ctb(LUA_TTHREAD)) |
| 148 | #define ttisdeadkey(o) checktag((o), LUA_TDEADKEY) |
| 149 | 149 | |
| 150 | | #define ttisequal(o1,o2) (rttype(o1) == rttype(o2)) |
| 150 | #define ttisequal(o1,o2) (rttype(o1) == rttype(o2)) |
| 151 | 151 | |
| 152 | 152 | /* Macros to access values */ |
| 153 | | #define nvalue(o) check_exp(ttisnumber(o), num_(o)) |
| 154 | | #define gcvalue(o) check_exp(iscollectable(o), val_(o).gc) |
| 155 | | #define pvalue(o) check_exp(ttislightuserdata(o), val_(o).p) |
| 156 | | #define rawtsvalue(o) check_exp(ttisstring(o), &val_(o).gc->ts) |
| 157 | | #define tsvalue(o) (&rawtsvalue(o)->tsv) |
| 158 | | #define rawuvalue(o) check_exp(ttisuserdata(o), &val_(o).gc->u) |
| 159 | | #define uvalue(o) (&rawuvalue(o)->uv) |
| 160 | | #define clvalue(o) check_exp(ttisclosure(o), &val_(o).gc->cl) |
| 161 | | #define clLvalue(o) check_exp(ttisLclosure(o), &val_(o).gc->cl.l) |
| 162 | | #define clCvalue(o) check_exp(ttisCclosure(o), &val_(o).gc->cl.c) |
| 163 | | #define fvalue(o) check_exp(ttislcf(o), val_(o).f) |
| 164 | | #define hvalue(o) check_exp(ttistable(o), &val_(o).gc->h) |
| 165 | | #define bvalue(o) check_exp(ttisboolean(o), val_(o).b) |
| 166 | | #define thvalue(o) check_exp(ttisthread(o), &val_(o).gc->th) |
| 153 | #define nvalue(o) check_exp(ttisnumber(o), num_(o)) |
| 154 | #define gcvalue(o) check_exp(iscollectable(o), val_(o).gc) |
| 155 | #define pvalue(o) check_exp(ttislightuserdata(o), val_(o).p) |
| 156 | #define rawtsvalue(o) check_exp(ttisstring(o), &val_(o).gc->ts) |
| 157 | #define tsvalue(o) (&rawtsvalue(o)->tsv) |
| 158 | #define rawuvalue(o) check_exp(ttisuserdata(o), &val_(o).gc->u) |
| 159 | #define uvalue(o) (&rawuvalue(o)->uv) |
| 160 | #define clvalue(o) check_exp(ttisclosure(o), &val_(o).gc->cl) |
| 161 | #define clLvalue(o) check_exp(ttisLclosure(o), &val_(o).gc->cl.l) |
| 162 | #define clCvalue(o) check_exp(ttisCclosure(o), &val_(o).gc->cl.c) |
| 163 | #define fvalue(o) check_exp(ttislcf(o), val_(o).f) |
| 164 | #define hvalue(o) check_exp(ttistable(o), &val_(o).gc->h) |
| 165 | #define bvalue(o) check_exp(ttisboolean(o), val_(o).b) |
| 166 | #define thvalue(o) check_exp(ttisthread(o), &val_(o).gc->th) |
| 167 | 167 | /* a dead value may get the 'gc' field, but cannot access its contents */ |
| 168 | | #define deadvalue(o) check_exp(ttisdeadkey(o), cast(void *, val_(o).gc)) |
| 168 | #define deadvalue(o) check_exp(ttisdeadkey(o), cast(void *, val_(o).gc)) |
| 169 | 169 | |
| 170 | | #define l_isfalse(o) (ttisnil(o) || (ttisboolean(o) && bvalue(o) == 0)) |
| 170 | #define l_isfalse(o) (ttisnil(o) || (ttisboolean(o) && bvalue(o) == 0)) |
| 171 | 171 | |
| 172 | 172 | |
| 173 | | #define iscollectable(o) (rttype(o) & BIT_ISCOLLECTABLE) |
| 173 | #define iscollectable(o) (rttype(o) & BIT_ISCOLLECTABLE) |
| 174 | 174 | |
| 175 | 175 | |
| 176 | 176 | /* Macros for internal tests */ |
| 177 | | #define righttt(obj) (ttype(obj) == gcvalue(obj)->gch.tt) |
| 177 | #define righttt(obj) (ttype(obj) == gcvalue(obj)->gch.tt) |
| 178 | 178 | |
| 179 | 179 | #define checkliveness(g,obj) \ |
| 180 | 180 | lua_longassert(!iscollectable(obj) || \ |
| r30857 | r30858 | |
| 182 | 182 | |
| 183 | 183 | |
| 184 | 184 | /* Macros to set values */ |
| 185 | | #define settt_(o,t) ((o)->tt_=(t)) |
| 185 | #define settt_(o,t) ((o)->tt_=(t)) |
| 186 | 186 | |
| 187 | 187 | #define setnvalue(obj,x) \ |
| 188 | | { TValue *io=(obj); num_(io)=(x); settt_(io, LUA_TNUMBER); } |
| 188 | { TValue *io=(obj); num_(io)=(x); settt_(io, LUA_TNUMBER); } |
| 189 | 189 | |
| 190 | 190 | #define setnilvalue(obj) settt_(obj, LUA_TNIL) |
| 191 | 191 | |
| 192 | 192 | #define setfvalue(obj,x) \ |
| 193 | | { TValue *io=(obj); val_(io).f=(x); settt_(io, LUA_TLCF); } |
| 193 | { TValue *io=(obj); val_(io).f=(x); settt_(io, LUA_TLCF); } |
| 194 | 194 | |
| 195 | 195 | #define setpvalue(obj,x) \ |
| 196 | | { TValue *io=(obj); val_(io).p=(x); settt_(io, LUA_TLIGHTUSERDATA); } |
| 196 | { TValue *io=(obj); val_(io).p=(x); settt_(io, LUA_TLIGHTUSERDATA); } |
| 197 | 197 | |
| 198 | 198 | #define setbvalue(obj,x) \ |
| 199 | | { TValue *io=(obj); val_(io).b=(x); settt_(io, LUA_TBOOLEAN); } |
| 199 | { TValue *io=(obj); val_(io).b=(x); settt_(io, LUA_TBOOLEAN); } |
| 200 | 200 | |
| 201 | 201 | #define setgcovalue(L,obj,x) \ |
| 202 | | { TValue *io=(obj); GCObject *i_g=(x); \ |
| 203 | | val_(io).gc=i_g; settt_(io, ctb(gch(i_g)->tt)); } |
| 202 | { TValue *io=(obj); GCObject *i_g=(x); \ |
| 203 | val_(io).gc=i_g; settt_(io, ctb(gch(i_g)->tt)); } |
| 204 | 204 | |
| 205 | 205 | #define setsvalue(L,obj,x) \ |
| 206 | | { TValue *io=(obj); \ |
| 207 | | TString *x_ = (x); \ |
| 208 | | val_(io).gc=cast(GCObject *, x_); settt_(io, ctb(x_->tsv.tt)); \ |
| 209 | | checkliveness(G(L),io); } |
| 206 | { TValue *io=(obj); \ |
| 207 | TString *x_ = (x); \ |
| 208 | val_(io).gc=cast(GCObject *, x_); settt_(io, ctb(x_->tsv.tt)); \ |
| 209 | checkliveness(G(L),io); } |
| 210 | 210 | |
| 211 | 211 | #define setuvalue(L,obj,x) \ |
| 212 | | { TValue *io=(obj); \ |
| 213 | | val_(io).gc=cast(GCObject *, (x)); settt_(io, ctb(LUA_TUSERDATA)); \ |
| 214 | | checkliveness(G(L),io); } |
| 212 | { TValue *io=(obj); \ |
| 213 | val_(io).gc=cast(GCObject *, (x)); settt_(io, ctb(LUA_TUSERDATA)); \ |
| 214 | checkliveness(G(L),io); } |
| 215 | 215 | |
| 216 | 216 | #define setthvalue(L,obj,x) \ |
| 217 | | { TValue *io=(obj); \ |
| 218 | | val_(io).gc=cast(GCObject *, (x)); settt_(io, ctb(LUA_TTHREAD)); \ |
| 219 | | checkliveness(G(L),io); } |
| 217 | { TValue *io=(obj); \ |
| 218 | val_(io).gc=cast(GCObject *, (x)); settt_(io, ctb(LUA_TTHREAD)); \ |
| 219 | checkliveness(G(L),io); } |
| 220 | 220 | |
| 221 | 221 | #define setclLvalue(L,obj,x) \ |
| 222 | | { TValue *io=(obj); \ |
| 223 | | val_(io).gc=cast(GCObject *, (x)); settt_(io, ctb(LUA_TLCL)); \ |
| 224 | | checkliveness(G(L),io); } |
| 222 | { TValue *io=(obj); \ |
| 223 | val_(io).gc=cast(GCObject *, (x)); settt_(io, ctb(LUA_TLCL)); \ |
| 224 | checkliveness(G(L),io); } |
| 225 | 225 | |
| 226 | 226 | #define setclCvalue(L,obj,x) \ |
| 227 | | { TValue *io=(obj); \ |
| 228 | | val_(io).gc=cast(GCObject *, (x)); settt_(io, ctb(LUA_TCCL)); \ |
| 229 | | checkliveness(G(L),io); } |
| 227 | { TValue *io=(obj); \ |
| 228 | val_(io).gc=cast(GCObject *, (x)); settt_(io, ctb(LUA_TCCL)); \ |
| 229 | checkliveness(G(L),io); } |
| 230 | 230 | |
| 231 | 231 | #define sethvalue(L,obj,x) \ |
| 232 | | { TValue *io=(obj); \ |
| 233 | | val_(io).gc=cast(GCObject *, (x)); settt_(io, ctb(LUA_TTABLE)); \ |
| 234 | | checkliveness(G(L),io); } |
| 232 | { TValue *io=(obj); \ |
| 233 | val_(io).gc=cast(GCObject *, (x)); settt_(io, ctb(LUA_TTABLE)); \ |
| 234 | checkliveness(G(L),io); } |
| 235 | 235 | |
| 236 | | #define setdeadvalue(obj) settt_(obj, LUA_TDEADKEY) |
| 236 | #define setdeadvalue(obj) settt_(obj, LUA_TDEADKEY) |
| 237 | 237 | |
| 238 | 238 | |
| 239 | 239 | |
| 240 | 240 | #define setobj(L,obj1,obj2) \ |
| 241 | 241 | { const TValue *io2=(obj2); TValue *io1=(obj1); \ |
| 242 | | io1->value_ = io2->value_; io1->tt_ = io2->tt_; \ |
| 243 | | checkliveness(G(L),io1); } |
| 242 | io1->value_ = io2->value_; io1->tt_ = io2->tt_; \ |
| 243 | checkliveness(G(L),io1); } |
| 244 | 244 | |
| 245 | 245 | |
| 246 | 246 | /* |
| r30857 | r30858 | |
| 248 | 248 | */ |
| 249 | 249 | |
| 250 | 250 | /* from stack to (same) stack */ |
| 251 | | #define setobjs2s setobj |
| 251 | #define setobjs2s setobj |
| 252 | 252 | /* to stack (not from same stack) */ |
| 253 | | #define setobj2s setobj |
| 254 | | #define setsvalue2s setsvalue |
| 255 | | #define sethvalue2s sethvalue |
| 256 | | #define setptvalue2s setptvalue |
| 253 | #define setobj2s setobj |
| 254 | #define setsvalue2s setsvalue |
| 255 | #define sethvalue2s sethvalue |
| 256 | #define setptvalue2s setptvalue |
| 257 | 257 | /* from table to same table */ |
| 258 | | #define setobjt2t setobj |
| 258 | #define setobjt2t setobj |
| 259 | 259 | /* to table */ |
| 260 | | #define setobj2t setobj |
| 260 | #define setobj2t setobj |
| 261 | 261 | /* to new object */ |
| 262 | | #define setobj2n setobj |
| 263 | | #define setsvalue2n setsvalue |
| 262 | #define setobj2n setobj |
| 263 | #define setsvalue2n setsvalue |
| 264 | 264 | |
| 265 | 265 | |
| 266 | 266 | /* check whether a number is valid (useful only for NaN trick) */ |
| 267 | | #define luai_checknum(L,o,c) { /* empty */ } |
| 267 | #define luai_checknum(L,o,c) { /* empty */ } |
| 268 | 268 | |
| 269 | 269 | |
| 270 | 270 | /* |
| r30857 | r30858 | |
| 282 | 282 | */ |
| 283 | 283 | |
| 284 | 284 | /* allows for external implementation for part of the trick */ |
| 285 | | #if !defined(NNMARK) /* { */ |
| 285 | #if !defined(NNMARK) /* { */ |
| 286 | 286 | |
| 287 | 287 | |
| 288 | 288 | #if !defined(LUA_IEEEENDIAN) |
| r30857 | r30858 | |
| 290 | 290 | #endif |
| 291 | 291 | |
| 292 | 292 | |
| 293 | | #define NNMARK 0x7FF7A500 |
| 294 | | #define NNMASK 0x7FFFFF00 |
| 293 | #define NNMARK 0x7FF7A500 |
| 294 | #define NNMASK 0x7FFFFF00 |
| 295 | 295 | |
| 296 | 296 | #undef TValuefields |
| 297 | 297 | #undef NILCONSTANT |
| 298 | 298 | |
| 299 | | #if (LUA_IEEEENDIAN == 0) /* { */ |
| 299 | #if (LUA_IEEEENDIAN == 0) /* { */ |
| 300 | 300 | |
| 301 | 301 | /* little endian */ |
| 302 | 302 | #define TValuefields \ |
| 303 | 303 | union { struct { Value v__; int tt__; } i; double d__; } u |
| 304 | | #define NILCONSTANT {{{NULL}, tag2tt(LUA_TNIL)}} |
| 304 | #define NILCONSTANT {{{NULL}, tag2tt(LUA_TNIL)}} |
| 305 | 305 | /* field-access macros */ |
| 306 | | #define v_(o) ((o)->u.i.v__) |
| 307 | | #define d_(o) ((o)->u.d__) |
| 308 | | #define tt_(o) ((o)->u.i.tt__) |
| 306 | #define v_(o) ((o)->u.i.v__) |
| 307 | #define d_(o) ((o)->u.d__) |
| 308 | #define tt_(o) ((o)->u.i.tt__) |
| 309 | 309 | |
| 310 | | #else /* }{ */ |
| 310 | #else /* }{ */ |
| 311 | 311 | |
| 312 | 312 | /* big endian */ |
| 313 | 313 | #define TValuefields \ |
| 314 | 314 | union { struct { int tt__; Value v__; } i; double d__; } u |
| 315 | | #define NILCONSTANT {{tag2tt(LUA_TNIL), {NULL}}} |
| 315 | #define NILCONSTANT {{tag2tt(LUA_TNIL), {NULL}}} |
| 316 | 316 | /* field-access macros */ |
| 317 | | #define v_(o) ((o)->u.i.v__) |
| 318 | | #define d_(o) ((o)->u.d__) |
| 319 | | #define tt_(o) ((o)->u.i.tt__) |
| 317 | #define v_(o) ((o)->u.i.v__) |
| 318 | #define d_(o) ((o)->u.d__) |
| 319 | #define tt_(o) ((o)->u.i.tt__) |
| 320 | 320 | |
| 321 | | #endif /* } */ |
| 321 | #endif /* } */ |
| 322 | 322 | |
| 323 | | #endif /* } */ |
| 323 | #endif /* } */ |
| 324 | 324 | |
| 325 | 325 | |
| 326 | 326 | /* correspondence with standard representation */ |
| 327 | 327 | #undef val_ |
| 328 | | #define val_(o) v_(o) |
| 328 | #define val_(o) v_(o) |
| 329 | 329 | #undef num_ |
| 330 | | #define num_(o) d_(o) |
| 330 | #define num_(o) d_(o) |
| 331 | 331 | |
| 332 | 332 | |
| 333 | 333 | #undef numfield |
| 334 | | #define numfield /* no such field; numbers are the entire struct */ |
| 334 | #define numfield /* no such field; numbers are the entire struct */ |
| 335 | 335 | |
| 336 | 336 | /* basic check to distinguish numbers from non-numbers */ |
| 337 | 337 | #undef ttisnumber |
| 338 | | #define ttisnumber(o) ((tt_(o) & NNMASK) != NNMARK) |
| 338 | #define ttisnumber(o) ((tt_(o) & NNMASK) != NNMARK) |
| 339 | 339 | |
| 340 | | #define tag2tt(t) (NNMARK | (t)) |
| 340 | #define tag2tt(t) (NNMARK | (t)) |
| 341 | 341 | |
| 342 | 342 | #undef rttype |
| 343 | | #define rttype(o) (ttisnumber(o) ? LUA_TNUMBER : tt_(o) & 0xff) |
| 343 | #define rttype(o) (ttisnumber(o) ? LUA_TNUMBER : tt_(o) & 0xff) |
| 344 | 344 | |
| 345 | 345 | #undef settt_ |
| 346 | | #define settt_(o,t) (tt_(o) = tag2tt(t)) |
| 346 | #define settt_(o,t) (tt_(o) = tag2tt(t)) |
| 347 | 347 | |
| 348 | 348 | #undef setnvalue |
| 349 | 349 | #define setnvalue(obj,x) \ |
| r30857 | r30858 | |
| 352 | 352 | #undef setobj |
| 353 | 353 | #define setobj(L,obj1,obj2) \ |
| 354 | 354 | { const TValue *o2_=(obj2); TValue *o1_=(obj1); \ |
| 355 | | o1_->u = o2_->u; \ |
| 356 | | checkliveness(G(L),o1_); } |
| 355 | o1_->u = o2_->u; \ |
| 356 | checkliveness(G(L),o1_); } |
| 357 | 357 | |
| 358 | 358 | |
| 359 | 359 | /* |
| r30857 | r30858 | |
| 362 | 362 | |
| 363 | 363 | #undef checktag |
| 364 | 364 | #undef checktype |
| 365 | | #define checktag(o,t) (tt_(o) == tag2tt(t)) |
| 366 | | #define checktype(o,t) (ctb(tt_(o) | VARBITS) == ctb(tag2tt(t) | VARBITS)) |
| 365 | #define checktag(o,t) (tt_(o) == tag2tt(t)) |
| 366 | #define checktype(o,t) (ctb(tt_(o) | VARBITS) == ctb(tag2tt(t) | VARBITS)) |
| 367 | 367 | |
| 368 | 368 | #undef ttisequal |
| 369 | 369 | #define ttisequal(o1,o2) \ |
| r30857 | r30858 | |
| 371 | 371 | |
| 372 | 372 | |
| 373 | 373 | #undef luai_checknum |
| 374 | | #define luai_checknum(L,o,c) { if (!ttisnumber(o)) c; } |
| 374 | #define luai_checknum(L,o,c) { if (!ttisnumber(o)) c; } |
| 375 | 375 | |
| 376 | 376 | #endif |
| 377 | 377 | /* }====================================================== */ |
| r30857 | r30858 | |
| 386 | 386 | |
| 387 | 387 | |
| 388 | 388 | union Value { |
| 389 | | GCObject *gc; /* collectable objects */ |
| 390 | | void *p; /* light userdata */ |
| 391 | | int b; /* booleans */ |
| 392 | | lua_CFunction f; /* light C functions */ |
| 393 | | numfield /* numbers */ |
| 389 | GCObject *gc; /* collectable objects */ |
| 390 | void *p; /* light userdata */ |
| 391 | int b; /* booleans */ |
| 392 | lua_CFunction f; /* light C functions */ |
| 393 | numfield /* numbers */ |
| 394 | 394 | }; |
| 395 | 395 | |
| 396 | 396 | |
| 397 | 397 | struct lua_TValue { |
| 398 | | TValuefields; |
| 398 | TValuefields; |
| 399 | 399 | }; |
| 400 | 400 | |
| 401 | 401 | |
| r30857 | r30858 | |
| 408 | 408 | ** Header for string value; string bytes follow the end of this structure |
| 409 | 409 | */ |
| 410 | 410 | typedef union TString { |
| 411 | | L_Umaxalign dummy; /* ensures maximum alignment for strings */ |
| 412 | | struct { |
| 413 | | CommonHeader; |
| 414 | | lu_byte extra; /* reserved words for short strings; "has hash" for longs */ |
| 415 | | unsigned int hash; |
| 416 | | size_t len; /* number of characters in string */ |
| 417 | | } tsv; |
| 411 | L_Umaxalign dummy; /* ensures maximum alignment for strings */ |
| 412 | struct { |
| 413 | CommonHeader; |
| 414 | lu_byte extra; /* reserved words for short strings; "has hash" for longs */ |
| 415 | unsigned int hash; |
| 416 | size_t len; /* number of characters in string */ |
| 417 | } tsv; |
| 418 | 418 | } TString; |
| 419 | 419 | |
| 420 | 420 | |
| 421 | 421 | /* get the actual string (array of bytes) from a TString */ |
| 422 | | #define getstr(ts) cast(const char *, (ts) + 1) |
| 422 | #define getstr(ts) cast(const char *, (ts) + 1) |
| 423 | 423 | |
| 424 | 424 | /* get the actual string (array of bytes) from a Lua value */ |
| 425 | 425 | #define svalue(o) getstr(rawtsvalue(o)) |
| r30857 | r30858 | |
| 429 | 429 | ** Header for userdata; memory area follows the end of this structure |
| 430 | 430 | */ |
| 431 | 431 | typedef union Udata { |
| 432 | | L_Umaxalign dummy; /* ensures maximum alignment for `local' udata */ |
| 433 | | struct { |
| 434 | | CommonHeader; |
| 435 | | struct Table *metatable; |
| 436 | | struct Table *env; |
| 437 | | size_t len; /* number of bytes */ |
| 438 | | } uv; |
| 432 | L_Umaxalign dummy; /* ensures maximum alignment for `local' udata */ |
| 433 | struct { |
| 434 | CommonHeader; |
| 435 | struct Table *metatable; |
| 436 | struct Table *env; |
| 437 | size_t len; /* number of bytes */ |
| 438 | } uv; |
| 439 | 439 | } Udata; |
| 440 | 440 | |
| 441 | 441 | |
| r30857 | r30858 | |
| 444 | 444 | ** Description of an upvalue for function prototypes |
| 445 | 445 | */ |
| 446 | 446 | typedef struct Upvaldesc { |
| 447 | | TString *name; /* upvalue name (for debug information) */ |
| 448 | | lu_byte instack; /* whether it is in stack */ |
| 449 | | lu_byte idx; /* index of upvalue (in stack or in outer function's list) */ |
| 447 | TString *name; /* upvalue name (for debug information) */ |
| 448 | lu_byte instack; /* whether it is in stack */ |
| 449 | lu_byte idx; /* index of upvalue (in stack or in outer function's list) */ |
| 450 | 450 | } Upvaldesc; |
| 451 | 451 | |
| 452 | 452 | |
| r30857 | r30858 | |
| 455 | 455 | ** (used for debug information) |
| 456 | 456 | */ |
| 457 | 457 | typedef struct LocVar { |
| 458 | | TString *varname; |
| 459 | | int startpc; /* first point where variable is active */ |
| 460 | | int endpc; /* first point where variable is dead */ |
| 458 | TString *varname; |
| 459 | int startpc; /* first point where variable is active */ |
| 460 | int endpc; /* first point where variable is dead */ |
| 461 | 461 | } LocVar; |
| 462 | 462 | |
| 463 | 463 | |
| r30857 | r30858 | |
| 465 | 465 | ** Function Prototypes |
| 466 | 466 | */ |
| 467 | 467 | typedef struct Proto { |
| 468 | | CommonHeader; |
| 469 | | TValue *k; /* constants used by the function */ |
| 470 | | Instruction *code; |
| 471 | | struct Proto **p; /* functions defined inside the function */ |
| 472 | | int *lineinfo; /* map from opcodes to source lines (debug information) */ |
| 473 | | LocVar *locvars; /* information about local variables (debug information) */ |
| 474 | | Upvaldesc *upvalues; /* upvalue information */ |
| 475 | | union Closure *cache; /* last created closure with this prototype */ |
| 476 | | TString *source; /* used for debug information */ |
| 477 | | int sizeupvalues; /* size of 'upvalues' */ |
| 478 | | int sizek; /* size of `k' */ |
| 479 | | int sizecode; |
| 480 | | int sizelineinfo; |
| 481 | | int sizep; /* size of `p' */ |
| 482 | | int sizelocvars; |
| 483 | | int linedefined; |
| 484 | | int lastlinedefined; |
| 485 | | GCObject *gclist; |
| 486 | | lu_byte numparams; /* number of fixed parameters */ |
| 487 | | lu_byte is_vararg; |
| 488 | | lu_byte maxstacksize; /* maximum stack used by this function */ |
| 468 | CommonHeader; |
| 469 | TValue *k; /* constants used by the function */ |
| 470 | Instruction *code; |
| 471 | struct Proto **p; /* functions defined inside the function */ |
| 472 | int *lineinfo; /* map from opcodes to source lines (debug information) */ |
| 473 | LocVar *locvars; /* information about local variables (debug information) */ |
| 474 | Upvaldesc *upvalues; /* upvalue information */ |
| 475 | union Closure *cache; /* last created closure with this prototype */ |
| 476 | TString *source; /* used for debug information */ |
| 477 | int sizeupvalues; /* size of 'upvalues' */ |
| 478 | int sizek; /* size of `k' */ |
| 479 | int sizecode; |
| 480 | int sizelineinfo; |
| 481 | int sizep; /* size of `p' */ |
| 482 | int sizelocvars; |
| 483 | int linedefined; |
| 484 | int lastlinedefined; |
| 485 | GCObject *gclist; |
| 486 | lu_byte numparams; /* number of fixed parameters */ |
| 487 | lu_byte is_vararg; |
| 488 | lu_byte maxstacksize; /* maximum stack used by this function */ |
| 489 | 489 | } Proto; |
| 490 | 490 | |
| 491 | 491 | |
| r30857 | r30858 | |
| 494 | 494 | ** Lua Upvalues |
| 495 | 495 | */ |
| 496 | 496 | typedef struct UpVal { |
| 497 | | CommonHeader; |
| 498 | | TValue *v; /* points to stack or to its own value */ |
| 499 | | union { |
| 500 | | TValue value; /* the value (when closed) */ |
| 501 | | struct { /* double linked list (when open) */ |
| 502 | | struct UpVal *prev; |
| 503 | | struct UpVal *next; |
| 504 | | } l; |
| 505 | | } u; |
| 497 | CommonHeader; |
| 498 | TValue *v; /* points to stack or to its own value */ |
| 499 | union { |
| 500 | TValue value; /* the value (when closed) */ |
| 501 | struct { /* double linked list (when open) */ |
| 502 | struct UpVal *prev; |
| 503 | struct UpVal *next; |
| 504 | } l; |
| 505 | } u; |
| 506 | 506 | } UpVal; |
| 507 | 507 | |
| 508 | 508 | |
| r30857 | r30858 | |
| 514 | 514 | CommonHeader; lu_byte nupvalues; GCObject *gclist |
| 515 | 515 | |
| 516 | 516 | typedef struct CClosure { |
| 517 | | ClosureHeader; |
| 518 | | lua_CFunction f; |
| 519 | | TValue upvalue[1]; /* list of upvalues */ |
| 517 | ClosureHeader; |
| 518 | lua_CFunction f; |
| 519 | TValue upvalue[1]; /* list of upvalues */ |
| 520 | 520 | } CClosure; |
| 521 | 521 | |
| 522 | 522 | |
| 523 | 523 | typedef struct LClosure { |
| 524 | | ClosureHeader; |
| 525 | | struct Proto *p; |
| 526 | | UpVal *upvals[1]; /* list of upvalues */ |
| 524 | ClosureHeader; |
| 525 | struct Proto *p; |
| 526 | UpVal *upvals[1]; /* list of upvalues */ |
| 527 | 527 | } LClosure; |
| 528 | 528 | |
| 529 | 529 | |
| 530 | 530 | typedef union Closure { |
| 531 | | CClosure c; |
| 532 | | LClosure l; |
| 531 | CClosure c; |
| 532 | LClosure l; |
| 533 | 533 | } Closure; |
| 534 | 534 | |
| 535 | 535 | |
| 536 | | #define isLfunction(o) ttisLclosure(o) |
| 536 | #define isLfunction(o) ttisLclosure(o) |
| 537 | 537 | |
| 538 | | #define getproto(o) (clLvalue(o)->p) |
| 538 | #define getproto(o) (clLvalue(o)->p) |
| 539 | 539 | |
| 540 | 540 | |
| 541 | 541 | /* |
| r30857 | r30858 | |
| 543 | 543 | */ |
| 544 | 544 | |
| 545 | 545 | typedef union TKey { |
| 546 | | struct { |
| 547 | | TValuefields; |
| 548 | | struct Node *next; /* for chaining */ |
| 549 | | } nk; |
| 550 | | TValue tvk; |
| 546 | struct { |
| 547 | TValuefields; |
| 548 | struct Node *next; /* for chaining */ |
| 549 | } nk; |
| 550 | TValue tvk; |
| 551 | 551 | } TKey; |
| 552 | 552 | |
| 553 | 553 | |
| 554 | 554 | typedef struct Node { |
| 555 | | TValue i_val; |
| 556 | | TKey i_key; |
| 555 | TValue i_val; |
| 556 | TKey i_key; |
| 557 | 557 | } Node; |
| 558 | 558 | |
| 559 | 559 | |
| 560 | 560 | typedef struct Table { |
| 561 | | CommonHeader; |
| 562 | | lu_byte flags; /* 1<<p means tagmethod(p) is not present */ |
| 563 | | lu_byte lsizenode; /* log2 of size of `node' array */ |
| 564 | | struct Table *metatable; |
| 565 | | TValue *array; /* array part */ |
| 566 | | Node *node; |
| 567 | | Node *lastfree; /* any free position is before this position */ |
| 568 | | GCObject *gclist; |
| 569 | | int sizearray; /* size of `array' array */ |
| 561 | CommonHeader; |
| 562 | lu_byte flags; /* 1<<p means tagmethod(p) is not present */ |
| 563 | lu_byte lsizenode; /* log2 of size of `node' array */ |
| 564 | struct Table *metatable; |
| 565 | TValue *array; /* array part */ |
| 566 | Node *node; |
| 567 | Node *lastfree; /* any free position is before this position */ |
| 568 | GCObject *gclist; |
| 569 | int sizearray; /* size of `array' array */ |
| 570 | 570 | } Table; |
| 571 | 571 | |
| 572 | 572 | |
| r30857 | r30858 | |
| 578 | 578 | (check_exp((size&(size-1))==0, (cast(int, (s) & ((size)-1))))) |
| 579 | 579 | |
| 580 | 580 | |
| 581 | | #define twoto(x) (1<<(x)) |
| 582 | | #define sizenode(t) (twoto((t)->lsizenode)) |
| 581 | #define twoto(x) (1<<(x)) |
| 582 | #define sizenode(t) (twoto((t)->lsizenode)) |
| 583 | 583 | |
| 584 | 584 | |
| 585 | 585 | /* |
| 586 | 586 | ** (address of) a fixed nil value |
| 587 | 587 | */ |
| 588 | | #define luaO_nilobject (&luaO_nilobject_) |
| 588 | #define luaO_nilobject (&luaO_nilobject_) |
| 589 | 589 | |
| 590 | 590 | |
| 591 | 591 | LUAI_DDEC const TValue luaO_nilobject_; |
| r30857 | r30858 | |
| 598 | 598 | LUAI_FUNC int luaO_str2d (const char *s, size_t len, lua_Number *result); |
| 599 | 599 | LUAI_FUNC int luaO_hexavalue (int c); |
| 600 | 600 | LUAI_FUNC const char *luaO_pushvfstring (lua_State *L, const char *fmt, |
| 601 | | va_list argp); |
| 601 | va_list argp); |
| 602 | 602 | LUAI_FUNC const char *luaO_pushfstring (lua_State *L, const char *fmt, ...); |
| 603 | 603 | LUAI_FUNC void luaO_chunkid (char *out, const char *source, size_t len); |
| 604 | 604 | |
| 605 | 605 | |
| 606 | 606 | #endif |
| 607 | |
trunk/src/lib/lua/lauxlib.c
| r30857 | r30858 | |
| 1 | 1 | /* |
| 2 | | ** $Id: lauxlib.c,v 1.248 2013/03/21 13:54:57 roberto Exp $ |
| 2 | ** $Id: lauxlib.c,v 1.248.1.1 2013/04/12 18:48:47 roberto Exp $ |
| 3 | 3 | ** Auxiliary functions for building Lua libraries |
| 4 | 4 | ** See Copyright Notice in lua.h |
| 5 | 5 | */ |
| r30857 | r30858 | |
| 31 | 31 | */ |
| 32 | 32 | |
| 33 | 33 | |
| 34 | | #define LEVELS1 12 /* size of the first part of the stack */ |
| 35 | | #define LEVELS2 10 /* size of the second part of the stack */ |
| 34 | #define LEVELS1 12 /* size of the first part of the stack */ |
| 35 | #define LEVELS2 10 /* size of the second part of the stack */ |
| 36 | 36 | |
| 37 | 37 | |
| 38 | 38 | |
| r30857 | r30858 | |
| 41 | 41 | ** return 1 + string at top if find a good name. |
| 42 | 42 | */ |
| 43 | 43 | static int findfield (lua_State *L, int objidx, int level) { |
| 44 | | if (level == 0 || !lua_istable(L, -1)) |
| 45 | | return 0; /* not found */ |
| 46 | | lua_pushnil(L); /* start 'next' loop */ |
| 47 | | while (lua_next(L, -2)) { /* for each pair in table */ |
| 48 | | if (lua_type(L, -2) == LUA_TSTRING) { /* ignore non-string keys */ |
| 49 | | if (lua_rawequal(L, objidx, -1)) { /* found object? */ |
| 50 | | lua_pop(L, 1); /* remove value (but keep name) */ |
| 51 | | return 1; |
| 52 | | } |
| 53 | | else if (findfield(L, objidx, level - 1)) { /* try recursively */ |
| 54 | | lua_remove(L, -2); /* remove table (but keep name) */ |
| 55 | | lua_pushliteral(L, "."); |
| 56 | | lua_insert(L, -2); /* place '.' between the two names */ |
| 57 | | lua_concat(L, 3); |
| 58 | | return 1; |
| 59 | | } |
| 60 | | } |
| 61 | | lua_pop(L, 1); /* remove value */ |
| 62 | | } |
| 63 | | return 0; /* not found */ |
| 44 | if (level == 0 || !lua_istable(L, -1)) |
| 45 | return 0; /* not found */ |
| 46 | lua_pushnil(L); /* start 'next' loop */ |
| 47 | while (lua_next(L, -2)) { /* for each pair in table */ |
| 48 | if (lua_type(L, -2) == LUA_TSTRING) { /* ignore non-string keys */ |
| 49 | if (lua_rawequal(L, objidx, -1)) { /* found object? */ |
| 50 | lua_pop(L, 1); /* remove value (but keep name) */ |
| 51 | return 1; |
| 52 | } |
| 53 | else if (findfield(L, objidx, level - 1)) { /* try recursively */ |
| 54 | lua_remove(L, -2); /* remove table (but keep name) */ |
| 55 | lua_pushliteral(L, "."); |
| 56 | lua_insert(L, -2); /* place '.' between the two names */ |
| 57 | lua_concat(L, 3); |
| 58 | return 1; |
| 59 | } |
| 60 | } |
| 61 | lua_pop(L, 1); /* remove value */ |
| 62 | } |
| 63 | return 0; /* not found */ |
| 64 | 64 | } |
| 65 | 65 | |
| 66 | 66 | |
| 67 | 67 | static int pushglobalfuncname (lua_State *L, lua_Debug *ar) { |
| 68 | | int top = lua_gettop(L); |
| 69 | | lua_getinfo(L, "f", ar); /* push function */ |
| 70 | | lua_pushglobaltable(L); |
| 71 | | if (findfield(L, top + 1, 2)) { |
| 72 | | lua_copy(L, -1, top + 1); /* move name to proper place */ |
| 73 | | lua_pop(L, 2); /* remove pushed values */ |
| 74 | | return 1; |
| 75 | | } |
| 76 | | else { |
| 77 | | lua_settop(L, top); /* remove function and global table */ |
| 78 | | return 0; |
| 79 | | } |
| 68 | int top = lua_gettop(L); |
| 69 | lua_getinfo(L, "f", ar); /* push function */ |
| 70 | lua_pushglobaltable(L); |
| 71 | if (findfield(L, top + 1, 2)) { |
| 72 | lua_copy(L, -1, top + 1); /* move name to proper place */ |
| 73 | lua_pop(L, 2); /* remove pushed values */ |
| 74 | return 1; |
| 75 | } |
| 76 | else { |
| 77 | lua_settop(L, top); /* remove function and global table */ |
| 78 | return 0; |
| 79 | } |
| 80 | 80 | } |
| 81 | 81 | |
| 82 | 82 | |
| 83 | 83 | static void pushfuncname (lua_State *L, lua_Debug *ar) { |
| 84 | | if (*ar->namewhat != '\0') /* is there a name? */ |
| 85 | | lua_pushfstring(L, "function " LUA_QS, ar->name); |
| 86 | | else if (*ar->what == 'm') /* main? */ |
| 87 | | lua_pushliteral(L, "main chunk"); |
| 88 | | else if (*ar->what == 'C') { |
| 89 | | if (pushglobalfuncname(L, ar)) { |
| 90 | | lua_pushfstring(L, "function " LUA_QS, lua_tostring(L, -1)); |
| 91 | | lua_remove(L, -2); /* remove name */ |
| 92 | | } |
| 93 | | else |
| 94 | | lua_pushliteral(L, "?"); |
| 95 | | } |
| 96 | | else |
| 97 | | lua_pushfstring(L, "function <%s:%d>", ar->short_src, ar->linedefined); |
| 84 | if (*ar->namewhat != '\0') /* is there a name? */ |
| 85 | lua_pushfstring(L, "function " LUA_QS, ar->name); |
| 86 | else if (*ar->what == 'm') /* main? */ |
| 87 | lua_pushliteral(L, "main chunk"); |
| 88 | else if (*ar->what == 'C') { |
| 89 | if (pushglobalfuncname(L, ar)) { |
| 90 | lua_pushfstring(L, "function " LUA_QS, lua_tostring(L, -1)); |
| 91 | lua_remove(L, -2); /* remove name */ |
| 92 | } |
| 93 | else |
| 94 | lua_pushliteral(L, "?"); |
| 95 | } |
| 96 | else |
| 97 | lua_pushfstring(L, "function <%s:%d>", ar->short_src, ar->linedefined); |
| 98 | 98 | } |
| 99 | 99 | |
| 100 | 100 | |
| 101 | 101 | static int countlevels (lua_State *L) { |
| 102 | | lua_Debug ar; |
| 103 | | int li = 1, le = 1; |
| 104 | | /* find an upper bound */ |
| 105 | | while (lua_getstack(L, le, &ar)) { li = le; le *= 2; } |
| 106 | | /* do a binary search */ |
| 107 | | while (li < le) { |
| 108 | | int m = (li + le)/2; |
| 109 | | if (lua_getstack(L, m, &ar)) li = m + 1; |
| 110 | | else le = m; |
| 111 | | } |
| 112 | | return le - 1; |
| 102 | lua_Debug ar; |
| 103 | int li = 1, le = 1; |
| 104 | /* find an upper bound */ |
| 105 | while (lua_getstack(L, le, &ar)) { li = le; le *= 2; } |
| 106 | /* do a binary search */ |
| 107 | while (li < le) { |
| 108 | int m = (li + le)/2; |
| 109 | if (lua_getstack(L, m, &ar)) li = m + 1; |
| 110 | else le = m; |
| 111 | } |
| 112 | return le - 1; |
| 113 | 113 | } |
| 114 | 114 | |
| 115 | 115 | |
| 116 | 116 | LUALIB_API void luaL_traceback (lua_State *L, lua_State *L1, |
| 117 | | const char *msg, int level) { |
| 118 | | lua_Debug ar; |
| 119 | | int top = lua_gettop(L); |
| 120 | | int numlevels = countlevels(L1); |
| 121 | | int mark = (numlevels > LEVELS1 + LEVELS2) ? LEVELS1 : 0; |
| 122 | | if (msg) lua_pushfstring(L, "%s\n", msg); |
| 123 | | lua_pushliteral(L, "stack traceback:"); |
| 124 | | while (lua_getstack(L1, level++, &ar)) { |
| 125 | | if (level == mark) { /* too many levels? */ |
| 126 | | lua_pushliteral(L, "\n\t..."); /* add a '...' */ |
| 127 | | level = numlevels - LEVELS2; /* and skip to last ones */ |
| 128 | | } |
| 129 | | else { |
| 130 | | lua_getinfo(L1, "Slnt", &ar); |
| 131 | | lua_pushfstring(L, "\n\t%s:", ar.short_src); |
| 132 | | if (ar.currentline > 0) |
| 133 | | lua_pushfstring(L, "%d:", ar.currentline); |
| 134 | | lua_pushliteral(L, " in "); |
| 135 | | pushfuncname(L, &ar); |
| 136 | | if (ar.istailcall) |
| 137 | | lua_pushliteral(L, "\n\t(...tail calls...)"); |
| 138 | | lua_concat(L, lua_gettop(L) - top); |
| 139 | | } |
| 140 | | } |
| 141 | | lua_concat(L, lua_gettop(L) - top); |
| 117 | const char *msg, int level) { |
| 118 | lua_Debug ar; |
| 119 | int top = lua_gettop(L); |
| 120 | int numlevels = countlevels(L1); |
| 121 | int mark = (numlevels > LEVELS1 + LEVELS2) ? LEVELS1 : 0; |
| 122 | if (msg) lua_pushfstring(L, "%s\n", msg); |
| 123 | lua_pushliteral(L, "stack traceback:"); |
| 124 | while (lua_getstack(L1, level++, &ar)) { |
| 125 | if (level == mark) { /* too many levels? */ |
| 126 | lua_pushliteral(L, "\n\t..."); /* add a '...' */ |
| 127 | level = numlevels - LEVELS2; /* and skip to last ones */ |
| 128 | } |
| 129 | else { |
| 130 | lua_getinfo(L1, "Slnt", &ar); |
| 131 | lua_pushfstring(L, "\n\t%s:", ar.short_src); |
| 132 | if (ar.currentline > 0) |
| 133 | lua_pushfstring(L, "%d:", ar.currentline); |
| 134 | lua_pushliteral(L, " in "); |
| 135 | pushfuncname(L, &ar); |
| 136 | if (ar.istailcall) |
| 137 | lua_pushliteral(L, "\n\t(...tail calls...)"); |
| 138 | lua_concat(L, lua_gettop(L) - top); |
| 139 | } |
| 140 | } |
| 141 | lua_concat(L, lua_gettop(L) - top); |
| 142 | 142 | } |
| 143 | 143 | |
| 144 | 144 | /* }====================================================== */ |
| r30857 | r30858 | |
| 151 | 151 | */ |
| 152 | 152 | |
| 153 | 153 | LUALIB_API int luaL_argerror (lua_State *L, int narg, const char *extramsg) { |
| 154 | | lua_Debug ar; |
| 155 | | if (!lua_getstack(L, 0, &ar)) /* no stack frame? */ |
| 156 | | return luaL_error(L, "bad argument #%d (%s)", narg, extramsg); |
| 157 | | lua_getinfo(L, "n", &ar); |
| 158 | | if (strcmp(ar.namewhat, "method") == 0) { |
| 159 | | narg--; /* do not count `self' */ |
| 160 | | if (narg == 0) /* error is in the self argument itself? */ |
| 161 | | return luaL_error(L, "calling " LUA_QS " on bad self (%s)", |
| 162 | | ar.name, extramsg); |
| 163 | | } |
| 164 | | if (ar.name == NULL) |
| 165 | | ar.name = (pushglobalfuncname(L, &ar)) ? lua_tostring(L, -1) : "?"; |
| 166 | | return luaL_error(L, "bad argument #%d to " LUA_QS " (%s)", |
| 167 | | narg, ar.name, extramsg); |
| 154 | lua_Debug ar; |
| 155 | if (!lua_getstack(L, 0, &ar)) /* no stack frame? */ |
| 156 | return luaL_error(L, "bad argument #%d (%s)", narg, extramsg); |
| 157 | lua_getinfo(L, "n", &ar); |
| 158 | if (strcmp(ar.namewhat, "method") == 0) { |
| 159 | narg--; /* do not count `self' */ |
| 160 | if (narg == 0) /* error is in the self argument itself? */ |
| 161 | return luaL_error(L, "calling " LUA_QS " on bad self (%s)", |
| 162 | ar.name, extramsg); |
| 163 | } |
| 164 | if (ar.name == NULL) |
| 165 | ar.name = (pushglobalfuncname(L, &ar)) ? lua_tostring(L, -1) : "?"; |
| 166 | return luaL_error(L, "bad argument #%d to " LUA_QS " (%s)", |
| 167 | narg, ar.name, extramsg); |
| 168 | 168 | } |
| 169 | 169 | |
| 170 | 170 | |
| 171 | 171 | static int typeerror (lua_State *L, int narg, const char *tname) { |
| 172 | | const char *msg = lua_pushfstring(L, "%s expected, got %s", |
| 173 | | tname, luaL_typename(L, narg)); |
| 174 | | return luaL_argerror(L, narg, msg); |
| 172 | const char *msg = lua_pushfstring(L, "%s expected, got %s", |
| 173 | tname, luaL_typename(L, narg)); |
| 174 | return luaL_argerror(L, narg, msg); |
| 175 | 175 | } |
| 176 | 176 | |
| 177 | 177 | |
| 178 | 178 | static void tag_error (lua_State *L, int narg, int tag) { |
| 179 | | typeerror(L, narg, lua_typename(L, tag)); |
| 179 | typeerror(L, narg, lua_typename(L, tag)); |
| 180 | 180 | } |
| 181 | 181 | |
| 182 | 182 | |
| 183 | 183 | LUALIB_API void luaL_where (lua_State *L, int level) { |
| 184 | | lua_Debug ar; |
| 185 | | if (lua_getstack(L, level, &ar)) { /* check function at level */ |
| 186 | | lua_getinfo(L, "Sl", &ar); /* get info about it */ |
| 187 | | if (ar.currentline > 0) { /* is there info? */ |
| 188 | | lua_pushfstring(L, "%s:%d: ", ar.short_src, ar.currentline); |
| 189 | | return; |
| 190 | | } |
| 191 | | } |
| 192 | | lua_pushliteral(L, ""); /* else, no information available... */ |
| 184 | lua_Debug ar; |
| 185 | if (lua_getstack(L, level, &ar)) { /* check function at level */ |
| 186 | lua_getinfo(L, "Sl", &ar); /* get info about it */ |
| 187 | if (ar.currentline > 0) { /* is there info? */ |
| 188 | lua_pushfstring(L, "%s:%d: ", ar.short_src, ar.currentline); |
| 189 | return; |
| 190 | } |
| 191 | } |
| 192 | lua_pushliteral(L, ""); /* else, no information available... */ |
| 193 | 193 | } |
| 194 | 194 | |
| 195 | 195 | |
| 196 | 196 | LUALIB_API int luaL_error (lua_State *L, const char *fmt, ...) { |
| 197 | | va_list argp; |
| 198 | | va_start(argp, fmt); |
| 199 | | luaL_where(L, 1); |
| 200 | | lua_pushvfstring(L, fmt, argp); |
| 201 | | va_end(argp); |
| 202 | | lua_concat(L, 2); |
| 203 | | return lua_error(L); |
| 197 | va_list argp; |
| 198 | va_start(argp, fmt); |
| 199 | luaL_where(L, 1); |
| 200 | lua_pushvfstring(L, fmt, argp); |
| 201 | va_end(argp); |
| 202 | lua_concat(L, 2); |
| 203 | return lua_error(L); |
| 204 | 204 | } |
| 205 | 205 | |
| 206 | 206 | |
| 207 | 207 | LUALIB_API int luaL_fileresult (lua_State *L, int stat, const char *fname) { |
| 208 | | int en = errno; /* calls to Lua API may change this value */ |
| 209 | | if (stat) { |
| 210 | | lua_pushboolean(L, 1); |
| 211 | | return 1; |
| 212 | | } |
| 213 | | else { |
| 214 | | lua_pushnil(L); |
| 215 | | if (fname) |
| 216 | | lua_pushfstring(L, "%s: %s", fname, strerror(en)); |
| 217 | | else |
| 218 | | lua_pushstring(L, strerror(en)); |
| 219 | | lua_pushinteger(L, en); |
| 220 | | return 3; |
| 221 | | } |
| 208 | int en = errno; /* calls to Lua API may change this value */ |
| 209 | if (stat) { |
| 210 | lua_pushboolean(L, 1); |
| 211 | return 1; |
| 212 | } |
| 213 | else { |
| 214 | lua_pushnil(L); |
| 215 | if (fname) |
| 216 | lua_pushfstring(L, "%s: %s", fname, strerror(en)); |
| 217 | else |
| 218 | lua_pushstring(L, strerror(en)); |
| 219 | lua_pushinteger(L, en); |
| 220 | return 3; |
| 221 | } |
| 222 | 222 | } |
| 223 | 223 | |
| 224 | 224 | |
| 225 | | #if !defined(inspectstat) /* { */ |
| 225 | #if !defined(inspectstat) /* { */ |
| 226 | 226 | |
| 227 | 227 | #if defined(LUA_USE_POSIX) |
| 228 | 228 | |
| r30857 | r30858 | |
| 232 | 232 | ** use appropriate macros to interpret 'pclose' return status |
| 233 | 233 | */ |
| 234 | 234 | #define inspectstat(stat,what) \ |
| 235 | | if (WIFEXITED(stat)) { stat = WEXITSTATUS(stat); } \ |
| 236 | | else if (WIFSIGNALED(stat)) { stat = WTERMSIG(stat); what = "signal"; } |
| 235 | if (WIFEXITED(stat)) { stat = WEXITSTATUS(stat); } \ |
| 236 | else if (WIFSIGNALED(stat)) { stat = WTERMSIG(stat); what = "signal"; } |
| 237 | 237 | |
| 238 | 238 | #else |
| 239 | 239 | |
| r30857 | r30858 | |
| 241 | 241 | |
| 242 | 242 | #endif |
| 243 | 243 | |
| 244 | | #endif /* } */ |
| 244 | #endif /* } */ |
| 245 | 245 | |
| 246 | 246 | |
| 247 | 247 | LUALIB_API int luaL_execresult (lua_State *L, int stat) { |
| 248 | | const char *what = "exit"; /* type of termination */ |
| 249 | | if (stat == -1) /* error? */ |
| 250 | | return luaL_fileresult(L, 0, NULL); |
| 251 | | else { |
| 252 | | inspectstat(stat, what); /* interpret result */ |
| 253 | | if (*what == 'e' && stat == 0) /* successful termination? */ |
| 254 | | lua_pushboolean(L, 1); |
| 255 | | else |
| 256 | | lua_pushnil(L); |
| 257 | | lua_pushstring(L, what); |
| 258 | | lua_pushinteger(L, stat); |
| 259 | | return 3; /* return true/nil,what,code */ |
| 260 | | } |
| 248 | const char *what = "exit"; /* type of termination */ |
| 249 | if (stat == -1) /* error? */ |
| 250 | return luaL_fileresult(L, 0, NULL); |
| 251 | else { |
| 252 | inspectstat(stat, what); /* interpret result */ |
| 253 | if (*what == 'e' && stat == 0) /* successful termination? */ |
| 254 | lua_pushboolean(L, 1); |
| 255 | else |
| 256 | lua_pushnil(L); |
| 257 | lua_pushstring(L, what); |
| 258 | lua_pushinteger(L, stat); |
| 259 | return 3; /* return true/nil,what,code */ |
| 260 | } |
| 261 | 261 | } |
| 262 | 262 | |
| 263 | 263 | /* }====================================================== */ |
| r30857 | r30858 | |
| 270 | 270 | */ |
| 271 | 271 | |
| 272 | 272 | LUALIB_API int luaL_newmetatable (lua_State *L, const char *tname) { |
| 273 | | luaL_getmetatable(L, tname); /* try to get metatable */ |
| 274 | | if (!lua_isnil(L, -1)) /* name already in use? */ |
| 275 | | return 0; /* leave previous value on top, but return 0 */ |
| 276 | | lua_pop(L, 1); |
| 277 | | lua_newtable(L); /* create metatable */ |
| 278 | | lua_pushvalue(L, -1); |
| 279 | | lua_setfield(L, LUA_REGISTRYINDEX, tname); /* registry.name = metatable */ |
| 280 | | return 1; |
| 273 | luaL_getmetatable(L, tname); /* try to get metatable */ |
| 274 | if (!lua_isnil(L, -1)) /* name already in use? */ |
| 275 | return 0; /* leave previous value on top, but return 0 */ |
| 276 | lua_pop(L, 1); |
| 277 | lua_newtable(L); /* create metatable */ |
| 278 | lua_pushvalue(L, -1); |
| 279 | lua_setfield(L, LUA_REGISTRYINDEX, tname); /* registry.name = metatable */ |
| 280 | return 1; |
| 281 | 281 | } |
| 282 | 282 | |
| 283 | 283 | |
| 284 | 284 | LUALIB_API void luaL_setmetatable (lua_State *L, const char *tname) { |
| 285 | | luaL_getmetatable(L, tname); |
| 286 | | lua_setmetatable(L, -2); |
| 285 | luaL_getmetatable(L, tname); |
| 286 | lua_setmetatable(L, -2); |
| 287 | 287 | } |
| 288 | 288 | |
| 289 | 289 | |
| 290 | 290 | LUALIB_API void *luaL_testudata (lua_State *L, int ud, const char *tname) { |
| 291 | | void *p = lua_touserdata(L, ud); |
| 292 | | if (p != NULL) { /* value is a userdata? */ |
| 293 | | if (lua_getmetatable(L, ud)) { /* does it have a metatable? */ |
| 294 | | luaL_getmetatable(L, tname); /* get correct metatable */ |
| 295 | | if (!lua_rawequal(L, -1, -2)) /* not the same? */ |
| 296 | | p = NULL; /* value is a userdata with wrong metatable */ |
| 297 | | lua_pop(L, 2); /* remove both metatables */ |
| 298 | | return p; |
| 299 | | } |
| 300 | | } |
| 301 | | return NULL; /* value is not a userdata with a metatable */ |
| 291 | void *p = lua_touserdata(L, ud); |
| 292 | if (p != NULL) { /* value is a userdata? */ |
| 293 | if (lua_getmetatable(L, ud)) { /* does it have a metatable? */ |
| 294 | luaL_getmetatable(L, tname); /* get correct metatable */ |
| 295 | if (!lua_rawequal(L, -1, -2)) /* not the same? */ |
| 296 | p = NULL; /* value is a userdata with wrong metatable */ |
| 297 | lua_pop(L, 2); /* remove both metatables */ |
| 298 | return p; |
| 299 | } |
| 300 | } |
| 301 | return NULL; /* value is not a userdata with a metatable */ |
| 302 | 302 | } |
| 303 | 303 | |
| 304 | 304 | |
| 305 | 305 | LUALIB_API void *luaL_checkudata (lua_State *L, int ud, const char *tname) { |
| 306 | | void *p = luaL_testudata(L, ud, tname); |
| 307 | | if (p == NULL) typeerror(L, ud, tname); |
| 308 | | return p; |
| 306 | void *p = luaL_testudata(L, ud, tname); |
| 307 | if (p == NULL) typeerror(L, ud, tname); |
| 308 | return p; |
| 309 | 309 | } |
| 310 | 310 | |
| 311 | 311 | /* }====================================================== */ |
| r30857 | r30858 | |
| 318 | 318 | */ |
| 319 | 319 | |
| 320 | 320 | LUALIB_API int luaL_checkoption (lua_State *L, int narg, const char *def, |
| 321 | | const char *const lst[]) { |
| 322 | | const char *name = (def) ? luaL_optstring(L, narg, def) : |
| 323 | | luaL_checkstring(L, narg); |
| 324 | | int i; |
| 325 | | for (i=0; lst[i]; i++) |
| 326 | | if (strcmp(lst[i], name) == 0) |
| 327 | | return i; |
| 328 | | return luaL_argerror(L, narg, |
| 329 | | lua_pushfstring(L, "invalid option " LUA_QS, name)); |
| 321 | const char *const lst[]) { |
| 322 | const char *name = (def) ? luaL_optstring(L, narg, def) : |
| 323 | luaL_checkstring(L, narg); |
| 324 | int i; |
| 325 | for (i=0; lst[i]; i++) |
| 326 | if (strcmp(lst[i], name) == 0) |
| 327 | return i; |
| 328 | return luaL_argerror(L, narg, |
| 329 | lua_pushfstring(L, "invalid option " LUA_QS, name)); |
| 330 | 330 | } |
| 331 | 331 | |
| 332 | 332 | |
| 333 | 333 | LUALIB_API void luaL_checkstack (lua_State *L, int space, const char *msg) { |
| 334 | | /* keep some extra space to run error routines, if needed */ |
| 335 | | const int extra = LUA_MINSTACK; |
| 336 | | if (!lua_checkstack(L, space + extra)) { |
| 337 | | if (msg) |
| 338 | | luaL_error(L, "stack overflow (%s)", msg); |
| 339 | | else |
| 340 | | luaL_error(L, "stack overflow"); |
| 341 | | } |
| 334 | /* keep some extra space to run error routines, if needed */ |
| 335 | const int extra = LUA_MINSTACK; |
| 336 | if (!lua_checkstack(L, space + extra)) { |
| 337 | if (msg) |
| 338 | luaL_error(L, "stack overflow (%s)", msg); |
| 339 | else |
| 340 | luaL_error(L, "stack overflow"); |
| 341 | } |
| 342 | 342 | } |
| 343 | 343 | |
| 344 | 344 | |
| 345 | 345 | LUALIB_API void luaL_checktype (lua_State *L, int narg, int t) { |
| 346 | | if (lua_type(L, narg) != t) |
| 347 | | tag_error(L, narg, t); |
| 346 | if (lua_type(L, narg) != t) |
| 347 | tag_error(L, narg, t); |
| 348 | 348 | } |
| 349 | 349 | |
| 350 | 350 | |
| 351 | 351 | LUALIB_API void luaL_checkany (lua_State *L, int narg) { |
| 352 | | if (lua_type(L, narg) == LUA_TNONE) |
| 353 | | luaL_argerror(L, narg, "value expected"); |
| 352 | if (lua_type(L, narg) == LUA_TNONE) |
| 353 | luaL_argerror(L, narg, "value expected"); |
| 354 | 354 | } |
| 355 | 355 | |
| 356 | 356 | |
| 357 | 357 | LUALIB_API const char *luaL_checklstring (lua_State *L, int narg, size_t *len) { |
| 358 | | const char *s = lua_tolstring(L, narg, len); |
| 359 | | if (!s) tag_error(L, narg, LUA_TSTRING); |
| 360 | | return s; |
| 358 | const char *s = lua_tolstring(L, narg, len); |
| 359 | if (!s) tag_error(L, narg, LUA_TSTRING); |
| 360 | return s; |
| 361 | 361 | } |
| 362 | 362 | |
| 363 | 363 | |
| 364 | 364 | LUALIB_API const char *luaL_optlstring (lua_State *L, int narg, |
| 365 | | const char *def, size_t *len) { |
| 366 | | if (lua_isnoneornil(L, narg)) { |
| 367 | | if (len) |
| 368 | | *len = (def ? strlen(def) : 0); |
| 369 | | return def; |
| 370 | | } |
| 371 | | else return luaL_checklstring(L, narg, len); |
| 365 | const char *def, size_t *len) { |
| 366 | if (lua_isnoneornil(L, narg)) { |
| 367 | if (len) |
| 368 | *len = (def ? strlen(def) : 0); |
| 369 | return def; |
| 370 | } |
| 371 | else return luaL_checklstring(L, narg, len); |
| 372 | 372 | } |
| 373 | 373 | |
| 374 | 374 | |
| 375 | 375 | LUALIB_API lua_Number luaL_checknumber (lua_State *L, int narg) { |
| 376 | | int isnum; |
| 377 | | lua_Number d = lua_tonumberx(L, narg, &isnum); |
| 378 | | if (!isnum) |
| 379 | | tag_error(L, narg, LUA_TNUMBER); |
| 380 | | return d; |
| 376 | int isnum; |
| 377 | lua_Number d = lua_tonumberx(L, narg, &isnum); |
| 378 | if (!isnum) |
| 379 | tag_error(L, narg, LUA_TNUMBER); |
| 380 | return d; |
| 381 | 381 | } |
| 382 | 382 | |
| 383 | 383 | |
| 384 | 384 | LUALIB_API lua_Number luaL_optnumber (lua_State *L, int narg, lua_Number def) { |
| 385 | | return luaL_opt(L, luaL_checknumber, narg, def); |
| 385 | return luaL_opt(L, luaL_checknumber, narg, def); |
| 386 | 386 | } |
| 387 | 387 | |
| 388 | 388 | |
| 389 | 389 | LUALIB_API lua_Integer luaL_checkinteger (lua_State *L, int narg) { |
| 390 | | int isnum; |
| 391 | | lua_Integer d = lua_tointegerx(L, narg, &isnum); |
| 392 | | if (!isnum) |
| 393 | | tag_error(L, narg, LUA_TNUMBER); |
| 394 | | return d; |
| 390 | int isnum; |
| 391 | lua_Integer d = lua_tointegerx(L, narg, &isnum); |
| 392 | if (!isnum) |
| 393 | tag_error(L, narg, LUA_TNUMBER); |
| 394 | return d; |
| 395 | 395 | } |
| 396 | 396 | |
| 397 | 397 | |
| 398 | 398 | LUALIB_API lua_Unsigned luaL_checkunsigned (lua_State *L, int narg) { |
| 399 | | int isnum; |
| 400 | | lua_Unsigned d = lua_tounsignedx(L, narg, &isnum); |
| 401 | | if (!isnum) |
| 402 | | tag_error(L, narg, LUA_TNUMBER); |
| 403 | | return d; |
| 399 | int isnum; |
| 400 | lua_Unsigned d = lua_tounsignedx(L, narg, &isnum); |
| 401 | if (!isnum) |
| 402 | tag_error(L, narg, LUA_TNUMBER); |
| 403 | return d; |
| 404 | 404 | } |
| 405 | 405 | |
| 406 | 406 | |
| 407 | 407 | LUALIB_API lua_Integer luaL_optinteger (lua_State *L, int narg, |
| 408 | | lua_Integer def) { |
| 409 | | return luaL_opt(L, luaL_checkinteger, narg, def); |
| 408 | lua_Integer def) { |
| 409 | return luaL_opt(L, luaL_checkinteger, narg, def); |
| 410 | 410 | } |
| 411 | 411 | |
| 412 | 412 | |
| 413 | 413 | LUALIB_API lua_Unsigned luaL_optunsigned (lua_State *L, int narg, |
| 414 | | lua_Unsigned def) { |
| 415 | | return luaL_opt(L, luaL_checkunsigned, narg, def); |
| 414 | lua_Unsigned def) { |
| 415 | return luaL_opt(L, luaL_checkunsigned, narg, def); |
| 416 | 416 | } |
| 417 | 417 | |
| 418 | 418 | /* }====================================================== */ |
| r30857 | r30858 | |
| 428 | 428 | ** check whether buffer is using a userdata on the stack as a temporary |
| 429 | 429 | ** buffer |
| 430 | 430 | */ |
| 431 | | #define buffonstack(B) ((B)->b != (B)->initb) |
| 431 | #define buffonstack(B) ((B)->b != (B)->initb) |
| 432 | 432 | |
| 433 | 433 | |
| 434 | 434 | /* |
| 435 | 435 | ** returns a pointer to a free area with at least 'sz' bytes |
| 436 | 436 | */ |
| 437 | 437 | LUALIB_API char *luaL_prepbuffsize (luaL_Buffer *B, size_t sz) { |
| 438 | | lua_State *L = B->L; |
| 439 | | if (B->size - B->n < sz) { /* not enough space? */ |
| 440 | | char *newbuff; |
| 441 | | size_t newsize = B->size * 2; /* double buffer size */ |
| 442 | | if (newsize - B->n < sz) /* not big enough? */ |
| 443 | | newsize = B->n + sz; |
| 444 | | if (newsize < B->n || newsize - B->n < sz) |
| 445 | | luaL_error(L, "buffer too large"); |
| 446 | | /* create larger buffer */ |
| 447 | | newbuff = (char *)lua_newuserdata(L, newsize * sizeof(char)); |
| 448 | | /* move content to new buffer */ |
| 449 | | memcpy(newbuff, B->b, B->n * sizeof(char)); |
| 450 | | if (buffonstack(B)) |
| 451 | | lua_remove(L, -2); /* remove old buffer */ |
| 452 | | B->b = newbuff; |
| 453 | | B->size = newsize; |
| 454 | | } |
| 455 | | return &B->b[B->n]; |
| 438 | lua_State *L = B->L; |
| 439 | if (B->size - B->n < sz) { /* not enough space? */ |
| 440 | char *newbuff; |
| 441 | size_t newsize = B->size * 2; /* double buffer size */ |
| 442 | if (newsize - B->n < sz) /* not big enough? */ |
| 443 | newsize = B->n + sz; |
| 444 | if (newsize < B->n || newsize - B->n < sz) |
| 445 | luaL_error(L, "buffer too large"); |
| 446 | /* create larger buffer */ |
| 447 | newbuff = (char *)lua_newuserdata(L, newsize * sizeof(char)); |
| 448 | /* move content to new buffer */ |
| 449 | memcpy(newbuff, B->b, B->n * sizeof(char)); |
| 450 | if (buffonstack(B)) |
| 451 | lua_remove(L, -2); /* remove old buffer */ |
| 452 | B->b = newbuff; |
| 453 | B->size = newsize; |
| 454 | } |
| 455 | return &B->b[B->n]; |
| 456 | 456 | } |
| 457 | 457 | |
| 458 | 458 | |
| 459 | 459 | LUALIB_API void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l) { |
| 460 | | char *b = luaL_prepbuffsize(B, l); |
| 461 | | memcpy(b, s, l * sizeof(char)); |
| 462 | | luaL_addsize(B, l); |
| 460 | char *b = luaL_prepbuffsize(B, l); |
| 461 | memcpy(b, s, l * sizeof(char)); |
| 462 | luaL_addsize(B, l); |
| 463 | 463 | } |
| 464 | 464 | |
| 465 | 465 | |
| 466 | 466 | LUALIB_API void luaL_addstring (luaL_Buffer *B, const char *s) { |
| 467 | | luaL_addlstring(B, s, strlen(s)); |
| 467 | luaL_addlstring(B, s, strlen(s)); |
| 468 | 468 | } |
| 469 | 469 | |
| 470 | 470 | |
| 471 | 471 | LUALIB_API void luaL_pushresult (luaL_Buffer *B) { |
| 472 | | lua_State *L = B->L; |
| 473 | | lua_pushlstring(L, B->b, B->n); |
| 474 | | if (buffonstack(B)) |
| 475 | | lua_remove(L, -2); /* remove old buffer */ |
| 472 | lua_State *L = B->L; |
| 473 | lua_pushlstring(L, B->b, B->n); |
| 474 | if (buffonstack(B)) |
| 475 | lua_remove(L, -2); /* remove old buffer */ |
| 476 | 476 | } |
| 477 | 477 | |
| 478 | 478 | |
| 479 | 479 | LUALIB_API void luaL_pushresultsize (luaL_Buffer *B, size_t sz) { |
| 480 | | luaL_addsize(B, sz); |
| 481 | | luaL_pushresult(B); |
| 480 | luaL_addsize(B, sz); |
| 481 | luaL_pushresult(B); |
| 482 | 482 | } |
| 483 | 483 | |
| 484 | 484 | |
| 485 | 485 | LUALIB_API void luaL_addvalue (luaL_Buffer *B) { |
| 486 | | lua_State *L = B->L; |
| 487 | | size_t l; |
| 488 | | const char *s = lua_tolstring(L, -1, &l); |
| 489 | | if (buffonstack(B)) |
| 490 | | lua_insert(L, -2); /* put value below buffer */ |
| 491 | | luaL_addlstring(B, s, l); |
| 492 | | lua_remove(L, (buffonstack(B)) ? -2 : -1); /* remove value */ |
| 486 | lua_State *L = B->L; |
| 487 | size_t l; |
| 488 | const char *s = lua_tolstring(L, -1, &l); |
| 489 | if (buffonstack(B)) |
| 490 | lua_insert(L, -2); /* put value below buffer */ |
| 491 | luaL_addlstring(B, s, l); |
| 492 | lua_remove(L, (buffonstack(B)) ? -2 : -1); /* remove value */ |
| 493 | 493 | } |
| 494 | 494 | |
| 495 | 495 | |
| 496 | 496 | LUALIB_API void luaL_buffinit (lua_State *L, luaL_Buffer *B) { |
| 497 | | B->L = L; |
| 498 | | B->b = B->initb; |
| 499 | | B->n = 0; |
| 500 | | B->size = LUAL_BUFFERSIZE; |
| 497 | B->L = L; |
| 498 | B->b = B->initb; |
| 499 | B->n = 0; |
| 500 | B->size = LUAL_BUFFERSIZE; |
| 501 | 501 | } |
| 502 | 502 | |
| 503 | 503 | |
| 504 | 504 | LUALIB_API char *luaL_buffinitsize (lua_State *L, luaL_Buffer *B, size_t sz) { |
| 505 | | luaL_buffinit(L, B); |
| 506 | | return luaL_prepbuffsize(B, sz); |
| 505 | luaL_buffinit(L, B); |
| 506 | return luaL_prepbuffsize(B, sz); |
| 507 | 507 | } |
| 508 | 508 | |
| 509 | 509 | /* }====================================================== */ |
| r30857 | r30858 | |
| 516 | 516 | */ |
| 517 | 517 | |
| 518 | 518 | /* index of free-list header */ |
| 519 | | #define freelist 0 |
| 519 | #define freelist 0 |
| 520 | 520 | |
| 521 | 521 | |
| 522 | 522 | LUALIB_API int luaL_ref (lua_State *L, int t) { |
| 523 | | int ref; |
| 524 | | if (lua_isnil(L, -1)) { |
| 525 | | lua_pop(L, 1); /* remove from stack */ |
| 526 | | return LUA_REFNIL; /* `nil' has a unique fixed reference */ |
| 527 | | } |
| 528 | | t = lua_absindex(L, t); |
| 529 | | lua_rawgeti(L, t, freelist); /* get first free element */ |
| 530 | | ref = (int)lua_tointeger(L, -1); /* ref = t[freelist] */ |
| 531 | | lua_pop(L, 1); /* remove it from stack */ |
| 532 | | if (ref != 0) { /* any free element? */ |
| 533 | | lua_rawgeti(L, t, ref); /* remove it from list */ |
| 534 | | lua_rawseti(L, t, freelist); /* (t[freelist] = t[ref]) */ |
| 535 | | } |
| 536 | | else /* no free elements */ |
| 537 | | ref = (int)lua_rawlen(L, t) + 1; /* get a new reference */ |
| 538 | | lua_rawseti(L, t, ref); |
| 539 | | return ref; |
| 523 | int ref; |
| 524 | if (lua_isnil(L, -1)) { |
| 525 | lua_pop(L, 1); /* remove from stack */ |
| 526 | return LUA_REFNIL; /* `nil' has a unique fixed reference */ |
| 527 | } |
| 528 | t = lua_absindex(L, t); |
| 529 | lua_rawgeti(L, t, freelist); /* get first free element */ |
| 530 | ref = (int)lua_tointeger(L, -1); /* ref = t[freelist] */ |
| 531 | lua_pop(L, 1); /* remove it from stack */ |
| 532 | if (ref != 0) { /* any free element? */ |
| 533 | lua_rawgeti(L, t, ref); /* remove it from list */ |
| 534 | lua_rawseti(L, t, freelist); /* (t[freelist] = t[ref]) */ |
| 535 | } |
| 536 | else /* no free elements */ |
| 537 | ref = (int)lua_rawlen(L, t) + 1; /* get a new reference */ |
| 538 | lua_rawseti(L, t, ref); |
| 539 | return ref; |
| 540 | 540 | } |
| 541 | 541 | |
| 542 | 542 | |
| 543 | 543 | LUALIB_API void luaL_unref (lua_State *L, int t, int ref) { |
| 544 | | if (ref >= 0) { |
| 545 | | t = lua_absindex(L, t); |
| 546 | | lua_rawgeti(L, t, freelist); |
| 547 | | lua_rawseti(L, t, ref); /* t[ref] = t[freelist] */ |
| 548 | | lua_pushinteger(L, ref); |
| 549 | | lua_rawseti(L, t, freelist); /* t[freelist] = ref */ |
| 550 | | } |
| 544 | if (ref >= 0) { |
| 545 | t = lua_absindex(L, t); |
| 546 | lua_rawgeti(L, t, freelist); |
| 547 | lua_rawseti(L, t, ref); /* t[ref] = t[freelist] */ |
| 548 | lua_pushinteger(L, ref); |
| 549 | lua_rawseti(L, t, freelist); /* t[freelist] = ref */ |
| 550 | } |
| 551 | 551 | } |
| 552 | 552 | |
| 553 | 553 | /* }====================================================== */ |
| r30857 | r30858 | |
| 560 | 560 | */ |
| 561 | 561 | |
| 562 | 562 | typedef struct LoadF { |
| 563 | | int n; /* number of pre-read characters */ |
| 564 | | FILE *f; /* file being read */ |
| 565 | | char buff[LUAL_BUFFERSIZE]; /* area for reading file */ |
| 563 | int n; /* number of pre-read characters */ |
| 564 | FILE *f; /* file being read */ |
| 565 | char buff[LUAL_BUFFERSIZE]; /* area for reading file */ |
| 566 | 566 | } LoadF; |
| 567 | 567 | |
| 568 | 568 | |
| 569 | 569 | static const char *getF (lua_State *L, void *ud, size_t *size) { |
| 570 | | LoadF *lf = (LoadF *)ud; |
| 571 | | (void)L; /* not used */ |
| 572 | | if (lf->n > 0) { /* are there pre-read characters to be read? */ |
| 573 | | *size = lf->n; /* return them (chars already in buffer) */ |
| 574 | | lf->n = 0; /* no more pre-read characters */ |
| 575 | | } |
| 576 | | else { /* read a block from file */ |
| 577 | | /* 'fread' can return > 0 *and* set the EOF flag. If next call to |
| 578 | | 'getF' called 'fread', it might still wait for user input. |
| 579 | | The next check avoids this problem. */ |
| 580 | | if (feof(lf->f)) return NULL; |
| 581 | | *size = fread(lf->buff, 1, sizeof(lf->buff), lf->f); /* read block */ |
| 582 | | } |
| 583 | | return lf->buff; |
| 570 | LoadF *lf = (LoadF *)ud; |
| 571 | (void)L; /* not used */ |
| 572 | if (lf->n > 0) { /* are there pre-read characters to be read? */ |
| 573 | *size = lf->n; /* return them (chars already in buffer) */ |
| 574 | lf->n = 0; /* no more pre-read characters */ |
| 575 | } |
| 576 | else { /* read a block from file */ |
| 577 | /* 'fread' can return > 0 *and* set the EOF flag. If next call to |
| 578 | 'getF' called 'fread', it might still wait for user input. |
| 579 | The next check avoids this problem. */ |
| 580 | if (feof(lf->f)) return NULL; |
| 581 | *size = fread(lf->buff, 1, sizeof(lf->buff), lf->f); /* read block */ |
| 582 | } |
| 583 | return lf->buff; |
| 584 | 584 | } |
| 585 | 585 | |
| 586 | 586 | |
| 587 | 587 | static int errfile (lua_State *L, const char *what, int fnameindex) { |
| 588 | | const char *serr = strerror(errno); |
| 589 | | const char *filename = lua_tostring(L, fnameindex) + 1; |
| 590 | | lua_pushfstring(L, "cannot %s %s: %s", what, filename, serr); |
| 591 | | lua_remove(L, fnameindex); |
| 592 | | return LUA_ERRFILE; |
| 588 | const char *serr = strerror(errno); |
| 589 | const char *filename = lua_tostring(L, fnameindex) + 1; |
| 590 | lua_pushfstring(L, "cannot %s %s: %s", what, filename, serr); |
| 591 | lua_remove(L, fnameindex); |
| 592 | return LUA_ERRFILE; |
| 593 | 593 | } |
| 594 | 594 | |
| 595 | 595 | |
| 596 | 596 | static int skipBOM (LoadF *lf) { |
| 597 | | const char *p = "\xEF\xBB\xBF"; /* Utf8 BOM mark */ |
| 598 | | int c; |
| 599 | | lf->n = 0; |
| 600 | | do { |
| 601 | | c = getc(lf->f); |
| 602 | | if (c == EOF || c != *(const unsigned char *)p++) return c; |
| 603 | | lf->buff[lf->n++] = c; /* to be read by the parser */ |
| 604 | | } while (*p != '\0'); |
| 605 | | lf->n = 0; /* prefix matched; discard it */ |
| 606 | | return getc(lf->f); /* return next character */ |
| 597 | const char *p = "\xEF\xBB\xBF"; /* Utf8 BOM mark */ |
| 598 | int c; |
| 599 | lf->n = 0; |
| 600 | do { |
| 601 | c = getc(lf->f); |
| 602 | if (c == EOF || c != *(const unsigned char *)p++) return c; |
| 603 | lf->buff[lf->n++] = c; /* to be read by the parser */ |
| 604 | } while (*p != '\0'); |
| 605 | lf->n = 0; /* prefix matched; discard it */ |
| 606 | return getc(lf->f); /* return next character */ |
| 607 | 607 | } |
| 608 | 608 | |
| 609 | 609 | |
| r30857 | r30858 | |
| 615 | 615 | ** a first-line comment). |
| 616 | 616 | */ |
| 617 | 617 | static int skipcomment (LoadF *lf, int *cp) { |
| 618 | | int c = *cp = skipBOM(lf); |
| 619 | | if (c == '#') { /* first line is a comment (Unix exec. file)? */ |
| 620 | | do { /* skip first line */ |
| 621 | | c = getc(lf->f); |
| 622 | | } while (c != EOF && c != '\n') ; |
| 623 | | *cp = getc(lf->f); /* skip end-of-line, if present */ |
| 624 | | return 1; /* there was a comment */ |
| 625 | | } |
| 626 | | else return 0; /* no comment */ |
| 618 | int c = *cp = skipBOM(lf); |
| 619 | if (c == '#') { /* first line is a comment (Unix exec. file)? */ |
| 620 | do { /* skip first line */ |
| 621 | c = getc(lf->f); |
| 622 | } while (c != EOF && c != '\n') ; |
| 623 | *cp = getc(lf->f); /* skip end-of-line, if present */ |
| 624 | return 1; /* there was a comment */ |
| 625 | } |
| 626 | else return 0; /* no comment */ |
| 627 | 627 | } |
| 628 | 628 | |
| 629 | 629 | |
| 630 | 630 | LUALIB_API int luaL_loadfilex (lua_State *L, const char *filename, |
| 631 | | const char *mode) { |
| 632 | | LoadF lf; |
| 633 | | int status, readstatus; |
| 634 | | int c; |
| 635 | | int fnameindex = lua_gettop(L) + 1; /* index of filename on the stack */ |
| 636 | | if (filename == NULL) { |
| 637 | | lua_pushliteral(L, "=stdin"); |
| 638 | | lf.f = stdin; |
| 639 | | } |
| 640 | | else { |
| 641 | | lua_pushfstring(L, "@%s", filename); |
| 642 | | lf.f = fopen(filename, "r"); |
| 643 | | if (lf.f == NULL) return errfile(L, "open", fnameindex); |
| 644 | | } |
| 645 | | if (skipcomment(&lf, &c)) /* read initial portion */ |
| 646 | | lf.buff[lf.n++] = '\n'; /* add line to correct line numbers */ |
| 647 | | if (c == LUA_SIGNATURE[0] && filename) { /* binary file? */ |
| 648 | | lf.f = freopen(filename, "rb", lf.f); /* reopen in binary mode */ |
| 649 | | if (lf.f == NULL) return errfile(L, "reopen", fnameindex); |
| 650 | | skipcomment(&lf, &c); /* re-read initial portion */ |
| 651 | | } |
| 652 | | if (c != EOF) |
| 653 | | lf.buff[lf.n++] = c; /* 'c' is the first character of the stream */ |
| 654 | | status = lua_load(L, getF, &lf, lua_tostring(L, -1), mode); |
| 655 | | readstatus = ferror(lf.f); |
| 656 | | if (filename) fclose(lf.f); /* close file (even in case of errors) */ |
| 657 | | if (readstatus) { |
| 658 | | lua_settop(L, fnameindex); /* ignore results from `lua_load' */ |
| 659 | | return errfile(L, "read", fnameindex); |
| 660 | | } |
| 661 | | lua_remove(L, fnameindex); |
| 662 | | return status; |
| 631 | const char *mode) { |
| 632 | LoadF lf; |
| 633 | int status, readstatus; |
| 634 | int c; |
| 635 | int fnameindex = lua_gettop(L) + 1; /* index of filename on the stack */ |
| 636 | if (filename == NULL) { |
| 637 | lua_pushliteral(L, "=stdin"); |
| 638 | lf.f = stdin; |
| 639 | } |
| 640 | else { |
| 641 | lua_pushfstring(L, "@%s", filename); |
| 642 | lf.f = fopen(filename, "r"); |
| 643 | if (lf.f == NULL) return errfile(L, "open", fnameindex); |
| 644 | } |
| 645 | if (skipcomment(&lf, &c)) /* read initial portion */ |
| 646 | lf.buff[lf.n++] = '\n'; /* add line to correct line numbers */ |
| 647 | if (c == LUA_SIGNATURE[0] && filename) { /* binary file? */ |
| 648 | lf.f = freopen(filename, "rb", lf.f); /* reopen in binary mode */ |
| 649 | if (lf.f == NULL) return errfile(L, "reopen", fnameindex); |
| 650 | skipcomment(&lf, &c); /* re-read initial portion */ |
| 651 | } |
| 652 | if (c != EOF) |
| 653 | lf.buff[lf.n++] = c; /* 'c' is the first character of the stream */ |
| 654 | status = lua_load(L, getF, &lf, lua_tostring(L, -1), mode); |
| 655 | readstatus = ferror(lf.f); |
| 656 | if (filename) fclose(lf.f); /* close file (even in case of errors) */ |
| 657 | if (readstatus) { |
| 658 | lua_settop(L, fnameindex); /* ignore results from `lua_load' */ |
| 659 | return errfile(L, "read", fnameindex); |
| 660 | } |
| 661 | lua_remove(L, fnameindex); |
| 662 | return status; |
| 663 | 663 | } |
| 664 | 664 | |
| 665 | 665 | |
| 666 | 666 | typedef struct LoadS { |
| 667 | | const char *s; |
| 668 | | size_t size; |
| 667 | const char *s; |
| 668 | size_t size; |
| 669 | 669 | } LoadS; |
| 670 | 670 | |
| 671 | 671 | |
| 672 | 672 | static const char *getS (lua_State *L, void *ud, size_t *size) { |
| 673 | | LoadS *ls = (LoadS *)ud; |
| 674 | | (void)L; /* not used */ |
| 675 | | if (ls->size == 0) return NULL; |
| 676 | | *size = ls->size; |
| 677 | | ls->size = 0; |
| 678 | | return ls->s; |
| 673 | LoadS *ls = (LoadS *)ud; |
| 674 | (void)L; /* not used */ |
| 675 | if (ls->size == 0) return NULL; |
| 676 | *size = ls->size; |
| 677 | ls->size = 0; |
| 678 | return ls->s; |
| 679 | 679 | } |
| 680 | 680 | |
| 681 | 681 | |
| 682 | 682 | LUALIB_API int luaL_loadbufferx (lua_State *L, const char *buff, size_t size, |
| 683 | | const char *name, const char *mode) { |
| 684 | | LoadS ls; |
| 685 | | ls.s = buff; |
| 686 | | ls.size = size; |
| 687 | | return lua_load(L, getS, &ls, name, mode); |
| 683 | const char *name, const char *mode) { |
| 684 | LoadS ls; |
| 685 | ls.s = buff; |
| 686 | ls.size = size; |
| 687 | return lua_load(L, getS, &ls, name, mode); |
| 688 | 688 | } |
| 689 | 689 | |
| 690 | 690 | |
| 691 | 691 | LUALIB_API int luaL_loadstring (lua_State *L, const char *s) { |
| 692 | | return luaL_loadbuffer(L, s, strlen(s), s); |
| 692 | return luaL_loadbuffer(L, s, strlen(s), s); |
| 693 | 693 | } |
| 694 | 694 | |
| 695 | 695 | /* }====================================================== */ |
| r30857 | r30858 | |
| 697 | 697 | |
| 698 | 698 | |
| 699 | 699 | LUALIB_API int luaL_getmetafield (lua_State *L, int obj, const char *event) { |
| 700 | | if (!lua_getmetatable(L, obj)) /* no metatable? */ |
| 701 | | return 0; |
| 702 | | lua_pushstring(L, event); |
| 703 | | lua_rawget(L, -2); |
| 704 | | if (lua_isnil(L, -1)) { |
| 705 | | lua_pop(L, 2); /* remove metatable and metafield */ |
| 706 | | return 0; |
| 707 | | } |
| 708 | | else { |
| 709 | | lua_remove(L, -2); /* remove only metatable */ |
| 710 | | return 1; |
| 711 | | } |
| 700 | if (!lua_getmetatable(L, obj)) /* no metatable? */ |
| 701 | return 0; |
| 702 | lua_pushstring(L, event); |
| 703 | lua_rawget(L, -2); |
| 704 | if (lua_isnil(L, -1)) { |
| 705 | lua_pop(L, 2); /* remove metatable and metafield */ |
| 706 | return 0; |
| 707 | } |
| 708 | else { |
| 709 | lua_remove(L, -2); /* remove only metatable */ |
| 710 | return 1; |
| 711 | } |
| 712 | 712 | } |
| 713 | 713 | |
| 714 | 714 | |
| 715 | 715 | LUALIB_API int luaL_callmeta (lua_State *L, int obj, const char *event) { |
| 716 | | obj = lua_absindex(L, obj); |
| 717 | | if (!luaL_getmetafield(L, obj, event)) /* no metafield? */ |
| 718 | | return 0; |
| 719 | | lua_pushvalue(L, obj); |
| 720 | | lua_call(L, 1, 1); |
| 721 | | return 1; |
| 716 | obj = lua_absindex(L, obj); |
| 717 | if (!luaL_getmetafield(L, obj, event)) /* no metafield? */ |
| 718 | return 0; |
| 719 | lua_pushvalue(L, obj); |
| 720 | lua_call(L, 1, 1); |
| 721 | return 1; |
| 722 | 722 | } |
| 723 | 723 | |
| 724 | 724 | |
| 725 | 725 | LUALIB_API int luaL_len (lua_State *L, int idx) { |
| 726 | | int l; |
| 727 | | int isnum; |
| 728 | | lua_len(L, idx); |
| 729 | | l = (int)lua_tointegerx(L, -1, &isnum); |
| 730 | | if (!isnum) |
| 731 | | luaL_error(L, "object length is not a number"); |
| 732 | | lua_pop(L, 1); /* remove object */ |
| 733 | | return l; |
| 726 | int l; |
| 727 | int isnum; |
| 728 | lua_len(L, idx); |
| 729 | l = (int)lua_tointegerx(L, -1, &isnum); |
| 730 | if (!isnum) |
| 731 | luaL_error(L, "object length is not a number"); |
| 732 | lua_pop(L, 1); /* remove object */ |
| 733 | return l; |
| 734 | 734 | } |
| 735 | 735 | |
| 736 | 736 | |
| 737 | 737 | LUALIB_API const char *luaL_tolstring (lua_State *L, int idx, size_t *len) { |
| 738 | | if (!luaL_callmeta(L, idx, "__tostring")) { /* no metafield? */ |
| 739 | | switch (lua_type(L, idx)) { |
| 740 | | case LUA_TNUMBER: |
| 741 | | case LUA_TSTRING: |
| 742 | | lua_pushvalue(L, idx); |
| 743 | | break; |
| 744 | | case LUA_TBOOLEAN: |
| 745 | | lua_pushstring(L, (lua_toboolean(L, idx) ? "true" : "false")); |
| 746 | | break; |
| 747 | | case LUA_TNIL: |
| 748 | | lua_pushliteral(L, "nil"); |
| 749 | | break; |
| 750 | | default: |
| 751 | | lua_pushfstring(L, "%s: %p", luaL_typename(L, idx), |
| 752 | | lua_topointer(L, idx)); |
| 753 | | break; |
| 754 | | } |
| 755 | | } |
| 756 | | return lua_tolstring(L, -1, len); |
| 738 | if (!luaL_callmeta(L, idx, "__tostring")) { /* no metafield? */ |
| 739 | switch (lua_type(L, idx)) { |
| 740 | case LUA_TNUMBER: |
| 741 | case LUA_TSTRING: |
| 742 | lua_pushvalue(L, idx); |
| 743 | break; |
| 744 | case LUA_TBOOLEAN: |
| 745 | lua_pushstring(L, (lua_toboolean(L, idx) ? "true" : "false")); |
| 746 | break; |
| 747 | case LUA_TNIL: |
| 748 | lua_pushliteral(L, "nil"); |
| 749 | break; |
| 750 | default: |
| 751 | lua_pushfstring(L, "%s: %p", luaL_typename(L, idx), |
| 752 | lua_topointer(L, idx)); |
| 753 | break; |
| 754 | } |
| 755 | } |
| 756 | return lua_tolstring(L, -1, len); |
| 757 | 757 | } |
| 758 | 758 | |
| 759 | 759 | |
| r30857 | r30858 | |
| 765 | 765 | #if defined(LUA_COMPAT_MODULE) |
| 766 | 766 | |
| 767 | 767 | static const char *luaL_findtable (lua_State *L, int idx, |
| 768 | | const char *fname, int szhint) { |
| 769 | | const char *e; |
| 770 | | if (idx) lua_pushvalue(L, idx); |
| 771 | | do { |
| 772 | | e = strchr(fname, '.'); |
| 773 | | if (e == NULL) e = fname + strlen(fname); |
| 774 | | lua_pushlstring(L, fname, e - fname); |
| 775 | | lua_rawget(L, -2); |
| 776 | | if (lua_isnil(L, -1)) { /* no such field? */ |
| 777 | | lua_pop(L, 1); /* remove this nil */ |
| 778 | | lua_createtable(L, 0, (*e == '.' ? 1 : szhint)); /* new table for field */ |
| 779 | | lua_pushlstring(L, fname, e - fname); |
| 780 | | lua_pushvalue(L, -2); |
| 781 | | lua_settable(L, -4); /* set new table into field */ |
| 782 | | } |
| 783 | | else if (!lua_istable(L, -1)) { /* field has a non-table value? */ |
| 784 | | lua_pop(L, 2); /* remove table and value */ |
| 785 | | return fname; /* return problematic part of the name */ |
| 786 | | } |
| 787 | | lua_remove(L, -2); /* remove previous table */ |
| 788 | | fname = e + 1; |
| 789 | | } while (*e == '.'); |
| 790 | | return NULL; |
| 768 | const char *fname, int szhint) { |
| 769 | const char *e; |
| 770 | if (idx) lua_pushvalue(L, idx); |
| 771 | do { |
| 772 | e = strchr(fname, '.'); |
| 773 | if (e == NULL) e = fname + strlen(fname); |
| 774 | lua_pushlstring(L, fname, e - fname); |
| 775 | lua_rawget(L, -2); |
| 776 | if (lua_isnil(L, -1)) { /* no such field? */ |
| 777 | lua_pop(L, 1); /* remove this nil */ |
| 778 | lua_createtable(L, 0, (*e == '.' ? 1 : szhint)); /* new table for field */ |
| 779 | lua_pushlstring(L, fname, e - fname); |
| 780 | lua_pushvalue(L, -2); |
| 781 | lua_settable(L, -4); /* set new table into field */ |
| 782 | } |
| 783 | else if (!lua_istable(L, -1)) { /* field has a non-table value? */ |
| 784 | lua_pop(L, 2); /* remove table and value */ |
| 785 | return fname; /* return problematic part of the name */ |
| 786 | } |
| 787 | lua_remove(L, -2); /* remove previous table */ |
| 788 | fname = e + 1; |
| 789 | } while (*e == '.'); |
| 790 | return NULL; |
| 791 | 791 | } |
| 792 | 792 | |
| 793 | 793 | |
| r30857 | r30858 | |
| 795 | 795 | ** Count number of elements in a luaL_Reg list. |
| 796 | 796 | */ |
| 797 | 797 | static int libsize (const luaL_Reg *l) { |
| 798 | | int size = 0; |
| 799 | | for (; l && l->name; l++) size++; |
| 800 | | return size; |
| 798 | int size = 0; |
| 799 | for (; l && l->name; l++) size++; |
| 800 | return size; |
| 801 | 801 | } |
| 802 | 802 | |
| 803 | 803 | |
| r30857 | r30858 | |
| 808 | 808 | ** the module table. |
| 809 | 809 | */ |
| 810 | 810 | LUALIB_API void luaL_pushmodule (lua_State *L, const char *modname, |
| 811 | | int sizehint) { |
| 812 | | luaL_findtable(L, LUA_REGISTRYINDEX, "_LOADED", 1); /* get _LOADED table */ |
| 813 | | lua_getfield(L, -1, modname); /* get _LOADED[modname] */ |
| 814 | | if (!lua_istable(L, -1)) { /* not found? */ |
| 815 | | lua_pop(L, 1); /* remove previous result */ |
| 816 | | /* try global variable (and create one if it does not exist) */ |
| 817 | | lua_pushglobaltable(L); |
| 818 | | if (luaL_findtable(L, 0, modname, sizehint) != NULL) |
| 819 | | luaL_error(L, "name conflict for module " LUA_QS, modname); |
| 820 | | lua_pushvalue(L, -1); |
| 821 | | lua_setfield(L, -3, modname); /* _LOADED[modname] = new table */ |
| 822 | | } |
| 823 | | lua_remove(L, -2); /* remove _LOADED table */ |
| 811 | int sizehint) { |
| 812 | luaL_findtable(L, LUA_REGISTRYINDEX, "_LOADED", 1); /* get _LOADED table */ |
| 813 | lua_getfield(L, -1, modname); /* get _LOADED[modname] */ |
| 814 | if (!lua_istable(L, -1)) { /* not found? */ |
| 815 | lua_pop(L, 1); /* remove previous result */ |
| 816 | /* try global variable (and create one if it does not exist) */ |
| 817 | lua_pushglobaltable(L); |
| 818 | if (luaL_findtable(L, 0, modname, sizehint) != NULL) |
| 819 | luaL_error(L, "name conflict for module " LUA_QS, modname); |
| 820 | lua_pushvalue(L, -1); |
| 821 | lua_setfield(L, -3, modname); /* _LOADED[modname] = new table */ |
| 822 | } |
| 823 | lua_remove(L, -2); /* remove _LOADED table */ |
| 824 | 824 | } |
| 825 | 825 | |
| 826 | 826 | |
| 827 | 827 | LUALIB_API void luaL_openlib (lua_State *L, const char *libname, |
| 828 | | const luaL_Reg *l, int nup) { |
| 829 | | luaL_checkversion(L); |
| 830 | | if (libname) { |
| 831 | | luaL_pushmodule(L, libname, libsize(l)); /* get/create library table */ |
| 832 | | lua_insert(L, -(nup + 1)); /* move library table to below upvalues */ |
| 833 | | } |
| 834 | | if (l) |
| 835 | | luaL_setfuncs(L, l, nup); |
| 836 | | else |
| 837 | | lua_pop(L, nup); /* remove upvalues */ |
| 828 | const luaL_Reg *l, int nup) { |
| 829 | luaL_checkversion(L); |
| 830 | if (libname) { |
| 831 | luaL_pushmodule(L, libname, libsize(l)); /* get/create library table */ |
| 832 | lua_insert(L, -(nup + 1)); /* move library table to below upvalues */ |
| 833 | } |
| 834 | if (l) |
| 835 | luaL_setfuncs(L, l, nup); |
| 836 | else |
| 837 | lua_pop(L, nup); /* remove upvalues */ |
| 838 | 838 | } |
| 839 | 839 | |
| 840 | 840 | #endif |
| r30857 | r30858 | |
| 846 | 846 | ** Returns with only the table at the stack. |
| 847 | 847 | */ |
| 848 | 848 | LUALIB_API void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup) { |
| 849 | | luaL_checkversion(L); |
| 850 | | luaL_checkstack(L, nup, "too many upvalues"); |
| 851 | | for (; l->name != NULL; l++) { /* fill the table with given functions */ |
| 852 | | int i; |
| 853 | | for (i = 0; i < nup; i++) /* copy upvalues to the top */ |
| 854 | | lua_pushvalue(L, -nup); |
| 855 | | lua_pushcclosure(L, l->func, nup); /* closure with those upvalues */ |
| 856 | | lua_setfield(L, -(nup + 2), l->name); |
| 857 | | } |
| 858 | | lua_pop(L, nup); /* remove upvalues */ |
| 849 | luaL_checkversion(L); |
| 850 | luaL_checkstack(L, nup, "too many upvalues"); |
| 851 | for (; l->name != NULL; l++) { /* fill the table with given functions */ |
| 852 | int i; |
| 853 | for (i = 0; i < nup; i++) /* copy upvalues to the top */ |
| 854 | lua_pushvalue(L, -nup); |
| 855 | lua_pushcclosure(L, l->func, nup); /* closure with those upvalues */ |
| 856 | lua_setfield(L, -(nup + 2), l->name); |
| 857 | } |
| 858 | lua_pop(L, nup); /* remove upvalues */ |
| 859 | 859 | } |
| 860 | 860 | |
| 861 | 861 | |
| r30857 | r30858 | |
| 864 | 864 | ** into the stack |
| 865 | 865 | */ |
| 866 | 866 | LUALIB_API int luaL_getsubtable (lua_State *L, int idx, const char *fname) { |
| 867 | | lua_getfield(L, idx, fname); |
| 868 | | if (lua_istable(L, -1)) return 1; /* table already there */ |
| 869 | | else { |
| 870 | | lua_pop(L, 1); /* remove previous result */ |
| 871 | | idx = lua_absindex(L, idx); |
| 872 | | lua_newtable(L); |
| 873 | | lua_pushvalue(L, -1); /* copy to be left at top */ |
| 874 | | lua_setfield(L, idx, fname); /* assign new table to field */ |
| 875 | | return 0; /* false, because did not find table there */ |
| 876 | | } |
| 867 | lua_getfield(L, idx, fname); |
| 868 | if (lua_istable(L, -1)) return 1; /* table already there */ |
| 869 | else { |
| 870 | lua_pop(L, 1); /* remove previous result */ |
| 871 | idx = lua_absindex(L, idx); |
| 872 | lua_newtable(L); |
| 873 | lua_pushvalue(L, -1); /* copy to be left at top */ |
| 874 | lua_setfield(L, idx, fname); /* assign new table to field */ |
| 875 | return 0; /* false, because did not find table there */ |
| 876 | } |
| 877 | 877 | } |
| 878 | 878 | |
| 879 | 879 | |
| r30857 | r30858 | |
| 884 | 884 | ** Leaves resulting module on the top. |
| 885 | 885 | */ |
| 886 | 886 | LUALIB_API void luaL_requiref (lua_State *L, const char *modname, |
| 887 | | lua_CFunction openf, int glb) { |
| 888 | | lua_pushcfunction(L, openf); |
| 889 | | lua_pushstring(L, modname); /* argument to open function */ |
| 890 | | lua_call(L, 1, 1); /* open module */ |
| 891 | | luaL_getsubtable(L, LUA_REGISTRYINDEX, "_LOADED"); |
| 892 | | lua_pushvalue(L, -2); /* make copy of module (call result) */ |
| 893 | | lua_setfield(L, -2, modname); /* _LOADED[modname] = module */ |
| 894 | | lua_pop(L, 1); /* remove _LOADED table */ |
| 895 | | if (glb) { |
| 896 | | lua_pushvalue(L, -1); /* copy of 'mod' */ |
| 897 | | lua_setglobal(L, modname); /* _G[modname] = module */ |
| 898 | | } |
| 887 | lua_CFunction openf, int glb) { |
| 888 | lua_pushcfunction(L, openf); |
| 889 | lua_pushstring(L, modname); /* argument to open function */ |
| 890 | lua_call(L, 1, 1); /* open module */ |
| 891 | luaL_getsubtable(L, LUA_REGISTRYINDEX, "_LOADED"); |
| 892 | lua_pushvalue(L, -2); /* make copy of module (call result) */ |
| 893 | lua_setfield(L, -2, modname); /* _LOADED[modname] = module */ |
| 894 | lua_pop(L, 1); /* remove _LOADED table */ |
| 895 | if (glb) { |
| 896 | lua_pushvalue(L, -1); /* copy of 'mod' */ |
| 897 | lua_setglobal(L, modname); /* _G[modname] = module */ |
| 898 | } |
| 899 | 899 | } |
| 900 | 900 | |
| 901 | 901 | |
| 902 | 902 | LUALIB_API const char *luaL_gsub (lua_State *L, const char *s, const char *p, |
| 903 | | const char *r) { |
| 904 | | const char *wild; |
| 905 | | size_t l = strlen(p); |
| 906 | | luaL_Buffer b; |
| 907 | | luaL_buffinit(L, &b); |
| 908 | | while ((wild = strstr(s, p)) != NULL) { |
| 909 | | luaL_addlstring(&b, s, wild - s); /* push prefix */ |
| 910 | | luaL_addstring(&b, r); /* push replacement in place of pattern */ |
| 911 | | s = wild + l; /* continue after `p' */ |
| 912 | | } |
| 913 | | luaL_addstring(&b, s); /* push last suffix */ |
| 914 | | luaL_pushresult(&b); |
| 915 | | return lua_tostring(L, -1); |
| 903 | const char *r) { |
| 904 | const char *wild; |
| 905 | size_t l = strlen(p); |
| 906 | luaL_Buffer b; |
| 907 | luaL_buffinit(L, &b); |
| 908 | while ((wild = strstr(s, p)) != NULL) { |
| 909 | luaL_addlstring(&b, s, wild - s); /* push prefix */ |
| 910 | luaL_addstring(&b, r); /* push replacement in place of pattern */ |
| 911 | s = wild + l; /* continue after `p' */ |
| 912 | } |
| 913 | luaL_addstring(&b, s); /* push last suffix */ |
| 914 | luaL_pushresult(&b); |
| 915 | return lua_tostring(L, -1); |
| 916 | 916 | } |
| 917 | 917 | |
| 918 | 918 | |
| 919 | 919 | static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) { |
| 920 | | (void)ud; (void)osize; /* not used */ |
| 921 | | if (nsize == 0) { |
| 922 | | free(ptr); |
| 923 | | return NULL; |
| 924 | | } |
| 925 | | else |
| 926 | | return realloc(ptr, nsize); |
| 920 | (void)ud; (void)osize; /* not used */ |
| 921 | if (nsize == 0) { |
| 922 | free(ptr); |
| 923 | return NULL; |
| 924 | } |
| 925 | else |
| 926 | return realloc(ptr, nsize); |
| 927 | 927 | } |
| 928 | 928 | |
| 929 | 929 | |
| 930 | 930 | static int panic (lua_State *L) { |
| 931 | | luai_writestringerror("PANIC: unprotected error in call to Lua API (%s)\n", |
| 932 | | lua_tostring(L, -1)); |
| 933 | | return 0; /* return to Lua to abort */ |
| 931 | luai_writestringerror("PANIC: unprotected error in call to Lua API (%s)\n", |
| 932 | lua_tostring(L, -1)); |
| 933 | return 0; /* return to Lua to abort */ |
| 934 | 934 | } |
| 935 | 935 | |
| 936 | 936 | |
| 937 | 937 | LUALIB_API lua_State *luaL_newstate (void) { |
| 938 | | lua_State *L = lua_newstate(l_alloc, NULL); |
| 939 | | if (L) lua_atpanic(L, &panic); |
| 940 | | return L; |
| 938 | lua_State *L = lua_newstate(l_alloc, NULL); |
| 939 | if (L) lua_atpanic(L, &panic); |
| 940 | return L; |
| 941 | 941 | } |
| 942 | 942 | |
| 943 | 943 | |
| 944 | 944 | LUALIB_API void luaL_checkversion_ (lua_State *L, lua_Number ver) { |
| 945 | | const lua_Number *v = lua_version(L); |
| 946 | | if (v != lua_version(NULL)) |
| 947 | | luaL_error(L, "multiple Lua VMs detected"); |
| 948 | | else if (*v != ver) |
| 949 | | luaL_error(L, "version mismatch: app. needs %f, Lua core provides %f", |
| 950 | | ver, *v); |
| 951 | | /* check conversions number -> integer types */ |
| 952 | | lua_pushnumber(L, -(lua_Number)0x1234); |
| 953 | | if (lua_tointeger(L, -1) != -0x1234 || |
| 954 | | lua_tounsigned(L, -1) != (lua_Unsigned)-0x1234) |
| 955 | | luaL_error(L, "bad conversion number->int;" |
| 956 | | " must recompile Lua with proper settings"); |
| 957 | | lua_pop(L, 1); |
| 945 | const lua_Number *v = lua_version(L); |
| 946 | if (v != lua_version(NULL)) |
| 947 | luaL_error(L, "multiple Lua VMs detected"); |
| 948 | else if (*v != ver) |
| 949 | luaL_error(L, "version mismatch: app. needs %f, Lua core provides %f", |
| 950 | ver, *v); |
| 951 | /* check conversions number -> integer types */ |
| 952 | lua_pushnumber(L, -(lua_Number)0x1234); |
| 953 | if (lua_tointeger(L, -1) != -0x1234 || |
| 954 | lua_tounsigned(L, -1) != (lua_Unsigned)-0x1234) |
| 955 | luaL_error(L, "bad conversion number->int;" |
| 956 | " must recompile Lua with proper settings"); |
| 957 | lua_pop(L, 1); |
| 958 | 958 | } |
| 959 | |
trunk/src/lib/lua/ldebug.c
| r30857 | r30858 | |
| 1 | 1 | /* |
| 2 | | ** $Id: ldebug.c,v 2.90 2012/08/16 17:34:28 roberto Exp $ |
| 2 | ** $Id: ldebug.c,v 2.90.1.3 2013/05/16 16:04:15 roberto Exp $ |
| 3 | 3 | ** Debug Interface |
| 4 | 4 | ** See Copyright Notice in lua.h |
| 5 | 5 | */ |
| r30857 | r30858 | |
| 30 | 30 | |
| 31 | 31 | |
| 32 | 32 | |
| 33 | | #define noLuaClosure(f) ((f) == NULL || (f)->c.tt == LUA_TCCL) |
| 33 | #define noLuaClosure(f) ((f) == NULL || (f)->c.tt == LUA_TCCL) |
| 34 | 34 | |
| 35 | 35 | |
| 36 | 36 | static const char *getfuncname (lua_State *L, CallInfo *ci, const char **name); |
| 37 | 37 | |
| 38 | 38 | |
| 39 | 39 | static int currentpc (CallInfo *ci) { |
| 40 | | lua_assert(isLua(ci)); |
| 41 | | return pcRel(ci->u.l.savedpc, ci_func(ci)->p); |
| 40 | lua_assert(isLua(ci)); |
| 41 | return pcRel(ci->u.l.savedpc, ci_func(ci)->p); |
| 42 | 42 | } |
| 43 | 43 | |
| 44 | 44 | |
| 45 | 45 | static int currentline (CallInfo *ci) { |
| 46 | | return getfuncline(ci_func(ci)->p, currentpc(ci)); |
| 46 | return getfuncline(ci_func(ci)->p, currentpc(ci)); |
| 47 | 47 | } |
| 48 | 48 | |
| 49 | 49 | |
| r30857 | r30858 | |
| 51 | 51 | ** this function can be called asynchronous (e.g. during a signal) |
| 52 | 52 | */ |
| 53 | 53 | LUA_API int lua_sethook (lua_State *L, lua_Hook func, int mask, int count) { |
| 54 | | if (func == NULL || mask == 0) { /* turn off hooks? */ |
| 55 | | mask = 0; |
| 56 | | func = NULL; |
| 57 | | } |
| 58 | | if (isLua(L->ci)) |
| 59 | | L->oldpc = L->ci->u.l.savedpc; |
| 60 | | L->hook = func; |
| 61 | | L->basehookcount = count; |
| 62 | | resethookcount(L); |
| 63 | | L->hookmask = cast_byte(mask); |
| 64 | | return 1; |
| 54 | if (func == NULL || mask == 0) { /* turn off hooks? */ |
| 55 | mask = 0; |
| 56 | func = NULL; |
| 57 | } |
| 58 | if (isLua(L->ci)) |
| 59 | L->oldpc = L->ci->u.l.savedpc; |
| 60 | L->hook = func; |
| 61 | L->basehookcount = count; |
| 62 | resethookcount(L); |
| 63 | L->hookmask = cast_byte(mask); |
| 64 | return 1; |
| 65 | 65 | } |
| 66 | 66 | |
| 67 | 67 | |
| 68 | 68 | LUA_API lua_Hook lua_gethook (lua_State *L) { |
| 69 | | return L->hook; |
| 69 | return L->hook; |
| 70 | 70 | } |
| 71 | 71 | |
| 72 | 72 | |
| 73 | 73 | LUA_API int lua_gethookmask (lua_State *L) { |
| 74 | | return L->hookmask; |
| 74 | return L->hookmask; |
| 75 | 75 | } |
| 76 | 76 | |
| 77 | 77 | |
| 78 | 78 | LUA_API int lua_gethookcount (lua_State *L) { |
| 79 | | return L->basehookcount; |
| 79 | return L->basehookcount; |
| 80 | 80 | } |
| 81 | 81 | |
| 82 | 82 | |
| 83 | 83 | LUA_API int lua_getstack (lua_State *L, int level, lua_Debug *ar) { |
| 84 | | int status; |
| 85 | | CallInfo *ci; |
| 86 | | if (level < 0) return 0; /* invalid (negative) level */ |
| 87 | | lua_lock(L); |
| 88 | | for (ci = L->ci; level > 0 && ci != &L->base_ci; ci = ci->previous) |
| 89 | | level--; |
| 90 | | if (level == 0 && ci != &L->base_ci) { /* level found? */ |
| 91 | | status = 1; |
| 92 | | ar->i_ci = ci; |
| 93 | | } |
| 94 | | else status = 0; /* no such level */ |
| 95 | | lua_unlock(L); |
| 96 | | return status; |
| 84 | int status; |
| 85 | CallInfo *ci; |
| 86 | if (level < 0) return 0; /* invalid (negative) level */ |
| 87 | lua_lock(L); |
| 88 | for (ci = L->ci; level > 0 && ci != &L->base_ci; ci = ci->previous) |
| 89 | level--; |
| 90 | if (level == 0 && ci != &L->base_ci) { /* level found? */ |
| 91 | status = 1; |
| 92 | ar->i_ci = ci; |
| 93 | } |
| 94 | else status = 0; /* no such level */ |
| 95 | lua_unlock(L); |
| 96 | return status; |
| 97 | 97 | } |
| 98 | 98 | |
| 99 | 99 | |
| 100 | 100 | static const char *upvalname (Proto *p, int uv) { |
| 101 | | TString *s = check_exp(uv < p->sizeupvalues, p->upvalues[uv].name); |
| 102 | | if (s == NULL) return "?"; |
| 103 | | else return getstr(s); |
| 101 | TString *s = check_exp(uv < p->sizeupvalues, p->upvalues[uv].name); |
| 102 | if (s == NULL) return "?"; |
| 103 | else return getstr(s); |
| 104 | 104 | } |
| 105 | 105 | |
| 106 | 106 | |
| 107 | 107 | static const char *findvararg (CallInfo *ci, int n, StkId *pos) { |
| 108 | | int nparams = clLvalue(ci->func)->p->numparams; |
| 109 | | if (n >= ci->u.l.base - ci->func - nparams) |
| 110 | | return NULL; /* no such vararg */ |
| 111 | | else { |
| 112 | | *pos = ci->func + nparams + n; |
| 113 | | return "(*vararg)"; /* generic name for any vararg */ |
| 114 | | } |
| 108 | int nparams = clLvalue(ci->func)->p->numparams; |
| 109 | if (n >= ci->u.l.base - ci->func - nparams) |
| 110 | return NULL; /* no such vararg */ |
| 111 | else { |
| 112 | *pos = ci->func + nparams + n; |
| 113 | return "(*vararg)"; /* generic name for any vararg */ |
| 114 | } |
| 115 | 115 | } |
| 116 | 116 | |
| 117 | 117 | |
| 118 | 118 | static const char *findlocal (lua_State *L, CallInfo *ci, int n, |
| 119 | | StkId *pos) { |
| 120 | | const char *name = NULL; |
| 121 | | StkId base; |
| 122 | | if (isLua(ci)) { |
| 123 | | if (n < 0) /* access to vararg values? */ |
| 124 | | return findvararg(ci, -n, pos); |
| 125 | | else { |
| 126 | | base = ci->u.l.base; |
| 127 | | name = luaF_getlocalname(ci_func(ci)->p, n, currentpc(ci)); |
| 128 | | } |
| 129 | | } |
| 130 | | else |
| 131 | | base = ci->func + 1; |
| 132 | | if (name == NULL) { /* no 'standard' name? */ |
| 133 | | StkId limit = (ci == L->ci) ? L->top : ci->next->func; |
| 134 | | if (limit - base >= n && n > 0) /* is 'n' inside 'ci' stack? */ |
| 135 | | name = "(*temporary)"; /* generic name for any valid slot */ |
| 136 | | else |
| 137 | | return NULL; /* no name */ |
| 138 | | } |
| 139 | | *pos = base + (n - 1); |
| 140 | | return name; |
| 119 | StkId *pos) { |
| 120 | const char *name = NULL; |
| 121 | StkId base; |
| 122 | if (isLua(ci)) { |
| 123 | if (n < 0) /* access to vararg values? */ |
| 124 | return findvararg(ci, -n, pos); |
| 125 | else { |
| 126 | base = ci->u.l.base; |
| 127 | name = luaF_getlocalname(ci_func(ci)->p, n, currentpc(ci)); |
| 128 | } |
| 129 | } |
| 130 | else |
| 131 | base = ci->func + 1; |
| 132 | if (name == NULL) { /* no 'standard' name? */ |
| 133 | StkId limit = (ci == L->ci) ? L->top : ci->next->func; |
| 134 | if (limit - base >= n && n > 0) /* is 'n' inside 'ci' stack? */ |
| 135 | name = "(*temporary)"; /* generic name for any valid slot */ |
| 136 | else |
| 137 | return NULL; /* no name */ |
| 138 | } |
| 139 | *pos = base + (n - 1); |
| 140 | return name; |
| 141 | 141 | } |
| 142 | 142 | |
| 143 | 143 | |
| 144 | 144 | LUA_API const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n) { |
| 145 | | const char *name; |
| 146 | | lua_lock(L); |
| 147 | | if (ar == NULL) { /* information about non-active function? */ |
| 148 | | if (!isLfunction(L->top - 1)) /* not a Lua function? */ |
| 149 | | name = NULL; |
| 150 | | else /* consider live variables at function start (parameters) */ |
| 151 | | name = luaF_getlocalname(clLvalue(L->top - 1)->p, n, 0); |
| 152 | | } |
| 153 | | else { /* active function; get information through 'ar' */ |
| 154 | | StkId pos = 0; /* to avoid warnings */ |
| 155 | | name = findlocal(L, ar->i_ci, n, &pos); |
| 156 | | if (name) { |
| 157 | | setobj2s(L, L->top, pos); |
| 158 | | api_incr_top(L); |
| 159 | | } |
| 160 | | } |
| 161 | | lua_unlock(L); |
| 162 | | return name; |
| 145 | const char *name; |
| 146 | lua_lock(L); |
| 147 | if (ar == NULL) { /* information about non-active function? */ |
| 148 | if (!isLfunction(L->top - 1)) /* not a Lua function? */ |
| 149 | name = NULL; |
| 150 | else /* consider live variables at function start (parameters) */ |
| 151 | name = luaF_getlocalname(clLvalue(L->top - 1)->p, n, 0); |
| 152 | } |
| 153 | else { /* active function; get information through 'ar' */ |
| 154 | StkId pos = 0; /* to avoid warnings */ |
| 155 | name = findlocal(L, ar->i_ci, n, &pos); |
| 156 | if (name) { |
| 157 | setobj2s(L, L->top, pos); |
| 158 | api_incr_top(L); |
| 159 | } |
| 160 | } |
| 161 | lua_unlock(L); |
| 162 | return name; |
| 163 | 163 | } |
| 164 | 164 | |
| 165 | 165 | |
| 166 | 166 | LUA_API const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n) { |
| 167 | | StkId pos = 0; /* to avoid warnings */ |
| 168 | | const char *name = findlocal(L, ar->i_ci, n, &pos); |
| 169 | | lua_lock(L); |
| 170 | | if (name) |
| 171 | | setobjs2s(L, pos, L->top - 1); |
| 172 | | L->top--; /* pop value */ |
| 173 | | lua_unlock(L); |
| 174 | | return name; |
| 167 | StkId pos = 0; /* to avoid warnings */ |
| 168 | const char *name = findlocal(L, ar->i_ci, n, &pos); |
| 169 | lua_lock(L); |
| 170 | if (name) |
| 171 | setobjs2s(L, pos, L->top - 1); |
| 172 | L->top--; /* pop value */ |
| 173 | lua_unlock(L); |
| 174 | return name; |
| 175 | 175 | } |
| 176 | 176 | |
| 177 | 177 | |
| 178 | 178 | static void funcinfo (lua_Debug *ar, Closure *cl) { |
| 179 | | if (noLuaClosure(cl)) { |
| 180 | | ar->source = "=[C]"; |
| 181 | | ar->linedefined = -1; |
| 182 | | ar->lastlinedefined = -1; |
| 183 | | ar->what = "C"; |
| 184 | | } |
| 185 | | else { |
| 186 | | Proto *p = cl->l.p; |
| 187 | | ar->source = p->source ? getstr(p->source) : "=?"; |
| 188 | | ar->linedefined = p->linedefined; |
| 189 | | ar->lastlinedefined = p->lastlinedefined; |
| 190 | | ar->what = (ar->linedefined == 0) ? "main" : "Lua"; |
| 191 | | } |
| 192 | | luaO_chunkid(ar->short_src, ar->source, LUA_IDSIZE); |
| 179 | if (noLuaClosure(cl)) { |
| 180 | ar->source = "=[C]"; |
| 181 | ar->linedefined = -1; |
| 182 | ar->lastlinedefined = -1; |
| 183 | ar->what = "C"; |
| 184 | } |
| 185 | else { |
| 186 | Proto *p = cl->l.p; |
| 187 | ar->source = p->source ? getstr(p->source) : "=?"; |
| 188 | ar->linedefined = p->linedefined; |
| 189 | ar->lastlinedefined = p->lastlinedefined; |
| 190 | ar->what = (ar->linedefined == 0) ? "main" : "Lua"; |
| 191 | } |
| 192 | luaO_chunkid(ar->short_src, ar->source, LUA_IDSIZE); |
| 193 | 193 | } |
| 194 | 194 | |
| 195 | 195 | |
| 196 | 196 | static void collectvalidlines (lua_State *L, Closure *f) { |
| 197 | | if (noLuaClosure(f)) { |
| 198 | | setnilvalue(L->top); |
| 199 | | api_incr_top(L); |
| 200 | | } |
| 201 | | else { |
| 202 | | int i; |
| 203 | | TValue v; |
| 204 | | int *lineinfo = f->l.p->lineinfo; |
| 205 | | Table *t = luaH_new(L); /* new table to store active lines */ |
| 206 | | sethvalue(L, L->top, t); /* push it on stack */ |
| 207 | | api_incr_top(L); |
| 208 | | setbvalue(&v, 1); /* boolean 'true' to be the value of all indices */ |
| 209 | | for (i = 0; i < f->l.p->sizelineinfo; i++) /* for all lines with code */ |
| 210 | | luaH_setint(L, t, lineinfo[i], &v); /* table[line] = true */ |
| 211 | | } |
| 197 | if (noLuaClosure(f)) { |
| 198 | setnilvalue(L->top); |
| 199 | api_incr_top(L); |
| 200 | } |
| 201 | else { |
| 202 | int i; |
| 203 | TValue v; |
| 204 | int *lineinfo = f->l.p->lineinfo; |
| 205 | Table *t = luaH_new(L); /* new table to store active lines */ |
| 206 | sethvalue(L, L->top, t); /* push it on stack */ |
| 207 | api_incr_top(L); |
| 208 | setbvalue(&v, 1); /* boolean 'true' to be the value of all indices */ |
| 209 | for (i = 0; i < f->l.p->sizelineinfo; i++) /* for all lines with code */ |
| 210 | luaH_setint(L, t, lineinfo[i], &v); /* table[line] = true */ |
| 211 | } |
| 212 | 212 | } |
| 213 | 213 | |
| 214 | 214 | |
| 215 | 215 | static int auxgetinfo (lua_State *L, const char *what, lua_Debug *ar, |
| 216 | | Closure *f, CallInfo *ci) { |
| 217 | | int status = 1; |
| 218 | | for (; *what; what++) { |
| 219 | | switch (*what) { |
| 220 | | case 'S': { |
| 221 | | funcinfo(ar, f); |
| 222 | | break; |
| 223 | | } |
| 224 | | case 'l': { |
| 225 | | ar->currentline = (ci && isLua(ci)) ? currentline(ci) : -1; |
| 226 | | break; |
| 227 | | } |
| 228 | | case 'u': { |
| 229 | | ar->nups = (f == NULL) ? 0 : f->c.nupvalues; |
| 230 | | if (noLuaClosure(f)) { |
| 231 | | ar->isvararg = 1; |
| 232 | | ar->nparams = 0; |
| 233 | | } |
| 234 | | else { |
| 235 | | ar->isvararg = f->l.p->is_vararg; |
| 236 | | ar->nparams = f->l.p->numparams; |
| 237 | | } |
| 238 | | break; |
| 239 | | } |
| 240 | | case 't': { |
| 241 | | ar->istailcall = (ci) ? ci->callstatus & CIST_TAIL : 0; |
| 242 | | break; |
| 243 | | } |
| 244 | | case 'n': { |
| 245 | | /* calling function is a known Lua function? */ |
| 246 | | if (ci && !(ci->callstatus & CIST_TAIL) && isLua(ci->previous)) |
| 247 | | ar->namewhat = getfuncname(L, ci->previous, &ar->name); |
| 248 | | else |
| 249 | | ar->namewhat = NULL; |
| 250 | | if (ar->namewhat == NULL) { |
| 251 | | ar->namewhat = ""; /* not found */ |
| 252 | | ar->name = NULL; |
| 253 | | } |
| 254 | | break; |
| 255 | | } |
| 256 | | case 'L': |
| 257 | | case 'f': /* handled by lua_getinfo */ |
| 258 | | break; |
| 259 | | default: status = 0; /* invalid option */ |
| 260 | | } |
| 261 | | } |
| 262 | | return status; |
| 216 | Closure *f, CallInfo *ci) { |
| 217 | int status = 1; |
| 218 | for (; *what; what++) { |
| 219 | switch (*what) { |
| 220 | case 'S': { |
| 221 | funcinfo(ar, f); |
| 222 | break; |
| 223 | } |
| 224 | case 'l': { |
| 225 | ar->currentline = (ci && isLua(ci)) ? currentline(ci) : -1; |
| 226 | break; |
| 227 | } |
| 228 | case 'u': { |
| 229 | ar->nups = (f == NULL) ? 0 : f->c.nupvalues; |
| 230 | if (noLuaClosure(f)) { |
| 231 | ar->isvararg = 1; |
| 232 | ar->nparams = 0; |
| 233 | } |
| 234 | else { |
| 235 | ar->isvararg = f->l.p->is_vararg; |
| 236 | ar->nparams = f->l.p->numparams; |
| 237 | } |
| 238 | break; |
| 239 | } |
| 240 | case 't': { |
| 241 | ar->istailcall = (ci) ? ci->callstatus & CIST_TAIL : 0; |
| 242 | break; |
| 243 | } |
| 244 | case 'n': { |
| 245 | /* calling function is a known Lua function? */ |
| 246 | if (ci && !(ci->callstatus & CIST_TAIL) && isLua(ci->previous)) |
| 247 | ar->namewhat = getfuncname(L, ci->previous, &ar->name); |
| 248 | else |
| 249 | ar->namewhat = NULL; |
| 250 | if (ar->namewhat == NULL) { |
| 251 | ar->namewhat = ""; /* not found */ |
| 252 | ar->name = NULL; |
| 253 | } |
| 254 | break; |
| 255 | } |
| 256 | case 'L': |
| 257 | case 'f': /* handled by lua_getinfo */ |
| 258 | break; |
| 259 | default: status = 0; /* invalid option */ |
| 260 | } |
| 261 | } |
| 262 | return status; |
| 263 | 263 | } |
| 264 | 264 | |
| 265 | 265 | |
| 266 | 266 | LUA_API int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar) { |
| 267 | | int status; |
| 268 | | Closure *cl; |
| 269 | | CallInfo *ci; |
| 270 | | StkId func; |
| 271 | | lua_lock(L); |
| 272 | | if (*what == '>') { |
| 273 | | ci = NULL; |
| 274 | | func = L->top - 1; |
| 275 | | api_check(L, ttisfunction(func), "function expected"); |
| 276 | | what++; /* skip the '>' */ |
| 277 | | L->top--; /* pop function */ |
| 278 | | } |
| 279 | | else { |
| 280 | | ci = ar->i_ci; |
| 281 | | func = ci->func; |
| 282 | | lua_assert(ttisfunction(ci->func)); |
| 283 | | } |
| 284 | | cl = ttisclosure(func) ? clvalue(func) : NULL; |
| 285 | | status = auxgetinfo(L, what, ar, cl, ci); |
| 286 | | if (strchr(what, 'f')) { |
| 287 | | setobjs2s(L, L->top, func); |
| 288 | | api_incr_top(L); |
| 289 | | } |
| 290 | | if (strchr(what, 'L')) |
| 291 | | collectvalidlines(L, cl); |
| 292 | | lua_unlock(L); |
| 293 | | return status; |
| 267 | int status; |
| 268 | Closure *cl; |
| 269 | CallInfo *ci; |
| 270 | StkId func; |
| 271 | lua_lock(L); |
| 272 | if (*what == '>') { |
| 273 | ci = NULL; |
| 274 | func = L->top - 1; |
| 275 | api_check(L, ttisfunction(func), "function expected"); |
| 276 | what++; /* skip the '>' */ |
| 277 | L->top--; /* pop function */ |
| 278 | } |
| 279 | else { |
| 280 | ci = ar->i_ci; |
| 281 | func = ci->func; |
| 282 | lua_assert(ttisfunction(ci->func)); |
| 283 | } |
| 284 | cl = ttisclosure(func) ? clvalue(func) : NULL; |
| 285 | status = auxgetinfo(L, what, ar, cl, ci); |
| 286 | if (strchr(what, 'f')) { |
| 287 | setobjs2s(L, L->top, func); |
| 288 | api_incr_top(L); |
| 289 | } |
| 290 | if (strchr(what, 'L')) |
| 291 | collectvalidlines(L, cl); |
| 292 | lua_unlock(L); |
| 293 | return status; |
| 294 | 294 | } |
| 295 | 295 | |
| 296 | 296 | |
| r30857 | r30858 | |
| 301 | 301 | */ |
| 302 | 302 | |
| 303 | 303 | static const char *getobjname (Proto *p, int lastpc, int reg, |
| 304 | | const char **name); |
| 304 | const char **name); |
| 305 | 305 | |
| 306 | 306 | |
| 307 | 307 | /* |
| 308 | 308 | ** find a "name" for the RK value 'c' |
| 309 | 309 | */ |
| 310 | 310 | static void kname (Proto *p, int pc, int c, const char **name) { |
| 311 | | if (ISK(c)) { /* is 'c' a constant? */ |
| 312 | | TValue *kvalue = &p->k[INDEXK(c)]; |
| 313 | | if (ttisstring(kvalue)) { /* literal constant? */ |
| 314 | | *name = svalue(kvalue); /* it is its own name */ |
| 315 | | return; |
| 316 | | } |
| 317 | | /* else no reasonable name found */ |
| 318 | | } |
| 319 | | else { /* 'c' is a register */ |
| 320 | | const char *what = getobjname(p, pc, c, name); /* search for 'c' */ |
| 321 | | if (what && *what == 'c') { /* found a constant name? */ |
| 322 | | return; /* 'name' already filled */ |
| 323 | | } |
| 324 | | /* else no reasonable name found */ |
| 325 | | } |
| 326 | | *name = "?"; /* no reasonable name found */ |
| 311 | if (ISK(c)) { /* is 'c' a constant? */ |
| 312 | TValue *kvalue = &p->k[INDEXK(c)]; |
| 313 | if (ttisstring(kvalue)) { /* literal constant? */ |
| 314 | *name = svalue(kvalue); /* it is its own name */ |
| 315 | return; |
| 316 | } |
| 317 | /* else no reasonable name found */ |
| 318 | } |
| 319 | else { /* 'c' is a register */ |
| 320 | const char *what = getobjname(p, pc, c, name); /* search for 'c' */ |
| 321 | if (what && *what == 'c') { /* found a constant name? */ |
| 322 | return; /* 'name' already filled */ |
| 323 | } |
| 324 | /* else no reasonable name found */ |
| 325 | } |
| 326 | *name = "?"; /* no reasonable name found */ |
| 327 | 327 | } |
| 328 | 328 | |
| 329 | 329 | |
| 330 | static int filterpc (int pc, int jmptarget) { |
| 331 | if (pc < jmptarget) /* is code conditional (inside a jump)? */ |
| 332 | return -1; /* cannot know who sets that register */ |
| 333 | else return pc; /* current position sets that register */ |
| 334 | } |
| 335 | |
| 336 | |
| 330 | 337 | /* |
| 331 | 338 | ** try to find last instruction before 'lastpc' that modified register 'reg' |
| 332 | 339 | */ |
| 333 | 340 | static int findsetreg (Proto *p, int lastpc, int reg) { |
| 334 | | int pc; |
| 335 | | int setreg = -1; /* keep last instruction that changed 'reg' */ |
| 336 | | for (pc = 0; pc < lastpc; pc++) { |
| 337 | | Instruction i = p->code[pc]; |
| 338 | | OpCode op = GET_OPCODE(i); |
| 339 | | int a = GETARG_A(i); |
| 340 | | switch (op) { |
| 341 | | case OP_LOADNIL: { |
| 342 | | int b = GETARG_B(i); |
| 343 | | if (a <= reg && reg <= a + b) /* set registers from 'a' to 'a+b' */ |
| 344 | | setreg = pc; |
| 345 | | break; |
| 346 | | } |
| 347 | | case OP_TFORCALL: { |
| 348 | | if (reg >= a + 2) setreg = pc; /* affect all regs above its base */ |
| 349 | | break; |
| 350 | | } |
| 351 | | case OP_CALL: |
| 352 | | case OP_TAILCALL: { |
| 353 | | if (reg >= a) setreg = pc; /* affect all registers above base */ |
| 354 | | break; |
| 355 | | } |
| 356 | | case OP_JMP: { |
| 357 | | int b = GETARG_sBx(i); |
| 358 | | int dest = pc + 1 + b; |
| 359 | | /* jump is forward and do not skip `lastpc'? */ |
| 360 | | if (pc < dest && dest <= lastpc) |
| 361 | | pc += b; /* do the jump */ |
| 362 | | break; |
| 363 | | } |
| 364 | | case OP_TEST: { |
| 365 | | if (reg == a) setreg = pc; /* jumped code can change 'a' */ |
| 366 | | break; |
| 367 | | } |
| 368 | | default: |
| 369 | | if (testAMode(op) && reg == a) /* any instruction that set A */ |
| 370 | | setreg = pc; |
| 371 | | break; |
| 372 | | } |
| 373 | | } |
| 374 | | return setreg; |
| 341 | int pc; |
| 342 | int setreg = -1; /* keep last instruction that changed 'reg' */ |
| 343 | int jmptarget = 0; /* any code before this address is conditional */ |
| 344 | for (pc = 0; pc < lastpc; pc++) { |
| 345 | Instruction i = p->code[pc]; |
| 346 | OpCode op = GET_OPCODE(i); |
| 347 | int a = GETARG_A(i); |
| 348 | switch (op) { |
| 349 | case OP_LOADNIL: { |
| 350 | int b = GETARG_B(i); |
| 351 | if (a <= reg && reg <= a + b) /* set registers from 'a' to 'a+b' */ |
| 352 | setreg = filterpc(pc, jmptarget); |
| 353 | break; |
| 354 | } |
| 355 | case OP_TFORCALL: { |
| 356 | if (reg >= a + 2) /* affect all regs above its base */ |
| 357 | setreg = filterpc(pc, jmptarget); |
| 358 | break; |
| 359 | } |
| 360 | case OP_CALL: |
| 361 | case OP_TAILCALL: { |
| 362 | if (reg >= a) /* affect all registers above base */ |
| 363 | setreg = filterpc(pc, jmptarget); |
| 364 | break; |
| 365 | } |
| 366 | case OP_JMP: { |
| 367 | int b = GETARG_sBx(i); |
| 368 | int dest = pc + 1 + b; |
| 369 | /* jump is forward and do not skip `lastpc'? */ |
| 370 | if (pc < dest && dest <= lastpc) { |
| 371 | if (dest > jmptarget) |
| 372 | jmptarget = dest; /* update 'jmptarget' */ |
| 373 | } |
| 374 | break; |
| 375 | } |
| 376 | case OP_TEST: { |
| 377 | if (reg == a) /* jumped code can change 'a' */ |
| 378 | setreg = filterpc(pc, jmptarget); |
| 379 | break; |
| 380 | } |
| 381 | default: |
| 382 | if (testAMode(op) && reg == a) /* any instruction that set A */ |
| 383 | setreg = filterpc(pc, jmptarget); |
| 384 | break; |
| 385 | } |
| 386 | } |
| 387 | return setreg; |
| 375 | 388 | } |
| 376 | 389 | |
| 377 | 390 | |
| 378 | 391 | static const char *getobjname (Proto *p, int lastpc, int reg, |
| 379 | | const char **name) { |
| 380 | | int pc; |
| 381 | | *name = luaF_getlocalname(p, reg + 1, lastpc); |
| 382 | | if (*name) /* is a local? */ |
| 383 | | return "local"; |
| 384 | | /* else try symbolic execution */ |
| 385 | | pc = findsetreg(p, lastpc, reg); |
| 386 | | if (pc != -1) { /* could find instruction? */ |
| 387 | | Instruction i = p->code[pc]; |
| 388 | | OpCode op = GET_OPCODE(i); |
| 389 | | switch (op) { |
| 390 | | case OP_MOVE: { |
| 391 | | int b = GETARG_B(i); /* move from 'b' to 'a' */ |
| 392 | | if (b < GETARG_A(i)) |
| 393 | | return getobjname(p, pc, b, name); /* get name for 'b' */ |
| 394 | | break; |
| 395 | | } |
| 396 | | case OP_GETTABUP: |
| 397 | | case OP_GETTABLE: { |
| 398 | | int k = GETARG_C(i); /* key index */ |
| 399 | | int t = GETARG_B(i); /* table index */ |
| 400 | | const char *vn = (op == OP_GETTABLE) /* name of indexed variable */ |
| 401 | | ? luaF_getlocalname(p, t + 1, pc) |
| 402 | | : upvalname(p, t); |
| 403 | | kname(p, pc, k, name); |
| 404 | | return (vn && strcmp(vn, LUA_ENV) == 0) ? "global" : "field"; |
| 405 | | } |
| 406 | | case OP_GETUPVAL: { |
| 407 | | *name = upvalname(p, GETARG_B(i)); |
| 408 | | return "upvalue"; |
| 409 | | } |
| 410 | | case OP_LOADK: |
| 411 | | case OP_LOADKX: { |
| 412 | | int b = (op == OP_LOADK) ? GETARG_Bx(i) |
| 413 | | : GETARG_Ax(p->code[pc + 1]); |
| 414 | | if (ttisstring(&p->k[b])) { |
| 415 | | *name = svalue(&p->k[b]); |
| 416 | | return "constant"; |
| 417 | | } |
| 418 | | break; |
| 419 | | } |
| 420 | | case OP_SELF: { |
| 421 | | int k = GETARG_C(i); /* key index */ |
| 422 | | kname(p, pc, k, name); |
| 423 | | return "method"; |
| 424 | | } |
| 425 | | default: break; /* go through to return NULL */ |
| 426 | | } |
| 427 | | } |
| 428 | | return NULL; /* could not find reasonable name */ |
| 392 | const char **name) { |
| 393 | int pc; |
| 394 | *name = luaF_getlocalname(p, reg + 1, lastpc); |
| 395 | if (*name) /* is a local? */ |
| 396 | return "local"; |
| 397 | /* else try symbolic execution */ |
| 398 | pc = findsetreg(p, lastpc, reg); |
| 399 | if (pc != -1) { /* could find instruction? */ |
| 400 | Instruction i = p->code[pc]; |
| 401 | OpCode op = GET_OPCODE(i); |
| 402 | switch (op) { |
| 403 | case OP_MOVE: { |
| 404 | int b = GETARG_B(i); /* move from 'b' to 'a' */ |
| 405 | if (b < GETARG_A(i)) |
| 406 | return getobjname(p, pc, b, name); /* get name for 'b' */ |
| 407 | break; |
| 408 | } |
| 409 | case OP_GETTABUP: |
| 410 | case OP_GETTABLE: { |
| 411 | int k = GETARG_C(i); /* key index */ |
| 412 | int t = GETARG_B(i); /* table index */ |
| 413 | const char *vn = (op == OP_GETTABLE) /* name of indexed variable */ |
| 414 | ? luaF_getlocalname(p, t + 1, pc) |
| 415 | : upvalname(p, t); |
| 416 | kname(p, pc, k, name); |
| 417 | return (vn && strcmp(vn, LUA_ENV) == 0) ? "global" : "field"; |
| 418 | } |
| 419 | case OP_GETUPVAL: { |
| 420 | *name = upvalname(p, GETARG_B(i)); |
| 421 | return "upvalue"; |
| 422 | } |
| 423 | case OP_LOADK: |
| 424 | case OP_LOADKX: { |
| 425 | int b = (op == OP_LOADK) ? GETARG_Bx(i) |
| 426 | : GETARG_Ax(p->code[pc + 1]); |
| 427 | if (ttisstring(&p->k[b])) { |
| 428 | *name = svalue(&p->k[b]); |
| 429 | return "constant"; |
| 430 | } |
| 431 | break; |
| 432 | } |
| 433 | case OP_SELF: { |
| 434 | int k = GETARG_C(i); /* key index */ |
| 435 | kname(p, pc, k, name); |
| 436 | return "method"; |
| 437 | } |
| 438 | default: break; /* go through to return NULL */ |
| 439 | } |
| 440 | } |
| 441 | return NULL; /* could not find reasonable name */ |
| 429 | 442 | } |
| 430 | 443 | |
| 431 | 444 | |
| 432 | 445 | static const char *getfuncname (lua_State *L, CallInfo *ci, const char **name) { |
| 433 | | TMS tm; |
| 434 | | Proto *p = ci_func(ci)->p; /* calling function */ |
| 435 | | int pc = currentpc(ci); /* calling instruction index */ |
| 436 | | Instruction i = p->code[pc]; /* calling instruction */ |
| 437 | | switch (GET_OPCODE(i)) { |
| 438 | | case OP_CALL: |
| 439 | | case OP_TAILCALL: /* get function name */ |
| 440 | | return getobjname(p, pc, GETARG_A(i), name); |
| 441 | | case OP_TFORCALL: { /* for iterator */ |
| 442 | | *name = "for iterator"; |
| 443 | | return "for iterator"; |
| 444 | | } |
| 445 | | /* all other instructions can call only through metamethods */ |
| 446 | | case OP_SELF: |
| 447 | | case OP_GETTABUP: |
| 448 | | case OP_GETTABLE: tm = TM_INDEX; break; |
| 449 | | case OP_SETTABUP: |
| 450 | | case OP_SETTABLE: tm = TM_NEWINDEX; break; |
| 451 | | case OP_EQ: tm = TM_EQ; break; |
| 452 | | case OP_ADD: tm = TM_ADD; break; |
| 453 | | case OP_SUB: tm = TM_SUB; break; |
| 454 | | case OP_MUL: tm = TM_MUL; break; |
| 455 | | case OP_DIV: tm = TM_DIV; break; |
| 456 | | case OP_MOD: tm = TM_MOD; break; |
| 457 | | case OP_POW: tm = TM_POW; break; |
| 458 | | case OP_UNM: tm = TM_UNM; break; |
| 459 | | case OP_LEN: tm = TM_LEN; break; |
| 460 | | case OP_LT: tm = TM_LT; break; |
| 461 | | case OP_LE: tm = TM_LE; break; |
| 462 | | case OP_CONCAT: tm = TM_CONCAT; break; |
| 463 | | default: |
| 464 | | return NULL; /* else no useful name can be found */ |
| 465 | | } |
| 466 | | *name = getstr(G(L)->tmname[tm]); |
| 467 | | return "metamethod"; |
| 446 | TMS tm; |
| 447 | Proto *p = ci_func(ci)->p; /* calling function */ |
| 448 | int pc = currentpc(ci); /* calling instruction index */ |
| 449 | Instruction i = p->code[pc]; /* calling instruction */ |
| 450 | switch (GET_OPCODE(i)) { |
| 451 | case OP_CALL: |
| 452 | case OP_TAILCALL: /* get function name */ |
| 453 | return getobjname(p, pc, GETARG_A(i), name); |
| 454 | case OP_TFORCALL: { /* for iterator */ |
| 455 | *name = "for iterator"; |
| 456 | return "for iterator"; |
| 457 | } |
| 458 | /* all other instructions can call only through metamethods */ |
| 459 | case OP_SELF: |
| 460 | case OP_GETTABUP: |
| 461 | case OP_GETTABLE: tm = TM_INDEX; break; |
| 462 | case OP_SETTABUP: |
| 463 | case OP_SETTABLE: tm = TM_NEWINDEX; break; |
| 464 | case OP_EQ: tm = TM_EQ; break; |
| 465 | case OP_ADD: tm = TM_ADD; break; |
| 466 | case OP_SUB: tm = TM_SUB; break; |
| 467 | case OP_MUL: tm = TM_MUL; break; |
| 468 | case OP_DIV: tm = TM_DIV; break; |
| 469 | case OP_MOD: tm = TM_MOD; break; |
| 470 | case OP_POW: tm = TM_POW; break; |
| 471 | case OP_UNM: tm = TM_UNM; break; |
| 472 | case OP_LEN: tm = TM_LEN; break; |
| 473 | case OP_LT: tm = TM_LT; break; |
| 474 | case OP_LE: tm = TM_LE; break; |
| 475 | case OP_CONCAT: tm = TM_CONCAT; break; |
| 476 | default: |
| 477 | return NULL; /* else no useful name can be found */ |
| 478 | } |
| 479 | *name = getstr(G(L)->tmname[tm]); |
| 480 | return "metamethod"; |
| 468 | 481 | } |
| 469 | 482 | |
| 470 | 483 | /* }====================================================== */ |
| r30857 | r30858 | |
| 476 | 489 | ** (used only for error messages, so efficiency is not a big concern) |
| 477 | 490 | */ |
| 478 | 491 | static int isinstack (CallInfo *ci, const TValue *o) { |
| 479 | | StkId p; |
| 480 | | for (p = ci->u.l.base; p < ci->top; p++) |
| 481 | | if (o == p) return 1; |
| 482 | | return 0; |
| 492 | StkId p; |
| 493 | for (p = ci->u.l.base; p < ci->top; p++) |
| 494 | if (o == p) return 1; |
| 495 | return 0; |
| 483 | 496 | } |
| 484 | 497 | |
| 485 | 498 | |
| 486 | 499 | static const char *getupvalname (CallInfo *ci, const TValue *o, |
| 487 | | const char **name) { |
| 488 | | LClosure *c = ci_func(ci); |
| 489 | | int i; |
| 490 | | for (i = 0; i < c->nupvalues; i++) { |
| 491 | | if (c->upvals[i]->v == o) { |
| 492 | | *name = upvalname(c->p, i); |
| 493 | | return "upvalue"; |
| 494 | | } |
| 495 | | } |
| 496 | | return NULL; |
| 500 | const char **name) { |
| 501 | LClosure *c = ci_func(ci); |
| 502 | int i; |
| 503 | for (i = 0; i < c->nupvalues; i++) { |
| 504 | if (c->upvals[i]->v == o) { |
| 505 | *name = upvalname(c->p, i); |
| 506 | return "upvalue"; |
| 507 | } |
| 508 | } |
| 509 | return NULL; |
| 497 | 510 | } |
| 498 | 511 | |
| 499 | 512 | |
| 500 | 513 | l_noret luaG_typeerror (lua_State *L, const TValue *o, const char *op) { |
| 501 | | CallInfo *ci = L->ci; |
| 502 | | const char *name = NULL; |
| 503 | | const char *t = objtypename(o); |
| 504 | | const char *kind = NULL; |
| 505 | | if (isLua(ci)) { |
| 506 | | kind = getupvalname(ci, o, &name); /* check whether 'o' is an upvalue */ |
| 507 | | if (!kind && isinstack(ci, o)) /* no? try a register */ |
| 508 | | kind = getobjname(ci_func(ci)->p, currentpc(ci), |
| 509 | | cast_int(o - ci->u.l.base), &name); |
| 510 | | } |
| 511 | | if (kind) |
| 512 | | luaG_runerror(L, "attempt to %s %s " LUA_QS " (a %s value)", |
| 513 | | op, kind, name, t); |
| 514 | | else |
| 515 | | luaG_runerror(L, "attempt to %s a %s value", op, t); |
| 514 | CallInfo *ci = L->ci; |
| 515 | const char *name = NULL; |
| 516 | const char *t = objtypename(o); |
| 517 | const char *kind = NULL; |
| 518 | if (isLua(ci)) { |
| 519 | kind = getupvalname(ci, o, &name); /* check whether 'o' is an upvalue */ |
| 520 | if (!kind && isinstack(ci, o)) /* no? try a register */ |
| 521 | kind = getobjname(ci_func(ci)->p, currentpc(ci), |
| 522 | cast_int(o - ci->u.l.base), &name); |
| 523 | } |
| 524 | if (kind) |
| 525 | luaG_runerror(L, "attempt to %s %s " LUA_QS " (a %s value)", |
| 526 | op, kind, name, t); |
| 527 | else |
| 528 | luaG_runerror(L, "attempt to %s a %s value", op, t); |
| 516 | 529 | } |
| 517 | 530 | |
| 518 | 531 | |
| 519 | 532 | l_noret luaG_concaterror (lua_State *L, StkId p1, StkId p2) { |
| 520 | | if (ttisstring(p1) || ttisnumber(p1)) p1 = p2; |
| 521 | | lua_assert(!ttisstring(p1) && !ttisnumber(p2)); |
| 522 | | luaG_typeerror(L, p1, "concatenate"); |
| 533 | if (ttisstring(p1) || ttisnumber(p1)) p1 = p2; |
| 534 | lua_assert(!ttisstring(p1) && !ttisnumber(p1)); |
| 535 | luaG_typeerror(L, p1, "concatenate"); |
| 523 | 536 | } |
| 524 | 537 | |
| 525 | 538 | |
| 526 | 539 | l_noret luaG_aritherror (lua_State *L, const TValue *p1, const TValue *p2) { |
| 527 | | TValue temp; |
| 528 | | if (luaV_tonumber(p1, &temp) == NULL) |
| 529 | | p2 = p1; /* first operand is wrong */ |
| 530 | | luaG_typeerror(L, p2, "perform arithmetic on"); |
| 540 | TValue temp; |
| 541 | if (luaV_tonumber(p1, &temp) == NULL) |
| 542 | p2 = p1; /* first operand is wrong */ |
| 543 | luaG_typeerror(L, p2, "perform arithmetic on"); |
| 531 | 544 | } |
| 532 | 545 | |
| 533 | 546 | |
| 534 | 547 | l_noret luaG_ordererror (lua_State *L, const TValue *p1, const TValue *p2) { |
| 535 | | const char *t1 = objtypename(p1); |
| 536 | | const char *t2 = objtypename(p2); |
| 537 | | if (t1 == t2) |
| 538 | | luaG_runerror(L, "attempt to compare two %s values", t1); |
| 539 | | else |
| 540 | | luaG_runerror(L, "attempt to compare %s with %s", t1, t2); |
| 548 | const char *t1 = objtypename(p1); |
| 549 | const char *t2 = objtypename(p2); |
| 550 | if (t1 == t2) |
| 551 | luaG_runerror(L, "attempt to compare two %s values", t1); |
| 552 | else |
| 553 | luaG_runerror(L, "attempt to compare %s with %s", t1, t2); |
| 541 | 554 | } |
| 542 | 555 | |
| 543 | 556 | |
| 544 | 557 | static void addinfo (lua_State *L, const char *msg) { |
| 545 | | CallInfo *ci = L->ci; |
| 546 | | if (isLua(ci)) { /* is Lua code? */ |
| 547 | | char buff[LUA_IDSIZE]; /* add file:line information */ |
| 548 | | int line = currentline(ci); |
| 549 | | TString *src = ci_func(ci)->p->source; |
| 550 | | if (src) |
| 551 | | luaO_chunkid(buff, getstr(src), LUA_IDSIZE); |
| 552 | | else { /* no source available; use "?" instead */ |
| 553 | | buff[0] = '?'; buff[1] = '\0'; |
| 554 | | } |
| 555 | | luaO_pushfstring(L, "%s:%d: %s", buff, line, msg); |
| 556 | | } |
| 558 | CallInfo *ci = L->ci; |
| 559 | if (isLua(ci)) { /* is Lua code? */ |
| 560 | char buff[LUA_IDSIZE]; /* add file:line information */ |
| 561 | int line = currentline(ci); |
| 562 | TString *src = ci_func(ci)->p->source; |
| 563 | if (src) |
| 564 | luaO_chunkid(buff, getstr(src), LUA_IDSIZE); |
| 565 | else { /* no source available; use "?" instead */ |
| 566 | buff[0] = '?'; buff[1] = '\0'; |
| 567 | } |
| 568 | luaO_pushfstring(L, "%s:%d: %s", buff, line, msg); |
| 569 | } |
| 557 | 570 | } |
| 558 | 571 | |
| 559 | 572 | |
| 560 | 573 | l_noret luaG_errormsg (lua_State *L) { |
| 561 | | if (L->errfunc != 0) { /* is there an error handling function? */ |
| 562 | | StkId errfunc = restorestack(L, L->errfunc); |
| 563 | | if (!ttisfunction(errfunc)) luaD_throw(L, LUA_ERRERR); |
| 564 | | setobjs2s(L, L->top, L->top - 1); /* move argument */ |
| 565 | | setobjs2s(L, L->top - 1, errfunc); /* push function */ |
| 566 | | L->top++; |
| 567 | | luaD_call(L, L->top - 2, 1, 0); /* call it */ |
| 568 | | } |
| 569 | | luaD_throw(L, LUA_ERRRUN); |
| 574 | if (L->errfunc != 0) { /* is there an error handling function? */ |
| 575 | StkId errfunc = restorestack(L, L->errfunc); |
| 576 | if (!ttisfunction(errfunc)) luaD_throw(L, LUA_ERRERR); |
| 577 | setobjs2s(L, L->top, L->top - 1); /* move argument */ |
| 578 | setobjs2s(L, L->top - 1, errfunc); /* push function */ |
| 579 | L->top++; |
| 580 | luaD_call(L, L->top - 2, 1, 0); /* call it */ |
| 581 | } |
| 582 | luaD_throw(L, LUA_ERRRUN); |
| 570 | 583 | } |
| 571 | 584 | |
| 572 | 585 | |
| 573 | 586 | l_noret luaG_runerror (lua_State *L, const char *fmt, ...) { |
| 574 | | va_list argp; |
| 575 | | va_start(argp, fmt); |
| 576 | | addinfo(L, luaO_pushvfstring(L, fmt, argp)); |
| 577 | | va_end(argp); |
| 578 | | luaG_errormsg(L); |
| 587 | va_list argp; |
| 588 | va_start(argp, fmt); |
| 589 | addinfo(L, luaO_pushvfstring(L, fmt, argp)); |
| 590 | va_end(argp); |
| 591 | luaG_errormsg(L); |
| 579 | 592 | } |
| 593 | |
trunk/src/lib/lua/liolib.c
| r30857 | r30858 | |
| 1 | 1 | /* |
| 2 | | ** $Id: liolib.c,v 2.111 2013/03/21 13:57:27 roberto Exp $ |
| 2 | ** $Id: liolib.c,v 2.112.1.1 2013/04/12 18:48:47 roberto Exp $ |
| 3 | 3 | ** Standard I/O (and system) library |
| 4 | 4 | ** See Copyright Notice in lua.h |
| 5 | 5 | */ |
| 6 | 6 | |
| 7 | 7 | |
| 8 | 8 | /* |
| 9 | | ** POSIX idiosyncrasy! |
| 10 | 9 | ** This definition must come before the inclusion of 'stdio.h'; it |
| 11 | 10 | ** should not affect non-POSIX systems |
| 12 | 11 | */ |
| 13 | 12 | #if !defined(_FILE_OFFSET_BITS) |
| 14 | | #define _FILE_OFFSET_BITS 64 |
| 13 | #define _LARGEFILE_SOURCE 1 |
| 14 | #define _FILE_OFFSET_BITS 64 |
| 15 | 15 | #endif |
| 16 | 16 | |
| 17 | 17 | |
| r30857 | r30858 | |
| 37 | 37 | ** the standard ones. |
| 38 | 38 | */ |
| 39 | 39 | #define lua_checkmode(mode) \ |
| 40 | | (*mode != '\0' && strchr("rwa", *(mode++)) != NULL && \ |
| 41 | | (*mode != '+' || ++mode) && /* skip if char is '+' */ \ |
| 42 | | (*mode != 'b' || ++mode) && /* skip if char is 'b' */ \ |
| 40 | (*mode != '\0' && strchr("rwa", *(mode++)) != NULL && \ |
| 41 | (*mode != '+' || ++mode) && /* skip if char is '+' */ \ |
| 42 | (*mode != 'b' || ++mode) && /* skip if char is 'b' */ \ |
| 43 | 43 | (*mode == '\0')) |
| 44 | 44 | |
| 45 | 45 | #endif |
| r30857 | r30858 | |
| 51 | 51 | ** ======================================================= |
| 52 | 52 | */ |
| 53 | 53 | |
| 54 | | #if !defined(lua_popen) /* { */ |
| 54 | #if !defined(lua_popen) /* { */ |
| 55 | 55 | |
| 56 | | #if defined(LUA_USE_POPEN) /* { */ |
| 56 | #if defined(LUA_USE_POPEN) /* { */ |
| 57 | 57 | |
| 58 | | #define lua_popen(L,c,m) ((void)L, fflush(NULL), popen(c,m)) |
| 59 | | #define lua_pclose(L,file) ((void)L, pclose(file)) |
| 58 | #define lua_popen(L,c,m) ((void)L, fflush(NULL), popen(c,m)) |
| 59 | #define lua_pclose(L,file) ((void)L, pclose(file)) |
| 60 | 60 | |
| 61 | | #elif defined(LUA_WIN) /* }{ */ |
| 61 | #elif defined(LUA_WIN) /* }{ */ |
| 62 | 62 | |
| 63 | | #define lua_popen(L,c,m) ((void)L, _popen(c,m)) |
| 64 | | #define lua_pclose(L,file) ((void)L, _pclose(file)) |
| 63 | #define lua_popen(L,c,m) ((void)L, _popen(c,m)) |
| 64 | #define lua_pclose(L,file) ((void)L, _pclose(file)) |
| 65 | 65 | |
| 66 | 66 | |
| 67 | | #else /* }{ */ |
| 67 | #else /* }{ */ |
| 68 | 68 | |
| 69 | | #define lua_popen(L,c,m) ((void)((void)c, m), \ |
| 69 | #define lua_popen(L,c,m) ((void)((void)c, m), \ |
| 70 | 70 | luaL_error(L, LUA_QL("popen") " not supported"), (FILE*)0) |
| 71 | | #define lua_pclose(L,file) ((void)((void)L, file), -1) |
| 71 | #define lua_pclose(L,file) ((void)((void)L, file), -1) |
| 72 | 72 | |
| 73 | 73 | |
| 74 | | #endif /* } */ |
| 74 | #endif /* } */ |
| 75 | 75 | |
| 76 | | #endif /* } */ |
| 76 | #endif /* } */ |
| 77 | 77 | |
| 78 | 78 | /* }====================================================== */ |
| 79 | 79 | |
| 80 | 80 | |
| 81 | 81 | /* |
| 82 | 82 | ** {====================================================== |
| 83 | | ** lua_fseek/lua_ftell: configuration for longer offsets |
| 83 | ** lua_fseek: configuration for longer offsets |
| 84 | 84 | ** ======================================================= |
| 85 | 85 | */ |
| 86 | 86 | |
| 87 | | #if !defined(lua_fseek) /* { */ |
| 87 | #if !defined(lua_fseek) && !defined(LUA_ANSI) /* { */ |
| 88 | 88 | |
| 89 | | #if defined(LUA_USE_POSIX) |
| 89 | #if defined(LUA_USE_POSIX) /* { */ |
| 90 | 90 | |
| 91 | | #define l_fseek(f,o,w) fseeko(f,o,w) |
| 92 | | #define l_ftell(f) ftello(f) |
| 93 | | #define l_seeknum off_t |
| 91 | #define l_fseek(f,o,w) fseeko(f,o,w) |
| 92 | #define l_ftell(f) ftello(f) |
| 93 | #define l_seeknum off_t |
| 94 | 94 | |
| 95 | 95 | #elif defined(LUA_WIN) && !defined(_CRTIMP_TYPEINFO) \ |
| 96 | | && defined(_MSC_VER) && (_MSC_VER >= 1400) |
| 96 | && defined(_MSC_VER) && (_MSC_VER >= 1400) /* }{ */ |
| 97 | 97 | /* Windows (but not DDK) and Visual C++ 2005 or higher */ |
| 98 | 98 | |
| 99 | | #define l_fseek(f,o,w) _fseeki64(f,o,w) |
| 100 | | #define l_ftell(f) _ftelli64(f) |
| 101 | | #define l_seeknum __int64 |
| 99 | #define l_fseek(f,o,w) _fseeki64(f,o,w) |
| 100 | #define l_ftell(f) _ftelli64(f) |
| 101 | #define l_seeknum __int64 |
| 102 | 102 | |
| 103 | | #else |
| 103 | #endif /* } */ |
| 104 | 104 | |
| 105 | | #define l_fseek(f,o,w) fseek(f,o,w) |
| 106 | | #define l_ftell(f) ftell(f) |
| 107 | | #define l_seeknum long |
| 105 | #endif /* } */ |
| 108 | 106 | |
| 107 | |
| 108 | #if !defined(l_fseek) /* default definitions */ |
| 109 | #define l_fseek(f,o,w) fseek(f,o,w) |
| 110 | #define l_ftell(f) ftell(f) |
| 111 | #define l_seeknum long |
| 109 | 112 | #endif |
| 110 | 113 | |
| 111 | | #endif /* } */ |
| 112 | | |
| 113 | 114 | /* }====================================================== */ |
| 114 | 115 | |
| 115 | 116 | |
| 116 | | #define IO_PREFIX "_IO_" |
| 117 | | #define IO_INPUT (IO_PREFIX "input") |
| 118 | | #define IO_OUTPUT (IO_PREFIX "output") |
| 117 | #define IO_PREFIX "_IO_" |
| 118 | #define IO_INPUT (IO_PREFIX "input") |
| 119 | #define IO_OUTPUT (IO_PREFIX "output") |
| 119 | 120 | |
| 120 | 121 | |
| 121 | 122 | typedef luaL_Stream LStream; |
| 122 | 123 | |
| 123 | 124 | |
| 124 | | #define tolstream(L) ((LStream *)luaL_checkudata(L, 1, LUA_FILEHANDLE)) |
| 125 | #define tolstream(L) ((LStream *)luaL_checkudata(L, 1, LUA_FILEHANDLE)) |
| 125 | 126 | |
| 126 | | #define isclosed(p) ((p)->closef == NULL) |
| 127 | #define isclosed(p) ((p)->closef == NULL) |
| 127 | 128 | |
| 128 | 129 | |
| 129 | 130 | static int io_type (lua_State *L) { |
| 130 | | LStream *p; |
| 131 | | luaL_checkany(L, 1); |
| 132 | | p = (LStream *)luaL_testudata(L, 1, LUA_FILEHANDLE); |
| 133 | | if (p == NULL) |
| 134 | | lua_pushnil(L); /* not a file */ |
| 135 | | else if (isclosed(p)) |
| 136 | | lua_pushliteral(L, "closed file"); |
| 137 | | else |
| 138 | | lua_pushliteral(L, "file"); |
| 139 | | return 1; |
| 131 | LStream *p; |
| 132 | luaL_checkany(L, 1); |
| 133 | p = (LStream *)luaL_testudata(L, 1, LUA_FILEHANDLE); |
| 134 | if (p == NULL) |
| 135 | lua_pushnil(L); /* not a file */ |
| 136 | else if (isclosed(p)) |
| 137 | lua_pushliteral(L, "closed file"); |
| 138 | else |
| 139 | lua_pushliteral(L, "file"); |
| 140 | return 1; |
| 140 | 141 | } |
| 141 | 142 | |
| 142 | 143 | |
| 143 | 144 | static int f_tostring (lua_State *L) { |
| 144 | | LStream *p = tolstream(L); |
| 145 | | if (isclosed(p)) |
| 146 | | lua_pushliteral(L, "file (closed)"); |
| 147 | | else |
| 148 | | lua_pushfstring(L, "file (%p)", p->f); |
| 149 | | return 1; |
| 145 | LStream *p = tolstream(L); |
| 146 | if (isclosed(p)) |
| 147 | lua_pushliteral(L, "file (closed)"); |
| 148 | else |
| 149 | lua_pushfstring(L, "file (%p)", p->f); |
| 150 | return 1; |
| 150 | 151 | } |
| 151 | 152 | |
| 152 | 153 | |
| 153 | 154 | static FILE *tofile (lua_State *L) { |
| 154 | | LStream *p = tolstream(L); |
| 155 | | if (isclosed(p)) |
| 156 | | luaL_error(L, "attempt to use a closed file"); |
| 157 | | lua_assert(p->f); |
| 158 | | return p->f; |
| 155 | LStream *p = tolstream(L); |
| 156 | if (isclosed(p)) |
| 157 | luaL_error(L, "attempt to use a closed file"); |
| 158 | lua_assert(p->f); |
| 159 | return p->f; |
| 159 | 160 | } |
| 160 | 161 | |
| 161 | 162 | |
| r30857 | r30858 | |
| 165 | 166 | ** file is not left opened. |
| 166 | 167 | */ |
| 167 | 168 | static LStream *newprefile (lua_State *L) { |
| 168 | | LStream *p = (LStream *)lua_newuserdata(L, sizeof(LStream)); |
| 169 | | p->closef = NULL; /* mark file handle as 'closed' */ |
| 170 | | luaL_setmetatable(L, LUA_FILEHANDLE); |
| 171 | | return p; |
| 169 | LStream *p = (LStream *)lua_newuserdata(L, sizeof(LStream)); |
| 170 | p->closef = NULL; /* mark file handle as 'closed' */ |
| 171 | luaL_setmetatable(L, LUA_FILEHANDLE); |
| 172 | return p; |
| 172 | 173 | } |
| 173 | 174 | |
| 174 | 175 | |
| 175 | 176 | static int aux_close (lua_State *L) { |
| 176 | | LStream *p = tolstream(L); |
| 177 | | lua_CFunction cf = p->closef; |
| 178 | | p->closef = NULL; /* mark stream as closed */ |
| 179 | | return (*cf)(L); /* close it */ |
| 177 | LStream *p = tolstream(L); |
| 178 | lua_CFunction cf = p->closef; |
| 179 | p->closef = NULL; /* mark stream as closed */ |
| 180 | return (*cf)(L); /* close it */ |
| 180 | 181 | } |
| 181 | 182 | |
| 182 | 183 | |
| 183 | 184 | static int io_close (lua_State *L) { |
| 184 | | if (lua_isnone(L, 1)) /* no argument? */ |
| 185 | | lua_getfield(L, LUA_REGISTRYINDEX, IO_OUTPUT); /* use standard output */ |
| 186 | | tofile(L); /* make sure argument is an open stream */ |
| 187 | | return aux_close(L); |
| 185 | if (lua_isnone(L, 1)) /* no argument? */ |
| 186 | lua_getfield(L, LUA_REGISTRYINDEX, IO_OUTPUT); /* use standard output */ |
| 187 | tofile(L); /* make sure argument is an open stream */ |
| 188 | return aux_close(L); |
| 188 | 189 | } |
| 189 | 190 | |
| 190 | 191 | |
| 191 | 192 | static int f_gc (lua_State *L) { |
| 192 | | LStream *p = tolstream(L); |
| 193 | | if (!isclosed(p) && p->f != NULL) |
| 194 | | aux_close(L); /* ignore closed and incompletely open files */ |
| 195 | | return 0; |
| 193 | LStream *p = tolstream(L); |
| 194 | if (!isclosed(p) && p->f != NULL) |
| 195 | aux_close(L); /* ignore closed and incompletely open files */ |
| 196 | return 0; |
| 196 | 197 | } |
| 197 | 198 | |
| 198 | 199 | |
| r30857 | r30858 | |
| 200 | 201 | ** function to close regular files |
| 201 | 202 | */ |
| 202 | 203 | static int io_fclose (lua_State *L) { |
| 203 | | LStream *p = tolstream(L); |
| 204 | | int res = fclose(p->f); |
| 205 | | return luaL_fileresult(L, (res == 0), NULL); |
| 204 | LStream *p = tolstream(L); |
| 205 | int res = fclose(p->f); |
| 206 | return luaL_fileresult(L, (res == 0), NULL); |
| 206 | 207 | } |
| 207 | 208 | |
| 208 | 209 | |
| 209 | 210 | static LStream *newfile (lua_State *L) { |
| 210 | | LStream *p = newprefile(L); |
| 211 | | p->f = NULL; |
| 212 | | p->closef = &io_fclose; |
| 213 | | return p; |
| 211 | LStream *p = newprefile(L); |
| 212 | p->f = NULL; |
| 213 | p->closef = &io_fclose; |
| 214 | return p; |
| 214 | 215 | } |
| 215 | 216 | |
| 216 | 217 | |
| 217 | 218 | static void opencheck (lua_State *L, const char *fname, const char *mode) { |
| 218 | | LStream *p = newfile(L); |
| 219 | | p->f = fopen(fname, mode); |
| 220 | | if (p->f == NULL) |
| 221 | | luaL_error(L, "cannot open file " LUA_QS " (%s)", fname, strerror(errno)); |
| 219 | LStream *p = newfile(L); |
| 220 | p->f = fopen(fname, mode); |
| 221 | if (p->f == NULL) |
| 222 | luaL_error(L, "cannot open file " LUA_QS " (%s)", fname, strerror(errno)); |
| 222 | 223 | } |
| 223 | 224 | |
| 224 | 225 | |
| 225 | 226 | static int io_open (lua_State *L) { |
| 226 | | const char *filename = luaL_checkstring(L, 1); |
| 227 | | const char *mode = luaL_optstring(L, 2, "r"); |
| 228 | | LStream *p = newfile(L); |
| 229 | | const char *md = mode; /* to traverse/check mode */ |
| 230 | | luaL_argcheck(L, lua_checkmode(md), 2, "invalid mode"); |
| 231 | | p->f = fopen(filename, mode); |
| 232 | | return (p->f == NULL) ? luaL_fileresult(L, 0, filename) : 1; |
| 227 | const char *filename = luaL_checkstring(L, 1); |
| 228 | const char *mode = luaL_optstring(L, 2, "r"); |
| 229 | LStream *p = newfile(L); |
| 230 | const char *md = mode; /* to traverse/check mode */ |
| 231 | luaL_argcheck(L, lua_checkmode(md), 2, "invalid mode"); |
| 232 | p->f = fopen(filename, mode); |
| 233 | return (p->f == NULL) ? luaL_fileresult(L, 0, filename) : 1; |
| 233 | 234 | } |
| 234 | 235 | |
| 235 | 236 | |
| r30857 | r30858 | |
| 237 | 238 | ** function to close 'popen' files |
| 238 | 239 | */ |
| 239 | 240 | static int io_pclose (lua_State *L) { |
| 240 | | LStream *p = tolstream(L); |
| 241 | | return luaL_execresult(L, lua_pclose(L, p->f)); |
| 241 | LStream *p = tolstream(L); |
| 242 | return luaL_execresult(L, lua_pclose(L, p->f)); |
| 242 | 243 | } |
| 243 | 244 | |
| 244 | 245 | |
| 245 | 246 | static int io_popen (lua_State *L) { |
| 246 | | const char *filename = luaL_checkstring(L, 1); |
| 247 | | const char *mode = luaL_optstring(L, 2, "r"); |
| 248 | | LStream *p = newprefile(L); |
| 249 | | p->f = lua_popen(L, filename, mode); |
| 250 | | p->closef = &io_pclose; |
| 251 | | return (p->f == NULL) ? luaL_fileresult(L, 0, filename) : 1; |
| 247 | const char *filename = luaL_checkstring(L, 1); |
| 248 | const char *mode = luaL_optstring(L, 2, "r"); |
| 249 | LStream *p = newprefile(L); |
| 250 | p->f = lua_popen(L, filename, mode); |
| 251 | p->closef = &io_pclose; |
| 252 | return (p->f == NULL) ? luaL_fileresult(L, 0, filename) : 1; |
| 252 | 253 | } |
| 253 | 254 | |
| 254 | 255 | |
| 255 | 256 | static int io_tmpfile (lua_State *L) { |
| 256 | | LStream *p = newfile(L); |
| 257 | | p->f = tmpfile(); |
| 258 | | return (p->f == NULL) ? luaL_fileresult(L, 0, NULL) : 1; |
| 257 | LStream *p = newfile(L); |
| 258 | p->f = tmpfile(); |
| 259 | return (p->f == NULL) ? luaL_fileresult(L, 0, NULL) : 1; |
| 259 | 260 | } |
| 260 | 261 | |
| 261 | 262 | |
| 262 | 263 | static FILE *getiofile (lua_State *L, const char *findex) { |
| 263 | | LStream *p; |
| 264 | | lua_getfield(L, LUA_REGISTRYINDEX, findex); |
| 265 | | p = (LStream *)lua_touserdata(L, -1); |
| 266 | | if (isclosed(p)) |
| 267 | | luaL_error(L, "standard %s file is closed", findex + strlen(IO_PREFIX)); |
| 268 | | return p->f; |
| 264 | LStream *p; |
| 265 | lua_getfield(L, LUA_REGISTRYINDEX, findex); |
| 266 | p = (LStream *)lua_touserdata(L, -1); |
| 267 | if (isclosed(p)) |
| 268 | luaL_error(L, "standard %s file is closed", findex + strlen(IO_PREFIX)); |
| 269 | return p->f; |
| 269 | 270 | } |
| 270 | 271 | |
| 271 | 272 | |
| 272 | 273 | static int g_iofile (lua_State *L, const char *f, const char *mode) { |
| 273 | | if (!lua_isnoneornil(L, 1)) { |
| 274 | | const char *filename = lua_tostring(L, 1); |
| 275 | | if (filename) |
| 276 | | opencheck(L, filename, mode); |
| 277 | | else { |
| 278 | | tofile(L); /* check that it's a valid file handle */ |
| 279 | | lua_pushvalue(L, 1); |
| 280 | | } |
| 281 | | lua_setfield(L, LUA_REGISTRYINDEX, f); |
| 282 | | } |
| 283 | | /* return current value */ |
| 284 | | lua_getfield(L, LUA_REGISTRYINDEX, f); |
| 285 | | return 1; |
| 274 | if (!lua_isnoneornil(L, 1)) { |
| 275 | const char *filename = lua_tostring(L, 1); |
| 276 | if (filename) |
| 277 | opencheck(L, filename, mode); |
| 278 | else { |
| 279 | tofile(L); /* check that it's a valid file handle */ |
| 280 | lua_pushvalue(L, 1); |
| 281 | } |
| 282 | lua_setfield(L, LUA_REGISTRYINDEX, f); |
| 283 | } |
| 284 | /* return current value */ |
| 285 | lua_getfield(L, LUA_REGISTRYINDEX, f); |
| 286 | return 1; |
| 286 | 287 | } |
| 287 | 288 | |
| 288 | 289 | |
| 289 | 290 | static int io_input (lua_State *L) { |
| 290 | | return g_iofile(L, IO_INPUT, "r"); |
| 291 | return g_iofile(L, IO_INPUT, "r"); |
| 291 | 292 | } |
| 292 | 293 | |
| 293 | 294 | |
| 294 | 295 | static int io_output (lua_State *L) { |
| 295 | | return g_iofile(L, IO_OUTPUT, "w"); |
| 296 | return g_iofile(L, IO_OUTPUT, "w"); |
| 296 | 297 | } |
| 297 | 298 | |
| 298 | 299 | |
| r30857 | r30858 | |
| 300 | 301 | |
| 301 | 302 | |
| 302 | 303 | static void aux_lines (lua_State *L, int toclose) { |
| 303 | | int i; |
| 304 | | int n = lua_gettop(L) - 1; /* number of arguments to read */ |
| 305 | | /* ensure that arguments will fit here and into 'io_readline' stack */ |
| 306 | | luaL_argcheck(L, n <= LUA_MINSTACK - 3, LUA_MINSTACK - 3, "too many options"); |
| 307 | | lua_pushvalue(L, 1); /* file handle */ |
| 308 | | lua_pushinteger(L, n); /* number of arguments to read */ |
| 309 | | lua_pushboolean(L, toclose); /* close/not close file when finished */ |
| 310 | | for (i = 1; i <= n; i++) lua_pushvalue(L, i + 1); /* copy arguments */ |
| 311 | | lua_pushcclosure(L, io_readline, 3 + n); |
| 304 | int i; |
| 305 | int n = lua_gettop(L) - 1; /* number of arguments to read */ |
| 306 | /* ensure that arguments will fit here and into 'io_readline' stack */ |
| 307 | luaL_argcheck(L, n <= LUA_MINSTACK - 3, LUA_MINSTACK - 3, "too many options"); |
| 308 | lua_pushvalue(L, 1); /* file handle */ |
| 309 | lua_pushinteger(L, n); /* number of arguments to read */ |
| 310 | lua_pushboolean(L, toclose); /* close/not close file when finished */ |
| 311 | for (i = 1; i <= n; i++) lua_pushvalue(L, i + 1); /* copy arguments */ |
| 312 | lua_pushcclosure(L, io_readline, 3 + n); |
| 312 | 313 | } |
| 313 | 314 | |
| 314 | 315 | |
| 315 | 316 | static int f_lines (lua_State *L) { |
| 316 | | tofile(L); /* check that it's a valid file handle */ |
| 317 | | aux_lines(L, 0); |
| 318 | | return 1; |
| 317 | tofile(L); /* check that it's a valid file handle */ |
| 318 | aux_lines(L, 0); |
| 319 | return 1; |
| 319 | 320 | } |
| 320 | 321 | |
| 321 | 322 | |
| 322 | 323 | static int io_lines (lua_State *L) { |
| 323 | | int toclose; |
| 324 | | if (lua_isnone(L, 1)) lua_pushnil(L); /* at least one argument */ |
| 325 | | if (lua_isnil(L, 1)) { /* no file name? */ |
| 326 | | lua_getfield(L, LUA_REGISTRYINDEX, IO_INPUT); /* get default input */ |
| 327 | | lua_replace(L, 1); /* put it at index 1 */ |
| 328 | | tofile(L); /* check that it's a valid file handle */ |
| 329 | | toclose = 0; /* do not close it after iteration */ |
| 330 | | } |
| 331 | | else { /* open a new file */ |
| 332 | | const char *filename = luaL_checkstring(L, 1); |
| 333 | | opencheck(L, filename, "r"); |
| 334 | | lua_replace(L, 1); /* put file at index 1 */ |
| 335 | | toclose = 1; /* close it after iteration */ |
| 336 | | } |
| 337 | | aux_lines(L, toclose); |
| 338 | | return 1; |
| 324 | int toclose; |
| 325 | if (lua_isnone(L, 1)) lua_pushnil(L); /* at least one argument */ |
| 326 | if (lua_isnil(L, 1)) { /* no file name? */ |
| 327 | lua_getfield(L, LUA_REGISTRYINDEX, IO_INPUT); /* get default input */ |
| 328 | lua_replace(L, 1); /* put it at index 1 */ |
| 329 | tofile(L); /* check that it's a valid file handle */ |
| 330 | toclose = 0; /* do not close it after iteration */ |
| 331 | } |
| 332 | else { /* open a new file */ |
| 333 | const char *filename = luaL_checkstring(L, 1); |
| 334 | opencheck(L, filename, "r"); |
| 335 | lua_replace(L, 1); /* put file at index 1 */ |
| 336 | toclose = 1; /* close it after iteration */ |
| 337 | } |
| 338 | aux_lines(L, toclose); |
| 339 | return 1; |
| 339 | 340 | } |
| 340 | 341 | |
| 341 | 342 | |
| r30857 | r30858 | |
| 347 | 348 | |
| 348 | 349 | |
| 349 | 350 | static int read_number (lua_State *L, FILE *f) { |
| 350 | | lua_Number d; |
| 351 | | if (fscanf(f, LUA_NUMBER_SCAN, &d) == 1) { |
| 352 | | lua_pushnumber(L, d); |
| 353 | | return 1; |
| 354 | | } |
| 355 | | else { |
| 356 | | lua_pushnil(L); /* "result" to be removed */ |
| 357 | | return 0; /* read fails */ |
| 358 | | } |
| 351 | lua_Number d; |
| 352 | if (fscanf(f, LUA_NUMBER_SCAN, &d) == 1) { |
| 353 | lua_pushnumber(L, d); |
| 354 | return 1; |
| 355 | } |
| 356 | else { |
| 357 | lua_pushnil(L); /* "result" to be removed */ |
| 358 | return 0; /* read fails */ |
| 359 | } |
| 359 | 360 | } |
| 360 | 361 | |
| 361 | 362 | |
| 362 | 363 | static int test_eof (lua_State *L, FILE *f) { |
| 363 | | int c = getc(f); |
| 364 | | ungetc(c, f); |
| 365 | | lua_pushlstring(L, NULL, 0); |
| 366 | | return (c != EOF); |
| 364 | int c = getc(f); |
| 365 | ungetc(c, f); |
| 366 | lua_pushlstring(L, NULL, 0); |
| 367 | return (c != EOF); |
| 367 | 368 | } |
| 368 | 369 | |
| 369 | 370 | |
| 370 | 371 | static int read_line (lua_State *L, FILE *f, int chop) { |
| 371 | | luaL_Buffer b; |
| 372 | | luaL_buffinit(L, &b); |
| 373 | | for (;;) { |
| 374 | | size_t l; |
| 375 | | char *p = luaL_prepbuffer(&b); |
| 376 | | if (fgets(p, LUAL_BUFFERSIZE, f) == NULL) { /* eof? */ |
| 377 | | luaL_pushresult(&b); /* close buffer */ |
| 378 | | return (lua_rawlen(L, -1) > 0); /* check whether read something */ |
| 379 | | } |
| 380 | | l = strlen(p); |
| 381 | | if (l == 0 || p[l-1] != '\n') |
| 382 | | luaL_addsize(&b, l); |
| 383 | | else { |
| 384 | | luaL_addsize(&b, l - chop); /* chop 'eol' if needed */ |
| 385 | | luaL_pushresult(&b); /* close buffer */ |
| 386 | | return 1; /* read at least an `eol' */ |
| 387 | | } |
| 388 | | } |
| 372 | luaL_Buffer b; |
| 373 | luaL_buffinit(L, &b); |
| 374 | for (;;) { |
| 375 | size_t l; |
| 376 | char *p = luaL_prepbuffer(&b); |
| 377 | if (fgets(p, LUAL_BUFFERSIZE, f) == NULL) { /* eof? */ |
| 378 | luaL_pushresult(&b); /* close buffer */ |
| 379 | return (lua_rawlen(L, -1) > 0); /* check whether read something */ |
| 380 | } |
| 381 | l = strlen(p); |
| 382 | if (l == 0 || p[l-1] != '\n') |
| 383 | luaL_addsize(&b, l); |
| 384 | else { |
| 385 | luaL_addsize(&b, l - chop); /* chop 'eol' if needed */ |
| 386 | luaL_pushresult(&b); /* close buffer */ |
| 387 | return 1; /* read at least an `eol' */ |
| 388 | } |
| 389 | } |
| 389 | 390 | } |
| 390 | 391 | |
| 391 | 392 | |
| 392 | | #define MAX_SIZE_T (~(size_t)0) |
| 393 | #define MAX_SIZE_T (~(size_t)0) |
| 393 | 394 | |
| 394 | 395 | static void read_all (lua_State *L, FILE *f) { |
| 395 | | size_t rlen = LUAL_BUFFERSIZE; /* how much to read in each cycle */ |
| 396 | | luaL_Buffer b; |
| 397 | | luaL_buffinit(L, &b); |
| 398 | | for (;;) { |
| 399 | | char *p = luaL_prepbuffsize(&b, rlen); |
| 400 | | size_t nr = fread(p, sizeof(char), rlen, f); |
| 401 | | luaL_addsize(&b, nr); |
| 402 | | if (nr < rlen) break; /* eof? */ |
| 403 | | else if (rlen <= (MAX_SIZE_T / 4)) /* avoid buffers too large */ |
| 404 | | rlen *= 2; /* double buffer size at each iteration */ |
| 405 | | } |
| 406 | | luaL_pushresult(&b); /* close buffer */ |
| 396 | size_t rlen = LUAL_BUFFERSIZE; /* how much to read in each cycle */ |
| 397 | luaL_Buffer b; |
| 398 | luaL_buffinit(L, &b); |
| 399 | for (;;) { |
| 400 | char *p = luaL_prepbuffsize(&b, rlen); |
| 401 | size_t nr = fread(p, sizeof(char), rlen, f); |
| 402 | luaL_addsize(&b, nr); |
| 403 | if (nr < rlen) break; /* eof? */ |
| 404 | else if (rlen <= (MAX_SIZE_T / 4)) /* avoid buffers too large */ |
| 405 | rlen *= 2; /* double buffer size at each iteration */ |
| 406 | } |
| 407 | luaL_pushresult(&b); /* close buffer */ |
| 407 | 408 | } |
| 408 | 409 | |
| 409 | 410 | |
| 410 | 411 | static int read_chars (lua_State *L, FILE *f, size_t n) { |
| 411 | | size_t nr; /* number of chars actually read */ |
| 412 | | char *p; |
| 413 | | luaL_Buffer b; |
| 414 | | luaL_buffinit(L, &b); |
| 415 | | p = luaL_prepbuffsize(&b, n); /* prepare buffer to read whole block */ |
| 416 | | nr = fread(p, sizeof(char), n, f); /* try to read 'n' chars */ |
| 417 | | luaL_addsize(&b, nr); |
| 418 | | luaL_pushresult(&b); /* close buffer */ |
| 419 | | return (nr > 0); /* true iff read something */ |
| 412 | size_t nr; /* number of chars actually read */ |
| 413 | char *p; |
| 414 | luaL_Buffer b; |
| 415 | luaL_buffinit(L, &b); |
| 416 | p = luaL_prepbuffsize(&b, n); /* prepare buffer to read whole block */ |
| 417 | nr = fread(p, sizeof(char), n, f); /* try to read 'n' chars */ |
| 418 | luaL_addsize(&b, nr); |
| 419 | luaL_pushresult(&b); /* close buffer */ |
| 420 | return (nr > 0); /* true iff read something */ |
| 420 | 421 | } |
| 421 | 422 | |
| 422 | 423 | |
| 423 | 424 | static int g_read (lua_State *L, FILE *f, int first) { |
| 424 | | int nargs = lua_gettop(L) - 1; |
| 425 | | int success; |
| 426 | | int n; |
| 427 | | clearerr(f); |
| 428 | | if (nargs == 0) { /* no arguments? */ |
| 429 | | success = read_line(L, f, 1); |
| 430 | | n = first+1; /* to return 1 result */ |
| 431 | | } |
| 432 | | else { /* ensure stack space for all results and for auxlib's buffer */ |
| 433 | | luaL_checkstack(L, nargs+LUA_MINSTACK, "too many arguments"); |
| 434 | | success = 1; |
| 435 | | for (n = first; nargs-- && success; n++) { |
| 436 | | if (lua_type(L, n) == LUA_TNUMBER) { |
| 437 | | size_t l = (size_t)lua_tointeger(L, n); |
| 438 | | success = (l == 0) ? test_eof(L, f) : read_chars(L, f, l); |
| 439 | | } |
| 440 | | else { |
| 441 | | const char *p = lua_tostring(L, n); |
| 442 | | luaL_argcheck(L, p && p[0] == '*', n, "invalid option"); |
| 443 | | switch (p[1]) { |
| 444 | | case 'n': /* number */ |
| 445 | | success = read_number(L, f); |
| 446 | | break; |
| 447 | | case 'l': /* line */ |
| 448 | | success = read_line(L, f, 1); |
| 449 | | break; |
| 450 | | case 'L': /* line with end-of-line */ |
| 451 | | success = read_line(L, f, 0); |
| 452 | | break; |
| 453 | | case 'a': /* file */ |
| 454 | | read_all(L, f); /* read entire file */ |
| 455 | | success = 1; /* always success */ |
| 456 | | break; |
| 457 | | default: |
| 458 | | return luaL_argerror(L, n, "invalid format"); |
| 459 | | } |
| 460 | | } |
| 461 | | } |
| 462 | | } |
| 463 | | if (ferror(f)) |
| 464 | | return luaL_fileresult(L, 0, NULL); |
| 465 | | if (!success) { |
| 466 | | lua_pop(L, 1); /* remove last result */ |
| 467 | | lua_pushnil(L); /* push nil instead */ |
| 468 | | } |
| 469 | | return n - first; |
| 425 | int nargs = lua_gettop(L) - 1; |
| 426 | int success; |
| 427 | int n; |
| 428 | clearerr(f); |
| 429 | if (nargs == 0) { /* no arguments? */ |
| 430 | success = read_line(L, f, 1); |
| 431 | n = first+1; /* to return 1 result */ |
| 432 | } |
| 433 | else { /* ensure stack space for all results and for auxlib's buffer */ |
| 434 | luaL_checkstack(L, nargs+LUA_MINSTACK, "too many arguments"); |
| 435 | success = 1; |
| 436 | for (n = first; nargs-- && success; n++) { |
| 437 | if (lua_type(L, n) == LUA_TNUMBER) { |
| 438 | size_t l = (size_t)lua_tointeger(L, n); |
| 439 | success = (l == 0) ? test_eof(L, f) : read_chars(L, f, l); |
| 440 | } |
| 441 | else { |
| 442 | const char *p = lua_tostring(L, n); |
| 443 | luaL_argcheck(L, p && p[0] == '*', n, "invalid option"); |
| 444 | switch (p[1]) { |
| 445 | case 'n': /* number */ |
| 446 | success = read_number(L, f); |
| 447 | break; |
| 448 | case 'l': /* line */ |
| 449 | success = read_line(L, f, 1); |
| 450 | break; |
| 451 | case 'L': /* line with end-of-line */ |
| 452 | success = read_line(L, f, 0); |
| 453 | break; |
| 454 | case 'a': /* file */ |
| 455 | read_all(L, f); /* read entire file */ |
| 456 | success = 1; /* always success */ |
| 457 | break; |
| 458 | default: |
| 459 | return luaL_argerror(L, n, "invalid format"); |
| 460 | } |
| 461 | } |
| 462 | } |
| 463 | } |
| 464 | if (ferror(f)) |
| 465 | return luaL_fileresult(L, 0, NULL); |
| 466 | if (!success) { |
| 467 | lua_pop(L, 1); /* remove last result */ |
| 468 | lua_pushnil(L); /* push nil instead */ |
| 469 | } |
| 470 | return n - first; |
| 470 | 471 | } |
| 471 | 472 | |
| 472 | 473 | |
| 473 | 474 | static int io_read (lua_State *L) { |
| 474 | | return g_read(L, getiofile(L, IO_INPUT), 1); |
| 475 | return g_read(L, getiofile(L, IO_INPUT), 1); |
| 475 | 476 | } |
| 476 | 477 | |
| 477 | 478 | |
| 478 | 479 | static int f_read (lua_State *L) { |
| 479 | | return g_read(L, tofile(L), 2); |
| 480 | return g_read(L, tofile(L), 2); |
| 480 | 481 | } |
| 481 | 482 | |
| 482 | 483 | |
| 483 | 484 | static int io_readline (lua_State *L) { |
| 484 | | LStream *p = (LStream *)lua_touserdata(L, lua_upvalueindex(1)); |
| 485 | | int i; |
| 486 | | int n = (int)lua_tointeger(L, lua_upvalueindex(2)); |
| 487 | | if (isclosed(p)) /* file is already closed? */ |
| 488 | | return luaL_error(L, "file is already closed"); |
| 489 | | lua_settop(L , 1); |
| 490 | | for (i = 1; i <= n; i++) /* push arguments to 'g_read' */ |
| 491 | | lua_pushvalue(L, lua_upvalueindex(3 + i)); |
| 492 | | n = g_read(L, p->f, 2); /* 'n' is number of results */ |
| 493 | | lua_assert(n > 0); /* should return at least a nil */ |
| 494 | | if (!lua_isnil(L, -n)) /* read at least one value? */ |
| 495 | | return n; /* return them */ |
| 496 | | else { /* first result is nil: EOF or error */ |
| 497 | | if (n > 1) { /* is there error information? */ |
| 498 | | /* 2nd result is error message */ |
| 499 | | return luaL_error(L, "%s", lua_tostring(L, -n + 1)); |
| 500 | | } |
| 501 | | if (lua_toboolean(L, lua_upvalueindex(3))) { /* generator created file? */ |
| 502 | | lua_settop(L, 0); |
| 503 | | lua_pushvalue(L, lua_upvalueindex(1)); |
| 504 | | aux_close(L); /* close it */ |
| 505 | | } |
| 506 | | return 0; |
| 507 | | } |
| 485 | LStream *p = (LStream *)lua_touserdata(L, lua_upvalueindex(1)); |
| 486 | int i; |
| 487 | int n = (int)lua_tointeger(L, lua_upvalueindex(2)); |
| 488 | if (isclosed(p)) /* file is already closed? */ |
| 489 | return luaL_error(L, "file is already closed"); |
| 490 | lua_settop(L , 1); |
| 491 | for (i = 1; i <= n; i++) /* push arguments to 'g_read' */ |
| 492 | lua_pushvalue(L, lua_upvalueindex(3 + i)); |
| 493 | n = g_read(L, p->f, 2); /* 'n' is number of results */ |
| 494 | lua_assert(n > 0); /* should return at least a nil */ |
| 495 | if (!lua_isnil(L, -n)) /* read at least one value? */ |
| 496 | return n; /* return them */ |
| 497 | else { /* first result is nil: EOF or error */ |
| 498 | if (n > 1) { /* is there error information? */ |
| 499 | /* 2nd result is error message */ |
| 500 | return luaL_error(L, "%s", lua_tostring(L, -n + 1)); |
| 501 | } |
| 502 | if (lua_toboolean(L, lua_upvalueindex(3))) { /* generator created file? */ |
| 503 | lua_settop(L, 0); |
| 504 | lua_pushvalue(L, lua_upvalueindex(1)); |
| 505 | aux_close(L); /* close it */ |
| 506 | } |
| 507 | return 0; |
| 508 | } |
| 508 | 509 | } |
| 509 | 510 | |
| 510 | 511 | /* }====================================================== */ |
| 511 | 512 | |
| 512 | 513 | |
| 513 | 514 | static int g_write (lua_State *L, FILE *f, int arg) { |
| 514 | | int nargs = lua_gettop(L) - arg; |
| 515 | | int status = 1; |
| 516 | | for (; nargs--; arg++) { |
| 517 | | if (lua_type(L, arg) == LUA_TNUMBER) { |
| 518 | | /* optimization: could be done exactly as for strings */ |
| 519 | | status = status && |
| 520 | | fprintf(f, LUA_NUMBER_FMT, lua_tonumber(L, arg)) > 0; |
| 521 | | } |
| 522 | | else { |
| 523 | | size_t l; |
| 524 | | const char *s = luaL_checklstring(L, arg, &l); |
| 525 | | status = status && (fwrite(s, sizeof(char), l, f) == l); |
| 526 | | } |
| 527 | | } |
| 528 | | if (status) return 1; /* file handle already on stack top */ |
| 529 | | else return luaL_fileresult(L, status, NULL); |
| 515 | int nargs = lua_gettop(L) - arg; |
| 516 | int status = 1; |
| 517 | for (; nargs--; arg++) { |
| 518 | if (lua_type(L, arg) == LUA_TNUMBER) { |
| 519 | /* optimization: could be done exactly as for strings */ |
| 520 | status = status && |
| 521 | fprintf(f, LUA_NUMBER_FMT, lua_tonumber(L, arg)) > 0; |
| 522 | } |
| 523 | else { |
| 524 | size_t l; |
| 525 | const char *s = luaL_checklstring(L, arg, &l); |
| 526 | status = status && (fwrite(s, sizeof(char), l, f) == l); |
| 527 | } |
| 528 | } |
| 529 | if (status) return 1; /* file handle already on stack top */ |
| 530 | else return luaL_fileresult(L, status, NULL); |
| 530 | 531 | } |
| 531 | 532 | |
| 532 | 533 | |
| 533 | 534 | static int io_write (lua_State *L) { |
| 534 | | return g_write(L, getiofile(L, IO_OUTPUT), 1); |
| 535 | return g_write(L, getiofile(L, IO_OUTPUT), 1); |
| 535 | 536 | } |
| 536 | 537 | |
| 537 | 538 | |
| 538 | 539 | static int f_write (lua_State *L) { |
| 539 | | FILE *f = tofile(L); |
| 540 | | lua_pushvalue(L, 1); /* push file at the stack top (to be returned) */ |
| 541 | | return g_write(L, f, 2); |
| 540 | FILE *f = tofile(L); |
| 541 | lua_pushvalue(L, 1); /* push file at the stack top (to be returned) */ |
| 542 | return g_write(L, f, 2); |
| 542 | 543 | } |
| 543 | 544 | |
| 544 | 545 | |
| 545 | 546 | static int f_seek (lua_State *L) { |
| 546 | | static const int mode[] = {SEEK_SET, SEEK_CUR, SEEK_END}; |
| 547 | | static const char *const modenames[] = {"set", "cur", "end", NULL}; |
| 548 | | FILE *f = tofile(L); |
| 549 | | int op = luaL_checkoption(L, 2, "cur", modenames); |
| 550 | | lua_Number p3 = luaL_optnumber(L, 3, 0); |
| 551 | | l_seeknum offset = (l_seeknum)p3; |
| 552 | | luaL_argcheck(L, (lua_Number)offset == p3, 3, |
| 553 | | "not an integer in proper range"); |
| 554 | | op = l_fseek(f, offset, mode[op]); |
| 555 | | if (op) |
| 556 | | return luaL_fileresult(L, 0, NULL); /* error */ |
| 557 | | else { |
| 558 | | lua_pushnumber(L, (lua_Number)(1.0*l_ftell(f))); |
| 559 | | return 1; |
| 560 | | } |
| 547 | static const int mode[] = {SEEK_SET, SEEK_CUR, SEEK_END}; |
| 548 | static const char *const modenames[] = {"set", "cur", "end", NULL}; |
| 549 | FILE *f = tofile(L); |
| 550 | int op = luaL_checkoption(L, 2, "cur", modenames); |
| 551 | lua_Number p3 = luaL_optnumber(L, 3, 0); |
| 552 | l_seeknum offset = (l_seeknum)p3; |
| 553 | luaL_argcheck(L, (lua_Number)offset == p3, 3, |
| 554 | "not an integer in proper range"); |
| 555 | op = l_fseek(f, offset, mode[op]); |
| 556 | if (op) |
| 557 | return luaL_fileresult(L, 0, NULL); /* error */ |
| 558 | else { |
| 559 | lua_pushnumber(L, (lua_Number)(1.0 * l_ftell(f))); |
| 560 | return 1; |
| 561 | } |
| 561 | 562 | } |
| 562 | 563 | |
| 563 | 564 | |
| 564 | 565 | static int f_setvbuf (lua_State *L) { |
| 565 | | static const int mode[] = {_IONBF, _IOFBF, _IOLBF}; |
| 566 | | static const char *const modenames[] = {"no", "full", "line", NULL}; |
| 567 | | FILE *f = tofile(L); |
| 568 | | int op = luaL_checkoption(L, 2, NULL, modenames); |
| 569 | | lua_Integer sz = luaL_optinteger(L, 3, LUAL_BUFFERSIZE); |
| 570 | | int res = setvbuf(f, NULL, mode[op], sz); |
| 571 | | return luaL_fileresult(L, res == 0, NULL); |
| 566 | static const int mode[] = {_IONBF, _IOFBF, _IOLBF}; |
| 567 | static const char *const modenames[] = {"no", "full", "line", NULL}; |
| 568 | FILE *f = tofile(L); |
| 569 | int op = luaL_checkoption(L, 2, NULL, modenames); |
| 570 | lua_Integer sz = luaL_optinteger(L, 3, LUAL_BUFFERSIZE); |
| 571 | int res = setvbuf(f, NULL, mode[op], sz); |
| 572 | return luaL_fileresult(L, res == 0, NULL); |
| 572 | 573 | } |
| 573 | 574 | |
| 574 | 575 | |
| 575 | 576 | |
| 576 | 577 | static int io_flush (lua_State *L) { |
| 577 | | return luaL_fileresult(L, fflush(getiofile(L, IO_OUTPUT)) == 0, NULL); |
| 578 | return luaL_fileresult(L, fflush(getiofile(L, IO_OUTPUT)) == 0, NULL); |
| 578 | 579 | } |
| 579 | 580 | |
| 580 | 581 | |
| 581 | 582 | static int f_flush (lua_State *L) { |
| 582 | | return luaL_fileresult(L, fflush(tofile(L)) == 0, NULL); |
| 583 | return luaL_fileresult(L, fflush(tofile(L)) == 0, NULL); |
| 583 | 584 | } |
| 584 | 585 | |
| 585 | 586 | |
| r30857 | r30858 | |
| 587 | 588 | ** functions for 'io' library |
| 588 | 589 | */ |
| 589 | 590 | static const luaL_Reg iolib[] = { |
| 590 | | {"close", io_close}, |
| 591 | | {"flush", io_flush}, |
| 592 | | {"input", io_input}, |
| 593 | | {"lines", io_lines}, |
| 594 | | {"open", io_open}, |
| 595 | | {"output", io_output}, |
| 596 | | {"popen", io_popen}, |
| 597 | | {"read", io_read}, |
| 598 | | {"tmpfile", io_tmpfile}, |
| 599 | | {"type", io_type}, |
| 600 | | {"write", io_write}, |
| 601 | | {NULL, NULL} |
| 591 | {"close", io_close}, |
| 592 | {"flush", io_flush}, |
| 593 | {"input", io_input}, |
| 594 | {"lines", io_lines}, |
| 595 | {"open", io_open}, |
| 596 | {"output", io_output}, |
| 597 | {"popen", io_popen}, |
| 598 | {"read", io_read}, |
| 599 | {"tmpfile", io_tmpfile}, |
| 600 | {"type", io_type}, |
| 601 | {"write", io_write}, |
| 602 | {NULL, NULL} |
| 602 | 603 | }; |
| 603 | 604 | |
| 604 | 605 | |
| r30857 | r30858 | |
| 606 | 607 | ** methods for file handles |
| 607 | 608 | */ |
| 608 | 609 | static const luaL_Reg flib[] = { |
| 609 | | {"close", io_close}, |
| 610 | | {"flush", f_flush}, |
| 611 | | {"lines", f_lines}, |
| 612 | | {"read", f_read}, |
| 613 | | {"seek", f_seek}, |
| 614 | | {"setvbuf", f_setvbuf}, |
| 615 | | {"write", f_write}, |
| 616 | | {"__gc", f_gc}, |
| 617 | | {"__tostring", f_tostring}, |
| 618 | | {NULL, NULL} |
| 610 | {"close", io_close}, |
| 611 | {"flush", f_flush}, |
| 612 | {"lines", f_lines}, |
| 613 | {"read", f_read}, |
| 614 | {"seek", f_seek}, |
| 615 | {"setvbuf", f_setvbuf}, |
| 616 | {"write", f_write}, |
| 617 | {"__gc", f_gc}, |
| 618 | {"__tostring", f_tostring}, |
| 619 | {NULL, NULL} |
| 619 | 620 | }; |
| 620 | 621 | |
| 621 | 622 | |
| 622 | 623 | static void createmeta (lua_State *L) { |
| 623 | | luaL_newmetatable(L, LUA_FILEHANDLE); /* create metatable for file handles */ |
| 624 | | lua_pushvalue(L, -1); /* push metatable */ |
| 625 | | lua_setfield(L, -2, "__index"); /* metatable.__index = metatable */ |
| 626 | | luaL_setfuncs(L, flib, 0); /* add file methods to new metatable */ |
| 627 | | lua_pop(L, 1); /* pop new metatable */ |
| 624 | luaL_newmetatable(L, LUA_FILEHANDLE); /* create metatable for file handles */ |
| 625 | lua_pushvalue(L, -1); /* push metatable */ |
| 626 | lua_setfield(L, -2, "__index"); /* metatable.__index = metatable */ |
| 627 | luaL_setfuncs(L, flib, 0); /* add file methods to new metatable */ |
| 628 | lua_pop(L, 1); /* pop new metatable */ |
| 628 | 629 | } |
| 629 | 630 | |
| 630 | 631 | |
| r30857 | r30858 | |
| 632 | 633 | ** function to (not) close the standard files stdin, stdout, and stderr |
| 633 | 634 | */ |
| 634 | 635 | static int io_noclose (lua_State *L) { |
| 635 | | LStream *p = tolstream(L); |
| 636 | | p->closef = &io_noclose; /* keep file opened */ |
| 637 | | lua_pushnil(L); |
| 638 | | lua_pushliteral(L, "cannot close standard file"); |
| 639 | | return 2; |
| 636 | LStream *p = tolstream(L); |
| 637 | p->closef = &io_noclose; /* keep file opened */ |
| 638 | lua_pushnil(L); |
| 639 | lua_pushliteral(L, "cannot close standard file"); |
| 640 | return 2; |
| 640 | 641 | } |
| 641 | 642 | |
| 642 | 643 | |
| 643 | 644 | static void createstdfile (lua_State *L, FILE *f, const char *k, |
| 644 | | const char *fname) { |
| 645 | | LStream *p = newprefile(L); |
| 646 | | p->f = f; |
| 647 | | p->closef = &io_noclose; |
| 648 | | if (k != NULL) { |
| 649 | | lua_pushvalue(L, -1); |
| 650 | | lua_setfield(L, LUA_REGISTRYINDEX, k); /* add file to registry */ |
| 651 | | } |
| 652 | | lua_setfield(L, -2, fname); /* add file to module */ |
| 645 | const char *fname) { |
| 646 | LStream *p = newprefile(L); |
| 647 | p->f = f; |
| 648 | p->closef = &io_noclose; |
| 649 | if (k != NULL) { |
| 650 | lua_pushvalue(L, -1); |
| 651 | lua_setfield(L, LUA_REGISTRYINDEX, k); /* add file to registry */ |
| 652 | } |
| 653 | lua_setfield(L, -2, fname); /* add file to module */ |
| 653 | 654 | } |
| 654 | 655 | |
| 655 | 656 | |
| 656 | 657 | LUAMOD_API int luaopen_io (lua_State *L) { |
| 657 | | luaL_newlib(L, iolib); /* new module */ |
| 658 | | createmeta(L); |
| 659 | | /* create (and set) default files */ |
| 660 | | createstdfile(L, stdin, IO_INPUT, "stdin"); |
| 661 | | createstdfile(L, stdout, IO_OUTPUT, "stdout"); |
| 662 | | createstdfile(L, stderr, NULL, "stderr"); |
| 663 | | return 1; |
| 658 | luaL_newlib(L, iolib); /* new module */ |
| 659 | createmeta(L); |
| 660 | /* create (and set) default files */ |
| 661 | createstdfile(L, stdin, IO_INPUT, "stdin"); |
| 662 | createstdfile(L, stdout, IO_OUTPUT, "stdout"); |
| 663 | createstdfile(L, stderr, NULL, "stderr"); |
| 664 | return 1; |
| 664 | 665 | } |
| 666 | |
trunk/src/lib/lua/lstrlib.c
| r30857 | r30858 | |
| 1 | 1 | /* |
| 2 | | ** $Id: lstrlib.c,v 1.178 2012/08/14 18:12:34 roberto Exp $ |
| 2 | ** $Id: lstrlib.c,v 1.178.1.1 2013/04/12 18:48:47 roberto Exp $ |
| 3 | 3 | ** Standard library for string operations and pattern-matching |
| 4 | 4 | ** See Copyright Notice in lua.h |
| 5 | 5 | */ |
| r30857 | r30858 | |
| 25 | 25 | ** pattern-matching. This limit is arbitrary. |
| 26 | 26 | */ |
| 27 | 27 | #if !defined(LUA_MAXCAPTURES) |
| 28 | | #define LUA_MAXCAPTURES 32 |
| 28 | #define LUA_MAXCAPTURES 32 |
| 29 | 29 | #endif |
| 30 | 30 | |
| 31 | 31 | |
| 32 | 32 | /* macro to `unsign' a character */ |
| 33 | | #define uchar(c) ((unsigned char)(c)) |
| 33 | #define uchar(c) ((unsigned char)(c)) |
| 34 | 34 | |
| 35 | 35 | |
| 36 | 36 | |
| 37 | 37 | static int str_len (lua_State *L) { |
| 38 | | size_t l; |
| 39 | | luaL_checklstring(L, 1, &l); |
| 40 | | lua_pushinteger(L, (lua_Integer)l); |
| 41 | | return 1; |
| 38 | size_t l; |
| 39 | luaL_checklstring(L, 1, &l); |
| 40 | lua_pushinteger(L, (lua_Integer)l); |
| 41 | return 1; |
| 42 | 42 | } |
| 43 | 43 | |
| 44 | 44 | |
| 45 | 45 | /* translate a relative string position: negative means back from end */ |
| 46 | 46 | static size_t posrelat (ptrdiff_t pos, size_t len) { |
| 47 | | if (pos >= 0) return (size_t)pos; |
| 48 | | else if (0u - (size_t)pos > len) return 0; |
| 49 | | else return len - ((size_t)-pos) + 1; |
| 47 | if (pos >= 0) return (size_t)pos; |
| 48 | else if (0u - (size_t)pos > len) return 0; |
| 49 | else return len - ((size_t)-pos) + 1; |
| 50 | 50 | } |
| 51 | 51 | |
| 52 | 52 | |
| 53 | 53 | static int str_sub (lua_State *L) { |
| 54 | | size_t l; |
| 55 | | const char *s = luaL_checklstring(L, 1, &l); |
| 56 | | size_t start = posrelat(luaL_checkinteger(L, 2), l); |
| 57 | | size_t end = posrelat(luaL_optinteger(L, 3, -1), l); |
| 58 | | if (start < 1) start = 1; |
| 59 | | if (end > l) end = l; |
| 60 | | if (start <= end) |
| 61 | | lua_pushlstring(L, s + start - 1, end - start + 1); |
| 62 | | else lua_pushliteral(L, ""); |
| 63 | | return 1; |
| 54 | size_t l; |
| 55 | const char *s = luaL_checklstring(L, 1, &l); |
| 56 | size_t start = posrelat(luaL_checkinteger(L, 2), l); |
| 57 | size_t end = posrelat(luaL_optinteger(L, 3, -1), l); |
| 58 | if (start < 1) start = 1; |
| 59 | if (end > l) end = l; |
| 60 | if (start <= end) |
| 61 | lua_pushlstring(L, s + start - 1, end - start + 1); |
| 62 | else lua_pushliteral(L, ""); |
| 63 | return 1; |
| 64 | 64 | } |
| 65 | 65 | |
| 66 | 66 | |
| 67 | 67 | static int str_reverse (lua_State *L) { |
| 68 | | size_t l, i; |
| 69 | | luaL_Buffer b; |
| 70 | | const char *s = luaL_checklstring(L, 1, &l); |
| 71 | | char *p = luaL_buffinitsize(L, &b, l); |
| 72 | | for (i = 0; i < l; i++) |
| 73 | | p[i] = s[l - i - 1]; |
| 74 | | luaL_pushresultsize(&b, l); |
| 75 | | return 1; |
| 68 | size_t l, i; |
| 69 | luaL_Buffer b; |
| 70 | const char *s = luaL_checklstring(L, 1, &l); |
| 71 | char *p = luaL_buffinitsize(L, &b, l); |
| 72 | for (i = 0; i < l; i++) |
| 73 | p[i] = s[l - i - 1]; |
| 74 | luaL_pushresultsize(&b, l); |
| 75 | return 1; |
| 76 | 76 | } |
| 77 | 77 | |
| 78 | 78 | |
| 79 | 79 | static int str_lower (lua_State *L) { |
| 80 | | size_t l; |
| 81 | | size_t i; |
| 82 | | luaL_Buffer b; |
| 83 | | const char *s = luaL_checklstring(L, 1, &l); |
| 84 | | char *p = luaL_buffinitsize(L, &b, l); |
| 85 | | for (i=0; i<l; i++) |
| 86 | | p[i] = tolower(uchar(s[i])); |
| 87 | | luaL_pushresultsize(&b, l); |
| 88 | | return 1; |
| 80 | size_t l; |
| 81 | size_t i; |
| 82 | luaL_Buffer b; |
| 83 | const char *s = luaL_checklstring(L, 1, &l); |
| 84 | char *p = luaL_buffinitsize(L, &b, l); |
| 85 | for (i=0; i<l; i++) |
| 86 | p[i] = tolower(uchar(s[i])); |
| 87 | luaL_pushresultsize(&b, l); |
| 88 | return 1; |
| 89 | 89 | } |
| 90 | 90 | |
| 91 | 91 | |
| 92 | 92 | static int str_upper (lua_State *L) { |
| 93 | | size_t l; |
| 94 | | size_t i; |
| 95 | | luaL_Buffer b; |
| 96 | | const char *s = luaL_checklstring(L, 1, &l); |
| 97 | | char *p = luaL_buffinitsize(L, &b, l); |
| 98 | | for (i=0; i<l; i++) |
| 99 | | p[i] = toupper(uchar(s[i])); |
| 100 | | luaL_pushresultsize(&b, l); |
| 101 | | return 1; |
| 93 | size_t l; |
| 94 | size_t i; |
| 95 | luaL_Buffer b; |
| 96 | const char *s = luaL_checklstring(L, 1, &l); |
| 97 | char *p = luaL_buffinitsize(L, &b, l); |
| 98 | for (i=0; i<l; i++) |
| 99 | p[i] = toupper(uchar(s[i])); |
| 100 | luaL_pushresultsize(&b, l); |
| 101 | return 1; |
| 102 | 102 | } |
| 103 | 103 | |
| 104 | 104 | |
| 105 | 105 | /* reasonable limit to avoid arithmetic overflow */ |
| 106 | | #define MAXSIZE ((~(size_t)0) >> 1) |
| 106 | #define MAXSIZE ((~(size_t)0) >> 1) |
| 107 | 107 | |
| 108 | 108 | static int str_rep (lua_State *L) { |
| 109 | | size_t l, lsep; |
| 110 | | const char *s = luaL_checklstring(L, 1, &l); |
| 111 | | int n = luaL_checkint(L, 2); |
| 112 | | const char *sep = luaL_optlstring(L, 3, "", &lsep); |
| 113 | | if (n <= 0) lua_pushliteral(L, ""); |
| 114 | | else if (l + lsep < l || l + lsep >= MAXSIZE / n) /* may overflow? */ |
| 115 | | return luaL_error(L, "resulting string too large"); |
| 116 | | else { |
| 117 | | size_t totallen = n * l + (n - 1) * lsep; |
| 118 | | luaL_Buffer b; |
| 119 | | char *p = luaL_buffinitsize(L, &b, totallen); |
| 120 | | while (n-- > 1) { /* first n-1 copies (followed by separator) */ |
| 121 | | memcpy(p, s, l * sizeof(char)); p += l; |
| 122 | | if (lsep > 0) { /* avoid empty 'memcpy' (may be expensive) */ |
| 123 | | memcpy(p, sep, lsep * sizeof(char)); p += lsep; |
| 124 | | } |
| 125 | | } |
| 126 | | memcpy(p, s, l * sizeof(char)); /* last copy (not followed by separator) */ |
| 127 | | luaL_pushresultsize(&b, totallen); |
| 128 | | } |
| 129 | | return 1; |
| 109 | size_t l, lsep; |
| 110 | const char *s = luaL_checklstring(L, 1, &l); |
| 111 | int n = luaL_checkint(L, 2); |
| 112 | const char *sep = luaL_optlstring(L, 3, "", &lsep); |
| 113 | if (n <= 0) lua_pushliteral(L, ""); |
| 114 | else if (l + lsep < l || l + lsep >= MAXSIZE / n) /* may overflow? */ |
| 115 | return luaL_error(L, "resulting string too large"); |
| 116 | else { |
| 117 | size_t totallen = n * l + (n - 1) * lsep; |
| 118 | luaL_Buffer b; |
| 119 | char *p = luaL_buffinitsize(L, &b, totallen); |
| 120 | while (n-- > 1) { /* first n-1 copies (followed by separator) */ |
| 121 | memcpy(p, s, l * sizeof(char)); p += l; |
| 122 | if (lsep > 0) { /* avoid empty 'memcpy' (may be expensive) */ |
| 123 | memcpy(p, sep, lsep * sizeof(char)); p += lsep; |
| 124 | } |
| 125 | } |
| 126 | memcpy(p, s, l * sizeof(char)); /* last copy (not followed by separator) */ |
| 127 | luaL_pushresultsize(&b, totallen); |
| 128 | } |
| 129 | return 1; |
| 130 | 130 | } |
| 131 | 131 | |
| 132 | 132 | |
| 133 | 133 | static int str_byte (lua_State *L) { |
| 134 | | size_t l; |
| 135 | | const char *s = luaL_checklstring(L, 1, &l); |
| 136 | | size_t posi = posrelat(luaL_optinteger(L, 2, 1), l); |
| 137 | | size_t pose = posrelat(luaL_optinteger(L, 3, posi), l); |
| 138 | | int n, i; |
| 139 | | if (posi < 1) posi = 1; |
| 140 | | if (pose > l) pose = l; |
| 141 | | if (posi > pose) return 0; /* empty interval; return no values */ |
| 142 | | n = (int)(pose - posi + 1); |
| 143 | | if (posi + n <= pose) /* (size_t -> int) overflow? */ |
| 144 | | return luaL_error(L, "string slice too long"); |
| 145 | | luaL_checkstack(L, n, "string slice too long"); |
| 146 | | for (i=0; i<n; i++) |
| 147 | | lua_pushinteger(L, uchar(s[posi+i-1])); |
| 148 | | return n; |
| 134 | size_t l; |
| 135 | const char *s = luaL_checklstring(L, 1, &l); |
| 136 | size_t posi = posrelat(luaL_optinteger(L, 2, 1), l); |
| 137 | size_t pose = posrelat(luaL_optinteger(L, 3, posi), l); |
| 138 | int n, i; |
| 139 | if (posi < 1) posi = 1; |
| 140 | if (pose > l) pose = l; |
| 141 | if (posi > pose) return 0; /* empty interval; return no values */ |
| 142 | n = (int)(pose - posi + 1); |
| 143 | if (posi + n <= pose) /* (size_t -> int) overflow? */ |
| 144 | return luaL_error(L, "string slice too long"); |
| 145 | luaL_checkstack(L, n, "string slice too long"); |
| 146 | for (i=0; i<n; i++) |
| 147 | lua_pushinteger(L, uchar(s[posi+i-1])); |
| 148 | return n; |
| 149 | 149 | } |
| 150 | 150 | |
| 151 | 151 | |
| 152 | 152 | static int str_char (lua_State *L) { |
| 153 | | int n = lua_gettop(L); /* number of arguments */ |
| 154 | | int i; |
| 155 | | luaL_Buffer b; |
| 156 | | char *p = luaL_buffinitsize(L, &b, n); |
| 157 | | for (i=1; i<=n; i++) { |
| 158 | | int c = luaL_checkint(L, i); |
| 159 | | luaL_argcheck(L, uchar(c) == c, i, "value out of range"); |
| 160 | | p[i - 1] = uchar(c); |
| 161 | | } |
| 162 | | luaL_pushresultsize(&b, n); |
| 163 | | return 1; |
| 153 | int n = lua_gettop(L); /* number of arguments */ |
| 154 | int i; |
| 155 | luaL_Buffer b; |
| 156 | char *p = luaL_buffinitsize(L, &b, n); |
| 157 | for (i=1; i<=n; i++) { |
| 158 | int c = luaL_checkint(L, i); |
| 159 | luaL_argcheck(L, uchar(c) == c, i, "value out of range"); |
| 160 | p[i - 1] = uchar(c); |
| 161 | } |
| 162 | luaL_pushresultsize(&b, n); |
| 163 | return 1; |
| 164 | 164 | } |
| 165 | 165 | |
| 166 | 166 | |
| 167 | 167 | static int writer (lua_State *L, const void* b, size_t size, void* B) { |
| 168 | | (void)L; |
| 169 | | luaL_addlstring((luaL_Buffer*) B, (const char *)b, size); |
| 170 | | return 0; |
| 168 | (void)L; |
| 169 | luaL_addlstring((luaL_Buffer*) B, (const char *)b, size); |
| 170 | return 0; |
| 171 | 171 | } |
| 172 | 172 | |
| 173 | 173 | |
| 174 | 174 | static int str_dump (lua_State *L) { |
| 175 | | luaL_Buffer b; |
| 176 | | luaL_checktype(L, 1, LUA_TFUNCTION); |
| 177 | | lua_settop(L, 1); |
| 178 | | luaL_buffinit(L,&b); |
| 179 | | if (lua_dump(L, writer, &b) != 0) |
| 180 | | return luaL_error(L, "unable to dump given function"); |
| 181 | | luaL_pushresult(&b); |
| 182 | | return 1; |
| 175 | luaL_Buffer b; |
| 176 | luaL_checktype(L, 1, LUA_TFUNCTION); |
| 177 | lua_settop(L, 1); |
| 178 | luaL_buffinit(L,&b); |
| 179 | if (lua_dump(L, writer, &b) != 0) |
| 180 | return luaL_error(L, "unable to dump given function"); |
| 181 | luaL_pushresult(&b); |
| 182 | return 1; |
| 183 | 183 | } |
| 184 | 184 | |
| 185 | 185 | |
| r30857 | r30858 | |
| 191 | 191 | */ |
| 192 | 192 | |
| 193 | 193 | |
| 194 | | #define CAP_UNFINISHED (-1) |
| 195 | | #define CAP_POSITION (-2) |
| 194 | #define CAP_UNFINISHED (-1) |
| 195 | #define CAP_POSITION (-2) |
| 196 | 196 | |
| 197 | 197 | |
| 198 | 198 | typedef struct MatchState { |
| 199 | | int matchdepth; /* control for recursive depth (to avoid C stack overflow) */ |
| 200 | | const char *src_init; /* init of source string */ |
| 201 | | const char *src_end; /* end ('\0') of source string */ |
| 202 | | const char *p_end; /* end ('\0') of pattern */ |
| 203 | | lua_State *L; |
| 204 | | int level; /* total number of captures (finished or unfinished) */ |
| 205 | | struct { |
| 206 | | const char *init; |
| 207 | | ptrdiff_t len; |
| 208 | | } capture[LUA_MAXCAPTURES]; |
| 199 | int matchdepth; /* control for recursive depth (to avoid C stack overflow) */ |
| 200 | const char *src_init; /* init of source string */ |
| 201 | const char *src_end; /* end ('\0') of source string */ |
| 202 | const char *p_end; /* end ('\0') of pattern */ |
| 203 | lua_State *L; |
| 204 | int level; /* total number of captures (finished or unfinished) */ |
| 205 | struct { |
| 206 | const char *init; |
| 207 | ptrdiff_t len; |
| 208 | } capture[LUA_MAXCAPTURES]; |
| 209 | 209 | } MatchState; |
| 210 | 210 | |
| 211 | 211 | |
| r30857 | r30858 | |
| 215 | 215 | |
| 216 | 216 | /* maximum recursion depth for 'match' */ |
| 217 | 217 | #if !defined(MAXCCALLS) |
| 218 | | #define MAXCCALLS 200 |
| 218 | #define MAXCCALLS 200 |
| 219 | 219 | #endif |
| 220 | 220 | |
| 221 | 221 | |
| 222 | | #define L_ESC '%' |
| 223 | | #define SPECIALS "^$*+?.([%-" |
| 222 | #define L_ESC '%' |
| 223 | #define SPECIALS "^$*+?.([%-" |
| 224 | 224 | |
| 225 | 225 | |
| 226 | 226 | static int check_capture (MatchState *ms, int l) { |
| 227 | | l -= '1'; |
| 228 | | if (l < 0 || l >= ms->level || ms->capture[l].len == CAP_UNFINISHED) |
| 229 | | return luaL_error(ms->L, "invalid capture index %%%d", l + 1); |
| 230 | | return l; |
| 227 | l -= '1'; |
| 228 | if (l < 0 || l >= ms->level || ms->capture[l].len == CAP_UNFINISHED) |
| 229 | return luaL_error(ms->L, "invalid capture index %%%d", l + 1); |
| 230 | return l; |
| 231 | 231 | } |
| 232 | 232 | |
| 233 | 233 | |
| 234 | 234 | static int capture_to_close (MatchState *ms) { |
| 235 | | int level = ms->level; |
| 236 | | for (level--; level>=0; level--) |
| 237 | | if (ms->capture[level].len == CAP_UNFINISHED) return level; |
| 238 | | return luaL_error(ms->L, "invalid pattern capture"); |
| 235 | int level = ms->level; |
| 236 | for (level--; level>=0; level--) |
| 237 | if (ms->capture[level].len == CAP_UNFINISHED) return level; |
| 238 | return luaL_error(ms->L, "invalid pattern capture"); |
| 239 | 239 | } |
| 240 | 240 | |
| 241 | 241 | |
| 242 | 242 | static const char *classend (MatchState *ms, const char *p) { |
| 243 | | switch (*p++) { |
| 244 | | case L_ESC: { |
| 245 | | if (p == ms->p_end) |
| 246 | | luaL_error(ms->L, "malformed pattern (ends with " LUA_QL("%%") ")"); |
| 247 | | return p+1; |
| 248 | | } |
| 249 | | case '[': { |
| 250 | | if (*p == '^') p++; |
| 251 | | do { /* look for a `]' */ |
| 252 | | if (p == ms->p_end) |
| 253 | | luaL_error(ms->L, "malformed pattern (missing " LUA_QL("]") ")"); |
| 254 | | if (*(p++) == L_ESC && p < ms->p_end) |
| 255 | | p++; /* skip escapes (e.g. `%]') */ |
| 256 | | } while (*p != ']'); |
| 257 | | return p+1; |
| 258 | | } |
| 259 | | default: { |
| 260 | | return p; |
| 261 | | } |
| 262 | | } |
| 243 | switch (*p++) { |
| 244 | case L_ESC: { |
| 245 | if (p == ms->p_end) |
| 246 | luaL_error(ms->L, "malformed pattern (ends with " LUA_QL("%%") ")"); |
| 247 | return p+1; |
| 248 | } |
| 249 | case '[': { |
| 250 | if (*p == '^') p++; |
| 251 | do { /* look for a `]' */ |
| 252 | if (p == ms->p_end) |
| 253 | luaL_error(ms->L, "malformed pattern (missing " LUA_QL("]") ")"); |
| 254 | if (*(p++) == L_ESC && p < ms->p_end) |
| 255 | p++; /* skip escapes (e.g. `%]') */ |
| 256 | } while (*p != ']'); |
| 257 | return p+1; |
| 258 | } |
| 259 | default: { |
| 260 | return p; |
| 261 | } |
| 262 | } |
| 263 | 263 | } |
| 264 | 264 | |
| 265 | 265 | |
| 266 | 266 | static int match_class (int c, int cl) { |
| 267 | | int res; |
| 268 | | switch (tolower(cl)) { |
| 269 | | case 'a' : res = isalpha(c); break; |
| 270 | | case 'c' : res = iscntrl(c); break; |
| 271 | | case 'd' : res = isdigit(c); break; |
| 272 | | case 'g' : res = isgraph(c); break; |
| 273 | | case 'l' : res = islower(c); break; |
| 274 | | case 'p' : res = ispunct(c); break; |
| 275 | | case 's' : res = isspace(c); break; |
| 276 | | case 'u' : res = isupper(c); break; |
| 277 | | case 'w' : res = isalnum(c); break; |
| 278 | | case 'x' : res = isxdigit(c); break; |
| 279 | | case 'z' : res = (c == 0); break; /* deprecated option */ |
| 280 | | default: return (cl == c); |
| 281 | | } |
| 282 | | return (islower(cl) ? res : !res); |
| 267 | int res; |
| 268 | switch (tolower(cl)) { |
| 269 | case 'a' : res = isalpha(c); break; |
| 270 | case 'c' : res = iscntrl(c); break; |
| 271 | case 'd' : res = isdigit(c); break; |
| 272 | case 'g' : res = isgraph(c); break; |
| 273 | case 'l' : res = islower(c); break; |
| 274 | case 'p' : res = ispunct(c); break; |
| 275 | case 's' : res = isspace(c); break; |
| 276 | case 'u' : res = isupper(c); break; |
| 277 | case 'w' : res = isalnum(c); break; |
| 278 | case 'x' : res = isxdigit(c); break; |
| 279 | case 'z' : res = (c == 0); break; /* deprecated option */ |
| 280 | default: return (cl == c); |
| 281 | } |
| 282 | return (islower(cl) ? res : !res); |
| 283 | 283 | } |
| 284 | 284 | |
| 285 | 285 | |
| 286 | 286 | static int matchbracketclass (int c, const char *p, const char *ec) { |
| 287 | | int sig = 1; |
| 288 | | if (*(p+1) == '^') { |
| 289 | | sig = 0; |
| 290 | | p++; /* skip the `^' */ |
| 291 | | } |
| 292 | | while (++p < ec) { |
| 293 | | if (*p == L_ESC) { |
| 294 | | p++; |
| 295 | | if (match_class(c, uchar(*p))) |
| 296 | | return sig; |
| 297 | | } |
| 298 | | else if ((*(p+1) == '-') && (p+2 < ec)) { |
| 299 | | p+=2; |
| 300 | | if (uchar(*(p-2)) <= c && c <= uchar(*p)) |
| 301 | | return sig; |
| 302 | | } |
| 303 | | else if (uchar(*p) == c) return sig; |
| 304 | | } |
| 305 | | return !sig; |
| 287 | int sig = 1; |
| 288 | if (*(p+1) == '^') { |
| 289 | sig = 0; |
| 290 | p++; /* skip the `^' */ |
| 291 | } |
| 292 | while (++p < ec) { |
| 293 | if (*p == L_ESC) { |
| 294 | p++; |
| 295 | if (match_class(c, uchar(*p))) |
| 296 | return sig; |
| 297 | } |
| 298 | else if ((*(p+1) == '-') && (p+2 < ec)) { |
| 299 | p+=2; |
| 300 | if (uchar(*(p-2)) <= c && c <= uchar(*p)) |
| 301 | return sig; |
| 302 | } |
| 303 | else if (uchar(*p) == c) return sig; |
| 304 | } |
| 305 | return !sig; |
| 306 | 306 | } |
| 307 | 307 | |
| 308 | 308 | |
| 309 | 309 | static int singlematch (MatchState *ms, const char *s, const char *p, |
| 310 | | const char *ep) { |
| 311 | | if (s >= ms->src_end) |
| 312 | | return 0; |
| 313 | | else { |
| 314 | | int c = uchar(*s); |
| 315 | | switch (*p) { |
| 316 | | case '.': return 1; /* matches any char */ |
| 317 | | case L_ESC: return match_class(c, uchar(*(p+1))); |
| 318 | | case '[': return matchbracketclass(c, p, ep-1); |
| 319 | | default: return (uchar(*p) == c); |
| 320 | | } |
| 321 | | } |
| 310 | const char *ep) { |
| 311 | if (s >= ms->src_end) |
| 312 | return 0; |
| 313 | else { |
| 314 | int c = uchar(*s); |
| 315 | switch (*p) { |
| 316 | case '.': return 1; /* matches any char */ |
| 317 | case L_ESC: return match_class(c, uchar(*(p+1))); |
| 318 | case '[': return matchbracketclass(c, p, ep-1); |
| 319 | default: return (uchar(*p) == c); |
| 320 | } |
| 321 | } |
| 322 | 322 | } |
| 323 | 323 | |
| 324 | 324 | |
| 325 | 325 | static const char *matchbalance (MatchState *ms, const char *s, |
| 326 | | const char *p) { |
| 327 | | if (p >= ms->p_end - 1) |
| 328 | | luaL_error(ms->L, "malformed pattern " |
| 329 | | "(missing arguments to " LUA_QL("%%b") ")"); |
| 330 | | if (*s != *p) return NULL; |
| 331 | | else { |
| 332 | | int b = *p; |
| 333 | | int e = *(p+1); |
| 334 | | int cont = 1; |
| 335 | | while (++s < ms->src_end) { |
| 336 | | if (*s == e) { |
| 337 | | if (--cont == 0) return s+1; |
| 338 | | } |
| 339 | | else if (*s == b) cont++; |
| 340 | | } |
| 341 | | } |
| 342 | | return NULL; /* string ends out of balance */ |
| 326 | const char *p) { |
| 327 | if (p >= ms->p_end - 1) |
| 328 | luaL_error(ms->L, "malformed pattern " |
| 329 | "(missing arguments to " LUA_QL("%%b") ")"); |
| 330 | if (*s != *p) return NULL; |
| 331 | else { |
| 332 | int b = *p; |
| 333 | int e = *(p+1); |
| 334 | int cont = 1; |
| 335 | while (++s < ms->src_end) { |
| 336 | if (*s == e) { |
| 337 | if (--cont == 0) return s+1; |
| 338 | } |
| 339 | else if (*s == b) cont++; |
| 340 | } |
| 341 | } |
| 342 | return NULL; /* string ends out of balance */ |
| 343 | 343 | } |
| 344 | 344 | |
| 345 | 345 | |
| 346 | 346 | static const char *max_expand (MatchState *ms, const char *s, |
| 347 | | const char *p, const char *ep) { |
| 348 | | ptrdiff_t i = 0; /* counts maximum expand for item */ |
| 349 | | while (singlematch(ms, s + i, p, ep)) |
| 350 | | i++; |
| 351 | | /* keeps trying to match with the maximum repetitions */ |
| 352 | | while (i>=0) { |
| 353 | | const char *res = match(ms, (s+i), ep+1); |
| 354 | | if (res) return res; |
| 355 | | i--; /* else didn't match; reduce 1 repetition to try again */ |
| 356 | | } |
| 357 | | return NULL; |
| 347 | const char *p, const char *ep) { |
| 348 | ptrdiff_t i = 0; /* counts maximum expand for item */ |
| 349 | while (singlematch(ms, s + i, p, ep)) |
| 350 | i++; |
| 351 | /* keeps trying to match with the maximum repetitions */ |
| 352 | while (i>=0) { |
| 353 | const char *res = match(ms, (s+i), ep+1); |
| 354 | if (res) return res; |
| 355 | i--; /* else didn't match; reduce 1 repetition to try again */ |
| 356 | } |
| 357 | return NULL; |
| 358 | 358 | } |
| 359 | 359 | |
| 360 | 360 | |
| 361 | 361 | static const char *min_expand (MatchState *ms, const char *s, |
| 362 | | const char *p, const char *ep) { |
| 363 | | for (;;) { |
| 364 | | const char *res = match(ms, s, ep+1); |
| 365 | | if (res != NULL) |
| 366 | | return res; |
| 367 | | else if (singlematch(ms, s, p, ep)) |
| 368 | | s++; /* try with one more repetition */ |
| 369 | | else return NULL; |
| 370 | | } |
| 362 | const char *p, const char *ep) { |
| 363 | for (;;) { |
| 364 | const char *res = match(ms, s, ep+1); |
| 365 | if (res != NULL) |
| 366 | return res; |
| 367 | else if (singlematch(ms, s, p, ep)) |
| 368 | s++; /* try with one more repetition */ |
| 369 | else return NULL; |
| 370 | } |
| 371 | 371 | } |
| 372 | 372 | |
| 373 | 373 | |
| 374 | 374 | static const char *start_capture (MatchState *ms, const char *s, |
| 375 | | const char *p, int what) { |
| 376 | | const char *res; |
| 377 | | int level = ms->level; |
| 378 | | if (level >= LUA_MAXCAPTURES) luaL_error(ms->L, "too many captures"); |
| 379 | | ms->capture[level].init = s; |
| 380 | | ms->capture[level].len = what; |
| 381 | | ms->level = level+1; |
| 382 | | if ((res=match(ms, s, p)) == NULL) /* match failed? */ |
| 383 | | ms->level--; /* undo capture */ |
| 384 | | return res; |
| 375 | const char *p, int what) { |
| 376 | const char *res; |
| 377 | int level = ms->level; |
| 378 | if (level >= LUA_MAXCAPTURES) luaL_error(ms->L, "too many captures"); |
| 379 | ms->capture[level].init = s; |
| 380 | ms->capture[level].len = what; |
| 381 | ms->level = level+1; |
| 382 | if ((res=match(ms, s, p)) == NULL) /* match failed? */ |
| 383 | ms->level--; /* undo capture */ |
| 384 | return res; |
| 385 | 385 | } |
| 386 | 386 | |
| 387 | 387 | |
| 388 | 388 | static const char *end_capture (MatchState *ms, const char *s, |
| 389 | | const char *p) { |
| 390 | | int l = capture_to_close(ms); |
| 391 | | const char *res; |
| 392 | | ms->capture[l].len = s - ms->capture[l].init; /* close capture */ |
| 393 | | if ((res = match(ms, s, p)) == NULL) /* match failed? */ |
| 394 | | ms->capture[l].len = CAP_UNFINISHED; /* undo capture */ |
| 395 | | return res; |
| 389 | const char *p) { |
| 390 | int l = capture_to_close(ms); |
| 391 | const char *res; |
| 392 | ms->capture[l].len = s - ms->capture[l].init; /* close capture */ |
| 393 | if ((res = match(ms, s, p)) == NULL) /* match failed? */ |
| 394 | ms->capture[l].len = CAP_UNFINISHED; /* undo capture */ |
| 395 | return res; |
| 396 | 396 | } |
| 397 | 397 | |
| 398 | 398 | |
| 399 | 399 | static const char *match_capture (MatchState *ms, const char *s, int l) { |
| 400 | | size_t len; |
| 401 | | l = check_capture(ms, l); |
| 402 | | len = ms->capture[l].len; |
| 403 | | if ((size_t)(ms->src_end-s) >= len && |
| 404 | | memcmp(ms->capture[l].init, s, len) == 0) |
| 405 | | return s+len; |
| 406 | | else return NULL; |
| 400 | size_t len; |
| 401 | l = check_capture(ms, l); |
| 402 | len = ms->capture[l].len; |
| 403 | if ((size_t)(ms->src_end-s) >= len && |
| 404 | memcmp(ms->capture[l].init, s, len) == 0) |
| 405 | return s+len; |
| 406 | else return NULL; |
| 407 | 407 | } |
| 408 | 408 | |
| 409 | 409 | |
| 410 | 410 | static const char *match (MatchState *ms, const char *s, const char *p) { |
| 411 | | if (ms->matchdepth-- == 0) |
| 412 | | luaL_error(ms->L, "pattern too complex"); |
| 413 | | init: /* using goto's to optimize tail recursion */ |
| 414 | | if (p != ms->p_end) { /* end of pattern? */ |
| 415 | | switch (*p) { |
| 416 | | case '(': { /* start capture */ |
| 417 | | if (*(p + 1) == ')') /* position capture? */ |
| 418 | | s = start_capture(ms, s, p + 2, CAP_POSITION); |
| 419 | | else |
| 420 | | s = start_capture(ms, s, p + 1, CAP_UNFINISHED); |
| 421 | | break; |
| 422 | | } |
| 423 | | case ')': { /* end capture */ |
| 424 | | s = end_capture(ms, s, p + 1); |
| 425 | | break; |
| 426 | | } |
| 427 | | case '$': { |
| 428 | | if ((p + 1) != ms->p_end) /* is the `$' the last char in pattern? */ |
| 429 | | goto dflt; /* no; go to default */ |
| 430 | | s = (s == ms->src_end) ? s : NULL; /* check end of string */ |
| 431 | | break; |
| 432 | | } |
| 433 | | case L_ESC: { /* escaped sequences not in the format class[*+?-]? */ |
| 434 | | switch (*(p + 1)) { |
| 435 | | case 'b': { /* balanced string? */ |
| 436 | | s = matchbalance(ms, s, p + 2); |
| 437 | | if (s != NULL) { |
| 438 | | p += 4; goto init; /* return match(ms, s, p + 4); */ |
| 439 | | } /* else fail (s == NULL) */ |
| 440 | | break; |
| 441 | | } |
| 442 | | case 'f': { /* frontier? */ |
| 443 | | const char *ep; char previous; |
| 444 | | p += 2; |
| 445 | | if (*p != '[') |
| 446 | | luaL_error(ms->L, "missing " LUA_QL("[") " after " |
| 447 | | LUA_QL("%%f") " in pattern"); |
| 448 | | ep = classend(ms, p); /* points to what is next */ |
| 449 | | previous = (s == ms->src_init) ? '\0' : *(s - 1); |
| 450 | | if (!matchbracketclass(uchar(previous), p, ep - 1) && |
| 451 | | matchbracketclass(uchar(*s), p, ep - 1)) { |
| 452 | | p = ep; goto init; /* return match(ms, s, ep); */ |
| 453 | | } |
| 454 | | s = NULL; /* match failed */ |
| 455 | | break; |
| 456 | | } |
| 457 | | case '0': case '1': case '2': case '3': |
| 458 | | case '4': case '5': case '6': case '7': |
| 459 | | case '8': case '9': { /* capture results (%0-%9)? */ |
| 460 | | s = match_capture(ms, s, uchar(*(p + 1))); |
| 461 | | if (s != NULL) { |
| 462 | | p += 2; goto init; /* return match(ms, s, p + 2) */ |
| 463 | | } |
| 464 | | break; |
| 465 | | } |
| 466 | | default: goto dflt; |
| 467 | | } |
| 468 | | break; |
| 469 | | } |
| 470 | | default: dflt: { /* pattern class plus optional suffix */ |
| 471 | | const char *ep = classend(ms, p); /* points to optional suffix */ |
| 472 | | /* does not match at least once? */ |
| 473 | | if (!singlematch(ms, s, p, ep)) { |
| 474 | | if (*ep == '*' || *ep == '?' || *ep == '-') { /* accept empty? */ |
| 475 | | p = ep + 1; goto init; /* return match(ms, s, ep + 1); */ |
| 476 | | } |
| 477 | | else /* '+' or no suffix */ |
| 478 | | s = NULL; /* fail */ |
| 479 | | } |
| 480 | | else { /* matched once */ |
| 481 | | switch (*ep) { /* handle optional suffix */ |
| 482 | | case '?': { /* optional */ |
| 483 | | const char *res; |
| 484 | | if ((res = match(ms, s + 1, ep + 1)) != NULL) |
| 485 | | s = res; |
| 486 | | else { |
| 487 | | p = ep + 1; goto init; /* else return match(ms, s, ep + 1); */ |
| 488 | | } |
| 489 | | break; |
| 490 | | } |
| 491 | | case '+': /* 1 or more repetitions */ |
| 492 | | s++; /* 1 match already done */ |
| 493 | | /* go through */ |
| 494 | | case '*': /* 0 or more repetitions */ |
| 495 | | s = max_expand(ms, s, p, ep); |
| 496 | | break; |
| 497 | | case '-': /* 0 or more repetitions (minimum) */ |
| 498 | | s = min_expand(ms, s, p, ep); |
| 499 | | break; |
| 500 | | default: /* no suffix */ |
| 501 | | s++; p = ep; goto init; /* return match(ms, s + 1, ep); */ |
| 502 | | } |
| 503 | | } |
| 504 | | break; |
| 505 | | } |
| 506 | | } |
| 507 | | } |
| 508 | | ms->matchdepth++; |
| 509 | | return s; |
| 411 | if (ms->matchdepth-- == 0) |
| 412 | luaL_error(ms->L, "pattern too complex"); |
| 413 | init: /* using goto's to optimize tail recursion */ |
| 414 | if (p != ms->p_end) { /* end of pattern? */ |
| 415 | switch (*p) { |
| 416 | case '(': { /* start capture */ |
| 417 | if (*(p + 1) == ')') /* position capture? */ |
| 418 | s = start_capture(ms, s, p + 2, CAP_POSITION); |
| 419 | else |
| 420 | s = start_capture(ms, s, p + 1, CAP_UNFINISHED); |
| 421 | break; |
| 422 | } |
| 423 | case ')': { /* end capture */ |
| 424 | s = end_capture(ms, s, p + 1); |
| 425 | break; |
| 426 | } |
| 427 | case '$': { |
| 428 | if ((p + 1) != ms->p_end) /* is the `$' the last char in pattern? */ |
| 429 | goto dflt; /* no; go to default */ |
| 430 | s = (s == ms->src_end) ? s : NULL; /* check end of string */ |
| 431 | break; |
| 432 | } |
| 433 | case L_ESC: { /* escaped sequences not in the format class[*+?-]? */ |
| 434 | switch (*(p + 1)) { |
| 435 | case 'b': { /* balanced string? */ |
| 436 | s = matchbalance(ms, s, p + 2); |
| 437 | if (s != NULL) { |
| 438 | p += 4; goto init; /* return match(ms, s, p + 4); */ |
| 439 | } /* else fail (s == NULL) */ |
| 440 | break; |
| 441 | } |
| 442 | case 'f': { /* frontier? */ |
| 443 | const char *ep; char previous; |
| 444 | p += 2; |
| 445 | if (*p != '[') |
| 446 | luaL_error(ms->L, "missing " LUA_QL("[") " after " |
| 447 | LUA_QL("%%f") " in pattern"); |
| 448 | ep = classend(ms, p); /* points to what is next */ |
| 449 | previous = (s == ms->src_init) ? '\0' : *(s - 1); |
| 450 | if (!matchbracketclass(uchar(previous), p, ep - 1) && |
| 451 | matchbracketclass(uchar(*s), p, ep - 1)) { |
| 452 | p = ep; goto init; /* return match(ms, s, ep); */ |
| 453 | } |
| 454 | s = NULL; /* match failed */ |
| 455 | break; |
| 456 | } |
| 457 | case '0': case '1': case '2': case '3': |
| 458 | case '4': case '5': case '6': case '7': |
| 459 | case '8': case '9': { /* capture results (%0-%9)? */ |
| 460 | s = match_capture(ms, s, uchar(*(p + 1))); |
| 461 | if (s != NULL) { |
| 462 | p += 2; goto init; /* return match(ms, s, p + 2) */ |
| 463 | } |
| 464 | break; |
| 465 | } |
| 466 | default: goto dflt; |
| 467 | } |
| 468 | break; |
| 469 | } |
| 470 | default: dflt: { /* pattern class plus optional suffix */ |
| 471 | const char *ep = classend(ms, p); /* points to optional suffix */ |
| 472 | /* does not match at least once? */ |
| 473 | if (!singlematch(ms, s, p, ep)) { |
| 474 | if (*ep == '*' || *ep == '?' || *ep == '-') { /* accept empty? */ |
| 475 | p = ep + 1; goto init; /* return match(ms, s, ep + 1); */ |
| 476 | } |
| 477 | else /* '+' or no suffix */ |
| 478 | s = NULL; /* fail */ |
| 479 | } |
| 480 | else { /* matched once */ |
| 481 | switch (*ep) { /* handle optional suffix */ |
| 482 | case '?': { /* optional */ |
| 483 | const char *res; |
| 484 | if ((res = match(ms, s + 1, ep + 1)) != NULL) |
| 485 | s = res; |
| 486 | else { |
| 487 | p = ep + 1; goto init; /* else return match(ms, s, ep + 1); */ |
| 488 | } |
| 489 | break; |
| 490 | } |
| 491 | case '+': /* 1 or more repetitions */ |
| 492 | s++; /* 1 match already done */ |
| 493 | /* go through */ |
| 494 | case '*': /* 0 or more repetitions */ |
| 495 | s = max_expand(ms, s, p, ep); |
| 496 | break; |
| 497 | case '-': /* 0 or more repetitions (minimum) */ |
| 498 | s = min_expand(ms, s, p, ep); |
| 499 | break; |
| 500 | default: /* no suffix */ |
| 501 | s++; p = ep; goto init; /* return match(ms, s + 1, ep); */ |
| 502 | } |
| 503 | } |
| 504 | break; |
| 505 | } |
| 506 | } |
| 507 | } |
| 508 | ms->matchdepth++; |
| 509 | return s; |
| 510 | 510 | } |
| 511 | 511 | |
| 512 | 512 | |
| 513 | 513 | |
| 514 | 514 | static const char *lmemfind (const char *s1, size_t l1, |
| 515 | | const char *s2, size_t l2) { |
| 516 | | if (l2 == 0) return s1; /* empty strings are everywhere */ |
| 517 | | else if (l2 > l1) return NULL; /* avoids a negative `l1' */ |
| 518 | | else { |
| 519 | | const char *init; /* to search for a `*s2' inside `s1' */ |
| 520 | | l2--; /* 1st char will be checked by `memchr' */ |
| 521 | | l1 = l1-l2; /* `s2' cannot be found after that */ |
| 522 | | while (l1 > 0 && (init = (const char *)memchr(s1, *s2, l1)) != NULL) { |
| 523 | | init++; /* 1st char is already checked */ |
| 524 | | if (memcmp(init, s2+1, l2) == 0) |
| 525 | | return init-1; |
| 526 | | else { /* correct `l1' and `s1' to try again */ |
| 527 | | l1 -= init-s1; |
| 528 | | s1 = init; |
| 529 | | } |
| 530 | | } |
| 531 | | return NULL; /* not found */ |
| 532 | | } |
| 515 | const char *s2, size_t l2) { |
| 516 | if (l2 == 0) return s1; /* empty strings are everywhere */ |
| 517 | else if (l2 > l1) return NULL; /* avoids a negative `l1' */ |
| 518 | else { |
| 519 | const char *init; /* to search for a `*s2' inside `s1' */ |
| 520 | l2--; /* 1st char will be checked by `memchr' */ |
| 521 | l1 = l1-l2; /* `s2' cannot be found after that */ |
| 522 | while (l1 > 0 && (init = (const char *)memchr(s1, *s2, l1)) != NULL) { |
| 523 | init++; /* 1st char is already checked */ |
| 524 | if (memcmp(init, s2+1, l2) == 0) |
| 525 | return init-1; |
| 526 | else { /* correct `l1' and `s1' to try again */ |
| 527 | l1 -= init-s1; |
| 528 | s1 = init; |
| 529 | } |
| 530 | } |
| 531 | return NULL; /* not found */ |
| 532 | } |
| 533 | 533 | } |
| 534 | 534 | |
| 535 | 535 | |
| 536 | 536 | static void push_onecapture (MatchState *ms, int i, const char *s, |
| 537 | | const char *e) { |
| 538 | | if (i >= ms->level) { |
| 539 | | if (i == 0) /* ms->level == 0, too */ |
| 540 | | lua_pushlstring(ms->L, s, e - s); /* add whole match */ |
| 541 | | else |
| 542 | | luaL_error(ms->L, "invalid capture index"); |
| 543 | | } |
| 544 | | else { |
| 545 | | ptrdiff_t l = ms->capture[i].len; |
| 546 | | if (l == CAP_UNFINISHED) luaL_error(ms->L, "unfinished capture"); |
| 547 | | if (l == CAP_POSITION) |
| 548 | | lua_pushinteger(ms->L, ms->capture[i].init - ms->src_init + 1); |
| 549 | | else |
| 550 | | lua_pushlstring(ms->L, ms->capture[i].init, l); |
| 551 | | } |
| 537 | const char *e) { |
| 538 | if (i >= ms->level) { |
| 539 | if (i == 0) /* ms->level == 0, too */ |
| 540 | lua_pushlstring(ms->L, s, e - s); /* add whole match */ |
| 541 | else |
| 542 | luaL_error(ms->L, "invalid capture index"); |
| 543 | } |
| 544 | else { |
| 545 | ptrdiff_t l = ms->capture[i].len; |
| 546 | if (l == CAP_UNFINISHED) luaL_error(ms->L, "unfinished capture"); |
| 547 | if (l == CAP_POSITION) |
| 548 | lua_pushinteger(ms->L, ms->capture[i].init - ms->src_init + 1); |
| 549 | else |
| 550 | lua_pushlstring(ms->L, ms->capture[i].init, l); |
| 551 | } |
| 552 | 552 | } |
| 553 | 553 | |
| 554 | 554 | |
| 555 | 555 | static int push_captures (MatchState *ms, const char *s, const char *e) { |
| 556 | | int i; |
| 557 | | int nlevels = (ms->level == 0 && s) ? 1 : ms->level; |
| 558 | | luaL_checkstack(ms->L, nlevels, "too many captures"); |
| 559 | | for (i = 0; i < nlevels; i++) |
| 560 | | push_onecapture(ms, i, s, e); |
| 561 | | return nlevels; /* number of strings pushed */ |
| 556 | int i; |
| 557 | int nlevels = (ms->level == 0 && s) ? 1 : ms->level; |
| 558 | luaL_checkstack(ms->L, nlevels, "too many captures"); |
| 559 | for (i = 0; i < nlevels; i++) |
| 560 | push_onecapture(ms, i, s, e); |
| 561 | return nlevels; /* number of strings pushed */ |
| 562 | 562 | } |
| 563 | 563 | |
| 564 | 564 | |
| 565 | 565 | /* check whether pattern has no special characters */ |
| 566 | 566 | static int nospecials (const char *p, size_t l) { |
| 567 | | size_t upto = 0; |
| 568 | | do { |
| 569 | | if (strpbrk(p + upto, SPECIALS)) |
| 570 | | return 0; /* pattern has a special character */ |
| 571 | | upto += strlen(p + upto) + 1; /* may have more after \0 */ |
| 572 | | } while (upto <= l); |
| 573 | | return 1; /* no special chars found */ |
| 567 | size_t upto = 0; |
| 568 | do { |
| 569 | if (strpbrk(p + upto, SPECIALS)) |
| 570 | return 0; /* pattern has a special character */ |
| 571 | upto += strlen(p + upto) + 1; /* may have more after \0 */ |
| 572 | } while (upto <= l); |
| 573 | return 1; /* no special chars found */ |
| 574 | 574 | } |
| 575 | 575 | |
| 576 | 576 | |
| 577 | 577 | static int str_find_aux (lua_State *L, int find) { |
| 578 | | size_t ls, lp; |
| 579 | | const char *s = luaL_checklstring(L, 1, &ls); |
| 580 | | const char *p = luaL_checklstring(L, 2, &lp); |
| 581 | | size_t init = posrelat(luaL_optinteger(L, 3, 1), ls); |
| 582 | | if (init < 1) init = 1; |
| 583 | | else if (init > ls + 1) { /* start after string's end? */ |
| 584 | | lua_pushnil(L); /* cannot find anything */ |
| 585 | | return 1; |
| 586 | | } |
| 587 | | /* explicit request or no special characters? */ |
| 588 | | if (find && (lua_toboolean(L, 4) || nospecials(p, lp))) { |
| 589 | | /* do a plain search */ |
| 590 | | const char *s2 = lmemfind(s + init - 1, ls - init + 1, p, lp); |
| 591 | | if (s2) { |
| 592 | | lua_pushinteger(L, s2 - s + 1); |
| 593 | | lua_pushinteger(L, s2 - s + lp); |
| 594 | | return 2; |
| 595 | | } |
| 596 | | } |
| 597 | | else { |
| 598 | | MatchState ms; |
| 599 | | const char *s1 = s + init - 1; |
| 600 | | int anchor = (*p == '^'); |
| 601 | | if (anchor) { |
| 602 | | p++; lp--; /* skip anchor character */ |
| 603 | | } |
| 604 | | ms.L = L; |
| 605 | | ms.matchdepth = MAXCCALLS; |
| 606 | | ms.src_init = s; |
| 607 | | ms.src_end = s + ls; |
| 608 | | ms.p_end = p + lp; |
| 609 | | do { |
| 610 | | const char *res; |
| 611 | | ms.level = 0; |
| 612 | | lua_assert(ms.matchdepth == MAXCCALLS); |
| 613 | | if ((res=match(&ms, s1, p)) != NULL) { |
| 614 | | if (find) { |
| 615 | | lua_pushinteger(L, s1 - s + 1); /* start */ |
| 616 | | lua_pushinteger(L, res - s); /* end */ |
| 617 | | return push_captures(&ms, NULL, 0) + 2; |
| 618 | | } |
| 619 | | else |
| 620 | | return push_captures(&ms, s1, res); |
| 621 | | } |
| 622 | | } while (s1++ < ms.src_end && !anchor); |
| 623 | | } |
| 624 | | lua_pushnil(L); /* not found */ |
| 625 | | return 1; |
| 578 | size_t ls, lp; |
| 579 | const char *s = luaL_checklstring(L, 1, &ls); |
| 580 | const char *p = luaL_checklstring(L, 2, &lp); |
| 581 | size_t init = posrelat(luaL_optinteger(L, 3, 1), ls); |
| 582 | if (init < 1) init = 1; |
| 583 | else if (init > ls + 1) { /* start after string's end? */ |
| 584 | lua_pushnil(L); /* cannot find anything */ |
| 585 | return 1; |
| 586 | } |
| 587 | /* explicit request or no special characters? */ |
| 588 | if (find && (lua_toboolean(L, 4) || nospecials(p, lp))) { |
| 589 | /* do a plain search */ |
| 590 | const char *s2 = lmemfind(s + init - 1, ls - init + 1, p, lp); |
| 591 | if (s2) { |
| 592 | lua_pushinteger(L, s2 - s + 1); |
| 593 | lua_pushinteger(L, s2 - s + lp); |
| 594 | return 2; |
| 595 | } |
| 596 | } |
| 597 | else { |
| 598 | MatchState ms; |
| 599 | const char *s1 = s + init - 1; |
| 600 | int anchor = (*p == '^'); |
| 601 | if (anchor) { |
| 602 | p++; lp--; /* skip anchor character */ |
| 603 | } |
| 604 | ms.L = L; |
| 605 | ms.matchdepth = MAXCCALLS; |
| 606 | ms.src_init = s; |
| 607 | ms.src_end = s + ls; |
| 608 | ms.p_end = p + lp; |
| 609 | do { |
| 610 | const char *res; |
| 611 | ms.level = 0; |
| 612 | lua_assert(ms.matchdepth == MAXCCALLS); |
| 613 | if ((res=match(&ms, s1, p)) != NULL) { |
| 614 | if (find) { |
| 615 | lua_pushinteger(L, s1 - s + 1); /* start */ |
| 616 | lua_pushinteger(L, res - s); /* end */ |
| 617 | return push_captures(&ms, NULL, 0) + 2; |
| 618 | } |
| 619 | else |
| 620 | return push_captures(&ms, s1, res); |
| 621 | } |
| 622 | } while (s1++ < ms.src_end && !anchor); |
| 623 | } |
| 624 | lua_pushnil(L); /* not found */ |
| 625 | return 1; |
| 626 | 626 | } |
| 627 | 627 | |
| 628 | 628 | |
| 629 | 629 | static int str_find (lua_State *L) { |
| 630 | | return str_find_aux(L, 1); |
| 630 | return str_find_aux(L, 1); |
| 631 | 631 | } |
| 632 | 632 | |
| 633 | 633 | |
| 634 | 634 | static int str_match (lua_State *L) { |
| 635 | | return str_find_aux(L, 0); |
| 635 | return str_find_aux(L, 0); |
| 636 | 636 | } |
| 637 | 637 | |
| 638 | 638 | |
| 639 | 639 | static int gmatch_aux (lua_State *L) { |
| 640 | | MatchState ms; |
| 641 | | size_t ls, lp; |
| 642 | | const char *s = lua_tolstring(L, lua_upvalueindex(1), &ls); |
| 643 | | const char *p = lua_tolstring(L, lua_upvalueindex(2), &lp); |
| 644 | | const char *src; |
| 645 | | ms.L = L; |
| 646 | | ms.matchdepth = MAXCCALLS; |
| 647 | | ms.src_init = s; |
| 648 | | ms.src_end = s+ls; |
| 649 | | ms.p_end = p + lp; |
| 650 | | for (src = s + (size_t)lua_tointeger(L, lua_upvalueindex(3)); |
| 651 | | src <= ms.src_end; |
| 652 | | src++) { |
| 653 | | const char *e; |
| 654 | | ms.level = 0; |
| 655 | | lua_assert(ms.matchdepth == MAXCCALLS); |
| 656 | | if ((e = match(&ms, src, p)) != NULL) { |
| 657 | | lua_Integer newstart = e-s; |
| 658 | | if (e == src) newstart++; /* empty match? go at least one position */ |
| 659 | | lua_pushinteger(L, newstart); |
| 660 | | lua_replace(L, lua_upvalueindex(3)); |
| 661 | | return push_captures(&ms, src, e); |
| 662 | | } |
| 663 | | } |
| 664 | | return 0; /* not found */ |
| 640 | MatchState ms; |
| 641 | size_t ls, lp; |
| 642 | const char *s = lua_tolstring(L, lua_upvalueindex(1), &ls); |
| 643 | const char *p = lua_tolstring(L, lua_upvalueindex(2), &lp); |
| 644 | const char *src; |
| 645 | ms.L = L; |
| 646 | ms.matchdepth = MAXCCALLS; |
| 647 | ms.src_init = s; |
| 648 | ms.src_end = s+ls; |
| 649 | ms.p_end = p + lp; |
| 650 | for (src = s + (size_t)lua_tointeger(L, lua_upvalueindex(3)); |
| 651 | src <= ms.src_end; |
| 652 | src++) { |
| 653 | const char *e; |
| 654 | ms.level = 0; |
| 655 | lua_assert(ms.matchdepth == MAXCCALLS); |
| 656 | if ((e = match(&ms, src, p)) != NULL) { |
| 657 | lua_Integer newstart = e-s; |
| 658 | if (e == src) newstart++; /* empty match? go at least one position */ |
| 659 | lua_pushinteger(L, newstart); |
| 660 | lua_replace(L, lua_upvalueindex(3)); |
| 661 | return push_captures(&ms, src, e); |
| 662 | } |
| 663 | } |
| 664 | return 0; /* not found */ |
| 665 | 665 | } |
| 666 | 666 | |
| 667 | 667 | |
| 668 | 668 | static int gmatch (lua_State *L) { |
| 669 | | luaL_checkstring(L, 1); |
| 670 | | luaL_checkstring(L, 2); |
| 671 | | lua_settop(L, 2); |
| 672 | | lua_pushinteger(L, 0); |
| 673 | | lua_pushcclosure(L, gmatch_aux, 3); |
| 674 | | return 1; |
| 669 | luaL_checkstring(L, 1); |
| 670 | luaL_checkstring(L, 2); |
| 671 | lua_settop(L, 2); |
| 672 | lua_pushinteger(L, 0); |
| 673 | lua_pushcclosure(L, gmatch_aux, 3); |
| 674 | return 1; |
| 675 | 675 | } |
| 676 | 676 | |
| 677 | 677 | |
| 678 | 678 | static void add_s (MatchState *ms, luaL_Buffer *b, const char *s, |
| 679 | | const char *e) { |
| 680 | | size_t l, i; |
| 681 | | const char *news = lua_tolstring(ms->L, 3, &l); |
| 682 | | for (i = 0; i < l; i++) { |
| 683 | | if (news[i] != L_ESC) |
| 684 | | luaL_addchar(b, news[i]); |
| 685 | | else { |
| 686 | | i++; /* skip ESC */ |
| 687 | | if (!isdigit(uchar(news[i]))) { |
| 688 | | if (news[i] != L_ESC) |
| 689 | | luaL_error(ms->L, "invalid use of " LUA_QL("%c") |
| 690 | | " in replacement string", L_ESC); |
| 691 | | luaL_addchar(b, news[i]); |
| 692 | | } |
| 693 | | else if (news[i] == '0') |
| 694 | | luaL_addlstring(b, s, e - s); |
| 695 | | else { |
| 696 | | push_onecapture(ms, news[i] - '1', s, e); |
| 697 | | luaL_addvalue(b); /* add capture to accumulated result */ |
| 698 | | } |
| 699 | | } |
| 700 | | } |
| 679 | const char *e) { |
| 680 | size_t l, i; |
| 681 | const char *news = lua_tolstring(ms->L, 3, &l); |
| 682 | for (i = 0; i < l; i++) { |
| 683 | if (news[i] != L_ESC) |
| 684 | luaL_addchar(b, news[i]); |
| 685 | else { |
| 686 | i++; /* skip ESC */ |
| 687 | if (!isdigit(uchar(news[i]))) { |
| 688 | if (news[i] != L_ESC) |
| 689 | luaL_error(ms->L, "invalid use of " LUA_QL("%c") |
| 690 | " in replacement string", L_ESC); |
| 691 | luaL_addchar(b, news[i]); |
| 692 | } |
| 693 | else if (news[i] == '0') |
| 694 | luaL_addlstring(b, s, e - s); |
| 695 | else { |
| 696 | push_onecapture(ms, news[i] - '1', s, e); |
| 697 | luaL_addvalue(b); /* add capture to accumulated result */ |
| 698 | } |
| 699 | } |
| 700 | } |
| 701 | 701 | } |
| 702 | 702 | |
| 703 | 703 | |
| 704 | 704 | static void add_value (MatchState *ms, luaL_Buffer *b, const char *s, |
| 705 | | const char *e, int tr) { |
| 706 | | lua_State *L = ms->L; |
| 707 | | switch (tr) { |
| 708 | | case LUA_TFUNCTION: { |
| 709 | | int n; |
| 710 | | lua_pushvalue(L, 3); |
| 711 | | n = push_captures(ms, s, e); |
| 712 | | lua_call(L, n, 1); |
| 713 | | break; |
| 714 | | } |
| 715 | | case LUA_TTABLE: { |
| 716 | | push_onecapture(ms, 0, s, e); |
| 717 | | lua_gettable(L, 3); |
| 718 | | break; |
| 719 | | } |
| 720 | | default: { /* LUA_TNUMBER or LUA_TSTRING */ |
| 721 | | add_s(ms, b, s, e); |
| 722 | | return; |
| 723 | | } |
| 724 | | } |
| 725 | | if (!lua_toboolean(L, -1)) { /* nil or false? */ |
| 726 | | lua_pop(L, 1); |
| 727 | | lua_pushlstring(L, s, e - s); /* keep original text */ |
| 728 | | } |
| 729 | | else if (!lua_isstring(L, -1)) |
| 730 | | luaL_error(L, "invalid replacement value (a %s)", luaL_typename(L, -1)); |
| 731 | | luaL_addvalue(b); /* add result to accumulator */ |
| 705 | const char *e, int tr) { |
| 706 | lua_State *L = ms->L; |
| 707 | switch (tr) { |
| 708 | case LUA_TFUNCTION: { |
| 709 | int n; |
| 710 | lua_pushvalue(L, 3); |
| 711 | n = push_captures(ms, s, e); |
| 712 | lua_call(L, n, 1); |
| 713 | break; |
| 714 | } |
| 715 | case LUA_TTABLE: { |
| 716 | push_onecapture(ms, 0, s, e); |
| 717 | lua_gettable(L, 3); |
| 718 | break; |
| 719 | } |
| 720 | default: { /* LUA_TNUMBER or LUA_TSTRING */ |
| 721 | add_s(ms, b, s, e); |
| 722 | return; |
| 723 | } |
| 724 | } |
| 725 | if (!lua_toboolean(L, -1)) { /* nil or false? */ |
| 726 | lua_pop(L, 1); |
| 727 | lua_pushlstring(L, s, e - s); /* keep original text */ |
| 728 | } |
| 729 | else if (!lua_isstring(L, -1)) |
| 730 | luaL_error(L, "invalid replacement value (a %s)", luaL_typename(L, -1)); |
| 731 | luaL_addvalue(b); /* add result to accumulator */ |
| 732 | 732 | } |
| 733 | 733 | |
| 734 | 734 | |
| 735 | 735 | static int str_gsub (lua_State *L) { |
| 736 | | size_t srcl, lp; |
| 737 | | const char *src = luaL_checklstring(L, 1, &srcl); |
| 738 | | const char *p = luaL_checklstring(L, 2, &lp); |
| 739 | | int tr = lua_type(L, 3); |
| 740 | | size_t max_s = luaL_optinteger(L, 4, srcl+1); |
| 741 | | int anchor = (*p == '^'); |
| 742 | | size_t n = 0; |
| 743 | | MatchState ms; |
| 744 | | luaL_Buffer b; |
| 745 | | luaL_argcheck(L, tr == LUA_TNUMBER || tr == LUA_TSTRING || |
| 746 | | tr == LUA_TFUNCTION || tr == LUA_TTABLE, 3, |
| 747 | | "string/function/table expected"); |
| 748 | | luaL_buffinit(L, &b); |
| 749 | | if (anchor) { |
| 750 | | p++; lp--; /* skip anchor character */ |
| 751 | | } |
| 752 | | ms.L = L; |
| 753 | | ms.matchdepth = MAXCCALLS; |
| 754 | | ms.src_init = src; |
| 755 | | ms.src_end = src+srcl; |
| 756 | | ms.p_end = p + lp; |
| 757 | | while (n < max_s) { |
| 758 | | const char *e; |
| 759 | | ms.level = 0; |
| 760 | | lua_assert(ms.matchdepth == MAXCCALLS); |
| 761 | | e = match(&ms, src, p); |
| 762 | | if (e) { |
| 763 | | n++; |
| 764 | | add_value(&ms, &b, src, e, tr); |
| 765 | | } |
| 766 | | if (e && e>src) /* non empty match? */ |
| 767 | | src = e; /* skip it */ |
| 768 | | else if (src < ms.src_end) |
| 769 | | luaL_addchar(&b, *src++); |
| 770 | | else break; |
| 771 | | if (anchor) break; |
| 772 | | } |
| 773 | | luaL_addlstring(&b, src, ms.src_end-src); |
| 774 | | luaL_pushresult(&b); |
| 775 | | lua_pushinteger(L, n); /* number of substitutions */ |
| 776 | | return 2; |
| 736 | size_t srcl, lp; |
| 737 | const char *src = luaL_checklstring(L, 1, &srcl); |
| 738 | const char *p = luaL_checklstring(L, 2, &lp); |
| 739 | int tr = lua_type(L, 3); |
| 740 | size_t max_s = luaL_optinteger(L, 4, srcl+1); |
| 741 | int anchor = (*p == '^'); |
| 742 | size_t n = 0; |
| 743 | MatchState ms; |
| 744 | luaL_Buffer b; |
| 745 | luaL_argcheck(L, tr == LUA_TNUMBER || tr == LUA_TSTRING || |
| 746 | tr == LUA_TFUNCTION || tr == LUA_TTABLE, 3, |
| 747 | "string/function/table expected"); |
| 748 | luaL_buffinit(L, &b); |
| 749 | if (anchor) { |
| 750 | p++; lp--; /* skip anchor character */ |
| 751 | } |
| 752 | ms.L = L; |
| 753 | ms.matchdepth = MAXCCALLS; |
| 754 | ms.src_init = src; |
| 755 | ms.src_end = src+srcl; |
| 756 | ms.p_end = p + lp; |
| 757 | while (n < max_s) { |
| 758 | const char *e; |
| 759 | ms.level = 0; |
| 760 | lua_assert(ms.matchdepth == MAXCCALLS); |
| 761 | e = match(&ms, src, p); |
| 762 | if (e) { |
| 763 | n++; |
| 764 | add_value(&ms, &b, src, e, tr); |
| 765 | } |
| 766 | if (e && e>src) /* non empty match? */ |
| 767 | src = e; /* skip it */ |
| 768 | else if (src < ms.src_end) |
| 769 | luaL_addchar(&b, *src++); |
| 770 | else break; |
| 771 | if (anchor) break; |
| 772 | } |
| 773 | luaL_addlstring(&b, src, ms.src_end-src); |
| 774 | luaL_pushresult(&b); |
| 775 | lua_pushinteger(L, n); /* number of substitutions */ |
| 776 | return 2; |
| 777 | 777 | } |
| 778 | 778 | |
| 779 | 779 | /* }====================================================== */ |
| r30857 | r30858 | |
| 791 | 791 | ** 'string.format'; LUA_INTFRM_T is the integer type corresponding to |
| 792 | 792 | ** the previous length |
| 793 | 793 | */ |
| 794 | | #if !defined(LUA_INTFRMLEN) /* { */ |
| 794 | #if !defined(LUA_INTFRMLEN) /* { */ |
| 795 | 795 | #if defined(LUA_USE_LONGLONG) |
| 796 | 796 | |
| 797 | | #define LUA_INTFRMLEN "ll" |
| 798 | | #define LUA_INTFRM_T long long |
| 797 | #define LUA_INTFRMLEN "ll" |
| 798 | #define LUA_INTFRM_T long long |
| 799 | 799 | |
| 800 | 800 | #else |
| 801 | 801 | |
| 802 | | #define LUA_INTFRMLEN "l" |
| 803 | | #define LUA_INTFRM_T long |
| 802 | #define LUA_INTFRMLEN "l" |
| 803 | #define LUA_INTFRM_T long |
| 804 | 804 | |
| 805 | 805 | #endif |
| 806 | | #endif /* } */ |
| 806 | #endif /* } */ |
| 807 | 807 | |
| 808 | 808 | |
| 809 | 809 | /* |
| r30857 | r30858 | |
| 813 | 813 | */ |
| 814 | 814 | #if !defined(LUA_FLTFRMLEN) |
| 815 | 815 | |
| 816 | | #define LUA_FLTFRMLEN "" |
| 817 | | #define LUA_FLTFRM_T double |
| 816 | #define LUA_FLTFRMLEN "" |
| 817 | #define LUA_FLTFRM_T double |
| 818 | 818 | |
| 819 | 819 | #endif |
| 820 | 820 | |
| 821 | 821 | |
| 822 | 822 | /* maximum size of each formatted item (> len(format('%99.99f', -1e308))) */ |
| 823 | | #define MAX_ITEM 512 |
| 823 | #define MAX_ITEM 512 |
| 824 | 824 | /* valid flags in a format specification */ |
| 825 | | #define FLAGS "-+ #0" |
| 825 | #define FLAGS "-+ #0" |
| 826 | 826 | /* |
| 827 | 827 | ** maximum size of each format specification (such as '%-099.99d') |
| 828 | 828 | ** (+10 accounts for %99.99x plus margin of error) |
| 829 | 829 | */ |
| 830 | | #define MAX_FORMAT (sizeof(FLAGS) + sizeof(LUA_INTFRMLEN) + 10) |
| 830 | #define MAX_FORMAT (sizeof(FLAGS) + sizeof(LUA_INTFRMLEN) + 10) |
| 831 | 831 | |
| 832 | 832 | |
| 833 | 833 | static void addquoted (lua_State *L, luaL_Buffer *b, int arg) { |
| 834 | | size_t l; |
| 835 | | const char *s = luaL_checklstring(L, arg, &l); |
| 836 | | luaL_addchar(b, '"'); |
| 837 | | while (l--) { |
| 838 | | if (*s == '"' || *s == '\\' || *s == '\n') { |
| 839 | | luaL_addchar(b, '\\'); |
| 840 | | luaL_addchar(b, *s); |
| 841 | | } |
| 842 | | else if (*s == '\0' || iscntrl(uchar(*s))) { |
| 843 | | char buff[10]; |
| 844 | | if (!isdigit(uchar(*(s+1)))) |
| 845 | | sprintf(buff, "\\%d", (int)uchar(*s)); |
| 846 | | else |
| 847 | | sprintf(buff, "\\%03d", (int)uchar(*s)); |
| 848 | | luaL_addstring(b, buff); |
| 849 | | } |
| 850 | | else |
| 851 | | luaL_addchar(b, *s); |
| 852 | | s++; |
| 853 | | } |
| 854 | | luaL_addchar(b, '"'); |
| 834 | size_t l; |
| 835 | const char *s = luaL_checklstring(L, arg, &l); |
| 836 | luaL_addchar(b, '"'); |
| 837 | while (l--) { |
| 838 | if (*s == '"' || *s == '\\' || *s == '\n') { |
| 839 | luaL_addchar(b, '\\'); |
| 840 | luaL_addchar(b, *s); |
| 841 | } |
| 842 | else if (*s == '\0' || iscntrl(uchar(*s))) { |
| 843 | char buff[10]; |
| 844 | if (!isdigit(uchar(*(s+1)))) |
| 845 | sprintf(buff, "\\%d", (int)uchar(*s)); |
| 846 | else |
| 847 | sprintf(buff, "\\%03d", (int)uchar(*s)); |
| 848 | luaL_addstring(b, buff); |
| 849 | } |
| 850 | else |
| 851 | luaL_addchar(b, *s); |
| 852 | s++; |
| 853 | } |
| 854 | luaL_addchar(b, '"'); |
| 855 | 855 | } |
| 856 | 856 | |
| 857 | 857 | static const char *scanformat (lua_State *L, const char *strfrmt, char *form) { |
| 858 | | const char *p = strfrmt; |
| 859 | | while (*p != '\0' && strchr(FLAGS, *p) != NULL) p++; /* skip flags */ |
| 860 | | if ((size_t)(p - strfrmt) >= sizeof(FLAGS)/sizeof(char)) |
| 861 | | luaL_error(L, "invalid format (repeated flags)"); |
| 862 | | if (isdigit(uchar(*p))) p++; /* skip width */ |
| 863 | | if (isdigit(uchar(*p))) p++; /* (2 digits at most) */ |
| 864 | | if (*p == '.') { |
| 865 | | p++; |
| 866 | | if (isdigit(uchar(*p))) p++; /* skip precision */ |
| 867 | | if (isdigit(uchar(*p))) p++; /* (2 digits at most) */ |
| 868 | | } |
| 869 | | if (isdigit(uchar(*p))) |
| 870 | | luaL_error(L, "invalid format (width or precision too long)"); |
| 871 | | *(form++) = '%'; |
| 872 | | memcpy(form, strfrmt, (p - strfrmt + 1) * sizeof(char)); |
| 873 | | form += p - strfrmt + 1; |
| 874 | | *form = '\0'; |
| 875 | | return p; |
| 858 | const char *p = strfrmt; |
| 859 | while (*p != '\0' && strchr(FLAGS, *p) != NULL) p++; /* skip flags */ |
| 860 | if ((size_t)(p - strfrmt) >= sizeof(FLAGS)/sizeof(char)) |
| 861 | luaL_error(L, "invalid format (repeated flags)"); |
| 862 | if (isdigit(uchar(*p))) p++; /* skip width */ |
| 863 | if (isdigit(uchar(*p))) p++; /* (2 digits at most) */ |
| 864 | if (*p == '.') { |
| 865 | p++; |
| 866 | if (isdigit(uchar(*p))) p++; /* skip precision */ |
| 867 | if (isdigit(uchar(*p))) p++; /* (2 digits at most) */ |
| 868 | } |
| 869 | if (isdigit(uchar(*p))) |
| 870 | luaL_error(L, "invalid format (width or precision too long)"); |
| 871 | *(form++) = '%'; |
| 872 | memcpy(form, strfrmt, (p - strfrmt + 1) * sizeof(char)); |
| 873 | form += p - strfrmt + 1; |
| 874 | *form = '\0'; |
| 875 | return p; |
| 876 | 876 | } |
| 877 | 877 | |
| 878 | 878 | |
| r30857 | r30858 | |
| 880 | 880 | ** add length modifier into formats |
| 881 | 881 | */ |
| 882 | 882 | static void addlenmod (char *form, const char *lenmod) { |
| 883 | | size_t l = strlen(form); |
| 884 | | size_t lm = strlen(lenmod); |
| 885 | | char spec = form[l - 1]; |
| 886 | | strcpy(form + l - 1, lenmod); |
| 887 | | form[l + lm - 1] = spec; |
| 888 | | form[l + lm] = '\0'; |
| 883 | size_t l = strlen(form); |
| 884 | size_t lm = strlen(lenmod); |
| 885 | char spec = form[l - 1]; |
| 886 | strcpy(form + l - 1, lenmod); |
| 887 | form[l + lm - 1] = spec; |
| 888 | form[l + lm] = '\0'; |
| 889 | 889 | } |
| 890 | 890 | |
| 891 | 891 | |
| 892 | 892 | static int str_format (lua_State *L) { |
| 893 | | int top = lua_gettop(L); |
| 894 | | int arg = 1; |
| 895 | | size_t sfl; |
| 896 | | const char *strfrmt = luaL_checklstring(L, arg, &sfl); |
| 897 | | const char *strfrmt_end = strfrmt+sfl; |
| 898 | | luaL_Buffer b; |
| 899 | | luaL_buffinit(L, &b); |
| 900 | | while (strfrmt < strfrmt_end) { |
| 901 | | if (*strfrmt != L_ESC) |
| 902 | | luaL_addchar(&b, *strfrmt++); |
| 903 | | else if (*++strfrmt == L_ESC) |
| 904 | | luaL_addchar(&b, *strfrmt++); /* %% */ |
| 905 | | else { /* format item */ |
| 906 | | char form[MAX_FORMAT]; /* to store the format (`%...') */ |
| 907 | | char *buff = luaL_prepbuffsize(&b, MAX_ITEM); /* to put formatted item */ |
| 908 | | int nb = 0; /* number of bytes in added item */ |
| 909 | | if (++arg > top) |
| 910 | | luaL_argerror(L, arg, "no value"); |
| 911 | | strfrmt = scanformat(L, strfrmt, form); |
| 912 | | switch (*strfrmt++) { |
| 913 | | case 'c': { |
| 914 | | nb = sprintf(buff, form, luaL_checkint(L, arg)); |
| 915 | | break; |
| 916 | | } |
| 917 | | case 'd': case 'i': { |
| 918 | | lua_Number n = luaL_checknumber(L, arg); |
| 919 | | LUA_INTFRM_T ni = (LUA_INTFRM_T)n; |
| 920 | | lua_Number diff = n - (lua_Number)ni; |
| 921 | | luaL_argcheck(L, -1 < diff && diff < 1, arg, |
| 922 | | "not a number in proper range"); |
| 923 | | addlenmod(form, LUA_INTFRMLEN); |
| 924 | | nb = sprintf(buff, form, ni); |
| 925 | | break; |
| 926 | | } |
| 927 | | case 'o': case 'u': case 'x': case 'X': { |
| 928 | | lua_Number n = luaL_checknumber(L, arg); |
| 929 | | unsigned LUA_INTFRM_T ni = (unsigned LUA_INTFRM_T)n; |
| 930 | | lua_Number diff = n - (lua_Number)ni; |
| 931 | | luaL_argcheck(L, -1 < diff && diff < 1, arg, |
| 932 | | "not a non-negative number in proper range"); |
| 933 | | addlenmod(form, LUA_INTFRMLEN); |
| 934 | | nb = sprintf(buff, form, ni); |
| 935 | | break; |
| 936 | | } |
| 937 | | case 'e': case 'E': case 'f': |
| 893 | int top = lua_gettop(L); |
| 894 | int arg = 1; |
| 895 | size_t sfl; |
| 896 | const char *strfrmt = luaL_checklstring(L, arg, &sfl); |
| 897 | const char *strfrmt_end = strfrmt+sfl; |
| 898 | luaL_Buffer b; |
| 899 | luaL_buffinit(L, &b); |
| 900 | while (strfrmt < strfrmt_end) { |
| 901 | if (*strfrmt != L_ESC) |
| 902 | luaL_addchar(&b, *strfrmt++); |
| 903 | else if (*++strfrmt == L_ESC) |
| 904 | luaL_addchar(&b, *strfrmt++); /* %% */ |
| 905 | else { /* format item */ |
| 906 | char form[MAX_FORMAT]; /* to store the format (`%...') */ |
| 907 | char *buff = luaL_prepbuffsize(&b, MAX_ITEM); /* to put formatted item */ |
| 908 | int nb = 0; /* number of bytes in added item */ |
| 909 | if (++arg > top) |
| 910 | luaL_argerror(L, arg, "no value"); |
| 911 | strfrmt = scanformat(L, strfrmt, form); |
| 912 | switch (*strfrmt++) { |
| 913 | case 'c': { |
| 914 | nb = sprintf(buff, form, luaL_checkint(L, arg)); |
| 915 | break; |
| 916 | } |
| 917 | case 'd': case 'i': { |
| 918 | lua_Number n = luaL_checknumber(L, arg); |
| 919 | LUA_INTFRM_T ni = (LUA_INTFRM_T)n; |
| 920 | lua_Number diff = n - (lua_Number)ni; |
| 921 | luaL_argcheck(L, -1 < diff && diff < 1, arg, |
| 922 | "not a number in proper range"); |
| 923 | addlenmod(form, LUA_INTFRMLEN); |
| 924 | nb = sprintf(buff, form, ni); |
| 925 | break; |
| 926 | } |
| 927 | case 'o': case 'u': case 'x': case 'X': { |
| 928 | lua_Number n = luaL_checknumber(L, arg); |
| 929 | unsigned LUA_INTFRM_T ni = (unsigned LUA_INTFRM_T)n; |
| 930 | lua_Number diff = n - (lua_Number)ni; |
| 931 | luaL_argcheck(L, -1 < diff && diff < 1, arg, |
| 932 | "not a non-negative number in proper range"); |
| 933 | addlenmod(form, LUA_INTFRMLEN); |
| 934 | nb = sprintf(buff, form, ni); |
| 935 | break; |
| 936 | } |
| 937 | case 'e': case 'E': case 'f': |
| 938 | 938 | #if defined(LUA_USE_AFORMAT) |
| 939 | | case 'a': case 'A': |
| 939 | case 'a': case 'A': |
| 940 | 940 | #endif |
| 941 | | case 'g': case 'G': { |
| 942 | | addlenmod(form, LUA_FLTFRMLEN); |
| 943 | | nb = sprintf(buff, form, (LUA_FLTFRM_T)luaL_checknumber(L, arg)); |
| 944 | | break; |
| 945 | | } |
| 946 | | case 'q': { |
| 947 | | addquoted(L, &b, arg); |
| 948 | | break; |
| 949 | | } |
| 950 | | case 's': { |
| 951 | | size_t l; |
| 952 | | const char *s = luaL_tolstring(L, arg, &l); |
| 953 | | if (!strchr(form, '.') && l >= 100) { |
| 954 | | /* no precision and string is too long to be formatted; |
| 955 | | keep original string */ |
| 956 | | luaL_addvalue(&b); |
| 957 | | break; |
| 958 | | } |
| 959 | | else { |
| 960 | | nb = sprintf(buff, form, s); |
| 961 | | lua_pop(L, 1); /* remove result from 'luaL_tolstring' */ |
| 962 | | break; |
| 963 | | } |
| 964 | | } |
| 965 | | default: { /* also treat cases `pnLlh' */ |
| 966 | | return luaL_error(L, "invalid option " LUA_QL("%%%c") " to " |
| 967 | | LUA_QL("format"), *(strfrmt - 1)); |
| 968 | | } |
| 969 | | } |
| 970 | | luaL_addsize(&b, nb); |
| 971 | | } |
| 972 | | } |
| 973 | | luaL_pushresult(&b); |
| 974 | | return 1; |
| 941 | case 'g': case 'G': { |
| 942 | addlenmod(form, LUA_FLTFRMLEN); |
| 943 | nb = sprintf(buff, form, (LUA_FLTFRM_T)luaL_checknumber(L, arg)); |
| 944 | break; |
| 945 | } |
| 946 | case 'q': { |
| 947 | addquoted(L, &b, arg); |
| 948 | break; |
| 949 | } |
| 950 | case 's': { |
| 951 | size_t l; |
| 952 | const char *s = luaL_tolstring(L, arg, &l); |
| 953 | if (!strchr(form, '.') && l >= 100) { |
| 954 | /* no precision and string is too long to be formatted; |
| 955 | keep original string */ |
| 956 | luaL_addvalue(&b); |
| 957 | break; |
| 958 | } |
| 959 | else { |
| 960 | nb = sprintf(buff, form, s); |
| 961 | lua_pop(L, 1); /* remove result from 'luaL_tolstring' */ |
| 962 | break; |
| 963 | } |
| 964 | } |
| 965 | default: { /* also treat cases `pnLlh' */ |
| 966 | return luaL_error(L, "invalid option " LUA_QL("%%%c") " to " |
| 967 | LUA_QL("format"), *(strfrmt - 1)); |
| 968 | } |
| 969 | } |
| 970 | luaL_addsize(&b, nb); |
| 971 | } |
| 972 | } |
| 973 | luaL_pushresult(&b); |
| 974 | return 1; |
| 975 | 975 | } |
| 976 | 976 | |
| 977 | 977 | /* }====================================================== */ |
| 978 | 978 | |
| 979 | 979 | |
| 980 | 980 | static const luaL_Reg strlib[] = { |
| 981 | | {"byte", str_byte}, |
| 982 | | {"char", str_char}, |
| 983 | | {"dump", str_dump}, |
| 984 | | {"find", str_find}, |
| 985 | | {"format", str_format}, |
| 986 | | {"gmatch", gmatch}, |
| 987 | | {"gsub", str_gsub}, |
| 988 | | {"len", str_len}, |
| 989 | | {"lower", str_lower}, |
| 990 | | {"match", str_match}, |
| 991 | | {"rep", str_rep}, |
| 992 | | {"reverse", str_reverse}, |
| 993 | | {"sub", str_sub}, |
| 994 | | {"upper", str_upper}, |
| 995 | | {NULL, NULL} |
| 981 | {"byte", str_byte}, |
| 982 | {"char", str_char}, |
| 983 | {"dump", str_dump}, |
| 984 | {"find", str_find}, |
| 985 | {"format", str_format}, |
| 986 | {"gmatch", gmatch}, |
| 987 | {"gsub", str_gsub}, |
| 988 | {"len", str_len}, |
| 989 | {"lower", str_lower}, |
| 990 | {"match", str_match}, |
| 991 | {"rep", str_rep}, |
| 992 | {"reverse", str_reverse}, |
| 993 | {"sub", str_sub}, |
| 994 | {"upper", str_upper}, |
| 995 | {NULL, NULL} |
| 996 | 996 | }; |
| 997 | 997 | |
| 998 | 998 | |
| 999 | 999 | static void createmetatable (lua_State *L) { |
| 1000 | | lua_createtable(L, 0, 1); /* table to be metatable for strings */ |
| 1001 | | lua_pushliteral(L, ""); /* dummy string */ |
| 1002 | | lua_pushvalue(L, -2); /* copy table */ |
| 1003 | | lua_setmetatable(L, -2); /* set table as metatable for strings */ |
| 1004 | | lua_pop(L, 1); /* pop dummy string */ |
| 1005 | | lua_pushvalue(L, -2); /* get string library */ |
| 1006 | | lua_setfield(L, -2, "__index"); /* metatable.__index = string */ |
| 1007 | | lua_pop(L, 1); /* pop metatable */ |
| 1000 | lua_createtable(L, 0, 1); /* table to be metatable for strings */ |
| 1001 | lua_pushliteral(L, ""); /* dummy string */ |
| 1002 | lua_pushvalue(L, -2); /* copy table */ |
| 1003 | lua_setmetatable(L, -2); /* set table as metatable for strings */ |
| 1004 | lua_pop(L, 1); /* pop dummy string */ |
| 1005 | lua_pushvalue(L, -2); /* get string library */ |
| 1006 | lua_setfield(L, -2, "__index"); /* metatable.__index = string */ |
| 1007 | lua_pop(L, 1); /* pop metatable */ |
| 1008 | 1008 | } |
| 1009 | 1009 | |
| 1010 | 1010 | |
| r30857 | r30858 | |
| 1012 | 1012 | ** Open string library |
| 1013 | 1013 | */ |
| 1014 | 1014 | LUAMOD_API int luaopen_string (lua_State *L) { |
| 1015 | | luaL_newlib(L, strlib); |
| 1016 | | createmetatable(L); |
| 1017 | | return 1; |
| 1015 | luaL_newlib(L, strlib); |
| 1016 | createmetatable(L); |
| 1017 | return 1; |
| 1018 | 1018 | } |
| 1019 | |
trunk/src/lib/lua/ldo.c
| r30857 | r30858 | |
| 1 | 1 | /* |
| 2 | | ** $Id: ldo.c,v 2.108 2012/10/01 14:05:04 roberto Exp $ |
| 2 | ** $Id: ldo.c,v 2.108.1.3 2013/11/08 18:22:50 roberto Exp $ |
| 3 | 3 | ** Stack and Call structure of Lua |
| 4 | 4 | ** See Copyright Notice in lua.h |
| 5 | 5 | */ |
| r30857 | r30858 | |
| 50 | 50 | |
| 51 | 51 | #if defined(__cplusplus) && !defined(LUA_USE_LONGJMP) |
| 52 | 52 | /* C++ exceptions */ |
| 53 | | #define LUAI_THROW(L,c) throw(c) |
| 53 | #define LUAI_THROW(L,c) throw(c) |
| 54 | 54 | #define LUAI_TRY(L,c,a) \ |
| 55 | 55 | try { a } catch(...) { if ((c)->status == 0) (c)->status = -1; } |
| 56 | | #define luai_jmpbuf int /* dummy variable */ |
| 56 | #define luai_jmpbuf int /* dummy variable */ |
| 57 | 57 | |
| 58 | 58 | #elif defined(LUA_USE_ULONGJMP) |
| 59 | 59 | /* in Unix, try _longjmp/_setjmp (more efficient) */ |
| 60 | | #define LUAI_THROW(L,c) _longjmp((c)->b, 1) |
| 61 | | #define LUAI_TRY(L,c,a) if (_setjmp((c)->b) == 0) { a } |
| 62 | | #define luai_jmpbuf jmp_buf |
| 60 | #define LUAI_THROW(L,c) _longjmp((c)->b, 1) |
| 61 | #define LUAI_TRY(L,c,a) if (_setjmp((c)->b) == 0) { a } |
| 62 | #define luai_jmpbuf jmp_buf |
| 63 | 63 | |
| 64 | 64 | #else |
| 65 | 65 | /* default handling with long jumps */ |
| 66 | | #define LUAI_THROW(L,c) longjmp((c)->b, 1) |
| 67 | | #define LUAI_TRY(L,c,a) if (setjmp((c)->b) == 0) { a } |
| 68 | | #define luai_jmpbuf jmp_buf |
| 66 | #define LUAI_THROW(L,c) longjmp((c)->b, 1) |
| 67 | #define LUAI_TRY(L,c,a) if (setjmp((c)->b) == 0) { a } |
| 68 | #define luai_jmpbuf jmp_buf |
| 69 | 69 | |
| 70 | 70 | #endif |
| 71 | 71 | |
| r30857 | r30858 | |
| 75 | 75 | |
| 76 | 76 | /* chain list of long jump buffers */ |
| 77 | 77 | struct lua_longjmp { |
| 78 | | struct lua_longjmp *previous; |
| 79 | | luai_jmpbuf b; |
| 80 | | volatile int status; /* error code */ |
| 78 | struct lua_longjmp *previous; |
| 79 | luai_jmpbuf b; |
| 80 | volatile int status; /* error code */ |
| 81 | 81 | }; |
| 82 | 82 | |
| 83 | 83 | |
| 84 | 84 | static void seterrorobj (lua_State *L, int errcode, StkId oldtop) { |
| 85 | | switch (errcode) { |
| 86 | | case LUA_ERRMEM: { /* memory error? */ |
| 87 | | setsvalue2s(L, oldtop, G(L)->memerrmsg); /* reuse preregistered msg. */ |
| 88 | | break; |
| 89 | | } |
| 90 | | case LUA_ERRERR: { |
| 91 | | setsvalue2s(L, oldtop, luaS_newliteral(L, "error in error handling")); |
| 92 | | break; |
| 93 | | } |
| 94 | | default: { |
| 95 | | setobjs2s(L, oldtop, L->top - 1); /* error message on current top */ |
| 96 | | break; |
| 97 | | } |
| 98 | | } |
| 99 | | L->top = oldtop + 1; |
| 85 | switch (errcode) { |
| 86 | case LUA_ERRMEM: { /* memory error? */ |
| 87 | setsvalue2s(L, oldtop, G(L)->memerrmsg); /* reuse preregistered msg. */ |
| 88 | break; |
| 89 | } |
| 90 | case LUA_ERRERR: { |
| 91 | setsvalue2s(L, oldtop, luaS_newliteral(L, "error in error handling")); |
| 92 | break; |
| 93 | } |
| 94 | default: { |
| 95 | setobjs2s(L, oldtop, L->top - 1); /* error message on current top */ |
| 96 | break; |
| 97 | } |
| 98 | } |
| 99 | L->top = oldtop + 1; |
| 100 | 100 | } |
| 101 | 101 | |
| 102 | 102 | |
| 103 | 103 | l_noret luaD_throw (lua_State *L, int errcode) { |
| 104 | | if (L->errorJmp) { /* thread has an error handler? */ |
| 105 | | L->errorJmp->status = errcode; /* set status */ |
| 106 | | LUAI_THROW(L, L->errorJmp); /* jump to it */ |
| 107 | | } |
| 108 | | else { /* thread has no error handler */ |
| 109 | | L->status = cast_byte(errcode); /* mark it as dead */ |
| 110 | | if (G(L)->mainthread->errorJmp) { /* main thread has a handler? */ |
| 111 | | setobjs2s(L, G(L)->mainthread->top++, L->top - 1); /* copy error obj. */ |
| 112 | | luaD_throw(G(L)->mainthread, errcode); /* re-throw in main thread */ |
| 113 | | } |
| 114 | | else { /* no handler at all; abort */ |
| 115 | | if (G(L)->panic) { /* panic function? */ |
| 116 | | lua_unlock(L); |
| 117 | | G(L)->panic(L); /* call it (last chance to jump out) */ |
| 118 | | } |
| 119 | | abort(); |
| 120 | | } |
| 121 | | } |
| 104 | if (L->errorJmp) { /* thread has an error handler? */ |
| 105 | L->errorJmp->status = errcode; /* set status */ |
| 106 | LUAI_THROW(L, L->errorJmp); /* jump to it */ |
| 107 | } |
| 108 | else { /* thread has no error handler */ |
| 109 | L->status = cast_byte(errcode); /* mark it as dead */ |
| 110 | if (G(L)->mainthread->errorJmp) { /* main thread has a handler? */ |
| 111 | setobjs2s(L, G(L)->mainthread->top++, L->top - 1); /* copy error obj. */ |
| 112 | luaD_throw(G(L)->mainthread, errcode); /* re-throw in main thread */ |
| 113 | } |
| 114 | else { /* no handler at all; abort */ |
| 115 | if (G(L)->panic) { /* panic function? */ |
| 116 | lua_unlock(L); |
| 117 | G(L)->panic(L); /* call it (last chance to jump out) */ |
| 118 | } |
| 119 | abort(); |
| 120 | } |
| 121 | } |
| 122 | 122 | } |
| 123 | 123 | |
| 124 | 124 | |
| 125 | 125 | int luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud) { |
| 126 | | unsigned short oldnCcalls = L->nCcalls; |
| 127 | | struct lua_longjmp lj; |
| 128 | | lj.status = LUA_OK; |
| 129 | | lj.previous = L->errorJmp; /* chain new error handler */ |
| 130 | | L->errorJmp = &lj; |
| 131 | | LUAI_TRY(L, &lj, |
| 132 | | (*f)(L, ud); |
| 133 | | ); |
| 134 | | L->errorJmp = lj.previous; /* restore old error handler */ |
| 135 | | L->nCcalls = oldnCcalls; |
| 136 | | return lj.status; |
| 126 | unsigned short oldnCcalls = L->nCcalls; |
| 127 | struct lua_longjmp lj; |
| 128 | lj.status = LUA_OK; |
| 129 | lj.previous = L->errorJmp; /* chain new error handler */ |
| 130 | L->errorJmp = &lj; |
| 131 | LUAI_TRY(L, &lj, |
| 132 | (*f)(L, ud); |
| 133 | ); |
| 134 | L->errorJmp = lj.previous; /* restore old error handler */ |
| 135 | L->nCcalls = oldnCcalls; |
| 136 | return lj.status; |
| 137 | 137 | } |
| 138 | 138 | |
| 139 | 139 | /* }====================================================== */ |
| 140 | 140 | |
| 141 | 141 | |
| 142 | 142 | static void correctstack (lua_State *L, TValue *oldstack) { |
| 143 | | CallInfo *ci; |
| 144 | | GCObject *up; |
| 145 | | L->top = (L->top - oldstack) + L->stack; |
| 146 | | for (up = L->openupval; up != NULL; up = up->gch.next) |
| 147 | | gco2uv(up)->v = (gco2uv(up)->v - oldstack) + L->stack; |
| 148 | | for (ci = L->ci; ci != NULL; ci = ci->previous) { |
| 149 | | ci->top = (ci->top - oldstack) + L->stack; |
| 150 | | ci->func = (ci->func - oldstack) + L->stack; |
| 151 | | if (isLua(ci)) |
| 152 | | ci->u.l.base = (ci->u.l.base - oldstack) + L->stack; |
| 153 | | } |
| 143 | CallInfo *ci; |
| 144 | GCObject *up; |
| 145 | L->top = (L->top - oldstack) + L->stack; |
| 146 | for (up = L->openupval; up != NULL; up = up->gch.next) |
| 147 | gco2uv(up)->v = (gco2uv(up)->v - oldstack) + L->stack; |
| 148 | for (ci = L->ci; ci != NULL; ci = ci->previous) { |
| 149 | ci->top = (ci->top - oldstack) + L->stack; |
| 150 | ci->func = (ci->func - oldstack) + L->stack; |
| 151 | if (isLua(ci)) |
| 152 | ci->u.l.base = (ci->u.l.base - oldstack) + L->stack; |
| 153 | } |
| 154 | 154 | } |
| 155 | 155 | |
| 156 | 156 | |
| 157 | 157 | /* some space for error handling */ |
| 158 | | #define ERRORSTACKSIZE (LUAI_MAXSTACK + 200) |
| 158 | #define ERRORSTACKSIZE (LUAI_MAXSTACK + 200) |
| 159 | 159 | |
| 160 | 160 | |
| 161 | 161 | void luaD_reallocstack (lua_State *L, int newsize) { |
| 162 | | TValue *oldstack = L->stack; |
| 163 | | int lim = L->stacksize; |
| 164 | | lua_assert(newsize <= LUAI_MAXSTACK || newsize == ERRORSTACKSIZE); |
| 165 | | lua_assert(L->stack_last - L->stack == L->stacksize - EXTRA_STACK); |
| 166 | | luaM_reallocvector(L, L->stack, L->stacksize, newsize, TValue); |
| 167 | | for (; lim < newsize; lim++) |
| 168 | | setnilvalue(L->stack + lim); /* erase new segment */ |
| 169 | | L->stacksize = newsize; |
| 170 | | L->stack_last = L->stack + newsize - EXTRA_STACK; |
| 171 | | correctstack(L, oldstack); |
| 162 | TValue *oldstack = L->stack; |
| 163 | int lim = L->stacksize; |
| 164 | lua_assert(newsize <= LUAI_MAXSTACK || newsize == ERRORSTACKSIZE); |
| 165 | lua_assert(L->stack_last - L->stack == L->stacksize - EXTRA_STACK); |
| 166 | luaM_reallocvector(L, L->stack, L->stacksize, newsize, TValue); |
| 167 | for (; lim < newsize; lim++) |
| 168 | setnilvalue(L->stack + lim); /* erase new segment */ |
| 169 | L->stacksize = newsize; |
| 170 | L->stack_last = L->stack + newsize - EXTRA_STACK; |
| 171 | correctstack(L, oldstack); |
| 172 | 172 | } |
| 173 | 173 | |
| 174 | 174 | |
| 175 | 175 | void luaD_growstack (lua_State *L, int n) { |
| 176 | | int size = L->stacksize; |
| 177 | | if (size > LUAI_MAXSTACK) /* error after extra size? */ |
| 178 | | luaD_throw(L, LUA_ERRERR); |
| 179 | | else { |
| 180 | | int needed = cast_int(L->top - L->stack) + n + EXTRA_STACK; |
| 181 | | int newsize = 2 * size; |
| 182 | | if (newsize > LUAI_MAXSTACK) newsize = LUAI_MAXSTACK; |
| 183 | | if (newsize < needed) newsize = needed; |
| 184 | | if (newsize > LUAI_MAXSTACK) { /* stack overflow? */ |
| 185 | | luaD_reallocstack(L, ERRORSTACKSIZE); |
| 186 | | luaG_runerror(L, "stack overflow"); |
| 187 | | } |
| 188 | | else |
| 189 | | luaD_reallocstack(L, newsize); |
| 190 | | } |
| 176 | int size = L->stacksize; |
| 177 | if (size > LUAI_MAXSTACK) /* error after extra size? */ |
| 178 | luaD_throw(L, LUA_ERRERR); |
| 179 | else { |
| 180 | int needed = cast_int(L->top - L->stack) + n + EXTRA_STACK; |
| 181 | int newsize = 2 * size; |
| 182 | if (newsize > LUAI_MAXSTACK) newsize = LUAI_MAXSTACK; |
| 183 | if (newsize < needed) newsize = needed; |
| 184 | if (newsize > LUAI_MAXSTACK) { /* stack overflow? */ |
| 185 | luaD_reallocstack(L, ERRORSTACKSIZE); |
| 186 | luaG_runerror(L, "stack overflow"); |
| 187 | } |
| 188 | else |
| 189 | luaD_reallocstack(L, newsize); |
| 190 | } |
| 191 | 191 | } |
| 192 | 192 | |
| 193 | 193 | |
| 194 | 194 | static int stackinuse (lua_State *L) { |
| 195 | | CallInfo *ci; |
| 196 | | StkId lim = L->top; |
| 197 | | for (ci = L->ci; ci != NULL; ci = ci->previous) { |
| 198 | | lua_assert(ci->top <= L->stack_last); |
| 199 | | if (lim < ci->top) lim = ci->top; |
| 200 | | } |
| 201 | | return cast_int(lim - L->stack) + 1; /* part of stack in use */ |
| 195 | CallInfo *ci; |
| 196 | StkId lim = L->top; |
| 197 | for (ci = L->ci; ci != NULL; ci = ci->previous) { |
| 198 | lua_assert(ci->top <= L->stack_last); |
| 199 | if (lim < ci->top) lim = ci->top; |
| 200 | } |
| 201 | return cast_int(lim - L->stack) + 1; /* part of stack in use */ |
| 202 | 202 | } |
| 203 | 203 | |
| 204 | 204 | |
| 205 | 205 | void luaD_shrinkstack (lua_State *L) { |
| 206 | | int inuse = stackinuse(L); |
| 207 | | int goodsize = inuse + (inuse / 8) + 2*EXTRA_STACK; |
| 208 | | if (goodsize > LUAI_MAXSTACK) goodsize = LUAI_MAXSTACK; |
| 209 | | if (inuse > LUAI_MAXSTACK || /* handling stack overflow? */ |
| 210 | | goodsize >= L->stacksize) /* would grow instead of shrink? */ |
| 211 | | condmovestack(L); /* don't change stack (change only for debugging) */ |
| 212 | | else |
| 213 | | luaD_reallocstack(L, goodsize); /* shrink it */ |
| 206 | int inuse = stackinuse(L); |
| 207 | int goodsize = inuse + (inuse / 8) + 2*EXTRA_STACK; |
| 208 | if (goodsize > LUAI_MAXSTACK) goodsize = LUAI_MAXSTACK; |
| 209 | if (inuse > LUAI_MAXSTACK || /* handling stack overflow? */ |
| 210 | goodsize >= L->stacksize) /* would grow instead of shrink? */ |
| 211 | condmovestack(L); /* don't change stack (change only for debugging) */ |
| 212 | else |
| 213 | luaD_reallocstack(L, goodsize); /* shrink it */ |
| 214 | 214 | } |
| 215 | 215 | |
| 216 | 216 | |
| 217 | 217 | void luaD_hook (lua_State *L, int event, int line) { |
| 218 | | lua_Hook hook = L->hook; |
| 219 | | if (hook && L->allowhook) { |
| 220 | | CallInfo *ci = L->ci; |
| 221 | | ptrdiff_t top = savestack(L, L->top); |
| 222 | | ptrdiff_t ci_top = savestack(L, ci->top); |
| 223 | | lua_Debug ar; |
| 224 | | ar.event = event; |
| 225 | | ar.currentline = line; |
| 226 | | ar.i_ci = ci; |
| 227 | | luaD_checkstack(L, LUA_MINSTACK); /* ensure minimum stack size */ |
| 228 | | ci->top = L->top + LUA_MINSTACK; |
| 229 | | lua_assert(ci->top <= L->stack_last); |
| 230 | | L->allowhook = 0; /* cannot call hooks inside a hook */ |
| 231 | | ci->callstatus |= CIST_HOOKED; |
| 232 | | lua_unlock(L); |
| 233 | | (*hook)(L, &ar); |
| 234 | | lua_lock(L); |
| 235 | | lua_assert(!L->allowhook); |
| 236 | | L->allowhook = 1; |
| 237 | | ci->top = restorestack(L, ci_top); |
| 238 | | L->top = restorestack(L, top); |
| 239 | | ci->callstatus &= ~CIST_HOOKED; |
| 240 | | } |
| 218 | lua_Hook hook = L->hook; |
| 219 | if (hook && L->allowhook) { |
| 220 | CallInfo *ci = L->ci; |
| 221 | ptrdiff_t top = savestack(L, L->top); |
| 222 | ptrdiff_t ci_top = savestack(L, ci->top); |
| 223 | lua_Debug ar; |
| 224 | ar.event = event; |
| 225 | ar.currentline = line; |
| 226 | ar.i_ci = ci; |
| 227 | luaD_checkstack(L, LUA_MINSTACK); /* ensure minimum stack size */ |
| 228 | ci->top = L->top + LUA_MINSTACK; |
| 229 | lua_assert(ci->top <= L->stack_last); |
| 230 | L->allowhook = 0; /* cannot call hooks inside a hook */ |
| 231 | ci->callstatus |= CIST_HOOKED; |
| 232 | lua_unlock(L); |
| 233 | (*hook)(L, &ar); |
| 234 | lua_lock(L); |
| 235 | lua_assert(!L->allowhook); |
| 236 | L->allowhook = 1; |
| 237 | ci->top = restorestack(L, ci_top); |
| 238 | L->top = restorestack(L, top); |
| 239 | ci->callstatus &= ~CIST_HOOKED; |
| 240 | } |
| 241 | 241 | } |
| 242 | 242 | |
| 243 | 243 | |
| 244 | 244 | static void callhook (lua_State *L, CallInfo *ci) { |
| 245 | | int hook = LUA_HOOKCALL; |
| 246 | | ci->u.l.savedpc++; /* hooks assume 'pc' is already incremented */ |
| 247 | | if (isLua(ci->previous) && |
| 248 | | GET_OPCODE(*(ci->previous->u.l.savedpc - 1)) == OP_TAILCALL) { |
| 249 | | ci->callstatus |= CIST_TAIL; |
| 250 | | hook = LUA_HOOKTAILCALL; |
| 251 | | } |
| 252 | | luaD_hook(L, hook, -1); |
| 253 | | ci->u.l.savedpc--; /* correct 'pc' */ |
| 245 | int hook = LUA_HOOKCALL; |
| 246 | ci->u.l.savedpc++; /* hooks assume 'pc' is already incremented */ |
| 247 | if (isLua(ci->previous) && |
| 248 | GET_OPCODE(*(ci->previous->u.l.savedpc - 1)) == OP_TAILCALL) { |
| 249 | ci->callstatus |= CIST_TAIL; |
| 250 | hook = LUA_HOOKTAILCALL; |
| 251 | } |
| 252 | luaD_hook(L, hook, -1); |
| 253 | ci->u.l.savedpc--; /* correct 'pc' */ |
| 254 | 254 | } |
| 255 | 255 | |
| 256 | 256 | |
| 257 | 257 | static StkId adjust_varargs (lua_State *L, Proto *p, int actual) { |
| 258 | | int i; |
| 259 | | int nfixargs = p->numparams; |
| 260 | | StkId base, fixed; |
| 261 | | lua_assert(actual >= nfixargs); |
| 262 | | /* move fixed parameters to final position */ |
| 263 | | fixed = L->top - actual; /* first fixed argument */ |
| 264 | | base = L->top; /* final position of first argument */ |
| 265 | | for (i=0; i<nfixargs; i++) { |
| 266 | | setobjs2s(L, L->top++, fixed + i); |
| 267 | | setnilvalue(fixed + i); |
| 268 | | } |
| 269 | | return base; |
| 258 | int i; |
| 259 | int nfixargs = p->numparams; |
| 260 | StkId base, fixed; |
| 261 | lua_assert(actual >= nfixargs); |
| 262 | /* move fixed parameters to final position */ |
| 263 | luaD_checkstack(L, p->maxstacksize); /* check again for new 'base' */ |
| 264 | fixed = L->top - actual; /* first fixed argument */ |
| 265 | base = L->top; /* final position of first argument */ |
| 266 | for (i=0; i<nfixargs; i++) { |
| 267 | setobjs2s(L, L->top++, fixed + i); |
| 268 | setnilvalue(fixed + i); |
| 269 | } |
| 270 | return base; |
| 270 | 271 | } |
| 271 | 272 | |
| 272 | 273 | |
| 273 | 274 | static StkId tryfuncTM (lua_State *L, StkId func) { |
| 274 | | const TValue *tm = luaT_gettmbyobj(L, func, TM_CALL); |
| 275 | | StkId p; |
| 276 | | ptrdiff_t funcr = savestack(L, func); |
| 277 | | if (!ttisfunction(tm)) |
| 278 | | luaG_typeerror(L, func, "call"); |
| 279 | | /* Open a hole inside the stack at `func' */ |
| 280 | | for (p = L->top; p > func; p--) setobjs2s(L, p, p-1); |
| 281 | | incr_top(L); |
| 282 | | func = restorestack(L, funcr); /* previous call may change stack */ |
| 283 | | setobj2s(L, func, tm); /* tag method is the new function to be called */ |
| 284 | | return func; |
| 275 | const TValue *tm = luaT_gettmbyobj(L, func, TM_CALL); |
| 276 | StkId p; |
| 277 | ptrdiff_t funcr = savestack(L, func); |
| 278 | if (!ttisfunction(tm)) |
| 279 | luaG_typeerror(L, func, "call"); |
| 280 | /* Open a hole inside the stack at `func' */ |
| 281 | for (p = L->top; p > func; p--) setobjs2s(L, p, p-1); |
| 282 | incr_top(L); |
| 283 | func = restorestack(L, funcr); /* previous call may change stack */ |
| 284 | setobj2s(L, func, tm); /* tag method is the new function to be called */ |
| 285 | return func; |
| 285 | 286 | } |
| 286 | 287 | |
| 287 | 288 | |
| r30857 | r30858 | |
| 293 | 294 | ** returns true if function has been executed (C function) |
| 294 | 295 | */ |
| 295 | 296 | int luaD_precall (lua_State *L, StkId func, int nresults) { |
| 296 | | lua_CFunction f; |
| 297 | | CallInfo *ci; |
| 298 | | int n; /* number of arguments (Lua) or returns (C) */ |
| 299 | | ptrdiff_t funcr = savestack(L, func); |
| 300 | | switch (ttype(func)) { |
| 301 | | case LUA_TLCF: /* light C function */ |
| 302 | | f = fvalue(func); |
| 303 | | goto Cfunc; |
| 304 | | case LUA_TCCL: { /* C closure */ |
| 305 | | f = clCvalue(func)->f; |
| 306 | | Cfunc: |
| 307 | | luaD_checkstack(L, LUA_MINSTACK); /* ensure minimum stack size */ |
| 308 | | ci = next_ci(L); /* now 'enter' new function */ |
| 309 | | ci->nresults = nresults; |
| 310 | | ci->func = restorestack(L, funcr); |
| 311 | | ci->top = L->top + LUA_MINSTACK; |
| 312 | | lua_assert(ci->top <= L->stack_last); |
| 313 | | ci->callstatus = 0; |
| 314 | | luaC_checkGC(L); /* stack grow uses memory */ |
| 315 | | if (L->hookmask & LUA_MASKCALL) |
| 316 | | luaD_hook(L, LUA_HOOKCALL, -1); |
| 317 | | lua_unlock(L); |
| 318 | | n = (*f)(L); /* do the actual call */ |
| 319 | | lua_lock(L); |
| 320 | | api_checknelems(L, n); |
| 321 | | luaD_poscall(L, L->top - n); |
| 322 | | return 1; |
| 323 | | } |
| 324 | | case LUA_TLCL: { /* Lua function: prepare its call */ |
| 325 | | StkId base; |
| 326 | | Proto *p = clLvalue(func)->p; |
| 327 | | luaD_checkstack(L, p->maxstacksize); |
| 328 | | func = restorestack(L, funcr); |
| 329 | | n = cast_int(L->top - func) - 1; /* number of real arguments */ |
| 330 | | for (; n < p->numparams; n++) |
| 331 | | setnilvalue(L->top++); /* complete missing arguments */ |
| 332 | | base = (!p->is_vararg) ? func + 1 : adjust_varargs(L, p, n); |
| 333 | | ci = next_ci(L); /* now 'enter' new function */ |
| 334 | | ci->nresults = nresults; |
| 335 | | ci->func = func; |
| 336 | | ci->u.l.base = base; |
| 337 | | ci->top = base + p->maxstacksize; |
| 338 | | lua_assert(ci->top <= L->stack_last); |
| 339 | | ci->u.l.savedpc = p->code; /* starting point */ |
| 340 | | ci->callstatus = CIST_LUA; |
| 341 | | L->top = ci->top; |
| 342 | | luaC_checkGC(L); /* stack grow uses memory */ |
| 343 | | if (L->hookmask & LUA_MASKCALL) |
| 344 | | callhook(L, ci); |
| 345 | | return 0; |
| 346 | | } |
| 347 | | default: { /* not a function */ |
| 348 | | func = tryfuncTM(L, func); /* retry with 'function' tag method */ |
| 349 | | return luaD_precall(L, func, nresults); /* now it must be a function */ |
| 350 | | } |
| 351 | | } |
| 297 | lua_CFunction f; |
| 298 | CallInfo *ci; |
| 299 | int n; /* number of arguments (Lua) or returns (C) */ |
| 300 | ptrdiff_t funcr = savestack(L, func); |
| 301 | switch (ttype(func)) { |
| 302 | case LUA_TLCF: /* light C function */ |
| 303 | f = fvalue(func); |
| 304 | goto Cfunc; |
| 305 | case LUA_TCCL: { /* C closure */ |
| 306 | f = clCvalue(func)->f; |
| 307 | Cfunc: |
| 308 | luaD_checkstack(L, LUA_MINSTACK); /* ensure minimum stack size */ |
| 309 | ci = next_ci(L); /* now 'enter' new function */ |
| 310 | ci->nresults = nresults; |
| 311 | ci->func = restorestack(L, funcr); |
| 312 | ci->top = L->top + LUA_MINSTACK; |
| 313 | lua_assert(ci->top <= L->stack_last); |
| 314 | ci->callstatus = 0; |
| 315 | luaC_checkGC(L); /* stack grow uses memory */ |
| 316 | if (L->hookmask & LUA_MASKCALL) |
| 317 | luaD_hook(L, LUA_HOOKCALL, -1); |
| 318 | lua_unlock(L); |
| 319 | n = (*f)(L); /* do the actual call */ |
| 320 | lua_lock(L); |
| 321 | api_checknelems(L, n); |
| 322 | luaD_poscall(L, L->top - n); |
| 323 | return 1; |
| 324 | } |
| 325 | case LUA_TLCL: { /* Lua function: prepare its call */ |
| 326 | StkId base; |
| 327 | Proto *p = clLvalue(func)->p; |
| 328 | n = cast_int(L->top - func) - 1; /* number of real arguments */ |
| 329 | luaD_checkstack(L, p->maxstacksize); |
| 330 | for (; n < p->numparams; n++) |
| 331 | setnilvalue(L->top++); /* complete missing arguments */ |
| 332 | if (!p->is_vararg) { |
| 333 | func = restorestack(L, funcr); |
| 334 | base = func + 1; |
| 335 | } |
| 336 | else { |
| 337 | base = adjust_varargs(L, p, n); |
| 338 | func = restorestack(L, funcr); /* previous call can change stack */ |
| 339 | } |
| 340 | ci = next_ci(L); /* now 'enter' new function */ |
| 341 | ci->nresults = nresults; |
| 342 | ci->func = func; |
| 343 | ci->u.l.base = base; |
| 344 | ci->top = base + p->maxstacksize; |
| 345 | lua_assert(ci->top <= L->stack_last); |
| 346 | ci->u.l.savedpc = p->code; /* starting point */ |
| 347 | ci->callstatus = CIST_LUA; |
| 348 | L->top = ci->top; |
| 349 | luaC_checkGC(L); /* stack grow uses memory */ |
| 350 | if (L->hookmask & LUA_MASKCALL) |
| 351 | callhook(L, ci); |
| 352 | return 0; |
| 353 | } |
| 354 | default: { /* not a function */ |
| 355 | func = tryfuncTM(L, func); /* retry with 'function' tag method */ |
| 356 | return luaD_precall(L, func, nresults); /* now it must be a function */ |
| 357 | } |
| 358 | } |
| 352 | 359 | } |
| 353 | 360 | |
| 354 | 361 | |
| 355 | 362 | int luaD_poscall (lua_State *L, StkId firstResult) { |
| 356 | | StkId res; |
| 357 | | int wanted, i; |
| 358 | | CallInfo *ci = L->ci; |
| 359 | | if (L->hookmask & (LUA_MASKRET | LUA_MASKLINE)) { |
| 360 | | if (L->hookmask & LUA_MASKRET) { |
| 361 | | ptrdiff_t fr = savestack(L, firstResult); /* hook may change stack */ |
| 362 | | luaD_hook(L, LUA_HOOKRET, -1); |
| 363 | | firstResult = restorestack(L, fr); |
| 364 | | } |
| 365 | | L->oldpc = ci->previous->u.l.savedpc; /* 'oldpc' for caller function */ |
| 366 | | } |
| 367 | | res = ci->func; /* res == final position of 1st result */ |
| 368 | | wanted = ci->nresults; |
| 369 | | L->ci = ci = ci->previous; /* back to caller */ |
| 370 | | /* move results to correct place */ |
| 371 | | for (i = wanted; i != 0 && firstResult < L->top; i--) |
| 372 | | setobjs2s(L, res++, firstResult++); |
| 373 | | while (i-- > 0) |
| 374 | | setnilvalue(res++); |
| 375 | | L->top = res; |
| 376 | | return (wanted - LUA_MULTRET); /* 0 iff wanted == LUA_MULTRET */ |
| 363 | StkId res; |
| 364 | int wanted, i; |
| 365 | CallInfo *ci = L->ci; |
| 366 | if (L->hookmask & (LUA_MASKRET | LUA_MASKLINE)) { |
| 367 | if (L->hookmask & LUA_MASKRET) { |
| 368 | ptrdiff_t fr = savestack(L, firstResult); /* hook may change stack */ |
| 369 | luaD_hook(L, LUA_HOOKRET, -1); |
| 370 | firstResult = restorestack(L, fr); |
| 371 | } |
| 372 | L->oldpc = ci->previous->u.l.savedpc; /* 'oldpc' for caller function */ |
| 373 | } |
| 374 | res = ci->func; /* res == final position of 1st result */ |
| 375 | wanted = ci->nresults; |
| 376 | L->ci = ci = ci->previous; /* back to caller */ |
| 377 | /* move results to correct place */ |
| 378 | for (i = wanted; i != 0 && firstResult < L->top; i--) |
| 379 | setobjs2s(L, res++, firstResult++); |
| 380 | while (i-- > 0) |
| 381 | setnilvalue(res++); |
| 382 | L->top = res; |
| 383 | return (wanted - LUA_MULTRET); /* 0 iff wanted == LUA_MULTRET */ |
| 377 | 384 | } |
| 378 | 385 | |
| 379 | 386 | |
| r30857 | r30858 | |
| 384 | 391 | ** function position. |
| 385 | 392 | */ |
| 386 | 393 | void luaD_call (lua_State *L, StkId func, int nResults, int allowyield) { |
| 387 | | if (++L->nCcalls >= LUAI_MAXCCALLS) { |
| 388 | | if (L->nCcalls == LUAI_MAXCCALLS) |
| 389 | | luaG_runerror(L, "C stack overflow"); |
| 390 | | else if (L->nCcalls >= (LUAI_MAXCCALLS + (LUAI_MAXCCALLS>>3))) |
| 391 | | luaD_throw(L, LUA_ERRERR); /* error while handing stack error */ |
| 392 | | } |
| 393 | | if (!allowyield) L->nny++; |
| 394 | | if (!luaD_precall(L, func, nResults)) /* is a Lua function? */ |
| 395 | | luaV_execute(L); /* call it */ |
| 396 | | if (!allowyield) L->nny--; |
| 397 | | L->nCcalls--; |
| 394 | if (++L->nCcalls >= LUAI_MAXCCALLS) { |
| 395 | if (L->nCcalls == LUAI_MAXCCALLS) |
| 396 | luaG_runerror(L, "C stack overflow"); |
| 397 | else if (L->nCcalls >= (LUAI_MAXCCALLS + (LUAI_MAXCCALLS>>3))) |
| 398 | luaD_throw(L, LUA_ERRERR); /* error while handing stack error */ |
| 399 | } |
| 400 | if (!allowyield) L->nny++; |
| 401 | if (!luaD_precall(L, func, nResults)) /* is a Lua function? */ |
| 402 | luaV_execute(L); /* call it */ |
| 403 | if (!allowyield) L->nny--; |
| 404 | L->nCcalls--; |
| 398 | 405 | } |
| 399 | 406 | |
| 400 | 407 | |
| 401 | 408 | static void finishCcall (lua_State *L) { |
| 402 | | CallInfo *ci = L->ci; |
| 403 | | int n; |
| 404 | | lua_assert(ci->u.c.k != NULL); /* must have a continuation */ |
| 405 | | lua_assert(L->nny == 0); |
| 406 | | if (ci->callstatus & CIST_YPCALL) { /* was inside a pcall? */ |
| 407 | | ci->callstatus &= ~CIST_YPCALL; /* finish 'lua_pcall' */ |
| 408 | | L->errfunc = ci->u.c.old_errfunc; |
| 409 | | } |
| 410 | | /* finish 'lua_callk'/'lua_pcall' */ |
| 411 | | adjustresults(L, ci->nresults); |
| 412 | | /* call continuation function */ |
| 413 | | if (!(ci->callstatus & CIST_STAT)) /* no call status? */ |
| 414 | | ci->u.c.status = LUA_YIELD; /* 'default' status */ |
| 415 | | lua_assert(ci->u.c.status != LUA_OK); |
| 416 | | ci->callstatus = (ci->callstatus & ~(CIST_YPCALL | CIST_STAT)) | CIST_YIELDED; |
| 417 | | lua_unlock(L); |
| 418 | | n = (*ci->u.c.k)(L); |
| 419 | | lua_lock(L); |
| 420 | | api_checknelems(L, n); |
| 421 | | /* finish 'luaD_precall' */ |
| 422 | | luaD_poscall(L, L->top - n); |
| 409 | CallInfo *ci = L->ci; |
| 410 | int n; |
| 411 | lua_assert(ci->u.c.k != NULL); /* must have a continuation */ |
| 412 | lua_assert(L->nny == 0); |
| 413 | if (ci->callstatus & CIST_YPCALL) { /* was inside a pcall? */ |
| 414 | ci->callstatus &= ~CIST_YPCALL; /* finish 'lua_pcall' */ |
| 415 | L->errfunc = ci->u.c.old_errfunc; |
| 416 | } |
| 417 | /* finish 'lua_callk'/'lua_pcall' */ |
| 418 | adjustresults(L, ci->nresults); |
| 419 | /* call continuation function */ |
| 420 | if (!(ci->callstatus & CIST_STAT)) /* no call status? */ |
| 421 | ci->u.c.status = LUA_YIELD; /* 'default' status */ |
| 422 | lua_assert(ci->u.c.status != LUA_OK); |
| 423 | ci->callstatus = (ci->callstatus & ~(CIST_YPCALL | CIST_STAT)) | CIST_YIELDED; |
| 424 | lua_unlock(L); |
| 425 | n = (*ci->u.c.k)(L); |
| 426 | lua_lock(L); |
| 427 | api_checknelems(L, n); |
| 428 | /* finish 'luaD_precall' */ |
| 429 | luaD_poscall(L, L->top - n); |
| 423 | 430 | } |
| 424 | 431 | |
| 425 | 432 | |
| 426 | 433 | static void unroll (lua_State *L, void *ud) { |
| 427 | | UNUSED(ud); |
| 428 | | for (;;) { |
| 429 | | if (L->ci == &L->base_ci) /* stack is empty? */ |
| 430 | | return; /* coroutine finished normally */ |
| 431 | | if (!isLua(L->ci)) /* C function? */ |
| 432 | | finishCcall(L); |
| 433 | | else { /* Lua function */ |
| 434 | | luaV_finishOp(L); /* finish interrupted instruction */ |
| 435 | | luaV_execute(L); /* execute down to higher C 'boundary' */ |
| 436 | | } |
| 437 | | } |
| 434 | UNUSED(ud); |
| 435 | for (;;) { |
| 436 | if (L->ci == &L->base_ci) /* stack is empty? */ |
| 437 | return; /* coroutine finished normally */ |
| 438 | if (!isLua(L->ci)) /* C function? */ |
| 439 | finishCcall(L); |
| 440 | else { /* Lua function */ |
| 441 | luaV_finishOp(L); /* finish interrupted instruction */ |
| 442 | luaV_execute(L); /* execute down to higher C 'boundary' */ |
| 443 | } |
| 444 | } |
| 438 | 445 | } |
| 439 | 446 | |
| 440 | 447 | |
| r30857 | r30858 | |
| 442 | 449 | ** check whether thread has a suspended protected call |
| 443 | 450 | */ |
| 444 | 451 | static CallInfo *findpcall (lua_State *L) { |
| 445 | | CallInfo *ci; |
| 446 | | for (ci = L->ci; ci != NULL; ci = ci->previous) { /* search for a pcall */ |
| 447 | | if (ci->callstatus & CIST_YPCALL) |
| 448 | | return ci; |
| 449 | | } |
| 450 | | return NULL; /* no pending pcall */ |
| 452 | CallInfo *ci; |
| 453 | for (ci = L->ci; ci != NULL; ci = ci->previous) { /* search for a pcall */ |
| 454 | if (ci->callstatus & CIST_YPCALL) |
| 455 | return ci; |
| 456 | } |
| 457 | return NULL; /* no pending pcall */ |
| 451 | 458 | } |
| 452 | 459 | |
| 453 | 460 | |
| 454 | 461 | static int recover (lua_State *L, int status) { |
| 455 | | StkId oldtop; |
| 456 | | CallInfo *ci = findpcall(L); |
| 457 | | if (ci == NULL) return 0; /* no recovery point */ |
| 458 | | /* "finish" luaD_pcall */ |
| 459 | | oldtop = restorestack(L, ci->extra); |
| 460 | | luaF_close(L, oldtop); |
| 461 | | seterrorobj(L, status, oldtop); |
| 462 | | L->ci = ci; |
| 463 | | L->allowhook = ci->u.c.old_allowhook; |
| 464 | | L->nny = 0; /* should be zero to be yieldable */ |
| 465 | | luaD_shrinkstack(L); |
| 466 | | L->errfunc = ci->u.c.old_errfunc; |
| 467 | | ci->callstatus |= CIST_STAT; /* call has error status */ |
| 468 | | ci->u.c.status = status; /* (here it is) */ |
| 469 | | return 1; /* continue running the coroutine */ |
| 462 | StkId oldtop; |
| 463 | CallInfo *ci = findpcall(L); |
| 464 | if (ci == NULL) return 0; /* no recovery point */ |
| 465 | /* "finish" luaD_pcall */ |
| 466 | oldtop = restorestack(L, ci->extra); |
| 467 | luaF_close(L, oldtop); |
| 468 | seterrorobj(L, status, oldtop); |
| 469 | L->ci = ci; |
| 470 | L->allowhook = ci->u.c.old_allowhook; |
| 471 | L->nny = 0; /* should be zero to be yieldable */ |
| 472 | luaD_shrinkstack(L); |
| 473 | L->errfunc = ci->u.c.old_errfunc; |
| 474 | ci->callstatus |= CIST_STAT; /* call has error status */ |
| 475 | ci->u.c.status = status; /* (here it is) */ |
| 476 | return 1; /* continue running the coroutine */ |
| 470 | 477 | } |
| 471 | 478 | |
| 472 | 479 | |
| r30857 | r30858 | |
| 476 | 483 | ** error handler and should not kill the coroutine.) |
| 477 | 484 | */ |
| 478 | 485 | static l_noret resume_error (lua_State *L, const char *msg, StkId firstArg) { |
| 479 | | L->top = firstArg; /* remove args from the stack */ |
| 480 | | setsvalue2s(L, L->top, luaS_new(L, msg)); /* push error message */ |
| 481 | | api_incr_top(L); |
| 482 | | luaD_throw(L, -1); /* jump back to 'lua_resume' */ |
| 486 | L->top = firstArg; /* remove args from the stack */ |
| 487 | setsvalue2s(L, L->top, luaS_new(L, msg)); /* push error message */ |
| 488 | api_incr_top(L); |
| 489 | luaD_throw(L, -1); /* jump back to 'lua_resume' */ |
| 483 | 490 | } |
| 484 | 491 | |
| 485 | 492 | |
| r30857 | r30858 | |
| 487 | 494 | ** do the work for 'lua_resume' in protected mode |
| 488 | 495 | */ |
| 489 | 496 | static void resume (lua_State *L, void *ud) { |
| 490 | | int nCcalls = L->nCcalls; |
| 491 | | StkId firstArg = cast(StkId, ud); |
| 492 | | CallInfo *ci = L->ci; |
| 493 | | if (nCcalls >= LUAI_MAXCCALLS) |
| 494 | | resume_error(L, "C stack overflow", firstArg); |
| 495 | | if (L->status == LUA_OK) { /* may be starting a coroutine */ |
| 496 | | if (ci != &L->base_ci) /* not in base level? */ |
| 497 | | resume_error(L, "cannot resume non-suspended coroutine", firstArg); |
| 498 | | /* coroutine is in base level; start running it */ |
| 499 | | if (!luaD_precall(L, firstArg - 1, LUA_MULTRET)) /* Lua function? */ |
| 500 | | luaV_execute(L); /* call it */ |
| 501 | | } |
| 502 | | else if (L->status != LUA_YIELD) |
| 503 | | resume_error(L, "cannot resume dead coroutine", firstArg); |
| 504 | | else { /* resuming from previous yield */ |
| 505 | | L->status = LUA_OK; |
| 506 | | ci->func = restorestack(L, ci->extra); |
| 507 | | if (isLua(ci)) /* yielded inside a hook? */ |
| 508 | | luaV_execute(L); /* just continue running Lua code */ |
| 509 | | else { /* 'common' yield */ |
| 510 | | if (ci->u.c.k != NULL) { /* does it have a continuation? */ |
| 511 | | int n; |
| 512 | | ci->u.c.status = LUA_YIELD; /* 'default' status */ |
| 513 | | ci->callstatus |= CIST_YIELDED; |
| 514 | | lua_unlock(L); |
| 515 | | n = (*ci->u.c.k)(L); /* call continuation */ |
| 516 | | lua_lock(L); |
| 517 | | api_checknelems(L, n); |
| 518 | | firstArg = L->top - n; /* yield results come from continuation */ |
| 519 | | } |
| 520 | | luaD_poscall(L, firstArg); /* finish 'luaD_precall' */ |
| 521 | | } |
| 522 | | unroll(L, NULL); |
| 523 | | } |
| 524 | | lua_assert(nCcalls == L->nCcalls); |
| 497 | int nCcalls = L->nCcalls; |
| 498 | StkId firstArg = cast(StkId, ud); |
| 499 | CallInfo *ci = L->ci; |
| 500 | if (nCcalls >= LUAI_MAXCCALLS) |
| 501 | resume_error(L, "C stack overflow", firstArg); |
| 502 | if (L->status == LUA_OK) { /* may be starting a coroutine */ |
| 503 | if (ci != &L->base_ci) /* not in base level? */ |
| 504 | resume_error(L, "cannot resume non-suspended coroutine", firstArg); |
| 505 | /* coroutine is in base level; start running it */ |
| 506 | if (!luaD_precall(L, firstArg - 1, LUA_MULTRET)) /* Lua function? */ |
| 507 | luaV_execute(L); /* call it */ |
| 508 | } |
| 509 | else if (L->status != LUA_YIELD) |
| 510 | resume_error(L, "cannot resume dead coroutine", firstArg); |
| 511 | else { /* resuming from previous yield */ |
| 512 | L->status = LUA_OK; |
| 513 | ci->func = restorestack(L, ci->extra); |
| 514 | if (isLua(ci)) /* yielded inside a hook? */ |
| 515 | luaV_execute(L); /* just continue running Lua code */ |
| 516 | else { /* 'common' yield */ |
| 517 | if (ci->u.c.k != NULL) { /* does it have a continuation? */ |
| 518 | int n; |
| 519 | ci->u.c.status = LUA_YIELD; /* 'default' status */ |
| 520 | ci->callstatus |= CIST_YIELDED; |
| 521 | lua_unlock(L); |
| 522 | n = (*ci->u.c.k)(L); /* call continuation */ |
| 523 | lua_lock(L); |
| 524 | api_checknelems(L, n); |
| 525 | firstArg = L->top - n; /* yield results come from continuation */ |
| 526 | } |
| 527 | luaD_poscall(L, firstArg); /* finish 'luaD_precall' */ |
| 528 | } |
| 529 | unroll(L, NULL); |
| 530 | } |
| 531 | lua_assert(nCcalls == L->nCcalls); |
| 525 | 532 | } |
| 526 | 533 | |
| 527 | 534 | |
| 528 | 535 | LUA_API int lua_resume (lua_State *L, lua_State *from, int nargs) { |
| 529 | | int status; |
| 530 | | lua_lock(L); |
| 531 | | luai_userstateresume(L, nargs); |
| 532 | | L->nCcalls = (from) ? from->nCcalls + 1 : 1; |
| 533 | | L->nny = 0; /* allow yields */ |
| 534 | | api_checknelems(L, (L->status == LUA_OK) ? nargs + 1 : nargs); |
| 535 | | status = luaD_rawrunprotected(L, resume, L->top - nargs); |
| 536 | | if (status == -1) /* error calling 'lua_resume'? */ |
| 537 | | status = LUA_ERRRUN; |
| 538 | | else { /* yield or regular error */ |
| 539 | | while (status != LUA_OK && status != LUA_YIELD) { /* error? */ |
| 540 | | if (recover(L, status)) /* recover point? */ |
| 541 | | status = luaD_rawrunprotected(L, unroll, NULL); /* run continuation */ |
| 542 | | else { /* unrecoverable error */ |
| 543 | | L->status = cast_byte(status); /* mark thread as `dead' */ |
| 544 | | seterrorobj(L, status, L->top); |
| 545 | | L->ci->top = L->top; |
| 546 | | break; |
| 547 | | } |
| 548 | | } |
| 549 | | lua_assert(status == L->status); |
| 550 | | } |
| 551 | | L->nny = 1; /* do not allow yields */ |
| 552 | | L->nCcalls--; |
| 553 | | lua_assert(L->nCcalls == ((from) ? from->nCcalls : 0)); |
| 554 | | lua_unlock(L); |
| 555 | | return status; |
| 536 | int status; |
| 537 | int oldnny = L->nny; /* save 'nny' */ |
| 538 | lua_lock(L); |
| 539 | luai_userstateresume(L, nargs); |
| 540 | L->nCcalls = (from) ? from->nCcalls + 1 : 1; |
| 541 | L->nny = 0; /* allow yields */ |
| 542 | api_checknelems(L, (L->status == LUA_OK) ? nargs + 1 : nargs); |
| 543 | status = luaD_rawrunprotected(L, resume, L->top - nargs); |
| 544 | if (status == -1) /* error calling 'lua_resume'? */ |
| 545 | status = LUA_ERRRUN; |
| 546 | else { /* yield or regular error */ |
| 547 | while (status != LUA_OK && status != LUA_YIELD) { /* error? */ |
| 548 | if (recover(L, status)) /* recover point? */ |
| 549 | status = luaD_rawrunprotected(L, unroll, NULL); /* run continuation */ |
| 550 | else { /* unrecoverable error */ |
| 551 | L->status = cast_byte(status); /* mark thread as `dead' */ |
| 552 | seterrorobj(L, status, L->top); |
| 553 | L->ci->top = L->top; |
| 554 | break; |
| 555 | } |
| 556 | } |
| 557 | lua_assert(status == L->status); |
| 558 | } |
| 559 | L->nny = oldnny; /* restore 'nny' */ |
| 560 | L->nCcalls--; |
| 561 | lua_assert(L->nCcalls == ((from) ? from->nCcalls : 0)); |
| 562 | lua_unlock(L); |
| 563 | return status; |
| 556 | 564 | } |
| 557 | 565 | |
| 558 | 566 | |
| 559 | 567 | LUA_API int lua_yieldk (lua_State *L, int nresults, int ctx, lua_CFunction k) { |
| 560 | | CallInfo *ci = L->ci; |
| 561 | | luai_userstateyield(L, nresults); |
| 562 | | lua_lock(L); |
| 563 | | api_checknelems(L, nresults); |
| 564 | | if (L->nny > 0) { |
| 565 | | if (L != G(L)->mainthread) |
| 566 | | luaG_runerror(L, "attempt to yield across a C-call boundary"); |
| 567 | | else |
| 568 | | luaG_runerror(L, "attempt to yield from outside a coroutine"); |
| 569 | | } |
| 570 | | L->status = LUA_YIELD; |
| 571 | | ci->extra = savestack(L, ci->func); /* save current 'func' */ |
| 572 | | if (isLua(ci)) { /* inside a hook? */ |
| 573 | | api_check(L, k == NULL, "hooks cannot continue after yielding"); |
| 574 | | } |
| 575 | | else { |
| 576 | | if ((ci->u.c.k = k) != NULL) /* is there a continuation? */ |
| 577 | | ci->u.c.ctx = ctx; /* save context */ |
| 578 | | ci->func = L->top - nresults - 1; /* protect stack below results */ |
| 579 | | luaD_throw(L, LUA_YIELD); |
| 580 | | } |
| 581 | | lua_assert(ci->callstatus & CIST_HOOKED); /* must be inside a hook */ |
| 582 | | lua_unlock(L); |
| 583 | | return 0; /* return to 'luaD_hook' */ |
| 568 | CallInfo *ci = L->ci; |
| 569 | luai_userstateyield(L, nresults); |
| 570 | lua_lock(L); |
| 571 | api_checknelems(L, nresults); |
| 572 | if (L->nny > 0) { |
| 573 | if (L != G(L)->mainthread) |
| 574 | luaG_runerror(L, "attempt to yield across a C-call boundary"); |
| 575 | else |
| 576 | luaG_runerror(L, "attempt to yield from outside a coroutine"); |
| 577 | } |
| 578 | L->status = LUA_YIELD; |
| 579 | ci->extra = savestack(L, ci->func); /* save current 'func' */ |
| 580 | if (isLua(ci)) { /* inside a hook? */ |
| 581 | api_check(L, k == NULL, "hooks cannot continue after yielding"); |
| 582 | } |
| 583 | else { |
| 584 | if ((ci->u.c.k = k) != NULL) /* is there a continuation? */ |
| 585 | ci->u.c.ctx = ctx; /* save context */ |
| 586 | ci->func = L->top - nresults - 1; /* protect stack below results */ |
| 587 | luaD_throw(L, LUA_YIELD); |
| 588 | } |
| 589 | lua_assert(ci->callstatus & CIST_HOOKED); /* must be inside a hook */ |
| 590 | lua_unlock(L); |
| 591 | return 0; /* return to 'luaD_hook' */ |
| 584 | 592 | } |
| 585 | 593 | |
| 586 | 594 | |
| 587 | 595 | int luaD_pcall (lua_State *L, Pfunc func, void *u, |
| 588 | | ptrdiff_t old_top, ptrdiff_t ef) { |
| 589 | | int status; |
| 590 | | CallInfo *old_ci = L->ci; |
| 591 | | lu_byte old_allowhooks = L->allowhook; |
| 592 | | unsigned short old_nny = L->nny; |
| 593 | | ptrdiff_t old_errfunc = L->errfunc; |
| 594 | | L->errfunc = ef; |
| 595 | | status = luaD_rawrunprotected(L, func, u); |
| 596 | | if (status != LUA_OK) { /* an error occurred? */ |
| 597 | | StkId oldtop = restorestack(L, old_top); |
| 598 | | luaF_close(L, oldtop); /* close possible pending closures */ |
| 599 | | seterrorobj(L, status, oldtop); |
| 600 | | L->ci = old_ci; |
| 601 | | L->allowhook = old_allowhooks; |
| 602 | | L->nny = old_nny; |
| 603 | | luaD_shrinkstack(L); |
| 604 | | } |
| 605 | | L->errfunc = old_errfunc; |
| 606 | | return status; |
| 596 | ptrdiff_t old_top, ptrdiff_t ef) { |
| 597 | int status; |
| 598 | CallInfo *old_ci = L->ci; |
| 599 | lu_byte old_allowhooks = L->allowhook; |
| 600 | unsigned short old_nny = L->nny; |
| 601 | ptrdiff_t old_errfunc = L->errfunc; |
| 602 | L->errfunc = ef; |
| 603 | status = luaD_rawrunprotected(L, func, u); |
| 604 | if (status != LUA_OK) { /* an error occurred? */ |
| 605 | StkId oldtop = restorestack(L, old_top); |
| 606 | luaF_close(L, oldtop); /* close possible pending closures */ |
| 607 | seterrorobj(L, status, oldtop); |
| 608 | L->ci = old_ci; |
| 609 | L->allowhook = old_allowhooks; |
| 610 | L->nny = old_nny; |
| 611 | luaD_shrinkstack(L); |
| 612 | } |
| 613 | L->errfunc = old_errfunc; |
| 614 | return status; |
| 607 | 615 | } |
| 608 | 616 | |
| 609 | 617 | |
| r30857 | r30858 | |
| 612 | 620 | ** Execute a protected parser. |
| 613 | 621 | */ |
| 614 | 622 | struct SParser { /* data to `f_parser' */ |
| 615 | | ZIO *z; |
| 616 | | Mbuffer buff; /* dynamic structure used by the scanner */ |
| 617 | | Dyndata dyd; /* dynamic structures used by the parser */ |
| 618 | | const char *mode; |
| 619 | | const char *name; |
| 623 | ZIO *z; |
| 624 | Mbuffer buff; /* dynamic structure used by the scanner */ |
| 625 | Dyndata dyd; /* dynamic structures used by the parser */ |
| 626 | const char *mode; |
| 627 | const char *name; |
| 620 | 628 | }; |
| 621 | 629 | |
| 622 | 630 | |
| 623 | 631 | static void checkmode (lua_State *L, const char *mode, const char *x) { |
| 624 | | if (mode && strchr(mode, x[0]) == NULL) { |
| 625 | | luaO_pushfstring(L, |
| 626 | | "attempt to load a %s chunk (mode is " LUA_QS ")", x, mode); |
| 627 | | luaD_throw(L, LUA_ERRSYNTAX); |
| 628 | | } |
| 632 | if (mode && strchr(mode, x[0]) == NULL) { |
| 633 | luaO_pushfstring(L, |
| 634 | "attempt to load a %s chunk (mode is " LUA_QS ")", x, mode); |
| 635 | luaD_throw(L, LUA_ERRSYNTAX); |
| 636 | } |
| 629 | 637 | } |
| 630 | 638 | |
| 631 | 639 | |
| 632 | 640 | static void f_parser (lua_State *L, void *ud) { |
| 633 | | int i; |
| 634 | | Closure *cl; |
| 635 | | struct SParser *p = cast(struct SParser *, ud); |
| 636 | | int c = zgetc(p->z); /* read first character */ |
| 637 | | if (c == LUA_SIGNATURE[0]) { |
| 638 | | checkmode(L, p->mode, "binary"); |
| 639 | | cl = luaU_undump(L, p->z, &p->buff, p->name); |
| 640 | | } |
| 641 | | else { |
| 642 | | checkmode(L, p->mode, "text"); |
| 643 | | cl = luaY_parser(L, p->z, &p->buff, &p->dyd, p->name, c); |
| 644 | | } |
| 645 | | lua_assert(cl->l.nupvalues == cl->l.p->sizeupvalues); |
| 646 | | for (i = 0; i < cl->l.nupvalues; i++) { /* initialize upvalues */ |
| 647 | | UpVal *up = luaF_newupval(L); |
| 648 | | cl->l.upvals[i] = up; |
| 649 | | luaC_objbarrier(L, cl, up); |
| 650 | | } |
| 641 | int i; |
| 642 | Closure *cl; |
| 643 | struct SParser *p = cast(struct SParser *, ud); |
| 644 | int c = zgetc(p->z); /* read first character */ |
| 645 | if (c == LUA_SIGNATURE[0]) { |
| 646 | checkmode(L, p->mode, "binary"); |
| 647 | cl = luaU_undump(L, p->z, &p->buff, p->name); |
| 648 | } |
| 649 | else { |
| 650 | checkmode(L, p->mode, "text"); |
| 651 | cl = luaY_parser(L, p->z, &p->buff, &p->dyd, p->name, c); |
| 652 | } |
| 653 | lua_assert(cl->l.nupvalues == cl->l.p->sizeupvalues); |
| 654 | for (i = 0; i < cl->l.nupvalues; i++) { /* initialize upvalues */ |
| 655 | UpVal *up = luaF_newupval(L); |
| 656 | cl->l.upvals[i] = up; |
| 657 | luaC_objbarrier(L, cl, up); |
| 658 | } |
| 651 | 659 | } |
| 652 | 660 | |
| 653 | 661 | |
| 654 | 662 | int luaD_protectedparser (lua_State *L, ZIO *z, const char *name, |
| 655 | | const char *mode) { |
| 656 | | struct SParser p; |
| 657 | | int status; |
| 658 | | L->nny++; /* cannot yield during parsing */ |
| 659 | | p.z = z; p.name = name; p.mode = mode; |
| 660 | | p.dyd.actvar.arr = NULL; p.dyd.actvar.size = 0; |
| 661 | | p.dyd.gt.arr = NULL; p.dyd.gt.size = 0; |
| 662 | | p.dyd.label.arr = NULL; p.dyd.label.size = 0; |
| 663 | | luaZ_initbuffer(L, &p.buff); |
| 664 | | status = luaD_pcall(L, f_parser, &p, savestack(L, L->top), L->errfunc); |
| 665 | | luaZ_freebuffer(L, &p.buff); |
| 666 | | luaM_freearray(L, p.dyd.actvar.arr, p.dyd.actvar.size); |
| 667 | | luaM_freearray(L, p.dyd.gt.arr, p.dyd.gt.size); |
| 668 | | luaM_freearray(L, p.dyd.label.arr, p.dyd.label.size); |
| 669 | | L->nny--; |
| 670 | | return status; |
| 663 | const char *mode) { |
| 664 | struct SParser p; |
| 665 | int status; |
| 666 | L->nny++; /* cannot yield during parsing */ |
| 667 | p.z = z; p.name = name; p.mode = mode; |
| 668 | p.dyd.actvar.arr = NULL; p.dyd.actvar.size = 0; |
| 669 | p.dyd.gt.arr = NULL; p.dyd.gt.size = 0; |
| 670 | p.dyd.label.arr = NULL; p.dyd.label.size = 0; |
| 671 | luaZ_initbuffer(L, &p.buff); |
| 672 | status = luaD_pcall(L, f_parser, &p, savestack(L, L->top), L->errfunc); |
| 673 | luaZ_freebuffer(L, &p.buff); |
| 674 | luaM_freearray(L, p.dyd.actvar.arr, p.dyd.actvar.size); |
| 675 | luaM_freearray(L, p.dyd.gt.arr, p.dyd.gt.size); |
| 676 | luaM_freearray(L, p.dyd.label.arr, p.dyd.label.size); |
| 677 | L->nny--; |
| 678 | return status; |
| 671 | 679 | } |
| 680 | |
| 681 | |
trunk/src/lib/lua/lib/lsqlite3.c
| r0 | r30858 | |
| 1 | /************************************************************************ |
| 2 | * lsqlite3 * |
| 3 | * Copyright (C) 2002-2013 Tiago Dionizio, Doug Currie * |
| 4 | * All rights reserved. * |
| 5 | * Author : Tiago Dionizio <tiago.dionizio@ist.utl.pt> * |
| 6 | * Author : Doug Currie <doug.currie@alum.mit.edu> * |
| 7 | * Library : lsqlite3 - a SQLite 3 database binding for Lua 5 * |
| 8 | * * |
| 9 | * Permission is hereby granted, free of charge, to any person obtaining * |
| 10 | * a copy of this software and associated documentation files (the * |
| 11 | * "Software"), to deal in the Software without restriction, including * |
| 12 | * without limitation the rights to use, copy, modify, merge, publish, * |
| 13 | * distribute, sublicense, and/or sell copies of the Software, and to * |
| 14 | * permit persons to whom the Software is furnished to do so, subject to * |
| 15 | * the following conditions: * |
| 16 | * * |
| 17 | * The above copyright notice and this permission notice shall be * |
| 18 | * included in all copies or substantial portions of the Software. * |
| 19 | * * |
| 20 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * |
| 21 | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * |
| 22 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.* |
| 23 | * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * |
| 24 | * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * |
| 25 | * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * |
| 26 | * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * |
| 27 | ************************************************************************/ |
| 28 | |
| 29 | #include <stdlib.h> |
| 30 | #include <string.h> |
| 31 | #include <assert.h> |
| 32 | |
| 33 | #define LUA_LIB |
| 34 | #include "..\lua.h" |
| 35 | #include "..\lauxlib.h" |
| 36 | |
| 37 | #if LUA_VERSION_NUM > 501 |
| 38 | // |
| 39 | // Lua 5.2 |
| 40 | // |
| 41 | //#define lua_strlen lua_rawlen |
| 42 | // luaL_typerror always used with arg at ndx == NULL |
| 43 | #define luaL_typerror(L,ndx,str) luaL_error(L,"bad argument %d (%s expected, got nil)",ndx,str) |
| 44 | // luaL_register used once, so below expansion is OK for this case |
| 45 | //#define luaL_register(L,name,reg) lua_newtable(L);luaL_setfuncs(L,reg,0) |
| 46 | // luaL_openlib always used with name == NULL |
| 47 | #define luaL_openlib(L,name,reg,nup) luaL_setfuncs(L,reg,nup) |
| 48 | #endif |
| 49 | |
| 50 | #include "sqlite3\sqlite3.h" |
| 51 | |
| 52 | /* compile time features */ |
| 53 | #if !defined(SQLITE_OMIT_PROGRESS_CALLBACK) |
| 54 | #define SQLITE_OMIT_PROGRESS_CALLBACK 0 |
| 55 | #endif |
| 56 | #if !defined(LSQLITE_OMIT_UPDATE_HOOK) |
| 57 | #define LSQLITE_OMIT_UPDATE_HOOK 0 |
| 58 | #endif |
| 59 | |
| 60 | typedef struct sdb sdb; |
| 61 | typedef struct sdb_vm sdb_vm; |
| 62 | typedef struct sdb_func sdb_func; |
| 63 | |
| 64 | /* to use as C user data so i know what function sqlite is calling */ |
| 65 | struct sdb_func { |
| 66 | /* references to associated lua values */ |
| 67 | int fn_step; |
| 68 | int fn_finalize; |
| 69 | int udata; |
| 70 | |
| 71 | sdb *db; |
| 72 | char aggregate; |
| 73 | |
| 74 | sdb_func *next; |
| 75 | }; |
| 76 | |
| 77 | /* information about database */ |
| 78 | struct sdb { |
| 79 | /* associated lua state */ |
| 80 | lua_State *L; |
| 81 | /* sqlite database handle */ |
| 82 | sqlite3 *db; |
| 83 | |
| 84 | /* sql functions stack usage */ |
| 85 | sdb_func *func; /* top SQL function being called */ |
| 86 | |
| 87 | /* references */ |
| 88 | int busy_cb; /* busy callback */ |
| 89 | int busy_udata; |
| 90 | |
| 91 | int progress_cb; /* progress handler */ |
| 92 | int progress_udata; |
| 93 | |
| 94 | int trace_cb; /* trace callback */ |
| 95 | int trace_udata; |
| 96 | |
| 97 | #if !defined(LSQLITE_OMIT_UPDATE_HOOK) || !LSQLITE_OMIT_UPDATE_HOOK |
| 98 | |
| 99 | int update_hook_cb; /* update_hook callback */ |
| 100 | int update_hook_udata; |
| 101 | |
| 102 | int commit_hook_cb; /* commit_hook callback */ |
| 103 | int commit_hook_udata; |
| 104 | |
| 105 | int rollback_hook_cb; /* rollback_hook callback */ |
| 106 | int rollback_hook_udata; |
| 107 | |
| 108 | #endif |
| 109 | }; |
| 110 | |
| 111 | static const char *sqlite_meta = ":sqlite3"; |
| 112 | static const char *sqlite_vm_meta = ":sqlite3:vm"; |
| 113 | static const char *sqlite_ctx_meta = ":sqlite3:ctx"; |
| 114 | static int sqlite_ctx_meta_ref; |
| 115 | |
| 116 | /* |
| 117 | ** ======================================================= |
| 118 | ** Database Virtual Machine Operations |
| 119 | ** ======================================================= |
| 120 | */ |
| 121 | |
| 122 | static void vm_push_column(lua_State *L, sqlite3_stmt *vm, int idx) { |
| 123 | switch (sqlite3_column_type(vm, idx)) { |
| 124 | case SQLITE_INTEGER: |
| 125 | { |
| 126 | sqlite_int64 i64 = sqlite3_column_int64(vm, idx); |
| 127 | lua_Number n = (lua_Number)i64; |
| 128 | if (n == i64) |
| 129 | lua_pushnumber(L, n); |
| 130 | else |
| 131 | lua_pushlstring(L, (const char*)sqlite3_column_text(vm, idx), sqlite3_column_bytes(vm, idx)); |
| 132 | } |
| 133 | break; |
| 134 | case SQLITE_FLOAT: |
| 135 | lua_pushnumber(L, sqlite3_column_double(vm, idx)); |
| 136 | break; |
| 137 | case SQLITE_TEXT: |
| 138 | lua_pushlstring(L, (const char*)sqlite3_column_text(vm, idx), sqlite3_column_bytes(vm, idx)); |
| 139 | break; |
| 140 | case SQLITE_BLOB: |
| 141 | lua_pushlstring(L, (const char*)sqlite3_column_blob(vm, idx), sqlite3_column_bytes(vm, idx)); |
| 142 | break; |
| 143 | case SQLITE_NULL: |
| 144 | lua_pushnil(L); |
| 145 | break; |
| 146 | default: |
| 147 | lua_pushnil(L); |
| 148 | break; |
| 149 | } |
| 150 | } |
| 151 | |
| 152 | /* virtual machine information */ |
| 153 | struct sdb_vm { |
| 154 | sdb *db; /* associated database handle */ |
| 155 | sqlite3_stmt *vm; /* virtual machine */ |
| 156 | |
| 157 | /* sqlite3_step info */ |
| 158 | int columns; /* number of columns in result */ |
| 159 | char has_values; /* true when step succeeds */ |
| 160 | |
| 161 | char temp; /* temporary vm used in db:rows */ |
| 162 | }; |
| 163 | |
| 164 | /* called with sql text on the lua stack */ |
| 165 | static sdb_vm *newvm(lua_State *L, sdb *db) { |
| 166 | sdb_vm *svm = (sdb_vm*)lua_newuserdata(L, sizeof(sdb_vm)); |
| 167 | |
| 168 | luaL_getmetatable(L, sqlite_vm_meta); |
| 169 | lua_setmetatable(L, -2); /* set metatable */ |
| 170 | |
| 171 | svm->db = db; |
| 172 | svm->columns = 0; |
| 173 | svm->has_values = 0; |
| 174 | svm->vm = NULL; |
| 175 | svm->temp = 0; |
| 176 | |
| 177 | /* add an entry on the database table: svm -> sql text */ |
| 178 | lua_pushlightuserdata(L, db); |
| 179 | lua_rawget(L, LUA_REGISTRYINDEX); |
| 180 | lua_pushlightuserdata(L, svm); |
| 181 | lua_pushvalue(L, -4); /* the sql text */ |
| 182 | lua_rawset(L, -3); |
| 183 | lua_pop(L, 1); |
| 184 | |
| 185 | return svm; |
| 186 | } |
| 187 | |
| 188 | static int cleanupvm(lua_State *L, sdb_vm *svm) { |
| 189 | /* remove entry in database table - no harm if not present in the table */ |
| 190 | lua_pushlightuserdata(L, svm->db); |
| 191 | lua_rawget(L, LUA_REGISTRYINDEX); |
| 192 | lua_pushlightuserdata(L, svm); |
| 193 | lua_pushnil(L); |
| 194 | lua_rawset(L, -3); |
| 195 | lua_pop(L, 1); |
| 196 | |
| 197 | svm->columns = 0; |
| 198 | svm->has_values = 0; |
| 199 | |
| 200 | if (!svm->vm) return 0; |
| 201 | |
| 202 | lua_pushnumber(L, sqlite3_finalize(svm->vm)); |
| 203 | svm->vm = NULL; |
| 204 | return 1; |
| 205 | } |
| 206 | |
| 207 | static int stepvm(lua_State *L, sdb_vm *svm) { |
| 208 | int result; |
| 209 | int loop_limit = 3; |
| 210 | while ( loop_limit-- ) { |
| 211 | result = sqlite3_step(svm->vm); |
| 212 | if ( result==SQLITE_ERROR ) { |
| 213 | result = sqlite3_reset (svm->vm); |
| 214 | } |
| 215 | if ( result==SQLITE_SCHEMA ) { |
| 216 | sqlite3_stmt *vn; |
| 217 | const char *sql; |
| 218 | /* recover sql text */ |
| 219 | lua_pushlightuserdata(L, svm->db); |
| 220 | lua_rawget(L, LUA_REGISTRYINDEX); |
| 221 | lua_pushlightuserdata(L, svm); |
| 222 | lua_rawget(L, -2); /* sql text */ |
| 223 | sql = luaL_checkstring(L, -1); |
| 224 | /* re-prepare */ |
| 225 | result = sqlite3_prepare(svm->db->db, sql, -1, &vn, NULL); |
| 226 | if (result != SQLITE_OK) break; |
| 227 | sqlite3_transfer_bindings(svm->vm, vn); |
| 228 | sqlite3_finalize(svm->vm); |
| 229 | svm->vm = vn; |
| 230 | lua_pop(L,2); |
| 231 | } else { |
| 232 | break; |
| 233 | } |
| 234 | } |
| 235 | return result; |
| 236 | } |
| 237 | |
| 238 | static sdb_vm *lsqlite_getvm(lua_State *L, int index) { |
| 239 | sdb_vm *svm = (sdb_vm*)luaL_checkudata(L, index, sqlite_vm_meta); |
| 240 | if (svm == NULL) luaL_argerror(L, index, "bad sqlite virtual machine"); |
| 241 | return svm; |
| 242 | } |
| 243 | |
| 244 | static sdb_vm *lsqlite_checkvm(lua_State *L, int index) { |
| 245 | sdb_vm *svm = lsqlite_getvm(L, index); |
| 246 | if (svm->vm == NULL) luaL_argerror(L, index, "attempt to use closed sqlite virtual machine"); |
| 247 | return svm; |
| 248 | } |
| 249 | |
| 250 | static int dbvm_isopen(lua_State *L) { |
| 251 | sdb_vm *svm = lsqlite_getvm(L, 1); |
| 252 | lua_pushboolean(L, svm->vm != NULL ? 1 : 0); |
| 253 | return 1; |
| 254 | } |
| 255 | |
| 256 | static int dbvm_tostring(lua_State *L) { |
| 257 | char buff[39]; |
| 258 | sdb_vm *svm = lsqlite_getvm(L, 1); |
| 259 | if (svm->vm == NULL) |
| 260 | strcpy(buff, "closed"); |
| 261 | else |
| 262 | sprintf(buff, "%p", svm); |
| 263 | lua_pushfstring(L, "sqlite virtual machine (%s)", buff); |
| 264 | return 1; |
| 265 | } |
| 266 | |
| 267 | static int dbvm_gc(lua_State *L) { |
| 268 | sdb_vm *svm = lsqlite_getvm(L, 1); |
| 269 | if (svm->vm != NULL) /* ignore closed vms */ |
| 270 | cleanupvm(L, svm); |
| 271 | return 0; |
| 272 | } |
| 273 | |
| 274 | static int dbvm_step(lua_State *L) { |
| 275 | int result; |
| 276 | sdb_vm *svm = lsqlite_checkvm(L, 1); |
| 277 | |
| 278 | result = stepvm(L, svm); |
| 279 | svm->has_values = result == SQLITE_ROW ? 1 : 0; |
| 280 | svm->columns = sqlite3_data_count(svm->vm); |
| 281 | |
| 282 | lua_pushnumber(L, result); |
| 283 | return 1; |
| 284 | } |
| 285 | |
| 286 | static int dbvm_finalize(lua_State *L) { |
| 287 | sdb_vm *svm = lsqlite_checkvm(L, 1); |
| 288 | return cleanupvm(L, svm); |
| 289 | } |
| 290 | |
| 291 | static int dbvm_reset(lua_State *L) { |
| 292 | sdb_vm *svm = lsqlite_checkvm(L, 1); |
| 293 | sqlite3_reset(svm->vm); |
| 294 | lua_pushnumber(L, sqlite3_errcode(svm->db->db)); |
| 295 | return 1; |
| 296 | } |
| 297 | |
| 298 | static void dbvm_check_contents(lua_State *L, sdb_vm *svm) { |
| 299 | if (!svm->has_values) { |
| 300 | luaL_error(L, "misuse of function"); |
| 301 | } |
| 302 | } |
| 303 | |
| 304 | static void dbvm_check_index(lua_State *L, sdb_vm *svm, int index) { |
| 305 | if (index < 0 || index >= svm->columns) { |
| 306 | luaL_error(L, "index out of range [0..%d]", svm->columns - 1); |
| 307 | } |
| 308 | } |
| 309 | |
| 310 | static void dbvm_check_bind_index(lua_State *L, sdb_vm *svm, int index) { |
| 311 | if (index < 1 || index > sqlite3_bind_parameter_count(svm->vm)) { |
| 312 | luaL_error(L, "bind index out of range [1..%d]", sqlite3_bind_parameter_count(svm->vm)); |
| 313 | } |
| 314 | } |
| 315 | |
| 316 | /* |
| 317 | ** ======================================================= |
| 318 | ** Virtual Machine - generic info |
| 319 | ** ======================================================= |
| 320 | */ |
| 321 | static int dbvm_columns(lua_State *L) { |
| 322 | sdb_vm *svm = lsqlite_checkvm(L, 1); |
| 323 | lua_pushnumber(L, sqlite3_column_count(svm->vm)); |
| 324 | return 1; |
| 325 | } |
| 326 | |
| 327 | /* |
| 328 | ** ======================================================= |
| 329 | ** Virtual Machine - getters |
| 330 | ** ======================================================= |
| 331 | */ |
| 332 | |
| 333 | static int dbvm_get_value(lua_State *L) { |
| 334 | sdb_vm *svm = lsqlite_checkvm(L, 1); |
| 335 | int index = luaL_checkint(L, 2); |
| 336 | dbvm_check_contents(L, svm); |
| 337 | dbvm_check_index(L, svm, index); |
| 338 | vm_push_column(L, svm->vm, index); |
| 339 | return 1; |
| 340 | } |
| 341 | |
| 342 | static int dbvm_get_name(lua_State *L) { |
| 343 | sdb_vm *svm = lsqlite_checkvm(L, 1); |
| 344 | int index = luaL_checknumber(L, 2); |
| 345 | dbvm_check_index(L, svm, index); |
| 346 | lua_pushstring(L, sqlite3_column_name(svm->vm, index)); |
| 347 | return 1; |
| 348 | } |
| 349 | |
| 350 | static int dbvm_get_type(lua_State *L) { |
| 351 | sdb_vm *svm = lsqlite_checkvm(L, 1); |
| 352 | int index = luaL_checknumber(L, 2); |
| 353 | dbvm_check_index(L, svm, index); |
| 354 | lua_pushstring(L, sqlite3_column_decltype(svm->vm, index)); |
| 355 | return 1; |
| 356 | } |
| 357 | |
| 358 | static int dbvm_get_values(lua_State *L) { |
| 359 | sdb_vm *svm = lsqlite_checkvm(L, 1); |
| 360 | sqlite3_stmt *vm = svm->vm; |
| 361 | int columns = svm->columns; |
| 362 | int n; |
| 363 | dbvm_check_contents(L, svm); |
| 364 | |
| 365 | lua_newtable(L); |
| 366 | for (n = 0; n < columns;) { |
| 367 | vm_push_column(L, vm, n++); |
| 368 | lua_rawseti(L, -2, n); |
| 369 | } |
| 370 | return 1; |
| 371 | } |
| 372 | |
| 373 | static int dbvm_get_names(lua_State *L) { |
| 374 | sdb_vm *svm = lsqlite_checkvm(L, 1); |
| 375 | sqlite3_stmt *vm = svm->vm; |
| 376 | int columns = sqlite3_column_count(vm); /* valid as soon as statement prepared */ |
| 377 | int n; |
| 378 | |
| 379 | lua_newtable(L); |
| 380 | for (n = 0; n < columns;) { |
| 381 | lua_pushstring(L, sqlite3_column_name(vm, n++)); |
| 382 | lua_rawseti(L, -2, n); |
| 383 | } |
| 384 | return 1; |
| 385 | } |
| 386 | |
| 387 | static int dbvm_get_types(lua_State *L) { |
| 388 | sdb_vm *svm = lsqlite_checkvm(L, 1); |
| 389 | sqlite3_stmt *vm = svm->vm; |
| 390 | int columns = sqlite3_column_count(vm); /* valid as soon as statement prepared */ |
| 391 | int n; |
| 392 | |
| 393 | lua_newtable(L); |
| 394 | for (n = 0; n < columns;) { |
| 395 | lua_pushstring(L, sqlite3_column_decltype(vm, n++)); |
| 396 | lua_rawseti(L, -2, n); |
| 397 | } |
| 398 | return 1; |
| 399 | } |
| 400 | |
| 401 | static int dbvm_get_uvalues(lua_State *L) { |
| 402 | sdb_vm *svm = lsqlite_checkvm(L, 1); |
| 403 | sqlite3_stmt *vm = svm->vm; |
| 404 | int columns = svm->columns; |
| 405 | int n; |
| 406 | dbvm_check_contents(L, svm); |
| 407 | |
| 408 | lua_checkstack(L, columns); |
| 409 | for (n = 0; n < columns; ++n) |
| 410 | vm_push_column(L, vm, n); |
| 411 | return columns; |
| 412 | } |
| 413 | |
| 414 | static int dbvm_get_unames(lua_State *L) { |
| 415 | sdb_vm *svm = lsqlite_checkvm(L, 1); |
| 416 | sqlite3_stmt *vm = svm->vm; |
| 417 | int columns = sqlite3_column_count(vm); /* valid as soon as statement prepared */ |
| 418 | int n; |
| 419 | |
| 420 | lua_checkstack(L, columns); |
| 421 | for (n = 0; n < columns; ++n) |
| 422 | lua_pushstring(L, sqlite3_column_name(vm, n)); |
| 423 | return columns; |
| 424 | } |
| 425 | |
| 426 | static int dbvm_get_utypes(lua_State *L) { |
| 427 | sdb_vm *svm = lsqlite_checkvm(L, 1); |
| 428 | sqlite3_stmt *vm = svm->vm; |
| 429 | int columns = sqlite3_column_count(vm); /* valid as soon as statement prepared */ |
| 430 | int n; |
| 431 | |
| 432 | lua_checkstack(L, columns); |
| 433 | for (n = 0; n < columns; ++n) |
| 434 | lua_pushstring(L, sqlite3_column_decltype(vm, n)); |
| 435 | return columns; |
| 436 | } |
| 437 | |
| 438 | static int dbvm_get_named_values(lua_State *L) { |
| 439 | sdb_vm *svm = lsqlite_checkvm(L, 1); |
| 440 | sqlite3_stmt *vm = svm->vm; |
| 441 | int columns = svm->columns; |
| 442 | int n; |
| 443 | dbvm_check_contents(L, svm); |
| 444 | |
| 445 | lua_newtable(L); |
| 446 | for (n = 0; n < columns; ++n) { |
| 447 | lua_pushstring(L, sqlite3_column_name(vm, n)); |
| 448 | vm_push_column(L, vm, n); |
| 449 | lua_rawset(L, -3); |
| 450 | } |
| 451 | return 1; |
| 452 | } |
| 453 | |
| 454 | static int dbvm_get_named_types(lua_State *L) { |
| 455 | sdb_vm *svm = lsqlite_checkvm(L, 1); |
| 456 | sqlite3_stmt *vm = svm->vm; |
| 457 | int columns = sqlite3_column_count(vm); |
| 458 | int n; |
| 459 | |
| 460 | lua_newtable(L); |
| 461 | for (n = 0; n < columns; ++n) { |
| 462 | lua_pushstring(L, sqlite3_column_name(vm, n)); |
| 463 | lua_pushstring(L, sqlite3_column_decltype(vm, n)); |
| 464 | lua_rawset(L, -3); |
| 465 | } |
| 466 | return 1; |
| 467 | } |
| 468 | |
| 469 | /* |
| 470 | ** ======================================================= |
| 471 | ** Virtual Machine - Bind |
| 472 | ** ======================================================= |
| 473 | */ |
| 474 | |
| 475 | static int dbvm_bind_index(lua_State *L, sqlite3_stmt *vm, int index, int lindex) { |
| 476 | switch (lua_type(L, lindex)) { |
| 477 | case LUA_TSTRING: |
| 478 | return sqlite3_bind_text(vm, index, lua_tostring(L, lindex), lua_strlen(L, lindex), SQLITE_TRANSIENT); |
| 479 | case LUA_TNUMBER: |
| 480 | return sqlite3_bind_double(vm, index, lua_tonumber(L, lindex)); |
| 481 | case LUA_TBOOLEAN: |
| 482 | return sqlite3_bind_int(vm, index, lua_toboolean(L, lindex) ? 1 : 0); |
| 483 | case LUA_TNONE: |
| 484 | case LUA_TNIL: |
| 485 | return sqlite3_bind_null(vm, index); |
| 486 | default: |
| 487 | luaL_error(L, "index (%d) - invalid data type for bind (%s)", index, lua_typename(L, lua_type(L, lindex))); |
| 488 | return SQLITE_MISUSE; /*!*/ |
| 489 | } |
| 490 | } |
| 491 | |
| 492 | |
| 493 | static int dbvm_bind_parameter_count(lua_State *L) { |
| 494 | sdb_vm *svm = lsqlite_checkvm(L, 1); |
| 495 | lua_pushnumber(L, sqlite3_bind_parameter_count(svm->vm)); |
| 496 | return 1; |
| 497 | } |
| 498 | |
| 499 | static int dbvm_bind_parameter_name(lua_State *L) { |
| 500 | sdb_vm *svm = lsqlite_checkvm(L, 1); |
| 501 | int index = luaL_checknumber(L, 2); |
| 502 | dbvm_check_bind_index(L, svm, index); |
| 503 | lua_pushstring(L, sqlite3_bind_parameter_name(svm->vm, index)); |
| 504 | return 1; |
| 505 | } |
| 506 | |
| 507 | static int dbvm_bind(lua_State *L) { |
| 508 | sdb_vm *svm = lsqlite_checkvm(L, 1); |
| 509 | sqlite3_stmt *vm = svm->vm; |
| 510 | int index = luaL_checkint(L, 2); |
| 511 | int result; |
| 512 | |
| 513 | dbvm_check_bind_index(L, svm, index); |
| 514 | result = dbvm_bind_index(L, vm, index, 3); |
| 515 | |
| 516 | lua_pushnumber(L, result); |
| 517 | return 1; |
| 518 | } |
| 519 | |
| 520 | static int dbvm_bind_blob(lua_State *L) { |
| 521 | sdb_vm *svm = lsqlite_checkvm(L, 1); |
| 522 | int index = luaL_checkint(L, 2); |
| 523 | const char *value = luaL_checkstring(L, 3); |
| 524 | int len = lua_strlen(L, 3); |
| 525 | |
| 526 | lua_pushnumber(L, sqlite3_bind_blob(svm->vm, index, value, len, SQLITE_TRANSIENT)); |
| 527 | return 1; |
| 528 | } |
| 529 | |
| 530 | static int dbvm_bind_values(lua_State *L) { |
| 531 | sdb_vm *svm = lsqlite_checkvm(L, 1); |
| 532 | sqlite3_stmt *vm = svm->vm; |
| 533 | int top = lua_gettop(L); |
| 534 | int result, n; |
| 535 | |
| 536 | if (top - 1 != sqlite3_bind_parameter_count(vm)) |
| 537 | luaL_error(L, |
| 538 | "incorrect number of parameters to bind (%d given, %d to bind)", |
| 539 | top - 1, |
| 540 | sqlite3_bind_parameter_count(vm) |
| 541 | ); |
| 542 | |
| 543 | for (n = 2; n <= top; ++n) { |
| 544 | if ((result = dbvm_bind_index(L, vm, n - 1, n)) != SQLITE_OK) { |
| 545 | lua_pushnumber(L, result); |
| 546 | return 1; |
| 547 | } |
| 548 | } |
| 549 | |
| 550 | lua_pushnumber(L, SQLITE_OK); |
| 551 | return 1; |
| 552 | } |
| 553 | |
| 554 | static int dbvm_bind_names(lua_State *L) { |
| 555 | sdb_vm *svm = lsqlite_checkvm(L, 1); |
| 556 | sqlite3_stmt *vm = svm->vm; |
| 557 | int count = sqlite3_bind_parameter_count(vm); |
| 558 | const char *name; |
| 559 | int result, n; |
| 560 | luaL_checktype(L, 2, LUA_TTABLE); |
| 561 | |
| 562 | for (n = 1; n <= count; ++n) { |
| 563 | name = sqlite3_bind_parameter_name(vm, n); |
| 564 | if (name && (name[0] == ':' || name[0] == '$')) { |
| 565 | lua_pushstring(L, ++name); |
| 566 | lua_gettable(L, 2); |
| 567 | result = dbvm_bind_index(L, vm, n, -1); |
| 568 | lua_pop(L, 1); |
| 569 | } |
| 570 | else { |
| 571 | lua_pushnumber(L, n); |
| 572 | lua_gettable(L, 2); |
| 573 | result = dbvm_bind_index(L, vm, n, -1); |
| 574 | lua_pop(L, 1); |
| 575 | } |
| 576 | |
| 577 | if (result != SQLITE_OK) { |
| 578 | lua_pushnumber(L, result); |
| 579 | return 1; |
| 580 | } |
| 581 | } |
| 582 | |
| 583 | lua_pushnumber(L, SQLITE_OK); |
| 584 | return 1; |
| 585 | } |
| 586 | |
| 587 | /* |
| 588 | ** ======================================================= |
| 589 | ** Database (internal management) |
| 590 | ** ======================================================= |
| 591 | */ |
| 592 | |
| 593 | /* |
| 594 | ** When creating database handles, always creates a `closed' database handle |
| 595 | ** before opening the actual database; so, if there is a memory error, the |
| 596 | ** database is not left opened. |
| 597 | ** |
| 598 | ** Creates a new 'table' and leaves it in the stack |
| 599 | */ |
| 600 | static sdb *newdb (lua_State *L) { |
| 601 | sdb *db = (sdb*)lua_newuserdata(L, sizeof(sdb)); |
| 602 | db->L = L; |
| 603 | db->db = NULL; /* database handle is currently `closed' */ |
| 604 | db->func = NULL; |
| 605 | |
| 606 | db->busy_cb = |
| 607 | db->busy_udata = |
| 608 | db->progress_cb = |
| 609 | db->progress_udata = |
| 610 | db->trace_cb = |
| 611 | db->trace_udata = |
| 612 | #if !defined(LSQLITE_OMIT_UPDATE_HOOK) || !LSQLITE_OMIT_UPDATE_HOOK |
| 613 | db->update_hook_cb = |
| 614 | db->update_hook_udata = |
| 615 | db->commit_hook_cb = |
| 616 | db->commit_hook_udata = |
| 617 | db->rollback_hook_cb = |
| 618 | db->rollback_hook_udata = |
| 619 | #endif |
| 620 | LUA_NOREF; |
| 621 | |
| 622 | luaL_getmetatable(L, sqlite_meta); |
| 623 | lua_setmetatable(L, -2); /* set metatable */ |
| 624 | |
| 625 | /* to keep track of 'open' virtual machines */ |
| 626 | lua_pushlightuserdata(L, db); |
| 627 | lua_newtable(L); |
| 628 | lua_rawset(L, LUA_REGISTRYINDEX); |
| 629 | |
| 630 | return db; |
| 631 | } |
| 632 | |
| 633 | static int cleanupdb(lua_State *L, sdb *db) { |
| 634 | sdb_func *func; |
| 635 | sdb_func *func_next; |
| 636 | int top; |
| 637 | int result; |
| 638 | |
| 639 | /* free associated virtual machines */ |
| 640 | lua_pushlightuserdata(L, db); |
| 641 | lua_rawget(L, LUA_REGISTRYINDEX); |
| 642 | |
| 643 | /* close all used handles */ |
| 644 | top = lua_gettop(L); |
| 645 | lua_pushnil(L); |
| 646 | while (lua_next(L, -2)) { |
| 647 | sdb_vm *svm = (sdb_vm *)lua_touserdata(L, -2); /* key: vm; val: sql text */ |
| 648 | cleanupvm(L, svm); |
| 649 | |
| 650 | lua_settop(L, top); |
| 651 | lua_pushnil(L); |
| 652 | } |
| 653 | |
| 654 | lua_pop(L, 1); /* pop vm table */ |
| 655 | |
| 656 | /* remove entry in lua registry table */ |
| 657 | lua_pushlightuserdata(L, db); |
| 658 | lua_pushnil(L); |
| 659 | lua_rawset(L, LUA_REGISTRYINDEX); |
| 660 | |
| 661 | /* 'free' all references */ |
| 662 | luaL_unref(L, LUA_REGISTRYINDEX, db->busy_cb); |
| 663 | luaL_unref(L, LUA_REGISTRYINDEX, db->busy_udata); |
| 664 | luaL_unref(L, LUA_REGISTRYINDEX, db->progress_cb); |
| 665 | luaL_unref(L, LUA_REGISTRYINDEX, db->progress_udata); |
| 666 | luaL_unref(L, LUA_REGISTRYINDEX, db->trace_cb); |
| 667 | luaL_unref(L, LUA_REGISTRYINDEX, db->trace_udata); |
| 668 | #if !defined(LSQLITE_OMIT_UPDATE_HOOK) || !LSQLITE_OMIT_UPDATE_HOOK |
| 669 | luaL_unref(L, LUA_REGISTRYINDEX, db->update_hook_cb); |
| 670 | luaL_unref(L, LUA_REGISTRYINDEX, db->update_hook_udata); |
| 671 | luaL_unref(L, LUA_REGISTRYINDEX, db->commit_hook_cb); |
| 672 | luaL_unref(L, LUA_REGISTRYINDEX, db->commit_hook_udata); |
| 673 | luaL_unref(L, LUA_REGISTRYINDEX, db->rollback_hook_cb); |
| 674 | luaL_unref(L, LUA_REGISTRYINDEX, db->rollback_hook_udata); |
| 675 | #endif |
| 676 | |
| 677 | /* close database */ |
| 678 | result = sqlite3_close(db->db); |
| 679 | db->db = NULL; |
| 680 | |
| 681 | /* free associated memory with created functions */ |
| 682 | func = db->func; |
| 683 | while (func) { |
| 684 | func_next = func->next; |
| 685 | luaL_unref(L, LUA_REGISTRYINDEX, func->fn_step); |
| 686 | luaL_unref(L, LUA_REGISTRYINDEX, func->fn_finalize); |
| 687 | luaL_unref(L, LUA_REGISTRYINDEX, func->udata); |
| 688 | free(func); |
| 689 | func = func_next; |
| 690 | } |
| 691 | db->func = NULL; |
| 692 | return result; |
| 693 | } |
| 694 | |
| 695 | static sdb *lsqlite_getdb(lua_State *L, int index) { |
| 696 | sdb *db = (sdb*)luaL_checkudata(L, index, sqlite_meta); |
| 697 | if (db == NULL) luaL_typerror(L, index, "sqlite database"); |
| 698 | return db; |
| 699 | } |
| 700 | |
| 701 | static sdb *lsqlite_checkdb(lua_State *L, int index) { |
| 702 | sdb *db = lsqlite_getdb(L, index); |
| 703 | if (db->db == NULL) luaL_argerror(L, index, "attempt to use closed sqlite database"); |
| 704 | return db; |
| 705 | } |
| 706 | |
| 707 | |
| 708 | /* |
| 709 | ** ======================================================= |
| 710 | ** User Defined Functions - Context Methods |
| 711 | ** ======================================================= |
| 712 | */ |
| 713 | typedef struct { |
| 714 | sqlite3_context *ctx; |
| 715 | int ud; |
| 716 | } lcontext; |
| 717 | |
| 718 | static lcontext *lsqlite_make_context(lua_State *L) { |
| 719 | lcontext *ctx = (lcontext*)lua_newuserdata(L, sizeof(lcontext)); |
| 720 | lua_rawgeti(L, LUA_REGISTRYINDEX, sqlite_ctx_meta_ref); |
| 721 | lua_setmetatable(L, -2); |
| 722 | ctx->ctx = NULL; |
| 723 | ctx->ud = LUA_NOREF; |
| 724 | return ctx; |
| 725 | } |
| 726 | |
| 727 | static lcontext *lsqlite_getcontext(lua_State *L, int index) { |
| 728 | lcontext *ctx = (lcontext*)luaL_checkudata(L, index, sqlite_ctx_meta); |
| 729 | if (ctx == NULL) luaL_typerror(L, index, "sqlite context"); |
| 730 | return ctx; |
| 731 | } |
| 732 | |
| 733 | static lcontext *lsqlite_checkcontext(lua_State *L, int index) { |
| 734 | lcontext *ctx = lsqlite_getcontext(L, index); |
| 735 | if (ctx->ctx == NULL) luaL_argerror(L, index, "invalid sqlite context"); |
| 736 | return ctx; |
| 737 | } |
| 738 | |
| 739 | static int lcontext_tostring(lua_State *L) { |
| 740 | char buff[39]; |
| 741 | lcontext *ctx = lsqlite_getcontext(L, 1); |
| 742 | if (ctx->ctx == NULL) |
| 743 | strcpy(buff, "closed"); |
| 744 | else |
| 745 | sprintf(buff, "%p", ctx->ctx); |
| 746 | lua_pushfstring(L, "sqlite function context (%s)", buff); |
| 747 | return 1; |
| 748 | } |
| 749 | |
| 750 | static void lcontext_check_aggregate(lua_State *L, lcontext *ctx) { |
| 751 | sdb_func *func = (sdb_func*)sqlite3_user_data(ctx->ctx); |
| 752 | if (!func->aggregate) { |
| 753 | luaL_error(L, "attempt to call aggregate method from scalar function"); |
| 754 | } |
| 755 | } |
| 756 | |
| 757 | static int lcontext_user_data(lua_State *L) { |
| 758 | lcontext *ctx = lsqlite_checkcontext(L, 1); |
| 759 | sdb_func *func = (sdb_func*)sqlite3_user_data(ctx->ctx); |
| 760 | lua_rawgeti(L, LUA_REGISTRYINDEX, func->udata); |
| 761 | return 1; |
| 762 | } |
| 763 | |
| 764 | static int lcontext_get_aggregate_context(lua_State *L) { |
| 765 | lcontext *ctx = lsqlite_checkcontext(L, 1); |
| 766 | lcontext_check_aggregate(L, ctx); |
| 767 | lua_rawgeti(L, LUA_REGISTRYINDEX, ctx->ud); |
| 768 | return 1; |
| 769 | } |
| 770 | |
| 771 | static int lcontext_set_aggregate_context(lua_State *L) { |
| 772 | lcontext *ctx = lsqlite_checkcontext(L, 1); |
| 773 | lcontext_check_aggregate(L, ctx); |
| 774 | lua_settop(L, 2); |
| 775 | luaL_unref(L, LUA_REGISTRYINDEX, ctx->ud); |
| 776 | ctx->ud = luaL_ref(L, LUA_REGISTRYINDEX); |
| 777 | return 0; |
| 778 | } |
| 779 | |
| 780 | static int lcontext_aggregate_count(lua_State *L) { |
| 781 | lcontext *ctx = lsqlite_checkcontext(L, 1); |
| 782 | lcontext_check_aggregate(L, ctx); |
| 783 | lua_pushnumber(L, sqlite3_aggregate_count(ctx->ctx)); |
| 784 | return 1; |
| 785 | } |
| 786 | |
| 787 | #if 0 |
| 788 | void *sqlite3_get_auxdata(sqlite3_context*, int); |
| 789 | void sqlite3_set_auxdata(sqlite3_context*, int, void*, void (*)(void*)); |
| 790 | #endif |
| 791 | |
| 792 | static int lcontext_result(lua_State *L) { |
| 793 | lcontext *ctx = lsqlite_checkcontext(L, 1); |
| 794 | switch (lua_type(L, 2)) { |
| 795 | case LUA_TNUMBER: |
| 796 | sqlite3_result_double(ctx->ctx, luaL_checknumber(L, 2)); |
| 797 | break; |
| 798 | case LUA_TSTRING: |
| 799 | sqlite3_result_text(ctx->ctx, luaL_checkstring(L, 2), lua_strlen(L, 2), SQLITE_TRANSIENT); |
| 800 | break; |
| 801 | case LUA_TNIL: |
| 802 | case LUA_TNONE: |
| 803 | sqlite3_result_null(ctx->ctx); |
| 804 | break; |
| 805 | default: |
| 806 | luaL_error(L, "invalid result type %s", lua_typename(L, 2)); |
| 807 | break; |
| 808 | } |
| 809 | |
| 810 | return 0; |
| 811 | } |
| 812 | |
| 813 | static int lcontext_result_blob(lua_State *L) { |
| 814 | lcontext *ctx = lsqlite_checkcontext(L, 1); |
| 815 | const char *blob = luaL_checkstring(L, 2); |
| 816 | int size = lua_strlen(L, 2); |
| 817 | sqlite3_result_blob(ctx->ctx, (const void*)blob, size, SQLITE_TRANSIENT); |
| 818 | return 0; |
| 819 | } |
| 820 | |
| 821 | static int lcontext_result_double(lua_State *L) { |
| 822 | lcontext *ctx = lsqlite_checkcontext(L, 1); |
| 823 | double d = luaL_checknumber(L, 2); |
| 824 | sqlite3_result_double(ctx->ctx, d); |
| 825 | return 0; |
| 826 | } |
| 827 | |
| 828 | static int lcontext_result_error(lua_State *L) { |
| 829 | lcontext *ctx = lsqlite_checkcontext(L, 1); |
| 830 | const char *err = luaL_checkstring(L, 2); |
| 831 | int size = lua_strlen(L, 2); |
| 832 | sqlite3_result_error(ctx->ctx, err, size); |
| 833 | return 0; |
| 834 | } |
| 835 | |
| 836 | static int lcontext_result_int(lua_State *L) { |
| 837 | lcontext *ctx = lsqlite_checkcontext(L, 1); |
| 838 | int i = luaL_checkint(L, 2); |
| 839 | sqlite3_result_int(ctx->ctx, i); |
| 840 | return 0; |
| 841 | } |
| 842 | |
| 843 | static int lcontext_result_null(lua_State *L) { |
| 844 | lcontext *ctx = lsqlite_checkcontext(L, 1); |
| 845 | sqlite3_result_null(ctx->ctx); |
| 846 | return 0; |
| 847 | } |
| 848 | |
| 849 | static int lcontext_result_text(lua_State *L) { |
| 850 | lcontext *ctx = lsqlite_checkcontext(L, 1); |
| 851 | const char *text = luaL_checkstring(L, 2); |
| 852 | int size = lua_strlen(L, 2); |
| 853 | sqlite3_result_text(ctx->ctx, text, size, SQLITE_TRANSIENT); |
| 854 | return 0; |
| 855 | } |
| 856 | |
| 857 | /* |
| 858 | ** ======================================================= |
| 859 | ** Database Methods |
| 860 | ** ======================================================= |
| 861 | */ |
| 862 | |
| 863 | static int db_isopen(lua_State *L) { |
| 864 | sdb *db = lsqlite_getdb(L, 1); |
| 865 | lua_pushboolean(L, db->db != NULL ? 1 : 0); |
| 866 | return 1; |
| 867 | } |
| 868 | |
| 869 | static int db_last_insert_rowid(lua_State *L) { |
| 870 | sdb *db = lsqlite_checkdb(L, 1); |
| 871 | /* conversion warning: int64 -> luaNumber */ |
| 872 | sqlite_int64 rowid = sqlite3_last_insert_rowid(db->db); |
| 873 | lua_Number n = (lua_Number)rowid; |
| 874 | if (n == rowid) |
| 875 | lua_pushnumber(L, n); |
| 876 | else |
| 877 | lua_pushfstring(L, "%ll", rowid); |
| 878 | return 1; |
| 879 | } |
| 880 | |
| 881 | static int db_changes(lua_State *L) { |
| 882 | sdb *db = lsqlite_checkdb(L, 1); |
| 883 | lua_pushnumber(L, sqlite3_changes(db->db)); |
| 884 | return 1; |
| 885 | } |
| 886 | |
| 887 | static int db_total_changes(lua_State *L) { |
| 888 | sdb *db = lsqlite_checkdb(L, 1); |
| 889 | lua_pushnumber(L, sqlite3_total_changes(db->db)); |
| 890 | return 1; |
| 891 | } |
| 892 | |
| 893 | static int db_errcode(lua_State *L) { |
| 894 | sdb *db = lsqlite_checkdb(L, 1); |
| 895 | lua_pushnumber(L, sqlite3_errcode(db->db)); |
| 896 | return 1; |
| 897 | } |
| 898 | |
| 899 | static int db_errmsg(lua_State *L) { |
| 900 | sdb *db = lsqlite_checkdb(L, 1); |
| 901 | lua_pushstring(L, sqlite3_errmsg(db->db)); |
| 902 | return 1; |
| 903 | } |
| 904 | |
| 905 | static int db_interrupt(lua_State *L) { |
| 906 | sdb *db = lsqlite_checkdb(L, 1); |
| 907 | sqlite3_interrupt(db->db); |
| 908 | return 0; |
| 909 | } |
| 910 | |
| 911 | /* |
| 912 | ** Registering SQL functions: |
| 913 | */ |
| 914 | |
| 915 | static void db_push_value(lua_State *L, sqlite3_value *value) { |
| 916 | switch (sqlite3_value_type(value)) { |
| 917 | case SQLITE_TEXT: |
| 918 | lua_pushlstring(L, (const char*)sqlite3_value_text(value), sqlite3_value_bytes(value)); |
| 919 | break; |
| 920 | |
| 921 | case SQLITE_INTEGER: |
| 922 | { |
| 923 | sqlite_int64 i64 = sqlite3_value_int64(value); |
| 924 | lua_Number n = (lua_Number)i64; |
| 925 | if (n == i64) |
| 926 | lua_pushnumber(L, n); |
| 927 | else |
| 928 | lua_pushlstring(L, (const char*)sqlite3_value_text(value), sqlite3_value_bytes(value)); |
| 929 | } |
| 930 | break; |
| 931 | |
| 932 | case SQLITE_FLOAT: |
| 933 | lua_pushnumber(L, sqlite3_value_double(value)); |
| 934 | break; |
| 935 | |
| 936 | case SQLITE_BLOB: |
| 937 | lua_pushlstring(L, (const char*)sqlite3_value_blob(value), sqlite3_value_bytes(value)); |
| 938 | break; |
| 939 | |
| 940 | case SQLITE_NULL: |
| 941 | lua_pushnil(L); |
| 942 | break; |
| 943 | |
| 944 | default: |
| 945 | /* things done properly (SQLite + Lua SQLite) |
| 946 | ** this should never happen */ |
| 947 | lua_pushnil(L); |
| 948 | break; |
| 949 | } |
| 950 | } |
| 951 | |
| 952 | /* |
| 953 | ** callback functions used when calling registered sql functions |
| 954 | */ |
| 955 | |
| 956 | /* scalar function to be called |
| 957 | ** callback params: context, values... */ |
| 958 | static void db_sql_normal_function(sqlite3_context *context, int argc, sqlite3_value **argv) { |
| 959 | sdb_func *func = (sdb_func*)sqlite3_user_data(context); |
| 960 | lua_State *L = func->db->L; |
| 961 | int n; |
| 962 | lcontext *ctx; |
| 963 | |
| 964 | int top = lua_gettop(L); |
| 965 | |
| 966 | /* ensure there is enough space in the stack */ |
| 967 | lua_checkstack(L, argc + 3); |
| 968 | |
| 969 | lua_rawgeti(L, LUA_REGISTRYINDEX, func->fn_step); /* function to call */ |
| 970 | |
| 971 | if (!func->aggregate) { |
| 972 | ctx = lsqlite_make_context(L); /* push context - used to set results */ |
| 973 | } |
| 974 | else { |
| 975 | /* reuse context userdata value */ |
| 976 | void *p = sqlite3_aggregate_context(context, 1); |
| 977 | /* i think it is OK to use assume that using a light user data |
| 978 | ** as an entry on LUA REGISTRY table will be unique */ |
| 979 | lua_pushlightuserdata(L, p); |
| 980 | lua_rawget(L, LUA_REGISTRYINDEX); /* context table */ |
| 981 | |
| 982 | if (lua_isnil(L, -1)) { /* not yet created? */ |
| 983 | lua_pop(L, 1); |
| 984 | ctx = lsqlite_make_context(L); |
| 985 | lua_pushlightuserdata(L, p); |
| 986 | lua_pushvalue(L, -2); |
| 987 | lua_rawset(L, LUA_REGISTRYINDEX); |
| 988 | } |
| 989 | else |
| 990 | ctx = lsqlite_getcontext(L, -1); |
| 991 | } |
| 992 | |
| 993 | /* push params */ |
| 994 | for (n = 0; n < argc; ++n) { |
| 995 | db_push_value(L, argv[n]); |
| 996 | } |
| 997 | |
| 998 | /* set context */ |
| 999 | ctx->ctx = context; |
| 1000 | |
| 1001 | if (lua_pcall(L, argc + 1, 0, 0)) { |
| 1002 | const char *errmsg = lua_tostring(L, -1); |
| 1003 | int size = lua_strlen(L, -1); |
| 1004 | sqlite3_result_error(context, errmsg, size); |
| 1005 | } |
| 1006 | |
| 1007 | /* invalidate context */ |
| 1008 | ctx->ctx = NULL; |
| 1009 | |
| 1010 | if (!func->aggregate) { |
| 1011 | luaL_unref(L, LUA_REGISTRYINDEX, ctx->ud); |
| 1012 | } |
| 1013 | |
| 1014 | lua_settop(L, top); |
| 1015 | } |
| 1016 | |
| 1017 | static void db_sql_finalize_function(sqlite3_context *context) { |
| 1018 | sdb_func *func = (sdb_func*)sqlite3_user_data(context); |
| 1019 | lua_State *L = func->db->L; |
| 1020 | void *p = sqlite3_aggregate_context(context, 1); /* minimal mem usage */ |
| 1021 | lcontext *ctx; |
| 1022 | int top = lua_gettop(L); |
| 1023 | |
| 1024 | lua_rawgeti(L, LUA_REGISTRYINDEX, func->fn_finalize); /* function to call */ |
| 1025 | |
| 1026 | /* i think it is OK to use assume that using a light user data |
| 1027 | ** as an entry on LUA REGISTRY table will be unique */ |
| 1028 | lua_pushlightuserdata(L, p); |
| 1029 | lua_rawget(L, LUA_REGISTRYINDEX); /* context table */ |
| 1030 | |
| 1031 | if (lua_isnil(L, -1)) { /* not yet created? - shouldn't happen in finalize function */ |
| 1032 | lua_pop(L, 1); |
| 1033 | ctx = lsqlite_make_context(L); |
| 1034 | lua_pushlightuserdata(L, p); |
| 1035 | lua_pushvalue(L, -2); |
| 1036 | lua_rawset(L, LUA_REGISTRYINDEX); |
| 1037 | } |
| 1038 | else |
| 1039 | ctx = lsqlite_getcontext(L, -1); |
| 1040 | |
| 1041 | /* set context */ |
| 1042 | ctx->ctx = context; |
| 1043 | |
| 1044 | if (lua_pcall(L, 1, 0, 0)) { |
| 1045 | sqlite3_result_error(context, lua_tostring(L, -1), -1); |
| 1046 | } |
| 1047 | |
| 1048 | /* invalidate context */ |
| 1049 | ctx->ctx = NULL; |
| 1050 | |
| 1051 | /* cleanup context */ |
| 1052 | luaL_unref(L, LUA_REGISTRYINDEX, ctx->ud); |
| 1053 | /* remove it from registry */ |
| 1054 | lua_pushlightuserdata(L, p); |
| 1055 | lua_pushnil(L); |
| 1056 | lua_rawset(L, LUA_REGISTRYINDEX); |
| 1057 | |
| 1058 | lua_settop(L, top); |
| 1059 | } |
| 1060 | |
| 1061 | /* |
| 1062 | ** Register a normal function |
| 1063 | ** Params: db, function name, number arguments, [ callback | step, finalize], user data |
| 1064 | ** Returns: true on sucess |
| 1065 | ** |
| 1066 | ** Normal function: |
| 1067 | ** Params: context, params |
| 1068 | ** |
| 1069 | ** Aggregate function: |
| 1070 | ** Params of step: context, params |
| 1071 | ** Params of finalize: context |
| 1072 | */ |
| 1073 | static int db_register_function(lua_State *L, int aggregate) { |
| 1074 | sdb *db = lsqlite_checkdb(L, 1); |
| 1075 | const char *name; |
| 1076 | int args; |
| 1077 | int result; |
| 1078 | sdb_func *func; |
| 1079 | |
| 1080 | /* safety measure */ |
| 1081 | if (aggregate) aggregate = 1; |
| 1082 | |
| 1083 | name = luaL_checkstring(L, 2); |
| 1084 | args = luaL_checkint(L, 3); |
| 1085 | luaL_checktype(L, 4, LUA_TFUNCTION); |
| 1086 | if (aggregate) luaL_checktype(L, 5, LUA_TFUNCTION); |
| 1087 | |
| 1088 | /* maybe an alternative way to allocate memory should be used/avoided */ |
| 1089 | func = (sdb_func*)malloc(sizeof(sdb_func)); |
| 1090 | if (func == NULL) { |
| 1091 | luaL_error(L, "out of memory"); |
| 1092 | } |
| 1093 | |
| 1094 | result = sqlite3_create_function( |
| 1095 | db->db, name, args, SQLITE_UTF8, func, |
| 1096 | aggregate ? NULL : db_sql_normal_function, |
| 1097 | aggregate ? db_sql_normal_function : NULL, |
| 1098 | aggregate ? db_sql_finalize_function : NULL |
| 1099 | ); |
| 1100 | |
| 1101 | if (result == SQLITE_OK) { |
| 1102 | /* safety measures for userdata field to be present in the stack */ |
| 1103 | lua_settop(L, 5 + aggregate); |
| 1104 | |
| 1105 | /* save registered function in db function list */ |
| 1106 | func->db = db; |
| 1107 | func->aggregate = aggregate; |
| 1108 | func->next = db->func; |
| 1109 | db->func = func; |
| 1110 | |
| 1111 | /* save the setp/normal function callback */ |
| 1112 | lua_pushvalue(L, 4); |
| 1113 | func->fn_step = luaL_ref(L, LUA_REGISTRYINDEX); |
| 1114 | /* save user data */ |
| 1115 | lua_pushvalue(L, 5+aggregate); |
| 1116 | func->udata = luaL_ref(L, LUA_REGISTRYINDEX); |
| 1117 | |
| 1118 | if (aggregate) { |
| 1119 | lua_pushvalue(L, 5); |
| 1120 | func->fn_finalize = luaL_ref(L, LUA_REGISTRYINDEX); |
| 1121 | } |
| 1122 | else |
| 1123 | func->fn_finalize = LUA_NOREF; |
| 1124 | } |
| 1125 | else { |
| 1126 | /* free allocated memory */ |
| 1127 | free(func); |
| 1128 | } |
| 1129 | |
| 1130 | lua_pushboolean(L, result == SQLITE_OK ? 1 : 0); |
| 1131 | return 1; |
| 1132 | } |
| 1133 | |
| 1134 | static int db_create_function(lua_State *L) { |
| 1135 | return db_register_function(L, 0); |
| 1136 | } |
| 1137 | |
| 1138 | static int db_create_aggregate(lua_State *L) { |
| 1139 | return db_register_function(L, 1); |
| 1140 | } |
| 1141 | |
| 1142 | /* create_collation; contributed by Thomas Lauer |
| 1143 | */ |
| 1144 | |
| 1145 | typedef struct { |
| 1146 | lua_State *L; |
| 1147 | int ref; |
| 1148 | } scc; |
| 1149 | |
| 1150 | static int collwrapper(scc *co,int l1,const void *p1, |
| 1151 | int l2,const void *p2) { |
| 1152 | int res=0; |
| 1153 | lua_State *L=co->L; |
| 1154 | lua_rawgeti(L,LUA_REGISTRYINDEX,co->ref); |
| 1155 | lua_pushlstring(L,(const char*)p1,l1); |
| 1156 | lua_pushlstring(L,(const char*)p2,l2); |
| 1157 | if (lua_pcall(L,2,1,0)==0) res=lua_tonumber(L,-1); |
| 1158 | lua_pop(L,1); |
| 1159 | return res; |
| 1160 | } |
| 1161 | |
| 1162 | static void collfree(scc *co) { |
| 1163 | if (co) { |
| 1164 | luaL_unref(co->L,LUA_REGISTRYINDEX,co->ref); |
| 1165 | free(co); |
| 1166 | } |
| 1167 | } |
| 1168 | |
| 1169 | static int db_create_collation(lua_State *L) { |
| 1170 | sdb *db=lsqlite_checkdb(L,1); |
| 1171 | const char *collname=luaL_checkstring(L,2); |
| 1172 | scc *co=NULL; |
| 1173 | int (*collfunc)(scc *,int,const void *,int,const void *)=NULL; |
| 1174 | lua_settop(L,3); /* default args to nil, and exclude extras */ |
| 1175 | if (lua_isfunction(L,3)) collfunc=collwrapper; |
| 1176 | else if (!lua_isnil(L,3)) |
| 1177 | luaL_error(L,"create_collation: function or nil expected"); |
| 1178 | if (collfunc != NULL) { |
| 1179 | co=(scc *)malloc(sizeof(scc)); /* userdata is a no-no as it |
| 1180 | will be garbage-collected */ |
| 1181 | if (co) { |
| 1182 | co->L=L; |
| 1183 | /* lua_settop(L,3) above means we don't need: lua_pushvalue(L,3); */ |
| 1184 | co->ref=luaL_ref(L,LUA_REGISTRYINDEX); |
| 1185 | } |
| 1186 | else luaL_error(L,"create_collation: could not allocate callback"); |
| 1187 | } |
| 1188 | sqlite3_create_collation_v2(db->db, collname, SQLITE_UTF8, |
| 1189 | (void *)co, |
| 1190 | (int(*)(void*,int,const void*,int,const void*))collfunc, |
| 1191 | (void(*)(void*))collfree); |
| 1192 | return 0; |
| 1193 | } |
| 1194 | |
| 1195 | /* |
| 1196 | ** trace callback: |
| 1197 | ** Params: database, callback function, userdata |
| 1198 | ** |
| 1199 | ** callback function: |
| 1200 | ** Params: userdata, sql |
| 1201 | */ |
| 1202 | static void db_trace_callback(void *user, const char *sql) { |
| 1203 | sdb *db = (sdb*)user; |
| 1204 | lua_State *L = db->L; |
| 1205 | int top = lua_gettop(L); |
| 1206 | |
| 1207 | /* setup lua callback call */ |
| 1208 | lua_rawgeti(L, LUA_REGISTRYINDEX, db->trace_cb); /* get callback */ |
| 1209 | lua_rawgeti(L, LUA_REGISTRYINDEX, db->trace_udata); /* get callback user data */ |
| 1210 | lua_pushstring(L, sql); /* traced sql statement */ |
| 1211 | |
| 1212 | /* call lua function */ |
| 1213 | lua_pcall(L, 2, 0, 0); |
| 1214 | /* ignore any error generated by this function */ |
| 1215 | |
| 1216 | lua_settop(L, top); |
| 1217 | } |
| 1218 | |
| 1219 | static int db_trace(lua_State *L) { |
| 1220 | sdb *db = lsqlite_checkdb(L, 1); |
| 1221 | |
| 1222 | if (lua_gettop(L) < 2 || lua_isnil(L, 2)) { |
| 1223 | luaL_unref(L, LUA_REGISTRYINDEX, db->trace_cb); |
| 1224 | luaL_unref(L, LUA_REGISTRYINDEX, db->trace_udata); |
| 1225 | |
| 1226 | db->trace_cb = |
| 1227 | db->trace_udata = LUA_NOREF; |
| 1228 | |
| 1229 | /* clear trace handler */ |
| 1230 | sqlite3_trace(db->db, NULL, NULL); |
| 1231 | } |
| 1232 | else { |
| 1233 | luaL_checktype(L, 2, LUA_TFUNCTION); |
| 1234 | |
| 1235 | /* make sure we have an userdata field (even if nil) */ |
| 1236 | lua_settop(L, 3); |
| 1237 | |
| 1238 | luaL_unref(L, LUA_REGISTRYINDEX, db->trace_cb); |
| 1239 | luaL_unref(L, LUA_REGISTRYINDEX, db->trace_udata); |
| 1240 | |
| 1241 | db->trace_udata = luaL_ref(L, LUA_REGISTRYINDEX); |
| 1242 | db->trace_cb = luaL_ref(L, LUA_REGISTRYINDEX); |
| 1243 | |
| 1244 | /* set trace handler */ |
| 1245 | sqlite3_trace(db->db, db_trace_callback, db); |
| 1246 | } |
| 1247 | |
| 1248 | return 0; |
| 1249 | } |
| 1250 | |
| 1251 | #if !defined(LSQLITE_OMIT_UPDATE_HOOK) || !LSQLITE_OMIT_UPDATE_HOOK |
| 1252 | |
| 1253 | /* |
| 1254 | ** update_hook callback: |
| 1255 | ** Params: database, callback function, userdata |
| 1256 | ** |
| 1257 | ** callback function: |
| 1258 | ** Params: userdata, {one of SQLITE_INSERT, SQLITE_DELETE, or SQLITE_UPDATE}, |
| 1259 | ** database name, table name (containing the affected row), rowid of the row |
| 1260 | */ |
| 1261 | static void db_update_hook_callback(void *user, int op, char const *dbname, char const *tblname, sqlite3_int64 rowid) { |
| 1262 | sdb *db = (sdb*)user; |
| 1263 | lua_State *L = db->L; |
| 1264 | int top = lua_gettop(L); |
| 1265 | lua_Number n; |
| 1266 | |
| 1267 | /* setup lua callback call */ |
| 1268 | lua_rawgeti(L, LUA_REGISTRYINDEX, db->update_hook_cb); /* get callback */ |
| 1269 | lua_rawgeti(L, LUA_REGISTRYINDEX, db->update_hook_udata); /* get callback user data */ |
| 1270 | lua_pushnumber(L, (lua_Number )op); |
| 1271 | lua_pushstring(L, dbname); /* update_hook database name */ |
| 1272 | lua_pushstring(L, tblname); /* update_hook database name */ |
| 1273 | n = (lua_Number)rowid; |
| 1274 | if (n == rowid) |
| 1275 | lua_pushnumber(L, n); |
| 1276 | else |
| 1277 | lua_pushfstring(L, "%ll", rowid); |
| 1278 | |
| 1279 | /* call lua function */ |
| 1280 | lua_pcall(L, 5, 0, 0); |
| 1281 | /* ignore any error generated by this function */ |
| 1282 | |
| 1283 | lua_settop(L, top); |
| 1284 | } |
| 1285 | |
| 1286 | static int db_update_hook(lua_State *L) { |
| 1287 | sdb *db = lsqlite_checkdb(L, 1); |
| 1288 | |
| 1289 | if (lua_gettop(L) < 2 || lua_isnil(L, 2)) { |
| 1290 | luaL_unref(L, LUA_REGISTRYINDEX, db->update_hook_cb); |
| 1291 | luaL_unref(L, LUA_REGISTRYINDEX, db->update_hook_udata); |
| 1292 | |
| 1293 | db->update_hook_cb = |
| 1294 | db->update_hook_udata = LUA_NOREF; |
| 1295 | |
| 1296 | /* clear update_hook handler */ |
| 1297 | sqlite3_update_hook(db->db, NULL, NULL); |
| 1298 | } |
| 1299 | else { |
| 1300 | luaL_checktype(L, 2, LUA_TFUNCTION); |
| 1301 | |
| 1302 | /* make sure we have an userdata field (even if nil) */ |
| 1303 | lua_settop(L, 3); |
| 1304 | |
| 1305 | luaL_unref(L, LUA_REGISTRYINDEX, db->update_hook_cb); |
| 1306 | luaL_unref(L, LUA_REGISTRYINDEX, db->update_hook_udata); |
| 1307 | |
| 1308 | db->update_hook_udata = luaL_ref(L, LUA_REGISTRYINDEX); |
| 1309 | db->update_hook_cb = luaL_ref(L, LUA_REGISTRYINDEX); |
| 1310 | |
| 1311 | /* set update_hook handler */ |
| 1312 | sqlite3_update_hook(db->db, db_update_hook_callback, db); |
| 1313 | } |
| 1314 | |
| 1315 | return 0; |
| 1316 | } |
| 1317 | |
| 1318 | /* |
| 1319 | ** commit_hook callback: |
| 1320 | ** Params: database, callback function, userdata |
| 1321 | ** |
| 1322 | ** callback function: |
| 1323 | ** Params: userdata |
| 1324 | ** Returned value: Return false or nil to continue the COMMIT operation normally. |
| 1325 | ** return true (non false, non nil), then the COMMIT is converted into a ROLLBACK. |
| 1326 | */ |
| 1327 | static int db_commit_hook_callback(void *user) { |
| 1328 | sdb *db = (sdb*)user; |
| 1329 | lua_State *L = db->L; |
| 1330 | int top = lua_gettop(L); |
| 1331 | int rollback = 0; |
| 1332 | |
| 1333 | /* setup lua callback call */ |
| 1334 | lua_rawgeti(L, LUA_REGISTRYINDEX, db->commit_hook_cb); /* get callback */ |
| 1335 | lua_rawgeti(L, LUA_REGISTRYINDEX, db->commit_hook_udata); /* get callback user data */ |
| 1336 | |
| 1337 | /* call lua function */ |
| 1338 | if (!lua_pcall(L, 1, 1, 0)) |
| 1339 | rollback = lua_toboolean(L, -1); /* use result if there was no error */ |
| 1340 | |
| 1341 | lua_settop(L, top); |
| 1342 | return rollback; |
| 1343 | } |
| 1344 | |
| 1345 | static int db_commit_hook(lua_State *L) { |
| 1346 | sdb *db = lsqlite_checkdb(L, 1); |
| 1347 | |
| 1348 | if (lua_gettop(L) < 2 || lua_isnil(L, 2)) { |
| 1349 | luaL_unref(L, LUA_REGISTRYINDEX, db->commit_hook_cb); |
| 1350 | luaL_unref(L, LUA_REGISTRYINDEX, db->commit_hook_udata); |
| 1351 | |
| 1352 | db->commit_hook_cb = |
| 1353 | db->commit_hook_udata = LUA_NOREF; |
| 1354 | |
| 1355 | /* clear commit_hook handler */ |
| 1356 | sqlite3_commit_hook(db->db, NULL, NULL); |
| 1357 | } |
| 1358 | else { |
| 1359 | luaL_checktype(L, 2, LUA_TFUNCTION); |
| 1360 | |
| 1361 | /* make sure we have an userdata field (even if nil) */ |
| 1362 | lua_settop(L, 3); |
| 1363 | |
| 1364 | luaL_unref(L, LUA_REGISTRYINDEX, db->commit_hook_cb); |
| 1365 | luaL_unref(L, LUA_REGISTRYINDEX, db->commit_hook_udata); |
| 1366 | |
| 1367 | db->commit_hook_udata = luaL_ref(L, LUA_REGISTRYINDEX); |
| 1368 | db->commit_hook_cb = luaL_ref(L, LUA_REGISTRYINDEX); |
| 1369 | |
| 1370 | /* set commit_hook handler */ |
| 1371 | sqlite3_commit_hook(db->db, db_commit_hook_callback, db); |
| 1372 | } |
| 1373 | |
| 1374 | return 0; |
| 1375 | } |
| 1376 | |
| 1377 | /* |
| 1378 | ** rollback hook callback: |
| 1379 | ** Params: database, callback function, userdata |
| 1380 | ** |
| 1381 | ** callback function: |
| 1382 | ** Params: userdata |
| 1383 | */ |
| 1384 | static void db_rollback_hook_callback(void *user) { |
| 1385 | sdb *db = (sdb*)user; |
| 1386 | lua_State *L = db->L; |
| 1387 | int top = lua_gettop(L); |
| 1388 | |
| 1389 | /* setup lua callback call */ |
| 1390 | lua_rawgeti(L, LUA_REGISTRYINDEX, db->rollback_hook_cb); /* get callback */ |
| 1391 | lua_rawgeti(L, LUA_REGISTRYINDEX, db->rollback_hook_udata); /* get callback user data */ |
| 1392 | |
| 1393 | /* call lua function */ |
| 1394 | lua_pcall(L, 1, 0, 0); |
| 1395 | /* ignore any error generated by this function */ |
| 1396 | |
| 1397 | lua_settop(L, top); |
| 1398 | } |
| 1399 | |
| 1400 | static int db_rollback_hook(lua_State *L) { |
| 1401 | sdb *db = lsqlite_checkdb(L, 1); |
| 1402 | |
| 1403 | if (lua_gettop(L) < 2 || lua_isnil(L, 2)) { |
| 1404 | luaL_unref(L, LUA_REGISTRYINDEX, db->rollback_hook_cb); |
| 1405 | luaL_unref(L, LUA_REGISTRYINDEX, db->rollback_hook_udata); |
| 1406 | |
| 1407 | db->rollback_hook_cb = |
| 1408 | db->rollback_hook_udata = LUA_NOREF; |
| 1409 | |
| 1410 | /* clear rollback_hook handler */ |
| 1411 | sqlite3_rollback_hook(db->db, NULL, NULL); |
| 1412 | } |
| 1413 | else { |
| 1414 | luaL_checktype(L, 2, LUA_TFUNCTION); |
| 1415 | |
| 1416 | /* make sure we have an userdata field (even if nil) */ |
| 1417 | lua_settop(L, 3); |
| 1418 | |
| 1419 | luaL_unref(L, LUA_REGISTRYINDEX, db->rollback_hook_cb); |
| 1420 | luaL_unref(L, LUA_REGISTRYINDEX, db->rollback_hook_udata); |
| 1421 | |
| 1422 | db->rollback_hook_udata = luaL_ref(L, LUA_REGISTRYINDEX); |
| 1423 | db->rollback_hook_cb = luaL_ref(L, LUA_REGISTRYINDEX); |
| 1424 | |
| 1425 | /* set rollback_hook handler */ |
| 1426 | sqlite3_rollback_hook(db->db, db_rollback_hook_callback, db); |
| 1427 | } |
| 1428 | |
| 1429 | return 0; |
| 1430 | } |
| 1431 | |
| 1432 | #endif /* #if !defined(LSQLITE_OMIT_UPDATE_HOOK) || !LSQLITE_OMIT_UPDATE_HOOK */ |
| 1433 | |
| 1434 | #if !defined(SQLITE_OMIT_PROGRESS_CALLBACK) || !SQLITE_OMIT_PROGRESS_CALLBACK |
| 1435 | |
| 1436 | /* |
| 1437 | ** progress handler: |
| 1438 | ** Params: database, number of opcodes, callback function, userdata |
| 1439 | ** |
| 1440 | ** callback function: |
| 1441 | ** Params: userdata |
| 1442 | ** returns: 0 to return immediatly and return SQLITE_ABORT, non-zero to continue |
| 1443 | */ |
| 1444 | static int db_progress_callback(void *user) { |
| 1445 | int result = 1; /* abort by default */ |
| 1446 | sdb *db = (sdb*)user; |
| 1447 | lua_State *L = db->L; |
| 1448 | int top = lua_gettop(L); |
| 1449 | |
| 1450 | lua_rawgeti(L, LUA_REGISTRYINDEX, db->progress_cb); |
| 1451 | lua_rawgeti(L, LUA_REGISTRYINDEX, db->progress_udata); |
| 1452 | |
| 1453 | /* call lua function */ |
| 1454 | if (!lua_pcall(L, 1, 1, 0)) |
| 1455 | result = lua_toboolean(L, -1); |
| 1456 | |
| 1457 | lua_settop(L, top); |
| 1458 | return result; |
| 1459 | } |
| 1460 | |
| 1461 | static int db_progress_handler(lua_State *L) { |
| 1462 | sdb *db = lsqlite_checkdb(L, 1); |
| 1463 | |
| 1464 | if (lua_gettop(L) < 2 || lua_isnil(L, 2)) { |
| 1465 | luaL_unref(L, LUA_REGISTRYINDEX, db->progress_cb); |
| 1466 | luaL_unref(L, LUA_REGISTRYINDEX, db->progress_udata); |
| 1467 | |
| 1468 | db->progress_cb = |
| 1469 | db->progress_udata = LUA_NOREF; |
| 1470 | |
| 1471 | /* clear busy handler */ |
| 1472 | sqlite3_progress_handler(db->db, 0, NULL, NULL); |
| 1473 | } |
| 1474 | else { |
| 1475 | int nop = luaL_checkint(L, 2); /* number of opcodes */ |
| 1476 | luaL_checktype(L, 3, LUA_TFUNCTION); |
| 1477 | |
| 1478 | /* make sure we have an userdata field (even if nil) */ |
| 1479 | lua_settop(L, 4); |
| 1480 | |
| 1481 | luaL_unref(L, LUA_REGISTRYINDEX, db->progress_cb); |
| 1482 | luaL_unref(L, LUA_REGISTRYINDEX, db->progress_udata); |
| 1483 | |
| 1484 | db->progress_udata = luaL_ref(L, LUA_REGISTRYINDEX); |
| 1485 | db->progress_cb = luaL_ref(L, LUA_REGISTRYINDEX); |
| 1486 | |
| 1487 | /* set progress callback */ |
| 1488 | sqlite3_progress_handler(db->db, nop, db_progress_callback, db); |
| 1489 | } |
| 1490 | |
| 1491 | return 0; |
| 1492 | } |
| 1493 | |
| 1494 | #else /* #if !defined(SQLITE_OMIT_PROGRESS_CALLBACK) || !SQLITE_OMIT_PROGRESS_CALLBACK */ |
| 1495 | |
| 1496 | static int db_progress_handler(lua_State *L) { |
| 1497 | lua_pushliteral(L, "progress callback support disabled at compile time"); |
| 1498 | lua_error(L); |
| 1499 | return 0; |
| 1500 | } |
| 1501 | |
| 1502 | #endif /* #if !defined(SQLITE_OMIT_PROGRESS_CALLBACK) || !SQLITE_OMIT_PROGRESS_CALLBACK */ |
| 1503 | |
| 1504 | /* |
| 1505 | ** busy handler: |
| 1506 | ** Params: database, callback function, userdata |
| 1507 | ** |
| 1508 | ** callback function: |
| 1509 | ** Params: userdata, number of tries |
| 1510 | ** returns: 0 to return immediatly and return SQLITE_BUSY, non-zero to try again |
| 1511 | */ |
| 1512 | static int db_busy_callback(void *user, int tries) { |
| 1513 | int retry = 0; /* abort by default */ |
| 1514 | sdb *db = (sdb*)user; |
| 1515 | lua_State *L = db->L; |
| 1516 | int top = lua_gettop(L); |
| 1517 | |
| 1518 | lua_rawgeti(L, LUA_REGISTRYINDEX, db->busy_cb); |
| 1519 | lua_rawgeti(L, LUA_REGISTRYINDEX, db->busy_udata); |
| 1520 | lua_pushnumber(L, tries); |
| 1521 | |
| 1522 | /* call lua function */ |
| 1523 | if (!lua_pcall(L, 2, 1, 0)) |
| 1524 | retry = lua_toboolean(L, -1); |
| 1525 | |
| 1526 | lua_settop(L, top); |
| 1527 | return retry; |
| 1528 | } |
| 1529 | |
| 1530 | static int db_busy_handler(lua_State *L) { |
| 1531 | sdb *db = lsqlite_checkdb(L, 1); |
| 1532 | |
| 1533 | if (lua_gettop(L) < 2 || lua_isnil(L, 2)) { |
| 1534 | luaL_unref(L, LUA_REGISTRYINDEX, db->busy_cb); |
| 1535 | luaL_unref(L, LUA_REGISTRYINDEX, db->busy_udata); |
| 1536 | |
| 1537 | db->busy_cb = |
| 1538 | db->busy_udata = LUA_NOREF; |
| 1539 | |
| 1540 | /* clear busy handler */ |
| 1541 | sqlite3_busy_handler(db->db, NULL, NULL); |
| 1542 | } |
| 1543 | else { |
| 1544 | luaL_checktype(L, 2, LUA_TFUNCTION); |
| 1545 | /* make sure we have an userdata field (even if nil) */ |
| 1546 | lua_settop(L, 3); |
| 1547 | |
| 1548 | luaL_unref(L, LUA_REGISTRYINDEX, db->busy_cb); |
| 1549 | luaL_unref(L, LUA_REGISTRYINDEX, db->busy_udata); |
| 1550 | |
| 1551 | db->busy_udata = luaL_ref(L, LUA_REGISTRYINDEX); |
| 1552 | db->busy_cb = luaL_ref(L, LUA_REGISTRYINDEX); |
| 1553 | |
| 1554 | /* set busy handler */ |
| 1555 | sqlite3_busy_handler(db->db, db_busy_callback, db); |
| 1556 | } |
| 1557 | |
| 1558 | return 0; |
| 1559 | } |
| 1560 | |
| 1561 | static int db_busy_timeout(lua_State *L) { |
| 1562 | sdb *db = lsqlite_checkdb(L, 1); |
| 1563 | int timeout = luaL_checkint(L, 2); |
| 1564 | sqlite3_busy_timeout(db->db, timeout); |
| 1565 | |
| 1566 | /* if there was a timeout callback registered, it is now |
| 1567 | ** invalid/useless. free any references we may have */ |
| 1568 | luaL_unref(L, LUA_REGISTRYINDEX, db->busy_cb); |
| 1569 | luaL_unref(L, LUA_REGISTRYINDEX, db->busy_udata); |
| 1570 | db->busy_cb = |
| 1571 | db->busy_udata = LUA_NOREF; |
| 1572 | |
| 1573 | return 0; |
| 1574 | } |
| 1575 | |
| 1576 | /* |
| 1577 | ** Params: db, sql, callback, user |
| 1578 | ** returns: code [, errmsg] |
| 1579 | ** |
| 1580 | ** Callback: |
| 1581 | ** Params: user, number of columns, values, names |
| 1582 | ** Returns: 0 to continue, other value will cause abort |
| 1583 | */ |
| 1584 | static int db_exec_callback(void* user, int columns, char **data, char **names) { |
| 1585 | int result = SQLITE_ABORT; /* abort by default */ |
| 1586 | lua_State *L = (lua_State*)user; |
| 1587 | int n; |
| 1588 | |
| 1589 | int top = lua_gettop(L); |
| 1590 | |
| 1591 | lua_pushvalue(L, 3); /* function to call */ |
| 1592 | lua_pushvalue(L, 4); /* user data */ |
| 1593 | lua_pushnumber(L, columns); /* total number of rows in result */ |
| 1594 | |
| 1595 | /* column values */ |
| 1596 | lua_pushvalue(L, 6); |
| 1597 | for (n = 0; n < columns;) { |
| 1598 | lua_pushstring(L, data[n++]); |
| 1599 | lua_rawseti(L, -2, n); |
| 1600 | } |
| 1601 | |
| 1602 | /* columns names */ |
| 1603 | lua_pushvalue(L, 5); |
| 1604 | if (lua_isnil(L, -1)) { |
| 1605 | lua_pop(L, 1); |
| 1606 | lua_newtable(L); |
| 1607 | lua_pushvalue(L, -1); |
| 1608 | lua_replace(L, 5); |
| 1609 | for (n = 0; n < columns;) { |
| 1610 | lua_pushstring(L, names[n++]); |
| 1611 | lua_rawseti(L, -2, n); |
| 1612 | } |
| 1613 | } |
| 1614 | |
| 1615 | /* call lua function */ |
| 1616 | if (!lua_pcall(L, 4, 1, 0)) { |
| 1617 | if (lua_isnumber(L, -1)) |
| 1618 | result = lua_tonumber(L, -1); |
| 1619 | } |
| 1620 | |
| 1621 | lua_settop(L, top); |
| 1622 | return result; |
| 1623 | } |
| 1624 | |
| 1625 | static int db_exec(lua_State *L) { |
| 1626 | sdb *db = lsqlite_checkdb(L, 1); |
| 1627 | const char *sql = luaL_checkstring(L, 2); |
| 1628 | int result; |
| 1629 | |
| 1630 | if (!lua_isnoneornil(L, 3)) { |
| 1631 | /* stack: |
| 1632 | ** 3: callback function |
| 1633 | ** 4: userdata |
| 1634 | ** 5: column names |
| 1635 | ** 6: reusable column values |
| 1636 | */ |
| 1637 | luaL_checktype(L, 3, LUA_TFUNCTION); |
| 1638 | lua_settop(L, 4); /* 'trap' userdata - nil extra parameters */ |
| 1639 | lua_pushnil(L); /* column names not known at this point */ |
| 1640 | lua_newtable(L); /* column values table */ |
| 1641 | |
| 1642 | result = sqlite3_exec(db->db, sql, db_exec_callback, L, NULL); |
| 1643 | } |
| 1644 | else { |
| 1645 | /* no callbacks */ |
| 1646 | result = sqlite3_exec(db->db, sql, NULL, NULL, NULL); |
| 1647 | } |
| 1648 | |
| 1649 | lua_pushnumber(L, result); |
| 1650 | return 1; |
| 1651 | } |
| 1652 | |
| 1653 | /* |
| 1654 | ** Params: db, sql |
| 1655 | ** returns: code, compiled length or error message |
| 1656 | */ |
| 1657 | static int db_prepare(lua_State *L) { |
| 1658 | sdb *db = lsqlite_checkdb(L, 1); |
| 1659 | const char *sql = luaL_checkstring(L, 2); |
| 1660 | int sql_len = lua_strlen(L, 2); |
| 1661 | const char *sqltail; |
| 1662 | sdb_vm *svm; |
| 1663 | lua_settop(L,2); /* sql is on top of stack for call to newvm */ |
| 1664 | svm = newvm(L, db); |
| 1665 | |
| 1666 | if (sqlite3_prepare(db->db, sql, sql_len, &svm->vm, &sqltail) != SQLITE_OK) { |
| 1667 | cleanupvm(L, svm); |
| 1668 | |
| 1669 | lua_pushnil(L); |
| 1670 | lua_pushnumber(L, sqlite3_errcode(db->db)); |
| 1671 | return 2; |
| 1672 | } |
| 1673 | |
| 1674 | /* vm already in the stack */ |
| 1675 | lua_pushstring(L, sqltail); |
| 1676 | return 2; |
| 1677 | } |
| 1678 | |
| 1679 | static int db_do_next_row(lua_State *L, int packed) { |
| 1680 | int result; |
| 1681 | sdb_vm *svm = lsqlite_checkvm(L, 1); |
| 1682 | sqlite3_stmt *vm; |
| 1683 | int columns; |
| 1684 | int i; |
| 1685 | |
| 1686 | result = stepvm(L, svm); |
| 1687 | vm = svm->vm; /* stepvm may change svm->vm if re-prepare is needed */ |
| 1688 | svm->has_values = result == SQLITE_ROW ? 1 : 0; |
| 1689 | svm->columns = columns = sqlite3_data_count(vm); |
| 1690 | |
| 1691 | if (result == SQLITE_ROW) { |
| 1692 | if (packed) { |
| 1693 | lua_newtable(L); |
| 1694 | if (packed == 1) { |
| 1695 | for (i = 0; i < columns;) { |
| 1696 | vm_push_column(L, vm, i); |
| 1697 | lua_rawseti(L, -2, ++i); |
| 1698 | } |
| 1699 | } |
| 1700 | else { |
| 1701 | for (i = 0; i < columns; ++i) { |
| 1702 | lua_pushstring(L, sqlite3_column_name(vm, i)); |
| 1703 | vm_push_column(L, vm, i); |
| 1704 | lua_rawset(L, -3); |
| 1705 | } |
| 1706 | } |
| 1707 | return 1; |
| 1708 | } |
| 1709 | else { |
| 1710 | lua_checkstack(L, columns); |
| 1711 | for (i = 0; i < columns; ++i) |
| 1712 | vm_push_column(L, vm, i); |
| 1713 | return svm->columns; |
| 1714 | } |
| 1715 | } |
| 1716 | |
| 1717 | if (svm->temp) { |
| 1718 | /* finalize and check for errors */ |
| 1719 | result = sqlite3_finalize(vm); |
| 1720 | svm->vm = NULL; |
| 1721 | cleanupvm(L, svm); |
| 1722 | } |
| 1723 | else if (result == SQLITE_DONE) { |
| 1724 | result = sqlite3_reset(vm); |
| 1725 | } |
| 1726 | |
| 1727 | if (result != SQLITE_OK) { |
| 1728 | lua_pushstring(L, sqlite3_errmsg(svm->db->db)); |
| 1729 | lua_error(L); |
| 1730 | } |
| 1731 | return 0; |
| 1732 | } |
| 1733 | |
| 1734 | static int db_next_row(lua_State *L) { |
| 1735 | return db_do_next_row(L, 0); |
| 1736 | } |
| 1737 | |
| 1738 | static int db_next_packed_row(lua_State *L) { |
| 1739 | return db_do_next_row(L, 1); |
| 1740 | } |
| 1741 | |
| 1742 | static int db_next_named_row(lua_State *L) { |
| 1743 | return db_do_next_row(L, 2); |
| 1744 | } |
| 1745 | |
| 1746 | static int dbvm_do_rows(lua_State *L, int(*f)(lua_State *)) { |
| 1747 | /* sdb_vm *svm = */ |
| 1748 | lsqlite_checkvm(L, 1); |
| 1749 | lua_pushvalue(L,1); |
| 1750 | lua_pushcfunction(L, f); |
| 1751 | lua_insert(L, -2); |
| 1752 | return 2; |
| 1753 | } |
| 1754 | |
| 1755 | static int dbvm_rows(lua_State *L) { |
| 1756 | return dbvm_do_rows(L, db_next_packed_row); |
| 1757 | } |
| 1758 | |
| 1759 | static int dbvm_nrows(lua_State *L) { |
| 1760 | return dbvm_do_rows(L, db_next_named_row); |
| 1761 | } |
| 1762 | |
| 1763 | static int dbvm_urows(lua_State *L) { |
| 1764 | return dbvm_do_rows(L, db_next_row); |
| 1765 | } |
| 1766 | |
| 1767 | static int db_do_rows(lua_State *L, int(*f)(lua_State *)) { |
| 1768 | sdb *db = lsqlite_checkdb(L, 1); |
| 1769 | const char *sql = luaL_checkstring(L, 2); |
| 1770 | sdb_vm *svm; |
| 1771 | lua_settop(L,2); /* sql is on top of stack for call to newvm */ |
| 1772 | svm = newvm(L, db); |
| 1773 | svm->temp = 1; |
| 1774 | |
| 1775 | if (sqlite3_prepare(db->db, sql, -1, &svm->vm, NULL) != SQLITE_OK) { |
| 1776 | cleanupvm(L, svm); |
| 1777 | |
| 1778 | lua_pushstring(L, sqlite3_errmsg(svm->db->db)); |
| 1779 | lua_error(L); |
| 1780 | } |
| 1781 | |
| 1782 | lua_pushcfunction(L, f); |
| 1783 | lua_insert(L, -2); |
| 1784 | return 2; |
| 1785 | } |
| 1786 | |
| 1787 | static int db_rows(lua_State *L) { |
| 1788 | return db_do_rows(L, db_next_packed_row); |
| 1789 | } |
| 1790 | |
| 1791 | static int db_nrows(lua_State *L) { |
| 1792 | return db_do_rows(L, db_next_named_row); |
| 1793 | } |
| 1794 | |
| 1795 | /* unpacked version of db:rows */ |
| 1796 | static int db_urows(lua_State *L) { |
| 1797 | return db_do_rows(L, db_next_row); |
| 1798 | } |
| 1799 | |
| 1800 | static int db_tostring(lua_State *L) { |
| 1801 | char buff[32]; |
| 1802 | sdb *db = lsqlite_getdb(L, 1); |
| 1803 | if (db->db == NULL) |
| 1804 | strcpy(buff, "closed"); |
| 1805 | else |
| 1806 | sprintf(buff, "%p", lua_touserdata(L, 1)); |
| 1807 | lua_pushfstring(L, "sqlite database (%s)", buff); |
| 1808 | return 1; |
| 1809 | } |
| 1810 | |
| 1811 | static int db_close(lua_State *L) { |
| 1812 | sdb *db = lsqlite_checkdb(L, 1); |
| 1813 | lua_pushnumber(L, cleanupdb(L, db)); |
| 1814 | return 1; |
| 1815 | } |
| 1816 | |
| 1817 | static int db_close_vm(lua_State *L) { |
| 1818 | sdb *db = lsqlite_checkdb(L, 1); |
| 1819 | /* cleanup temporary only tables? */ |
| 1820 | int temp = lua_toboolean(L, 2); |
| 1821 | |
| 1822 | /* free associated virtual machines */ |
| 1823 | lua_pushlightuserdata(L, db); |
| 1824 | lua_rawget(L, LUA_REGISTRYINDEX); |
| 1825 | |
| 1826 | /* close all used handles */ |
| 1827 | lua_pushnil(L); |
| 1828 | while (lua_next(L, -2)) { |
| 1829 | sdb_vm *svm = (sdb_vm *)lua_touserdata(L, -2); /* key: vm; val: sql text */ |
| 1830 | |
| 1831 | if ((!temp || svm->temp) && svm->vm) |
| 1832 | { |
| 1833 | sqlite3_finalize(svm->vm); |
| 1834 | svm->vm = NULL; |
| 1835 | } |
| 1836 | |
| 1837 | /* leave key in the stack */ |
| 1838 | lua_pop(L, 1); |
| 1839 | } |
| 1840 | return 0; |
| 1841 | } |
| 1842 | |
| 1843 | static int db_gc(lua_State *L) { |
| 1844 | sdb *db = lsqlite_getdb(L, 1); |
| 1845 | if (db->db != NULL) /* ignore closed databases */ |
| 1846 | cleanupdb(L, db); |
| 1847 | return 0; |
| 1848 | } |
| 1849 | |
| 1850 | /* |
| 1851 | ** ======================================================= |
| 1852 | ** General library functions |
| 1853 | ** ======================================================= |
| 1854 | */ |
| 1855 | |
| 1856 | static int lsqlite_version(lua_State *L) { |
| 1857 | lua_pushstring(L, sqlite3_libversion()); |
| 1858 | return 1; |
| 1859 | } |
| 1860 | |
| 1861 | static int lsqlite_complete(lua_State *L) { |
| 1862 | const char *sql = luaL_checkstring(L, 1); |
| 1863 | lua_pushboolean(L, sqlite3_complete(sql)); |
| 1864 | return 1; |
| 1865 | } |
| 1866 | |
| 1867 | #ifndef WIN32 |
| 1868 | static int lsqlite_temp_directory(lua_State *L) { |
| 1869 | const char *oldtemp = sqlite3_temp_directory; |
| 1870 | |
| 1871 | if (!lua_isnone(L, 1)) { |
| 1872 | const char *temp = luaL_optstring(L, 1, NULL); |
| 1873 | if (sqlite3_temp_directory) { |
| 1874 | sqlite3_free((char*)sqlite3_temp_directory); |
| 1875 | } |
| 1876 | if (temp) { |
| 1877 | sqlite3_temp_directory = sqlite3_mprintf("%s", temp); |
| 1878 | } |
| 1879 | else { |
| 1880 | sqlite3_temp_directory = NULL; |
| 1881 | } |
| 1882 | } |
| 1883 | lua_pushstring(L, oldtemp); |
| 1884 | return 1; |
| 1885 | } |
| 1886 | #endif |
| 1887 | |
| 1888 | static int lsqlite_do_open(lua_State *L, const char *filename) { |
| 1889 | sdb *db = newdb(L); /* create and leave in stack */ |
| 1890 | |
| 1891 | if (sqlite3_open(filename, &db->db) == SQLITE_OK) { |
| 1892 | /* database handle already in the stack - return it */ |
| 1893 | return 1; |
| 1894 | } |
| 1895 | |
| 1896 | /* failed to open database */ |
| 1897 | lua_pushnil(L); /* push nil */ |
| 1898 | lua_pushnumber(L, sqlite3_errcode(db->db)); |
| 1899 | lua_pushstring(L, sqlite3_errmsg(db->db)); /* push error message */ |
| 1900 | |
| 1901 | /* clean things up */ |
| 1902 | cleanupdb(L, db); |
| 1903 | |
| 1904 | /* return */ |
| 1905 | return 3; |
| 1906 | } |
| 1907 | |
| 1908 | static int lsqlite_open(lua_State *L) { |
| 1909 | const char *filename = luaL_checkstring(L, 1); |
| 1910 | return lsqlite_do_open(L, filename); |
| 1911 | } |
| 1912 | |
| 1913 | static int lsqlite_open_memory(lua_State *L) { |
| 1914 | return lsqlite_do_open(L, ":memory:"); |
| 1915 | } |
| 1916 | |
| 1917 | static int lsqlite_newindex(lua_State *L) { |
| 1918 | lua_pushliteral(L, "attempt to change readonly table"); |
| 1919 | lua_error(L); |
| 1920 | return 0; |
| 1921 | } |
| 1922 | |
| 1923 | /* |
| 1924 | ** ======================================================= |
| 1925 | ** Register functions |
| 1926 | ** ======================================================= |
| 1927 | */ |
| 1928 | |
| 1929 | #define SC(s) { #s, SQLITE_ ## s }, |
| 1930 | #define LSC(s) { #s, LSQLITE_ ## s }, |
| 1931 | |
| 1932 | static const struct { |
| 1933 | const char* name; |
| 1934 | int value; |
| 1935 | } sqlite_constants[] = { |
| 1936 | /* error codes */ |
| 1937 | SC(OK) SC(ERROR) SC(INTERNAL) SC(PERM) |
| 1938 | SC(ABORT) SC(BUSY) SC(LOCKED) SC(NOMEM) |
| 1939 | SC(READONLY) SC(INTERRUPT) SC(IOERR) SC(CORRUPT) |
| 1940 | SC(NOTFOUND) SC(FULL) SC(CANTOPEN) SC(PROTOCOL) |
| 1941 | SC(EMPTY) SC(SCHEMA) SC(TOOBIG) SC(CONSTRAINT) |
| 1942 | SC(MISMATCH) SC(MISUSE) SC(NOLFS) |
| 1943 | SC(FORMAT) SC(NOTADB) |
| 1944 | |
| 1945 | /* sqlite_step specific return values */ |
| 1946 | SC(RANGE) SC(ROW) SC(DONE) |
| 1947 | |
| 1948 | /* column types */ |
| 1949 | SC(INTEGER) SC(FLOAT) SC(TEXT) SC(BLOB) |
| 1950 | SC(NULL) |
| 1951 | |
| 1952 | /* Authorizer Action Codes */ |
| 1953 | SC(CREATE_INDEX ) |
| 1954 | SC(CREATE_TABLE ) |
| 1955 | SC(CREATE_TEMP_INDEX ) |
| 1956 | SC(CREATE_TEMP_TABLE ) |
| 1957 | SC(CREATE_TEMP_TRIGGER) |
| 1958 | SC(CREATE_TEMP_VIEW ) |
| 1959 | SC(CREATE_TRIGGER ) |
| 1960 | SC(CREATE_VIEW ) |
| 1961 | SC(DELETE ) |
| 1962 | SC(DROP_INDEX ) |
| 1963 | SC(DROP_TABLE ) |
| 1964 | SC(DROP_TEMP_INDEX ) |
| 1965 | SC(DROP_TEMP_TABLE ) |
| 1966 | SC(DROP_TEMP_TRIGGER ) |
| 1967 | SC(DROP_TEMP_VIEW ) |
| 1968 | SC(DROP_TRIGGER ) |
| 1969 | SC(DROP_VIEW ) |
| 1970 | SC(INSERT ) |
| 1971 | SC(PRAGMA ) |
| 1972 | SC(READ ) |
| 1973 | SC(SELECT ) |
| 1974 | SC(TRANSACTION ) |
| 1975 | SC(UPDATE ) |
| 1976 | SC(ATTACH ) |
| 1977 | SC(DETACH ) |
| 1978 | SC(ALTER_TABLE ) |
| 1979 | SC(REINDEX ) |
| 1980 | SC(ANALYZE ) |
| 1981 | SC(CREATE_VTABLE ) |
| 1982 | SC(DROP_VTABLE ) |
| 1983 | SC(FUNCTION ) |
| 1984 | SC(SAVEPOINT ) |
| 1985 | |
| 1986 | /* terminator */ |
| 1987 | { NULL, 0 } |
| 1988 | }; |
| 1989 | |
| 1990 | /* ======================================================= */ |
| 1991 | |
| 1992 | static const luaL_Reg dblib[] = { |
| 1993 | {"isopen", db_isopen }, |
| 1994 | {"last_insert_rowid", db_last_insert_rowid }, |
| 1995 | {"changes", db_changes }, |
| 1996 | {"total_changes", db_total_changes }, |
| 1997 | {"errcode", db_errcode }, |
| 1998 | {"error_code", db_errcode }, |
| 1999 | {"errmsg", db_errmsg }, |
| 2000 | {"error_message", db_errmsg }, |
| 2001 | {"interrupt", db_interrupt }, |
| 2002 | |
| 2003 | {"create_function", db_create_function }, |
| 2004 | {"create_aggregate", db_create_aggregate }, |
| 2005 | {"create_collation", db_create_collation }, |
| 2006 | |
| 2007 | {"trace", db_trace }, |
| 2008 | {"progress_handler", db_progress_handler }, |
| 2009 | {"busy_timeout", db_busy_timeout }, |
| 2010 | {"busy_handler", db_busy_handler }, |
| 2011 | #if !defined(LSQLITE_OMIT_UPDATE_HOOK) || !LSQLITE_OMIT_UPDATE_HOOK |
| 2012 | {"update_hook", db_update_hook }, |
| 2013 | {"commit_hook", db_commit_hook }, |
| 2014 | {"rollback_hook", db_rollback_hook }, |
| 2015 | #endif |
| 2016 | |
| 2017 | {"prepare", db_prepare }, |
| 2018 | {"rows", db_rows }, |
| 2019 | {"urows", db_urows }, |
| 2020 | {"nrows", db_nrows }, |
| 2021 | |
| 2022 | {"exec", db_exec }, |
| 2023 | {"execute", db_exec }, |
| 2024 | {"close", db_close }, |
| 2025 | {"close_vm", db_close_vm }, |
| 2026 | |
| 2027 | {"__tostring", db_tostring }, |
| 2028 | {"__gc", db_gc }, |
| 2029 | |
| 2030 | {NULL, NULL} |
| 2031 | }; |
| 2032 | |
| 2033 | static const luaL_Reg vmlib[] = { |
| 2034 | {"isopen", dbvm_isopen }, |
| 2035 | |
| 2036 | {"step", dbvm_step }, |
| 2037 | {"reset", dbvm_reset }, |
| 2038 | {"finalize", dbvm_finalize }, |
| 2039 | |
| 2040 | {"columns", dbvm_columns }, |
| 2041 | |
| 2042 | {"bind", dbvm_bind }, |
| 2043 | {"bind_values", dbvm_bind_values }, |
| 2044 | {"bind_names", dbvm_bind_names }, |
| 2045 | {"bind_blob", dbvm_bind_blob }, |
| 2046 | {"bind_parameter_count",dbvm_bind_parameter_count}, |
| 2047 | {"bind_parameter_name", dbvm_bind_parameter_name}, |
| 2048 | |
| 2049 | {"get_value", dbvm_get_value }, |
| 2050 | {"get_values", dbvm_get_values }, |
| 2051 | {"get_name", dbvm_get_name }, |
| 2052 | {"get_names", dbvm_get_names }, |
| 2053 | {"get_type", dbvm_get_type }, |
| 2054 | {"get_types", dbvm_get_types }, |
| 2055 | {"get_uvalues", dbvm_get_uvalues }, |
| 2056 | {"get_unames", dbvm_get_unames }, |
| 2057 | {"get_utypes", dbvm_get_utypes }, |
| 2058 | |
| 2059 | {"get_named_values", dbvm_get_named_values }, |
| 2060 | {"get_named_types", dbvm_get_named_types }, |
| 2061 | |
| 2062 | {"rows", dbvm_rows }, |
| 2063 | {"urows", dbvm_urows }, |
| 2064 | {"nrows", dbvm_nrows }, |
| 2065 | |
| 2066 | /* compatibility names (added by request) */ |
| 2067 | {"idata", dbvm_get_values }, |
| 2068 | {"inames", dbvm_get_names }, |
| 2069 | {"itypes", dbvm_get_types }, |
| 2070 | {"data", dbvm_get_named_values }, |
| 2071 | {"type", dbvm_get_named_types }, |
| 2072 | |
| 2073 | {"__tostring", dbvm_tostring }, |
| 2074 | {"__gc", dbvm_gc }, |
| 2075 | |
| 2076 | { NULL, NULL } |
| 2077 | }; |
| 2078 | |
| 2079 | static const luaL_Reg ctxlib[] = { |
| 2080 | {"user_data", lcontext_user_data }, |
| 2081 | |
| 2082 | {"get_aggregate_data", lcontext_get_aggregate_context }, |
| 2083 | {"set_aggregate_data", lcontext_set_aggregate_context }, |
| 2084 | {"aggregate_count", lcontext_aggregate_count }, |
| 2085 | |
| 2086 | {"result", lcontext_result }, |
| 2087 | {"result_null", lcontext_result_null }, |
| 2088 | {"result_number", lcontext_result_double }, |
| 2089 | {"result_double", lcontext_result_double }, |
| 2090 | {"result_int", lcontext_result_int }, |
| 2091 | {"result_text", lcontext_result_text }, |
| 2092 | {"result_blob", lcontext_result_blob }, |
| 2093 | {"result_error", lcontext_result_error }, |
| 2094 | |
| 2095 | {"__tostring", lcontext_tostring }, |
| 2096 | {NULL, NULL} |
| 2097 | }; |
| 2098 | |
| 2099 | static const luaL_Reg sqlitelib[] = { |
| 2100 | {"version", lsqlite_version }, |
| 2101 | {"complete", lsqlite_complete }, |
| 2102 | #ifndef WIN32 |
| 2103 | {"temp_directory", lsqlite_temp_directory }, |
| 2104 | #endif |
| 2105 | {"open", lsqlite_open }, |
| 2106 | {"open_memory", lsqlite_open_memory }, |
| 2107 | |
| 2108 | {"__newindex", lsqlite_newindex }, |
| 2109 | {NULL, NULL} |
| 2110 | }; |
| 2111 | |
| 2112 | static void create_meta(lua_State *L, const char *name, const luaL_Reg *lib) { |
| 2113 | luaL_newmetatable(L, name); |
| 2114 | lua_pushstring(L, "__index"); |
| 2115 | lua_pushvalue(L, -2); /* push metatable */ |
| 2116 | lua_rawset(L, -3); /* metatable.__index = metatable */ |
| 2117 | |
| 2118 | /* register metatable functions */ |
| 2119 | luaL_openlib(L, NULL, lib, 0); |
| 2120 | |
| 2121 | /* remove metatable from stack */ |
| 2122 | lua_pop(L, 1); |
| 2123 | } |
| 2124 | |
| 2125 | static int luaopen_sqlite3 ( lua_State * L ) |
| 2126 | { |
| 2127 | luaL_newlib(L, sqlitelib); |
| 2128 | return 1; |
| 2129 | } |
| 2130 | |
| 2131 | LUALIB_API int luaopen_lsqlite3(lua_State *L) { |
| 2132 | create_meta(L, sqlite_meta, dblib); |
| 2133 | create_meta(L, sqlite_vm_meta, vmlib); |
| 2134 | create_meta(L, sqlite_ctx_meta, ctxlib); |
| 2135 | |
| 2136 | luaL_getmetatable(L, sqlite_ctx_meta); |
| 2137 | sqlite_ctx_meta_ref = luaL_ref(L, LUA_REGISTRYINDEX); |
| 2138 | /* register (local) sqlite metatable */ |
| 2139 | //luaL_register(L, "sqlite3", sqlitelib); |
| 2140 | luaL_requiref(L, "sqlite3", luaopen_sqlite3, 1); |
| 2141 | { |
| 2142 | int i = 0; |
| 2143 | /* add constants to global table */ |
| 2144 | while (sqlite_constants[i].name) { |
| 2145 | lua_pushstring(L, sqlite_constants[i].name); |
| 2146 | lua_pushnumber(L, sqlite_constants[i].value); |
| 2147 | lua_rawset(L, -3); |
| 2148 | ++i; |
| 2149 | } |
| 2150 | } |
| 2151 | /* set sqlite's metatable to itself - set as readonly (__newindex) */ |
| 2152 | lua_pushvalue(L, -1); |
| 2153 | lua_setmetatable(L, -2); |
| 2154 | |
| 2155 | return 1; |
| 2156 | } |
trunk/src/lib/lua/ldblib.c
| r30857 | r30858 | |
| 1 | 1 | /* |
| 2 | | ** $Id: ldblib.c,v 1.132 2012/01/19 20:14:44 roberto Exp $ |
| 2 | ** $Id: ldblib.c,v 1.132.1.1 2013/04/12 18:48:47 roberto Exp $ |
| 3 | 3 | ** Interface from Lua to its debug API |
| 4 | 4 | ** See Copyright Notice in lua.h |
| 5 | 5 | */ |
| r30857 | r30858 | |
| 18 | 18 | #include "lualib.h" |
| 19 | 19 | |
| 20 | 20 | |
| 21 | | #define HOOKKEY "_HKEY" |
| 21 | #define HOOKKEY "_HKEY" |
| 22 | 22 | |
| 23 | 23 | |
| 24 | 24 | |
| 25 | 25 | static int db_getregistry (lua_State *L) { |
| 26 | | lua_pushvalue(L, LUA_REGISTRYINDEX); |
| 27 | | return 1; |
| 26 | lua_pushvalue(L, LUA_REGISTRYINDEX); |
| 27 | return 1; |
| 28 | 28 | } |
| 29 | 29 | |
| 30 | 30 | |
| 31 | 31 | static int db_getmetatable (lua_State *L) { |
| 32 | | luaL_checkany(L, 1); |
| 33 | | if (!lua_getmetatable(L, 1)) { |
| 34 | | lua_pushnil(L); /* no metatable */ |
| 35 | | } |
| 36 | | return 1; |
| 32 | luaL_checkany(L, 1); |
| 33 | if (!lua_getmetatable(L, 1)) { |
| 34 | lua_pushnil(L); /* no metatable */ |
| 35 | } |
| 36 | return 1; |
| 37 | 37 | } |
| 38 | 38 | |
| 39 | 39 | |
| 40 | 40 | static int db_setmetatable (lua_State *L) { |
| 41 | | int t = lua_type(L, 2); |
| 42 | | luaL_argcheck(L, t == LUA_TNIL || t == LUA_TTABLE, 2, |
| 43 | | "nil or table expected"); |
| 44 | | lua_settop(L, 2); |
| 45 | | lua_setmetatable(L, 1); |
| 46 | | return 1; /* return 1st argument */ |
| 41 | int t = lua_type(L, 2); |
| 42 | luaL_argcheck(L, t == LUA_TNIL || t == LUA_TTABLE, 2, |
| 43 | "nil or table expected"); |
| 44 | lua_settop(L, 2); |
| 45 | lua_setmetatable(L, 1); |
| 46 | return 1; /* return 1st argument */ |
| 47 | 47 | } |
| 48 | 48 | |
| 49 | 49 | |
| 50 | 50 | static int db_getuservalue (lua_State *L) { |
| 51 | | if (lua_type(L, 1) != LUA_TUSERDATA) |
| 52 | | lua_pushnil(L); |
| 53 | | else |
| 54 | | lua_getuservalue(L, 1); |
| 55 | | return 1; |
| 51 | if (lua_type(L, 1) != LUA_TUSERDATA) |
| 52 | lua_pushnil(L); |
| 53 | else |
| 54 | lua_getuservalue(L, 1); |
| 55 | return 1; |
| 56 | 56 | } |
| 57 | 57 | |
| 58 | 58 | |
| 59 | 59 | static int db_setuservalue (lua_State *L) { |
| 60 | | if (lua_type(L, 1) == LUA_TLIGHTUSERDATA) |
| 61 | | luaL_argerror(L, 1, "full userdata expected, got light userdata"); |
| 62 | | luaL_checktype(L, 1, LUA_TUSERDATA); |
| 63 | | if (!lua_isnoneornil(L, 2)) |
| 64 | | luaL_checktype(L, 2, LUA_TTABLE); |
| 65 | | lua_settop(L, 2); |
| 66 | | lua_setuservalue(L, 1); |
| 67 | | return 1; |
| 60 | if (lua_type(L, 1) == LUA_TLIGHTUSERDATA) |
| 61 | luaL_argerror(L, 1, "full userdata expected, got light userdata"); |
| 62 | luaL_checktype(L, 1, LUA_TUSERDATA); |
| 63 | if (!lua_isnoneornil(L, 2)) |
| 64 | luaL_checktype(L, 2, LUA_TTABLE); |
| 65 | lua_settop(L, 2); |
| 66 | lua_setuservalue(L, 1); |
| 67 | return 1; |
| 68 | 68 | } |
| 69 | 69 | |
| 70 | 70 | |
| 71 | 71 | static void settabss (lua_State *L, const char *i, const char *v) { |
| 72 | | lua_pushstring(L, v); |
| 73 | | lua_setfield(L, -2, i); |
| 72 | lua_pushstring(L, v); |
| 73 | lua_setfield(L, -2, i); |
| 74 | 74 | } |
| 75 | 75 | |
| 76 | 76 | |
| 77 | 77 | static void settabsi (lua_State *L, const char *i, int v) { |
| 78 | | lua_pushinteger(L, v); |
| 79 | | lua_setfield(L, -2, i); |
| 78 | lua_pushinteger(L, v); |
| 79 | lua_setfield(L, -2, i); |
| 80 | 80 | } |
| 81 | 81 | |
| 82 | 82 | |
| 83 | 83 | static void settabsb (lua_State *L, const char *i, int v) { |
| 84 | | lua_pushboolean(L, v); |
| 85 | | lua_setfield(L, -2, i); |
| 84 | lua_pushboolean(L, v); |
| 85 | lua_setfield(L, -2, i); |
| 86 | 86 | } |
| 87 | 87 | |
| 88 | 88 | |
| 89 | 89 | static lua_State *getthread (lua_State *L, int *arg) { |
| 90 | | if (lua_isthread(L, 1)) { |
| 91 | | *arg = 1; |
| 92 | | return lua_tothread(L, 1); |
| 93 | | } |
| 94 | | else { |
| 95 | | *arg = 0; |
| 96 | | return L; |
| 97 | | } |
| 90 | if (lua_isthread(L, 1)) { |
| 91 | *arg = 1; |
| 92 | return lua_tothread(L, 1); |
| 93 | } |
| 94 | else { |
| 95 | *arg = 0; |
| 96 | return L; |
| 97 | } |
| 98 | 98 | } |
| 99 | 99 | |
| 100 | 100 | |
| 101 | 101 | static void treatstackoption (lua_State *L, lua_State *L1, const char *fname) { |
| 102 | | if (L == L1) { |
| 103 | | lua_pushvalue(L, -2); |
| 104 | | lua_remove(L, -3); |
| 105 | | } |
| 106 | | else |
| 107 | | lua_xmove(L1, L, 1); |
| 108 | | lua_setfield(L, -2, fname); |
| 102 | if (L == L1) { |
| 103 | lua_pushvalue(L, -2); |
| 104 | lua_remove(L, -3); |
| 105 | } |
| 106 | else |
| 107 | lua_xmove(L1, L, 1); |
| 108 | lua_setfield(L, -2, fname); |
| 109 | 109 | } |
| 110 | 110 | |
| 111 | 111 | |
| 112 | 112 | static int db_getinfo (lua_State *L) { |
| 113 | | lua_Debug ar; |
| 114 | | int arg; |
| 115 | | lua_State *L1 = getthread(L, &arg); |
| 116 | | const char *options = luaL_optstring(L, arg+2, "flnStu"); |
| 117 | | if (lua_isnumber(L, arg+1)) { |
| 118 | | if (!lua_getstack(L1, (int)lua_tointeger(L, arg+1), &ar)) { |
| 119 | | lua_pushnil(L); /* level out of range */ |
| 120 | | return 1; |
| 121 | | } |
| 122 | | } |
| 123 | | else if (lua_isfunction(L, arg+1)) { |
| 124 | | lua_pushfstring(L, ">%s", options); |
| 125 | | options = lua_tostring(L, -1); |
| 126 | | lua_pushvalue(L, arg+1); |
| 127 | | lua_xmove(L, L1, 1); |
| 128 | | } |
| 129 | | else |
| 130 | | return luaL_argerror(L, arg+1, "function or level expected"); |
| 131 | | if (!lua_getinfo(L1, options, &ar)) |
| 132 | | return luaL_argerror(L, arg+2, "invalid option"); |
| 133 | | lua_createtable(L, 0, 2); |
| 134 | | if (strchr(options, 'S')) { |
| 135 | | settabss(L, "source", ar.source); |
| 136 | | settabss(L, "short_src", ar.short_src); |
| 137 | | settabsi(L, "linedefined", ar.linedefined); |
| 138 | | settabsi(L, "lastlinedefined", ar.lastlinedefined); |
| 139 | | settabss(L, "what", ar.what); |
| 140 | | } |
| 141 | | if (strchr(options, 'l')) |
| 142 | | settabsi(L, "currentline", ar.currentline); |
| 143 | | if (strchr(options, 'u')) { |
| 144 | | settabsi(L, "nups", ar.nups); |
| 145 | | settabsi(L, "nparams", ar.nparams); |
| 146 | | settabsb(L, "isvararg", ar.isvararg); |
| 147 | | } |
| 148 | | if (strchr(options, 'n')) { |
| 149 | | settabss(L, "name", ar.name); |
| 150 | | settabss(L, "namewhat", ar.namewhat); |
| 151 | | } |
| 152 | | if (strchr(options, 't')) |
| 153 | | settabsb(L, "istailcall", ar.istailcall); |
| 154 | | if (strchr(options, 'L')) |
| 155 | | treatstackoption(L, L1, "activelines"); |
| 156 | | if (strchr(options, 'f')) |
| 157 | | treatstackoption(L, L1, "func"); |
| 158 | | return 1; /* return table */ |
| 113 | lua_Debug ar; |
| 114 | int arg; |
| 115 | lua_State *L1 = getthread(L, &arg); |
| 116 | const char *options = luaL_optstring(L, arg+2, "flnStu"); |
| 117 | if (lua_isnumber(L, arg+1)) { |
| 118 | if (!lua_getstack(L1, (int)lua_tointeger(L, arg+1), &ar)) { |
| 119 | lua_pushnil(L); /* level out of range */ |
| 120 | return 1; |
| 121 | } |
| 122 | } |
| 123 | else if (lua_isfunction(L, arg+1)) { |
| 124 | lua_pushfstring(L, ">%s", options); |
| 125 | options = lua_tostring(L, -1); |
| 126 | lua_pushvalue(L, arg+1); |
| 127 | lua_xmove(L, L1, 1); |
| 128 | } |
| 129 | else |
| 130 | return luaL_argerror(L, arg+1, "function or level expected"); |
| 131 | if (!lua_getinfo(L1, options, &ar)) |
| 132 | return luaL_argerror(L, arg+2, "invalid option"); |
| 133 | lua_createtable(L, 0, 2); |
| 134 | if (strchr(options, 'S')) { |
| 135 | settabss(L, "source", ar.source); |
| 136 | settabss(L, "short_src", ar.short_src); |
| 137 | settabsi(L, "linedefined", ar.linedefined); |
| 138 | settabsi(L, "lastlinedefined", ar.lastlinedefined); |
| 139 | settabss(L, "what", ar.what); |
| 140 | } |
| 141 | if (strchr(options, 'l')) |
| 142 | settabsi(L, "currentline", ar.currentline); |
| 143 | if (strchr(options, 'u')) { |
| 144 | settabsi(L, "nups", ar.nups); |
| 145 | settabsi(L, "nparams", ar.nparams); |
| 146 | settabsb(L, "isvararg", ar.isvararg); |
| 147 | } |
| 148 | if (strchr(options, 'n')) { |
| 149 | settabss(L, "name", ar.name); |
| 150 | settabss(L, "namewhat", ar.namewhat); |
| 151 | } |
| 152 | if (strchr(options, 't')) |
| 153 | settabsb(L, "istailcall", ar.istailcall); |
| 154 | if (strchr(options, 'L')) |
| 155 | treatstackoption(L, L1, "activelines"); |
| 156 | if (strchr(options, 'f')) |
| 157 | treatstackoption(L, L1, "func"); |
| 158 | return 1; /* return table */ |
| 159 | 159 | } |
| 160 | 160 | |
| 161 | 161 | |
| 162 | 162 | static int db_getlocal (lua_State *L) { |
| 163 | | int arg; |
| 164 | | lua_State *L1 = getthread(L, &arg); |
| 165 | | lua_Debug ar; |
| 166 | | const char *name; |
| 167 | | int nvar = luaL_checkint(L, arg+2); /* local-variable index */ |
| 168 | | if (lua_isfunction(L, arg + 1)) { /* function argument? */ |
| 169 | | lua_pushvalue(L, arg + 1); /* push function */ |
| 170 | | lua_pushstring(L, lua_getlocal(L, NULL, nvar)); /* push local name */ |
| 171 | | return 1; |
| 172 | | } |
| 173 | | else { /* stack-level argument */ |
| 174 | | if (!lua_getstack(L1, luaL_checkint(L, arg+1), &ar)) /* out of range? */ |
| 175 | | return luaL_argerror(L, arg+1, "level out of range"); |
| 176 | | name = lua_getlocal(L1, &ar, nvar); |
| 177 | | if (name) { |
| 178 | | lua_xmove(L1, L, 1); /* push local value */ |
| 179 | | lua_pushstring(L, name); /* push name */ |
| 180 | | lua_pushvalue(L, -2); /* re-order */ |
| 181 | | return 2; |
| 182 | | } |
| 183 | | else { |
| 184 | | lua_pushnil(L); /* no name (nor value) */ |
| 185 | | return 1; |
| 186 | | } |
| 187 | | } |
| 163 | int arg; |
| 164 | lua_State *L1 = getthread(L, &arg); |
| 165 | lua_Debug ar; |
| 166 | const char *name; |
| 167 | int nvar = luaL_checkint(L, arg+2); /* local-variable index */ |
| 168 | if (lua_isfunction(L, arg + 1)) { /* function argument? */ |
| 169 | lua_pushvalue(L, arg + 1); /* push function */ |
| 170 | lua_pushstring(L, lua_getlocal(L, NULL, nvar)); /* push local name */ |
| 171 | return 1; |
| 172 | } |
| 173 | else { /* stack-level argument */ |
| 174 | if (!lua_getstack(L1, luaL_checkint(L, arg+1), &ar)) /* out of range? */ |
| 175 | return luaL_argerror(L, arg+1, "level out of range"); |
| 176 | name = lua_getlocal(L1, &ar, nvar); |
| 177 | if (name) { |
| 178 | lua_xmove(L1, L, 1); /* push local value */ |
| 179 | lua_pushstring(L, name); /* push name */ |
| 180 | lua_pushvalue(L, -2); /* re-order */ |
| 181 | return 2; |
| 182 | } |
| 183 | else { |
| 184 | lua_pushnil(L); /* no name (nor value) */ |
| 185 | return 1; |
| 186 | } |
| 187 | } |
| 188 | 188 | } |
| 189 | 189 | |
| 190 | 190 | |
| 191 | 191 | static int db_setlocal (lua_State *L) { |
| 192 | | int arg; |
| 193 | | lua_State *L1 = getthread(L, &arg); |
| 194 | | lua_Debug ar; |
| 195 | | if (!lua_getstack(L1, luaL_checkint(L, arg+1), &ar)) /* out of range? */ |
| 196 | | return luaL_argerror(L, arg+1, "level out of range"); |
| 197 | | luaL_checkany(L, arg+3); |
| 198 | | lua_settop(L, arg+3); |
| 199 | | lua_xmove(L, L1, 1); |
| 200 | | lua_pushstring(L, lua_setlocal(L1, &ar, luaL_checkint(L, arg+2))); |
| 201 | | return 1; |
| 192 | int arg; |
| 193 | lua_State *L1 = getthread(L, &arg); |
| 194 | lua_Debug ar; |
| 195 | if (!lua_getstack(L1, luaL_checkint(L, arg+1), &ar)) /* out of range? */ |
| 196 | return luaL_argerror(L, arg+1, "level out of range"); |
| 197 | luaL_checkany(L, arg+3); |
| 198 | lua_settop(L, arg+3); |
| 199 | lua_xmove(L, L1, 1); |
| 200 | lua_pushstring(L, lua_setlocal(L1, &ar, luaL_checkint(L, arg+2))); |
| 201 | return 1; |
| 202 | 202 | } |
| 203 | 203 | |
| 204 | 204 | |
| 205 | 205 | static int auxupvalue (lua_State *L, int get) { |
| 206 | | const char *name; |
| 207 | | int n = luaL_checkint(L, 2); |
| 208 | | luaL_checktype(L, 1, LUA_TFUNCTION); |
| 209 | | name = get ? lua_getupvalue(L, 1, n) : lua_setupvalue(L, 1, n); |
| 210 | | if (name == NULL) return 0; |
| 211 | | lua_pushstring(L, name); |
| 212 | | lua_insert(L, -(get+1)); |
| 213 | | return get + 1; |
| 206 | const char *name; |
| 207 | int n = luaL_checkint(L, 2); |
| 208 | luaL_checktype(L, 1, LUA_TFUNCTION); |
| 209 | name = get ? lua_getupvalue(L, 1, n) : lua_setupvalue(L, 1, n); |
| 210 | if (name == NULL) return 0; |
| 211 | lua_pushstring(L, name); |
| 212 | lua_insert(L, -(get+1)); |
| 213 | return get + 1; |
| 214 | 214 | } |
| 215 | 215 | |
| 216 | 216 | |
| 217 | 217 | static int db_getupvalue (lua_State *L) { |
| 218 | | return auxupvalue(L, 1); |
| 218 | return auxupvalue(L, 1); |
| 219 | 219 | } |
| 220 | 220 | |
| 221 | 221 | |
| 222 | 222 | static int db_setupvalue (lua_State *L) { |
| 223 | | luaL_checkany(L, 3); |
| 224 | | return auxupvalue(L, 0); |
| 223 | luaL_checkany(L, 3); |
| 224 | return auxupvalue(L, 0); |
| 225 | 225 | } |
| 226 | 226 | |
| 227 | 227 | |
| 228 | 228 | static int checkupval (lua_State *L, int argf, int argnup) { |
| 229 | | lua_Debug ar; |
| 230 | | int nup = luaL_checkint(L, argnup); |
| 231 | | luaL_checktype(L, argf, LUA_TFUNCTION); |
| 232 | | lua_pushvalue(L, argf); |
| 233 | | lua_getinfo(L, ">u", &ar); |
| 234 | | luaL_argcheck(L, 1 <= nup && nup <= ar.nups, argnup, "invalid upvalue index"); |
| 235 | | return nup; |
| 229 | lua_Debug ar; |
| 230 | int nup = luaL_checkint(L, argnup); |
| 231 | luaL_checktype(L, argf, LUA_TFUNCTION); |
| 232 | lua_pushvalue(L, argf); |
| 233 | lua_getinfo(L, ">u", &ar); |
| 234 | luaL_argcheck(L, 1 <= nup && nup <= ar.nups, argnup, "invalid upvalue index"); |
| 235 | return nup; |
| 236 | 236 | } |
| 237 | 237 | |
| 238 | 238 | |
| 239 | 239 | static int db_upvalueid (lua_State *L) { |
| 240 | | int n = checkupval(L, 1, 2); |
| 241 | | lua_pushlightuserdata(L, lua_upvalueid(L, 1, n)); |
| 242 | | return 1; |
| 240 | int n = checkupval(L, 1, 2); |
| 241 | lua_pushlightuserdata(L, lua_upvalueid(L, 1, n)); |
| 242 | return 1; |
| 243 | 243 | } |
| 244 | 244 | |
| 245 | 245 | |
| 246 | 246 | static int db_upvaluejoin (lua_State *L) { |
| 247 | | int n1 = checkupval(L, 1, 2); |
| 248 | | int n2 = checkupval(L, 3, 4); |
| 249 | | luaL_argcheck(L, !lua_iscfunction(L, 1), 1, "Lua function expected"); |
| 250 | | luaL_argcheck(L, !lua_iscfunction(L, 3), 3, "Lua function expected"); |
| 251 | | lua_upvaluejoin(L, 1, n1, 3, n2); |
| 252 | | return 0; |
| 247 | int n1 = checkupval(L, 1, 2); |
| 248 | int n2 = checkupval(L, 3, 4); |
| 249 | luaL_argcheck(L, !lua_iscfunction(L, 1), 1, "Lua function expected"); |
| 250 | luaL_argcheck(L, !lua_iscfunction(L, 3), 3, "Lua function expected"); |
| 251 | lua_upvaluejoin(L, 1, n1, 3, n2); |
| 252 | return 0; |
| 253 | 253 | } |
| 254 | 254 | |
| 255 | 255 | |
| 256 | | #define gethooktable(L) luaL_getsubtable(L, LUA_REGISTRYINDEX, HOOKKEY) |
| 256 | #define gethooktable(L) luaL_getsubtable(L, LUA_REGISTRYINDEX, HOOKKEY) |
| 257 | 257 | |
| 258 | 258 | |
| 259 | 259 | static void hookf (lua_State *L, lua_Debug *ar) { |
| 260 | | static const char *const hooknames[] = |
| 261 | | {"call", "return", "line", "count", "tail call"}; |
| 262 | | gethooktable(L); |
| 263 | | lua_pushthread(L); |
| 264 | | lua_rawget(L, -2); |
| 265 | | if (lua_isfunction(L, -1)) { |
| 266 | | lua_pushstring(L, hooknames[(int)ar->event]); |
| 267 | | if (ar->currentline >= 0) |
| 268 | | lua_pushinteger(L, ar->currentline); |
| 269 | | else lua_pushnil(L); |
| 270 | | lua_assert(lua_getinfo(L, "lS", ar)); |
| 271 | | lua_call(L, 2, 0); |
| 272 | | } |
| 260 | static const char *const hooknames[] = |
| 261 | {"call", "return", "line", "count", "tail call"}; |
| 262 | gethooktable(L); |
| 263 | lua_pushthread(L); |
| 264 | lua_rawget(L, -2); |
| 265 | if (lua_isfunction(L, -1)) { |
| 266 | lua_pushstring(L, hooknames[(int)ar->event]); |
| 267 | if (ar->currentline >= 0) |
| 268 | lua_pushinteger(L, ar->currentline); |
| 269 | else lua_pushnil(L); |
| 270 | lua_assert(lua_getinfo(L, "lS", ar)); |
| 271 | lua_call(L, 2, 0); |
| 272 | } |
| 273 | 273 | } |
| 274 | 274 | |
| 275 | 275 | |
| 276 | 276 | static int makemask (const char *smask, int count) { |
| 277 | | int mask = 0; |
| 278 | | if (strchr(smask, 'c')) mask |= LUA_MASKCALL; |
| 279 | | if (strchr(smask, 'r')) mask |= LUA_MASKRET; |
| 280 | | if (strchr(smask, 'l')) mask |= LUA_MASKLINE; |
| 281 | | if (count > 0) mask |= LUA_MASKCOUNT; |
| 282 | | return mask; |
| 277 | int mask = 0; |
| 278 | if (strchr(smask, 'c')) mask |= LUA_MASKCALL; |
| 279 | if (strchr(smask, 'r')) mask |= LUA_MASKRET; |
| 280 | if (strchr(smask, 'l')) mask |= LUA_MASKLINE; |
| 281 | if (count > 0) mask |= LUA_MASKCOUNT; |
| 282 | return mask; |
| 283 | 283 | } |
| 284 | 284 | |
| 285 | 285 | |
| 286 | 286 | static char *unmakemask (int mask, char *smask) { |
| 287 | | int i = 0; |
| 288 | | if (mask & LUA_MASKCALL) smask[i++] = 'c'; |
| 289 | | if (mask & LUA_MASKRET) smask[i++] = 'r'; |
| 290 | | if (mask & LUA_MASKLINE) smask[i++] = 'l'; |
| 291 | | smask[i] = '\0'; |
| 292 | | return smask; |
| 287 | int i = 0; |
| 288 | if (mask & LUA_MASKCALL) smask[i++] = 'c'; |
| 289 | if (mask & LUA_MASKRET) smask[i++] = 'r'; |
| 290 | if (mask & LUA_MASKLINE) smask[i++] = 'l'; |
| 291 | smask[i] = '\0'; |
| 292 | return smask; |
| 293 | 293 | } |
| 294 | 294 | |
| 295 | 295 | |
| 296 | 296 | static int db_sethook (lua_State *L) { |
| 297 | | int arg, mask, count; |
| 298 | | lua_Hook func; |
| 299 | | lua_State *L1 = getthread(L, &arg); |
| 300 | | if (lua_isnoneornil(L, arg+1)) { |
| 301 | | lua_settop(L, arg+1); |
| 302 | | func = NULL; mask = 0; count = 0; /* turn off hooks */ |
| 303 | | } |
| 304 | | else { |
| 305 | | const char *smask = luaL_checkstring(L, arg+2); |
| 306 | | luaL_checktype(L, arg+1, LUA_TFUNCTION); |
| 307 | | count = luaL_optint(L, arg+3, 0); |
| 308 | | func = hookf; mask = makemask(smask, count); |
| 309 | | } |
| 310 | | if (gethooktable(L) == 0) { /* creating hook table? */ |
| 311 | | lua_pushstring(L, "k"); |
| 312 | | lua_setfield(L, -2, "__mode"); /** hooktable.__mode = "k" */ |
| 313 | | lua_pushvalue(L, -1); |
| 314 | | lua_setmetatable(L, -2); /* setmetatable(hooktable) = hooktable */ |
| 315 | | } |
| 316 | | lua_pushthread(L1); lua_xmove(L1, L, 1); |
| 317 | | lua_pushvalue(L, arg+1); |
| 318 | | lua_rawset(L, -3); /* set new hook */ |
| 319 | | lua_sethook(L1, func, mask, count); /* set hooks */ |
| 320 | | return 0; |
| 297 | int arg, mask, count; |
| 298 | lua_Hook func; |
| 299 | lua_State *L1 = getthread(L, &arg); |
| 300 | if (lua_isnoneornil(L, arg+1)) { |
| 301 | lua_settop(L, arg+1); |
| 302 | func = NULL; mask = 0; count = 0; /* turn off hooks */ |
| 303 | } |
| 304 | else { |
| 305 | const char *smask = luaL_checkstring(L, arg+2); |
| 306 | luaL_checktype(L, arg+1, LUA_TFUNCTION); |
| 307 | count = luaL_optint(L, arg+3, 0); |
| 308 | func = hookf; mask = makemask(smask, count); |
| 309 | } |
| 310 | if (gethooktable(L) == 0) { /* creating hook table? */ |
| 311 | lua_pushstring(L, "k"); |
| 312 | lua_setfield(L, -2, "__mode"); /** hooktable.__mode = "k" */ |
| 313 | lua_pushvalue(L, -1); |
| 314 | lua_setmetatable(L, -2); /* setmetatable(hooktable) = hooktable */ |
| 315 | } |
| 316 | lua_pushthread(L1); lua_xmove(L1, L, 1); |
| 317 | lua_pushvalue(L, arg+1); |
| 318 | lua_rawset(L, -3); /* set new hook */ |
| 319 | lua_sethook(L1, func, mask, count); /* set hooks */ |
| 320 | return 0; |
| 321 | 321 | } |
| 322 | 322 | |
| 323 | 323 | |
| 324 | 324 | static int db_gethook (lua_State *L) { |
| 325 | | int arg; |
| 326 | | lua_State *L1 = getthread(L, &arg); |
| 327 | | char buff[5]; |
| 328 | | int mask = lua_gethookmask(L1); |
| 329 | | lua_Hook hook = lua_gethook(L1); |
| 330 | | if (hook != NULL && hook != hookf) /* external hook? */ |
| 331 | | lua_pushliteral(L, "external hook"); |
| 332 | | else { |
| 333 | | gethooktable(L); |
| 334 | | lua_pushthread(L1); lua_xmove(L1, L, 1); |
| 335 | | lua_rawget(L, -2); /* get hook */ |
| 336 | | lua_remove(L, -2); /* remove hook table */ |
| 337 | | } |
| 338 | | lua_pushstring(L, unmakemask(mask, buff)); |
| 339 | | lua_pushinteger(L, lua_gethookcount(L1)); |
| 340 | | return 3; |
| 325 | int arg; |
| 326 | lua_State *L1 = getthread(L, &arg); |
| 327 | char buff[5]; |
| 328 | int mask = lua_gethookmask(L1); |
| 329 | lua_Hook hook = lua_gethook(L1); |
| 330 | if (hook != NULL && hook != hookf) /* external hook? */ |
| 331 | lua_pushliteral(L, "external hook"); |
| 332 | else { |
| 333 | gethooktable(L); |
| 334 | lua_pushthread(L1); lua_xmove(L1, L, 1); |
| 335 | lua_rawget(L, -2); /* get hook */ |
| 336 | lua_remove(L, -2); /* remove hook table */ |
| 337 | } |
| 338 | lua_pushstring(L, unmakemask(mask, buff)); |
| 339 | lua_pushinteger(L, lua_gethookcount(L1)); |
| 340 | return 3; |
| 341 | 341 | } |
| 342 | 342 | |
| 343 | 343 | |
| 344 | 344 | static int db_debug (lua_State *L) { |
| 345 | | for (;;) { |
| 346 | | char buffer[250]; |
| 347 | | luai_writestringerror("%s", "lua_debug> "); |
| 348 | | if (fgets(buffer, sizeof(buffer), stdin) == 0 || |
| 349 | | strcmp(buffer, "cont\n") == 0) |
| 350 | | return 0; |
| 351 | | if (luaL_loadbuffer(L, buffer, strlen(buffer), "=(debug command)") || |
| 352 | | lua_pcall(L, 0, 0, 0)) |
| 353 | | luai_writestringerror("%s\n", lua_tostring(L, -1)); |
| 354 | | lua_settop(L, 0); /* remove eventual returns */ |
| 355 | | } |
| 345 | for (;;) { |
| 346 | char buffer[250]; |
| 347 | luai_writestringerror("%s", "lua_debug> "); |
| 348 | if (fgets(buffer, sizeof(buffer), stdin) == 0 || |
| 349 | strcmp(buffer, "cont\n") == 0) |
| 350 | return 0; |
| 351 | if (luaL_loadbuffer(L, buffer, strlen(buffer), "=(debug command)") || |
| 352 | lua_pcall(L, 0, 0, 0)) |
| 353 | luai_writestringerror("%s\n", lua_tostring(L, -1)); |
| 354 | lua_settop(L, 0); /* remove eventual returns */ |
| 355 | } |
| 356 | 356 | } |
| 357 | 357 | |
| 358 | 358 | |
| 359 | 359 | static int db_traceback (lua_State *L) { |
| 360 | | int arg; |
| 361 | | lua_State *L1 = getthread(L, &arg); |
| 362 | | const char *msg = lua_tostring(L, arg + 1); |
| 363 | | if (msg == NULL && !lua_isnoneornil(L, arg + 1)) /* non-string 'msg'? */ |
| 364 | | lua_pushvalue(L, arg + 1); /* return it untouched */ |
| 365 | | else { |
| 366 | | int level = luaL_optint(L, arg + 2, (L == L1) ? 1 : 0); |
| 367 | | luaL_traceback(L, L1, msg, level); |
| 368 | | } |
| 369 | | return 1; |
| 360 | int arg; |
| 361 | lua_State *L1 = getthread(L, &arg); |
| 362 | const char *msg = lua_tostring(L, arg + 1); |
| 363 | if (msg == NULL && !lua_isnoneornil(L, arg + 1)) /* non-string 'msg'? */ |
| 364 | lua_pushvalue(L, arg + 1); /* return it untouched */ |
| 365 | else { |
| 366 | int level = luaL_optint(L, arg + 2, (L == L1) ? 1 : 0); |
| 367 | luaL_traceback(L, L1, msg, level); |
| 368 | } |
| 369 | return 1; |
| 370 | 370 | } |
| 371 | 371 | |
| 372 | 372 | |
| 373 | 373 | static const luaL_Reg dblib[] = { |
| 374 | | {"debug", db_debug}, |
| 375 | | {"getuservalue", db_getuservalue}, |
| 376 | | {"gethook", db_gethook}, |
| 377 | | {"getinfo", db_getinfo}, |
| 378 | | {"getlocal", db_getlocal}, |
| 379 | | {"getregistry", db_getregistry}, |
| 380 | | {"getmetatable", db_getmetatable}, |
| 381 | | {"getupvalue", db_getupvalue}, |
| 382 | | {"upvaluejoin", db_upvaluejoin}, |
| 383 | | {"upvalueid", db_upvalueid}, |
| 384 | | {"setuservalue", db_setuservalue}, |
| 385 | | {"sethook", db_sethook}, |
| 386 | | {"setlocal", db_setlocal}, |
| 387 | | {"setmetatable", db_setmetatable}, |
| 388 | | {"setupvalue", db_setupvalue}, |
| 389 | | {"traceback", db_traceback}, |
| 390 | | {NULL, NULL} |
| 374 | {"debug", db_debug}, |
| 375 | {"getuservalue", db_getuservalue}, |
| 376 | {"gethook", db_gethook}, |
| 377 | {"getinfo", db_getinfo}, |
| 378 | {"getlocal", db_getlocal}, |
| 379 | {"getregistry", db_getregistry}, |
| 380 | {"getmetatable", db_getmetatable}, |
| 381 | {"getupvalue", db_getupvalue}, |
| 382 | {"upvaluejoin", db_upvaluejoin}, |
| 383 | {"upvalueid", db_upvalueid}, |
| 384 | {"setuservalue", db_setuservalue}, |
| 385 | {"sethook", db_sethook}, |
| 386 | {"setlocal", db_setlocal}, |
| 387 | {"setmetatable", db_setmetatable}, |
| 388 | {"setupvalue", db_setupvalue}, |
| 389 | {"traceback", db_traceback}, |
| 390 | {NULL, NULL} |
| 391 | 391 | }; |
| 392 | 392 | |
| 393 | 393 | |
| 394 | 394 | LUAMOD_API int luaopen_debug (lua_State *L) { |
| 395 | | luaL_newlib(L, dblib); |
| 396 | | return 1; |
| 395 | luaL_newlib(L, dblib); |
| 396 | return 1; |
| 397 | 397 | } |
| 398 | |
trunk/src/lib/lua/lvm.c
| r30857 | r30858 | |
| 1 | 1 | /* |
| 2 | | ** $Id: lvm.c,v 2.155 2013/03/16 21:10:18 roberto Exp $ |
| 2 | ** $Id: lvm.c,v 2.155.1.1 2013/04/12 18:48:47 roberto Exp $ |
| 3 | 3 | ** Lua virtual machine |
| 4 | 4 | ** See Copyright Notice in lua.h |
| 5 | 5 | */ |
| r30857 | r30858 | |
| 29 | 29 | |
| 30 | 30 | |
| 31 | 31 | /* limit for table tag-method chains (to avoid loops) */ |
| 32 | | #define MAXTAGLOOP 100 |
| 32 | #define MAXTAGLOOP 100 |
| 33 | 33 | |
| 34 | 34 | |
| 35 | 35 | const TValue *luaV_tonumber (const TValue *obj, TValue *n) { |
| 36 | | lua_Number num; |
| 37 | | if (ttisnumber(obj)) return obj; |
| 38 | | if (ttisstring(obj) && luaO_str2d(svalue(obj), tsvalue(obj)->len, &num)) { |
| 39 | | setnvalue(n, num); |
| 40 | | return n; |
| 41 | | } |
| 42 | | else |
| 43 | | return NULL; |
| 36 | lua_Number num; |
| 37 | if (ttisnumber(obj)) return obj; |
| 38 | if (ttisstring(obj) && luaO_str2d(svalue(obj), tsvalue(obj)->len, &num)) { |
| 39 | setnvalue(n, num); |
| 40 | return n; |
| 41 | } |
| 42 | else |
| 43 | return NULL; |
| 44 | 44 | } |
| 45 | 45 | |
| 46 | 46 | |
| 47 | 47 | int luaV_tostring (lua_State *L, StkId obj) { |
| 48 | | if (!ttisnumber(obj)) |
| 49 | | return 0; |
| 50 | | else { |
| 51 | | char s[LUAI_MAXNUMBER2STR]; |
| 52 | | lua_Number n = nvalue(obj); |
| 53 | | int l = lua_number2str(s, n); |
| 54 | | setsvalue2s(L, obj, luaS_newlstr(L, s, l)); |
| 55 | | return 1; |
| 56 | | } |
| 48 | if (!ttisnumber(obj)) |
| 49 | return 0; |
| 50 | else { |
| 51 | char s[LUAI_MAXNUMBER2STR]; |
| 52 | lua_Number n = nvalue(obj); |
| 53 | int l = lua_number2str(s, n); |
| 54 | setsvalue2s(L, obj, luaS_newlstr(L, s, l)); |
| 55 | return 1; |
| 56 | } |
| 57 | 57 | } |
| 58 | 58 | |
| 59 | 59 | |
| 60 | 60 | static void traceexec (lua_State *L) { |
| 61 | | CallInfo *ci = L->ci; |
| 62 | | lu_byte mask = L->hookmask; |
| 63 | | int counthook = ((mask & LUA_MASKCOUNT) && L->hookcount == 0); |
| 64 | | if (counthook) |
| 65 | | resethookcount(L); /* reset count */ |
| 66 | | if (ci->callstatus & CIST_HOOKYIELD) { /* called hook last time? */ |
| 67 | | ci->callstatus &= ~CIST_HOOKYIELD; /* erase mark */ |
| 68 | | return; /* do not call hook again (VM yielded, so it did not move) */ |
| 69 | | } |
| 70 | | if (counthook) |
| 71 | | luaD_hook(L, LUA_HOOKCOUNT, -1); /* call count hook */ |
| 72 | | if (mask & LUA_MASKLINE) { |
| 73 | | Proto *p = ci_func(ci)->p; |
| 74 | | int npc = pcRel(ci->u.l.savedpc, p); |
| 75 | | int newline = getfuncline(p, npc); |
| 76 | | if (npc == 0 || /* call linehook when enter a new function, */ |
| 77 | | ci->u.l.savedpc <= L->oldpc || /* when jump back (loop), or when */ |
| 78 | | newline != getfuncline(p, pcRel(L->oldpc, p))) /* enter a new line */ |
| 79 | | luaD_hook(L, LUA_HOOKLINE, newline); /* call line hook */ |
| 80 | | } |
| 81 | | L->oldpc = ci->u.l.savedpc; |
| 82 | | if (L->status == LUA_YIELD) { /* did hook yield? */ |
| 83 | | if (counthook) |
| 84 | | L->hookcount = 1; /* undo decrement to zero */ |
| 85 | | ci->u.l.savedpc--; /* undo increment (resume will increment it again) */ |
| 86 | | ci->callstatus |= CIST_HOOKYIELD; /* mark that it yielded */ |
| 87 | | ci->func = L->top - 1; /* protect stack below results */ |
| 88 | | luaD_throw(L, LUA_YIELD); |
| 89 | | } |
| 61 | CallInfo *ci = L->ci; |
| 62 | lu_byte mask = L->hookmask; |
| 63 | int counthook = ((mask & LUA_MASKCOUNT) && L->hookcount == 0); |
| 64 | if (counthook) |
| 65 | resethookcount(L); /* reset count */ |
| 66 | if (ci->callstatus & CIST_HOOKYIELD) { /* called hook last time? */ |
| 67 | ci->callstatus &= ~CIST_HOOKYIELD; /* erase mark */ |
| 68 | return; /* do not call hook again (VM yielded, so it did not move) */ |
| 69 | } |
| 70 | if (counthook) |
| 71 | luaD_hook(L, LUA_HOOKCOUNT, -1); /* call count hook */ |
| 72 | if (mask & LUA_MASKLINE) { |
| 73 | Proto *p = ci_func(ci)->p; |
| 74 | int npc = pcRel(ci->u.l.savedpc, p); |
| 75 | int newline = getfuncline(p, npc); |
| 76 | if (npc == 0 || /* call linehook when enter a new function, */ |
| 77 | ci->u.l.savedpc <= L->oldpc || /* when jump back (loop), or when */ |
| 78 | newline != getfuncline(p, pcRel(L->oldpc, p))) /* enter a new line */ |
| 79 | luaD_hook(L, LUA_HOOKLINE, newline); /* call line hook */ |
| 80 | } |
| 81 | L->oldpc = ci->u.l.savedpc; |
| 82 | if (L->status == LUA_YIELD) { /* did hook yield? */ |
| 83 | if (counthook) |
| 84 | L->hookcount = 1; /* undo decrement to zero */ |
| 85 | ci->u.l.savedpc--; /* undo increment (resume will increment it again) */ |
| 86 | ci->callstatus |= CIST_HOOKYIELD; /* mark that it yielded */ |
| 87 | ci->func = L->top - 1; /* protect stack below results */ |
| 88 | luaD_throw(L, LUA_YIELD); |
| 89 | } |
| 90 | 90 | } |
| 91 | 91 | |
| 92 | 92 | |
| 93 | 93 | static void callTM (lua_State *L, const TValue *f, const TValue *p1, |
| 94 | | const TValue *p2, TValue *p3, int hasres) { |
| 95 | | ptrdiff_t result = savestack(L, p3); |
| 96 | | setobj2s(L, L->top++, f); /* push function */ |
| 97 | | setobj2s(L, L->top++, p1); /* 1st argument */ |
| 98 | | setobj2s(L, L->top++, p2); /* 2nd argument */ |
| 99 | | if (!hasres) /* no result? 'p3' is third argument */ |
| 100 | | setobj2s(L, L->top++, p3); /* 3rd argument */ |
| 101 | | /* metamethod may yield only when called from Lua code */ |
| 102 | | luaD_call(L, L->top - (4 - hasres), hasres, isLua(L->ci)); |
| 103 | | if (hasres) { /* if has result, move it to its place */ |
| 104 | | p3 = restorestack(L, result); |
| 105 | | setobjs2s(L, p3, --L->top); |
| 106 | | } |
| 94 | const TValue *p2, TValue *p3, int hasres) { |
| 95 | ptrdiff_t result = savestack(L, p3); |
| 96 | setobj2s(L, L->top++, f); /* push function */ |
| 97 | setobj2s(L, L->top++, p1); /* 1st argument */ |
| 98 | setobj2s(L, L->top++, p2); /* 2nd argument */ |
| 99 | if (!hasres) /* no result? 'p3' is third argument */ |
| 100 | setobj2s(L, L->top++, p3); /* 3rd argument */ |
| 101 | /* metamethod may yield only when called from Lua code */ |
| 102 | luaD_call(L, L->top - (4 - hasres), hasres, isLua(L->ci)); |
| 103 | if (hasres) { /* if has result, move it to its place */ |
| 104 | p3 = restorestack(L, result); |
| 105 | setobjs2s(L, p3, --L->top); |
| 106 | } |
| 107 | 107 | } |
| 108 | 108 | |
| 109 | 109 | |
| 110 | 110 | void luaV_gettable (lua_State *L, const TValue *t, TValue *key, StkId val) { |
| 111 | | int loop; |
| 112 | | for (loop = 0; loop < MAXTAGLOOP; loop++) { |
| 113 | | const TValue *tm; |
| 114 | | if (ttistable(t)) { /* `t' is a table? */ |
| 115 | | Table *h = hvalue(t); |
| 116 | | const TValue *res = luaH_get(h, key); /* do a primitive get */ |
| 117 | | if (!ttisnil(res) || /* result is not nil? */ |
| 118 | | (tm = fasttm(L, h->metatable, TM_INDEX)) == NULL) { /* or no TM? */ |
| 119 | | setobj2s(L, val, res); |
| 120 | | return; |
| 121 | | } |
| 122 | | /* else will try the tag method */ |
| 123 | | } |
| 124 | | else if (ttisnil(tm = luaT_gettmbyobj(L, t, TM_INDEX))) |
| 125 | | luaG_typeerror(L, t, "index"); |
| 126 | | if (ttisfunction(tm)) { |
| 127 | | callTM(L, tm, t, key, val, 1); |
| 128 | | return; |
| 129 | | } |
| 130 | | t = tm; /* else repeat with 'tm' */ |
| 131 | | } |
| 132 | | luaG_runerror(L, "loop in gettable"); |
| 111 | int loop; |
| 112 | for (loop = 0; loop < MAXTAGLOOP; loop++) { |
| 113 | const TValue *tm; |
| 114 | if (ttistable(t)) { /* `t' is a table? */ |
| 115 | Table *h = hvalue(t); |
| 116 | const TValue *res = luaH_get(h, key); /* do a primitive get */ |
| 117 | if (!ttisnil(res) || /* result is not nil? */ |
| 118 | (tm = fasttm(L, h->metatable, TM_INDEX)) == NULL) { /* or no TM? */ |
| 119 | setobj2s(L, val, res); |
| 120 | return; |
| 121 | } |
| 122 | /* else will try the tag method */ |
| 123 | } |
| 124 | else if (ttisnil(tm = luaT_gettmbyobj(L, t, TM_INDEX))) |
| 125 | luaG_typeerror(L, t, "index"); |
| 126 | if (ttisfunction(tm)) { |
| 127 | callTM(L, tm, t, key, val, 1); |
| 128 | return; |
| 129 | } |
| 130 | t = tm; /* else repeat with 'tm' */ |
| 131 | } |
| 132 | luaG_runerror(L, "loop in gettable"); |
| 133 | 133 | } |
| 134 | 134 | |
| 135 | 135 | |
| 136 | 136 | void luaV_settable (lua_State *L, const TValue *t, TValue *key, StkId val) { |
| 137 | | int loop; |
| 138 | | for (loop = 0; loop < MAXTAGLOOP; loop++) { |
| 139 | | const TValue *tm; |
| 140 | | if (ttistable(t)) { /* `t' is a table? */ |
| 141 | | Table *h = hvalue(t); |
| 142 | | TValue *oldval = cast(TValue *, luaH_get(h, key)); |
| 143 | | /* if previous value is not nil, there must be a previous entry |
| 144 | | in the table; moreover, a metamethod has no relevance */ |
| 145 | | if (!ttisnil(oldval) || |
| 146 | | /* previous value is nil; must check the metamethod */ |
| 147 | | ((tm = fasttm(L, h->metatable, TM_NEWINDEX)) == NULL && |
| 148 | | /* no metamethod; is there a previous entry in the table? */ |
| 149 | | (oldval != luaO_nilobject || |
| 150 | | /* no previous entry; must create one. (The next test is |
| 151 | | always true; we only need the assignment.) */ |
| 152 | | (oldval = luaH_newkey(L, h, key), 1)))) { |
| 153 | | /* no metamethod and (now) there is an entry with given key */ |
| 154 | | setobj2t(L, oldval, val); /* assign new value to that entry */ |
| 155 | | invalidateTMcache(h); |
| 156 | | luaC_barrierback(L, obj2gco(h), val); |
| 157 | | return; |
| 158 | | } |
| 159 | | /* else will try the metamethod */ |
| 160 | | } |
| 161 | | else /* not a table; check metamethod */ |
| 162 | | if (ttisnil(tm = luaT_gettmbyobj(L, t, TM_NEWINDEX))) |
| 163 | | luaG_typeerror(L, t, "index"); |
| 164 | | /* there is a metamethod */ |
| 165 | | if (ttisfunction(tm)) { |
| 166 | | callTM(L, tm, t, key, val, 0); |
| 167 | | return; |
| 168 | | } |
| 169 | | t = tm; /* else repeat with 'tm' */ |
| 170 | | } |
| 171 | | luaG_runerror(L, "loop in settable"); |
| 137 | int loop; |
| 138 | for (loop = 0; loop < MAXTAGLOOP; loop++) { |
| 139 | const TValue *tm; |
| 140 | if (ttistable(t)) { /* `t' is a table? */ |
| 141 | Table *h = hvalue(t); |
| 142 | TValue *oldval = cast(TValue *, luaH_get(h, key)); |
| 143 | /* if previous value is not nil, there must be a previous entry |
| 144 | in the table; moreover, a metamethod has no relevance */ |
| 145 | if (!ttisnil(oldval) || |
| 146 | /* previous value is nil; must check the metamethod */ |
| 147 | ((tm = fasttm(L, h->metatable, TM_NEWINDEX)) == NULL && |
| 148 | /* no metamethod; is there a previous entry in the table? */ |
| 149 | (oldval != luaO_nilobject || |
| 150 | /* no previous entry; must create one. (The next test is |
| 151 | always true; we only need the assignment.) */ |
| 152 | (oldval = luaH_newkey(L, h, key), 1)))) { |
| 153 | /* no metamethod and (now) there is an entry with given key */ |
| 154 | setobj2t(L, oldval, val); /* assign new value to that entry */ |
| 155 | invalidateTMcache(h); |
| 156 | luaC_barrierback(L, obj2gco(h), val); |
| 157 | return; |
| 158 | } |
| 159 | /* else will try the metamethod */ |
| 160 | } |
| 161 | else /* not a table; check metamethod */ |
| 162 | if (ttisnil(tm = luaT_gettmbyobj(L, t, TM_NEWINDEX))) |
| 163 | luaG_typeerror(L, t, "index"); |
| 164 | /* there is a metamethod */ |
| 165 | if (ttisfunction(tm)) { |
| 166 | callTM(L, tm, t, key, val, 0); |
| 167 | return; |
| 168 | } |
| 169 | t = tm; /* else repeat with 'tm' */ |
| 170 | } |
| 171 | luaG_runerror(L, "loop in settable"); |
| 172 | 172 | } |
| 173 | 173 | |
| 174 | 174 | |
| 175 | 175 | static int call_binTM (lua_State *L, const TValue *p1, const TValue *p2, |
| 176 | | StkId res, TMS event) { |
| 177 | | const TValue *tm = luaT_gettmbyobj(L, p1, event); /* try first operand */ |
| 178 | | if (ttisnil(tm)) |
| 179 | | tm = luaT_gettmbyobj(L, p2, event); /* try second operand */ |
| 180 | | if (ttisnil(tm)) return 0; |
| 181 | | callTM(L, tm, p1, p2, res, 1); |
| 182 | | return 1; |
| 176 | StkId res, TMS event) { |
| 177 | const TValue *tm = luaT_gettmbyobj(L, p1, event); /* try first operand */ |
| 178 | if (ttisnil(tm)) |
| 179 | tm = luaT_gettmbyobj(L, p2, event); /* try second operand */ |
| 180 | if (ttisnil(tm)) return 0; |
| 181 | callTM(L, tm, p1, p2, res, 1); |
| 182 | return 1; |
| 183 | 183 | } |
| 184 | 184 | |
| 185 | 185 | |
| 186 | 186 | static const TValue *get_equalTM (lua_State *L, Table *mt1, Table *mt2, |
| 187 | | TMS event) { |
| 188 | | const TValue *tm1 = fasttm(L, mt1, event); |
| 189 | | const TValue *tm2; |
| 190 | | if (tm1 == NULL) return NULL; /* no metamethod */ |
| 191 | | if (mt1 == mt2) return tm1; /* same metatables => same metamethods */ |
| 192 | | tm2 = fasttm(L, mt2, event); |
| 193 | | if (tm2 == NULL) return NULL; /* no metamethod */ |
| 194 | | if (luaV_rawequalobj(tm1, tm2)) /* same metamethods? */ |
| 195 | | return tm1; |
| 196 | | return NULL; |
| 187 | TMS event) { |
| 188 | const TValue *tm1 = fasttm(L, mt1, event); |
| 189 | const TValue *tm2; |
| 190 | if (tm1 == NULL) return NULL; /* no metamethod */ |
| 191 | if (mt1 == mt2) return tm1; /* same metatables => same metamethods */ |
| 192 | tm2 = fasttm(L, mt2, event); |
| 193 | if (tm2 == NULL) return NULL; /* no metamethod */ |
| 194 | if (luaV_rawequalobj(tm1, tm2)) /* same metamethods? */ |
| 195 | return tm1; |
| 196 | return NULL; |
| 197 | 197 | } |
| 198 | 198 | |
| 199 | 199 | |
| 200 | 200 | static int call_orderTM (lua_State *L, const TValue *p1, const TValue *p2, |
| 201 | | TMS event) { |
| 202 | | if (!call_binTM(L, p1, p2, L->top, event)) |
| 203 | | return -1; /* no metamethod */ |
| 204 | | else |
| 205 | | return !l_isfalse(L->top); |
| 201 | TMS event) { |
| 202 | if (!call_binTM(L, p1, p2, L->top, event)) |
| 203 | return -1; /* no metamethod */ |
| 204 | else |
| 205 | return !l_isfalse(L->top); |
| 206 | 206 | } |
| 207 | 207 | |
| 208 | 208 | |
| 209 | 209 | static int l_strcmp (const TString *ls, const TString *rs) { |
| 210 | | const char *l = getstr(ls); |
| 211 | | size_t ll = ls->tsv.len; |
| 212 | | const char *r = getstr(rs); |
| 213 | | size_t lr = rs->tsv.len; |
| 214 | | for (;;) { |
| 215 | | int temp = strcoll(l, r); |
| 216 | | if (temp != 0) return temp; |
| 217 | | else { /* strings are equal up to a `\0' */ |
| 218 | | size_t len = strlen(l); /* index of first `\0' in both strings */ |
| 219 | | if (len == lr) /* r is finished? */ |
| 220 | | return (len == ll) ? 0 : 1; |
| 221 | | else if (len == ll) /* l is finished? */ |
| 222 | | return -1; /* l is smaller than r (because r is not finished) */ |
| 223 | | /* both strings longer than `len'; go on comparing (after the `\0') */ |
| 224 | | len++; |
| 225 | | l += len; ll -= len; r += len; lr -= len; |
| 226 | | } |
| 227 | | } |
| 210 | const char *l = getstr(ls); |
| 211 | size_t ll = ls->tsv.len; |
| 212 | const char *r = getstr(rs); |
| 213 | size_t lr = rs->tsv.len; |
| 214 | for (;;) { |
| 215 | int temp = strcoll(l, r); |
| 216 | if (temp != 0) return temp; |
| 217 | else { /* strings are equal up to a `\0' */ |
| 218 | size_t len = strlen(l); /* index of first `\0' in both strings */ |
| 219 | if (len == lr) /* r is finished? */ |
| 220 | return (len == ll) ? 0 : 1; |
| 221 | else if (len == ll) /* l is finished? */ |
| 222 | return -1; /* l is smaller than r (because r is not finished) */ |
| 223 | /* both strings longer than `len'; go on comparing (after the `\0') */ |
| 224 | len++; |
| 225 | l += len; ll -= len; r += len; lr -= len; |
| 226 | } |
| 227 | } |
| 228 | 228 | } |
| 229 | 229 | |
| 230 | 230 | |
| 231 | 231 | int luaV_lessthan (lua_State *L, const TValue *l, const TValue *r) { |
| 232 | | int res; |
| 233 | | if (ttisnumber(l) && ttisnumber(r)) |
| 234 | | return luai_numlt(L, nvalue(l), nvalue(r)); |
| 235 | | else if (ttisstring(l) && ttisstring(r)) |
| 236 | | return l_strcmp(rawtsvalue(l), rawtsvalue(r)) < 0; |
| 237 | | else if ((res = call_orderTM(L, l, r, TM_LT)) < 0) |
| 238 | | luaG_ordererror(L, l, r); |
| 239 | | return res; |
| 232 | int res; |
| 233 | if (ttisnumber(l) && ttisnumber(r)) |
| 234 | return luai_numlt(L, nvalue(l), nvalue(r)); |
| 235 | else if (ttisstring(l) && ttisstring(r)) |
| 236 | return l_strcmp(rawtsvalue(l), rawtsvalue(r)) < 0; |
| 237 | else if ((res = call_orderTM(L, l, r, TM_LT)) < 0) |
| 238 | luaG_ordererror(L, l, r); |
| 239 | return res; |
| 240 | 240 | } |
| 241 | 241 | |
| 242 | 242 | |
| 243 | 243 | int luaV_lessequal (lua_State *L, const TValue *l, const TValue *r) { |
| 244 | | int res; |
| 245 | | if (ttisnumber(l) && ttisnumber(r)) |
| 246 | | return luai_numle(L, nvalue(l), nvalue(r)); |
| 247 | | else if (ttisstring(l) && ttisstring(r)) |
| 248 | | return l_strcmp(rawtsvalue(l), rawtsvalue(r)) <= 0; |
| 249 | | else if ((res = call_orderTM(L, l, r, TM_LE)) >= 0) /* first try `le' */ |
| 250 | | return res; |
| 251 | | else if ((res = call_orderTM(L, r, l, TM_LT)) < 0) /* else try `lt' */ |
| 252 | | luaG_ordererror(L, l, r); |
| 253 | | return !res; |
| 244 | int res; |
| 245 | if (ttisnumber(l) && ttisnumber(r)) |
| 246 | return luai_numle(L, nvalue(l), nvalue(r)); |
| 247 | else if (ttisstring(l) && ttisstring(r)) |
| 248 | return l_strcmp(rawtsvalue(l), rawtsvalue(r)) <= 0; |
| 249 | else if ((res = call_orderTM(L, l, r, TM_LE)) >= 0) /* first try `le' */ |
| 250 | return res; |
| 251 | else if ((res = call_orderTM(L, r, l, TM_LT)) < 0) /* else try `lt' */ |
| 252 | luaG_ordererror(L, l, r); |
| 253 | return !res; |
| 254 | 254 | } |
| 255 | 255 | |
| 256 | 256 | |
| r30857 | r30858 | |
| 258 | 258 | ** equality of Lua values. L == NULL means raw equality (no metamethods) |
| 259 | 259 | */ |
| 260 | 260 | int luaV_equalobj_ (lua_State *L, const TValue *t1, const TValue *t2) { |
| 261 | | const TValue *tm; |
| 262 | | lua_assert(ttisequal(t1, t2)); |
| 263 | | switch (ttype(t1)) { |
| 264 | | case LUA_TNIL: return 1; |
| 265 | | case LUA_TNUMBER: return luai_numeq(nvalue(t1), nvalue(t2)); |
| 266 | | case LUA_TBOOLEAN: return bvalue(t1) == bvalue(t2); /* true must be 1 !! */ |
| 267 | | case LUA_TLIGHTUSERDATA: return pvalue(t1) == pvalue(t2); |
| 268 | | case LUA_TLCF: return fvalue(t1) == fvalue(t2); |
| 269 | | case LUA_TSHRSTR: return eqshrstr(rawtsvalue(t1), rawtsvalue(t2)); |
| 270 | | case LUA_TLNGSTR: return luaS_eqlngstr(rawtsvalue(t1), rawtsvalue(t2)); |
| 271 | | case LUA_TUSERDATA: { |
| 272 | | if (uvalue(t1) == uvalue(t2)) return 1; |
| 273 | | else if (L == NULL) return 0; |
| 274 | | tm = get_equalTM(L, uvalue(t1)->metatable, uvalue(t2)->metatable, TM_EQ); |
| 275 | | break; /* will try TM */ |
| 276 | | } |
| 277 | | case LUA_TTABLE: { |
| 278 | | if (hvalue(t1) == hvalue(t2)) return 1; |
| 279 | | else if (L == NULL) return 0; |
| 280 | | tm = get_equalTM(L, hvalue(t1)->metatable, hvalue(t2)->metatable, TM_EQ); |
| 281 | | break; /* will try TM */ |
| 282 | | } |
| 283 | | default: |
| 284 | | lua_assert(iscollectable(t1)); |
| 285 | | return gcvalue(t1) == gcvalue(t2); |
| 286 | | } |
| 287 | | if (tm == NULL) return 0; /* no TM? */ |
| 288 | | callTM(L, tm, t1, t2, L->top, 1); /* call TM */ |
| 289 | | return !l_isfalse(L->top); |
| 261 | const TValue *tm; |
| 262 | lua_assert(ttisequal(t1, t2)); |
| 263 | switch (ttype(t1)) { |
| 264 | case LUA_TNIL: return 1; |
| 265 | case LUA_TNUMBER: return luai_numeq(nvalue(t1), nvalue(t2)); |
| 266 | case LUA_TBOOLEAN: return bvalue(t1) == bvalue(t2); /* true must be 1 !! */ |
| 267 | case LUA_TLIGHTUSERDATA: return pvalue(t1) == pvalue(t2); |
| 268 | case LUA_TLCF: return fvalue(t1) == fvalue(t2); |
| 269 | case LUA_TSHRSTR: return eqshrstr(rawtsvalue(t1), rawtsvalue(t2)); |
| 270 | case LUA_TLNGSTR: return luaS_eqlngstr(rawtsvalue(t1), rawtsvalue(t2)); |
| 271 | case LUA_TUSERDATA: { |
| 272 | if (uvalue(t1) == uvalue(t2)) return 1; |
| 273 | else if (L == NULL) return 0; |
| 274 | tm = get_equalTM(L, uvalue(t1)->metatable, uvalue(t2)->metatable, TM_EQ); |
| 275 | break; /* will try TM */ |
| 276 | } |
| 277 | case LUA_TTABLE: { |
| 278 | if (hvalue(t1) == hvalue(t2)) return 1; |
| 279 | else if (L == NULL) return 0; |
| 280 | tm = get_equalTM(L, hvalue(t1)->metatable, hvalue(t2)->metatable, TM_EQ); |
| 281 | break; /* will try TM */ |
| 282 | } |
| 283 | default: |
| 284 | lua_assert(iscollectable(t1)); |
| 285 | return gcvalue(t1) == gcvalue(t2); |
| 286 | } |
| 287 | if (tm == NULL) return 0; /* no TM? */ |
| 288 | callTM(L, tm, t1, t2, L->top, 1); /* call TM */ |
| 289 | return !l_isfalse(L->top); |
| 290 | 290 | } |
| 291 | 291 | |
| 292 | 292 | |
| 293 | 293 | void luaV_concat (lua_State *L, int total) { |
| 294 | | lua_assert(total >= 2); |
| 295 | | do { |
| 296 | | StkId top = L->top; |
| 297 | | int n = 2; /* number of elements handled in this pass (at least 2) */ |
| 298 | | if (!(ttisstring(top-2) || ttisnumber(top-2)) || !tostring(L, top-1)) { |
| 299 | | if (!call_binTM(L, top-2, top-1, top-2, TM_CONCAT)) |
| 300 | | luaG_concaterror(L, top-2, top-1); |
| 301 | | } |
| 302 | | else if (tsvalue(top-1)->len == 0) /* second operand is empty? */ |
| 303 | | (void)tostring(L, top - 2); /* result is first operand */ |
| 304 | | else if (ttisstring(top-2) && tsvalue(top-2)->len == 0) { |
| 305 | | setobjs2s(L, top - 2, top - 1); /* result is second op. */ |
| 306 | | } |
| 307 | | else { |
| 308 | | /* at least two non-empty string values; get as many as possible */ |
| 309 | | size_t tl = tsvalue(top-1)->len; |
| 310 | | char *buffer; |
| 311 | | int i; |
| 312 | | /* collect total length */ |
| 313 | | for (i = 1; i < total && tostring(L, top-i-1); i++) { |
| 314 | | size_t l = tsvalue(top-i-1)->len; |
| 315 | | if (l >= (MAX_SIZET/sizeof(char)) - tl) |
| 316 | | luaG_runerror(L, "string length overflow"); |
| 317 | | tl += l; |
| 318 | | } |
| 319 | | buffer = luaZ_openspace(L, &G(L)->buff, tl); |
| 320 | | tl = 0; |
| 321 | | n = i; |
| 322 | | do { /* concat all strings */ |
| 323 | | size_t l = tsvalue(top-i)->len; |
| 324 | | memcpy(buffer+tl, svalue(top-i), l * sizeof(char)); |
| 325 | | tl += l; |
| 326 | | } while (--i > 0); |
| 327 | | setsvalue2s(L, top-n, luaS_newlstr(L, buffer, tl)); |
| 328 | | } |
| 329 | | total -= n-1; /* got 'n' strings to create 1 new */ |
| 330 | | L->top -= n-1; /* popped 'n' strings and pushed one */ |
| 331 | | } while (total > 1); /* repeat until only 1 result left */ |
| 294 | lua_assert(total >= 2); |
| 295 | do { |
| 296 | StkId top = L->top; |
| 297 | int n = 2; /* number of elements handled in this pass (at least 2) */ |
| 298 | if (!(ttisstring(top-2) || ttisnumber(top-2)) || !tostring(L, top-1)) { |
| 299 | if (!call_binTM(L, top-2, top-1, top-2, TM_CONCAT)) |
| 300 | luaG_concaterror(L, top-2, top-1); |
| 301 | } |
| 302 | else if (tsvalue(top-1)->len == 0) /* second operand is empty? */ |
| 303 | (void)tostring(L, top - 2); /* result is first operand */ |
| 304 | else if (ttisstring(top-2) && tsvalue(top-2)->len == 0) { |
| 305 | setobjs2s(L, top - 2, top - 1); /* result is second op. */ |
| 306 | } |
| 307 | else { |
| 308 | /* at least two non-empty string values; get as many as possible */ |
| 309 | size_t tl = tsvalue(top-1)->len; |
| 310 | char *buffer; |
| 311 | int i; |
| 312 | /* collect total length */ |
| 313 | for (i = 1; i < total && tostring(L, top-i-1); i++) { |
| 314 | size_t l = tsvalue(top-i-1)->len; |
| 315 | if (l >= (MAX_SIZET/sizeof(char)) - tl) |
| 316 | luaG_runerror(L, "string length overflow"); |
| 317 | tl += l; |
| 318 | } |
| 319 | buffer = luaZ_openspace(L, &G(L)->buff, tl); |
| 320 | tl = 0; |
| 321 | n = i; |
| 322 | do { /* concat all strings */ |
| 323 | size_t l = tsvalue(top-i)->len; |
| 324 | memcpy(buffer+tl, svalue(top-i), l * sizeof(char)); |
| 325 | tl += l; |
| 326 | } while (--i > 0); |
| 327 | setsvalue2s(L, top-n, luaS_newlstr(L, buffer, tl)); |
| 328 | } |
| 329 | total -= n-1; /* got 'n' strings to create 1 new */ |
| 330 | L->top -= n-1; /* popped 'n' strings and pushed one */ |
| 331 | } while (total > 1); /* repeat until only 1 result left */ |
| 332 | 332 | } |
| 333 | 333 | |
| 334 | 334 | |
| 335 | 335 | void luaV_objlen (lua_State *L, StkId ra, const TValue *rb) { |
| 336 | | const TValue *tm; |
| 337 | | switch (ttypenv(rb)) { |
| 338 | | case LUA_TTABLE: { |
| 339 | | Table *h = hvalue(rb); |
| 340 | | tm = fasttm(L, h->metatable, TM_LEN); |
| 341 | | if (tm) break; /* metamethod? break switch to call it */ |
| 342 | | setnvalue(ra, cast_num(1.0*luaH_getn(h))); /* else primitive len */ |
| 343 | | return; |
| 344 | | } |
| 345 | | case LUA_TSTRING: { |
| 346 | | setnvalue(ra, cast_num(tsvalue(rb)->len)); |
| 347 | | return; |
| 348 | | } |
| 349 | | default: { /* try metamethod */ |
| 350 | | tm = luaT_gettmbyobj(L, rb, TM_LEN); |
| 351 | | if (ttisnil(tm)) /* no metamethod? */ |
| 352 | | luaG_typeerror(L, rb, "get length of"); |
| 353 | | break; |
| 354 | | } |
| 355 | | } |
| 356 | | callTM(L, tm, rb, rb, ra, 1); |
| 336 | const TValue *tm; |
| 337 | switch (ttypenv(rb)) { |
| 338 | case LUA_TTABLE: { |
| 339 | Table *h = hvalue(rb); |
| 340 | tm = fasttm(L, h->metatable, TM_LEN); |
| 341 | if (tm) break; /* metamethod? break switch to call it */ |
| 342 | setnvalue(ra, cast_num(1.0*luaH_getn(h))); /* else primitive len */ |
| 343 | return; |
| 344 | } |
| 345 | case LUA_TSTRING: { |
| 346 | setnvalue(ra, cast_num(tsvalue(rb)->len)); |
| 347 | return; |
| 348 | } |
| 349 | default: { /* try metamethod */ |
| 350 | tm = luaT_gettmbyobj(L, rb, TM_LEN); |
| 351 | if (ttisnil(tm)) /* no metamethod? */ |
| 352 | luaG_typeerror(L, rb, "get length of"); |
| 353 | break; |
| 354 | } |
| 355 | } |
| 356 | callTM(L, tm, rb, rb, ra, 1); |
| 357 | 357 | } |
| 358 | 358 | |
| 359 | 359 | |
| 360 | 360 | void luaV_arith (lua_State *L, StkId ra, const TValue *rb, |
| 361 | | const TValue *rc, TMS op) { |
| 362 | | TValue tempb, tempc; |
| 363 | | const TValue *b, *c; |
| 364 | | if ((b = luaV_tonumber(rb, &tempb)) != NULL && |
| 365 | | (c = luaV_tonumber(rc, &tempc)) != NULL) { |
| 366 | | lua_Number res = luaO_arith(op - TM_ADD + LUA_OPADD, nvalue(b), nvalue(c)); |
| 367 | | setnvalue(ra, res); |
| 368 | | } |
| 369 | | else if (!call_binTM(L, rb, rc, ra, op)) |
| 370 | | luaG_aritherror(L, rb, rc); |
| 361 | const TValue *rc, TMS op) { |
| 362 | TValue tempb, tempc; |
| 363 | const TValue *b, *c; |
| 364 | if ((b = luaV_tonumber(rb, &tempb)) != NULL && |
| 365 | (c = luaV_tonumber(rc, &tempc)) != NULL) { |
| 366 | lua_Number res = luaO_arith(op - TM_ADD + LUA_OPADD, nvalue(b), nvalue(c)); |
| 367 | setnvalue(ra, res); |
| 368 | } |
| 369 | else if (!call_binTM(L, rb, rc, ra, op)) |
| 370 | luaG_aritherror(L, rb, rc); |
| 371 | 371 | } |
| 372 | 372 | |
| 373 | 373 | |
| r30857 | r30858 | |
| 377 | 377 | ** new closure to be created. |
| 378 | 378 | */ |
| 379 | 379 | static Closure *getcached (Proto *p, UpVal **encup, StkId base) { |
| 380 | | Closure *c = p->cache; |
| 381 | | if (c != NULL) { /* is there a cached closure? */ |
| 382 | | int nup = p->sizeupvalues; |
| 383 | | Upvaldesc *uv = p->upvalues; |
| 384 | | int i; |
| 385 | | for (i = 0; i < nup; i++) { /* check whether it has right upvalues */ |
| 386 | | TValue *v = uv[i].instack ? base + uv[i].idx : encup[uv[i].idx]->v; |
| 387 | | if (c->l.upvals[i]->v != v) |
| 388 | | return NULL; /* wrong upvalue; cannot reuse closure */ |
| 389 | | } |
| 390 | | } |
| 391 | | return c; /* return cached closure (or NULL if no cached closure) */ |
| 380 | Closure *c = p->cache; |
| 381 | if (c != NULL) { /* is there a cached closure? */ |
| 382 | int nup = p->sizeupvalues; |
| 383 | Upvaldesc *uv = p->upvalues; |
| 384 | int i; |
| 385 | for (i = 0; i < nup; i++) { /* check whether it has right upvalues */ |
| 386 | TValue *v = uv[i].instack ? base + uv[i].idx : encup[uv[i].idx]->v; |
| 387 | if (c->l.upvals[i]->v != v) |
| 388 | return NULL; /* wrong upvalue; cannot reuse closure */ |
| 389 | } |
| 390 | } |
| 391 | return c; /* return cached closure (or NULL if no cached closure) */ |
| 392 | 392 | } |
| 393 | 393 | |
| 394 | 394 | |
| r30857 | r30858 | |
| 399 | 399 | ** original value of that field. |
| 400 | 400 | */ |
| 401 | 401 | static void pushclosure (lua_State *L, Proto *p, UpVal **encup, StkId base, |
| 402 | | StkId ra) { |
| 403 | | int nup = p->sizeupvalues; |
| 404 | | Upvaldesc *uv = p->upvalues; |
| 405 | | int i; |
| 406 | | Closure *ncl = luaF_newLclosure(L, nup); |
| 407 | | ncl->l.p = p; |
| 408 | | setclLvalue(L, ra, ncl); /* anchor new closure in stack */ |
| 409 | | for (i = 0; i < nup; i++) { /* fill in its upvalues */ |
| 410 | | if (uv[i].instack) /* upvalue refers to local variable? */ |
| 411 | | ncl->l.upvals[i] = luaF_findupval(L, base + uv[i].idx); |
| 412 | | else /* get upvalue from enclosing function */ |
| 413 | | ncl->l.upvals[i] = encup[uv[i].idx]; |
| 414 | | } |
| 415 | | luaC_barrierproto(L, p, ncl); |
| 416 | | p->cache = ncl; /* save it on cache for reuse */ |
| 402 | StkId ra) { |
| 403 | int nup = p->sizeupvalues; |
| 404 | Upvaldesc *uv = p->upvalues; |
| 405 | int i; |
| 406 | Closure *ncl = luaF_newLclosure(L, nup); |
| 407 | ncl->l.p = p; |
| 408 | setclLvalue(L, ra, ncl); /* anchor new closure in stack */ |
| 409 | for (i = 0; i < nup; i++) { /* fill in its upvalues */ |
| 410 | if (uv[i].instack) /* upvalue refers to local variable? */ |
| 411 | ncl->l.upvals[i] = luaF_findupval(L, base + uv[i].idx); |
| 412 | else /* get upvalue from enclosing function */ |
| 413 | ncl->l.upvals[i] = encup[uv[i].idx]; |
| 414 | } |
| 415 | luaC_barrierproto(L, p, ncl); |
| 416 | p->cache = ncl; /* save it on cache for reuse */ |
| 417 | 417 | } |
| 418 | 418 | |
| 419 | 419 | |
| r30857 | r30858 | |
| 421 | 421 | ** finish execution of an opcode interrupted by an yield |
| 422 | 422 | */ |
| 423 | 423 | void luaV_finishOp (lua_State *L) { |
| 424 | | CallInfo *ci = L->ci; |
| 425 | | StkId base = ci->u.l.base; |
| 426 | | Instruction inst = *(ci->u.l.savedpc - 1); /* interrupted instruction */ |
| 427 | | OpCode op = GET_OPCODE(inst); |
| 428 | | switch (op) { /* finish its execution */ |
| 429 | | case OP_ADD: case OP_SUB: case OP_MUL: case OP_DIV: |
| 430 | | case OP_MOD: case OP_POW: case OP_UNM: case OP_LEN: |
| 431 | | case OP_GETTABUP: case OP_GETTABLE: case OP_SELF: { |
| 432 | | setobjs2s(L, base + GETARG_A(inst), --L->top); |
| 433 | | break; |
| 434 | | } |
| 435 | | case OP_LE: case OP_LT: case OP_EQ: { |
| 436 | | int res = !l_isfalse(L->top - 1); |
| 437 | | L->top--; |
| 438 | | /* metamethod should not be called when operand is K */ |
| 439 | | lua_assert(!ISK(GETARG_B(inst))); |
| 440 | | if (op == OP_LE && /* "<=" using "<" instead? */ |
| 441 | | ttisnil(luaT_gettmbyobj(L, base + GETARG_B(inst), TM_LE))) |
| 442 | | res = !res; /* invert result */ |
| 443 | | lua_assert(GET_OPCODE(*ci->u.l.savedpc) == OP_JMP); |
| 444 | | if (res != GETARG_A(inst)) /* condition failed? */ |
| 445 | | ci->u.l.savedpc++; /* skip jump instruction */ |
| 446 | | break; |
| 447 | | } |
| 448 | | case OP_CONCAT: { |
| 449 | | StkId top = L->top - 1; /* top when 'call_binTM' was called */ |
| 450 | | int b = GETARG_B(inst); /* first element to concatenate */ |
| 451 | | int total = cast_int(top - 1 - (base + b)); /* yet to concatenate */ |
| 452 | | setobj2s(L, top - 2, top); /* put TM result in proper position */ |
| 453 | | if (total > 1) { /* are there elements to concat? */ |
| 454 | | L->top = top - 1; /* top is one after last element (at top-2) */ |
| 455 | | luaV_concat(L, total); /* concat them (may yield again) */ |
| 456 | | } |
| 457 | | /* move final result to final position */ |
| 458 | | setobj2s(L, ci->u.l.base + GETARG_A(inst), L->top - 1); |
| 459 | | L->top = ci->top; /* restore top */ |
| 460 | | break; |
| 461 | | } |
| 462 | | case OP_TFORCALL: { |
| 463 | | lua_assert(GET_OPCODE(*ci->u.l.savedpc) == OP_TFORLOOP); |
| 464 | | L->top = ci->top; /* correct top */ |
| 465 | | break; |
| 466 | | } |
| 467 | | case OP_CALL: { |
| 468 | | if (GETARG_C(inst) - 1 >= 0) /* nresults >= 0? */ |
| 469 | | L->top = ci->top; /* adjust results */ |
| 470 | | break; |
| 471 | | } |
| 472 | | case OP_TAILCALL: case OP_SETTABUP: case OP_SETTABLE: |
| 473 | | break; |
| 474 | | default: lua_assert(0); |
| 475 | | } |
| 424 | CallInfo *ci = L->ci; |
| 425 | StkId base = ci->u.l.base; |
| 426 | Instruction inst = *(ci->u.l.savedpc - 1); /* interrupted instruction */ |
| 427 | OpCode op = GET_OPCODE(inst); |
| 428 | switch (op) { /* finish its execution */ |
| 429 | case OP_ADD: case OP_SUB: case OP_MUL: case OP_DIV: |
| 430 | case OP_MOD: case OP_POW: case OP_UNM: case OP_LEN: |
| 431 | case OP_GETTABUP: case OP_GETTABLE: case OP_SELF: { |
| 432 | setobjs2s(L, base + GETARG_A(inst), --L->top); |
| 433 | break; |
| 434 | } |
| 435 | case OP_LE: case OP_LT: case OP_EQ: { |
| 436 | int res = !l_isfalse(L->top - 1); |
| 437 | L->top--; |
| 438 | /* metamethod should not be called when operand is K */ |
| 439 | lua_assert(!ISK(GETARG_B(inst))); |
| 440 | if (op == OP_LE && /* "<=" using "<" instead? */ |
| 441 | ttisnil(luaT_gettmbyobj(L, base + GETARG_B(inst), TM_LE))) |
| 442 | res = !res; /* invert result */ |
| 443 | lua_assert(GET_OPCODE(*ci->u.l.savedpc) == OP_JMP); |
| 444 | if (res != GETARG_A(inst)) /* condition failed? */ |
| 445 | ci->u.l.savedpc++; /* skip jump instruction */ |
| 446 | break; |
| 447 | } |
| 448 | case OP_CONCAT: { |
| 449 | StkId top = L->top - 1; /* top when 'call_binTM' was called */ |
| 450 | int b = GETARG_B(inst); /* first element to concatenate */ |
| 451 | int total = cast_int(top - 1 - (base + b)); /* yet to concatenate */ |
| 452 | setobj2s(L, top - 2, top); /* put TM result in proper position */ |
| 453 | if (total > 1) { /* are there elements to concat? */ |
| 454 | L->top = top - 1; /* top is one after last element (at top-2) */ |
| 455 | luaV_concat(L, total); /* concat them (may yield again) */ |
| 456 | } |
| 457 | /* move final result to final position */ |
| 458 | setobj2s(L, ci->u.l.base + GETARG_A(inst), L->top - 1); |
| 459 | L->top = ci->top; /* restore top */ |
| 460 | break; |
| 461 | } |
| 462 | case OP_TFORCALL: { |
| 463 | lua_assert(GET_OPCODE(*ci->u.l.savedpc) == OP_TFORLOOP); |
| 464 | L->top = ci->top; /* correct top */ |
| 465 | break; |
| 466 | } |
| 467 | case OP_CALL: { |
| 468 | if (GETARG_C(inst) - 1 >= 0) /* nresults >= 0? */ |
| 469 | L->top = ci->top; /* adjust results */ |
| 470 | break; |
| 471 | } |
| 472 | case OP_TAILCALL: case OP_SETTABUP: case OP_SETTABLE: |
| 473 | break; |
| 474 | default: lua_assert(0); |
| 475 | } |
| 476 | 476 | } |
| 477 | 477 | |
| 478 | 478 | |
| r30857 | r30858 | |
| 482 | 482 | */ |
| 483 | 483 | |
| 484 | 484 | #if !defined luai_runtimecheck |
| 485 | | #define luai_runtimecheck(L, c) /* void */ |
| 485 | #define luai_runtimecheck(L, c) /* void */ |
| 486 | 486 | #endif |
| 487 | 487 | |
| 488 | 488 | |
| 489 | | #define RA(i) (base+GETARG_A(i)) |
| 489 | #define RA(i) (base+GETARG_A(i)) |
| 490 | 490 | /* to be used after possible stack reallocation */ |
| 491 | | #define RB(i) check_exp(getBMode(GET_OPCODE(i)) == OpArgR, base+GETARG_B(i)) |
| 492 | | #define RC(i) check_exp(getCMode(GET_OPCODE(i)) == OpArgR, base+GETARG_C(i)) |
| 493 | | #define RKB(i) check_exp(getBMode(GET_OPCODE(i)) == OpArgK, \ |
| 491 | #define RB(i) check_exp(getBMode(GET_OPCODE(i)) == OpArgR, base+GETARG_B(i)) |
| 492 | #define RC(i) check_exp(getCMode(GET_OPCODE(i)) == OpArgR, base+GETARG_C(i)) |
| 493 | #define RKB(i) check_exp(getBMode(GET_OPCODE(i)) == OpArgK, \ |
| 494 | 494 | ISK(GETARG_B(i)) ? k+INDEXK(GETARG_B(i)) : base+GETARG_B(i)) |
| 495 | | #define RKC(i) check_exp(getCMode(GET_OPCODE(i)) == OpArgK, \ |
| 495 | #define RKC(i) check_exp(getCMode(GET_OPCODE(i)) == OpArgK, \ |
| 496 | 496 | ISK(GETARG_C(i)) ? k+INDEXK(GETARG_C(i)) : base+GETARG_C(i)) |
| 497 | 497 | #define KBx(i) \ |
| 498 | | (k + (GETARG_Bx(i) != 0 ? GETARG_Bx(i) - 1 : GETARG_Ax(*ci->u.l.savedpc++))) |
| 498 | (k + (GETARG_Bx(i) != 0 ? GETARG_Bx(i) - 1 : GETARG_Ax(*ci->u.l.savedpc++))) |
| 499 | 499 | |
| 500 | 500 | |
| 501 | 501 | /* execute a jump instruction */ |
| 502 | 502 | #define dojump(ci,i,e) \ |
| 503 | | { int a = GETARG_A(i); \ |
| 504 | | if (a > 0) luaF_close(L, ci->u.l.base + a - 1); \ |
| 505 | | ci->u.l.savedpc += GETARG_sBx(i) + e; } |
| 503 | { int a = GETARG_A(i); \ |
| 504 | if (a > 0) luaF_close(L, ci->u.l.base + a - 1); \ |
| 505 | ci->u.l.savedpc += GETARG_sBx(i) + e; } |
| 506 | 506 | |
| 507 | 507 | /* for test instructions, execute the jump instruction that follows it */ |
| 508 | | #define donextjump(ci) { i = *ci->u.l.savedpc; dojump(ci, i, 1); } |
| 508 | #define donextjump(ci) { i = *ci->u.l.savedpc; dojump(ci, i, 1); } |
| 509 | 509 | |
| 510 | 510 | |
| 511 | | #define Protect(x) { {x;}; base = ci->u.l.base; } |
| 511 | #define Protect(x) { {x;}; base = ci->u.l.base; } |
| 512 | 512 | |
| 513 | 513 | #define checkGC(L,c) \ |
| 514 | | Protect( luaC_condGC(L,{L->top = (c); /* limit of live values */ \ |
| 515 | | luaC_step(L); \ |
| 516 | | L->top = ci->top;}) /* restore top */ \ |
| 517 | | luai_threadyield(L); ) |
| 514 | Protect( luaC_condGC(L,{L->top = (c); /* limit of live values */ \ |
| 515 | luaC_step(L); \ |
| 516 | L->top = ci->top;}) /* restore top */ \ |
| 517 | luai_threadyield(L); ) |
| 518 | 518 | |
| 519 | 519 | |
| 520 | 520 | #define arith_op(op,tm) { \ |
| 521 | | TValue *rb = RKB(i); \ |
| 522 | | TValue *rc = RKC(i); \ |
| 523 | | if (ttisnumber(rb) && ttisnumber(rc)) { \ |
| 524 | | lua_Number nb = nvalue(rb), nc = nvalue(rc); \ |
| 525 | | setnvalue(ra, op(L, nb, nc)); \ |
| 526 | | } \ |
| 527 | | else { Protect(luaV_arith(L, ra, rb, rc, tm)); } } |
| 521 | TValue *rb = RKB(i); \ |
| 522 | TValue *rc = RKC(i); \ |
| 523 | if (ttisnumber(rb) && ttisnumber(rc)) { \ |
| 524 | lua_Number nb = nvalue(rb), nc = nvalue(rc); \ |
| 525 | setnvalue(ra, op(L, nb, nc)); \ |
| 526 | } \ |
| 527 | else { Protect(luaV_arith(L, ra, rb, rc, tm)); } } |
| 528 | 528 | |
| 529 | 529 | |
| 530 | | #define vmdispatch(o) switch(o) |
| 531 | | #define vmcase(l,b) case l: {b} break; |
| 532 | | #define vmcasenb(l,b) case l: {b} /* nb = no break */ |
| 530 | #define vmdispatch(o) switch(o) |
| 531 | #define vmcase(l,b) case l: {b} break; |
| 532 | #define vmcasenb(l,b) case l: {b} /* nb = no break */ |
| 533 | 533 | |
| 534 | 534 | void luaV_execute (lua_State *L) { |
| 535 | | CallInfo *ci = L->ci; |
| 536 | | LClosure *cl; |
| 537 | | TValue *k; |
| 538 | | StkId base; |
| 539 | | newframe: /* reentry point when frame changes (call/return) */ |
| 540 | | lua_assert(ci == L->ci); |
| 541 | | cl = clLvalue(ci->func); |
| 542 | | k = cl->p->k; |
| 543 | | base = ci->u.l.base; |
| 544 | | /* main loop of interpreter */ |
| 545 | | for (;;) { |
| 546 | | Instruction i = *(ci->u.l.savedpc++); |
| 547 | | StkId ra; |
| 548 | | if ((L->hookmask & (LUA_MASKLINE | LUA_MASKCOUNT)) && |
| 549 | | (--L->hookcount == 0 || L->hookmask & LUA_MASKLINE)) { |
| 550 | | Protect(traceexec(L)); |
| 551 | | } |
| 552 | | /* WARNING: several calls may realloc the stack and invalidate `ra' */ |
| 553 | | ra = RA(i); |
| 554 | | lua_assert(base == ci->u.l.base); |
| 555 | | lua_assert(base <= L->top && L->top < L->stack + L->stacksize); |
| 556 | | vmdispatch (GET_OPCODE(i)) { |
| 557 | | vmcase(OP_MOVE, |
| 558 | | setobjs2s(L, ra, RB(i)); |
| 559 | | ) |
| 560 | | vmcase(OP_LOADK, |
| 561 | | TValue *rb = k + GETARG_Bx(i); |
| 562 | | setobj2s(L, ra, rb); |
| 563 | | ) |
| 564 | | vmcase(OP_LOADKX, |
| 565 | | TValue *rb; |
| 566 | | lua_assert(GET_OPCODE(*ci->u.l.savedpc) == OP_EXTRAARG); |
| 567 | | rb = k + GETARG_Ax(*ci->u.l.savedpc++); |
| 568 | | setobj2s(L, ra, rb); |
| 569 | | ) |
| 570 | | vmcase(OP_LOADBOOL, |
| 571 | | setbvalue(ra, GETARG_B(i)); |
| 572 | | if (GETARG_C(i)) ci->u.l.savedpc++; /* skip next instruction (if C) */ |
| 573 | | ) |
| 574 | | vmcase(OP_LOADNIL, |
| 575 | | int b = GETARG_B(i); |
| 576 | | do { |
| 577 | | setnilvalue(ra++); |
| 578 | | } while (b--); |
| 579 | | ) |
| 580 | | vmcase(OP_GETUPVAL, |
| 581 | | int b = GETARG_B(i); |
| 582 | | setobj2s(L, ra, cl->upvals[b]->v); |
| 583 | | ) |
| 584 | | vmcase(OP_GETTABUP, |
| 585 | | int b = GETARG_B(i); |
| 586 | | Protect(luaV_gettable(L, cl->upvals[b]->v, RKC(i), ra)); |
| 587 | | ) |
| 588 | | vmcase(OP_GETTABLE, |
| 589 | | Protect(luaV_gettable(L, RB(i), RKC(i), ra)); |
| 590 | | ) |
| 591 | | vmcase(OP_SETTABUP, |
| 592 | | int a = GETARG_A(i); |
| 593 | | Protect(luaV_settable(L, cl->upvals[a]->v, RKB(i), RKC(i))); |
| 594 | | ) |
| 595 | | vmcase(OP_SETUPVAL, |
| 596 | | UpVal *uv = cl->upvals[GETARG_B(i)]; |
| 597 | | setobj(L, uv->v, ra); |
| 598 | | luaC_barrier(L, uv, ra); |
| 599 | | ) |
| 600 | | vmcase(OP_SETTABLE, |
| 601 | | Protect(luaV_settable(L, ra, RKB(i), RKC(i))); |
| 602 | | ) |
| 603 | | vmcase(OP_NEWTABLE, |
| 604 | | int b = GETARG_B(i); |
| 605 | | int c = GETARG_C(i); |
| 606 | | Table *t = luaH_new(L); |
| 607 | | sethvalue(L, ra, t); |
| 608 | | if (b != 0 || c != 0) |
| 609 | | luaH_resize(L, t, luaO_fb2int(b), luaO_fb2int(c)); |
| 610 | | checkGC(L, ra + 1); |
| 611 | | ) |
| 612 | | vmcase(OP_SELF, |
| 613 | | StkId rb = RB(i); |
| 614 | | setobjs2s(L, ra+1, rb); |
| 615 | | Protect(luaV_gettable(L, rb, RKC(i), ra)); |
| 616 | | ) |
| 617 | | vmcase(OP_ADD, |
| 618 | | arith_op(luai_numadd, TM_ADD); |
| 619 | | ) |
| 620 | | vmcase(OP_SUB, |
| 621 | | arith_op(luai_numsub, TM_SUB); |
| 622 | | ) |
| 623 | | vmcase(OP_MUL, |
| 624 | | arith_op(luai_nummul, TM_MUL); |
| 625 | | ) |
| 626 | | vmcase(OP_DIV, |
| 627 | | arith_op(luai_numdiv, TM_DIV); |
| 628 | | ) |
| 629 | | vmcase(OP_MOD, |
| 630 | | arith_op(luai_nummod, TM_MOD); |
| 631 | | ) |
| 632 | | vmcase(OP_POW, |
| 633 | | arith_op(luai_numpow, TM_POW); |
| 634 | | ) |
| 635 | | vmcase(OP_UNM, |
| 636 | | TValue *rb = RB(i); |
| 637 | | if (ttisnumber(rb)) { |
| 638 | | lua_Number nb = nvalue(rb); |
| 639 | | setnvalue(ra, luai_numunm(L, nb)); |
| 640 | | } |
| 641 | | else { |
| 642 | | Protect(luaV_arith(L, ra, rb, rb, TM_UNM)); |
| 643 | | } |
| 644 | | ) |
| 645 | | vmcase(OP_NOT, |
| 646 | | TValue *rb = RB(i); |
| 647 | | int res = l_isfalse(rb); /* next assignment may change this value */ |
| 648 | | setbvalue(ra, res); |
| 649 | | ) |
| 650 | | vmcase(OP_LEN, |
| 651 | | Protect(luaV_objlen(L, ra, RB(i))); |
| 652 | | ) |
| 653 | | vmcase(OP_CONCAT, |
| 654 | | int b = GETARG_B(i); |
| 655 | | int c = GETARG_C(i); |
| 656 | | StkId rb; |
| 657 | | L->top = base + c + 1; /* mark the end of concat operands */ |
| 658 | | Protect(luaV_concat(L, c - b + 1)); |
| 659 | | ra = RA(i); /* 'luav_concat' may invoke TMs and move the stack */ |
| 660 | | rb = b + base; |
| 661 | | setobjs2s(L, ra, rb); |
| 662 | | checkGC(L, (ra >= rb ? ra + 1 : rb)); |
| 663 | | L->top = ci->top; /* restore top */ |
| 664 | | ) |
| 665 | | vmcase(OP_JMP, |
| 666 | | dojump(ci, i, 0); |
| 667 | | ) |
| 668 | | vmcase(OP_EQ, |
| 669 | | TValue *rb = RKB(i); |
| 670 | | TValue *rc = RKC(i); |
| 671 | | Protect( |
| 672 | | if (cast_int(equalobj(L, rb, rc)) != GETARG_A(i)) |
| 673 | | ci->u.l.savedpc++; |
| 674 | | else |
| 675 | | donextjump(ci); |
| 676 | | ) |
| 677 | | ) |
| 678 | | vmcase(OP_LT, |
| 679 | | Protect( |
| 680 | | if (luaV_lessthan(L, RKB(i), RKC(i)) != GETARG_A(i)) |
| 681 | | ci->u.l.savedpc++; |
| 682 | | else |
| 683 | | donextjump(ci); |
| 684 | | ) |
| 685 | | ) |
| 686 | | vmcase(OP_LE, |
| 687 | | Protect( |
| 688 | | if (luaV_lessequal(L, RKB(i), RKC(i)) != GETARG_A(i)) |
| 689 | | ci->u.l.savedpc++; |
| 690 | | else |
| 691 | | donextjump(ci); |
| 692 | | ) |
| 693 | | ) |
| 694 | | vmcase(OP_TEST, |
| 695 | | if (GETARG_C(i) ? l_isfalse(ra) : !l_isfalse(ra)) |
| 696 | | ci->u.l.savedpc++; |
| 697 | | else |
| 698 | | donextjump(ci); |
| 699 | | ) |
| 700 | | vmcase(OP_TESTSET, |
| 701 | | TValue *rb = RB(i); |
| 702 | | if (GETARG_C(i) ? l_isfalse(rb) : !l_isfalse(rb)) |
| 703 | | ci->u.l.savedpc++; |
| 704 | | else { |
| 705 | | setobjs2s(L, ra, rb); |
| 706 | | donextjump(ci); |
| 707 | | } |
| 708 | | ) |
| 709 | | vmcase(OP_CALL, |
| 710 | | int b = GETARG_B(i); |
| 711 | | int nresults = GETARG_C(i) - 1; |
| 712 | | if (b != 0) L->top = ra+b; /* else previous instruction set top */ |
| 713 | | if (luaD_precall(L, ra, nresults)) { /* C function? */ |
| 714 | | if (nresults >= 0) L->top = ci->top; /* adjust results */ |
| 715 | | base = ci->u.l.base; |
| 716 | | } |
| 717 | | else { /* Lua function */ |
| 718 | | ci = L->ci; |
| 719 | | ci->callstatus |= CIST_REENTRY; |
| 720 | | goto newframe; /* restart luaV_execute over new Lua function */ |
| 721 | | } |
| 722 | | ) |
| 723 | | vmcase(OP_TAILCALL, |
| 724 | | int b = GETARG_B(i); |
| 725 | | if (b != 0) L->top = ra+b; /* else previous instruction set top */ |
| 726 | | lua_assert(GETARG_C(i) - 1 == LUA_MULTRET); |
| 727 | | if (luaD_precall(L, ra, LUA_MULTRET)) /* C function? */ |
| 728 | | base = ci->u.l.base; |
| 729 | | else { |
| 730 | | /* tail call: put called frame (n) in place of caller one (o) */ |
| 731 | | CallInfo *nci = L->ci; /* called frame */ |
| 732 | | CallInfo *oci = nci->previous; /* caller frame */ |
| 733 | | StkId nfunc = nci->func; /* called function */ |
| 734 | | StkId ofunc = oci->func; /* caller function */ |
| 735 | | /* last stack slot filled by 'precall' */ |
| 736 | | StkId lim = nci->u.l.base + getproto(nfunc)->numparams; |
| 737 | | int aux; |
| 738 | | /* close all upvalues from previous call */ |
| 739 | | if (cl->p->sizep > 0) luaF_close(L, oci->u.l.base); |
| 740 | | /* move new frame into old one */ |
| 741 | | for (aux = 0; nfunc + aux < lim; aux++) |
| 742 | | setobjs2s(L, ofunc + aux, nfunc + aux); |
| 743 | | oci->u.l.base = ofunc + (nci->u.l.base - nfunc); /* correct base */ |
| 744 | | oci->top = L->top = ofunc + (L->top - nfunc); /* correct top */ |
| 745 | | oci->u.l.savedpc = nci->u.l.savedpc; |
| 746 | | oci->callstatus |= CIST_TAIL; /* function was tail called */ |
| 747 | | ci = L->ci = oci; /* remove new frame */ |
| 748 | | lua_assert(L->top == oci->u.l.base + getproto(ofunc)->maxstacksize); |
| 749 | | goto newframe; /* restart luaV_execute over new Lua function */ |
| 750 | | } |
| 751 | | ) |
| 752 | | vmcasenb(OP_RETURN, |
| 753 | | int b = GETARG_B(i); |
| 754 | | if (b != 0) L->top = ra+b-1; |
| 755 | | if (cl->p->sizep > 0) luaF_close(L, base); |
| 756 | | b = luaD_poscall(L, ra); |
| 757 | | if (!(ci->callstatus & CIST_REENTRY)) /* 'ci' still the called one */ |
| 758 | | return; /* external invocation: return */ |
| 759 | | else { /* invocation via reentry: continue execution */ |
| 760 | | ci = L->ci; |
| 761 | | if (b) L->top = ci->top; |
| 762 | | lua_assert(isLua(ci)); |
| 763 | | lua_assert(GET_OPCODE(*((ci)->u.l.savedpc - 1)) == OP_CALL); |
| 764 | | goto newframe; /* restart luaV_execute over new Lua function */ |
| 765 | | } |
| 766 | | ) |
| 767 | | vmcase(OP_FORLOOP, |
| 768 | | lua_Number step = nvalue(ra+2); |
| 769 | | lua_Number idx = luai_numadd(L, nvalue(ra), step); /* increment index */ |
| 770 | | lua_Number limit = nvalue(ra+1); |
| 771 | | if (luai_numlt(L, 0, step) ? luai_numle(L, idx, limit) |
| 772 | | : luai_numle(L, limit, idx)) { |
| 773 | | ci->u.l.savedpc += GETARG_sBx(i); /* jump back */ |
| 774 | | setnvalue(ra, idx); /* update internal index... */ |
| 775 | | setnvalue(ra+3, idx); /* ...and external index */ |
| 776 | | } |
| 777 | | ) |
| 778 | | vmcase(OP_FORPREP, |
| 779 | | const TValue *init = ra; |
| 780 | | const TValue *plimit = ra+1; |
| 781 | | const TValue *pstep = ra+2; |
| 782 | | if (!tonumber(init, ra)) |
| 783 | | luaG_runerror(L, LUA_QL("for") " initial value must be a number"); |
| 784 | | else if (!tonumber(plimit, ra+1)) |
| 785 | | luaG_runerror(L, LUA_QL("for") " limit must be a number"); |
| 786 | | else if (!tonumber(pstep, ra+2)) |
| 787 | | luaG_runerror(L, LUA_QL("for") " step must be a number"); |
| 788 | | setnvalue(ra, luai_numsub(L, nvalue(ra), nvalue(pstep))); |
| 789 | | ci->u.l.savedpc += GETARG_sBx(i); |
| 790 | | ) |
| 791 | | vmcasenb(OP_TFORCALL, |
| 792 | | StkId cb = ra + 3; /* call base */ |
| 793 | | setobjs2s(L, cb+2, ra+2); |
| 794 | | setobjs2s(L, cb+1, ra+1); |
| 795 | | setobjs2s(L, cb, ra); |
| 796 | | L->top = cb + 3; /* func. + 2 args (state and index) */ |
| 797 | | Protect(luaD_call(L, cb, GETARG_C(i), 1)); |
| 798 | | L->top = ci->top; |
| 799 | | i = *(ci->u.l.savedpc++); /* go to next instruction */ |
| 800 | | ra = RA(i); |
| 801 | | lua_assert(GET_OPCODE(i) == OP_TFORLOOP); |
| 802 | | goto l_tforloop; |
| 803 | | ) |
| 804 | | vmcase(OP_TFORLOOP, |
| 805 | | l_tforloop: |
| 806 | | if (!ttisnil(ra + 1)) { /* continue loop? */ |
| 807 | | setobjs2s(L, ra, ra + 1); /* save control variable */ |
| 808 | | ci->u.l.savedpc += GETARG_sBx(i); /* jump back */ |
| 809 | | } |
| 810 | | ) |
| 811 | | vmcase(OP_SETLIST, |
| 812 | | int n = GETARG_B(i); |
| 813 | | int c = GETARG_C(i); |
| 814 | | int last; |
| 815 | | Table *h; |
| 816 | | if (n == 0) n = cast_int(L->top - ra) - 1; |
| 817 | | if (c == 0) { |
| 818 | | lua_assert(GET_OPCODE(*ci->u.l.savedpc) == OP_EXTRAARG); |
| 819 | | c = GETARG_Ax(*ci->u.l.savedpc++); |
| 820 | | } |
| 821 | | luai_runtimecheck(L, ttistable(ra)); |
| 822 | | h = hvalue(ra); |
| 823 | | last = ((c-1)*LFIELDS_PER_FLUSH) + n; |
| 824 | | if (last > h->sizearray) /* needs more space? */ |
| 825 | | luaH_resizearray(L, h, last); /* pre-allocate it at once */ |
| 826 | | for (; n > 0; n--) { |
| 827 | | TValue *val = ra+n; |
| 828 | | luaH_setint(L, h, last--, val); |
| 829 | | luaC_barrierback(L, obj2gco(h), val); |
| 830 | | } |
| 831 | | L->top = ci->top; /* correct top (in case of previous open call) */ |
| 832 | | ) |
| 833 | | vmcase(OP_CLOSURE, |
| 834 | | Proto *p = cl->p->p[GETARG_Bx(i)]; |
| 835 | | Closure *ncl = getcached(p, cl->upvals, base); /* cached closure */ |
| 836 | | if (ncl == NULL) /* no match? */ |
| 837 | | pushclosure(L, p, cl->upvals, base, ra); /* create a new one */ |
| 838 | | else |
| 839 | | setclLvalue(L, ra, ncl); /* push cashed closure */ |
| 840 | | checkGC(L, ra + 1); |
| 841 | | ) |
| 842 | | vmcase(OP_VARARG, |
| 843 | | int b = GETARG_B(i) - 1; |
| 844 | | int j; |
| 845 | | int n = cast_int(base - ci->func) - cl->p->numparams - 1; |
| 846 | | if (b < 0) { /* B == 0? */ |
| 847 | | b = n; /* get all var. arguments */ |
| 848 | | Protect(luaD_checkstack(L, n)); |
| 849 | | ra = RA(i); /* previous call may change the stack */ |
| 850 | | L->top = ra + n; |
| 851 | | } |
| 852 | | for (j = 0; j < b; j++) { |
| 853 | | if (j < n) { |
| 854 | | setobjs2s(L, ra + j, base - n + j); |
| 855 | | } |
| 856 | | else { |
| 857 | | setnilvalue(ra + j); |
| 858 | | } |
| 859 | | } |
| 860 | | ) |
| 861 | | vmcase(OP_EXTRAARG, |
| 862 | | lua_assert(0); |
| 863 | | ) |
| 864 | | } |
| 865 | | } |
| 535 | CallInfo *ci = L->ci; |
| 536 | LClosure *cl; |
| 537 | TValue *k; |
| 538 | StkId base; |
| 539 | newframe: /* reentry point when frame changes (call/return) */ |
| 540 | lua_assert(ci == L->ci); |
| 541 | cl = clLvalue(ci->func); |
| 542 | k = cl->p->k; |
| 543 | base = ci->u.l.base; |
| 544 | /* main loop of interpreter */ |
| 545 | for (;;) { |
| 546 | Instruction i = *(ci->u.l.savedpc++); |
| 547 | StkId ra; |
| 548 | if ((L->hookmask & (LUA_MASKLINE | LUA_MASKCOUNT)) && |
| 549 | (--L->hookcount == 0 || L->hookmask & LUA_MASKLINE)) { |
| 550 | Protect(traceexec(L)); |
| 551 | } |
| 552 | /* WARNING: several calls may realloc the stack and invalidate `ra' */ |
| 553 | ra = RA(i); |
| 554 | lua_assert(base == ci->u.l.base); |
| 555 | lua_assert(base <= L->top && L->top < L->stack + L->stacksize); |
| 556 | vmdispatch (GET_OPCODE(i)) { |
| 557 | vmcase(OP_MOVE, |
| 558 | setobjs2s(L, ra, RB(i)); |
| 559 | ) |
| 560 | vmcase(OP_LOADK, |
| 561 | TValue *rb = k + GETARG_Bx(i); |
| 562 | setobj2s(L, ra, rb); |
| 563 | ) |
| 564 | vmcase(OP_LOADKX, |
| 565 | TValue *rb; |
| 566 | lua_assert(GET_OPCODE(*ci->u.l.savedpc) == OP_EXTRAARG); |
| 567 | rb = k + GETARG_Ax(*ci->u.l.savedpc++); |
| 568 | setobj2s(L, ra, rb); |
| 569 | ) |
| 570 | vmcase(OP_LOADBOOL, |
| 571 | setbvalue(ra, GETARG_B(i)); |
| 572 | if (GETARG_C(i)) ci->u.l.savedpc++; /* skip next instruction (if C) */ |
| 573 | ) |
| 574 | vmcase(OP_LOADNIL, |
| 575 | int b = GETARG_B(i); |
| 576 | do { |
| 577 | setnilvalue(ra++); |
| 578 | } while (b--); |
| 579 | ) |
| 580 | vmcase(OP_GETUPVAL, |
| 581 | int b = GETARG_B(i); |
| 582 | setobj2s(L, ra, cl->upvals[b]->v); |
| 583 | ) |
| 584 | vmcase(OP_GETTABUP, |
| 585 | int b = GETARG_B(i); |
| 586 | Protect(luaV_gettable(L, cl->upvals[b]->v, RKC(i), ra)); |
| 587 | ) |
| 588 | vmcase(OP_GETTABLE, |
| 589 | Protect(luaV_gettable(L, RB(i), RKC(i), ra)); |
| 590 | ) |
| 591 | vmcase(OP_SETTABUP, |
| 592 | int a = GETARG_A(i); |
| 593 | Protect(luaV_settable(L, cl->upvals[a]->v, RKB(i), RKC(i))); |
| 594 | ) |
| 595 | vmcase(OP_SETUPVAL, |
| 596 | UpVal *uv = cl->upvals[GETARG_B(i)]; |
| 597 | setobj(L, uv->v, ra); |
| 598 | luaC_barrier(L, uv, ra); |
| 599 | ) |
| 600 | vmcase(OP_SETTABLE, |
| 601 | Protect(luaV_settable(L, ra, RKB(i), RKC(i))); |
| 602 | ) |
| 603 | vmcase(OP_NEWTABLE, |
| 604 | int b = GETARG_B(i); |
| 605 | int c = GETARG_C(i); |
| 606 | Table *t = luaH_new(L); |
| 607 | sethvalue(L, ra, t); |
| 608 | if (b != 0 || c != 0) |
| 609 | luaH_resize(L, t, luaO_fb2int(b), luaO_fb2int(c)); |
| 610 | checkGC(L, ra + 1); |
| 611 | ) |
| 612 | vmcase(OP_SELF, |
| 613 | StkId rb = RB(i); |
| 614 | setobjs2s(L, ra+1, rb); |
| 615 | Protect(luaV_gettable(L, rb, RKC(i), ra)); |
| 616 | ) |
| 617 | vmcase(OP_ADD, |
| 618 | arith_op(luai_numadd, TM_ADD); |
| 619 | ) |
| 620 | vmcase(OP_SUB, |
| 621 | arith_op(luai_numsub, TM_SUB); |
| 622 | ) |
| 623 | vmcase(OP_MUL, |
| 624 | arith_op(luai_nummul, TM_MUL); |
| 625 | ) |
| 626 | vmcase(OP_DIV, |
| 627 | arith_op(luai_numdiv, TM_DIV); |
| 628 | ) |
| 629 | vmcase(OP_MOD, |
| 630 | arith_op(luai_nummod, TM_MOD); |
| 631 | ) |
| 632 | vmcase(OP_POW, |
| 633 | arith_op(luai_numpow, TM_POW); |
| 634 | ) |
| 635 | vmcase(OP_UNM, |
| 636 | TValue *rb = RB(i); |
| 637 | if (ttisnumber(rb)) { |
| 638 | lua_Number nb = nvalue(rb); |
| 639 | setnvalue(ra, luai_numunm(L, nb)); |
| 640 | } |
| 641 | else { |
| 642 | Protect(luaV_arith(L, ra, rb, rb, TM_UNM)); |
| 643 | } |
| 644 | ) |
| 645 | vmcase(OP_NOT, |
| 646 | TValue *rb = RB(i); |
| 647 | int res = l_isfalse(rb); /* next assignment may change this value */ |
| 648 | setbvalue(ra, res); |
| 649 | ) |
| 650 | vmcase(OP_LEN, |
| 651 | Protect(luaV_objlen(L, ra, RB(i))); |
| 652 | ) |
| 653 | vmcase(OP_CONCAT, |
| 654 | int b = GETARG_B(i); |
| 655 | int c = GETARG_C(i); |
| 656 | StkId rb; |
| 657 | L->top = base + c + 1; /* mark the end of concat operands */ |
| 658 | Protect(luaV_concat(L, c - b + 1)); |
| 659 | ra = RA(i); /* 'luav_concat' may invoke TMs and move the stack */ |
| 660 | rb = b + base; |
| 661 | setobjs2s(L, ra, rb); |
| 662 | checkGC(L, (ra >= rb ? ra + 1 : rb)); |
| 663 | L->top = ci->top; /* restore top */ |
| 664 | ) |
| 665 | vmcase(OP_JMP, |
| 666 | dojump(ci, i, 0); |
| 667 | ) |
| 668 | vmcase(OP_EQ, |
| 669 | TValue *rb = RKB(i); |
| 670 | TValue *rc = RKC(i); |
| 671 | Protect( |
| 672 | if (cast_int(equalobj(L, rb, rc)) != GETARG_A(i)) |
| 673 | ci->u.l.savedpc++; |
| 674 | else |
| 675 | donextjump(ci); |
| 676 | ) |
| 677 | ) |
| 678 | vmcase(OP_LT, |
| 679 | Protect( |
| 680 | if (luaV_lessthan(L, RKB(i), RKC(i)) != GETARG_A(i)) |
| 681 | ci->u.l.savedpc++; |
| 682 | else |
| 683 | donextjump(ci); |
| 684 | ) |
| 685 | ) |
| 686 | vmcase(OP_LE, |
| 687 | Protect( |
| 688 | if (luaV_lessequal(L, RKB(i), RKC(i)) != GETARG_A(i)) |
| 689 | ci->u.l.savedpc++; |
| 690 | else |
| 691 | donextjump(ci); |
| 692 | ) |
| 693 | ) |
| 694 | vmcase(OP_TEST, |
| 695 | if (GETARG_C(i) ? l_isfalse(ra) : !l_isfalse(ra)) |
| 696 | ci->u.l.savedpc++; |
| 697 | else |
| 698 | donextjump(ci); |
| 699 | ) |
| 700 | vmcase(OP_TESTSET, |
| 701 | TValue *rb = RB(i); |
| 702 | if (GETARG_C(i) ? l_isfalse(rb) : !l_isfalse(rb)) |
| 703 | ci->u.l.savedpc++; |
| 704 | else { |
| 705 | setobjs2s(L, ra, rb); |
| 706 | donextjump(ci); |
| 707 | } |
| 708 | ) |
| 709 | vmcase(OP_CALL, |
| 710 | int b = GETARG_B(i); |
| 711 | int nresults = GETARG_C(i) - 1; |
| 712 | if (b != 0) L->top = ra+b; /* else previous instruction set top */ |
| 713 | if (luaD_precall(L, ra, nresults)) { /* C function? */ |
| 714 | if (nresults >= 0) L->top = ci->top; /* adjust results */ |
| 715 | base = ci->u.l.base; |
| 716 | } |
| 717 | else { /* Lua function */ |
| 718 | ci = L->ci; |
| 719 | ci->callstatus |= CIST_REENTRY; |
| 720 | goto newframe; /* restart luaV_execute over new Lua function */ |
| 721 | } |
| 722 | ) |
| 723 | vmcase(OP_TAILCALL, |
| 724 | int b = GETARG_B(i); |
| 725 | if (b != 0) L->top = ra+b; /* else previous instruction set top */ |
| 726 | lua_assert(GETARG_C(i) - 1 == LUA_MULTRET); |
| 727 | if (luaD_precall(L, ra, LUA_MULTRET)) /* C function? */ |
| 728 | base = ci->u.l.base; |
| 729 | else { |
| 730 | /* tail call: put called frame (n) in place of caller one (o) */ |
| 731 | CallInfo *nci = L->ci; /* called frame */ |
| 732 | CallInfo *oci = nci->previous; /* caller frame */ |
| 733 | StkId nfunc = nci->func; /* called function */ |
| 734 | StkId ofunc = oci->func; /* caller function */ |
| 735 | /* last stack slot filled by 'precall' */ |
| 736 | StkId lim = nci->u.l.base + getproto(nfunc)->numparams; |
| 737 | int aux; |
| 738 | /* close all upvalues from previous call */ |
| 739 | if (cl->p->sizep > 0) luaF_close(L, oci->u.l.base); |
| 740 | /* move new frame into old one */ |
| 741 | for (aux = 0; nfunc + aux < lim; aux++) |
| 742 | setobjs2s(L, ofunc + aux, nfunc + aux); |
| 743 | oci->u.l.base = ofunc + (nci->u.l.base - nfunc); /* correct base */ |
| 744 | oci->top = L->top = ofunc + (L->top - nfunc); /* correct top */ |
| 745 | oci->u.l.savedpc = nci->u.l.savedpc; |
| 746 | oci->callstatus |= CIST_TAIL; /* function was tail called */ |
| 747 | ci = L->ci = oci; /* remove new frame */ |
| 748 | lua_assert(L->top == oci->u.l.base + getproto(ofunc)->maxstacksize); |
| 749 | goto newframe; /* restart luaV_execute over new Lua function */ |
| 750 | } |
| 751 | ) |
| 752 | vmcasenb(OP_RETURN, |
| 753 | int b = GETARG_B(i); |
| 754 | if (b != 0) L->top = ra+b-1; |
| 755 | if (cl->p->sizep > 0) luaF_close(L, base); |
| 756 | b = luaD_poscall(L, ra); |
| 757 | if (!(ci->callstatus & CIST_REENTRY)) /* 'ci' still the called one */ |
| 758 | return; /* external invocation: return */ |
| 759 | else { /* invocation via reentry: continue execution */ |
| 760 | ci = L->ci; |
| 761 | if (b) L->top = ci->top; |
| 762 | lua_assert(isLua(ci)); |
| 763 | lua_assert(GET_OPCODE(*((ci)->u.l.savedpc - 1)) == OP_CALL); |
| 764 | goto newframe; /* restart luaV_execute over new Lua function */ |
| 765 | } |
| 766 | ) |
| 767 | vmcase(OP_FORLOOP, |
| 768 | lua_Number step = nvalue(ra+2); |
| 769 | lua_Number idx = luai_numadd(L, nvalue(ra), step); /* increment index */ |
| 770 | lua_Number limit = nvalue(ra+1); |
| 771 | if (luai_numlt(L, 0, step) ? luai_numle(L, idx, limit) |
| 772 | : luai_numle(L, limit, idx)) { |
| 773 | ci->u.l.savedpc += GETARG_sBx(i); /* jump back */ |
| 774 | setnvalue(ra, idx); /* update internal index... */ |
| 775 | setnvalue(ra+3, idx); /* ...and external index */ |
| 776 | } |
| 777 | ) |
| 778 | vmcase(OP_FORPREP, |
| 779 | const TValue *init = ra; |
| 780 | const TValue *plimit = ra+1; |
| 781 | const TValue *pstep = ra+2; |
| 782 | if (!tonumber(init, ra)) |
| 783 | luaG_runerror(L, LUA_QL("for") " initial value must be a number"); |
| 784 | else if (!tonumber(plimit, ra+1)) |
| 785 | luaG_runerror(L, LUA_QL("for") " limit must be a number"); |
| 786 | else if (!tonumber(pstep, ra+2)) |
| 787 | luaG_runerror(L, LUA_QL("for") " step must be a number"); |
| 788 | setnvalue(ra, luai_numsub(L, nvalue(ra), nvalue(pstep))); |
| 789 | ci->u.l.savedpc += GETARG_sBx(i); |
| 790 | ) |
| 791 | vmcasenb(OP_TFORCALL, |
| 792 | StkId cb = ra + 3; /* call base */ |
| 793 | setobjs2s(L, cb+2, ra+2); |
| 794 | setobjs2s(L, cb+1, ra+1); |
| 795 | setobjs2s(L, cb, ra); |
| 796 | L->top = cb + 3; /* func. + 2 args (state and index) */ |
| 797 | Protect(luaD_call(L, cb, GETARG_C(i), 1)); |
| 798 | L->top = ci->top; |
| 799 | i = *(ci->u.l.savedpc++); /* go to next instruction */ |
| 800 | ra = RA(i); |
| 801 | lua_assert(GET_OPCODE(i) == OP_TFORLOOP); |
| 802 | goto l_tforloop; |
| 803 | ) |
| 804 | vmcase(OP_TFORLOOP, |
| 805 | l_tforloop: |
| 806 | if (!ttisnil(ra + 1)) { /* continue loop? */ |
| 807 | setobjs2s(L, ra, ra + 1); /* save control variable */ |
| 808 | ci->u.l.savedpc += GETARG_sBx(i); /* jump back */ |
| 809 | } |
| 810 | ) |
| 811 | vmcase(OP_SETLIST, |
| 812 | int n = GETARG_B(i); |
| 813 | int c = GETARG_C(i); |
| 814 | int last; |
| 815 | Table *h; |
| 816 | if (n == 0) n = cast_int(L->top - ra) - 1; |
| 817 | if (c == 0) { |
| 818 | lua_assert(GET_OPCODE(*ci->u.l.savedpc) == OP_EXTRAARG); |
| 819 | c = GETARG_Ax(*ci->u.l.savedpc++); |
| 820 | } |
| 821 | luai_runtimecheck(L, ttistable(ra)); |
| 822 | h = hvalue(ra); |
| 823 | last = ((c-1)*LFIELDS_PER_FLUSH) + n; |
| 824 | if (last > h->sizearray) /* needs more space? */ |
| 825 | luaH_resizearray(L, h, last); /* pre-allocate it at once */ |
| 826 | for (; n > 0; n--) { |
| 827 | TValue *val = ra+n; |
| 828 | luaH_setint(L, h, last--, val); |
| 829 | luaC_barrierback(L, obj2gco(h), val); |
| 830 | } |
| 831 | L->top = ci->top; /* correct top (in case of previous open call) */ |
| 832 | ) |
| 833 | vmcase(OP_CLOSURE, |
| 834 | Proto *p = cl->p->p[GETARG_Bx(i)]; |
| 835 | Closure *ncl = getcached(p, cl->upvals, base); /* cached closure */ |
| 836 | if (ncl == NULL) /* no match? */ |
| 837 | pushclosure(L, p, cl->upvals, base, ra); /* create a new one */ |
| 838 | else |
| 839 | setclLvalue(L, ra, ncl); /* push cashed closure */ |
| 840 | checkGC(L, ra + 1); |
| 841 | ) |
| 842 | vmcase(OP_VARARG, |
| 843 | int b = GETARG_B(i) - 1; |
| 844 | int j; |
| 845 | int n = cast_int(base - ci->func) - cl->p->numparams - 1; |
| 846 | if (b < 0) { /* B == 0? */ |
| 847 | b = n; /* get all var. arguments */ |
| 848 | Protect(luaD_checkstack(L, n)); |
| 849 | ra = RA(i); /* previous call may change the stack */ |
| 850 | L->top = ra + n; |
| 851 | } |
| 852 | for (j = 0; j < b; j++) { |
| 853 | if (j < n) { |
| 854 | setobjs2s(L, ra + j, base - n + j); |
| 855 | } |
| 856 | else { |
| 857 | setnilvalue(ra + j); |
| 858 | } |
| 859 | } |
| 860 | ) |
| 861 | vmcase(OP_EXTRAARG, |
| 862 | lua_assert(0); |
| 863 | ) |
| 864 | } |
| 865 | } |
| 866 | 866 | } |
| 867 | |
trunk/src/lib/lua/ltable.c
| r30857 | r30858 | |
| 1 | 1 | /* |
| 2 | | ** $Id: ltable.c,v 2.72 2012/09/11 19:37:16 roberto Exp $ |
| 2 | ** $Id: ltable.c,v 2.72.1.1 2013/04/12 18:48:47 roberto Exp $ |
| 3 | 3 | ** Lua tables (hash) |
| 4 | 4 | ** See Copyright Notice in lua.h |
| 5 | 5 | */ |
| r30857 | r30858 | |
| 40 | 40 | ** max size of array part is 2^MAXBITS |
| 41 | 41 | */ |
| 42 | 42 | #if LUAI_BITSINT >= 32 |
| 43 | | #define MAXBITS 30 |
| 43 | #define MAXBITS 30 |
| 44 | 44 | #else |
| 45 | | #define MAXBITS (LUAI_BITSINT-2) |
| 45 | #define MAXBITS (LUAI_BITSINT-2) |
| 46 | 46 | #endif |
| 47 | 47 | |
| 48 | | #define MAXASIZE (1 << MAXBITS) |
| 48 | #define MAXASIZE (1 << MAXBITS) |
| 49 | 49 | |
| 50 | 50 | |
| 51 | | #define hashpow2(t,n) (gnode(t, lmod((n), sizenode(t)))) |
| 51 | #define hashpow2(t,n) (gnode(t, lmod((n), sizenode(t)))) |
| 52 | 52 | |
| 53 | | #define hashstr(t,str) hashpow2(t, (str)->tsv.hash) |
| 54 | | #define hashboolean(t,p) hashpow2(t, p) |
| 53 | #define hashstr(t,str) hashpow2(t, (str)->tsv.hash) |
| 54 | #define hashboolean(t,p) hashpow2(t, p) |
| 55 | 55 | |
| 56 | 56 | |
| 57 | 57 | /* |
| 58 | 58 | ** for some types, it is better to avoid modulus by power of 2, as |
| 59 | 59 | ** they tend to have many 2 factors. |
| 60 | 60 | */ |
| 61 | | #define hashmod(t,n) (gnode(t, ((n) % ((sizenode(t)-1)|1)))) |
| 61 | #define hashmod(t,n) (gnode(t, ((n) % ((sizenode(t)-1)|1)))) |
| 62 | 62 | |
| 63 | 63 | |
| 64 | | #define hashpointer(t,p) hashmod(t, IntPoint(p)) |
| 64 | #define hashpointer(t,p) hashmod(t, IntPoint(p)) |
| 65 | 65 | |
| 66 | 66 | |
| 67 | | #define dummynode (&dummynode_) |
| 67 | #define dummynode (&dummynode_) |
| 68 | 68 | |
| 69 | | #define isdummy(n) ((n) == dummynode) |
| 69 | #define isdummy(n) ((n) == dummynode) |
| 70 | 70 | |
| 71 | 71 | static const Node dummynode_ = { |
| 72 | | {NILCONSTANT}, /* value */ |
| 73 | | {{NILCONSTANT, NULL}} /* key */ |
| 72 | {NILCONSTANT}, /* value */ |
| 73 | {{NILCONSTANT, NULL}} /* key */ |
| 74 | 74 | }; |
| 75 | 75 | |
| 76 | 76 | |
| r30857 | r30858 | |
| 78 | 78 | ** hash for lua_Numbers |
| 79 | 79 | */ |
| 80 | 80 | static Node *hashnum (const Table *t, lua_Number n) { |
| 81 | | int i; |
| 82 | | luai_hashnum(i, n); |
| 83 | | if (i < 0) { |
| 84 | | if (cast(unsigned int, i) == 0u - i) /* use unsigned to avoid overflows */ |
| 85 | | i = 0; /* handle INT_MIN */ |
| 86 | | i = -i; /* must be a positive value */ |
| 87 | | } |
| 88 | | return hashmod(t, i); |
| 81 | int i; |
| 82 | luai_hashnum(i, n); |
| 83 | if (i < 0) { |
| 84 | if (cast(unsigned int, i) == 0u - i) /* use unsigned to avoid overflows */ |
| 85 | i = 0; /* handle INT_MIN */ |
| 86 | i = -i; /* must be a positive value */ |
| 87 | } |
| 88 | return hashmod(t, i); |
| 89 | 89 | } |
| 90 | 90 | |
| 91 | 91 | |
| r30857 | r30858 | |
| 95 | 95 | ** of its hash value) |
| 96 | 96 | */ |
| 97 | 97 | static Node *mainposition (const Table *t, const TValue *key) { |
| 98 | | switch (ttype(key)) { |
| 99 | | case LUA_TNUMBER: |
| 100 | | return hashnum(t, nvalue(key)); |
| 101 | | case LUA_TLNGSTR: { |
| 102 | | TString *s = rawtsvalue(key); |
| 103 | | if (s->tsv.extra == 0) { /* no hash? */ |
| 104 | | s->tsv.hash = luaS_hash(getstr(s), s->tsv.len, s->tsv.hash); |
| 105 | | s->tsv.extra = 1; /* now it has its hash */ |
| 106 | | } |
| 107 | | return hashstr(t, rawtsvalue(key)); |
| 108 | | } |
| 109 | | case LUA_TSHRSTR: |
| 110 | | return hashstr(t, rawtsvalue(key)); |
| 111 | | case LUA_TBOOLEAN: |
| 112 | | return hashboolean(t, bvalue(key)); |
| 113 | | case LUA_TLIGHTUSERDATA: |
| 114 | | return hashpointer(t, pvalue(key)); |
| 115 | | case LUA_TLCF: |
| 116 | | return hashpointer(t, fvalue(key)); |
| 117 | | default: |
| 118 | | return hashpointer(t, gcvalue(key)); |
| 119 | | } |
| 98 | switch (ttype(key)) { |
| 99 | case LUA_TNUMBER: |
| 100 | return hashnum(t, nvalue(key)); |
| 101 | case LUA_TLNGSTR: { |
| 102 | TString *s = rawtsvalue(key); |
| 103 | if (s->tsv.extra == 0) { /* no hash? */ |
| 104 | s->tsv.hash = luaS_hash(getstr(s), s->tsv.len, s->tsv.hash); |
| 105 | s->tsv.extra = 1; /* now it has its hash */ |
| 106 | } |
| 107 | return hashstr(t, rawtsvalue(key)); |
| 108 | } |
| 109 | case LUA_TSHRSTR: |
| 110 | return hashstr(t, rawtsvalue(key)); |
| 111 | case LUA_TBOOLEAN: |
| 112 | return hashboolean(t, bvalue(key)); |
| 113 | case LUA_TLIGHTUSERDATA: |
| 114 | return hashpointer(t, pvalue(key)); |
| 115 | case LUA_TLCF: |
| 116 | return hashpointer(t, fvalue(key)); |
| 117 | default: |
| 118 | return hashpointer(t, gcvalue(key)); |
| 119 | } |
| 120 | 120 | } |
| 121 | 121 | |
| 122 | 122 | |
| r30857 | r30858 | |
| 125 | 125 | ** the array part of the table, -1 otherwise. |
| 126 | 126 | */ |
| 127 | 127 | static int arrayindex (const TValue *key) { |
| 128 | | if (ttisnumber(key)) { |
| 129 | | lua_Number n = nvalue(key); |
| 130 | | int k; |
| 131 | | lua_number2int(k, n); |
| 132 | | if (luai_numeq(cast_num(k), n)) |
| 133 | | return k; |
| 134 | | } |
| 135 | | return -1; /* `key' did not match some condition */ |
| 128 | if (ttisnumber(key)) { |
| 129 | lua_Number n = nvalue(key); |
| 130 | int k; |
| 131 | lua_number2int(k, n); |
| 132 | if (luai_numeq(cast_num(k), n)) |
| 133 | return k; |
| 134 | } |
| 135 | return -1; /* `key' did not match some condition */ |
| 136 | 136 | } |
| 137 | 137 | |
| 138 | 138 | |
| r30857 | r30858 | |
| 142 | 142 | ** beginning of a traversal is signaled by -1. |
| 143 | 143 | */ |
| 144 | 144 | static int findindex (lua_State *L, Table *t, StkId key) { |
| 145 | | int i; |
| 146 | | if (ttisnil(key)) return -1; /* first iteration */ |
| 147 | | i = arrayindex(key); |
| 148 | | if (0 < i && i <= t->sizearray) /* is `key' inside array part? */ |
| 149 | | return i-1; /* yes; that's the index (corrected to C) */ |
| 150 | | else { |
| 151 | | Node *n = mainposition(t, key); |
| 152 | | for (;;) { /* check whether `key' is somewhere in the chain */ |
| 153 | | /* key may be dead already, but it is ok to use it in `next' */ |
| 154 | | if (luaV_rawequalobj(gkey(n), key) || |
| 155 | | (ttisdeadkey(gkey(n)) && iscollectable(key) && |
| 156 | | deadvalue(gkey(n)) == gcvalue(key))) { |
| 157 | | i = cast_int(n - gnode(t, 0)); /* key index in hash table */ |
| 158 | | /* hash elements are numbered after array ones */ |
| 159 | | return i + t->sizearray; |
| 160 | | } |
| 161 | | else n = gnext(n); |
| 162 | | if (n == NULL) |
| 163 | | luaG_runerror(L, "invalid key to " LUA_QL("next")); /* key not found */ |
| 164 | | } |
| 165 | | } |
| 145 | int i; |
| 146 | if (ttisnil(key)) return -1; /* first iteration */ |
| 147 | i = arrayindex(key); |
| 148 | if (0 < i && i <= t->sizearray) /* is `key' inside array part? */ |
| 149 | return i-1; /* yes; that's the index (corrected to C) */ |
| 150 | else { |
| 151 | Node *n = mainposition(t, key); |
| 152 | for (;;) { /* check whether `key' is somewhere in the chain */ |
| 153 | /* key may be dead already, but it is ok to use it in `next' */ |
| 154 | if (luaV_rawequalobj(gkey(n), key) || |
| 155 | (ttisdeadkey(gkey(n)) && iscollectable(key) && |
| 156 | deadvalue(gkey(n)) == gcvalue(key))) { |
| 157 | i = cast_int(n - gnode(t, 0)); /* key index in hash table */ |
| 158 | /* hash elements are numbered after array ones */ |
| 159 | return i + t->sizearray; |
| 160 | } |
| 161 | else n = gnext(n); |
| 162 | if (n == NULL) |
| 163 | luaG_runerror(L, "invalid key to " LUA_QL("next")); /* key not found */ |
| 164 | } |
| 165 | } |
| 166 | 166 | } |
| 167 | 167 | |
| 168 | 168 | |
| 169 | 169 | int luaH_next (lua_State *L, Table *t, StkId key) { |
| 170 | | int i = findindex(L, t, key); /* find original element */ |
| 171 | | for (i++; i < t->sizearray; i++) { /* try first array part */ |
| 172 | | if (!ttisnil(&t->array[i])) { /* a non-nil value? */ |
| 173 | | setnvalue(key, cast_num(i+1)); |
| 174 | | setobj2s(L, key+1, &t->array[i]); |
| 175 | | return 1; |
| 176 | | } |
| 177 | | } |
| 178 | | for (i -= t->sizearray; i < sizenode(t); i++) { /* then hash part */ |
| 179 | | if (!ttisnil(gval(gnode(t, i)))) { /* a non-nil value? */ |
| 180 | | setobj2s(L, key, gkey(gnode(t, i))); |
| 181 | | setobj2s(L, key+1, gval(gnode(t, i))); |
| 182 | | return 1; |
| 183 | | } |
| 184 | | } |
| 185 | | return 0; /* no more elements */ |
| 170 | int i = findindex(L, t, key); /* find original element */ |
| 171 | for (i++; i < t->sizearray; i++) { /* try first array part */ |
| 172 | if (!ttisnil(&t->array[i])) { /* a non-nil value? */ |
| 173 | setnvalue(key, cast_num(i+1)); |
| 174 | setobj2s(L, key+1, &t->array[i]); |
| 175 | return 1; |
| 176 | } |
| 177 | } |
| 178 | for (i -= t->sizearray; i < sizenode(t); i++) { /* then hash part */ |
| 179 | if (!ttisnil(gval(gnode(t, i)))) { /* a non-nil value? */ |
| 180 | setobj2s(L, key, gkey(gnode(t, i))); |
| 181 | setobj2s(L, key+1, gval(gnode(t, i))); |
| 182 | return 1; |
| 183 | } |
| 184 | } |
| 185 | return 0; /* no more elements */ |
| 186 | 186 | } |
| 187 | 187 | |
| 188 | 188 | |
| r30857 | r30858 | |
| 194 | 194 | |
| 195 | 195 | |
| 196 | 196 | static int computesizes (int nums[], int *narray) { |
| 197 | | int i; |
| 198 | | int twotoi; /* 2^i */ |
| 199 | | int a = 0; /* number of elements smaller than 2^i */ |
| 200 | | int na = 0; /* number of elements to go to array part */ |
| 201 | | int n = 0; /* optimal size for array part */ |
| 202 | | for (i = 0, twotoi = 1; twotoi/2 < *narray; i++, twotoi *= 2) { |
| 203 | | if (nums[i] > 0) { |
| 204 | | a += nums[i]; |
| 205 | | if (a > twotoi/2) { /* more than half elements present? */ |
| 206 | | n = twotoi; /* optimal size (till now) */ |
| 207 | | na = a; /* all elements smaller than n will go to array part */ |
| 208 | | } |
| 209 | | } |
| 210 | | if (a == *narray) break; /* all elements already counted */ |
| 211 | | } |
| 212 | | *narray = n; |
| 213 | | lua_assert(*narray/2 <= na && na <= *narray); |
| 214 | | return na; |
| 197 | int i; |
| 198 | int twotoi; /* 2^i */ |
| 199 | int a = 0; /* number of elements smaller than 2^i */ |
| 200 | int na = 0; /* number of elements to go to array part */ |
| 201 | int n = 0; /* optimal size for array part */ |
| 202 | for (i = 0, twotoi = 1; twotoi/2 < *narray; i++, twotoi *= 2) { |
| 203 | if (nums[i] > 0) { |
| 204 | a += nums[i]; |
| 205 | if (a > twotoi/2) { /* more than half elements present? */ |
| 206 | n = twotoi; /* optimal size (till now) */ |
| 207 | na = a; /* all elements smaller than n will go to array part */ |
| 208 | } |
| 209 | } |
| 210 | if (a == *narray) break; /* all elements already counted */ |
| 211 | } |
| 212 | *narray = n; |
| 213 | lua_assert(*narray/2 <= na && na <= *narray); |
| 214 | return na; |
| 215 | 215 | } |
| 216 | 216 | |
| 217 | 217 | |
| 218 | 218 | static int countint (const TValue *key, int *nums) { |
| 219 | | int k = arrayindex(key); |
| 220 | | if (0 < k && k <= MAXASIZE) { /* is `key' an appropriate array index? */ |
| 221 | | nums[luaO_ceillog2(k)]++; /* count as such */ |
| 222 | | return 1; |
| 223 | | } |
| 224 | | else |
| 225 | | return 0; |
| 219 | int k = arrayindex(key); |
| 220 | if (0 < k && k <= MAXASIZE) { /* is `key' an appropriate array index? */ |
| 221 | nums[luaO_ceillog2(k)]++; /* count as such */ |
| 222 | return 1; |
| 223 | } |
| 224 | else |
| 225 | return 0; |
| 226 | 226 | } |
| 227 | 227 | |
| 228 | 228 | |
| 229 | 229 | static int numusearray (const Table *t, int *nums) { |
| 230 | | int lg; |
| 231 | | int ttlg; /* 2^lg */ |
| 232 | | int ause = 0; /* summation of `nums' */ |
| 233 | | int i = 1; /* count to traverse all array keys */ |
| 234 | | for (lg=0, ttlg=1; lg<=MAXBITS; lg++, ttlg*=2) { /* for each slice */ |
| 235 | | int lc = 0; /* counter */ |
| 236 | | int lim = ttlg; |
| 237 | | if (lim > t->sizearray) { |
| 238 | | lim = t->sizearray; /* adjust upper limit */ |
| 239 | | if (i > lim) |
| 240 | | break; /* no more elements to count */ |
| 241 | | } |
| 242 | | /* count elements in range (2^(lg-1), 2^lg] */ |
| 243 | | for (; i <= lim; i++) { |
| 244 | | if (!ttisnil(&t->array[i-1])) |
| 245 | | lc++; |
| 246 | | } |
| 247 | | nums[lg] += lc; |
| 248 | | ause += lc; |
| 249 | | } |
| 250 | | return ause; |
| 230 | int lg; |
| 231 | int ttlg; /* 2^lg */ |
| 232 | int ause = 0; /* summation of `nums' */ |
| 233 | int i = 1; /* count to traverse all array keys */ |
| 234 | for (lg=0, ttlg=1; lg<=MAXBITS; lg++, ttlg*=2) { /* for each slice */ |
| 235 | int lc = 0; /* counter */ |
| 236 | int lim = ttlg; |
| 237 | if (lim > t->sizearray) { |
| 238 | lim = t->sizearray; /* adjust upper limit */ |
| 239 | if (i > lim) |
| 240 | break; /* no more elements to count */ |
| 241 | } |
| 242 | /* count elements in range (2^(lg-1), 2^lg] */ |
| 243 | for (; i <= lim; i++) { |
| 244 | if (!ttisnil(&t->array[i-1])) |
| 245 | lc++; |
| 246 | } |
| 247 | nums[lg] += lc; |
| 248 | ause += lc; |
| 249 | } |
| 250 | return ause; |
| 251 | 251 | } |
| 252 | 252 | |
| 253 | 253 | |
| 254 | 254 | static int numusehash (const Table *t, int *nums, int *pnasize) { |
| 255 | | int totaluse = 0; /* total number of elements */ |
| 256 | | int ause = 0; /* summation of `nums' */ |
| 257 | | int i = sizenode(t); |
| 258 | | while (i--) { |
| 259 | | Node *n = &t->node[i]; |
| 260 | | if (!ttisnil(gval(n))) { |
| 261 | | ause += countint(gkey(n), nums); |
| 262 | | totaluse++; |
| 263 | | } |
| 264 | | } |
| 265 | | *pnasize += ause; |
| 266 | | return totaluse; |
| 255 | int totaluse = 0; /* total number of elements */ |
| 256 | int ause = 0; /* summation of `nums' */ |
| 257 | int i = sizenode(t); |
| 258 | while (i--) { |
| 259 | Node *n = &t->node[i]; |
| 260 | if (!ttisnil(gval(n))) { |
| 261 | ause += countint(gkey(n), nums); |
| 262 | totaluse++; |
| 263 | } |
| 264 | } |
| 265 | *pnasize += ause; |
| 266 | return totaluse; |
| 267 | 267 | } |
| 268 | 268 | |
| 269 | 269 | |
| 270 | 270 | static void setarrayvector (lua_State *L, Table *t, int size) { |
| 271 | | int i; |
| 272 | | luaM_reallocvector(L, t->array, t->sizearray, size, TValue); |
| 273 | | for (i=t->sizearray; i<size; i++) |
| 274 | | setnilvalue(&t->array[i]); |
| 275 | | t->sizearray = size; |
| 271 | int i; |
| 272 | luaM_reallocvector(L, t->array, t->sizearray, size, TValue); |
| 273 | for (i=t->sizearray; i<size; i++) |
| 274 | setnilvalue(&t->array[i]); |
| 275 | t->sizearray = size; |
| 276 | 276 | } |
| 277 | 277 | |
| 278 | 278 | |
| 279 | 279 | static void setnodevector (lua_State *L, Table *t, int size) { |
| 280 | | int lsize; |
| 281 | | if (size == 0) { /* no elements to hash part? */ |
| 282 | | t->node = cast(Node *, dummynode); /* use common `dummynode' */ |
| 283 | | lsize = 0; |
| 284 | | } |
| 285 | | else { |
| 286 | | int i; |
| 287 | | lsize = luaO_ceillog2(size); |
| 288 | | if (lsize > MAXBITS) |
| 289 | | luaG_runerror(L, "table overflow"); |
| 290 | | size = twoto(lsize); |
| 291 | | t->node = luaM_newvector(L, size, Node); |
| 292 | | for (i=0; i<size; i++) { |
| 293 | | Node *n = gnode(t, i); |
| 294 | | gnext(n) = NULL; |
| 295 | | setnilvalue(gkey(n)); |
| 296 | | setnilvalue(gval(n)); |
| 297 | | } |
| 298 | | } |
| 299 | | t->lsizenode = cast_byte(lsize); |
| 300 | | t->lastfree = gnode(t, size); /* all positions are free */ |
| 280 | int lsize; |
| 281 | if (size == 0) { /* no elements to hash part? */ |
| 282 | t->node = cast(Node *, dummynode); /* use common `dummynode' */ |
| 283 | lsize = 0; |
| 284 | } |
| 285 | else { |
| 286 | int i; |
| 287 | lsize = luaO_ceillog2(size); |
| 288 | if (lsize > MAXBITS) |
| 289 | luaG_runerror(L, "table overflow"); |
| 290 | size = twoto(lsize); |
| 291 | t->node = luaM_newvector(L, size, Node); |
| 292 | for (i=0; i<size; i++) { |
| 293 | Node *n = gnode(t, i); |
| 294 | gnext(n) = NULL; |
| 295 | setnilvalue(gkey(n)); |
| 296 | setnilvalue(gval(n)); |
| 297 | } |
| 298 | } |
| 299 | t->lsizenode = cast_byte(lsize); |
| 300 | t->lastfree = gnode(t, size); /* all positions are free */ |
| 301 | 301 | } |
| 302 | 302 | |
| 303 | 303 | |
| 304 | 304 | void luaH_resize (lua_State *L, Table *t, int nasize, int nhsize) { |
| 305 | | int i; |
| 306 | | int oldasize = t->sizearray; |
| 307 | | int oldhsize = t->lsizenode; |
| 308 | | Node *nold = t->node; /* save old hash ... */ |
| 309 | | if (nasize > oldasize) /* array part must grow? */ |
| 310 | | setarrayvector(L, t, nasize); |
| 311 | | /* create new hash part with appropriate size */ |
| 312 | | setnodevector(L, t, nhsize); |
| 313 | | if (nasize < oldasize) { /* array part must shrink? */ |
| 314 | | t->sizearray = nasize; |
| 315 | | /* re-insert elements from vanishing slice */ |
| 316 | | for (i=nasize; i<oldasize; i++) { |
| 317 | | if (!ttisnil(&t->array[i])) |
| 318 | | luaH_setint(L, t, i + 1, &t->array[i]); |
| 319 | | } |
| 320 | | /* shrink array */ |
| 321 | | luaM_reallocvector(L, t->array, oldasize, nasize, TValue); |
| 322 | | } |
| 323 | | /* re-insert elements from hash part */ |
| 324 | | for (i = twoto(oldhsize) - 1; i >= 0; i--) { |
| 325 | | Node *old = nold+i; |
| 326 | | if (!ttisnil(gval(old))) { |
| 327 | | /* doesn't need barrier/invalidate cache, as entry was |
| 328 | | already present in the table */ |
| 329 | | setobjt2t(L, luaH_set(L, t, gkey(old)), gval(old)); |
| 330 | | } |
| 331 | | } |
| 332 | | if (!isdummy(nold)) |
| 333 | | luaM_freearray(L, nold, cast(size_t, twoto(oldhsize))); /* free old array */ |
| 305 | int i; |
| 306 | int oldasize = t->sizearray; |
| 307 | int oldhsize = t->lsizenode; |
| 308 | Node *nold = t->node; /* save old hash ... */ |
| 309 | if (nasize > oldasize) /* array part must grow? */ |
| 310 | setarrayvector(L, t, nasize); |
| 311 | /* create new hash part with appropriate size */ |
| 312 | setnodevector(L, t, nhsize); |
| 313 | if (nasize < oldasize) { /* array part must shrink? */ |
| 314 | t->sizearray = nasize; |
| 315 | /* re-insert elements from vanishing slice */ |
| 316 | for (i=nasize; i<oldasize; i++) { |
| 317 | if (!ttisnil(&t->array[i])) |
| 318 | luaH_setint(L, t, i + 1, &t->array[i]); |
| 319 | } |
| 320 | /* shrink array */ |
| 321 | luaM_reallocvector(L, t->array, oldasize, nasize, TValue); |
| 322 | } |
| 323 | /* re-insert elements from hash part */ |
| 324 | for (i = twoto(oldhsize) - 1; i >= 0; i--) { |
| 325 | Node *old = nold+i; |
| 326 | if (!ttisnil(gval(old))) { |
| 327 | /* doesn't need barrier/invalidate cache, as entry was |
| 328 | already present in the table */ |
| 329 | setobjt2t(L, luaH_set(L, t, gkey(old)), gval(old)); |
| 330 | } |
| 331 | } |
| 332 | if (!isdummy(nold)) |
| 333 | luaM_freearray(L, nold, cast(size_t, twoto(oldhsize))); /* free old array */ |
| 334 | 334 | } |
| 335 | 335 | |
| 336 | 336 | |
| 337 | 337 | void luaH_resizearray (lua_State *L, Table *t, int nasize) { |
| 338 | | int nsize = isdummy(t->node) ? 0 : sizenode(t); |
| 339 | | luaH_resize(L, t, nasize, nsize); |
| 338 | int nsize = isdummy(t->node) ? 0 : sizenode(t); |
| 339 | luaH_resize(L, t, nasize, nsize); |
| 340 | 340 | } |
| 341 | 341 | |
| 342 | 342 | |
| 343 | 343 | static void rehash (lua_State *L, Table *t, const TValue *ek) { |
| 344 | | int nasize, na; |
| 345 | | int nums[MAXBITS+1]; /* nums[i] = number of keys with 2^(i-1) < k <= 2^i */ |
| 346 | | int i; |
| 347 | | int totaluse; |
| 348 | | for (i=0; i<=MAXBITS; i++) nums[i] = 0; /* reset counts */ |
| 349 | | nasize = numusearray(t, nums); /* count keys in array part */ |
| 350 | | totaluse = nasize; /* all those keys are integer keys */ |
| 351 | | totaluse += numusehash(t, nums, &nasize); /* count keys in hash part */ |
| 352 | | /* count extra key */ |
| 353 | | nasize += countint(ek, nums); |
| 354 | | totaluse++; |
| 355 | | /* compute new size for array part */ |
| 356 | | na = computesizes(nums, &nasize); |
| 357 | | /* resize the table to new computed sizes */ |
| 358 | | luaH_resize(L, t, nasize, totaluse - na); |
| 344 | int nasize, na; |
| 345 | int nums[MAXBITS+1]; /* nums[i] = number of keys with 2^(i-1) < k <= 2^i */ |
| 346 | int i; |
| 347 | int totaluse; |
| 348 | for (i=0; i<=MAXBITS; i++) nums[i] = 0; /* reset counts */ |
| 349 | nasize = numusearray(t, nums); /* count keys in array part */ |
| 350 | totaluse = nasize; /* all those keys are integer keys */ |
| 351 | totaluse += numusehash(t, nums, &nasize); /* count keys in hash part */ |
| 352 | /* count extra key */ |
| 353 | nasize += countint(ek, nums); |
| 354 | totaluse++; |
| 355 | /* compute new size for array part */ |
| 356 | na = computesizes(nums, &nasize); |
| 357 | /* resize the table to new computed sizes */ |
| 358 | luaH_resize(L, t, nasize, totaluse - na); |
| 359 | 359 | } |
| 360 | 360 | |
| 361 | 361 | |
| r30857 | r30858 | |
| 366 | 366 | |
| 367 | 367 | |
| 368 | 368 | Table *luaH_new (lua_State *L) { |
| 369 | | Table *t = &luaC_newobj(L, LUA_TTABLE, sizeof(Table), NULL, 0)->h; |
| 370 | | t->metatable = NULL; |
| 371 | | t->flags = cast_byte(~0); |
| 372 | | t->array = NULL; |
| 373 | | t->sizearray = 0; |
| 374 | | setnodevector(L, t, 0); |
| 375 | | return t; |
| 369 | Table *t = &luaC_newobj(L, LUA_TTABLE, sizeof(Table), NULL, 0)->h; |
| 370 | t->metatable = NULL; |
| 371 | t->flags = cast_byte(~0); |
| 372 | t->array = NULL; |
| 373 | t->sizearray = 0; |
| 374 | setnodevector(L, t, 0); |
| 375 | return t; |
| 376 | 376 | } |
| 377 | 377 | |
| 378 | 378 | |
| 379 | 379 | void luaH_free (lua_State *L, Table *t) { |
| 380 | | if (!isdummy(t->node)) |
| 381 | | luaM_freearray(L, t->node, cast(size_t, sizenode(t))); |
| 382 | | luaM_freearray(L, t->array, t->sizearray); |
| 383 | | luaM_free(L, t); |
| 380 | if (!isdummy(t->node)) |
| 381 | luaM_freearray(L, t->node, cast(size_t, sizenode(t))); |
| 382 | luaM_freearray(L, t->array, t->sizearray); |
| 383 | luaM_free(L, t); |
| 384 | 384 | } |
| 385 | 385 | |
| 386 | 386 | |
| 387 | 387 | static Node *getfreepos (Table *t) { |
| 388 | | while (t->lastfree > t->node) { |
| 389 | | t->lastfree--; |
| 390 | | if (ttisnil(gkey(t->lastfree))) |
| 391 | | return t->lastfree; |
| 392 | | } |
| 393 | | return NULL; /* could not find a free place */ |
| 388 | while (t->lastfree > t->node) { |
| 389 | t->lastfree--; |
| 390 | if (ttisnil(gkey(t->lastfree))) |
| 391 | return t->lastfree; |
| 392 | } |
| 393 | return NULL; /* could not find a free place */ |
| 394 | 394 | } |
| 395 | 395 | |
| 396 | 396 | |
| r30857 | r30858 | |
| 403 | 403 | ** position), new key goes to an empty position. |
| 404 | 404 | */ |
| 405 | 405 | TValue *luaH_newkey (lua_State *L, Table *t, const TValue *key) { |
| 406 | | Node *mp; |
| 407 | | if (ttisnil(key)) luaG_runerror(L, "table index is nil"); |
| 408 | | else if (ttisnumber(key) && luai_numisnan(L, nvalue(key))) |
| 409 | | luaG_runerror(L, "table index is NaN"); |
| 410 | | mp = mainposition(t, key); |
| 411 | | if (!ttisnil(gval(mp)) || isdummy(mp)) { /* main position is taken? */ |
| 412 | | Node *othern; |
| 413 | | Node *n = getfreepos(t); /* get a free place */ |
| 414 | | if (n == NULL) { /* cannot find a free place? */ |
| 415 | | rehash(L, t, key); /* grow table */ |
| 416 | | /* whatever called 'newkey' take care of TM cache and GC barrier */ |
| 417 | | return luaH_set(L, t, key); /* insert key into grown table */ |
| 418 | | } |
| 419 | | lua_assert(!isdummy(n)); |
| 420 | | othern = mainposition(t, gkey(mp)); |
| 421 | | if (othern != mp) { /* is colliding node out of its main position? */ |
| 422 | | /* yes; move colliding node into free position */ |
| 423 | | while (gnext(othern) != mp) othern = gnext(othern); /* find previous */ |
| 424 | | gnext(othern) = n; /* redo the chain with `n' in place of `mp' */ |
| 425 | | *n = *mp; /* copy colliding node into free pos. (mp->next also goes) */ |
| 426 | | gnext(mp) = NULL; /* now `mp' is free */ |
| 427 | | setnilvalue(gval(mp)); |
| 428 | | } |
| 429 | | else { /* colliding node is in its own main position */ |
| 430 | | /* new node will go into free position */ |
| 431 | | gnext(n) = gnext(mp); /* chain new position */ |
| 432 | | gnext(mp) = n; |
| 433 | | mp = n; |
| 434 | | } |
| 435 | | } |
| 436 | | setobj2t(L, gkey(mp), key); |
| 437 | | luaC_barrierback(L, obj2gco(t), key); |
| 438 | | lua_assert(ttisnil(gval(mp))); |
| 439 | | return gval(mp); |
| 406 | Node *mp; |
| 407 | if (ttisnil(key)) luaG_runerror(L, "table index is nil"); |
| 408 | else if (ttisnumber(key) && luai_numisnan(L, nvalue(key))) |
| 409 | luaG_runerror(L, "table index is NaN"); |
| 410 | mp = mainposition(t, key); |
| 411 | if (!ttisnil(gval(mp)) || isdummy(mp)) { /* main position is taken? */ |
| 412 | Node *othern; |
| 413 | Node *n = getfreepos(t); /* get a free place */ |
| 414 | if (n == NULL) { /* cannot find a free place? */ |
| 415 | rehash(L, t, key); /* grow table */ |
| 416 | /* whatever called 'newkey' take care of TM cache and GC barrier */ |
| 417 | return luaH_set(L, t, key); /* insert key into grown table */ |
| 418 | } |
| 419 | lua_assert(!isdummy(n)); |
| 420 | othern = mainposition(t, gkey(mp)); |
| 421 | if (othern != mp) { /* is colliding node out of its main position? */ |
| 422 | /* yes; move colliding node into free position */ |
| 423 | while (gnext(othern) != mp) othern = gnext(othern); /* find previous */ |
| 424 | gnext(othern) = n; /* redo the chain with `n' in place of `mp' */ |
| 425 | *n = *mp; /* copy colliding node into free pos. (mp->next also goes) */ |
| 426 | gnext(mp) = NULL; /* now `mp' is free */ |
| 427 | setnilvalue(gval(mp)); |
| 428 | } |
| 429 | else { /* colliding node is in its own main position */ |
| 430 | /* new node will go into free position */ |
| 431 | gnext(n) = gnext(mp); /* chain new position */ |
| 432 | gnext(mp) = n; |
| 433 | mp = n; |
| 434 | } |
| 435 | } |
| 436 | setobj2t(L, gkey(mp), key); |
| 437 | luaC_barrierback(L, obj2gco(t), key); |
| 438 | lua_assert(ttisnil(gval(mp))); |
| 439 | return gval(mp); |
| 440 | 440 | } |
| 441 | 441 | |
| 442 | 442 | |
| r30857 | r30858 | |
| 444 | 444 | ** search function for integers |
| 445 | 445 | */ |
| 446 | 446 | const TValue *luaH_getint (Table *t, int key) { |
| 447 | | /* (1 <= key && key <= t->sizearray) */ |
| 448 | | if (cast(unsigned int, key-1) < cast(unsigned int, t->sizearray)) |
| 449 | | return &t->array[key-1]; |
| 450 | | else { |
| 451 | | lua_Number nk = cast_num(key); |
| 452 | | Node *n = hashnum(t, nk); |
| 453 | | do { /* check whether `key' is somewhere in the chain */ |
| 454 | | if (ttisnumber(gkey(n)) && luai_numeq(nvalue(gkey(n)), nk)) |
| 455 | | return gval(n); /* that's it */ |
| 456 | | else n = gnext(n); |
| 457 | | } while (n); |
| 458 | | return luaO_nilobject; |
| 459 | | } |
| 447 | /* (1 <= key && key <= t->sizearray) */ |
| 448 | if (cast(unsigned int, key-1) < cast(unsigned int, t->sizearray)) |
| 449 | return &t->array[key-1]; |
| 450 | else { |
| 451 | lua_Number nk = cast_num(key); |
| 452 | Node *n = hashnum(t, nk); |
| 453 | do { /* check whether `key' is somewhere in the chain */ |
| 454 | if (ttisnumber(gkey(n)) && luai_numeq(nvalue(gkey(n)), nk)) |
| 455 | return gval(n); /* that's it */ |
| 456 | else n = gnext(n); |
| 457 | } while (n); |
| 458 | return luaO_nilobject; |
| 459 | } |
| 460 | 460 | } |
| 461 | 461 | |
| 462 | 462 | |
| r30857 | r30858 | |
| 464 | 464 | ** search function for short strings |
| 465 | 465 | */ |
| 466 | 466 | const TValue *luaH_getstr (Table *t, TString *key) { |
| 467 | | Node *n = hashstr(t, key); |
| 468 | | lua_assert(key->tsv.tt == LUA_TSHRSTR); |
| 469 | | do { /* check whether `key' is somewhere in the chain */ |
| 470 | | if (ttisshrstring(gkey(n)) && eqshrstr(rawtsvalue(gkey(n)), key)) |
| 471 | | return gval(n); /* that's it */ |
| 472 | | else n = gnext(n); |
| 473 | | } while (n); |
| 474 | | return luaO_nilobject; |
| 467 | Node *n = hashstr(t, key); |
| 468 | lua_assert(key->tsv.tt == LUA_TSHRSTR); |
| 469 | do { /* check whether `key' is somewhere in the chain */ |
| 470 | if (ttisshrstring(gkey(n)) && eqshrstr(rawtsvalue(gkey(n)), key)) |
| 471 | return gval(n); /* that's it */ |
| 472 | else n = gnext(n); |
| 473 | } while (n); |
| 474 | return luaO_nilobject; |
| 475 | 475 | } |
| 476 | 476 | |
| 477 | 477 | |
| r30857 | r30858 | |
| 479 | 479 | ** main search function |
| 480 | 480 | */ |
| 481 | 481 | const TValue *luaH_get (Table *t, const TValue *key) { |
| 482 | | switch (ttype(key)) { |
| 483 | | case LUA_TSHRSTR: return luaH_getstr(t, rawtsvalue(key)); |
| 484 | | case LUA_TNIL: return luaO_nilobject; |
| 485 | | case LUA_TNUMBER: { |
| 486 | | int k; |
| 487 | | lua_Number n = nvalue(key); |
| 488 | | lua_number2int(k, n); |
| 489 | | if (luai_numeq(cast_num(k), n)) /* index is int? */ |
| 490 | | return luaH_getint(t, k); /* use specialized version */ |
| 491 | | /* else go through */ |
| 492 | | } |
| 493 | | default: { |
| 494 | | Node *n = mainposition(t, key); |
| 495 | | do { /* check whether `key' is somewhere in the chain */ |
| 496 | | if (luaV_rawequalobj(gkey(n), key)) |
| 497 | | return gval(n); /* that's it */ |
| 498 | | else n = gnext(n); |
| 499 | | } while (n); |
| 500 | | return luaO_nilobject; |
| 501 | | } |
| 502 | | } |
| 482 | switch (ttype(key)) { |
| 483 | case LUA_TSHRSTR: return luaH_getstr(t, rawtsvalue(key)); |
| 484 | case LUA_TNIL: return luaO_nilobject; |
| 485 | case LUA_TNUMBER: { |
| 486 | int k; |
| 487 | lua_Number n = nvalue(key); |
| 488 | lua_number2int(k, n); |
| 489 | if (luai_numeq(cast_num(k), n)) /* index is int? */ |
| 490 | return luaH_getint(t, k); /* use specialized version */ |
| 491 | /* else go through */ |
| 492 | } |
| 493 | default: { |
| 494 | Node *n = mainposition(t, key); |
| 495 | do { /* check whether `key' is somewhere in the chain */ |
| 496 | if (luaV_rawequalobj(gkey(n), key)) |
| 497 | return gval(n); /* that's it */ |
| 498 | else n = gnext(n); |
| 499 | } while (n); |
| 500 | return luaO_nilobject; |
| 501 | } |
| 502 | } |
| 503 | 503 | } |
| 504 | 504 | |
| 505 | 505 | |
| r30857 | r30858 | |
| 508 | 508 | ** barrier and invalidate the TM cache. |
| 509 | 509 | */ |
| 510 | 510 | TValue *luaH_set (lua_State *L, Table *t, const TValue *key) { |
| 511 | | const TValue *p = luaH_get(t, key); |
| 512 | | if (p != luaO_nilobject) |
| 513 | | return cast(TValue *, p); |
| 514 | | else return luaH_newkey(L, t, key); |
| 511 | const TValue *p = luaH_get(t, key); |
| 512 | if (p != luaO_nilobject) |
| 513 | return cast(TValue *, p); |
| 514 | else return luaH_newkey(L, t, key); |
| 515 | 515 | } |
| 516 | 516 | |
| 517 | 517 | |
| 518 | 518 | void luaH_setint (lua_State *L, Table *t, int key, TValue *value) { |
| 519 | | const TValue *p = luaH_getint(t, key); |
| 520 | | TValue *cell; |
| 521 | | if (p != luaO_nilobject) |
| 522 | | cell = cast(TValue *, p); |
| 523 | | else { |
| 524 | | TValue k; |
| 525 | | setnvalue(&k, cast_num(key)); |
| 526 | | cell = luaH_newkey(L, t, &k); |
| 527 | | } |
| 528 | | setobj2t(L, cell, value); |
| 519 | const TValue *p = luaH_getint(t, key); |
| 520 | TValue *cell; |
| 521 | if (p != luaO_nilobject) |
| 522 | cell = cast(TValue *, p); |
| 523 | else { |
| 524 | TValue k; |
| 525 | setnvalue(&k, cast_num(key)); |
| 526 | cell = luaH_newkey(L, t, &k); |
| 527 | } |
| 528 | setobj2t(L, cell, value); |
| 529 | 529 | } |
| 530 | 530 | |
| 531 | 531 | |
| 532 | 532 | static int unbound_search (Table *t, unsigned int j) { |
| 533 | | unsigned int i = j; /* i is zero or a present index */ |
| 534 | | j++; |
| 535 | | /* find `i' and `j' such that i is present and j is not */ |
| 536 | | while (!ttisnil(luaH_getint(t, j))) { |
| 537 | | i = j; |
| 538 | | j *= 2; |
| 539 | | if (j > cast(unsigned int, MAX_INT)) { /* overflow? */ |
| 540 | | /* table was built with bad purposes: resort to linear search */ |
| 541 | | i = 1; |
| 542 | | while (!ttisnil(luaH_getint(t, i))) i++; |
| 543 | | return i - 1; |
| 544 | | } |
| 545 | | } |
| 546 | | /* now do a binary search between them */ |
| 547 | | while (j - i > 1) { |
| 548 | | unsigned int m = (i+j)/2; |
| 549 | | if (ttisnil(luaH_getint(t, m))) j = m; |
| 550 | | else i = m; |
| 551 | | } |
| 552 | | return i; |
| 533 | unsigned int i = j; /* i is zero or a present index */ |
| 534 | j++; |
| 535 | /* find `i' and `j' such that i is present and j is not */ |
| 536 | while (!ttisnil(luaH_getint(t, j))) { |
| 537 | i = j; |
| 538 | j *= 2; |
| 539 | if (j > cast(unsigned int, MAX_INT)) { /* overflow? */ |
| 540 | /* table was built with bad purposes: resort to linear search */ |
| 541 | i = 1; |
| 542 | while (!ttisnil(luaH_getint(t, i))) i++; |
| 543 | return i - 1; |
| 544 | } |
| 545 | } |
| 546 | /* now do a binary search between them */ |
| 547 | while (j - i > 1) { |
| 548 | unsigned int m = (i+j)/2; |
| 549 | if (ttisnil(luaH_getint(t, m))) j = m; |
| 550 | else i = m; |
| 551 | } |
| 552 | return i; |
| 553 | 553 | } |
| 554 | 554 | |
| 555 | 555 | |
| r30857 | r30858 | |
| 558 | 558 | ** such that t[i] is non-nil and t[i+1] is nil (and 0 if t[1] is nil). |
| 559 | 559 | */ |
| 560 | 560 | int luaH_getn (Table *t) { |
| 561 | | unsigned int j = t->sizearray; |
| 562 | | if (j > 0 && ttisnil(&t->array[j - 1])) { |
| 563 | | /* there is a boundary in the array part: (binary) search for it */ |
| 564 | | unsigned int i = 0; |
| 565 | | while (j - i > 1) { |
| 566 | | unsigned int m = (i+j)/2; |
| 567 | | if (ttisnil(&t->array[m - 1])) j = m; |
| 568 | | else i = m; |
| 569 | | } |
| 570 | | return i; |
| 571 | | } |
| 572 | | /* else must find a boundary in hash part */ |
| 573 | | else if (isdummy(t->node)) /* hash part is empty? */ |
| 574 | | return j; /* that is easy... */ |
| 575 | | else return unbound_search(t, j); |
| 561 | unsigned int j = t->sizearray; |
| 562 | if (j > 0 && ttisnil(&t->array[j - 1])) { |
| 563 | /* there is a boundary in the array part: (binary) search for it */ |
| 564 | unsigned int i = 0; |
| 565 | while (j - i > 1) { |
| 566 | unsigned int m = (i+j)/2; |
| 567 | if (ttisnil(&t->array[m - 1])) j = m; |
| 568 | else i = m; |
| 569 | } |
| 570 | return i; |
| 571 | } |
| 572 | /* else must find a boundary in hash part */ |
| 573 | else if (isdummy(t->node)) /* hash part is empty? */ |
| 574 | return j; /* that is easy... */ |
| 575 | else return unbound_search(t, j); |
| 576 | 576 | } |
| 577 | 577 | |
| 578 | 578 | |
| r30857 | r30858 | |
| 580 | 580 | #if defined(LUA_DEBUG) |
| 581 | 581 | |
| 582 | 582 | Node *luaH_mainposition (const Table *t, const TValue *key) { |
| 583 | | return mainposition(t, key); |
| 583 | return mainposition(t, key); |
| 584 | 584 | } |
| 585 | 585 | |
| 586 | 586 | int luaH_isdummy (Node *n) { return isdummy(n); } |
trunk/src/lib/lua/llex.c
| r30857 | r30858 | |
| 1 | 1 | /* |
| 2 | | ** $Id: llex.c,v 2.63 2013/03/16 21:10:18 roberto Exp $ |
| 2 | ** $Id: llex.c,v 2.63.1.2 2013/08/30 15:49:41 roberto Exp $ |
| 3 | 3 | ** Lexical Analyzer |
| 4 | 4 | ** See Copyright Notice in lua.h |
| 5 | 5 | */ |
| r30857 | r30858 | |
| 29 | 29 | |
| 30 | 30 | |
| 31 | 31 | |
| 32 | | #define currIsNewline(ls) (ls->current == '\n' || ls->current == '\r') |
| 32 | #define currIsNewline(ls) (ls->current == '\n' || ls->current == '\r') |
| 33 | 33 | |
| 34 | 34 | |
| 35 | 35 | /* ORDER RESERVED */ |
| 36 | 36 | static const char *const luaX_tokens [] = { |
| 37 | | "and", "break", "do", "else", "elseif", |
| 38 | | "end", "false", "for", "function", "goto", "if", |
| 39 | | "in", "local", "nil", "not", "or", "repeat", |
| 40 | | "return", "then", "true", "until", "while", |
| 41 | | "..", "...", "==", ">=", "<=", "~=", "::", "<eof>", |
| 42 | | "<number>", "<name>", "<string>" |
| 37 | "and", "break", "do", "else", "elseif", |
| 38 | "end", "false", "for", "function", "goto", "if", |
| 39 | "in", "local", "nil", "not", "or", "repeat", |
| 40 | "return", "then", "true", "until", "while", |
| 41 | "..", "...", "==", ">=", "<=", "~=", "::", "<eof>", |
| 42 | "<number>", "<name>", "<string>" |
| 43 | 43 | }; |
| 44 | 44 | |
| 45 | 45 | |
| r30857 | r30858 | |
| 50 | 50 | |
| 51 | 51 | |
| 52 | 52 | static void save (LexState *ls, int c) { |
| 53 | | Mbuffer *b = ls->buff; |
| 54 | | if (luaZ_bufflen(b) + 1 > luaZ_sizebuffer(b)) { |
| 55 | | size_t newsize; |
| 56 | | if (luaZ_sizebuffer(b) >= MAX_SIZET/2) |
| 57 | | lexerror(ls, "lexical element too long", 0); |
| 58 | | newsize = luaZ_sizebuffer(b) * 2; |
| 59 | | luaZ_resizebuffer(ls->L, b, newsize); |
| 60 | | } |
| 61 | | b->buffer[luaZ_bufflen(b)++] = cast(char, c); |
| 53 | Mbuffer *b = ls->buff; |
| 54 | if (luaZ_bufflen(b) + 1 > luaZ_sizebuffer(b)) { |
| 55 | size_t newsize; |
| 56 | if (luaZ_sizebuffer(b) >= MAX_SIZET/2) |
| 57 | lexerror(ls, "lexical element too long", 0); |
| 58 | newsize = luaZ_sizebuffer(b) * 2; |
| 59 | luaZ_resizebuffer(ls->L, b, newsize); |
| 60 | } |
| 61 | b->buffer[luaZ_bufflen(b)++] = cast(char, c); |
| 62 | 62 | } |
| 63 | 63 | |
| 64 | 64 | |
| 65 | 65 | void luaX_init (lua_State *L) { |
| 66 | | int i; |
| 67 | | for (i=0; i<NUM_RESERVED; i++) { |
| 68 | | TString *ts = luaS_new(L, luaX_tokens[i]); |
| 69 | | luaS_fix(ts); /* reserved words are never collected */ |
| 70 | | ts->tsv.extra = cast_byte(i+1); /* reserved word */ |
| 71 | | } |
| 66 | int i; |
| 67 | for (i=0; i<NUM_RESERVED; i++) { |
| 68 | TString *ts = luaS_new(L, luaX_tokens[i]); |
| 69 | luaS_fix(ts); /* reserved words are never collected */ |
| 70 | ts->tsv.extra = cast_byte(i+1); /* reserved word */ |
| 71 | } |
| 72 | 72 | } |
| 73 | 73 | |
| 74 | 74 | |
| 75 | 75 | const char *luaX_token2str (LexState *ls, int token) { |
| 76 | | if (token < FIRST_RESERVED) { /* single-byte symbols? */ |
| 77 | | lua_assert(token == cast(unsigned char, token)); |
| 78 | | return (lisprint(token)) ? luaO_pushfstring(ls->L, LUA_QL("%c"), token) : |
| 79 | | luaO_pushfstring(ls->L, "char(%d)", token); |
| 80 | | } |
| 81 | | else { |
| 82 | | const char *s = luaX_tokens[token - FIRST_RESERVED]; |
| 83 | | if (token < TK_EOS) /* fixed format (symbols and reserved words)? */ |
| 84 | | return luaO_pushfstring(ls->L, LUA_QS, s); |
| 85 | | else /* names, strings, and numerals */ |
| 86 | | return s; |
| 87 | | } |
| 76 | if (token < FIRST_RESERVED) { /* single-byte symbols? */ |
| 77 | lua_assert(token == cast(unsigned char, token)); |
| 78 | return (lisprint(token)) ? luaO_pushfstring(ls->L, LUA_QL("%c"), token) : |
| 79 | luaO_pushfstring(ls->L, "char(%d)", token); |
| 80 | } |
| 81 | else { |
| 82 | const char *s = luaX_tokens[token - FIRST_RESERVED]; |
| 83 | if (token < TK_EOS) /* fixed format (symbols and reserved words)? */ |
| 84 | return luaO_pushfstring(ls->L, LUA_QS, s); |
| 85 | else /* names, strings, and numerals */ |
| 86 | return s; |
| 87 | } |
| 88 | 88 | } |
| 89 | 89 | |
| 90 | 90 | |
| 91 | 91 | static const char *txtToken (LexState *ls, int token) { |
| 92 | | switch (token) { |
| 93 | | case TK_NAME: |
| 94 | | case TK_STRING: |
| 95 | | case TK_NUMBER: |
| 96 | | save(ls, '\0'); |
| 97 | | return luaO_pushfstring(ls->L, LUA_QS, luaZ_buffer(ls->buff)); |
| 98 | | default: |
| 99 | | return luaX_token2str(ls, token); |
| 100 | | } |
| 92 | switch (token) { |
| 93 | case TK_NAME: |
| 94 | case TK_STRING: |
| 95 | case TK_NUMBER: |
| 96 | save(ls, '\0'); |
| 97 | return luaO_pushfstring(ls->L, LUA_QS, luaZ_buffer(ls->buff)); |
| 98 | default: |
| 99 | return luaX_token2str(ls, token); |
| 100 | } |
| 101 | 101 | } |
| 102 | 102 | |
| 103 | 103 | |
| 104 | 104 | static l_noret lexerror (LexState *ls, const char *msg, int token) { |
| 105 | | char buff[LUA_IDSIZE]; |
| 106 | | luaO_chunkid(buff, getstr(ls->source), LUA_IDSIZE); |
| 107 | | msg = luaO_pushfstring(ls->L, "%s:%d: %s", buff, ls->linenumber, msg); |
| 108 | | if (token) |
| 109 | | luaO_pushfstring(ls->L, "%s near %s", msg, txtToken(ls, token)); |
| 110 | | luaD_throw(ls->L, LUA_ERRSYNTAX); |
| 105 | char buff[LUA_IDSIZE]; |
| 106 | luaO_chunkid(buff, getstr(ls->source), LUA_IDSIZE); |
| 107 | msg = luaO_pushfstring(ls->L, "%s:%d: %s", buff, ls->linenumber, msg); |
| 108 | if (token) |
| 109 | luaO_pushfstring(ls->L, "%s near %s", msg, txtToken(ls, token)); |
| 110 | luaD_throw(ls->L, LUA_ERRSYNTAX); |
| 111 | 111 | } |
| 112 | 112 | |
| 113 | 113 | |
| 114 | 114 | l_noret luaX_syntaxerror (LexState *ls, const char *msg) { |
| 115 | | lexerror(ls, msg, ls->t.token); |
| 115 | lexerror(ls, msg, ls->t.token); |
| 116 | 116 | } |
| 117 | 117 | |
| 118 | 118 | |
| r30857 | r30858 | |
| 122 | 122 | ** (by that time it should be anchored in function's prototype) |
| 123 | 123 | */ |
| 124 | 124 | TString *luaX_newstring (LexState *ls, const char *str, size_t l) { |
| 125 | | lua_State *L = ls->L; |
| 126 | | TValue *o; /* entry for `str' */ |
| 127 | | TString *ts = luaS_newlstr(L, str, l); /* create new string */ |
| 128 | | setsvalue2s(L, L->top++, ts); /* temporarily anchor it in stack */ |
| 129 | | o = luaH_set(L, ls->fs->h, L->top - 1); |
| 130 | | if (ttisnil(o)) { /* not in use yet? (see 'addK') */ |
| 131 | | /* boolean value does not need GC barrier; |
| 132 | | table has no metatable, so it does not need to invalidate cache */ |
| 133 | | setbvalue(o, 1); /* t[string] = true */ |
| 134 | | luaC_checkGC(L); |
| 135 | | } |
| 136 | | L->top--; /* remove string from stack */ |
| 137 | | return ts; |
| 125 | lua_State *L = ls->L; |
| 126 | TValue *o; /* entry for `str' */ |
| 127 | TString *ts = luaS_newlstr(L, str, l); /* create new string */ |
| 128 | setsvalue2s(L, L->top++, ts); /* temporarily anchor it in stack */ |
| 129 | o = luaH_set(L, ls->fs->h, L->top - 1); |
| 130 | if (ttisnil(o)) { /* not in use yet? (see 'addK') */ |
| 131 | /* boolean value does not need GC barrier; |
| 132 | table has no metatable, so it does not need to invalidate cache */ |
| 133 | setbvalue(o, 1); /* t[string] = true */ |
| 134 | luaC_checkGC(L); |
| 135 | } |
| 136 | else { /* string already present */ |
| 137 | ts = rawtsvalue(keyfromval(o)); /* re-use value previously stored */ |
| 138 | } |
| 139 | L->top--; /* remove string from stack */ |
| 140 | return ts; |
| 138 | 141 | } |
| 139 | 142 | |
| 140 | 143 | |
| r30857 | r30858 | |
| 143 | 146 | ** \n, \r, \n\r, or \r\n) |
| 144 | 147 | */ |
| 145 | 148 | static void inclinenumber (LexState *ls) { |
| 146 | | int old = ls->current; |
| 147 | | lua_assert(currIsNewline(ls)); |
| 148 | | next(ls); /* skip `\n' or `\r' */ |
| 149 | | if (currIsNewline(ls) && ls->current != old) |
| 150 | | next(ls); /* skip `\n\r' or `\r\n' */ |
| 151 | | if (++ls->linenumber >= MAX_INT) |
| 152 | | luaX_syntaxerror(ls, "chunk has too many lines"); |
| 149 | int old = ls->current; |
| 150 | lua_assert(currIsNewline(ls)); |
| 151 | next(ls); /* skip `\n' or `\r' */ |
| 152 | if (currIsNewline(ls) && ls->current != old) |
| 153 | next(ls); /* skip `\n\r' or `\r\n' */ |
| 154 | if (++ls->linenumber >= MAX_INT) |
| 155 | luaX_syntaxerror(ls, "chunk has too many lines"); |
| 153 | 156 | } |
| 154 | 157 | |
| 155 | 158 | |
| 156 | 159 | void luaX_setinput (lua_State *L, LexState *ls, ZIO *z, TString *source, |
| 157 | | int firstchar) { |
| 158 | | ls->decpoint = '.'; |
| 159 | | ls->L = L; |
| 160 | | ls->current = firstchar; |
| 161 | | ls->lookahead.token = TK_EOS; /* no look-ahead token */ |
| 162 | | ls->z = z; |
| 163 | | ls->fs = NULL; |
| 164 | | ls->linenumber = 1; |
| 165 | | ls->lastline = 1; |
| 166 | | ls->source = source; |
| 167 | | ls->envn = luaS_new(L, LUA_ENV); /* create env name */ |
| 168 | | luaS_fix(ls->envn); /* never collect this name */ |
| 169 | | luaZ_resizebuffer(ls->L, ls->buff, LUA_MINBUFFER); /* initialize buffer */ |
| 160 | int firstchar) { |
| 161 | ls->decpoint = '.'; |
| 162 | ls->L = L; |
| 163 | ls->current = firstchar; |
| 164 | ls->lookahead.token = TK_EOS; /* no look-ahead token */ |
| 165 | ls->z = z; |
| 166 | ls->fs = NULL; |
| 167 | ls->linenumber = 1; |
| 168 | ls->lastline = 1; |
| 169 | ls->source = source; |
| 170 | ls->envn = luaS_new(L, LUA_ENV); /* create env name */ |
| 171 | luaS_fix(ls->envn); /* never collect this name */ |
| 172 | luaZ_resizebuffer(ls->L, ls->buff, LUA_MINBUFFER); /* initialize buffer */ |
| 170 | 173 | } |
| 171 | 174 | |
| 172 | 175 | |
| r30857 | r30858 | |
| 180 | 183 | |
| 181 | 184 | |
| 182 | 185 | static int check_next (LexState *ls, const char *set) { |
| 183 | | if (ls->current == '\0' || !strchr(set, ls->current)) |
| 184 | | return 0; |
| 185 | | save_and_next(ls); |
| 186 | | return 1; |
| 186 | if (ls->current == '\0' || !strchr(set, ls->current)) |
| 187 | return 0; |
| 188 | save_and_next(ls); |
| 189 | return 1; |
| 187 | 190 | } |
| 188 | 191 | |
| 189 | 192 | |
| r30857 | r30858 | |
| 191 | 194 | ** change all characters 'from' in buffer to 'to' |
| 192 | 195 | */ |
| 193 | 196 | static void buffreplace (LexState *ls, char from, char to) { |
| 194 | | size_t n = luaZ_bufflen(ls->buff); |
| 195 | | char *p = luaZ_buffer(ls->buff); |
| 196 | | while (n--) |
| 197 | | if (p[n] == from) p[n] = to; |
| 197 | size_t n = luaZ_bufflen(ls->buff); |
| 198 | char *p = luaZ_buffer(ls->buff); |
| 199 | while (n--) |
| 200 | if (p[n] == from) p[n] = to; |
| 198 | 201 | } |
| 199 | 202 | |
| 200 | 203 | |
| 201 | 204 | #if !defined(getlocaledecpoint) |
| 202 | | #define getlocaledecpoint() (localeconv()->decimal_point[0]) |
| 205 | #define getlocaledecpoint() (localeconv()->decimal_point[0]) |
| 203 | 206 | #endif |
| 204 | 207 | |
| 205 | 208 | |
| 206 | | #define buff2d(b,e) luaO_str2d(luaZ_buffer(b), luaZ_bufflen(b) - 1, e) |
| 209 | #define buff2d(b,e) luaO_str2d(luaZ_buffer(b), luaZ_bufflen(b) - 1, e) |
| 207 | 210 | |
| 208 | 211 | /* |
| 209 | 212 | ** in case of format error, try to change decimal point separator to |
| 210 | 213 | ** the one defined in the current locale and check again |
| 211 | 214 | */ |
| 212 | 215 | static void trydecpoint (LexState *ls, SemInfo *seminfo) { |
| 213 | | char old = ls->decpoint; |
| 214 | | ls->decpoint = getlocaledecpoint(); |
| 215 | | buffreplace(ls, old, ls->decpoint); /* try new decimal separator */ |
| 216 | | if (!buff2d(ls->buff, &seminfo->r)) { |
| 217 | | /* format error with correct decimal point: no more options */ |
| 218 | | buffreplace(ls, ls->decpoint, '.'); /* undo change (for error message) */ |
| 219 | | lexerror(ls, "malformed number", TK_NUMBER); |
| 220 | | } |
| 216 | char old = ls->decpoint; |
| 217 | ls->decpoint = getlocaledecpoint(); |
| 218 | buffreplace(ls, old, ls->decpoint); /* try new decimal separator */ |
| 219 | if (!buff2d(ls->buff, &seminfo->r)) { |
| 220 | /* format error with correct decimal point: no more options */ |
| 221 | buffreplace(ls, ls->decpoint, '.'); /* undo change (for error message) */ |
| 222 | lexerror(ls, "malformed number", TK_NUMBER); |
| 223 | } |
| 221 | 224 | } |
| 222 | 225 | |
| 223 | 226 | |
| r30857 | r30858 | |
| 227 | 230 | ** will reject ill-formed numerals. |
| 228 | 231 | */ |
| 229 | 232 | static void read_numeral (LexState *ls, SemInfo *seminfo) { |
| 230 | | const char *expo = "Ee"; |
| 231 | | int first = ls->current; |
| 232 | | lua_assert(lisdigit(ls->current)); |
| 233 | | save_and_next(ls); |
| 234 | | if (first == '0' && check_next(ls, "Xx")) /* hexadecimal? */ |
| 235 | | expo = "Pp"; |
| 236 | | for (;;) { |
| 237 | | if (check_next(ls, expo)) /* exponent part? */ |
| 238 | | check_next(ls, "+-"); /* optional exponent sign */ |
| 239 | | if (lisxdigit(ls->current) || ls->current == '.') |
| 240 | | save_and_next(ls); |
| 241 | | else break; |
| 242 | | } |
| 243 | | save(ls, '\0'); |
| 244 | | buffreplace(ls, '.', ls->decpoint); /* follow locale for decimal point */ |
| 245 | | if (!buff2d(ls->buff, &seminfo->r)) /* format error? */ |
| 246 | | trydecpoint(ls, seminfo); /* try to update decimal point separator */ |
| 233 | const char *expo = "Ee"; |
| 234 | int first = ls->current; |
| 235 | lua_assert(lisdigit(ls->current)); |
| 236 | save_and_next(ls); |
| 237 | if (first == '0' && check_next(ls, "Xx")) /* hexadecimal? */ |
| 238 | expo = "Pp"; |
| 239 | for (;;) { |
| 240 | if (check_next(ls, expo)) /* exponent part? */ |
| 241 | check_next(ls, "+-"); /* optional exponent sign */ |
| 242 | if (lisxdigit(ls->current) || ls->current == '.') |
| 243 | save_and_next(ls); |
| 244 | else break; |
| 245 | } |
| 246 | save(ls, '\0'); |
| 247 | buffreplace(ls, '.', ls->decpoint); /* follow locale for decimal point */ |
| 248 | if (!buff2d(ls->buff, &seminfo->r)) /* format error? */ |
| 249 | trydecpoint(ls, seminfo); /* try to update decimal point separator */ |
| 247 | 250 | } |
| 248 | 251 | |
| 249 | 252 | |
| r30857 | r30858 | |
| 252 | 255 | ** -1 if sequence is malformed |
| 253 | 256 | */ |
| 254 | 257 | static int skip_sep (LexState *ls) { |
| 255 | | int count = 0; |
| 256 | | int s = ls->current; |
| 257 | | lua_assert(s == '[' || s == ']'); |
| 258 | | save_and_next(ls); |
| 259 | | while (ls->current == '=') { |
| 260 | | save_and_next(ls); |
| 261 | | count++; |
| 262 | | } |
| 263 | | return (ls->current == s) ? count : (-count) - 1; |
| 258 | int count = 0; |
| 259 | int s = ls->current; |
| 260 | lua_assert(s == '[' || s == ']'); |
| 261 | save_and_next(ls); |
| 262 | while (ls->current == '=') { |
| 263 | save_and_next(ls); |
| 264 | count++; |
| 265 | } |
| 266 | return (ls->current == s) ? count : (-count) - 1; |
| 264 | 267 | } |
| 265 | 268 | |
| 266 | 269 | |
| 267 | 270 | static void read_long_string (LexState *ls, SemInfo *seminfo, int sep) { |
| 268 | | save_and_next(ls); /* skip 2nd `[' */ |
| 269 | | if (currIsNewline(ls)) /* string starts with a newline? */ |
| 270 | | inclinenumber(ls); /* skip it */ |
| 271 | | for (;;) { |
| 272 | | switch (ls->current) { |
| 273 | | case EOZ: |
| 274 | | lexerror(ls, (seminfo) ? "unfinished long string" : |
| 275 | | "unfinished long comment", TK_EOS); |
| 276 | | break; /* to avoid warnings */ |
| 277 | | case ']': { |
| 278 | | if (skip_sep(ls) == sep) { |
| 279 | | save_and_next(ls); /* skip 2nd `]' */ |
| 280 | | goto endloop; |
| 281 | | } |
| 282 | | break; |
| 283 | | } |
| 284 | | case '\n': case '\r': { |
| 285 | | save(ls, '\n'); |
| 286 | | inclinenumber(ls); |
| 287 | | if (!seminfo) luaZ_resetbuffer(ls->buff); /* avoid wasting space */ |
| 288 | | break; |
| 289 | | } |
| 290 | | default: { |
| 291 | | if (seminfo) save_and_next(ls); |
| 292 | | else next(ls); |
| 293 | | } |
| 294 | | } |
| 295 | | } endloop: |
| 296 | | if (seminfo) |
| 297 | | seminfo->ts = luaX_newstring(ls, luaZ_buffer(ls->buff) + (2 + sep), |
| 298 | | luaZ_bufflen(ls->buff) - 2*(2 + sep)); |
| 271 | save_and_next(ls); /* skip 2nd `[' */ |
| 272 | if (currIsNewline(ls)) /* string starts with a newline? */ |
| 273 | inclinenumber(ls); /* skip it */ |
| 274 | for (;;) { |
| 275 | switch (ls->current) { |
| 276 | case EOZ: |
| 277 | lexerror(ls, (seminfo) ? "unfinished long string" : |
| 278 | "unfinished long comment", TK_EOS); |
| 279 | break; /* to avoid warnings */ |
| 280 | case ']': { |
| 281 | if (skip_sep(ls) == sep) { |
| 282 | save_and_next(ls); /* skip 2nd `]' */ |
| 283 | goto endloop; |
| 284 | } |
| 285 | break; |
| 286 | } |
| 287 | case '\n': case '\r': { |
| 288 | save(ls, '\n'); |
| 289 | inclinenumber(ls); |
| 290 | if (!seminfo) luaZ_resetbuffer(ls->buff); /* avoid wasting space */ |
| 291 | break; |
| 292 | } |
| 293 | default: { |
| 294 | if (seminfo) save_and_next(ls); |
| 295 | else next(ls); |
| 296 | } |
| 297 | } |
| 298 | } endloop: |
| 299 | if (seminfo) |
| 300 | seminfo->ts = luaX_newstring(ls, luaZ_buffer(ls->buff) + (2 + sep), |
| 301 | luaZ_bufflen(ls->buff) - 2*(2 + sep)); |
| 299 | 302 | } |
| 300 | 303 | |
| 301 | 304 | |
| 302 | 305 | static void escerror (LexState *ls, int *c, int n, const char *msg) { |
| 303 | | int i; |
| 304 | | luaZ_resetbuffer(ls->buff); /* prepare error message */ |
| 305 | | save(ls, '\\'); |
| 306 | | for (i = 0; i < n && c[i] != EOZ; i++) |
| 307 | | save(ls, c[i]); |
| 308 | | lexerror(ls, msg, TK_STRING); |
| 306 | int i; |
| 307 | luaZ_resetbuffer(ls->buff); /* prepare error message */ |
| 308 | save(ls, '\\'); |
| 309 | for (i = 0; i < n && c[i] != EOZ; i++) |
| 310 | save(ls, c[i]); |
| 311 | lexerror(ls, msg, TK_STRING); |
| 309 | 312 | } |
| 310 | 313 | |
| 311 | 314 | |
| 312 | 315 | static int readhexaesc (LexState *ls) { |
| 313 | | int c[3], i; /* keep input for error message */ |
| 314 | | int r = 0; /* result accumulator */ |
| 315 | | c[0] = 'x'; /* for error message */ |
| 316 | | for (i = 1; i < 3; i++) { /* read two hexadecimal digits */ |
| 317 | | c[i] = next(ls); |
| 318 | | if (!lisxdigit(c[i])) |
| 319 | | escerror(ls, c, i + 1, "hexadecimal digit expected"); |
| 320 | | r = (r << 4) + luaO_hexavalue(c[i]); |
| 321 | | } |
| 322 | | return r; |
| 316 | int c[3], i; /* keep input for error message */ |
| 317 | int r = 0; /* result accumulator */ |
| 318 | c[0] = 'x'; /* for error message */ |
| 319 | for (i = 1; i < 3; i++) { /* read two hexadecimal digits */ |
| 320 | c[i] = next(ls); |
| 321 | if (!lisxdigit(c[i])) |
| 322 | escerror(ls, c, i + 1, "hexadecimal digit expected"); |
| 323 | r = (r << 4) + luaO_hexavalue(c[i]); |
| 324 | } |
| 325 | return r; |
| 323 | 326 | } |
| 324 | 327 | |
| 325 | 328 | |
| 326 | 329 | static int readdecesc (LexState *ls) { |
| 327 | | int c[3], i; |
| 328 | | int r = 0; /* result accumulator */ |
| 329 | | for (i = 0; i < 3 && lisdigit(ls->current); i++) { /* read up to 3 digits */ |
| 330 | | c[i] = ls->current; |
| 331 | | r = 10*r + c[i] - '0'; |
| 332 | | next(ls); |
| 333 | | } |
| 334 | | if (r > UCHAR_MAX) |
| 335 | | escerror(ls, c, i, "decimal escape too large"); |
| 336 | | return r; |
| 330 | int c[3], i; |
| 331 | int r = 0; /* result accumulator */ |
| 332 | for (i = 0; i < 3 && lisdigit(ls->current); i++) { /* read up to 3 digits */ |
| 333 | c[i] = ls->current; |
| 334 | r = 10*r + c[i] - '0'; |
| 335 | next(ls); |
| 336 | } |
| 337 | if (r > UCHAR_MAX) |
| 338 | escerror(ls, c, i, "decimal escape too large"); |
| 339 | return r; |
| 337 | 340 | } |
| 338 | 341 | |
| 339 | 342 | |
| 340 | 343 | static void read_string (LexState *ls, int del, SemInfo *seminfo) { |
| 341 | | save_and_next(ls); /* keep delimiter (for error messages) */ |
| 342 | | while (ls->current != del) { |
| 343 | | switch (ls->current) { |
| 344 | | case EOZ: |
| 345 | | lexerror(ls, "unfinished string", TK_EOS); |
| 346 | | break; /* to avoid warnings */ |
| 347 | | case '\n': |
| 348 | | case '\r': |
| 349 | | lexerror(ls, "unfinished string", TK_STRING); |
| 350 | | break; /* to avoid warnings */ |
| 351 | | case '\\': { /* escape sequences */ |
| 352 | | int c; /* final character to be saved */ |
| 353 | | next(ls); /* do not save the `\' */ |
| 354 | | switch (ls->current) { |
| 355 | | case 'a': c = '\a'; goto read_save; |
| 356 | | case 'b': c = '\b'; goto read_save; |
| 357 | | case 'f': c = '\f'; goto read_save; |
| 358 | | case 'n': c = '\n'; goto read_save; |
| 359 | | case 'r': c = '\r'; goto read_save; |
| 360 | | case 't': c = '\t'; goto read_save; |
| 361 | | case 'v': c = '\v'; goto read_save; |
| 362 | | case 'x': c = readhexaesc(ls); goto read_save; |
| 363 | | case '\n': case '\r': |
| 364 | | inclinenumber(ls); c = '\n'; goto only_save; |
| 365 | | case '\\': case '\"': case '\'': |
| 366 | | c = ls->current; goto read_save; |
| 367 | | case EOZ: goto no_save; /* will raise an error next loop */ |
| 368 | | case 'z': { /* zap following span of spaces */ |
| 369 | | next(ls); /* skip the 'z' */ |
| 370 | | while (lisspace(ls->current)) { |
| 371 | | if (currIsNewline(ls)) inclinenumber(ls); |
| 372 | | else next(ls); |
| 373 | | } |
| 374 | | goto no_save; |
| 375 | | } |
| 376 | | default: { |
| 377 | | if (!lisdigit(ls->current)) |
| 378 | | escerror(ls, &ls->current, 1, "invalid escape sequence"); |
| 379 | | /* digital escape \ddd */ |
| 380 | | c = readdecesc(ls); |
| 381 | | goto only_save; |
| 382 | | } |
| 383 | | } |
| 384 | | read_save: next(ls); /* read next character */ |
| 385 | | only_save: save(ls, c); /* save 'c' */ |
| 386 | | no_save: break; |
| 387 | | } |
| 388 | | default: |
| 389 | | save_and_next(ls); |
| 390 | | } |
| 391 | | } |
| 392 | | save_and_next(ls); /* skip delimiter */ |
| 393 | | seminfo->ts = luaX_newstring(ls, luaZ_buffer(ls->buff) + 1, |
| 394 | | luaZ_bufflen(ls->buff) - 2); |
| 344 | save_and_next(ls); /* keep delimiter (for error messages) */ |
| 345 | while (ls->current != del) { |
| 346 | switch (ls->current) { |
| 347 | case EOZ: |
| 348 | lexerror(ls, "unfinished string", TK_EOS); |
| 349 | break; /* to avoid warnings */ |
| 350 | case '\n': |
| 351 | case '\r': |
| 352 | lexerror(ls, "unfinished string", TK_STRING); |
| 353 | break; /* to avoid warnings */ |
| 354 | case '\\': { /* escape sequences */ |
| 355 | int c; /* final character to be saved */ |
| 356 | next(ls); /* do not save the `\' */ |
| 357 | switch (ls->current) { |
| 358 | case 'a': c = '\a'; goto read_save; |
| 359 | case 'b': c = '\b'; goto read_save; |
| 360 | case 'f': c = '\f'; goto read_save; |
| 361 | case 'n': c = '\n'; goto read_save; |
| 362 | case 'r': c = '\r'; goto read_save; |
| 363 | case 't': c = '\t'; goto read_save; |
| 364 | case 'v': c = '\v'; goto read_save; |
| 365 | case 'x': c = readhexaesc(ls); goto read_save; |
| 366 | case '\n': case '\r': |
| 367 | inclinenumber(ls); c = '\n'; goto only_save; |
| 368 | case '\\': case '\"': case '\'': |
| 369 | c = ls->current; goto read_save; |
| 370 | case EOZ: goto no_save; /* will raise an error next loop */ |
| 371 | case 'z': { /* zap following span of spaces */ |
| 372 | next(ls); /* skip the 'z' */ |
| 373 | while (lisspace(ls->current)) { |
| 374 | if (currIsNewline(ls)) inclinenumber(ls); |
| 375 | else next(ls); |
| 376 | } |
| 377 | goto no_save; |
| 378 | } |
| 379 | default: { |
| 380 | if (!lisdigit(ls->current)) |
| 381 | escerror(ls, &ls->current, 1, "invalid escape sequence"); |
| 382 | /* digital escape \ddd */ |
| 383 | c = readdecesc(ls); |
| 384 | goto only_save; |
| 385 | } |
| 386 | } |
| 387 | read_save: next(ls); /* read next character */ |
| 388 | only_save: save(ls, c); /* save 'c' */ |
| 389 | no_save: break; |
| 390 | } |
| 391 | default: |
| 392 | save_and_next(ls); |
| 393 | } |
| 394 | } |
| 395 | save_and_next(ls); /* skip delimiter */ |
| 396 | seminfo->ts = luaX_newstring(ls, luaZ_buffer(ls->buff) + 1, |
| 397 | luaZ_bufflen(ls->buff) - 2); |
| 395 | 398 | } |
| 396 | 399 | |
| 397 | 400 | |
| 398 | 401 | static int llex (LexState *ls, SemInfo *seminfo) { |
| 399 | | luaZ_resetbuffer(ls->buff); |
| 400 | | for (;;) { |
| 401 | | switch (ls->current) { |
| 402 | | case '\n': case '\r': { /* line breaks */ |
| 403 | | inclinenumber(ls); |
| 404 | | break; |
| 405 | | } |
| 406 | | case ' ': case '\f': case '\t': case '\v': { /* spaces */ |
| 407 | | next(ls); |
| 408 | | break; |
| 409 | | } |
| 410 | | case '-': { /* '-' or '--' (comment) */ |
| 411 | | next(ls); |
| 412 | | if (ls->current != '-') return '-'; |
| 413 | | /* else is a comment */ |
| 414 | | next(ls); |
| 415 | | if (ls->current == '[') { /* long comment? */ |
| 416 | | int sep = skip_sep(ls); |
| 417 | | luaZ_resetbuffer(ls->buff); /* `skip_sep' may dirty the buffer */ |
| 418 | | if (sep >= 0) { |
| 419 | | read_long_string(ls, NULL, sep); /* skip long comment */ |
| 420 | | luaZ_resetbuffer(ls->buff); /* previous call may dirty the buff. */ |
| 421 | | break; |
| 422 | | } |
| 423 | | } |
| 424 | | /* else short comment */ |
| 425 | | while (!currIsNewline(ls) && ls->current != EOZ) |
| 426 | | next(ls); /* skip until end of line (or end of file) */ |
| 427 | | break; |
| 428 | | } |
| 429 | | case '[': { /* long string or simply '[' */ |
| 430 | | int sep = skip_sep(ls); |
| 431 | | if (sep >= 0) { |
| 432 | | read_long_string(ls, seminfo, sep); |
| 433 | | return TK_STRING; |
| 434 | | } |
| 435 | | else if (sep == -1) return '['; |
| 436 | | else lexerror(ls, "invalid long string delimiter", TK_STRING); |
| 437 | | } |
| 438 | | case '=': { |
| 439 | | next(ls); |
| 440 | | if (ls->current != '=') return '='; |
| 441 | | else { next(ls); return TK_EQ; } |
| 442 | | } |
| 443 | | case '<': { |
| 444 | | next(ls); |
| 445 | | if (ls->current != '=') return '<'; |
| 446 | | else { next(ls); return TK_LE; } |
| 447 | | } |
| 448 | | case '>': { |
| 449 | | next(ls); |
| 450 | | if (ls->current != '=') return '>'; |
| 451 | | else { next(ls); return TK_GE; } |
| 452 | | } |
| 453 | | case '~': { |
| 454 | | next(ls); |
| 455 | | if (ls->current != '=') return '~'; |
| 456 | | else { next(ls); return TK_NE; } |
| 457 | | } |
| 458 | | case ':': { |
| 459 | | next(ls); |
| 460 | | if (ls->current != ':') return ':'; |
| 461 | | else { next(ls); return TK_DBCOLON; } |
| 462 | | } |
| 463 | | case '"': case '\'': { /* short literal strings */ |
| 464 | | read_string(ls, ls->current, seminfo); |
| 465 | | return TK_STRING; |
| 466 | | } |
| 467 | | case '.': { /* '.', '..', '...', or number */ |
| 468 | | save_and_next(ls); |
| 469 | | if (check_next(ls, ".")) { |
| 470 | | if (check_next(ls, ".")) |
| 471 | | return TK_DOTS; /* '...' */ |
| 472 | | else return TK_CONCAT; /* '..' */ |
| 473 | | } |
| 474 | | else if (!lisdigit(ls->current)) return '.'; |
| 475 | | /* else go through */ |
| 476 | | } |
| 477 | | case '0': case '1': case '2': case '3': case '4': |
| 478 | | case '5': case '6': case '7': case '8': case '9': { |
| 479 | | read_numeral(ls, seminfo); |
| 480 | | return TK_NUMBER; |
| 481 | | } |
| 482 | | case EOZ: { |
| 483 | | return TK_EOS; |
| 484 | | } |
| 485 | | default: { |
| 486 | | if (lislalpha(ls->current)) { /* identifier or reserved word? */ |
| 487 | | TString *ts; |
| 488 | | do { |
| 489 | | save_and_next(ls); |
| 490 | | } while (lislalnum(ls->current)); |
| 491 | | ts = luaX_newstring(ls, luaZ_buffer(ls->buff), |
| 492 | | luaZ_bufflen(ls->buff)); |
| 493 | | seminfo->ts = ts; |
| 494 | | if (isreserved(ts)) /* reserved word? */ |
| 495 | | return ts->tsv.extra - 1 + FIRST_RESERVED; |
| 496 | | else { |
| 497 | | return TK_NAME; |
| 498 | | } |
| 499 | | } |
| 500 | | else { /* single-char tokens (+ - / ...) */ |
| 501 | | int c = ls->current; |
| 502 | | next(ls); |
| 503 | | return c; |
| 504 | | } |
| 505 | | } |
| 506 | | } |
| 507 | | } |
| 402 | luaZ_resetbuffer(ls->buff); |
| 403 | for (;;) { |
| 404 | switch (ls->current) { |
| 405 | case '\n': case '\r': { /* line breaks */ |
| 406 | inclinenumber(ls); |
| 407 | break; |
| 408 | } |
| 409 | case ' ': case '\f': case '\t': case '\v': { /* spaces */ |
| 410 | next(ls); |
| 411 | break; |
| 412 | } |
| 413 | case '-': { /* '-' or '--' (comment) */ |
| 414 | next(ls); |
| 415 | if (ls->current != '-') return '-'; |
| 416 | /* else is a comment */ |
| 417 | next(ls); |
| 418 | if (ls->current == '[') { /* long comment? */ |
| 419 | int sep = skip_sep(ls); |
| 420 | luaZ_resetbuffer(ls->buff); /* `skip_sep' may dirty the buffer */ |
| 421 | if (sep >= 0) { |
| 422 | read_long_string(ls, NULL, sep); /* skip long comment */ |
| 423 | luaZ_resetbuffer(ls->buff); /* previous call may dirty the buff. */ |
| 424 | break; |
| 425 | } |
| 426 | } |
| 427 | /* else short comment */ |
| 428 | while (!currIsNewline(ls) && ls->current != EOZ) |
| 429 | next(ls); /* skip until end of line (or end of file) */ |
| 430 | break; |
| 431 | } |
| 432 | case '[': { /* long string or simply '[' */ |
| 433 | int sep = skip_sep(ls); |
| 434 | if (sep >= 0) { |
| 435 | read_long_string(ls, seminfo, sep); |
| 436 | return TK_STRING; |
| 437 | } |
| 438 | else if (sep == -1) return '['; |
| 439 | else lexerror(ls, "invalid long string delimiter", TK_STRING); |
| 440 | } |
| 441 | case '=': { |
| 442 | next(ls); |
| 443 | if (ls->current != '=') return '='; |
| 444 | else { next(ls); return TK_EQ; } |
| 445 | } |
| 446 | case '<': { |
| 447 | next(ls); |
| 448 | if (ls->current != '=') return '<'; |
| 449 | else { next(ls); return TK_LE; } |
| 450 | } |
| 451 | case '>': { |
| 452 | next(ls); |
| 453 | if (ls->current != '=') return '>'; |
| 454 | else { next(ls); return TK_GE; } |
| 455 | } |
| 456 | case '~': { |
| 457 | next(ls); |
| 458 | if (ls->current != '=') return '~'; |
| 459 | else { next(ls); return TK_NE; } |
| 460 | } |
| 461 | case ':': { |
| 462 | next(ls); |
| 463 | if (ls->current != ':') return ':'; |
| 464 | else { next(ls); return TK_DBCOLON; } |
| 465 | } |
| 466 | case '"': case '\'': { /* short literal strings */ |
| 467 | read_string(ls, ls->current, seminfo); |
| 468 | return TK_STRING; |
| 469 | } |
| 470 | case '.': { /* '.', '..', '...', or number */ |
| 471 | save_and_next(ls); |
| 472 | if (check_next(ls, ".")) { |
| 473 | if (check_next(ls, ".")) |
| 474 | return TK_DOTS; /* '...' */ |
| 475 | else return TK_CONCAT; /* '..' */ |
| 476 | } |
| 477 | else if (!lisdigit(ls->current)) return '.'; |
| 478 | /* else go through */ |
| 479 | } |
| 480 | case '0': case '1': case '2': case '3': case '4': |
| 481 | case '5': case '6': case '7': case '8': case '9': { |
| 482 | read_numeral(ls, seminfo); |
| 483 | return TK_NUMBER; |
| 484 | } |
| 485 | case EOZ: { |
| 486 | return TK_EOS; |
| 487 | } |
| 488 | default: { |
| 489 | if (lislalpha(ls->current)) { /* identifier or reserved word? */ |
| 490 | TString *ts; |
| 491 | do { |
| 492 | save_and_next(ls); |
| 493 | } while (lislalnum(ls->current)); |
| 494 | ts = luaX_newstring(ls, luaZ_buffer(ls->buff), |
| 495 | luaZ_bufflen(ls->buff)); |
| 496 | seminfo->ts = ts; |
| 497 | if (isreserved(ts)) /* reserved word? */ |
| 498 | return ts->tsv.extra - 1 + FIRST_RESERVED; |
| 499 | else { |
| 500 | return TK_NAME; |
| 501 | } |
| 502 | } |
| 503 | else { /* single-char tokens (+ - / ...) */ |
| 504 | int c = ls->current; |
| 505 | next(ls); |
| 506 | return c; |
| 507 | } |
| 508 | } |
| 509 | } |
| 510 | } |
| 508 | 511 | } |
| 509 | 512 | |
| 510 | 513 | |
| 511 | 514 | void luaX_next (LexState *ls) { |
| 512 | | ls->lastline = ls->linenumber; |
| 513 | | if (ls->lookahead.token != TK_EOS) { /* is there a look-ahead token? */ |
| 514 | | ls->t = ls->lookahead; /* use this one */ |
| 515 | | ls->lookahead.token = TK_EOS; /* and discharge it */ |
| 516 | | } |
| 517 | | else |
| 518 | | ls->t.token = llex(ls, &ls->t.seminfo); /* read next token */ |
| 515 | ls->lastline = ls->linenumber; |
| 516 | if (ls->lookahead.token != TK_EOS) { /* is there a look-ahead token? */ |
| 517 | ls->t = ls->lookahead; /* use this one */ |
| 518 | ls->lookahead.token = TK_EOS; /* and discharge it */ |
| 519 | } |
| 520 | else |
| 521 | ls->t.token = llex(ls, &ls->t.seminfo); /* read next token */ |
| 519 | 522 | } |
| 520 | 523 | |
| 521 | 524 | |
| 522 | 525 | int luaX_lookahead (LexState *ls) { |
| 523 | | lua_assert(ls->lookahead.token == TK_EOS); |
| 524 | | ls->lookahead.token = llex(ls, &ls->lookahead.seminfo); |
| 525 | | return ls->lookahead.token; |
| 526 | lua_assert(ls->lookahead.token == TK_EOS); |
| 527 | ls->lookahead.token = llex(ls, &ls->lookahead.seminfo); |
| 528 | return ls->lookahead.token; |
| 526 | 529 | } |
| 530 | |
trunk/src/lib/lua/lgc.c
| r30857 | r30858 | |
| 1 | 1 | /* |
| 2 | | ** $Id: lgc.c,v 2.140 2013/03/16 21:10:18 roberto Exp $ |
| 2 | ** $Id: lgc.c,v 2.140.1.2 2013/04/26 18:22:05 roberto Exp $ |
| 3 | 3 | ** Garbage Collector |
| 4 | 4 | ** See Copyright Notice in lua.h |
| 5 | 5 | */ |
| r30857 | r30858 | |
| 28 | 28 | ** cost of sweeping one element (the size of a small object divided |
| 29 | 29 | ** by some adjust for the sweep speed) |
| 30 | 30 | */ |
| 31 | | #define GCSWEEPCOST ((sizeof(TString) + 4) / 4) |
| 31 | #define GCSWEEPCOST ((sizeof(TString) + 4) / 4) |
| 32 | 32 | |
| 33 | 33 | /* maximum number of elements to sweep in each single step */ |
| 34 | | #define GCSWEEPMAX (cast_int((GCSTEPSIZE / GCSWEEPCOST) / 4)) |
| 34 | #define GCSWEEPMAX (cast_int((GCSTEPSIZE / GCSWEEPCOST) / 4)) |
| 35 | 35 | |
| 36 | 36 | /* maximum number of finalizers to call in each GC step */ |
| 37 | | #define GCFINALIZENUM 4 |
| 37 | #define GCFINALIZENUM 4 |
| 38 | 38 | |
| 39 | 39 | |
| 40 | 40 | /* |
| 41 | 41 | ** macro to adjust 'stepmul': 'stepmul' is actually used like |
| 42 | 42 | ** 'stepmul / STEPMULADJ' (value chosen by tests) |
| 43 | 43 | */ |
| 44 | | #define STEPMULADJ 200 |
| 44 | #define STEPMULADJ 200 |
| 45 | 45 | |
| 46 | 46 | |
| 47 | 47 | /* |
| 48 | 48 | ** macro to adjust 'pause': 'pause' is actually used like |
| 49 | 49 | ** 'pause / PAUSEADJ' (value chosen by tests) |
| 50 | 50 | */ |
| 51 | | #define PAUSEADJ 100 |
| 51 | #define PAUSEADJ 100 |
| 52 | 52 | |
| 53 | 53 | |
| 54 | 54 | /* |
| 55 | 55 | ** 'makewhite' erases all color bits plus the old bit and then |
| 56 | 56 | ** sets only the current white bit |
| 57 | 57 | */ |
| 58 | | #define maskcolors (~(bit2mask(BLACKBIT, OLDBIT) | WHITEBITS)) |
| 59 | | #define makewhite(g,x) \ |
| 60 | | (gch(x)->marked = cast_byte((gch(x)->marked & maskcolors) | luaC_white(g))) |
| 58 | #define maskcolors (~(bit2mask(BLACKBIT, OLDBIT) | WHITEBITS)) |
| 59 | #define makewhite(g,x) \ |
| 60 | (gch(x)->marked = cast_byte((gch(x)->marked & maskcolors) | luaC_white(g))) |
| 61 | 61 | |
| 62 | | #define white2gray(x) resetbits(gch(x)->marked, WHITEBITS) |
| 63 | | #define black2gray(x) resetbit(gch(x)->marked, BLACKBIT) |
| 62 | #define white2gray(x) resetbits(gch(x)->marked, WHITEBITS) |
| 63 | #define black2gray(x) resetbit(gch(x)->marked, BLACKBIT) |
| 64 | 64 | |
| 65 | 65 | |
| 66 | | #define isfinalized(x) testbit(gch(x)->marked, FINALIZEDBIT) |
| 66 | #define isfinalized(x) testbit(gch(x)->marked, FINALIZEDBIT) |
| 67 | 67 | |
| 68 | | #define checkdeadkey(n) lua_assert(!ttisdeadkey(gkey(n)) || ttisnil(gval(n))) |
| 68 | #define checkdeadkey(n) lua_assert(!ttisdeadkey(gkey(n)) || ttisnil(gval(n))) |
| 69 | 69 | |
| 70 | 70 | |
| 71 | 71 | #define checkconsistency(obj) \ |
| 72 | | lua_longassert(!iscollectable(obj) || righttt(obj)) |
| 72 | lua_longassert(!iscollectable(obj) || righttt(obj)) |
| 73 | 73 | |
| 74 | 74 | |
| 75 | 75 | #define markvalue(g,o) { checkconsistency(o); \ |
| 76 | | if (valiswhite(o)) reallymarkobject(g,gcvalue(o)); } |
| 76 | if (valiswhite(o)) reallymarkobject(g,gcvalue(o)); } |
| 77 | 77 | |
| 78 | 78 | #define markobject(g,t) { if ((t) && iswhite(obj2gco(t))) \ |
| 79 | 79 | reallymarkobject(g, obj2gco(t)); } |
| r30857 | r30858 | |
| 91 | 91 | /* |
| 92 | 92 | ** one after last element in a hash array |
| 93 | 93 | */ |
| 94 | | #define gnodelast(h) gnode(h, cast(size_t, sizenode(h))) |
| 94 | #define gnodelast(h) gnode(h, cast(size_t, sizenode(h))) |
| 95 | 95 | |
| 96 | 96 | |
| 97 | 97 | /* |
| 98 | 98 | ** link table 'h' into list pointed by 'p' |
| 99 | 99 | */ |
| 100 | | #define linktable(h,p) ((h)->gclist = *(p), *(p) = obj2gco(h)) |
| 100 | #define linktable(h,p) ((h)->gclist = *(p), *(p) = obj2gco(h)) |
| 101 | 101 | |
| 102 | 102 | |
| 103 | 103 | /* |
| r30857 | r30858 | |
| 105 | 105 | ** from the table) |
| 106 | 106 | */ |
| 107 | 107 | static void removeentry (Node *n) { |
| 108 | | lua_assert(ttisnil(gval(n))); |
| 109 | | if (valiswhite(gkey(n))) |
| 110 | | setdeadvalue(gkey(n)); /* unused and unmarked key; remove it */ |
| 108 | lua_assert(ttisnil(gval(n))); |
| 109 | if (valiswhite(gkey(n))) |
| 110 | setdeadvalue(gkey(n)); /* unused and unmarked key; remove it */ |
| 111 | 111 | } |
| 112 | 112 | |
| 113 | 113 | |
| r30857 | r30858 | |
| 119 | 119 | ** being finalized, keep them in keys, but not in values |
| 120 | 120 | */ |
| 121 | 121 | static int iscleared (global_State *g, const TValue *o) { |
| 122 | | if (!iscollectable(o)) return 0; |
| 123 | | else if (ttisstring(o)) { |
| 124 | | markobject(g, rawtsvalue(o)); /* strings are `values', so are never weak */ |
| 125 | | return 0; |
| 126 | | } |
| 127 | | else return iswhite(gcvalue(o)); |
| 122 | if (!iscollectable(o)) return 0; |
| 123 | else if (ttisstring(o)) { |
| 124 | markobject(g, rawtsvalue(o)); /* strings are `values', so are never weak */ |
| 125 | return 0; |
| 126 | } |
| 127 | else return iswhite(gcvalue(o)); |
| 128 | 128 | } |
| 129 | 129 | |
| 130 | 130 | |
| r30857 | r30858 | |
| 133 | 133 | ** being pointed by a black object. |
| 134 | 134 | */ |
| 135 | 135 | void luaC_barrier_ (lua_State *L, GCObject *o, GCObject *v) { |
| 136 | | global_State *g = G(L); |
| 137 | | lua_assert(isblack(o) && iswhite(v) && !isdead(g, v) && !isdead(g, o)); |
| 138 | | lua_assert(g->gcstate != GCSpause); |
| 139 | | lua_assert(gch(o)->tt != LUA_TTABLE); |
| 140 | | if (keepinvariantout(g)) /* must keep invariant? */ |
| 141 | | reallymarkobject(g, v); /* restore invariant */ |
| 142 | | else { /* sweep phase */ |
| 143 | | lua_assert(issweepphase(g)); |
| 144 | | makewhite(g, o); /* mark main obj. as white to avoid other barriers */ |
| 145 | | } |
| 136 | global_State *g = G(L); |
| 137 | lua_assert(isblack(o) && iswhite(v) && !isdead(g, v) && !isdead(g, o)); |
| 138 | lua_assert(g->gcstate != GCSpause); |
| 139 | lua_assert(gch(o)->tt != LUA_TTABLE); |
| 140 | if (keepinvariantout(g)) /* must keep invariant? */ |
| 141 | reallymarkobject(g, v); /* restore invariant */ |
| 142 | else { /* sweep phase */ |
| 143 | lua_assert(issweepphase(g)); |
| 144 | makewhite(g, o); /* mark main obj. as white to avoid other barriers */ |
| 145 | } |
| 146 | 146 | } |
| 147 | 147 | |
| 148 | 148 | |
| r30857 | r30858 | |
| 153 | 153 | ** different types.) |
| 154 | 154 | */ |
| 155 | 155 | void luaC_barrierback_ (lua_State *L, GCObject *o) { |
| 156 | | global_State *g = G(L); |
| 157 | | lua_assert(isblack(o) && !isdead(g, o) && gch(o)->tt == LUA_TTABLE); |
| 158 | | black2gray(o); /* make object gray (again) */ |
| 159 | | gco2t(o)->gclist = g->grayagain; |
| 160 | | g->grayagain = o; |
| 156 | global_State *g = G(L); |
| 157 | lua_assert(isblack(o) && !isdead(g, o) && gch(o)->tt == LUA_TTABLE); |
| 158 | black2gray(o); /* make object gray (again) */ |
| 159 | gco2t(o)->gclist = g->grayagain; |
| 160 | g->grayagain = o; |
| 161 | 161 | } |
| 162 | 162 | |
| 163 | 163 | |
| r30857 | r30858 | |
| 170 | 170 | ** possible instances. |
| 171 | 171 | */ |
| 172 | 172 | LUAI_FUNC void luaC_barrierproto_ (lua_State *L, Proto *p, Closure *c) { |
| 173 | | global_State *g = G(L); |
| 174 | | lua_assert(isblack(obj2gco(p))); |
| 175 | | if (p->cache == NULL) { /* first time? */ |
| 176 | | luaC_objbarrier(L, p, c); |
| 177 | | } |
| 178 | | else { /* use a backward barrier */ |
| 179 | | black2gray(obj2gco(p)); /* make prototype gray (again) */ |
| 180 | | p->gclist = g->grayagain; |
| 181 | | g->grayagain = obj2gco(p); |
| 182 | | } |
| 173 | global_State *g = G(L); |
| 174 | lua_assert(isblack(obj2gco(p))); |
| 175 | if (p->cache == NULL) { /* first time? */ |
| 176 | luaC_objbarrier(L, p, c); |
| 177 | } |
| 178 | else { /* use a backward barrier */ |
| 179 | black2gray(obj2gco(p)); /* make prototype gray (again) */ |
| 180 | p->gclist = g->grayagain; |
| 181 | g->grayagain = obj2gco(p); |
| 182 | } |
| 183 | 183 | } |
| 184 | 184 | |
| 185 | 185 | |
| r30857 | r30858 | |
| 188 | 188 | ** i.e., moved into the 'allgc' list |
| 189 | 189 | */ |
| 190 | 190 | void luaC_checkupvalcolor (global_State *g, UpVal *uv) { |
| 191 | | GCObject *o = obj2gco(uv); |
| 192 | | lua_assert(!isblack(o)); /* open upvalues are never black */ |
| 193 | | if (isgray(o)) { |
| 194 | | if (keepinvariant(g)) { |
| 195 | | resetoldbit(o); /* see MOVE OLD rule */ |
| 196 | | gray2black(o); /* it is being visited now */ |
| 197 | | markvalue(g, uv->v); |
| 198 | | } |
| 199 | | else { |
| 200 | | lua_assert(issweepphase(g)); |
| 201 | | makewhite(g, o); |
| 202 | | } |
| 203 | | } |
| 191 | GCObject *o = obj2gco(uv); |
| 192 | lua_assert(!isblack(o)); /* open upvalues are never black */ |
| 193 | if (isgray(o)) { |
| 194 | if (keepinvariant(g)) { |
| 195 | resetoldbit(o); /* see MOVE OLD rule */ |
| 196 | gray2black(o); /* it is being visited now */ |
| 197 | markvalue(g, uv->v); |
| 198 | } |
| 199 | else { |
| 200 | lua_assert(issweepphase(g)); |
| 201 | makewhite(g, o); |
| 202 | } |
| 203 | } |
| 204 | 204 | } |
| 205 | 205 | |
| 206 | 206 | |
| r30857 | r30858 | |
| 210 | 210 | ** object itself (used only by states). |
| 211 | 211 | */ |
| 212 | 212 | GCObject *luaC_newobj (lua_State *L, int tt, size_t sz, GCObject **list, |
| 213 | | int offset) { |
| 214 | | global_State *g = G(L); |
| 215 | | char *raw = cast(char *, luaM_newobject(L, novariant(tt), sz)); |
| 216 | | GCObject *o = obj2gco(raw + offset); |
| 217 | | if (list == NULL) |
| 218 | | list = &g->allgc; /* standard list for collectable objects */ |
| 219 | | gch(o)->marked = luaC_white(g); |
| 220 | | gch(o)->tt = tt; |
| 221 | | gch(o)->next = *list; |
| 222 | | *list = o; |
| 223 | | return o; |
| 213 | int offset) { |
| 214 | global_State *g = G(L); |
| 215 | char *raw = cast(char *, luaM_newobject(L, novariant(tt), sz)); |
| 216 | GCObject *o = obj2gco(raw + offset); |
| 217 | if (list == NULL) |
| 218 | list = &g->allgc; /* standard list for collectable objects */ |
| 219 | gch(o)->marked = luaC_white(g); |
| 220 | gch(o)->tt = tt; |
| 221 | gch(o)->next = *list; |
| 222 | *list = o; |
| 223 | return o; |
| 224 | 224 | } |
| 225 | 225 | |
| 226 | 226 | /* }====================================================== */ |
| r30857 | r30858 | |
| 241 | 241 | ** upvalues are already linked in 'headuv' list.) |
| 242 | 242 | */ |
| 243 | 243 | static void reallymarkobject (global_State *g, GCObject *o) { |
| 244 | | lu_mem size; |
| 245 | | white2gray(o); |
| 246 | | switch (gch(o)->tt) { |
| 247 | | case LUA_TSHRSTR: |
| 248 | | case LUA_TLNGSTR: { |
| 249 | | size = sizestring(gco2ts(o)); |
| 250 | | break; /* nothing else to mark; make it black */ |
| 251 | | } |
| 252 | | case LUA_TUSERDATA: { |
| 253 | | Table *mt = gco2u(o)->metatable; |
| 254 | | markobject(g, mt); |
| 255 | | markobject(g, gco2u(o)->env); |
| 256 | | size = sizeudata(gco2u(o)); |
| 257 | | break; |
| 258 | | } |
| 259 | | case LUA_TUPVAL: { |
| 260 | | UpVal *uv = gco2uv(o); |
| 261 | | markvalue(g, uv->v); |
| 262 | | if (uv->v != &uv->u.value) /* open? */ |
| 263 | | return; /* open upvalues remain gray */ |
| 264 | | size = sizeof(UpVal); |
| 265 | | break; |
| 266 | | } |
| 267 | | case LUA_TLCL: { |
| 268 | | gco2lcl(o)->gclist = g->gray; |
| 269 | | g->gray = o; |
| 270 | | return; |
| 271 | | } |
| 272 | | case LUA_TCCL: { |
| 273 | | gco2ccl(o)->gclist = g->gray; |
| 274 | | g->gray = o; |
| 275 | | return; |
| 276 | | } |
| 277 | | case LUA_TTABLE: { |
| 278 | | linktable(gco2t(o), &g->gray); |
| 279 | | return; |
| 280 | | } |
| 281 | | case LUA_TTHREAD: { |
| 282 | | gco2th(o)->gclist = g->gray; |
| 283 | | g->gray = o; |
| 284 | | return; |
| 285 | | } |
| 286 | | case LUA_TPROTO: { |
| 287 | | gco2p(o)->gclist = g->gray; |
| 288 | | g->gray = o; |
| 289 | | return; |
| 290 | | } |
| 291 | | default: lua_assert(0); return; |
| 292 | | } |
| 293 | | gray2black(o); |
| 294 | | g->GCmemtrav += size; |
| 244 | lu_mem size; |
| 245 | white2gray(o); |
| 246 | switch (gch(o)->tt) { |
| 247 | case LUA_TSHRSTR: |
| 248 | case LUA_TLNGSTR: { |
| 249 | size = sizestring(gco2ts(o)); |
| 250 | break; /* nothing else to mark; make it black */ |
| 251 | } |
| 252 | case LUA_TUSERDATA: { |
| 253 | Table *mt = gco2u(o)->metatable; |
| 254 | markobject(g, mt); |
| 255 | markobject(g, gco2u(o)->env); |
| 256 | size = sizeudata(gco2u(o)); |
| 257 | break; |
| 258 | } |
| 259 | case LUA_TUPVAL: { |
| 260 | UpVal *uv = gco2uv(o); |
| 261 | markvalue(g, uv->v); |
| 262 | if (uv->v != &uv->u.value) /* open? */ |
| 263 | return; /* open upvalues remain gray */ |
| 264 | size = sizeof(UpVal); |
| 265 | break; |
| 266 | } |
| 267 | case LUA_TLCL: { |
| 268 | gco2lcl(o)->gclist = g->gray; |
| 269 | g->gray = o; |
| 270 | return; |
| 271 | } |
| 272 | case LUA_TCCL: { |
| 273 | gco2ccl(o)->gclist = g->gray; |
| 274 | g->gray = o; |
| 275 | return; |
| 276 | } |
| 277 | case LUA_TTABLE: { |
| 278 | linktable(gco2t(o), &g->gray); |
| 279 | return; |
| 280 | } |
| 281 | case LUA_TTHREAD: { |
| 282 | gco2th(o)->gclist = g->gray; |
| 283 | g->gray = o; |
| 284 | return; |
| 285 | } |
| 286 | case LUA_TPROTO: { |
| 287 | gco2p(o)->gclist = g->gray; |
| 288 | g->gray = o; |
| 289 | return; |
| 290 | } |
| 291 | default: lua_assert(0); return; |
| 292 | } |
| 293 | gray2black(o); |
| 294 | g->GCmemtrav += size; |
| 295 | 295 | } |
| 296 | 296 | |
| 297 | 297 | |
| r30857 | r30858 | |
| 299 | 299 | ** mark metamethods for basic types |
| 300 | 300 | */ |
| 301 | 301 | static void markmt (global_State *g) { |
| 302 | | int i; |
| 303 | | for (i=0; i < LUA_NUMTAGS; i++) |
| 304 | | markobject(g, g->mt[i]); |
| 302 | int i; |
| 303 | for (i=0; i < LUA_NUMTAGS; i++) |
| 304 | markobject(g, g->mt[i]); |
| 305 | 305 | } |
| 306 | 306 | |
| 307 | 307 | |
| r30857 | r30858 | |
| 309 | 309 | ** mark all objects in list of being-finalized |
| 310 | 310 | */ |
| 311 | 311 | static void markbeingfnz (global_State *g) { |
| 312 | | GCObject *o; |
| 313 | | for (o = g->tobefnz; o != NULL; o = gch(o)->next) { |
| 314 | | makewhite(g, o); |
| 315 | | reallymarkobject(g, o); |
| 316 | | } |
| 312 | GCObject *o; |
| 313 | for (o = g->tobefnz; o != NULL; o = gch(o)->next) { |
| 314 | makewhite(g, o); |
| 315 | reallymarkobject(g, o); |
| 316 | } |
| 317 | 317 | } |
| 318 | 318 | |
| 319 | 319 | |
| r30857 | r30858 | |
| 322 | 322 | ** 'lstate.h'.) |
| 323 | 323 | */ |
| 324 | 324 | static void remarkupvals (global_State *g) { |
| 325 | | UpVal *uv; |
| 326 | | for (uv = g->uvhead.u.l.next; uv != &g->uvhead; uv = uv->u.l.next) { |
| 327 | | if (isgray(obj2gco(uv))) |
| 328 | | markvalue(g, uv->v); |
| 329 | | } |
| 325 | UpVal *uv; |
| 326 | for (uv = g->uvhead.u.l.next; uv != &g->uvhead; uv = uv->u.l.next) { |
| 327 | if (isgray(obj2gco(uv))) |
| 328 | markvalue(g, uv->v); |
| 329 | } |
| 330 | 330 | } |
| 331 | 331 | |
| 332 | 332 | |
| r30857 | r30858 | |
| 335 | 335 | ** incremental (or full) collection |
| 336 | 336 | */ |
| 337 | 337 | static void restartcollection (global_State *g) { |
| 338 | | g->gray = g->grayagain = NULL; |
| 339 | | g->weak = g->allweak = g->ephemeron = NULL; |
| 340 | | markobject(g, g->mainthread); |
| 341 | | markvalue(g, &g->l_registry); |
| 342 | | markmt(g); |
| 343 | | markbeingfnz(g); /* mark any finalizing object left from previous cycle */ |
| 338 | g->gray = g->grayagain = NULL; |
| 339 | g->weak = g->allweak = g->ephemeron = NULL; |
| 340 | markobject(g, g->mainthread); |
| 341 | markvalue(g, &g->l_registry); |
| 342 | markmt(g); |
| 343 | markbeingfnz(g); /* mark any finalizing object left from previous cycle */ |
| 344 | 344 | } |
| 345 | 345 | |
| 346 | 346 | /* }====================================================== */ |
| r30857 | r30858 | |
| 353 | 353 | */ |
| 354 | 354 | |
| 355 | 355 | static void traverseweakvalue (global_State *g, Table *h) { |
| 356 | | Node *n, *limit = gnodelast(h); |
| 357 | | /* if there is array part, assume it may have white values (do not |
| 358 | | traverse it just to check) */ |
| 359 | | int hasclears = (h->sizearray > 0); |
| 360 | | for (n = gnode(h, 0); n < limit; n++) { |
| 361 | | checkdeadkey(n); |
| 362 | | if (ttisnil(gval(n))) /* entry is empty? */ |
| 363 | | removeentry(n); /* remove it */ |
| 364 | | else { |
| 365 | | lua_assert(!ttisnil(gkey(n))); |
| 366 | | markvalue(g, gkey(n)); /* mark key */ |
| 367 | | if (!hasclears && iscleared(g, gval(n))) /* is there a white value? */ |
| 368 | | hasclears = 1; /* table will have to be cleared */ |
| 369 | | } |
| 370 | | } |
| 371 | | if (hasclears) |
| 372 | | linktable(h, &g->weak); /* has to be cleared later */ |
| 373 | | else /* no white values */ |
| 374 | | linktable(h, &g->grayagain); /* no need to clean */ |
| 356 | Node *n, *limit = gnodelast(h); |
| 357 | /* if there is array part, assume it may have white values (do not |
| 358 | traverse it just to check) */ |
| 359 | int hasclears = (h->sizearray > 0); |
| 360 | for (n = gnode(h, 0); n < limit; n++) { |
| 361 | checkdeadkey(n); |
| 362 | if (ttisnil(gval(n))) /* entry is empty? */ |
| 363 | removeentry(n); /* remove it */ |
| 364 | else { |
| 365 | lua_assert(!ttisnil(gkey(n))); |
| 366 | markvalue(g, gkey(n)); /* mark key */ |
| 367 | if (!hasclears && iscleared(g, gval(n))) /* is there a white value? */ |
| 368 | hasclears = 1; /* table will have to be cleared */ |
| 369 | } |
| 370 | } |
| 371 | if (hasclears) |
| 372 | linktable(h, &g->weak); /* has to be cleared later */ |
| 373 | else /* no white values */ |
| 374 | linktable(h, &g->grayagain); /* no need to clean */ |
| 375 | 375 | } |
| 376 | 376 | |
| 377 | 377 | |
| 378 | 378 | static int traverseephemeron (global_State *g, Table *h) { |
| 379 | | int marked = 0; /* true if an object is marked in this traversal */ |
| 380 | | int hasclears = 0; /* true if table has white keys */ |
| 381 | | int prop = 0; /* true if table has entry "white-key -> white-value" */ |
| 382 | | Node *n, *limit = gnodelast(h); |
| 383 | | int i; |
| 384 | | /* traverse array part (numeric keys are 'strong') */ |
| 385 | | for (i = 0; i < h->sizearray; i++) { |
| 386 | | if (valiswhite(&h->array[i])) { |
| 387 | | marked = 1; |
| 388 | | reallymarkobject(g, gcvalue(&h->array[i])); |
| 389 | | } |
| 390 | | } |
| 391 | | /* traverse hash part */ |
| 392 | | for (n = gnode(h, 0); n < limit; n++) { |
| 393 | | checkdeadkey(n); |
| 394 | | if (ttisnil(gval(n))) /* entry is empty? */ |
| 395 | | removeentry(n); /* remove it */ |
| 396 | | else if (iscleared(g, gkey(n))) { /* key is not marked (yet)? */ |
| 397 | | hasclears = 1; /* table must be cleared */ |
| 398 | | if (valiswhite(gval(n))) /* value not marked yet? */ |
| 399 | | prop = 1; /* must propagate again */ |
| 400 | | } |
| 401 | | else if (valiswhite(gval(n))) { /* value not marked yet? */ |
| 402 | | marked = 1; |
| 403 | | reallymarkobject(g, gcvalue(gval(n))); /* mark it now */ |
| 404 | | } |
| 405 | | } |
| 406 | | if (prop) |
| 407 | | linktable(h, &g->ephemeron); /* have to propagate again */ |
| 408 | | else if (hasclears) /* does table have white keys? */ |
| 409 | | linktable(h, &g->allweak); /* may have to clean white keys */ |
| 410 | | else /* no white keys */ |
| 411 | | linktable(h, &g->grayagain); /* no need to clean */ |
| 412 | | return marked; |
| 379 | int marked = 0; /* true if an object is marked in this traversal */ |
| 380 | int hasclears = 0; /* true if table has white keys */ |
| 381 | int prop = 0; /* true if table has entry "white-key -> white-value" */ |
| 382 | Node *n, *limit = gnodelast(h); |
| 383 | int i; |
| 384 | /* traverse array part (numeric keys are 'strong') */ |
| 385 | for (i = 0; i < h->sizearray; i++) { |
| 386 | if (valiswhite(&h->array[i])) { |
| 387 | marked = 1; |
| 388 | reallymarkobject(g, gcvalue(&h->array[i])); |
| 389 | } |
| 390 | } |
| 391 | /* traverse hash part */ |
| 392 | for (n = gnode(h, 0); n < limit; n++) { |
| 393 | checkdeadkey(n); |
| 394 | if (ttisnil(gval(n))) /* entry is empty? */ |
| 395 | removeentry(n); /* remove it */ |
| 396 | else if (iscleared(g, gkey(n))) { /* key is not marked (yet)? */ |
| 397 | hasclears = 1; /* table must be cleared */ |
| 398 | if (valiswhite(gval(n))) /* value not marked yet? */ |
| 399 | prop = 1; /* must propagate again */ |
| 400 | } |
| 401 | else if (valiswhite(gval(n))) { /* value not marked yet? */ |
| 402 | marked = 1; |
| 403 | reallymarkobject(g, gcvalue(gval(n))); /* mark it now */ |
| 404 | } |
| 405 | } |
| 406 | if (prop) |
| 407 | linktable(h, &g->ephemeron); /* have to propagate again */ |
| 408 | else if (hasclears) /* does table have white keys? */ |
| 409 | linktable(h, &g->allweak); /* may have to clean white keys */ |
| 410 | else /* no white keys */ |
| 411 | linktable(h, &g->grayagain); /* no need to clean */ |
| 412 | return marked; |
| 413 | 413 | } |
| 414 | 414 | |
| 415 | 415 | |
| 416 | 416 | static void traversestrongtable (global_State *g, Table *h) { |
| 417 | | Node *n, *limit = gnodelast(h); |
| 418 | | int i; |
| 419 | | for (i = 0; i < h->sizearray; i++) /* traverse array part */ |
| 420 | | markvalue(g, &h->array[i]); |
| 421 | | for (n = gnode(h, 0); n < limit; n++) { /* traverse hash part */ |
| 422 | | checkdeadkey(n); |
| 423 | | if (ttisnil(gval(n))) /* entry is empty? */ |
| 424 | | removeentry(n); /* remove it */ |
| 425 | | else { |
| 426 | | lua_assert(!ttisnil(gkey(n))); |
| 427 | | markvalue(g, gkey(n)); /* mark key */ |
| 428 | | markvalue(g, gval(n)); /* mark value */ |
| 429 | | } |
| 430 | | } |
| 417 | Node *n, *limit = gnodelast(h); |
| 418 | int i; |
| 419 | for (i = 0; i < h->sizearray; i++) /* traverse array part */ |
| 420 | markvalue(g, &h->array[i]); |
| 421 | for (n = gnode(h, 0); n < limit; n++) { /* traverse hash part */ |
| 422 | checkdeadkey(n); |
| 423 | if (ttisnil(gval(n))) /* entry is empty? */ |
| 424 | removeentry(n); /* remove it */ |
| 425 | else { |
| 426 | lua_assert(!ttisnil(gkey(n))); |
| 427 | markvalue(g, gkey(n)); /* mark key */ |
| 428 | markvalue(g, gval(n)); /* mark value */ |
| 429 | } |
| 430 | } |
| 431 | 431 | } |
| 432 | 432 | |
| 433 | 433 | |
| 434 | 434 | static lu_mem traversetable (global_State *g, Table *h) { |
| 435 | | const char *weakkey, *weakvalue; |
| 436 | | const TValue *mode = gfasttm(g, h->metatable, TM_MODE); |
| 437 | | markobject(g, h->metatable); |
| 438 | | if (mode && ttisstring(mode) && /* is there a weak mode? */ |
| 439 | | ((weakkey = strchr(svalue(mode), 'k')), |
| 440 | | (weakvalue = strchr(svalue(mode), 'v')), |
| 441 | | (weakkey || weakvalue))) { /* is really weak? */ |
| 442 | | black2gray(obj2gco(h)); /* keep table gray */ |
| 443 | | if (!weakkey) /* strong keys? */ |
| 444 | | traverseweakvalue(g, h); |
| 445 | | else if (!weakvalue) /* strong values? */ |
| 446 | | traverseephemeron(g, h); |
| 447 | | else /* all weak */ |
| 448 | | linktable(h, &g->allweak); /* nothing to traverse now */ |
| 449 | | } |
| 450 | | else /* not weak */ |
| 451 | | traversestrongtable(g, h); |
| 452 | | return sizeof(Table) + sizeof(TValue) * h->sizearray + |
| 453 | | sizeof(Node) * cast(size_t, sizenode(h)); |
| 435 | const char *weakkey, *weakvalue; |
| 436 | const TValue *mode = gfasttm(g, h->metatable, TM_MODE); |
| 437 | markobject(g, h->metatable); |
| 438 | if (mode && ttisstring(mode) && /* is there a weak mode? */ |
| 439 | ((weakkey = strchr(svalue(mode), 'k')), |
| 440 | (weakvalue = strchr(svalue(mode), 'v')), |
| 441 | (weakkey || weakvalue))) { /* is really weak? */ |
| 442 | black2gray(obj2gco(h)); /* keep table gray */ |
| 443 | if (!weakkey) /* strong keys? */ |
| 444 | traverseweakvalue(g, h); |
| 445 | else if (!weakvalue) /* strong values? */ |
| 446 | traverseephemeron(g, h); |
| 447 | else /* all weak */ |
| 448 | linktable(h, &g->allweak); /* nothing to traverse now */ |
| 449 | } |
| 450 | else /* not weak */ |
| 451 | traversestrongtable(g, h); |
| 452 | return sizeof(Table) + sizeof(TValue) * h->sizearray + |
| 453 | sizeof(Node) * cast(size_t, sizenode(h)); |
| 454 | 454 | } |
| 455 | 455 | |
| 456 | 456 | |
| 457 | 457 | static int traverseproto (global_State *g, Proto *f) { |
| 458 | | int i; |
| 459 | | if (f->cache && iswhite(obj2gco(f->cache))) |
| 460 | | f->cache = NULL; /* allow cache to be collected */ |
| 461 | | markobject(g, f->source); |
| 462 | | for (i = 0; i < f->sizek; i++) /* mark literals */ |
| 463 | | markvalue(g, &f->k[i]); |
| 464 | | for (i = 0; i < f->sizeupvalues; i++) /* mark upvalue names */ |
| 465 | | markobject(g, f->upvalues[i].name); |
| 466 | | for (i = 0; i < f->sizep; i++) /* mark nested protos */ |
| 467 | | markobject(g, f->p[i]); |
| 468 | | for (i = 0; i < f->sizelocvars; i++) /* mark local-variable names */ |
| 469 | | markobject(g, f->locvars[i].varname); |
| 470 | | return sizeof(Proto) + sizeof(Instruction) * f->sizecode + |
| 471 | | sizeof(Proto *) * f->sizep + |
| 472 | | sizeof(TValue) * f->sizek + |
| 473 | | sizeof(int) * f->sizelineinfo + |
| 474 | | sizeof(LocVar) * f->sizelocvars + |
| 475 | | sizeof(Upvaldesc) * f->sizeupvalues; |
| 458 | int i; |
| 459 | if (f->cache && iswhite(obj2gco(f->cache))) |
| 460 | f->cache = NULL; /* allow cache to be collected */ |
| 461 | markobject(g, f->source); |
| 462 | for (i = 0; i < f->sizek; i++) /* mark literals */ |
| 463 | markvalue(g, &f->k[i]); |
| 464 | for (i = 0; i < f->sizeupvalues; i++) /* mark upvalue names */ |
| 465 | markobject(g, f->upvalues[i].name); |
| 466 | for (i = 0; i < f->sizep; i++) /* mark nested protos */ |
| 467 | markobject(g, f->p[i]); |
| 468 | for (i = 0; i < f->sizelocvars; i++) /* mark local-variable names */ |
| 469 | markobject(g, f->locvars[i].varname); |
| 470 | return sizeof(Proto) + sizeof(Instruction) * f->sizecode + |
| 471 | sizeof(Proto *) * f->sizep + |
| 472 | sizeof(TValue) * f->sizek + |
| 473 | sizeof(int) * f->sizelineinfo + |
| 474 | sizeof(LocVar) * f->sizelocvars + |
| 475 | sizeof(Upvaldesc) * f->sizeupvalues; |
| 476 | 476 | } |
| 477 | 477 | |
| 478 | 478 | |
| 479 | 479 | static lu_mem traverseCclosure (global_State *g, CClosure *cl) { |
| 480 | | int i; |
| 481 | | for (i = 0; i < cl->nupvalues; i++) /* mark its upvalues */ |
| 482 | | markvalue(g, &cl->upvalue[i]); |
| 483 | | return sizeCclosure(cl->nupvalues); |
| 480 | int i; |
| 481 | for (i = 0; i < cl->nupvalues; i++) /* mark its upvalues */ |
| 482 | markvalue(g, &cl->upvalue[i]); |
| 483 | return sizeCclosure(cl->nupvalues); |
| 484 | 484 | } |
| 485 | 485 | |
| 486 | 486 | static lu_mem traverseLclosure (global_State *g, LClosure *cl) { |
| 487 | | int i; |
| 488 | | markobject(g, cl->p); /* mark its prototype */ |
| 489 | | for (i = 0; i < cl->nupvalues; i++) /* mark its upvalues */ |
| 490 | | markobject(g, cl->upvals[i]); |
| 491 | | return sizeLclosure(cl->nupvalues); |
| 487 | int i; |
| 488 | markobject(g, cl->p); /* mark its prototype */ |
| 489 | for (i = 0; i < cl->nupvalues; i++) /* mark its upvalues */ |
| 490 | markobject(g, cl->upvals[i]); |
| 491 | return sizeLclosure(cl->nupvalues); |
| 492 | 492 | } |
| 493 | 493 | |
| 494 | 494 | |
| 495 | 495 | static lu_mem traversestack (global_State *g, lua_State *th) { |
| 496 | | StkId o = th->stack; |
| 497 | | if (o == NULL) |
| 498 | | return 1; /* stack not completely built yet */ |
| 499 | | for (; o < th->top; o++) |
| 500 | | markvalue(g, o); |
| 501 | | if (g->gcstate == GCSatomic) { /* final traversal? */ |
| 502 | | StkId lim = th->stack + th->stacksize; /* real end of stack */ |
| 503 | | for (; o < lim; o++) /* clear not-marked stack slice */ |
| 504 | | setnilvalue(o); |
| 505 | | } |
| 506 | | return sizeof(lua_State) + sizeof(TValue) * th->stacksize; |
| 496 | int n = 0; |
| 497 | StkId o = th->stack; |
| 498 | if (o == NULL) |
| 499 | return 1; /* stack not completely built yet */ |
| 500 | for (; o < th->top; o++) /* mark live elements in the stack */ |
| 501 | markvalue(g, o); |
| 502 | if (g->gcstate == GCSatomic) { /* final traversal? */ |
| 503 | StkId lim = th->stack + th->stacksize; /* real end of stack */ |
| 504 | for (; o < lim; o++) /* clear not-marked stack slice */ |
| 505 | setnilvalue(o); |
| 506 | } |
| 507 | else { /* count call infos to compute size */ |
| 508 | CallInfo *ci; |
| 509 | for (ci = &th->base_ci; ci != th->ci; ci = ci->next) |
| 510 | n++; |
| 511 | } |
| 512 | return sizeof(lua_State) + sizeof(TValue) * th->stacksize + |
| 513 | sizeof(CallInfo) * n; |
| 507 | 514 | } |
| 508 | 515 | |
| 509 | 516 | |
| r30857 | r30858 | |
| 512 | 519 | ** which are always gray). |
| 513 | 520 | */ |
| 514 | 521 | static void propagatemark (global_State *g) { |
| 515 | | lu_mem size; |
| 516 | | GCObject *o = g->gray; |
| 517 | | lua_assert(isgray(o)); |
| 518 | | gray2black(o); |
| 519 | | switch (gch(o)->tt) { |
| 520 | | case LUA_TTABLE: { |
| 521 | | Table *h = gco2t(o); |
| 522 | | g->gray = h->gclist; /* remove from 'gray' list */ |
| 523 | | size = traversetable(g, h); |
| 524 | | break; |
| 525 | | } |
| 526 | | case LUA_TLCL: { |
| 527 | | LClosure *cl = gco2lcl(o); |
| 528 | | g->gray = cl->gclist; /* remove from 'gray' list */ |
| 529 | | size = traverseLclosure(g, cl); |
| 530 | | break; |
| 531 | | } |
| 532 | | case LUA_TCCL: { |
| 533 | | CClosure *cl = gco2ccl(o); |
| 534 | | g->gray = cl->gclist; /* remove from 'gray' list */ |
| 535 | | size = traverseCclosure(g, cl); |
| 536 | | break; |
| 537 | | } |
| 538 | | case LUA_TTHREAD: { |
| 539 | | lua_State *th = gco2th(o); |
| 540 | | g->gray = th->gclist; /* remove from 'gray' list */ |
| 541 | | th->gclist = g->grayagain; |
| 542 | | g->grayagain = o; /* insert into 'grayagain' list */ |
| 543 | | black2gray(o); |
| 544 | | size = traversestack(g, th); |
| 545 | | break; |
| 546 | | } |
| 547 | | case LUA_TPROTO: { |
| 548 | | Proto *p = gco2p(o); |
| 549 | | g->gray = p->gclist; /* remove from 'gray' list */ |
| 550 | | size = traverseproto(g, p); |
| 551 | | break; |
| 552 | | } |
| 553 | | default: lua_assert(0); return; |
| 554 | | } |
| 555 | | g->GCmemtrav += size; |
| 522 | lu_mem size; |
| 523 | GCObject *o = g->gray; |
| 524 | lua_assert(isgray(o)); |
| 525 | gray2black(o); |
| 526 | switch (gch(o)->tt) { |
| 527 | case LUA_TTABLE: { |
| 528 | Table *h = gco2t(o); |
| 529 | g->gray = h->gclist; /* remove from 'gray' list */ |
| 530 | size = traversetable(g, h); |
| 531 | break; |
| 532 | } |
| 533 | case LUA_TLCL: { |
| 534 | LClosure *cl = gco2lcl(o); |
| 535 | g->gray = cl->gclist; /* remove from 'gray' list */ |
| 536 | size = traverseLclosure(g, cl); |
| 537 | break; |
| 538 | } |
| 539 | case LUA_TCCL: { |
| 540 | CClosure *cl = gco2ccl(o); |
| 541 | g->gray = cl->gclist; /* remove from 'gray' list */ |
| 542 | size = traverseCclosure(g, cl); |
| 543 | break; |
| 544 | } |
| 545 | case LUA_TTHREAD: { |
| 546 | lua_State *th = gco2th(o); |
| 547 | g->gray = th->gclist; /* remove from 'gray' list */ |
| 548 | th->gclist = g->grayagain; |
| 549 | g->grayagain = o; /* insert into 'grayagain' list */ |
| 550 | black2gray(o); |
| 551 | size = traversestack(g, th); |
| 552 | break; |
| 553 | } |
| 554 | case LUA_TPROTO: { |
| 555 | Proto *p = gco2p(o); |
| 556 | g->gray = p->gclist; /* remove from 'gray' list */ |
| 557 | size = traverseproto(g, p); |
| 558 | break; |
| 559 | } |
| 560 | default: lua_assert(0); return; |
| 561 | } |
| 562 | g->GCmemtrav += size; |
| 556 | 563 | } |
| 557 | 564 | |
| 558 | 565 | |
| 559 | 566 | static void propagateall (global_State *g) { |
| 560 | | while (g->gray) propagatemark(g); |
| 567 | while (g->gray) propagatemark(g); |
| 561 | 568 | } |
| 562 | 569 | |
| 563 | 570 | |
| 564 | 571 | static void propagatelist (global_State *g, GCObject *l) { |
| 565 | | lua_assert(g->gray == NULL); /* no grays left */ |
| 566 | | g->gray = l; |
| 567 | | propagateall(g); /* traverse all elements from 'l' */ |
| 572 | lua_assert(g->gray == NULL); /* no grays left */ |
| 573 | g->gray = l; |
| 574 | propagateall(g); /* traverse all elements from 'l' */ |
| 568 | 575 | } |
| 569 | 576 | |
| 570 | 577 | /* |
| r30857 | r30858 | |
| 573 | 580 | ** twice the same table (which is not wrong, but inefficient) |
| 574 | 581 | */ |
| 575 | 582 | static void retraversegrays (global_State *g) { |
| 576 | | GCObject *weak = g->weak; /* save original lists */ |
| 577 | | GCObject *grayagain = g->grayagain; |
| 578 | | GCObject *ephemeron = g->ephemeron; |
| 579 | | g->weak = g->grayagain = g->ephemeron = NULL; |
| 580 | | propagateall(g); /* traverse main gray list */ |
| 581 | | propagatelist(g, grayagain); |
| 582 | | propagatelist(g, weak); |
| 583 | | propagatelist(g, ephemeron); |
| 583 | GCObject *weak = g->weak; /* save original lists */ |
| 584 | GCObject *grayagain = g->grayagain; |
| 585 | GCObject *ephemeron = g->ephemeron; |
| 586 | g->weak = g->grayagain = g->ephemeron = NULL; |
| 587 | propagateall(g); /* traverse main gray list */ |
| 588 | propagatelist(g, grayagain); |
| 589 | propagatelist(g, weak); |
| 590 | propagatelist(g, ephemeron); |
| 584 | 591 | } |
| 585 | 592 | |
| 586 | 593 | |
| 587 | 594 | static void convergeephemerons (global_State *g) { |
| 588 | | int changed; |
| 589 | | do { |
| 590 | | GCObject *w; |
| 591 | | GCObject *next = g->ephemeron; /* get ephemeron list */ |
| 592 | | g->ephemeron = NULL; /* tables will return to this list when traversed */ |
| 593 | | changed = 0; |
| 594 | | while ((w = next) != NULL) { |
| 595 | | next = gco2t(w)->gclist; |
| 596 | | if (traverseephemeron(g, gco2t(w))) { /* traverse marked some value? */ |
| 597 | | propagateall(g); /* propagate changes */ |
| 598 | | changed = 1; /* will have to revisit all ephemeron tables */ |
| 599 | | } |
| 600 | | } |
| 601 | | } while (changed); |
| 595 | int changed; |
| 596 | do { |
| 597 | GCObject *w; |
| 598 | GCObject *next = g->ephemeron; /* get ephemeron list */ |
| 599 | g->ephemeron = NULL; /* tables will return to this list when traversed */ |
| 600 | changed = 0; |
| 601 | while ((w = next) != NULL) { |
| 602 | next = gco2t(w)->gclist; |
| 603 | if (traverseephemeron(g, gco2t(w))) { /* traverse marked some value? */ |
| 604 | propagateall(g); /* propagate changes */ |
| 605 | changed = 1; /* will have to revisit all ephemeron tables */ |
| 606 | } |
| 607 | } |
| 608 | } while (changed); |
| 602 | 609 | } |
| 603 | 610 | |
| 604 | 611 | /* }====================================================== */ |
| r30857 | r30858 | |
| 616 | 623 | ** to element 'f' |
| 617 | 624 | */ |
| 618 | 625 | static void clearkeys (global_State *g, GCObject *l, GCObject *f) { |
| 619 | | for (; l != f; l = gco2t(l)->gclist) { |
| 620 | | Table *h = gco2t(l); |
| 621 | | Node *n, *limit = gnodelast(h); |
| 622 | | for (n = gnode(h, 0); n < limit; n++) { |
| 623 | | if (!ttisnil(gval(n)) && (iscleared(g, gkey(n)))) { |
| 624 | | setnilvalue(gval(n)); /* remove value ... */ |
| 625 | | removeentry(n); /* and remove entry from table */ |
| 626 | | } |
| 627 | | } |
| 628 | | } |
| 626 | for (; l != f; l = gco2t(l)->gclist) { |
| 627 | Table *h = gco2t(l); |
| 628 | Node *n, *limit = gnodelast(h); |
| 629 | for (n = gnode(h, 0); n < limit; n++) { |
| 630 | if (!ttisnil(gval(n)) && (iscleared(g, gkey(n)))) { |
| 631 | setnilvalue(gval(n)); /* remove value ... */ |
| 632 | removeentry(n); /* and remove entry from table */ |
| 633 | } |
| 634 | } |
| 635 | } |
| 629 | 636 | } |
| 630 | 637 | |
| 631 | 638 | |
| r30857 | r30858 | |
| 634 | 641 | ** to element 'f' |
| 635 | 642 | */ |
| 636 | 643 | static void clearvalues (global_State *g, GCObject *l, GCObject *f) { |
| 637 | | for (; l != f; l = gco2t(l)->gclist) { |
| 638 | | Table *h = gco2t(l); |
| 639 | | Node *n, *limit = gnodelast(h); |
| 640 | | int i; |
| 641 | | for (i = 0; i < h->sizearray; i++) { |
| 642 | | TValue *o = &h->array[i]; |
| 643 | | if (iscleared(g, o)) /* value was collected? */ |
| 644 | | setnilvalue(o); /* remove value */ |
| 645 | | } |
| 646 | | for (n = gnode(h, 0); n < limit; n++) { |
| 647 | | if (!ttisnil(gval(n)) && iscleared(g, gval(n))) { |
| 648 | | setnilvalue(gval(n)); /* remove value ... */ |
| 649 | | removeentry(n); /* and remove entry from table */ |
| 650 | | } |
| 651 | | } |
| 652 | | } |
| 644 | for (; l != f; l = gco2t(l)->gclist) { |
| 645 | Table *h = gco2t(l); |
| 646 | Node *n, *limit = gnodelast(h); |
| 647 | int i; |
| 648 | for (i = 0; i < h->sizearray; i++) { |
| 649 | TValue *o = &h->array[i]; |
| 650 | if (iscleared(g, o)) /* value was collected? */ |
| 651 | setnilvalue(o); /* remove value */ |
| 652 | } |
| 653 | for (n = gnode(h, 0); n < limit; n++) { |
| 654 | if (!ttisnil(gval(n)) && iscleared(g, gval(n))) { |
| 655 | setnilvalue(gval(n)); /* remove value ... */ |
| 656 | removeentry(n); /* and remove entry from table */ |
| 657 | } |
| 658 | } |
| 659 | } |
| 653 | 660 | } |
| 654 | 661 | |
| 655 | 662 | |
| 656 | 663 | static void freeobj (lua_State *L, GCObject *o) { |
| 657 | | switch (gch(o)->tt) { |
| 658 | | case LUA_TPROTO: luaF_freeproto(L, gco2p(o)); break; |
| 659 | | case LUA_TLCL: { |
| 660 | | luaM_freemem(L, o, sizeLclosure(gco2lcl(o)->nupvalues)); |
| 661 | | break; |
| 662 | | } |
| 663 | | case LUA_TCCL: { |
| 664 | | luaM_freemem(L, o, sizeCclosure(gco2ccl(o)->nupvalues)); |
| 665 | | break; |
| 666 | | } |
| 667 | | case LUA_TUPVAL: luaF_freeupval(L, gco2uv(o)); break; |
| 668 | | case LUA_TTABLE: luaH_free(L, gco2t(o)); break; |
| 669 | | case LUA_TTHREAD: luaE_freethread(L, gco2th(o)); break; |
| 670 | | case LUA_TUSERDATA: luaM_freemem(L, o, sizeudata(gco2u(o))); break; |
| 671 | | case LUA_TSHRSTR: |
| 672 | | G(L)->strt.nuse--; |
| 673 | | /* go through */ |
| 674 | | case LUA_TLNGSTR: { |
| 675 | | luaM_freemem(L, o, sizestring(gco2ts(o))); |
| 676 | | break; |
| 677 | | } |
| 678 | | default: lua_assert(0); |
| 679 | | } |
| 664 | switch (gch(o)->tt) { |
| 665 | case LUA_TPROTO: luaF_freeproto(L, gco2p(o)); break; |
| 666 | case LUA_TLCL: { |
| 667 | luaM_freemem(L, o, sizeLclosure(gco2lcl(o)->nupvalues)); |
| 668 | break; |
| 669 | } |
| 670 | case LUA_TCCL: { |
| 671 | luaM_freemem(L, o, sizeCclosure(gco2ccl(o)->nupvalues)); |
| 672 | break; |
| 673 | } |
| 674 | case LUA_TUPVAL: luaF_freeupval(L, gco2uv(o)); break; |
| 675 | case LUA_TTABLE: luaH_free(L, gco2t(o)); break; |
| 676 | case LUA_TTHREAD: luaE_freethread(L, gco2th(o)); break; |
| 677 | case LUA_TUSERDATA: luaM_freemem(L, o, sizeudata(gco2u(o))); break; |
| 678 | case LUA_TSHRSTR: |
| 679 | G(L)->strt.nuse--; |
| 680 | /* go through */ |
| 681 | case LUA_TLNGSTR: { |
| 682 | luaM_freemem(L, o, sizestring(gco2ts(o))); |
| 683 | break; |
| 684 | } |
| 685 | default: lua_assert(0); |
| 686 | } |
| 680 | 687 | } |
| 681 | 688 | |
| 682 | 689 | |
| 683 | | #define sweepwholelist(L,p) sweeplist(L,p,MAX_LUMEM) |
| 690 | #define sweepwholelist(L,p) sweeplist(L,p,MAX_LUMEM) |
| 684 | 691 | static GCObject **sweeplist (lua_State *L, GCObject **p, lu_mem count); |
| 685 | 692 | |
| 686 | 693 | |
| r30857 | r30858 | |
| 689 | 696 | ** list of call-info structures. |
| 690 | 697 | */ |
| 691 | 698 | static void sweepthread (lua_State *L, lua_State *L1) { |
| 692 | | if (L1->stack == NULL) return; /* stack not completely built yet */ |
| 693 | | sweepwholelist(L, &L1->openupval); /* sweep open upvalues */ |
| 694 | | luaE_freeCI(L1); /* free extra CallInfo slots */ |
| 695 | | /* should not change the stack during an emergency gc cycle */ |
| 696 | | if (G(L)->gckind != KGC_EMERGENCY) |
| 697 | | luaD_shrinkstack(L1); |
| 699 | if (L1->stack == NULL) return; /* stack not completely built yet */ |
| 700 | sweepwholelist(L, &L1->openupval); /* sweep open upvalues */ |
| 701 | luaE_freeCI(L1); /* free extra CallInfo slots */ |
| 702 | /* should not change the stack during an emergency gc cycle */ |
| 703 | if (G(L)->gckind != KGC_EMERGENCY) |
| 704 | luaD_shrinkstack(L1); |
| 698 | 705 | } |
| 699 | 706 | |
| 700 | 707 | |
| r30857 | r30858 | |
| 710 | 717 | ** When object is a thread, sweep its list of open upvalues too. |
| 711 | 718 | */ |
| 712 | 719 | static GCObject **sweeplist (lua_State *L, GCObject **p, lu_mem count) { |
| 713 | | global_State *g = G(L); |
| 714 | | int ow = otherwhite(g); |
| 715 | | int toclear, toset; /* bits to clear and to set in all live objects */ |
| 716 | | int tostop; /* stop sweep when this is true */ |
| 717 | | if (isgenerational(g)) { /* generational mode? */ |
| 718 | | toclear = ~0; /* clear nothing */ |
| 719 | | toset = bitmask(OLDBIT); /* set the old bit of all surviving objects */ |
| 720 | | tostop = bitmask(OLDBIT); /* do not sweep old generation */ |
| 721 | | } |
| 722 | | else { /* normal mode */ |
| 723 | | toclear = maskcolors; /* clear all color bits + old bit */ |
| 724 | | toset = luaC_white(g); /* make object white */ |
| 725 | | tostop = 0; /* do not stop */ |
| 726 | | } |
| 727 | | while (*p != NULL && count-- > 0) { |
| 728 | | GCObject *curr = *p; |
| 729 | | int marked = gch(curr)->marked; |
| 730 | | if (isdeadm(ow, marked)) { /* is 'curr' dead? */ |
| 731 | | *p = gch(curr)->next; /* remove 'curr' from list */ |
| 732 | | freeobj(L, curr); /* erase 'curr' */ |
| 733 | | } |
| 734 | | else { |
| 735 | | if (testbits(marked, tostop)) |
| 736 | | return NULL; /* stop sweeping this list */ |
| 737 | | if (gch(curr)->tt == LUA_TTHREAD) |
| 738 | | sweepthread(L, gco2th(curr)); /* sweep thread's upvalues */ |
| 739 | | /* update marks */ |
| 740 | | gch(curr)->marked = cast_byte((marked & toclear) | toset); |
| 741 | | p = &gch(curr)->next; /* go to next element */ |
| 742 | | } |
| 743 | | } |
| 744 | | return (*p == NULL) ? NULL : p; |
| 720 | global_State *g = G(L); |
| 721 | int ow = otherwhite(g); |
| 722 | int toclear, toset; /* bits to clear and to set in all live objects */ |
| 723 | int tostop; /* stop sweep when this is true */ |
| 724 | if (isgenerational(g)) { /* generational mode? */ |
| 725 | toclear = ~0; /* clear nothing */ |
| 726 | toset = bitmask(OLDBIT); /* set the old bit of all surviving objects */ |
| 727 | tostop = bitmask(OLDBIT); /* do not sweep old generation */ |
| 728 | } |
| 729 | else { /* normal mode */ |
| 730 | toclear = maskcolors; /* clear all color bits + old bit */ |
| 731 | toset = luaC_white(g); /* make object white */ |
| 732 | tostop = 0; /* do not stop */ |
| 733 | } |
| 734 | while (*p != NULL && count-- > 0) { |
| 735 | GCObject *curr = *p; |
| 736 | int marked = gch(curr)->marked; |
| 737 | if (isdeadm(ow, marked)) { /* is 'curr' dead? */ |
| 738 | *p = gch(curr)->next; /* remove 'curr' from list */ |
| 739 | freeobj(L, curr); /* erase 'curr' */ |
| 740 | } |
| 741 | else { |
| 742 | if (testbits(marked, tostop)) |
| 743 | return NULL; /* stop sweeping this list */ |
| 744 | if (gch(curr)->tt == LUA_TTHREAD) |
| 745 | sweepthread(L, gco2th(curr)); /* sweep thread's upvalues */ |
| 746 | /* update marks */ |
| 747 | gch(curr)->marked = cast_byte((marked & toclear) | toset); |
| 748 | p = &gch(curr)->next; /* go to next element */ |
| 749 | } |
| 750 | } |
| 751 | return (*p == NULL) ? NULL : p; |
| 745 | 752 | } |
| 746 | 753 | |
| 747 | 754 | |
| r30857 | r30858 | |
| 749 | 756 | ** sweep a list until a live object (or end of list) |
| 750 | 757 | */ |
| 751 | 758 | static GCObject **sweeptolive (lua_State *L, GCObject **p, int *n) { |
| 752 | | GCObject ** old = p; |
| 753 | | int i = 0; |
| 754 | | do { |
| 755 | | i++; |
| 756 | | p = sweeplist(L, p, 1); |
| 757 | | } while (p == old); |
| 758 | | if (n) *n += i; |
| 759 | | return p; |
| 759 | GCObject ** old = p; |
| 760 | int i = 0; |
| 761 | do { |
| 762 | i++; |
| 763 | p = sweeplist(L, p, 1); |
| 764 | } while (p == old); |
| 765 | if (n) *n += i; |
| 766 | return p; |
| 760 | 767 | } |
| 761 | 768 | |
| 762 | 769 | /* }====================================================== */ |
| r30857 | r30858 | |
| 769 | 776 | */ |
| 770 | 777 | |
| 771 | 778 | static void checkSizes (lua_State *L) { |
| 772 | | global_State *g = G(L); |
| 773 | | if (g->gckind != KGC_EMERGENCY) { /* do not change sizes in emergency */ |
| 774 | | int hs = g->strt.size / 2; /* half the size of the string table */ |
| 775 | | if (g->strt.nuse < cast(lu_int32, hs)) /* using less than that half? */ |
| 776 | | luaS_resize(L, hs); /* halve its size */ |
| 777 | | luaZ_freebuffer(L, &g->buff); /* free concatenation buffer */ |
| 778 | | } |
| 779 | global_State *g = G(L); |
| 780 | if (g->gckind != KGC_EMERGENCY) { /* do not change sizes in emergency */ |
| 781 | int hs = g->strt.size / 2; /* half the size of the string table */ |
| 782 | if (g->strt.nuse < cast(lu_int32, hs)) /* using less than that half? */ |
| 783 | luaS_resize(L, hs); /* halve its size */ |
| 784 | luaZ_freebuffer(L, &g->buff); /* free concatenation buffer */ |
| 785 | } |
| 779 | 786 | } |
| 780 | 787 | |
| 781 | 788 | |
| 782 | 789 | static GCObject *udata2finalize (global_State *g) { |
| 783 | | GCObject *o = g->tobefnz; /* get first element */ |
| 784 | | lua_assert(isfinalized(o)); |
| 785 | | g->tobefnz = gch(o)->next; /* remove it from 'tobefnz' list */ |
| 786 | | gch(o)->next = g->allgc; /* return it to 'allgc' list */ |
| 787 | | g->allgc = o; |
| 788 | | resetbit(gch(o)->marked, SEPARATED); /* mark that it is not in 'tobefnz' */ |
| 789 | | lua_assert(!isold(o)); /* see MOVE OLD rule */ |
| 790 | | if (!keepinvariantout(g)) /* not keeping invariant? */ |
| 791 | | makewhite(g, o); /* "sweep" object */ |
| 792 | | return o; |
| 790 | GCObject *o = g->tobefnz; /* get first element */ |
| 791 | lua_assert(isfinalized(o)); |
| 792 | g->tobefnz = gch(o)->next; /* remove it from 'tobefnz' list */ |
| 793 | gch(o)->next = g->allgc; /* return it to 'allgc' list */ |
| 794 | g->allgc = o; |
| 795 | resetbit(gch(o)->marked, SEPARATED); /* mark that it is not in 'tobefnz' */ |
| 796 | lua_assert(!isold(o)); /* see MOVE OLD rule */ |
| 797 | if (!keepinvariantout(g)) /* not keeping invariant? */ |
| 798 | makewhite(g, o); /* "sweep" object */ |
| 799 | return o; |
| 793 | 800 | } |
| 794 | 801 | |
| 795 | 802 | |
| 796 | 803 | static void dothecall (lua_State *L, void *ud) { |
| 797 | | UNUSED(ud); |
| 798 | | luaD_call(L, L->top - 2, 0, 0); |
| 804 | UNUSED(ud); |
| 805 | luaD_call(L, L->top - 2, 0, 0); |
| 799 | 806 | } |
| 800 | 807 | |
| 801 | 808 | |
| 802 | 809 | static void GCTM (lua_State *L, int propagateerrors) { |
| 803 | | global_State *g = G(L); |
| 804 | | const TValue *tm; |
| 805 | | TValue v; |
| 806 | | setgcovalue(L, &v, udata2finalize(g)); |
| 807 | | tm = luaT_gettmbyobj(L, &v, TM_GC); |
| 808 | | if (tm != NULL && ttisfunction(tm)) { /* is there a finalizer? */ |
| 809 | | int status; |
| 810 | | lu_byte oldah = L->allowhook; |
| 811 | | int running = g->gcrunning; |
| 812 | | L->allowhook = 0; /* stop debug hooks during GC metamethod */ |
| 813 | | g->gcrunning = 0; /* avoid GC steps */ |
| 814 | | setobj2s(L, L->top, tm); /* push finalizer... */ |
| 815 | | setobj2s(L, L->top + 1, &v); /* ... and its argument */ |
| 816 | | L->top += 2; /* and (next line) call the finalizer */ |
| 817 | | status = luaD_pcall(L, dothecall, NULL, savestack(L, L->top - 2), 0); |
| 818 | | L->allowhook = oldah; /* restore hooks */ |
| 819 | | g->gcrunning = running; /* restore state */ |
| 820 | | if (status != LUA_OK && propagateerrors) { /* error while running __gc? */ |
| 821 | | if (status == LUA_ERRRUN) { /* is there an error object? */ |
| 822 | | const char *msg = (ttisstring(L->top - 1)) |
| 823 | | ? svalue(L->top - 1) |
| 824 | | : "no message"; |
| 825 | | luaO_pushfstring(L, "error in __gc metamethod (%s)", msg); |
| 826 | | status = LUA_ERRGCMM; /* error in __gc metamethod */ |
| 827 | | } |
| 828 | | luaD_throw(L, status); /* re-throw error */ |
| 829 | | } |
| 830 | | } |
| 810 | global_State *g = G(L); |
| 811 | const TValue *tm; |
| 812 | TValue v; |
| 813 | setgcovalue(L, &v, udata2finalize(g)); |
| 814 | tm = luaT_gettmbyobj(L, &v, TM_GC); |
| 815 | if (tm != NULL && ttisfunction(tm)) { /* is there a finalizer? */ |
| 816 | int status; |
| 817 | lu_byte oldah = L->allowhook; |
| 818 | int running = g->gcrunning; |
| 819 | L->allowhook = 0; /* stop debug hooks during GC metamethod */ |
| 820 | g->gcrunning = 0; /* avoid GC steps */ |
| 821 | setobj2s(L, L->top, tm); /* push finalizer... */ |
| 822 | setobj2s(L, L->top + 1, &v); /* ... and its argument */ |
| 823 | L->top += 2; /* and (next line) call the finalizer */ |
| 824 | status = luaD_pcall(L, dothecall, NULL, savestack(L, L->top - 2), 0); |
| 825 | L->allowhook = oldah; /* restore hooks */ |
| 826 | g->gcrunning = running; /* restore state */ |
| 827 | if (status != LUA_OK && propagateerrors) { /* error while running __gc? */ |
| 828 | if (status == LUA_ERRRUN) { /* is there an error object? */ |
| 829 | const char *msg = (ttisstring(L->top - 1)) |
| 830 | ? svalue(L->top - 1) |
| 831 | : "no message"; |
| 832 | luaO_pushfstring(L, "error in __gc metamethod (%s)", msg); |
| 833 | status = LUA_ERRGCMM; /* error in __gc metamethod */ |
| 834 | } |
| 835 | luaD_throw(L, status); /* re-throw error */ |
| 836 | } |
| 837 | } |
| 831 | 838 | } |
| 832 | 839 | |
| 833 | 840 | |
| r30857 | r30858 | |
| 836 | 843 | ** finalization from list 'finobj' to list 'tobefnz' (to be finalized) |
| 837 | 844 | */ |
| 838 | 845 | static void separatetobefnz (lua_State *L, int all) { |
| 839 | | global_State *g = G(L); |
| 840 | | GCObject **p = &g->finobj; |
| 841 | | GCObject *curr; |
| 842 | | GCObject **lastnext = &g->tobefnz; |
| 843 | | /* find last 'next' field in 'tobefnz' list (to add elements in its end) */ |
| 844 | | while (*lastnext != NULL) |
| 845 | | lastnext = &gch(*lastnext)->next; |
| 846 | | while ((curr = *p) != NULL) { /* traverse all finalizable objects */ |
| 847 | | lua_assert(!isfinalized(curr)); |
| 848 | | lua_assert(testbit(gch(curr)->marked, SEPARATED)); |
| 849 | | if (!(iswhite(curr) || all)) /* not being collected? */ |
| 850 | | p = &gch(curr)->next; /* don't bother with it */ |
| 851 | | else { |
| 852 | | l_setbit(gch(curr)->marked, FINALIZEDBIT); /* won't be finalized again */ |
| 853 | | *p = gch(curr)->next; /* remove 'curr' from 'finobj' list */ |
| 854 | | gch(curr)->next = *lastnext; /* link at the end of 'tobefnz' list */ |
| 855 | | *lastnext = curr; |
| 856 | | lastnext = &gch(curr)->next; |
| 857 | | } |
| 858 | | } |
| 846 | global_State *g = G(L); |
| 847 | GCObject **p = &g->finobj; |
| 848 | GCObject *curr; |
| 849 | GCObject **lastnext = &g->tobefnz; |
| 850 | /* find last 'next' field in 'tobefnz' list (to add elements in its end) */ |
| 851 | while (*lastnext != NULL) |
| 852 | lastnext = &gch(*lastnext)->next; |
| 853 | while ((curr = *p) != NULL) { /* traverse all finalizable objects */ |
| 854 | lua_assert(!isfinalized(curr)); |
| 855 | lua_assert(testbit(gch(curr)->marked, SEPARATED)); |
| 856 | if (!(iswhite(curr) || all)) /* not being collected? */ |
| 857 | p = &gch(curr)->next; /* don't bother with it */ |
| 858 | else { |
| 859 | l_setbit(gch(curr)->marked, FINALIZEDBIT); /* won't be finalized again */ |
| 860 | *p = gch(curr)->next; /* remove 'curr' from 'finobj' list */ |
| 861 | gch(curr)->next = *lastnext; /* link at the end of 'tobefnz' list */ |
| 862 | *lastnext = curr; |
| 863 | lastnext = &gch(curr)->next; |
| 864 | } |
| 865 | } |
| 859 | 866 | } |
| 860 | 867 | |
| 861 | 868 | |
| r30857 | r30858 | |
| 864 | 871 | ** search the list to find it) and link it in 'finobj' list. |
| 865 | 872 | */ |
| 866 | 873 | void luaC_checkfinalizer (lua_State *L, GCObject *o, Table *mt) { |
| 867 | | global_State *g = G(L); |
| 868 | | if (testbit(gch(o)->marked, SEPARATED) || /* obj. is already separated... */ |
| 869 | | isfinalized(o) || /* ... or is finalized... */ |
| 870 | | gfasttm(g, mt, TM_GC) == NULL) /* or has no finalizer? */ |
| 871 | | return; /* nothing to be done */ |
| 872 | | else { /* move 'o' to 'finobj' list */ |
| 873 | | GCObject **p; |
| 874 | | GCheader *ho = gch(o); |
| 875 | | if (g->sweepgc == &ho->next) { /* avoid removing current sweep object */ |
| 876 | | lua_assert(issweepphase(g)); |
| 877 | | g->sweepgc = sweeptolive(L, g->sweepgc, NULL); |
| 878 | | } |
| 879 | | /* search for pointer pointing to 'o' */ |
| 880 | | for (p = &g->allgc; *p != o; p = &gch(*p)->next) { /* empty */ } |
| 881 | | *p = ho->next; /* remove 'o' from root list */ |
| 882 | | ho->next = g->finobj; /* link it in list 'finobj' */ |
| 883 | | g->finobj = o; |
| 884 | | l_setbit(ho->marked, SEPARATED); /* mark it as such */ |
| 885 | | if (!keepinvariantout(g)) /* not keeping invariant? */ |
| 886 | | makewhite(g, o); /* "sweep" object */ |
| 887 | | else |
| 888 | | resetoldbit(o); /* see MOVE OLD rule */ |
| 889 | | } |
| 874 | global_State *g = G(L); |
| 875 | if (testbit(gch(o)->marked, SEPARATED) || /* obj. is already separated... */ |
| 876 | isfinalized(o) || /* ... or is finalized... */ |
| 877 | gfasttm(g, mt, TM_GC) == NULL) /* or has no finalizer? */ |
| 878 | return; /* nothing to be done */ |
| 879 | else { /* move 'o' to 'finobj' list */ |
| 880 | GCObject **p; |
| 881 | GCheader *ho = gch(o); |
| 882 | if (g->sweepgc == &ho->next) { /* avoid removing current sweep object */ |
| 883 | lua_assert(issweepphase(g)); |
| 884 | g->sweepgc = sweeptolive(L, g->sweepgc, NULL); |
| 885 | } |
| 886 | /* search for pointer pointing to 'o' */ |
| 887 | for (p = &g->allgc; *p != o; p = &gch(*p)->next) { /* empty */ } |
| 888 | *p = ho->next; /* remove 'o' from root list */ |
| 889 | ho->next = g->finobj; /* link it in list 'finobj' */ |
| 890 | g->finobj = o; |
| 891 | l_setbit(ho->marked, SEPARATED); /* mark it as such */ |
| 892 | if (!keepinvariantout(g)) /* not keeping invariant? */ |
| 893 | makewhite(g, o); /* "sweep" object */ |
| 894 | else |
| 895 | resetoldbit(o); /* see MOVE OLD rule */ |
| 896 | } |
| 890 | 897 | } |
| 891 | 898 | |
| 892 | 899 | /* }====================================================== */ |
| r30857 | r30858 | |
| 904 | 911 | ** cycle will start when memory use hits threshold |
| 905 | 912 | */ |
| 906 | 913 | static void setpause (global_State *g, l_mem estimate) { |
| 907 | | l_mem debt, threshold; |
| 908 | | estimate = estimate / PAUSEADJ; /* adjust 'estimate' */ |
| 909 | | threshold = (g->gcpause < MAX_LMEM / estimate) /* overflow? */ |
| 910 | | ? estimate * g->gcpause /* no overflow */ |
| 911 | | : MAX_LMEM; /* overflow; truncate to maximum */ |
| 912 | | debt = -cast(l_mem, threshold - gettotalbytes(g)); |
| 913 | | luaE_setdebt(g, debt); |
| 914 | l_mem debt, threshold; |
| 915 | estimate = estimate / PAUSEADJ; /* adjust 'estimate' */ |
| 916 | threshold = (g->gcpause < MAX_LMEM / estimate) /* overflow? */ |
| 917 | ? estimate * g->gcpause /* no overflow */ |
| 918 | : MAX_LMEM; /* overflow; truncate to maximum */ |
| 919 | debt = -cast(l_mem, threshold - gettotalbytes(g)); |
| 920 | luaE_setdebt(g, debt); |
| 914 | 921 | } |
| 915 | 922 | |
| 916 | 923 | |
| r30857 | r30858 | |
| 927 | 934 | ** Returns how many objects it swept. |
| 928 | 935 | */ |
| 929 | 936 | static int entersweep (lua_State *L) { |
| 930 | | global_State *g = G(L); |
| 931 | | int n = 0; |
| 932 | | g->gcstate = GCSsweepstring; |
| 933 | | lua_assert(g->sweepgc == NULL && g->sweepfin == NULL); |
| 934 | | /* prepare to sweep strings, finalizable objects, and regular objects */ |
| 935 | | g->sweepstrgc = 0; |
| 936 | | g->sweepfin = sweeptolive(L, &g->finobj, &n); |
| 937 | | g->sweepgc = sweeptolive(L, &g->allgc, &n); |
| 938 | | return n; |
| 937 | global_State *g = G(L); |
| 938 | int n = 0; |
| 939 | g->gcstate = GCSsweepstring; |
| 940 | lua_assert(g->sweepgc == NULL && g->sweepfin == NULL); |
| 941 | /* prepare to sweep strings, finalizable objects, and regular objects */ |
| 942 | g->sweepstrgc = 0; |
| 943 | g->sweepfin = sweeptolive(L, &g->finobj, &n); |
| 944 | g->sweepgc = sweeptolive(L, &g->allgc, &n); |
| 945 | return n; |
| 939 | 946 | } |
| 940 | 947 | |
| 941 | 948 | |
| r30857 | r30858 | |
| 943 | 950 | ** change GC mode |
| 944 | 951 | */ |
| 945 | 952 | void luaC_changemode (lua_State *L, int mode) { |
| 946 | | global_State *g = G(L); |
| 947 | | if (mode == g->gckind) return; /* nothing to change */ |
| 948 | | if (mode == KGC_GEN) { /* change to generational mode */ |
| 949 | | /* make sure gray lists are consistent */ |
| 950 | | luaC_runtilstate(L, bitmask(GCSpropagate)); |
| 951 | | g->GCestimate = gettotalbytes(g); |
| 952 | | g->gckind = KGC_GEN; |
| 953 | | } |
| 954 | | else { /* change to incremental mode */ |
| 955 | | /* sweep all objects to turn them back to white |
| 956 | | (as white has not changed, nothing extra will be collected) */ |
| 957 | | g->gckind = KGC_NORMAL; |
| 958 | | entersweep(L); |
| 959 | | luaC_runtilstate(L, ~sweepphases); |
| 960 | | } |
| 953 | global_State *g = G(L); |
| 954 | if (mode == g->gckind) return; /* nothing to change */ |
| 955 | if (mode == KGC_GEN) { /* change to generational mode */ |
| 956 | /* make sure gray lists are consistent */ |
| 957 | luaC_runtilstate(L, bitmask(GCSpropagate)); |
| 958 | g->GCestimate = gettotalbytes(g); |
| 959 | g->gckind = KGC_GEN; |
| 960 | } |
| 961 | else { /* change to incremental mode */ |
| 962 | /* sweep all objects to turn them back to white |
| 963 | (as white has not changed, nothing extra will be collected) */ |
| 964 | g->gckind = KGC_NORMAL; |
| 965 | entersweep(L); |
| 966 | luaC_runtilstate(L, ~sweepphases); |
| 967 | } |
| 961 | 968 | } |
| 962 | 969 | |
| 963 | 970 | |
| r30857 | r30858 | |
| 965 | 972 | ** call all pending finalizers |
| 966 | 973 | */ |
| 967 | 974 | static void callallpendingfinalizers (lua_State *L, int propagateerrors) { |
| 968 | | global_State *g = G(L); |
| 969 | | while (g->tobefnz) { |
| 970 | | resetoldbit(g->tobefnz); |
| 971 | | GCTM(L, propagateerrors); |
| 972 | | } |
| 975 | global_State *g = G(L); |
| 976 | while (g->tobefnz) { |
| 977 | resetoldbit(g->tobefnz); |
| 978 | GCTM(L, propagateerrors); |
| 979 | } |
| 973 | 980 | } |
| 974 | 981 | |
| 975 | 982 | |
| 976 | 983 | void luaC_freeallobjects (lua_State *L) { |
| 977 | | global_State *g = G(L); |
| 978 | | int i; |
| 979 | | separatetobefnz(L, 1); /* separate all objects with finalizers */ |
| 980 | | lua_assert(g->finobj == NULL); |
| 981 | | callallpendingfinalizers(L, 0); |
| 982 | | g->currentwhite = WHITEBITS; /* this "white" makes all objects look dead */ |
| 983 | | g->gckind = KGC_NORMAL; |
| 984 | | sweepwholelist(L, &g->finobj); /* finalizers can create objs. in 'finobj' */ |
| 985 | | sweepwholelist(L, &g->allgc); |
| 986 | | for (i = 0; i < g->strt.size; i++) /* free all string lists */ |
| 987 | | sweepwholelist(L, &g->strt.hash[i]); |
| 988 | | lua_assert(g->strt.nuse == 0); |
| 984 | global_State *g = G(L); |
| 985 | int i; |
| 986 | separatetobefnz(L, 1); /* separate all objects with finalizers */ |
| 987 | lua_assert(g->finobj == NULL); |
| 988 | callallpendingfinalizers(L, 0); |
| 989 | g->currentwhite = WHITEBITS; /* this "white" makes all objects look dead */ |
| 990 | g->gckind = KGC_NORMAL; |
| 991 | sweepwholelist(L, &g->finobj); /* finalizers can create objs. in 'finobj' */ |
| 992 | sweepwholelist(L, &g->allgc); |
| 993 | for (i = 0; i < g->strt.size; i++) /* free all string lists */ |
| 994 | sweepwholelist(L, &g->strt.hash[i]); |
| 995 | lua_assert(g->strt.nuse == 0); |
| 989 | 996 | } |
| 990 | 997 | |
| 991 | 998 | |
| 992 | 999 | static l_mem atomic (lua_State *L) { |
| 993 | | global_State *g = G(L); |
| 994 | | l_mem work = -cast(l_mem, g->GCmemtrav); /* start counting work */ |
| 995 | | GCObject *origweak, *origall; |
| 996 | | lua_assert(!iswhite(obj2gco(g->mainthread))); |
| 997 | | markobject(g, L); /* mark running thread */ |
| 998 | | /* registry and global metatables may be changed by API */ |
| 999 | | markvalue(g, &g->l_registry); |
| 1000 | | markmt(g); /* mark basic metatables */ |
| 1001 | | /* remark occasional upvalues of (maybe) dead threads */ |
| 1002 | | remarkupvals(g); |
| 1003 | | propagateall(g); /* propagate changes */ |
| 1004 | | work += g->GCmemtrav; /* stop counting (do not (re)count grays) */ |
| 1005 | | /* traverse objects caught by write barrier and by 'remarkupvals' */ |
| 1006 | | retraversegrays(g); |
| 1007 | | work -= g->GCmemtrav; /* restart counting */ |
| 1008 | | convergeephemerons(g); |
| 1009 | | /* at this point, all strongly accessible objects are marked. */ |
| 1010 | | /* clear values from weak tables, before checking finalizers */ |
| 1011 | | clearvalues(g, g->weak, NULL); |
| 1012 | | clearvalues(g, g->allweak, NULL); |
| 1013 | | origweak = g->weak; origall = g->allweak; |
| 1014 | | work += g->GCmemtrav; /* stop counting (objects being finalized) */ |
| 1015 | | separatetobefnz(L, 0); /* separate objects to be finalized */ |
| 1016 | | markbeingfnz(g); /* mark objects that will be finalized */ |
| 1017 | | propagateall(g); /* remark, to propagate `preserveness' */ |
| 1018 | | work -= g->GCmemtrav; /* restart counting */ |
| 1019 | | convergeephemerons(g); |
| 1020 | | /* at this point, all resurrected objects are marked. */ |
| 1021 | | /* remove dead objects from weak tables */ |
| 1022 | | clearkeys(g, g->ephemeron, NULL); /* clear keys from all ephemeron tables */ |
| 1023 | | clearkeys(g, g->allweak, NULL); /* clear keys from all allweak tables */ |
| 1024 | | /* clear values from resurrected weak tables */ |
| 1025 | | clearvalues(g, g->weak, origweak); |
| 1026 | | clearvalues(g, g->allweak, origall); |
| 1027 | | g->currentwhite = cast_byte(otherwhite(g)); /* flip current white */ |
| 1028 | | work += g->GCmemtrav; /* complete counting */ |
| 1029 | | return work; /* estimate of memory marked by 'atomic' */ |
| 1000 | global_State *g = G(L); |
| 1001 | l_mem work = -cast(l_mem, g->GCmemtrav); /* start counting work */ |
| 1002 | GCObject *origweak, *origall; |
| 1003 | lua_assert(!iswhite(obj2gco(g->mainthread))); |
| 1004 | markobject(g, L); /* mark running thread */ |
| 1005 | /* registry and global metatables may be changed by API */ |
| 1006 | markvalue(g, &g->l_registry); |
| 1007 | markmt(g); /* mark basic metatables */ |
| 1008 | /* remark occasional upvalues of (maybe) dead threads */ |
| 1009 | remarkupvals(g); |
| 1010 | propagateall(g); /* propagate changes */ |
| 1011 | work += g->GCmemtrav; /* stop counting (do not (re)count grays) */ |
| 1012 | /* traverse objects caught by write barrier and by 'remarkupvals' */ |
| 1013 | retraversegrays(g); |
| 1014 | work -= g->GCmemtrav; /* restart counting */ |
| 1015 | convergeephemerons(g); |
| 1016 | /* at this point, all strongly accessible objects are marked. */ |
| 1017 | /* clear values from weak tables, before checking finalizers */ |
| 1018 | clearvalues(g, g->weak, NULL); |
| 1019 | clearvalues(g, g->allweak, NULL); |
| 1020 | origweak = g->weak; origall = g->allweak; |
| 1021 | work += g->GCmemtrav; /* stop counting (objects being finalized) */ |
| 1022 | separatetobefnz(L, 0); /* separate objects to be finalized */ |
| 1023 | markbeingfnz(g); /* mark objects that will be finalized */ |
| 1024 | propagateall(g); /* remark, to propagate `preserveness' */ |
| 1025 | work -= g->GCmemtrav; /* restart counting */ |
| 1026 | convergeephemerons(g); |
| 1027 | /* at this point, all resurrected objects are marked. */ |
| 1028 | /* remove dead objects from weak tables */ |
| 1029 | clearkeys(g, g->ephemeron, NULL); /* clear keys from all ephemeron tables */ |
| 1030 | clearkeys(g, g->allweak, NULL); /* clear keys from all allweak tables */ |
| 1031 | /* clear values from resurrected weak tables */ |
| 1032 | clearvalues(g, g->weak, origweak); |
| 1033 | clearvalues(g, g->allweak, origall); |
| 1034 | g->currentwhite = cast_byte(otherwhite(g)); /* flip current white */ |
| 1035 | work += g->GCmemtrav; /* complete counting */ |
| 1036 | return work; /* estimate of memory marked by 'atomic' */ |
| 1030 | 1037 | } |
| 1031 | 1038 | |
| 1032 | 1039 | |
| 1033 | 1040 | static lu_mem singlestep (lua_State *L) { |
| 1034 | | global_State *g = G(L); |
| 1035 | | switch (g->gcstate) { |
| 1036 | | case GCSpause: { |
| 1037 | | /* start to count memory traversed */ |
| 1038 | | g->GCmemtrav = g->strt.size * sizeof(GCObject*); |
| 1039 | | lua_assert(!isgenerational(g)); |
| 1040 | | restartcollection(g); |
| 1041 | | g->gcstate = GCSpropagate; |
| 1042 | | return g->GCmemtrav; |
| 1043 | | } |
| 1044 | | case GCSpropagate: { |
| 1045 | | if (g->gray) { |
| 1046 | | lu_mem oldtrav = g->GCmemtrav; |
| 1047 | | propagatemark(g); |
| 1048 | | return g->GCmemtrav - oldtrav; /* memory traversed in this step */ |
| 1049 | | } |
| 1050 | | else { /* no more `gray' objects */ |
| 1051 | | lu_mem work; |
| 1052 | | int sw; |
| 1053 | | g->gcstate = GCSatomic; /* finish mark phase */ |
| 1054 | | g->GCestimate = g->GCmemtrav; /* save what was counted */; |
| 1055 | | work = atomic(L); /* add what was traversed by 'atomic' */ |
| 1056 | | g->GCestimate += work; /* estimate of total memory traversed */ |
| 1057 | | sw = entersweep(L); |
| 1058 | | return work + sw * GCSWEEPCOST; |
| 1059 | | } |
| 1060 | | } |
| 1061 | | case GCSsweepstring: { |
| 1062 | | int i; |
| 1063 | | for (i = 0; i < GCSWEEPMAX && g->sweepstrgc + i < g->strt.size; i++) |
| 1064 | | sweepwholelist(L, &g->strt.hash[g->sweepstrgc + i]); |
| 1065 | | g->sweepstrgc += i; |
| 1066 | | if (g->sweepstrgc >= g->strt.size) /* no more strings to sweep? */ |
| 1067 | | g->gcstate = GCSsweepudata; |
| 1068 | | return i * GCSWEEPCOST; |
| 1069 | | } |
| 1070 | | case GCSsweepudata: { |
| 1071 | | if (g->sweepfin) { |
| 1072 | | g->sweepfin = sweeplist(L, g->sweepfin, GCSWEEPMAX); |
| 1073 | | return GCSWEEPMAX*GCSWEEPCOST; |
| 1074 | | } |
| 1075 | | else { |
| 1076 | | g->gcstate = GCSsweep; |
| 1077 | | return 0; |
| 1078 | | } |
| 1079 | | } |
| 1080 | | case GCSsweep: { |
| 1081 | | if (g->sweepgc) { |
| 1082 | | g->sweepgc = sweeplist(L, g->sweepgc, GCSWEEPMAX); |
| 1083 | | return GCSWEEPMAX*GCSWEEPCOST; |
| 1084 | | } |
| 1085 | | else { |
| 1086 | | /* sweep main thread */ |
| 1087 | | GCObject *mt = obj2gco(g->mainthread); |
| 1088 | | sweeplist(L, &mt, 1); |
| 1089 | | checkSizes(L); |
| 1090 | | g->gcstate = GCSpause; /* finish collection */ |
| 1091 | | return GCSWEEPCOST; |
| 1092 | | } |
| 1093 | | } |
| 1094 | | default: lua_assert(0); return 0; |
| 1095 | | } |
| 1041 | global_State *g = G(L); |
| 1042 | switch (g->gcstate) { |
| 1043 | case GCSpause: { |
| 1044 | /* start to count memory traversed */ |
| 1045 | g->GCmemtrav = g->strt.size * sizeof(GCObject*); |
| 1046 | lua_assert(!isgenerational(g)); |
| 1047 | restartcollection(g); |
| 1048 | g->gcstate = GCSpropagate; |
| 1049 | return g->GCmemtrav; |
| 1050 | } |
| 1051 | case GCSpropagate: { |
| 1052 | if (g->gray) { |
| 1053 | lu_mem oldtrav = g->GCmemtrav; |
| 1054 | propagatemark(g); |
| 1055 | return g->GCmemtrav - oldtrav; /* memory traversed in this step */ |
| 1056 | } |
| 1057 | else { /* no more `gray' objects */ |
| 1058 | lu_mem work; |
| 1059 | int sw; |
| 1060 | g->gcstate = GCSatomic; /* finish mark phase */ |
| 1061 | g->GCestimate = g->GCmemtrav; /* save what was counted */; |
| 1062 | work = atomic(L); /* add what was traversed by 'atomic' */ |
| 1063 | g->GCestimate += work; /* estimate of total memory traversed */ |
| 1064 | sw = entersweep(L); |
| 1065 | return work + sw * GCSWEEPCOST; |
| 1066 | } |
| 1067 | } |
| 1068 | case GCSsweepstring: { |
| 1069 | int i; |
| 1070 | for (i = 0; i < GCSWEEPMAX && g->sweepstrgc + i < g->strt.size; i++) |
| 1071 | sweepwholelist(L, &g->strt.hash[g->sweepstrgc + i]); |
| 1072 | g->sweepstrgc += i; |
| 1073 | if (g->sweepstrgc >= g->strt.size) /* no more strings to sweep? */ |
| 1074 | g->gcstate = GCSsweepudata; |
| 1075 | return i * GCSWEEPCOST; |
| 1076 | } |
| 1077 | case GCSsweepudata: { |
| 1078 | if (g->sweepfin) { |
| 1079 | g->sweepfin = sweeplist(L, g->sweepfin, GCSWEEPMAX); |
| 1080 | return GCSWEEPMAX*GCSWEEPCOST; |
| 1081 | } |
| 1082 | else { |
| 1083 | g->gcstate = GCSsweep; |
| 1084 | return 0; |
| 1085 | } |
| 1086 | } |
| 1087 | case GCSsweep: { |
| 1088 | if (g->sweepgc) { |
| 1089 | g->sweepgc = sweeplist(L, g->sweepgc, GCSWEEPMAX); |
| 1090 | return GCSWEEPMAX*GCSWEEPCOST; |
| 1091 | } |
| 1092 | else { |
| 1093 | /* sweep main thread */ |
| 1094 | GCObject *mt = obj2gco(g->mainthread); |
| 1095 | sweeplist(L, &mt, 1); |
| 1096 | checkSizes(L); |
| 1097 | g->gcstate = GCSpause; /* finish collection */ |
| 1098 | return GCSWEEPCOST; |
| 1099 | } |
| 1100 | } |
| 1101 | default: lua_assert(0); return 0; |
| 1102 | } |
| 1096 | 1103 | } |
| 1097 | 1104 | |
| 1098 | 1105 | |
| r30857 | r30858 | |
| 1101 | 1108 | ** by 'statemask' |
| 1102 | 1109 | */ |
| 1103 | 1110 | void luaC_runtilstate (lua_State *L, int statesmask) { |
| 1104 | | global_State *g = G(L); |
| 1105 | | while (!testbit(statesmask, g->gcstate)) |
| 1106 | | singlestep(L); |
| 1111 | global_State *g = G(L); |
| 1112 | while (!testbit(statesmask, g->gcstate)) |
| 1113 | singlestep(L); |
| 1107 | 1114 | } |
| 1108 | 1115 | |
| 1109 | 1116 | |
| 1110 | 1117 | static void generationalcollection (lua_State *L) { |
| 1111 | | global_State *g = G(L); |
| 1112 | | lua_assert(g->gcstate == GCSpropagate); |
| 1113 | | if (g->GCestimate == 0) { /* signal for another major collection? */ |
| 1114 | | luaC_fullgc(L, 0); /* perform a full regular collection */ |
| 1115 | | g->GCestimate = gettotalbytes(g); /* update control */ |
| 1116 | | } |
| 1117 | | else { |
| 1118 | | lu_mem estimate = g->GCestimate; |
| 1119 | | luaC_runtilstate(L, bitmask(GCSpause)); /* run complete (minor) cycle */ |
| 1120 | | g->gcstate = GCSpropagate; /* skip restart */ |
| 1121 | | if (gettotalbytes(g) > (estimate / 100) * g->gcmajorinc) |
| 1122 | | g->GCestimate = 0; /* signal for a major collection */ |
| 1123 | | else |
| 1124 | | g->GCestimate = estimate; /* keep estimate from last major coll. */ |
| 1118 | global_State *g = G(L); |
| 1119 | lua_assert(g->gcstate == GCSpropagate); |
| 1120 | if (g->GCestimate == 0) { /* signal for another major collection? */ |
| 1121 | luaC_fullgc(L, 0); /* perform a full regular collection */ |
| 1122 | g->GCestimate = gettotalbytes(g); /* update control */ |
| 1123 | } |
| 1124 | else { |
| 1125 | lu_mem estimate = g->GCestimate; |
| 1126 | luaC_runtilstate(L, bitmask(GCSpause)); /* run complete (minor) cycle */ |
| 1127 | g->gcstate = GCSpropagate; /* skip restart */ |
| 1128 | if (gettotalbytes(g) > (estimate / 100) * g->gcmajorinc) |
| 1129 | g->GCestimate = 0; /* signal for a major collection */ |
| 1130 | else |
| 1131 | g->GCestimate = estimate; /* keep estimate from last major coll. */ |
| 1125 | 1132 | |
| 1126 | | } |
| 1127 | | setpause(g, gettotalbytes(g)); |
| 1128 | | lua_assert(g->gcstate == GCSpropagate); |
| 1133 | } |
| 1134 | setpause(g, gettotalbytes(g)); |
| 1135 | lua_assert(g->gcstate == GCSpropagate); |
| 1129 | 1136 | } |
| 1130 | 1137 | |
| 1131 | 1138 | |
| 1132 | 1139 | static void incstep (lua_State *L) { |
| 1133 | | global_State *g = G(L); |
| 1134 | | l_mem debt = g->GCdebt; |
| 1135 | | int stepmul = g->gcstepmul; |
| 1136 | | if (stepmul < 40) stepmul = 40; /* avoid ridiculous low values (and 0) */ |
| 1137 | | /* convert debt from Kb to 'work units' (avoid zero debt and overflows) */ |
| 1138 | | debt = (debt / STEPMULADJ) + 1; |
| 1139 | | debt = (debt < MAX_LMEM / stepmul) ? debt * stepmul : MAX_LMEM; |
| 1140 | | do { /* always perform at least one single step */ |
| 1141 | | lu_mem work = singlestep(L); /* do some work */ |
| 1142 | | debt -= work; |
| 1143 | | } while (debt > -GCSTEPSIZE && g->gcstate != GCSpause); |
| 1144 | | if (g->gcstate == GCSpause) |
| 1145 | | setpause(g, g->GCestimate); /* pause until next cycle */ |
| 1146 | | else { |
| 1147 | | debt = (debt / stepmul) * STEPMULADJ; /* convert 'work units' to Kb */ |
| 1148 | | luaE_setdebt(g, debt); |
| 1149 | | } |
| 1140 | global_State *g = G(L); |
| 1141 | l_mem debt = g->GCdebt; |
| 1142 | int stepmul = g->gcstepmul; |
| 1143 | if (stepmul < 40) stepmul = 40; /* avoid ridiculous low values (and 0) */ |
| 1144 | /* convert debt from Kb to 'work units' (avoid zero debt and overflows) */ |
| 1145 | debt = (debt / STEPMULADJ) + 1; |
| 1146 | debt = (debt < MAX_LMEM / stepmul) ? debt * stepmul : MAX_LMEM; |
| 1147 | do { /* always perform at least one single step */ |
| 1148 | lu_mem work = singlestep(L); /* do some work */ |
| 1149 | debt -= work; |
| 1150 | } while (debt > -GCSTEPSIZE && g->gcstate != GCSpause); |
| 1151 | if (g->gcstate == GCSpause) |
| 1152 | setpause(g, g->GCestimate); /* pause until next cycle */ |
| 1153 | else { |
| 1154 | debt = (debt / stepmul) * STEPMULADJ; /* convert 'work units' to Kb */ |
| 1155 | luaE_setdebt(g, debt); |
| 1156 | } |
| 1150 | 1157 | } |
| 1151 | 1158 | |
| 1152 | 1159 | |
| r30857 | r30858 | |
| 1154 | 1161 | ** performs a basic GC step |
| 1155 | 1162 | */ |
| 1156 | 1163 | void luaC_forcestep (lua_State *L) { |
| 1157 | | global_State *g = G(L); |
| 1158 | | int i; |
| 1159 | | if (isgenerational(g)) generationalcollection(L); |
| 1160 | | else incstep(L); |
| 1161 | | /* run a few finalizers (or all of them at the end of a collect cycle) */ |
| 1162 | | for (i = 0; g->tobefnz && (i < GCFINALIZENUM || g->gcstate == GCSpause); i++) |
| 1163 | | GCTM(L, 1); /* call one finalizer */ |
| 1164 | global_State *g = G(L); |
| 1165 | int i; |
| 1166 | if (isgenerational(g)) generationalcollection(L); |
| 1167 | else incstep(L); |
| 1168 | /* run a few finalizers (or all of them at the end of a collect cycle) */ |
| 1169 | for (i = 0; g->tobefnz && (i < GCFINALIZENUM || g->gcstate == GCSpause); i++) |
| 1170 | GCTM(L, 1); /* call one finalizer */ |
| 1164 | 1171 | } |
| 1165 | 1172 | |
| 1166 | 1173 | |
| r30857 | r30858 | |
| 1168 | 1175 | ** performs a basic GC step only if collector is running |
| 1169 | 1176 | */ |
| 1170 | 1177 | void luaC_step (lua_State *L) { |
| 1171 | | global_State *g = G(L); |
| 1172 | | if (g->gcrunning) luaC_forcestep(L); |
| 1173 | | else luaE_setdebt(g, -GCSTEPSIZE); /* avoid being called too often */ |
| 1178 | global_State *g = G(L); |
| 1179 | if (g->gcrunning) luaC_forcestep(L); |
| 1180 | else luaE_setdebt(g, -GCSTEPSIZE); /* avoid being called too often */ |
| 1174 | 1181 | } |
| 1175 | 1182 | |
| 1176 | 1183 | |
| r30857 | r30858 | |
| 1180 | 1187 | ** finalizers (which could change stack positions) |
| 1181 | 1188 | */ |
| 1182 | 1189 | void luaC_fullgc (lua_State *L, int isemergency) { |
| 1183 | | global_State *g = G(L); |
| 1184 | | int origkind = g->gckind; |
| 1185 | | lua_assert(origkind != KGC_EMERGENCY); |
| 1186 | | if (isemergency) /* do not run finalizers during emergency GC */ |
| 1187 | | g->gckind = KGC_EMERGENCY; |
| 1188 | | else { |
| 1189 | | g->gckind = KGC_NORMAL; |
| 1190 | | callallpendingfinalizers(L, 1); |
| 1191 | | } |
| 1192 | | if (keepinvariant(g)) { /* may there be some black objects? */ |
| 1193 | | /* must sweep all objects to turn them back to white |
| 1194 | | (as white has not changed, nothing will be collected) */ |
| 1195 | | entersweep(L); |
| 1196 | | } |
| 1197 | | /* finish any pending sweep phase to start a new cycle */ |
| 1198 | | luaC_runtilstate(L, bitmask(GCSpause)); |
| 1199 | | luaC_runtilstate(L, ~bitmask(GCSpause)); /* start new collection */ |
| 1200 | | luaC_runtilstate(L, bitmask(GCSpause)); /* run entire collection */ |
| 1201 | | if (origkind == KGC_GEN) { /* generational mode? */ |
| 1202 | | /* generational mode must be kept in propagate phase */ |
| 1203 | | luaC_runtilstate(L, bitmask(GCSpropagate)); |
| 1204 | | } |
| 1205 | | g->gckind = origkind; |
| 1206 | | setpause(g, gettotalbytes(g)); |
| 1207 | | if (!isemergency) /* do not run finalizers during emergency GC */ |
| 1208 | | callallpendingfinalizers(L, 1); |
| 1190 | global_State *g = G(L); |
| 1191 | int origkind = g->gckind; |
| 1192 | lua_assert(origkind != KGC_EMERGENCY); |
| 1193 | if (isemergency) /* do not run finalizers during emergency GC */ |
| 1194 | g->gckind = KGC_EMERGENCY; |
| 1195 | else { |
| 1196 | g->gckind = KGC_NORMAL; |
| 1197 | callallpendingfinalizers(L, 1); |
| 1198 | } |
| 1199 | if (keepinvariant(g)) { /* may there be some black objects? */ |
| 1200 | /* must sweep all objects to turn them back to white |
| 1201 | (as white has not changed, nothing will be collected) */ |
| 1202 | entersweep(L); |
| 1203 | } |
| 1204 | /* finish any pending sweep phase to start a new cycle */ |
| 1205 | luaC_runtilstate(L, bitmask(GCSpause)); |
| 1206 | luaC_runtilstate(L, ~bitmask(GCSpause)); /* start new collection */ |
| 1207 | luaC_runtilstate(L, bitmask(GCSpause)); /* run entire collection */ |
| 1208 | if (origkind == KGC_GEN) { /* generational mode? */ |
| 1209 | /* generational mode must be kept in propagate phase */ |
| 1210 | luaC_runtilstate(L, bitmask(GCSpropagate)); |
| 1211 | } |
| 1212 | g->gckind = origkind; |
| 1213 | setpause(g, gettotalbytes(g)); |
| 1214 | if (!isemergency) /* do not run finalizers during emergency GC */ |
| 1215 | callallpendingfinalizers(L, 1); |
| 1209 | 1216 | } |
| 1210 | 1217 | |
| 1211 | 1218 | /* }====================================================== */ |
| 1219 | |
| 1220 | |
trunk/src/lib/lua/loadlib.c
| r30857 | r30858 | |
| 1 | 1 | /* |
| 2 | | ** $Id: loadlib.c,v 1.111 2012/05/30 12:33:44 roberto Exp $ |
| 2 | ** $Id: loadlib.c,v 1.111.1.1 2013/04/12 18:48:47 roberto Exp $ |
| 3 | 3 | ** Dynamic library loader for Lua |
| 4 | 4 | ** See Copyright Notice in lua.h |
| 5 | 5 | ** |
| r30857 | r30858 | |
| 35 | 35 | ** variables that Lua check to set its paths. |
| 36 | 36 | */ |
| 37 | 37 | #if !defined(LUA_PATH) |
| 38 | | #define LUA_PATH "LUA_PATH" |
| 38 | #define LUA_PATH "LUA_PATH" |
| 39 | 39 | #endif |
| 40 | 40 | |
| 41 | 41 | #if !defined(LUA_CPATH) |
| 42 | | #define LUA_CPATH "LUA_CPATH" |
| 42 | #define LUA_CPATH "LUA_CPATH" |
| 43 | 43 | #endif |
| 44 | 44 | |
| 45 | | #define LUA_PATHSUFFIX "_" LUA_VERSION_MAJOR "_" LUA_VERSION_MINOR |
| 45 | #define LUA_PATHSUFFIX "_" LUA_VERSION_MAJOR "_" LUA_VERSION_MINOR |
| 46 | 46 | |
| 47 | | #define LUA_PATHVERSION LUA_PATH LUA_PATHSUFFIX |
| 48 | | #define LUA_CPATHVERSION LUA_CPATH LUA_PATHSUFFIX |
| 47 | #define LUA_PATHVERSION LUA_PATH LUA_PATHSUFFIX |
| 48 | #define LUA_CPATHVERSION LUA_CPATH LUA_PATHSUFFIX |
| 49 | 49 | |
| 50 | 50 | /* |
| 51 | 51 | ** LUA_PATH_SEP is the character that separates templates in a path. |
| r30857 | r30858 | |
| 57 | 57 | ** luaopen_ function name. |
| 58 | 58 | */ |
| 59 | 59 | #if !defined (LUA_PATH_SEP) |
| 60 | | #define LUA_PATH_SEP ";" |
| 60 | #define LUA_PATH_SEP ";" |
| 61 | 61 | #endif |
| 62 | 62 | #if !defined (LUA_PATH_MARK) |
| 63 | | #define LUA_PATH_MARK "?" |
| 63 | #define LUA_PATH_MARK "?" |
| 64 | 64 | #endif |
| 65 | 65 | #if !defined (LUA_EXEC_DIR) |
| 66 | | #define LUA_EXEC_DIR "!" |
| 66 | #define LUA_EXEC_DIR "!" |
| 67 | 67 | #endif |
| 68 | 68 | #if !defined (LUA_IGMARK) |
| 69 | | #define LUA_IGMARK "-" |
| 69 | #define LUA_IGMARK "-" |
| 70 | 70 | #endif |
| 71 | 71 | |
| 72 | 72 | |
| r30857 | r30858 | |
| 77 | 77 | ** when searching for a Lua loader. |
| 78 | 78 | */ |
| 79 | 79 | #if !defined(LUA_CSUBSEP) |
| 80 | | #define LUA_CSUBSEP LUA_DIRSEP |
| 80 | #define LUA_CSUBSEP LUA_DIRSEP |
| 81 | 81 | #endif |
| 82 | 82 | |
| 83 | 83 | #if !defined(LUA_LSUBSEP) |
| 84 | | #define LUA_LSUBSEP LUA_DIRSEP |
| 84 | #define LUA_LSUBSEP LUA_DIRSEP |
| 85 | 85 | #endif |
| 86 | 86 | |
| 87 | 87 | |
| 88 | 88 | /* prefix for open functions in C libraries */ |
| 89 | | #define LUA_POF "luaopen_" |
| 89 | #define LUA_POF "luaopen_" |
| 90 | 90 | |
| 91 | 91 | /* separator for open functions in C libraries */ |
| 92 | | #define LUA_OFSEP "_" |
| 92 | #define LUA_OFSEP "_" |
| 93 | 93 | |
| 94 | 94 | |
| 95 | 95 | /* table (in the registry) that keeps handles for all loaded C libraries */ |
| 96 | | #define CLIBS "_CLIBS" |
| 96 | #define CLIBS "_CLIBS" |
| 97 | 97 | |
| 98 | | #define LIB_FAIL "open" |
| 98 | #define LIB_FAIL "open" |
| 99 | 99 | |
| 100 | 100 | |
| 101 | 101 | /* error codes for ll_loadfunc */ |
| 102 | | #define ERRLIB 1 |
| 103 | | #define ERRFUNC 2 |
| 102 | #define ERRLIB 1 |
| 103 | #define ERRFUNC 2 |
| 104 | 104 | |
| 105 | | #define setprogdir(L) ((void)0) |
| 105 | #define setprogdir(L) ((void)0) |
| 106 | 106 | |
| 107 | 107 | |
| 108 | 108 | /* |
| r30857 | r30858 | |
| 127 | 127 | #include <dlfcn.h> |
| 128 | 128 | |
| 129 | 129 | static void ll_unloadlib (void *lib) { |
| 130 | | dlclose(lib); |
| 130 | dlclose(lib); |
| 131 | 131 | } |
| 132 | 132 | |
| 133 | 133 | |
| 134 | 134 | static void *ll_load (lua_State *L, const char *path, int seeglb) { |
| 135 | | void *lib = dlopen(path, RTLD_NOW | (seeglb ? RTLD_GLOBAL : RTLD_LOCAL)); |
| 136 | | if (lib == NULL) lua_pushstring(L, dlerror()); |
| 137 | | return lib; |
| 135 | void *lib = dlopen(path, RTLD_NOW | (seeglb ? RTLD_GLOBAL : RTLD_LOCAL)); |
| 136 | if (lib == NULL) lua_pushstring(L, dlerror()); |
| 137 | return lib; |
| 138 | 138 | } |
| 139 | 139 | |
| 140 | 140 | |
| 141 | 141 | static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym) { |
| 142 | | lua_CFunction f = (lua_CFunction)dlsym(lib, sym); |
| 143 | | if (f == NULL) lua_pushstring(L, dlerror()); |
| 144 | | return f; |
| 142 | lua_CFunction f = (lua_CFunction)dlsym(lib, sym); |
| 143 | if (f == NULL) lua_pushstring(L, dlerror()); |
| 144 | return f; |
| 145 | 145 | } |
| 146 | 146 | |
| 147 | 147 | /* }====================================================== */ |
| r30857 | r30858 | |
| 161 | 161 | ** optional flags for LoadLibraryEx |
| 162 | 162 | */ |
| 163 | 163 | #if !defined(LUA_LLE_FLAGS) |
| 164 | | #define LUA_LLE_FLAGS 0 |
| 164 | #define LUA_LLE_FLAGS 0 |
| 165 | 165 | #endif |
| 166 | 166 | |
| 167 | 167 | |
| 168 | 168 | static void setprogdir (lua_State *L) { |
| 169 | | char buff[MAX_PATH + 1]; |
| 170 | | char *lb; |
| 171 | | DWORD nsize = sizeof(buff)/sizeof(char); |
| 172 | | DWORD n = GetModuleFileNameA(NULL, buff, nsize); |
| 173 | | if (n == 0 || n == nsize || (lb = strrchr(buff, '\\')) == NULL) |
| 174 | | luaL_error(L, "unable to get ModuleFileName"); |
| 175 | | else { |
| 176 | | *lb = '\0'; |
| 177 | | luaL_gsub(L, lua_tostring(L, -1), LUA_EXEC_DIR, buff); |
| 178 | | lua_remove(L, -2); /* remove original string */ |
| 179 | | } |
| 169 | char buff[MAX_PATH + 1]; |
| 170 | char *lb; |
| 171 | DWORD nsize = sizeof(buff)/sizeof(char); |
| 172 | DWORD n = GetModuleFileNameA(NULL, buff, nsize); |
| 173 | if (n == 0 || n == nsize || (lb = strrchr(buff, '\\')) == NULL) |
| 174 | luaL_error(L, "unable to get ModuleFileName"); |
| 175 | else { |
| 176 | *lb = '\0'; |
| 177 | luaL_gsub(L, lua_tostring(L, -1), LUA_EXEC_DIR, buff); |
| 178 | lua_remove(L, -2); /* remove original string */ |
| 179 | } |
| 180 | 180 | } |
| 181 | 181 | |
| 182 | 182 | |
| 183 | 183 | static void pusherror (lua_State *L) { |
| 184 | | int error = GetLastError(); |
| 185 | | char buffer[128]; |
| 186 | | if (FormatMessageA(FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM, |
| 187 | | NULL, error, 0, buffer, sizeof(buffer)/sizeof(char), NULL)) |
| 188 | | lua_pushstring(L, buffer); |
| 189 | | else |
| 190 | | lua_pushfstring(L, "system error %d\n", error); |
| 184 | int error = GetLastError(); |
| 185 | char buffer[128]; |
| 186 | if (FormatMessageA(FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM, |
| 187 | NULL, error, 0, buffer, sizeof(buffer)/sizeof(char), NULL)) |
| 188 | lua_pushstring(L, buffer); |
| 189 | else |
| 190 | lua_pushfstring(L, "system error %d\n", error); |
| 191 | 191 | } |
| 192 | 192 | |
| 193 | 193 | static void ll_unloadlib (void *lib) { |
| 194 | | FreeLibrary((HMODULE)lib); |
| 194 | FreeLibrary((HMODULE)lib); |
| 195 | 195 | } |
| 196 | 196 | |
| 197 | 197 | |
| 198 | 198 | static void *ll_load (lua_State *L, const char *path, int seeglb) { |
| 199 | | HMODULE lib = LoadLibraryExA(path, NULL, LUA_LLE_FLAGS); |
| 200 | | (void)(seeglb); /* not used: symbols are 'global' by default */ |
| 201 | | if (lib == NULL) pusherror(L); |
| 202 | | return lib; |
| 199 | HMODULE lib = LoadLibraryExA(path, NULL, LUA_LLE_FLAGS); |
| 200 | (void)(seeglb); /* not used: symbols are 'global' by default */ |
| 201 | if (lib == NULL) pusherror(L); |
| 202 | return lib; |
| 203 | 203 | } |
| 204 | 204 | |
| 205 | 205 | |
| 206 | 206 | static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym) { |
| 207 | | lua_CFunction f = (lua_CFunction)GetProcAddress((HMODULE)lib, sym); |
| 208 | | if (f == NULL) pusherror(L); |
| 209 | | return f; |
| 207 | lua_CFunction f = (lua_CFunction)GetProcAddress((HMODULE)lib, sym); |
| 208 | if (f == NULL) pusherror(L); |
| 209 | return f; |
| 210 | 210 | } |
| 211 | 211 | |
| 212 | 212 | /* }====================================================== */ |
| r30857 | r30858 | |
| 220 | 220 | */ |
| 221 | 221 | |
| 222 | 222 | #undef LIB_FAIL |
| 223 | | #define LIB_FAIL "absent" |
| 223 | #define LIB_FAIL "absent" |
| 224 | 224 | |
| 225 | 225 | |
| 226 | | #define DLMSG "dynamic libraries not enabled; check your Lua installation" |
| 226 | #define DLMSG "dynamic libraries not enabled; check your Lua installation" |
| 227 | 227 | |
| 228 | 228 | |
| 229 | 229 | static void ll_unloadlib (void *lib) { |
| 230 | | (void)(lib); /* not used */ |
| 230 | (void)(lib); /* not used */ |
| 231 | 231 | } |
| 232 | 232 | |
| 233 | 233 | |
| 234 | 234 | static void *ll_load (lua_State *L, const char *path, int seeglb) { |
| 235 | | (void)(path); (void)(seeglb); /* not used */ |
| 236 | | lua_pushliteral(L, DLMSG); |
| 237 | | return NULL; |
| 235 | (void)(path); (void)(seeglb); /* not used */ |
| 236 | lua_pushliteral(L, DLMSG); |
| 237 | return NULL; |
| 238 | 238 | } |
| 239 | 239 | |
| 240 | 240 | |
| 241 | 241 | static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym) { |
| 242 | | (void)(lib); (void)(sym); /* not used */ |
| 243 | | lua_pushliteral(L, DLMSG); |
| 244 | | return NULL; |
| 242 | (void)(lib); (void)(sym); /* not used */ |
| 243 | lua_pushliteral(L, DLMSG); |
| 244 | return NULL; |
| 245 | 245 | } |
| 246 | 246 | |
| 247 | 247 | /* }====================================================== */ |
| r30857 | r30858 | |
| 249 | 249 | |
| 250 | 250 | |
| 251 | 251 | static void *ll_checkclib (lua_State *L, const char *path) { |
| 252 | | void *plib; |
| 253 | | lua_getfield(L, LUA_REGISTRYINDEX, CLIBS); |
| 254 | | lua_getfield(L, -1, path); |
| 255 | | plib = lua_touserdata(L, -1); /* plib = CLIBS[path] */ |
| 256 | | lua_pop(L, 2); /* pop CLIBS table and 'plib' */ |
| 257 | | return plib; |
| 252 | void *plib; |
| 253 | lua_getfield(L, LUA_REGISTRYINDEX, CLIBS); |
| 254 | lua_getfield(L, -1, path); |
| 255 | plib = lua_touserdata(L, -1); /* plib = CLIBS[path] */ |
| 256 | lua_pop(L, 2); /* pop CLIBS table and 'plib' */ |
| 257 | return plib; |
| 258 | 258 | } |
| 259 | 259 | |
| 260 | 260 | |
| 261 | 261 | static void ll_addtoclib (lua_State *L, const char *path, void *plib) { |
| 262 | | lua_getfield(L, LUA_REGISTRYINDEX, CLIBS); |
| 263 | | lua_pushlightuserdata(L, plib); |
| 264 | | lua_pushvalue(L, -1); |
| 265 | | lua_setfield(L, -3, path); /* CLIBS[path] = plib */ |
| 266 | | lua_rawseti(L, -2, luaL_len(L, -2) + 1); /* CLIBS[#CLIBS + 1] = plib */ |
| 267 | | lua_pop(L, 1); /* pop CLIBS table */ |
| 262 | lua_getfield(L, LUA_REGISTRYINDEX, CLIBS); |
| 263 | lua_pushlightuserdata(L, plib); |
| 264 | lua_pushvalue(L, -1); |
| 265 | lua_setfield(L, -3, path); /* CLIBS[path] = plib */ |
| 266 | lua_rawseti(L, -2, luaL_len(L, -2) + 1); /* CLIBS[#CLIBS + 1] = plib */ |
| 267 | lua_pop(L, 1); /* pop CLIBS table */ |
| 268 | 268 | } |
| 269 | 269 | |
| 270 | 270 | |
| r30857 | r30858 | |
| 273 | 273 | ** handles in list CLIBS |
| 274 | 274 | */ |
| 275 | 275 | static int gctm (lua_State *L) { |
| 276 | | int n = luaL_len(L, 1); |
| 277 | | for (; n >= 1; n--) { /* for each handle, in reverse order */ |
| 278 | | lua_rawgeti(L, 1, n); /* get handle CLIBS[n] */ |
| 279 | | ll_unloadlib(lua_touserdata(L, -1)); |
| 280 | | lua_pop(L, 1); /* pop handle */ |
| 281 | | } |
| 282 | | return 0; |
| 276 | int n = luaL_len(L, 1); |
| 277 | for (; n >= 1; n--) { /* for each handle, in reverse order */ |
| 278 | lua_rawgeti(L, 1, n); /* get handle CLIBS[n] */ |
| 279 | ll_unloadlib(lua_touserdata(L, -1)); |
| 280 | lua_pop(L, 1); /* pop handle */ |
| 281 | } |
| 282 | return 0; |
| 283 | 283 | } |
| 284 | 284 | |
| 285 | 285 | |
| 286 | 286 | static int ll_loadfunc (lua_State *L, const char *path, const char *sym) { |
| 287 | | void *reg = ll_checkclib(L, path); /* check loaded C libraries */ |
| 288 | | if (reg == NULL) { /* must load library? */ |
| 289 | | reg = ll_load(L, path, *sym == '*'); |
| 290 | | if (reg == NULL) return ERRLIB; /* unable to load library */ |
| 291 | | ll_addtoclib(L, path, reg); |
| 292 | | } |
| 293 | | if (*sym == '*') { /* loading only library (no function)? */ |
| 294 | | lua_pushboolean(L, 1); /* return 'true' */ |
| 295 | | return 0; /* no errors */ |
| 296 | | } |
| 297 | | else { |
| 298 | | lua_CFunction f = ll_sym(L, reg, sym); |
| 299 | | if (f == NULL) |
| 300 | | return ERRFUNC; /* unable to find function */ |
| 301 | | lua_pushcfunction(L, f); /* else create new function */ |
| 302 | | return 0; /* no errors */ |
| 303 | | } |
| 287 | void *reg = ll_checkclib(L, path); /* check loaded C libraries */ |
| 288 | if (reg == NULL) { /* must load library? */ |
| 289 | reg = ll_load(L, path, *sym == '*'); |
| 290 | if (reg == NULL) return ERRLIB; /* unable to load library */ |
| 291 | ll_addtoclib(L, path, reg); |
| 292 | } |
| 293 | if (*sym == '*') { /* loading only library (no function)? */ |
| 294 | lua_pushboolean(L, 1); /* return 'true' */ |
| 295 | return 0; /* no errors */ |
| 296 | } |
| 297 | else { |
| 298 | lua_CFunction f = ll_sym(L, reg, sym); |
| 299 | if (f == NULL) |
| 300 | return ERRFUNC; /* unable to find function */ |
| 301 | lua_pushcfunction(L, f); /* else create new function */ |
| 302 | return 0; /* no errors */ |
| 303 | } |
| 304 | 304 | } |
| 305 | 305 | |
| 306 | 306 | |
| 307 | 307 | static int ll_loadlib (lua_State *L) { |
| 308 | | const char *path = luaL_checkstring(L, 1); |
| 309 | | const char *init = luaL_checkstring(L, 2); |
| 310 | | int stat = ll_loadfunc(L, path, init); |
| 311 | | if (stat == 0) /* no errors? */ |
| 312 | | return 1; /* return the loaded function */ |
| 313 | | else { /* error; error message is on stack top */ |
| 314 | | lua_pushnil(L); |
| 315 | | lua_insert(L, -2); |
| 316 | | lua_pushstring(L, (stat == ERRLIB) ? LIB_FAIL : "init"); |
| 317 | | return 3; /* return nil, error message, and where */ |
| 318 | | } |
| 308 | const char *path = luaL_checkstring(L, 1); |
| 309 | const char *init = luaL_checkstring(L, 2); |
| 310 | int stat = ll_loadfunc(L, path, init); |
| 311 | if (stat == 0) /* no errors? */ |
| 312 | return 1; /* return the loaded function */ |
| 313 | else { /* error; error message is on stack top */ |
| 314 | lua_pushnil(L); |
| 315 | lua_insert(L, -2); |
| 316 | lua_pushstring(L, (stat == ERRLIB) ? LIB_FAIL : "init"); |
| 317 | return 3; /* return nil, error message, and where */ |
| 318 | } |
| 319 | 319 | } |
| 320 | 320 | |
| 321 | 321 | |
| r30857 | r30858 | |
| 328 | 328 | |
| 329 | 329 | |
| 330 | 330 | static int readable (const char *filename) { |
| 331 | | FILE *f = fopen(filename, "r"); /* try to open file */ |
| 332 | | if (f == NULL) return 0; /* open failed */ |
| 333 | | fclose(f); |
| 334 | | return 1; |
| 331 | FILE *f = fopen(filename, "r"); /* try to open file */ |
| 332 | if (f == NULL) return 0; /* open failed */ |
| 333 | fclose(f); |
| 334 | return 1; |
| 335 | 335 | } |
| 336 | 336 | |
| 337 | 337 | |
| 338 | 338 | static const char *pushnexttemplate (lua_State *L, const char *path) { |
| 339 | | const char *l; |
| 340 | | while (*path == *LUA_PATH_SEP) path++; /* skip separators */ |
| 341 | | if (*path == '\0') return NULL; /* no more templates */ |
| 342 | | l = strchr(path, *LUA_PATH_SEP); /* find next separator */ |
| 343 | | if (l == NULL) l = path + strlen(path); |
| 344 | | lua_pushlstring(L, path, l - path); /* template */ |
| 345 | | return l; |
| 339 | const char *l; |
| 340 | while (*path == *LUA_PATH_SEP) path++; /* skip separators */ |
| 341 | if (*path == '\0') return NULL; /* no more templates */ |
| 342 | l = strchr(path, *LUA_PATH_SEP); /* find next separator */ |
| 343 | if (l == NULL) l = path + strlen(path); |
| 344 | lua_pushlstring(L, path, l - path); /* template */ |
| 345 | return l; |
| 346 | 346 | } |
| 347 | 347 | |
| 348 | 348 | |
| 349 | 349 | static const char *searchpath (lua_State *L, const char *name, |
| 350 | | const char *path, |
| 351 | | const char *sep, |
| 352 | | const char *dirsep) { |
| 353 | | luaL_Buffer msg; /* to build error message */ |
| 354 | | luaL_buffinit(L, &msg); |
| 355 | | if (*sep != '\0') /* non-empty separator? */ |
| 356 | | name = luaL_gsub(L, name, sep, dirsep); /* replace it by 'dirsep' */ |
| 357 | | while ((path = pushnexttemplate(L, path)) != NULL) { |
| 358 | | const char *filename = luaL_gsub(L, lua_tostring(L, -1), |
| 359 | | LUA_PATH_MARK, name); |
| 360 | | lua_remove(L, -2); /* remove path template */ |
| 361 | | if (readable(filename)) /* does file exist and is readable? */ |
| 362 | | return filename; /* return that file name */ |
| 363 | | lua_pushfstring(L, "\n\tno file " LUA_QS, filename); |
| 364 | | lua_remove(L, -2); /* remove file name */ |
| 365 | | luaL_addvalue(&msg); /* concatenate error msg. entry */ |
| 366 | | } |
| 367 | | luaL_pushresult(&msg); /* create error message */ |
| 368 | | return NULL; /* not found */ |
| 350 | const char *path, |
| 351 | const char *sep, |
| 352 | const char *dirsep) { |
| 353 | luaL_Buffer msg; /* to build error message */ |
| 354 | luaL_buffinit(L, &msg); |
| 355 | if (*sep != '\0') /* non-empty separator? */ |
| 356 | name = luaL_gsub(L, name, sep, dirsep); /* replace it by 'dirsep' */ |
| 357 | while ((path = pushnexttemplate(L, path)) != NULL) { |
| 358 | const char *filename = luaL_gsub(L, lua_tostring(L, -1), |
| 359 | LUA_PATH_MARK, name); |
| 360 | lua_remove(L, -2); /* remove path template */ |
| 361 | if (readable(filename)) /* does file exist and is readable? */ |
| 362 | return filename; /* return that file name */ |
| 363 | lua_pushfstring(L, "\n\tno file " LUA_QS, filename); |
| 364 | lua_remove(L, -2); /* remove file name */ |
| 365 | luaL_addvalue(&msg); /* concatenate error msg. entry */ |
| 366 | } |
| 367 | luaL_pushresult(&msg); /* create error message */ |
| 368 | return NULL; /* not found */ |
| 369 | 369 | } |
| 370 | 370 | |
| 371 | 371 | |
| 372 | 372 | static int ll_searchpath (lua_State *L) { |
| 373 | | const char *f = searchpath(L, luaL_checkstring(L, 1), |
| 374 | | luaL_checkstring(L, 2), |
| 375 | | luaL_optstring(L, 3, "."), |
| 376 | | luaL_optstring(L, 4, LUA_DIRSEP)); |
| 377 | | if (f != NULL) return 1; |
| 378 | | else { /* error message is on top of the stack */ |
| 379 | | lua_pushnil(L); |
| 380 | | lua_insert(L, -2); |
| 381 | | return 2; /* return nil + error message */ |
| 382 | | } |
| 373 | const char *f = searchpath(L, luaL_checkstring(L, 1), |
| 374 | luaL_checkstring(L, 2), |
| 375 | luaL_optstring(L, 3, "."), |
| 376 | luaL_optstring(L, 4, LUA_DIRSEP)); |
| 377 | if (f != NULL) return 1; |
| 378 | else { /* error message is on top of the stack */ |
| 379 | lua_pushnil(L); |
| 380 | lua_insert(L, -2); |
| 381 | return 2; /* return nil + error message */ |
| 382 | } |
| 383 | 383 | } |
| 384 | 384 | |
| 385 | 385 | |
| 386 | 386 | static const char *findfile (lua_State *L, const char *name, |
| 387 | | const char *pname, |
| 388 | | const char *dirsep) { |
| 389 | | const char *path; |
| 390 | | lua_getfield(L, lua_upvalueindex(1), pname); |
| 391 | | path = lua_tostring(L, -1); |
| 392 | | if (path == NULL) |
| 393 | | luaL_error(L, LUA_QL("package.%s") " must be a string", pname); |
| 394 | | return searchpath(L, name, path, ".", dirsep); |
| 387 | const char *pname, |
| 388 | const char *dirsep) { |
| 389 | const char *path; |
| 390 | lua_getfield(L, lua_upvalueindex(1), pname); |
| 391 | path = lua_tostring(L, -1); |
| 392 | if (path == NULL) |
| 393 | luaL_error(L, LUA_QL("package.%s") " must be a string", pname); |
| 394 | return searchpath(L, name, path, ".", dirsep); |
| 395 | 395 | } |
| 396 | 396 | |
| 397 | 397 | |
| 398 | 398 | static int checkload (lua_State *L, int stat, const char *filename) { |
| 399 | | if (stat) { /* module loaded successfully? */ |
| 400 | | lua_pushstring(L, filename); /* will be 2nd argument to module */ |
| 401 | | return 2; /* return open function and file name */ |
| 402 | | } |
| 403 | | else |
| 404 | | return luaL_error(L, "error loading module " LUA_QS |
| 405 | | " from file " LUA_QS ":\n\t%s", |
| 406 | | lua_tostring(L, 1), filename, lua_tostring(L, -1)); |
| 399 | if (stat) { /* module loaded successfully? */ |
| 400 | lua_pushstring(L, filename); /* will be 2nd argument to module */ |
| 401 | return 2; /* return open function and file name */ |
| 402 | } |
| 403 | else |
| 404 | return luaL_error(L, "error loading module " LUA_QS |
| 405 | " from file " LUA_QS ":\n\t%s", |
| 406 | lua_tostring(L, 1), filename, lua_tostring(L, -1)); |
| 407 | 407 | } |
| 408 | 408 | |
| 409 | 409 | |
| 410 | 410 | static int searcher_Lua (lua_State *L) { |
| 411 | | const char *filename; |
| 412 | | const char *name = luaL_checkstring(L, 1); |
| 413 | | filename = findfile(L, name, "path", LUA_LSUBSEP); |
| 414 | | if (filename == NULL) return 1; /* module not found in this path */ |
| 415 | | return checkload(L, (luaL_loadfile(L, filename) == LUA_OK), filename); |
| 411 | const char *filename; |
| 412 | const char *name = luaL_checkstring(L, 1); |
| 413 | filename = findfile(L, name, "path", LUA_LSUBSEP); |
| 414 | if (filename == NULL) return 1; /* module not found in this path */ |
| 415 | return checkload(L, (luaL_loadfile(L, filename) == LUA_OK), filename); |
| 416 | 416 | } |
| 417 | 417 | |
| 418 | 418 | |
| 419 | 419 | static int loadfunc (lua_State *L, const char *filename, const char *modname) { |
| 420 | | const char *funcname; |
| 421 | | const char *mark; |
| 422 | | modname = luaL_gsub(L, modname, ".", LUA_OFSEP); |
| 423 | | mark = strchr(modname, *LUA_IGMARK); |
| 424 | | if (mark) { |
| 425 | | int stat; |
| 426 | | funcname = lua_pushlstring(L, modname, mark - modname); |
| 427 | | funcname = lua_pushfstring(L, LUA_POF"%s", funcname); |
| 428 | | stat = ll_loadfunc(L, filename, funcname); |
| 429 | | if (stat != ERRFUNC) return stat; |
| 430 | | modname = mark + 1; /* else go ahead and try old-style name */ |
| 431 | | } |
| 432 | | funcname = lua_pushfstring(L, LUA_POF"%s", modname); |
| 433 | | return ll_loadfunc(L, filename, funcname); |
| 420 | const char *funcname; |
| 421 | const char *mark; |
| 422 | modname = luaL_gsub(L, modname, ".", LUA_OFSEP); |
| 423 | mark = strchr(modname, *LUA_IGMARK); |
| 424 | if (mark) { |
| 425 | int stat; |
| 426 | funcname = lua_pushlstring(L, modname, mark - modname); |
| 427 | funcname = lua_pushfstring(L, LUA_POF"%s", funcname); |
| 428 | stat = ll_loadfunc(L, filename, funcname); |
| 429 | if (stat != ERRFUNC) return stat; |
| 430 | modname = mark + 1; /* else go ahead and try old-style name */ |
| 431 | } |
| 432 | funcname = lua_pushfstring(L, LUA_POF"%s", modname); |
| 433 | return ll_loadfunc(L, filename, funcname); |
| 434 | 434 | } |
| 435 | 435 | |
| 436 | 436 | |
| 437 | 437 | static int searcher_C (lua_State *L) { |
| 438 | | const char *name = luaL_checkstring(L, 1); |
| 439 | | const char *filename = findfile(L, name, "cpath", LUA_CSUBSEP); |
| 440 | | if (filename == NULL) return 1; /* module not found in this path */ |
| 441 | | return checkload(L, (loadfunc(L, filename, name) == 0), filename); |
| 438 | const char *name = luaL_checkstring(L, 1); |
| 439 | const char *filename = findfile(L, name, "cpath", LUA_CSUBSEP); |
| 440 | if (filename == NULL) return 1; /* module not found in this path */ |
| 441 | return checkload(L, (loadfunc(L, filename, name) == 0), filename); |
| 442 | 442 | } |
| 443 | 443 | |
| 444 | 444 | |
| 445 | 445 | static int searcher_Croot (lua_State *L) { |
| 446 | | const char *filename; |
| 447 | | const char *name = luaL_checkstring(L, 1); |
| 448 | | const char *p = strchr(name, '.'); |
| 449 | | int stat; |
| 450 | | if (p == NULL) return 0; /* is root */ |
| 451 | | lua_pushlstring(L, name, p - name); |
| 452 | | filename = findfile(L, lua_tostring(L, -1), "cpath", LUA_CSUBSEP); |
| 453 | | if (filename == NULL) return 1; /* root not found */ |
| 454 | | if ((stat = loadfunc(L, filename, name)) != 0) { |
| 455 | | if (stat != ERRFUNC) |
| 456 | | return checkload(L, 0, filename); /* real error */ |
| 457 | | else { /* open function not found */ |
| 458 | | lua_pushfstring(L, "\n\tno module " LUA_QS " in file " LUA_QS, |
| 459 | | name, filename); |
| 460 | | return 1; |
| 461 | | } |
| 462 | | } |
| 463 | | lua_pushstring(L, filename); /* will be 2nd argument to module */ |
| 464 | | return 2; |
| 446 | const char *filename; |
| 447 | const char *name = luaL_checkstring(L, 1); |
| 448 | const char *p = strchr(name, '.'); |
| 449 | int stat; |
| 450 | if (p == NULL) return 0; /* is root */ |
| 451 | lua_pushlstring(L, name, p - name); |
| 452 | filename = findfile(L, lua_tostring(L, -1), "cpath", LUA_CSUBSEP); |
| 453 | if (filename == NULL) return 1; /* root not found */ |
| 454 | if ((stat = loadfunc(L, filename, name)) != 0) { |
| 455 | if (stat != ERRFUNC) |
| 456 | return checkload(L, 0, filename); /* real error */ |
| 457 | else { /* open function not found */ |
| 458 | lua_pushfstring(L, "\n\tno module " LUA_QS " in file " LUA_QS, |
| 459 | name, filename); |
| 460 | return 1; |
| 461 | } |
| 462 | } |
| 463 | lua_pushstring(L, filename); /* will be 2nd argument to module */ |
| 464 | return 2; |
| 465 | 465 | } |
| 466 | 466 | |
| 467 | 467 | |
| 468 | 468 | static int searcher_preload (lua_State *L) { |
| 469 | | const char *name = luaL_checkstring(L, 1); |
| 470 | | lua_getfield(L, LUA_REGISTRYINDEX, "_PRELOAD"); |
| 471 | | lua_getfield(L, -1, name); |
| 472 | | if (lua_isnil(L, -1)) /* not found? */ |
| 473 | | lua_pushfstring(L, "\n\tno field package.preload['%s']", name); |
| 474 | | return 1; |
| 469 | const char *name = luaL_checkstring(L, 1); |
| 470 | lua_getfield(L, LUA_REGISTRYINDEX, "_PRELOAD"); |
| 471 | lua_getfield(L, -1, name); |
| 472 | if (lua_isnil(L, -1)) /* not found? */ |
| 473 | lua_pushfstring(L, "\n\tno field package.preload['%s']", name); |
| 474 | return 1; |
| 475 | 475 | } |
| 476 | 476 | |
| 477 | 477 | |
| 478 | 478 | static void findloader (lua_State *L, const char *name) { |
| 479 | | int i; |
| 480 | | luaL_Buffer msg; /* to build error message */ |
| 481 | | luaL_buffinit(L, &msg); |
| 482 | | lua_getfield(L, lua_upvalueindex(1), "searchers"); /* will be at index 3 */ |
| 483 | | if (!lua_istable(L, 3)) |
| 484 | | luaL_error(L, LUA_QL("package.searchers") " must be a table"); |
| 485 | | /* iterate over available searchers to find a loader */ |
| 486 | | for (i = 1; ; i++) { |
| 487 | | lua_rawgeti(L, 3, i); /* get a searcher */ |
| 488 | | if (lua_isnil(L, -1)) { /* no more searchers? */ |
| 489 | | lua_pop(L, 1); /* remove nil */ |
| 490 | | luaL_pushresult(&msg); /* create error message */ |
| 491 | | luaL_error(L, "module " LUA_QS " not found:%s", |
| 492 | | name, lua_tostring(L, -1)); |
| 493 | | } |
| 494 | | lua_pushstring(L, name); |
| 495 | | lua_call(L, 1, 2); /* call it */ |
| 496 | | if (lua_isfunction(L, -2)) /* did it find a loader? */ |
| 497 | | return; /* module loader found */ |
| 498 | | else if (lua_isstring(L, -2)) { /* searcher returned error message? */ |
| 499 | | lua_pop(L, 1); /* remove extra return */ |
| 500 | | luaL_addvalue(&msg); /* concatenate error message */ |
| 501 | | } |
| 502 | | else |
| 503 | | lua_pop(L, 2); /* remove both returns */ |
| 504 | | } |
| 479 | int i; |
| 480 | luaL_Buffer msg; /* to build error message */ |
| 481 | luaL_buffinit(L, &msg); |
| 482 | lua_getfield(L, lua_upvalueindex(1), "searchers"); /* will be at index 3 */ |
| 483 | if (!lua_istable(L, 3)) |
| 484 | luaL_error(L, LUA_QL("package.searchers") " must be a table"); |
| 485 | /* iterate over available searchers to find a loader */ |
| 486 | for (i = 1; ; i++) { |
| 487 | lua_rawgeti(L, 3, i); /* get a searcher */ |
| 488 | if (lua_isnil(L, -1)) { /* no more searchers? */ |
| 489 | lua_pop(L, 1); /* remove nil */ |
| 490 | luaL_pushresult(&msg); /* create error message */ |
| 491 | luaL_error(L, "module " LUA_QS " not found:%s", |
| 492 | name, lua_tostring(L, -1)); |
| 493 | } |
| 494 | lua_pushstring(L, name); |
| 495 | lua_call(L, 1, 2); /* call it */ |
| 496 | if (lua_isfunction(L, -2)) /* did it find a loader? */ |
| 497 | return; /* module loader found */ |
| 498 | else if (lua_isstring(L, -2)) { /* searcher returned error message? */ |
| 499 | lua_pop(L, 1); /* remove extra return */ |
| 500 | luaL_addvalue(&msg); /* concatenate error message */ |
| 501 | } |
| 502 | else |
| 503 | lua_pop(L, 2); /* remove both returns */ |
| 504 | } |
| 505 | 505 | } |
| 506 | 506 | |
| 507 | 507 | |
| 508 | 508 | static int ll_require (lua_State *L) { |
| 509 | | const char *name = luaL_checkstring(L, 1); |
| 510 | | lua_settop(L, 1); /* _LOADED table will be at index 2 */ |
| 511 | | lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED"); |
| 512 | | lua_getfield(L, 2, name); /* _LOADED[name] */ |
| 513 | | if (lua_toboolean(L, -1)) /* is it there? */ |
| 514 | | return 1; /* package is already loaded */ |
| 515 | | /* else must load package */ |
| 516 | | lua_pop(L, 1); /* remove 'getfield' result */ |
| 517 | | findloader(L, name); |
| 518 | | lua_pushstring(L, name); /* pass name as argument to module loader */ |
| 519 | | lua_insert(L, -2); /* name is 1st argument (before search data) */ |
| 520 | | lua_call(L, 2, 1); /* run loader to load module */ |
| 521 | | if (!lua_isnil(L, -1)) /* non-nil return? */ |
| 522 | | lua_setfield(L, 2, name); /* _LOADED[name] = returned value */ |
| 523 | | lua_getfield(L, 2, name); |
| 524 | | if (lua_isnil(L, -1)) { /* module did not set a value? */ |
| 525 | | lua_pushboolean(L, 1); /* use true as result */ |
| 526 | | lua_pushvalue(L, -1); /* extra copy to be returned */ |
| 527 | | lua_setfield(L, 2, name); /* _LOADED[name] = true */ |
| 528 | | } |
| 529 | | return 1; |
| 509 | const char *name = luaL_checkstring(L, 1); |
| 510 | lua_settop(L, 1); /* _LOADED table will be at index 2 */ |
| 511 | lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED"); |
| 512 | lua_getfield(L, 2, name); /* _LOADED[name] */ |
| 513 | if (lua_toboolean(L, -1)) /* is it there? */ |
| 514 | return 1; /* package is already loaded */ |
| 515 | /* else must load package */ |
| 516 | lua_pop(L, 1); /* remove 'getfield' result */ |
| 517 | findloader(L, name); |
| 518 | lua_pushstring(L, name); /* pass name as argument to module loader */ |
| 519 | lua_insert(L, -2); /* name is 1st argument (before search data) */ |
| 520 | lua_call(L, 2, 1); /* run loader to load module */ |
| 521 | if (!lua_isnil(L, -1)) /* non-nil return? */ |
| 522 | lua_setfield(L, 2, name); /* _LOADED[name] = returned value */ |
| 523 | lua_getfield(L, 2, name); |
| 524 | if (lua_isnil(L, -1)) { /* module did not set a value? */ |
| 525 | lua_pushboolean(L, 1); /* use true as result */ |
| 526 | lua_pushvalue(L, -1); /* extra copy to be returned */ |
| 527 | lua_setfield(L, 2, name); /* _LOADED[name] = true */ |
| 528 | } |
| 529 | return 1; |
| 530 | 530 | } |
| 531 | 531 | |
| 532 | 532 | /* }====================================================== */ |
| r30857 | r30858 | |
| 544 | 544 | ** changes the environment variable of calling function |
| 545 | 545 | */ |
| 546 | 546 | static void set_env (lua_State *L) { |
| 547 | | lua_Debug ar; |
| 548 | | if (lua_getstack(L, 1, &ar) == 0 || |
| 549 | | lua_getinfo(L, "f", &ar) == 0 || /* get calling function */ |
| 550 | | lua_iscfunction(L, -1)) |
| 551 | | luaL_error(L, LUA_QL("module") " not called from a Lua function"); |
| 552 | | lua_pushvalue(L, -2); /* copy new environment table to top */ |
| 553 | | lua_setupvalue(L, -2, 1); |
| 554 | | lua_pop(L, 1); /* remove function */ |
| 547 | lua_Debug ar; |
| 548 | if (lua_getstack(L, 1, &ar) == 0 || |
| 549 | lua_getinfo(L, "f", &ar) == 0 || /* get calling function */ |
| 550 | lua_iscfunction(L, -1)) |
| 551 | luaL_error(L, LUA_QL("module") " not called from a Lua function"); |
| 552 | lua_pushvalue(L, -2); /* copy new environment table to top */ |
| 553 | lua_setupvalue(L, -2, 1); |
| 554 | lua_pop(L, 1); /* remove function */ |
| 555 | 555 | } |
| 556 | 556 | |
| 557 | 557 | |
| 558 | 558 | static void dooptions (lua_State *L, int n) { |
| 559 | | int i; |
| 560 | | for (i = 2; i <= n; i++) { |
| 561 | | if (lua_isfunction(L, i)) { /* avoid 'calling' extra info. */ |
| 562 | | lua_pushvalue(L, i); /* get option (a function) */ |
| 563 | | lua_pushvalue(L, -2); /* module */ |
| 564 | | lua_call(L, 1, 0); |
| 565 | | } |
| 566 | | } |
| 559 | int i; |
| 560 | for (i = 2; i <= n; i++) { |
| 561 | if (lua_isfunction(L, i)) { /* avoid 'calling' extra info. */ |
| 562 | lua_pushvalue(L, i); /* get option (a function) */ |
| 563 | lua_pushvalue(L, -2); /* module */ |
| 564 | lua_call(L, 1, 0); |
| 565 | } |
| 566 | } |
| 567 | 567 | } |
| 568 | 568 | |
| 569 | 569 | |
| 570 | 570 | static void modinit (lua_State *L, const char *modname) { |
| 571 | | const char *dot; |
| 572 | | lua_pushvalue(L, -1); |
| 573 | | lua_setfield(L, -2, "_M"); /* module._M = module */ |
| 574 | | lua_pushstring(L, modname); |
| 575 | | lua_setfield(L, -2, "_NAME"); |
| 576 | | dot = strrchr(modname, '.'); /* look for last dot in module name */ |
| 577 | | if (dot == NULL) dot = modname; |
| 578 | | else dot++; |
| 579 | | /* set _PACKAGE as package name (full module name minus last part) */ |
| 580 | | lua_pushlstring(L, modname, dot - modname); |
| 581 | | lua_setfield(L, -2, "_PACKAGE"); |
| 571 | const char *dot; |
| 572 | lua_pushvalue(L, -1); |
| 573 | lua_setfield(L, -2, "_M"); /* module._M = module */ |
| 574 | lua_pushstring(L, modname); |
| 575 | lua_setfield(L, -2, "_NAME"); |
| 576 | dot = strrchr(modname, '.'); /* look for last dot in module name */ |
| 577 | if (dot == NULL) dot = modname; |
| 578 | else dot++; |
| 579 | /* set _PACKAGE as package name (full module name minus last part) */ |
| 580 | lua_pushlstring(L, modname, dot - modname); |
| 581 | lua_setfield(L, -2, "_PACKAGE"); |
| 582 | 582 | } |
| 583 | 583 | |
| 584 | 584 | |
| 585 | 585 | static int ll_module (lua_State *L) { |
| 586 | | const char *modname = luaL_checkstring(L, 1); |
| 587 | | int lastarg = lua_gettop(L); /* last parameter */ |
| 588 | | luaL_pushmodule(L, modname, 1); /* get/create module table */ |
| 589 | | /* check whether table already has a _NAME field */ |
| 590 | | lua_getfield(L, -1, "_NAME"); |
| 591 | | if (!lua_isnil(L, -1)) /* is table an initialized module? */ |
| 592 | | lua_pop(L, 1); |
| 593 | | else { /* no; initialize it */ |
| 594 | | lua_pop(L, 1); |
| 595 | | modinit(L, modname); |
| 596 | | } |
| 597 | | lua_pushvalue(L, -1); |
| 598 | | set_env(L); |
| 599 | | dooptions(L, lastarg); |
| 600 | | return 1; |
| 586 | const char *modname = luaL_checkstring(L, 1); |
| 587 | int lastarg = lua_gettop(L); /* last parameter */ |
| 588 | luaL_pushmodule(L, modname, 1); /* get/create module table */ |
| 589 | /* check whether table already has a _NAME field */ |
| 590 | lua_getfield(L, -1, "_NAME"); |
| 591 | if (!lua_isnil(L, -1)) /* is table an initialized module? */ |
| 592 | lua_pop(L, 1); |
| 593 | else { /* no; initialize it */ |
| 594 | lua_pop(L, 1); |
| 595 | modinit(L, modname); |
| 596 | } |
| 597 | lua_pushvalue(L, -1); |
| 598 | set_env(L); |
| 599 | dooptions(L, lastarg); |
| 600 | return 1; |
| 601 | 601 | } |
| 602 | 602 | |
| 603 | 603 | |
| 604 | 604 | static int ll_seeall (lua_State *L) { |
| 605 | | luaL_checktype(L, 1, LUA_TTABLE); |
| 606 | | if (!lua_getmetatable(L, 1)) { |
| 607 | | lua_createtable(L, 0, 1); /* create new metatable */ |
| 608 | | lua_pushvalue(L, -1); |
| 609 | | lua_setmetatable(L, 1); |
| 610 | | } |
| 611 | | lua_pushglobaltable(L); |
| 612 | | lua_setfield(L, -2, "__index"); /* mt.__index = _G */ |
| 613 | | return 0; |
| 605 | luaL_checktype(L, 1, LUA_TTABLE); |
| 606 | if (!lua_getmetatable(L, 1)) { |
| 607 | lua_createtable(L, 0, 1); /* create new metatable */ |
| 608 | lua_pushvalue(L, -1); |
| 609 | lua_setmetatable(L, 1); |
| 610 | } |
| 611 | lua_pushglobaltable(L); |
| 612 | lua_setfield(L, -2, "__index"); /* mt.__index = _G */ |
| 613 | return 0; |
| 614 | 614 | } |
| 615 | 615 | |
| 616 | 616 | #endif |
| r30857 | r30858 | |
| 619 | 619 | |
| 620 | 620 | |
| 621 | 621 | /* auxiliary mark (for internal use) */ |
| 622 | | #define AUXMARK "\1" |
| 622 | #define AUXMARK "\1" |
| 623 | 623 | |
| 624 | 624 | |
| 625 | 625 | /* |
| 626 | 626 | ** return registry.LUA_NOENV as a boolean |
| 627 | 627 | */ |
| 628 | 628 | static int noenv (lua_State *L) { |
| 629 | | int b; |
| 630 | | lua_getfield(L, LUA_REGISTRYINDEX, "LUA_NOENV"); |
| 631 | | b = lua_toboolean(L, -1); |
| 632 | | lua_pop(L, 1); /* remove value */ |
| 633 | | return b; |
| 629 | int b; |
| 630 | lua_getfield(L, LUA_REGISTRYINDEX, "LUA_NOENV"); |
| 631 | b = lua_toboolean(L, -1); |
| 632 | lua_pop(L, 1); /* remove value */ |
| 633 | return b; |
| 634 | 634 | } |
| 635 | 635 | |
| 636 | 636 | |
| 637 | 637 | static void setpath (lua_State *L, const char *fieldname, const char *envname1, |
| 638 | | const char *envname2, const char *def) { |
| 639 | | const char *path = getenv(envname1); |
| 640 | | if (path == NULL) /* no environment variable? */ |
| 641 | | path = getenv(envname2); /* try alternative name */ |
| 642 | | if (path == NULL || noenv(L)) /* no environment variable? */ |
| 643 | | lua_pushstring(L, def); /* use default */ |
| 644 | | else { |
| 645 | | /* replace ";;" by ";AUXMARK;" and then AUXMARK by default path */ |
| 646 | | path = luaL_gsub(L, path, LUA_PATH_SEP LUA_PATH_SEP, |
| 647 | | LUA_PATH_SEP AUXMARK LUA_PATH_SEP); |
| 648 | | luaL_gsub(L, path, AUXMARK, def); |
| 649 | | lua_remove(L, -2); |
| 650 | | } |
| 651 | | setprogdir(L); |
| 652 | | lua_setfield(L, -2, fieldname); |
| 638 | const char *envname2, const char *def) { |
| 639 | const char *path = getenv(envname1); |
| 640 | if (path == NULL) /* no environment variable? */ |
| 641 | path = getenv(envname2); /* try alternative name */ |
| 642 | if (path == NULL || noenv(L)) /* no environment variable? */ |
| 643 | lua_pushstring(L, def); /* use default */ |
| 644 | else { |
| 645 | /* replace ";;" by ";AUXMARK;" and then AUXMARK by default path */ |
| 646 | path = luaL_gsub(L, path, LUA_PATH_SEP LUA_PATH_SEP, |
| 647 | LUA_PATH_SEP AUXMARK LUA_PATH_SEP); |
| 648 | luaL_gsub(L, path, AUXMARK, def); |
| 649 | lua_remove(L, -2); |
| 650 | } |
| 651 | setprogdir(L); |
| 652 | lua_setfield(L, -2, fieldname); |
| 653 | 653 | } |
| 654 | 654 | |
| 655 | 655 | |
| 656 | 656 | static const luaL_Reg pk_funcs[] = { |
| 657 | | {"loadlib", ll_loadlib}, |
| 658 | | {"searchpath", ll_searchpath}, |
| 657 | {"loadlib", ll_loadlib}, |
| 658 | {"searchpath", ll_searchpath}, |
| 659 | 659 | #if defined(LUA_COMPAT_MODULE) |
| 660 | | {"seeall", ll_seeall}, |
| 660 | {"seeall", ll_seeall}, |
| 661 | 661 | #endif |
| 662 | | {NULL, NULL} |
| 662 | {NULL, NULL} |
| 663 | 663 | }; |
| 664 | 664 | |
| 665 | 665 | |
| 666 | 666 | static const luaL_Reg ll_funcs[] = { |
| 667 | 667 | #if defined(LUA_COMPAT_MODULE) |
| 668 | | {"module", ll_module}, |
| 668 | {"module", ll_module}, |
| 669 | 669 | #endif |
| 670 | | {"require", ll_require}, |
| 671 | | {NULL, NULL} |
| 670 | {"require", ll_require}, |
| 671 | {NULL, NULL} |
| 672 | 672 | }; |
| 673 | 673 | |
| 674 | 674 | |
| 675 | 675 | static void createsearcherstable (lua_State *L) { |
| 676 | | static const lua_CFunction searchers[] = |
| 677 | | {searcher_preload, searcher_Lua, searcher_C, searcher_Croot, NULL}; |
| 678 | | int i; |
| 679 | | /* create 'searchers' table */ |
| 680 | | lua_createtable(L, sizeof(searchers)/sizeof(searchers[0]) - 1, 0); |
| 681 | | /* fill it with pre-defined searchers */ |
| 682 | | for (i=0; searchers[i] != NULL; i++) { |
| 683 | | lua_pushvalue(L, -2); /* set 'package' as upvalue for all searchers */ |
| 684 | | lua_pushcclosure(L, searchers[i], 1); |
| 685 | | lua_rawseti(L, -2, i+1); |
| 686 | | } |
| 676 | static const lua_CFunction searchers[] = |
| 677 | {searcher_preload, searcher_Lua, searcher_C, searcher_Croot, NULL}; |
| 678 | int i; |
| 679 | /* create 'searchers' table */ |
| 680 | lua_createtable(L, sizeof(searchers)/sizeof(searchers[0]) - 1, 0); |
| 681 | /* fill it with pre-defined searchers */ |
| 682 | for (i=0; searchers[i] != NULL; i++) { |
| 683 | lua_pushvalue(L, -2); /* set 'package' as upvalue for all searchers */ |
| 684 | lua_pushcclosure(L, searchers[i], 1); |
| 685 | lua_rawseti(L, -2, i+1); |
| 686 | } |
| 687 | 687 | } |
| 688 | 688 | |
| 689 | 689 | |
| 690 | 690 | LUAMOD_API int luaopen_package (lua_State *L) { |
| 691 | | /* create table CLIBS to keep track of loaded C libraries */ |
| 692 | | luaL_getsubtable(L, LUA_REGISTRYINDEX, CLIBS); |
| 693 | | lua_createtable(L, 0, 1); /* metatable for CLIBS */ |
| 694 | | lua_pushcfunction(L, gctm); |
| 695 | | lua_setfield(L, -2, "__gc"); /* set finalizer for CLIBS table */ |
| 696 | | lua_setmetatable(L, -2); |
| 697 | | /* create `package' table */ |
| 698 | | luaL_newlib(L, pk_funcs); |
| 699 | | createsearcherstable(L); |
| 691 | /* create table CLIBS to keep track of loaded C libraries */ |
| 692 | luaL_getsubtable(L, LUA_REGISTRYINDEX, CLIBS); |
| 693 | lua_createtable(L, 0, 1); /* metatable for CLIBS */ |
| 694 | lua_pushcfunction(L, gctm); |
| 695 | lua_setfield(L, -2, "__gc"); /* set finalizer for CLIBS table */ |
| 696 | lua_setmetatable(L, -2); |
| 697 | /* create `package' table */ |
| 698 | luaL_newlib(L, pk_funcs); |
| 699 | createsearcherstable(L); |
| 700 | 700 | #if defined(LUA_COMPAT_LOADERS) |
| 701 | | lua_pushvalue(L, -1); /* make a copy of 'searchers' table */ |
| 702 | | lua_setfield(L, -3, "loaders"); /* put it in field `loaders' */ |
| 701 | lua_pushvalue(L, -1); /* make a copy of 'searchers' table */ |
| 702 | lua_setfield(L, -3, "loaders"); /* put it in field `loaders' */ |
| 703 | 703 | #endif |
| 704 | | lua_setfield(L, -2, "searchers"); /* put it in field 'searchers' */ |
| 705 | | /* set field 'path' */ |
| 706 | | setpath(L, "path", LUA_PATHVERSION, LUA_PATH, LUA_PATH_DEFAULT); |
| 707 | | /* set field 'cpath' */ |
| 708 | | setpath(L, "cpath", LUA_CPATHVERSION, LUA_CPATH, LUA_CPATH_DEFAULT); |
| 709 | | /* store config information */ |
| 710 | | lua_pushliteral(L, LUA_DIRSEP "\n" LUA_PATH_SEP "\n" LUA_PATH_MARK "\n" |
| 711 | | LUA_EXEC_DIR "\n" LUA_IGMARK "\n"); |
| 712 | | lua_setfield(L, -2, "config"); |
| 713 | | /* set field `loaded' */ |
| 714 | | luaL_getsubtable(L, LUA_REGISTRYINDEX, "_LOADED"); |
| 715 | | lua_setfield(L, -2, "loaded"); |
| 716 | | /* set field `preload' */ |
| 717 | | luaL_getsubtable(L, LUA_REGISTRYINDEX, "_PRELOAD"); |
| 718 | | lua_setfield(L, -2, "preload"); |
| 719 | | lua_pushglobaltable(L); |
| 720 | | lua_pushvalue(L, -2); /* set 'package' as upvalue for next lib */ |
| 721 | | luaL_setfuncs(L, ll_funcs, 1); /* open lib into global table */ |
| 722 | | lua_pop(L, 1); /* pop global table */ |
| 723 | | return 1; /* return 'package' table */ |
| 704 | lua_setfield(L, -2, "searchers"); /* put it in field 'searchers' */ |
| 705 | /* set field 'path' */ |
| 706 | setpath(L, "path", LUA_PATHVERSION, LUA_PATH, LUA_PATH_DEFAULT); |
| 707 | /* set field 'cpath' */ |
| 708 | setpath(L, "cpath", LUA_CPATHVERSION, LUA_CPATH, LUA_CPATH_DEFAULT); |
| 709 | /* store config information */ |
| 710 | lua_pushliteral(L, LUA_DIRSEP "\n" LUA_PATH_SEP "\n" LUA_PATH_MARK "\n" |
| 711 | LUA_EXEC_DIR "\n" LUA_IGMARK "\n"); |
| 712 | lua_setfield(L, -2, "config"); |
| 713 | /* set field `loaded' */ |
| 714 | luaL_getsubtable(L, LUA_REGISTRYINDEX, "_LOADED"); |
| 715 | lua_setfield(L, -2, "loaded"); |
| 716 | /* set field `preload' */ |
| 717 | luaL_getsubtable(L, LUA_REGISTRYINDEX, "_PRELOAD"); |
| 718 | lua_setfield(L, -2, "preload"); |
| 719 | lua_pushglobaltable(L); |
| 720 | lua_pushvalue(L, -2); /* set 'package' as upvalue for next lib */ |
| 721 | luaL_setfuncs(L, ll_funcs, 1); /* open lib into global table */ |
| 722 | lua_pop(L, 1); /* pop global table */ |
| 723 | return 1; /* return 'package' table */ |
| 724 | 724 | } |
| 725 | |
trunk/src/lib/lua/lparser.c
| r30857 | r30858 | |
| 1 | 1 | /* |
| 2 | | ** $Id: lparser.c,v 2.130 2013/02/06 13:37:39 roberto Exp $ |
| 2 | ** $Id: lparser.c,v 2.130.1.1 2013/04/12 18:48:47 roberto Exp $ |
| 3 | 3 | ** Lua Parser |
| 4 | 4 | ** See Copyright Notice in lua.h |
| 5 | 5 | */ |
| r30857 | r30858 | |
| 29 | 29 | |
| 30 | 30 | /* maximum number of local variables per function (must be smaller |
| 31 | 31 | than 250, due to the bytecode format) */ |
| 32 | | #define MAXVARS 200 |
| 32 | #define MAXVARS 200 |
| 33 | 33 | |
| 34 | 34 | |
| 35 | | #define hasmultret(k) ((k) == VCALL || (k) == VVARARG) |
| 35 | #define hasmultret(k) ((k) == VCALL || (k) == VVARARG) |
| 36 | 36 | |
| 37 | 37 | |
| 38 | 38 | |
| r30857 | r30858 | |
| 40 | 40 | ** nodes for block list (list of active blocks) |
| 41 | 41 | */ |
| 42 | 42 | typedef struct BlockCnt { |
| 43 | | struct BlockCnt *previous; /* chain */ |
| 44 | | short firstlabel; /* index of first label in this block */ |
| 45 | | short firstgoto; /* index of first pending goto in this block */ |
| 46 | | lu_byte nactvar; /* # active locals outside the block */ |
| 47 | | lu_byte upval; /* true if some variable in the block is an upvalue */ |
| 48 | | lu_byte isloop; /* true if `block' is a loop */ |
| 43 | struct BlockCnt *previous; /* chain */ |
| 44 | short firstlabel; /* index of first label in this block */ |
| 45 | short firstgoto; /* index of first pending goto in this block */ |
| 46 | lu_byte nactvar; /* # active locals outside the block */ |
| 47 | lu_byte upval; /* true if some variable in the block is an upvalue */ |
| 48 | lu_byte isloop; /* true if `block' is a loop */ |
| 49 | 49 | } BlockCnt; |
| 50 | 50 | |
| 51 | 51 | |
| r30857 | r30858 | |
| 58 | 58 | |
| 59 | 59 | |
| 60 | 60 | static void anchor_token (LexState *ls) { |
| 61 | | /* last token from outer function must be EOS */ |
| 62 | | lua_assert(ls->fs != NULL || ls->t.token == TK_EOS); |
| 63 | | if (ls->t.token == TK_NAME || ls->t.token == TK_STRING) { |
| 64 | | TString *ts = ls->t.seminfo.ts; |
| 65 | | luaX_newstring(ls, getstr(ts), ts->tsv.len); |
| 66 | | } |
| 61 | /* last token from outer function must be EOS */ |
| 62 | lua_assert(ls->fs != NULL || ls->t.token == TK_EOS); |
| 63 | if (ls->t.token == TK_NAME || ls->t.token == TK_STRING) { |
| 64 | TString *ts = ls->t.seminfo.ts; |
| 65 | luaX_newstring(ls, getstr(ts), ts->tsv.len); |
| 66 | } |
| 67 | 67 | } |
| 68 | 68 | |
| 69 | 69 | |
| 70 | 70 | /* semantic error */ |
| 71 | 71 | static l_noret semerror (LexState *ls, const char *msg) { |
| 72 | | ls->t.token = 0; /* remove 'near to' from final message */ |
| 73 | | luaX_syntaxerror(ls, msg); |
| 72 | ls->t.token = 0; /* remove 'near to' from final message */ |
| 73 | luaX_syntaxerror(ls, msg); |
| 74 | 74 | } |
| 75 | 75 | |
| 76 | 76 | |
| 77 | 77 | static l_noret error_expected (LexState *ls, int token) { |
| 78 | | luaX_syntaxerror(ls, |
| 79 | | luaO_pushfstring(ls->L, "%s expected", luaX_token2str(ls, token))); |
| 78 | luaX_syntaxerror(ls, |
| 79 | luaO_pushfstring(ls->L, "%s expected", luaX_token2str(ls, token))); |
| 80 | 80 | } |
| 81 | 81 | |
| 82 | 82 | |
| 83 | 83 | static l_noret errorlimit (FuncState *fs, int limit, const char *what) { |
| 84 | | lua_State *L = fs->ls->L; |
| 85 | | const char *msg; |
| 86 | | int line = fs->f->linedefined; |
| 87 | | const char *where = (line == 0) |
| 88 | | ? "main function" |
| 89 | | : luaO_pushfstring(L, "function at line %d", line); |
| 90 | | msg = luaO_pushfstring(L, "too many %s (limit is %d) in %s", |
| 91 | | what, limit, where); |
| 92 | | luaX_syntaxerror(fs->ls, msg); |
| 84 | lua_State *L = fs->ls->L; |
| 85 | const char *msg; |
| 86 | int line = fs->f->linedefined; |
| 87 | const char *where = (line == 0) |
| 88 | ? "main function" |
| 89 | : luaO_pushfstring(L, "function at line %d", line); |
| 90 | msg = luaO_pushfstring(L, "too many %s (limit is %d) in %s", |
| 91 | what, limit, where); |
| 92 | luaX_syntaxerror(fs->ls, msg); |
| 93 | 93 | } |
| 94 | 94 | |
| 95 | 95 | |
| 96 | 96 | static void checklimit (FuncState *fs, int v, int l, const char *what) { |
| 97 | | if (v > l) errorlimit(fs, l, what); |
| 97 | if (v > l) errorlimit(fs, l, what); |
| 98 | 98 | } |
| 99 | 99 | |
| 100 | 100 | |
| 101 | 101 | static int testnext (LexState *ls, int c) { |
| 102 | | if (ls->t.token == c) { |
| 103 | | luaX_next(ls); |
| 104 | | return 1; |
| 105 | | } |
| 106 | | else return 0; |
| 102 | if (ls->t.token == c) { |
| 103 | luaX_next(ls); |
| 104 | return 1; |
| 105 | } |
| 106 | else return 0; |
| 107 | 107 | } |
| 108 | 108 | |
| 109 | 109 | |
| 110 | 110 | static void check (LexState *ls, int c) { |
| 111 | | if (ls->t.token != c) |
| 112 | | error_expected(ls, c); |
| 111 | if (ls->t.token != c) |
| 112 | error_expected(ls, c); |
| 113 | 113 | } |
| 114 | 114 | |
| 115 | 115 | |
| 116 | 116 | static void checknext (LexState *ls, int c) { |
| 117 | | check(ls, c); |
| 118 | | luaX_next(ls); |
| 117 | check(ls, c); |
| 118 | luaX_next(ls); |
| 119 | 119 | } |
| 120 | 120 | |
| 121 | 121 | |
| 122 | | #define check_condition(ls,c,msg) { if (!(c)) luaX_syntaxerror(ls, msg); } |
| 122 | #define check_condition(ls,c,msg) { if (!(c)) luaX_syntaxerror(ls, msg); } |
| 123 | 123 | |
| 124 | 124 | |
| 125 | 125 | |
| 126 | 126 | static void check_match (LexState *ls, int what, int who, int where) { |
| 127 | | if (!testnext(ls, what)) { |
| 128 | | if (where == ls->linenumber) |
| 129 | | error_expected(ls, what); |
| 130 | | else { |
| 131 | | luaX_syntaxerror(ls, luaO_pushfstring(ls->L, |
| 132 | | "%s expected (to close %s at line %d)", |
| 133 | | luaX_token2str(ls, what), luaX_token2str(ls, who), where)); |
| 134 | | } |
| 135 | | } |
| 127 | if (!testnext(ls, what)) { |
| 128 | if (where == ls->linenumber) |
| 129 | error_expected(ls, what); |
| 130 | else { |
| 131 | luaX_syntaxerror(ls, luaO_pushfstring(ls->L, |
| 132 | "%s expected (to close %s at line %d)", |
| 133 | luaX_token2str(ls, what), luaX_token2str(ls, who), where)); |
| 134 | } |
| 135 | } |
| 136 | 136 | } |
| 137 | 137 | |
| 138 | 138 | |
| 139 | 139 | static TString *str_checkname (LexState *ls) { |
| 140 | | TString *ts; |
| 141 | | check(ls, TK_NAME); |
| 142 | | ts = ls->t.seminfo.ts; |
| 143 | | luaX_next(ls); |
| 144 | | return ts; |
| 140 | TString *ts; |
| 141 | check(ls, TK_NAME); |
| 142 | ts = ls->t.seminfo.ts; |
| 143 | luaX_next(ls); |
| 144 | return ts; |
| 145 | 145 | } |
| 146 | 146 | |
| 147 | 147 | |
| 148 | 148 | static void init_exp (expdesc *e, expkind k, int i) { |
| 149 | | e->f = e->t = NO_JUMP; |
| 150 | | e->k = k; |
| 151 | | e->u.info = i; |
| 149 | e->f = e->t = NO_JUMP; |
| 150 | e->k = k; |
| 151 | e->u.info = i; |
| 152 | 152 | } |
| 153 | 153 | |
| 154 | 154 | |
| 155 | 155 | static void codestring (LexState *ls, expdesc *e, TString *s) { |
| 156 | | init_exp(e, VK, luaK_stringK(ls->fs, s)); |
| 156 | init_exp(e, VK, luaK_stringK(ls->fs, s)); |
| 157 | 157 | } |
| 158 | 158 | |
| 159 | 159 | |
| 160 | 160 | static void checkname (LexState *ls, expdesc *e) { |
| 161 | | codestring(ls, e, str_checkname(ls)); |
| 161 | codestring(ls, e, str_checkname(ls)); |
| 162 | 162 | } |
| 163 | 163 | |
| 164 | 164 | |
| 165 | 165 | static int registerlocalvar (LexState *ls, TString *varname) { |
| 166 | | FuncState *fs = ls->fs; |
| 167 | | Proto *f = fs->f; |
| 168 | | int oldsize = f->sizelocvars; |
| 169 | | luaM_growvector(ls->L, f->locvars, fs->nlocvars, f->sizelocvars, |
| 170 | | LocVar, SHRT_MAX, "local variables"); |
| 171 | | while (oldsize < f->sizelocvars) f->locvars[oldsize++].varname = NULL; |
| 172 | | f->locvars[fs->nlocvars].varname = varname; |
| 173 | | luaC_objbarrier(ls->L, f, varname); |
| 174 | | return fs->nlocvars++; |
| 166 | FuncState *fs = ls->fs; |
| 167 | Proto *f = fs->f; |
| 168 | int oldsize = f->sizelocvars; |
| 169 | luaM_growvector(ls->L, f->locvars, fs->nlocvars, f->sizelocvars, |
| 170 | LocVar, SHRT_MAX, "local variables"); |
| 171 | while (oldsize < f->sizelocvars) f->locvars[oldsize++].varname = NULL; |
| 172 | f->locvars[fs->nlocvars].varname = varname; |
| 173 | luaC_objbarrier(ls->L, f, varname); |
| 174 | return fs->nlocvars++; |
| 175 | 175 | } |
| 176 | 176 | |
| 177 | 177 | |
| 178 | 178 | static void new_localvar (LexState *ls, TString *name) { |
| 179 | | FuncState *fs = ls->fs; |
| 180 | | Dyndata *dyd = ls->dyd; |
| 181 | | int reg = registerlocalvar(ls, name); |
| 182 | | checklimit(fs, dyd->actvar.n + 1 - fs->firstlocal, |
| 183 | | MAXVARS, "local variables"); |
| 184 | | luaM_growvector(ls->L, dyd->actvar.arr, dyd->actvar.n + 1, |
| 185 | | dyd->actvar.size, Vardesc, MAX_INT, "local variables"); |
| 186 | | dyd->actvar.arr[dyd->actvar.n++].idx = cast(short, reg); |
| 179 | FuncState *fs = ls->fs; |
| 180 | Dyndata *dyd = ls->dyd; |
| 181 | int reg = registerlocalvar(ls, name); |
| 182 | checklimit(fs, dyd->actvar.n + 1 - fs->firstlocal, |
| 183 | MAXVARS, "local variables"); |
| 184 | luaM_growvector(ls->L, dyd->actvar.arr, dyd->actvar.n + 1, |
| 185 | dyd->actvar.size, Vardesc, MAX_INT, "local variables"); |
| 186 | dyd->actvar.arr[dyd->actvar.n++].idx = cast(short, reg); |
| 187 | 187 | } |
| 188 | 188 | |
| 189 | 189 | |
| 190 | 190 | static void new_localvarliteral_ (LexState *ls, const char *name, size_t sz) { |
| 191 | | new_localvar(ls, luaX_newstring(ls, name, sz)); |
| 191 | new_localvar(ls, luaX_newstring(ls, name, sz)); |
| 192 | 192 | } |
| 193 | 193 | |
| 194 | 194 | #define new_localvarliteral(ls,v) \ |
| r30857 | r30858 | |
| 196 | 196 | |
| 197 | 197 | |
| 198 | 198 | static LocVar *getlocvar (FuncState *fs, int i) { |
| 199 | | int idx = fs->ls->dyd->actvar.arr[fs->firstlocal + i].idx; |
| 200 | | lua_assert(idx < fs->nlocvars); |
| 201 | | return &fs->f->locvars[idx]; |
| 199 | int idx = fs->ls->dyd->actvar.arr[fs->firstlocal + i].idx; |
| 200 | lua_assert(idx < fs->nlocvars); |
| 201 | return &fs->f->locvars[idx]; |
| 202 | 202 | } |
| 203 | 203 | |
| 204 | 204 | |
| 205 | 205 | static void adjustlocalvars (LexState *ls, int nvars) { |
| 206 | | FuncState *fs = ls->fs; |
| 207 | | fs->nactvar = cast_byte(fs->nactvar + nvars); |
| 208 | | for (; nvars; nvars--) { |
| 209 | | getlocvar(fs, fs->nactvar - nvars)->startpc = fs->pc; |
| 210 | | } |
| 206 | FuncState *fs = ls->fs; |
| 207 | fs->nactvar = cast_byte(fs->nactvar + nvars); |
| 208 | for (; nvars; nvars--) { |
| 209 | getlocvar(fs, fs->nactvar - nvars)->startpc = fs->pc; |
| 210 | } |
| 211 | 211 | } |
| 212 | 212 | |
| 213 | 213 | |
| 214 | 214 | static void removevars (FuncState *fs, int tolevel) { |
| 215 | | fs->ls->dyd->actvar.n -= (fs->nactvar - tolevel); |
| 216 | | while (fs->nactvar > tolevel) |
| 217 | | getlocvar(fs, --fs->nactvar)->endpc = fs->pc; |
| 215 | fs->ls->dyd->actvar.n -= (fs->nactvar - tolevel); |
| 216 | while (fs->nactvar > tolevel) |
| 217 | getlocvar(fs, --fs->nactvar)->endpc = fs->pc; |
| 218 | 218 | } |
| 219 | 219 | |
| 220 | 220 | |
| 221 | 221 | static int searchupvalue (FuncState *fs, TString *name) { |
| 222 | | int i; |
| 223 | | Upvaldesc *up = fs->f->upvalues; |
| 224 | | for (i = 0; i < fs->nups; i++) { |
| 225 | | if (luaS_eqstr(up[i].name, name)) return i; |
| 226 | | } |
| 227 | | return -1; /* not found */ |
| 222 | int i; |
| 223 | Upvaldesc *up = fs->f->upvalues; |
| 224 | for (i = 0; i < fs->nups; i++) { |
| 225 | if (luaS_eqstr(up[i].name, name)) return i; |
| 226 | } |
| 227 | return -1; /* not found */ |
| 228 | 228 | } |
| 229 | 229 | |
| 230 | 230 | |
| 231 | 231 | static int newupvalue (FuncState *fs, TString *name, expdesc *v) { |
| 232 | | Proto *f = fs->f; |
| 233 | | int oldsize = f->sizeupvalues; |
| 234 | | checklimit(fs, fs->nups + 1, MAXUPVAL, "upvalues"); |
| 235 | | luaM_growvector(fs->ls->L, f->upvalues, fs->nups, f->sizeupvalues, |
| 236 | | Upvaldesc, MAXUPVAL, "upvalues"); |
| 237 | | while (oldsize < f->sizeupvalues) f->upvalues[oldsize++].name = NULL; |
| 238 | | f->upvalues[fs->nups].instack = (v->k == VLOCAL); |
| 239 | | f->upvalues[fs->nups].idx = cast_byte(v->u.info); |
| 240 | | f->upvalues[fs->nups].name = name; |
| 241 | | luaC_objbarrier(fs->ls->L, f, name); |
| 242 | | return fs->nups++; |
| 232 | Proto *f = fs->f; |
| 233 | int oldsize = f->sizeupvalues; |
| 234 | checklimit(fs, fs->nups + 1, MAXUPVAL, "upvalues"); |
| 235 | luaM_growvector(fs->ls->L, f->upvalues, fs->nups, f->sizeupvalues, |
| 236 | Upvaldesc, MAXUPVAL, "upvalues"); |
| 237 | while (oldsize < f->sizeupvalues) f->upvalues[oldsize++].name = NULL; |
| 238 | f->upvalues[fs->nups].instack = (v->k == VLOCAL); |
| 239 | f->upvalues[fs->nups].idx = cast_byte(v->u.info); |
| 240 | f->upvalues[fs->nups].name = name; |
| 241 | luaC_objbarrier(fs->ls->L, f, name); |
| 242 | return fs->nups++; |
| 243 | 243 | } |
| 244 | 244 | |
| 245 | 245 | |
| 246 | 246 | static int searchvar (FuncState *fs, TString *n) { |
| 247 | | int i; |
| 248 | | for (i = cast_int(fs->nactvar) - 1; i >= 0; i--) { |
| 249 | | if (luaS_eqstr(n, getlocvar(fs, i)->varname)) |
| 250 | | return i; |
| 251 | | } |
| 252 | | return -1; /* not found */ |
| 247 | int i; |
| 248 | for (i = cast_int(fs->nactvar) - 1; i >= 0; i--) { |
| 249 | if (luaS_eqstr(n, getlocvar(fs, i)->varname)) |
| 250 | return i; |
| 251 | } |
| 252 | return -1; /* not found */ |
| 253 | 253 | } |
| 254 | 254 | |
| 255 | 255 | |
| r30857 | r30858 | |
| 258 | 258 | (to emit close instructions later). |
| 259 | 259 | */ |
| 260 | 260 | static void markupval (FuncState *fs, int level) { |
| 261 | | BlockCnt *bl = fs->bl; |
| 262 | | while (bl->nactvar > level) bl = bl->previous; |
| 263 | | bl->upval = 1; |
| 261 | BlockCnt *bl = fs->bl; |
| 262 | while (bl->nactvar > level) bl = bl->previous; |
| 263 | bl->upval = 1; |
| 264 | 264 | } |
| 265 | 265 | |
| 266 | 266 | |
| r30857 | r30858 | |
| 269 | 269 | upvalue into all intermediate functions. |
| 270 | 270 | */ |
| 271 | 271 | static int singlevaraux (FuncState *fs, TString *n, expdesc *var, int base) { |
| 272 | | if (fs == NULL) /* no more levels? */ |
| 273 | | return VVOID; /* default is global */ |
| 274 | | else { |
| 275 | | int v = searchvar(fs, n); /* look up locals at current level */ |
| 276 | | if (v >= 0) { /* found? */ |
| 277 | | init_exp(var, VLOCAL, v); /* variable is local */ |
| 278 | | if (!base) |
| 279 | | markupval(fs, v); /* local will be used as an upval */ |
| 280 | | return VLOCAL; |
| 281 | | } |
| 282 | | else { /* not found as local at current level; try upvalues */ |
| 283 | | int idx = searchupvalue(fs, n); /* try existing upvalues */ |
| 284 | | if (idx < 0) { /* not found? */ |
| 285 | | if (singlevaraux(fs->prev, n, var, 0) == VVOID) /* try upper levels */ |
| 286 | | return VVOID; /* not found; is a global */ |
| 287 | | /* else was LOCAL or UPVAL */ |
| 288 | | idx = newupvalue(fs, n, var); /* will be a new upvalue */ |
| 289 | | } |
| 290 | | init_exp(var, VUPVAL, idx); |
| 291 | | return VUPVAL; |
| 292 | | } |
| 293 | | } |
| 272 | if (fs == NULL) /* no more levels? */ |
| 273 | return VVOID; /* default is global */ |
| 274 | else { |
| 275 | int v = searchvar(fs, n); /* look up locals at current level */ |
| 276 | if (v >= 0) { /* found? */ |
| 277 | init_exp(var, VLOCAL, v); /* variable is local */ |
| 278 | if (!base) |
| 279 | markupval(fs, v); /* local will be used as an upval */ |
| 280 | return VLOCAL; |
| 281 | } |
| 282 | else { /* not found as local at current level; try upvalues */ |
| 283 | int idx = searchupvalue(fs, n); /* try existing upvalues */ |
| 284 | if (idx < 0) { /* not found? */ |
| 285 | if (singlevaraux(fs->prev, n, var, 0) == VVOID) /* try upper levels */ |
| 286 | return VVOID; /* not found; is a global */ |
| 287 | /* else was LOCAL or UPVAL */ |
| 288 | idx = newupvalue(fs, n, var); /* will be a new upvalue */ |
| 289 | } |
| 290 | init_exp(var, VUPVAL, idx); |
| 291 | return VUPVAL; |
| 292 | } |
| 293 | } |
| 294 | 294 | } |
| 295 | 295 | |
| 296 | 296 | |
| 297 | 297 | static void singlevar (LexState *ls, expdesc *var) { |
| 298 | | TString *varname = str_checkname(ls); |
| 299 | | FuncState *fs = ls->fs; |
| 300 | | if (singlevaraux(fs, varname, var, 1) == VVOID) { /* global name? */ |
| 301 | | expdesc key; |
| 302 | | singlevaraux(fs, ls->envn, var, 1); /* get environment variable */ |
| 303 | | lua_assert(var->k == VLOCAL || var->k == VUPVAL); |
| 304 | | codestring(ls, &key, varname); /* key is variable name */ |
| 305 | | luaK_indexed(fs, var, &key); /* env[varname] */ |
| 306 | | } |
| 298 | TString *varname = str_checkname(ls); |
| 299 | FuncState *fs = ls->fs; |
| 300 | if (singlevaraux(fs, varname, var, 1) == VVOID) { /* global name? */ |
| 301 | expdesc key; |
| 302 | singlevaraux(fs, ls->envn, var, 1); /* get environment variable */ |
| 303 | lua_assert(var->k == VLOCAL || var->k == VUPVAL); |
| 304 | codestring(ls, &key, varname); /* key is variable name */ |
| 305 | luaK_indexed(fs, var, &key); /* env[varname] */ |
| 306 | } |
| 307 | 307 | } |
| 308 | 308 | |
| 309 | 309 | |
| 310 | 310 | static void adjust_assign (LexState *ls, int nvars, int nexps, expdesc *e) { |
| 311 | | FuncState *fs = ls->fs; |
| 312 | | int extra = nvars - nexps; |
| 313 | | if (hasmultret(e->k)) { |
| 314 | | extra++; /* includes call itself */ |
| 315 | | if (extra < 0) extra = 0; |
| 316 | | luaK_setreturns(fs, e, extra); /* last exp. provides the difference */ |
| 317 | | if (extra > 1) luaK_reserveregs(fs, extra-1); |
| 318 | | } |
| 319 | | else { |
| 320 | | if (e->k != VVOID) luaK_exp2nextreg(fs, e); /* close last expression */ |
| 321 | | if (extra > 0) { |
| 322 | | int reg = fs->freereg; |
| 323 | | luaK_reserveregs(fs, extra); |
| 324 | | luaK_nil(fs, reg, extra); |
| 325 | | } |
| 326 | | } |
| 311 | FuncState *fs = ls->fs; |
| 312 | int extra = nvars - nexps; |
| 313 | if (hasmultret(e->k)) { |
| 314 | extra++; /* includes call itself */ |
| 315 | if (extra < 0) extra = 0; |
| 316 | luaK_setreturns(fs, e, extra); /* last exp. provides the difference */ |
| 317 | if (extra > 1) luaK_reserveregs(fs, extra-1); |
| 318 | } |
| 319 | else { |
| 320 | if (e->k != VVOID) luaK_exp2nextreg(fs, e); /* close last expression */ |
| 321 | if (extra > 0) { |
| 322 | int reg = fs->freereg; |
| 323 | luaK_reserveregs(fs, extra); |
| 324 | luaK_nil(fs, reg, extra); |
| 325 | } |
| 326 | } |
| 327 | 327 | } |
| 328 | 328 | |
| 329 | 329 | |
| 330 | 330 | static void enterlevel (LexState *ls) { |
| 331 | | lua_State *L = ls->L; |
| 332 | | ++L->nCcalls; |
| 333 | | checklimit(ls->fs, L->nCcalls, LUAI_MAXCCALLS, "C levels"); |
| 331 | lua_State *L = ls->L; |
| 332 | ++L->nCcalls; |
| 333 | checklimit(ls->fs, L->nCcalls, LUAI_MAXCCALLS, "C levels"); |
| 334 | 334 | } |
| 335 | 335 | |
| 336 | 336 | |
| 337 | | #define leavelevel(ls) ((ls)->L->nCcalls--) |
| 337 | #define leavelevel(ls) ((ls)->L->nCcalls--) |
| 338 | 338 | |
| 339 | 339 | |
| 340 | 340 | static void closegoto (LexState *ls, int g, Labeldesc *label) { |
| 341 | | int i; |
| 342 | | FuncState *fs = ls->fs; |
| 343 | | Labellist *gl = &ls->dyd->gt; |
| 344 | | Labeldesc *gt = &gl->arr[g]; |
| 345 | | lua_assert(luaS_eqstr(gt->name, label->name)); |
| 346 | | if (gt->nactvar < label->nactvar) { |
| 347 | | TString *vname = getlocvar(fs, gt->nactvar)->varname; |
| 348 | | const char *msg = luaO_pushfstring(ls->L, |
| 349 | | "<goto %s> at line %d jumps into the scope of local " LUA_QS, |
| 350 | | getstr(gt->name), gt->line, getstr(vname)); |
| 351 | | semerror(ls, msg); |
| 352 | | } |
| 353 | | luaK_patchlist(fs, gt->pc, label->pc); |
| 354 | | /* remove goto from pending list */ |
| 355 | | for (i = g; i < gl->n - 1; i++) |
| 356 | | gl->arr[i] = gl->arr[i + 1]; |
| 357 | | gl->n--; |
| 341 | int i; |
| 342 | FuncState *fs = ls->fs; |
| 343 | Labellist *gl = &ls->dyd->gt; |
| 344 | Labeldesc *gt = &gl->arr[g]; |
| 345 | lua_assert(luaS_eqstr(gt->name, label->name)); |
| 346 | if (gt->nactvar < label->nactvar) { |
| 347 | TString *vname = getlocvar(fs, gt->nactvar)->varname; |
| 348 | const char *msg = luaO_pushfstring(ls->L, |
| 349 | "<goto %s> at line %d jumps into the scope of local " LUA_QS, |
| 350 | getstr(gt->name), gt->line, getstr(vname)); |
| 351 | semerror(ls, msg); |
| 352 | } |
| 353 | luaK_patchlist(fs, gt->pc, label->pc); |
| 354 | /* remove goto from pending list */ |
| 355 | for (i = g; i < gl->n - 1; i++) |
| 356 | gl->arr[i] = gl->arr[i + 1]; |
| 357 | gl->n--; |
| 358 | 358 | } |
| 359 | 359 | |
| 360 | 360 | |
| r30857 | r30858 | |
| 362 | 362 | ** try to close a goto with existing labels; this solves backward jumps |
| 363 | 363 | */ |
| 364 | 364 | static int findlabel (LexState *ls, int g) { |
| 365 | | int i; |
| 366 | | BlockCnt *bl = ls->fs->bl; |
| 367 | | Dyndata *dyd = ls->dyd; |
| 368 | | Labeldesc *gt = &dyd->gt.arr[g]; |
| 369 | | /* check labels in current block for a match */ |
| 370 | | for (i = bl->firstlabel; i < dyd->label.n; i++) { |
| 371 | | Labeldesc *lb = &dyd->label.arr[i]; |
| 372 | | if (luaS_eqstr(lb->name, gt->name)) { /* correct label? */ |
| 373 | | if (gt->nactvar > lb->nactvar && |
| 374 | | (bl->upval || dyd->label.n > bl->firstlabel)) |
| 375 | | luaK_patchclose(ls->fs, gt->pc, lb->nactvar); |
| 376 | | closegoto(ls, g, lb); /* close it */ |
| 377 | | return 1; |
| 378 | | } |
| 379 | | } |
| 380 | | return 0; /* label not found; cannot close goto */ |
| 365 | int i; |
| 366 | BlockCnt *bl = ls->fs->bl; |
| 367 | Dyndata *dyd = ls->dyd; |
| 368 | Labeldesc *gt = &dyd->gt.arr[g]; |
| 369 | /* check labels in current block for a match */ |
| 370 | for (i = bl->firstlabel; i < dyd->label.n; i++) { |
| 371 | Labeldesc *lb = &dyd->label.arr[i]; |
| 372 | if (luaS_eqstr(lb->name, gt->name)) { /* correct label? */ |
| 373 | if (gt->nactvar > lb->nactvar && |
| 374 | (bl->upval || dyd->label.n > bl->firstlabel)) |
| 375 | luaK_patchclose(ls->fs, gt->pc, lb->nactvar); |
| 376 | closegoto(ls, g, lb); /* close it */ |
| 377 | return 1; |
| 378 | } |
| 379 | } |
| 380 | return 0; /* label not found; cannot close goto */ |
| 381 | 381 | } |
| 382 | 382 | |
| 383 | 383 | |
| 384 | 384 | static int newlabelentry (LexState *ls, Labellist *l, TString *name, |
| 385 | | int line, int pc) { |
| 386 | | int n = l->n; |
| 387 | | luaM_growvector(ls->L, l->arr, n, l->size, |
| 388 | | Labeldesc, SHRT_MAX, "labels/gotos"); |
| 389 | | l->arr[n].name = name; |
| 390 | | l->arr[n].line = line; |
| 391 | | l->arr[n].nactvar = ls->fs->nactvar; |
| 392 | | l->arr[n].pc = pc; |
| 393 | | l->n++; |
| 394 | | return n; |
| 385 | int line, int pc) { |
| 386 | int n = l->n; |
| 387 | luaM_growvector(ls->L, l->arr, n, l->size, |
| 388 | Labeldesc, SHRT_MAX, "labels/gotos"); |
| 389 | l->arr[n].name = name; |
| 390 | l->arr[n].line = line; |
| 391 | l->arr[n].nactvar = ls->fs->nactvar; |
| 392 | l->arr[n].pc = pc; |
| 393 | l->n++; |
| 394 | return n; |
| 395 | 395 | } |
| 396 | 396 | |
| 397 | 397 | |
| r30857 | r30858 | |
| 400 | 400 | ** block; solves forward jumps |
| 401 | 401 | */ |
| 402 | 402 | static void findgotos (LexState *ls, Labeldesc *lb) { |
| 403 | | Labellist *gl = &ls->dyd->gt; |
| 404 | | int i = ls->fs->bl->firstgoto; |
| 405 | | while (i < gl->n) { |
| 406 | | if (luaS_eqstr(gl->arr[i].name, lb->name)) |
| 407 | | closegoto(ls, i, lb); |
| 408 | | else |
| 409 | | i++; |
| 410 | | } |
| 403 | Labellist *gl = &ls->dyd->gt; |
| 404 | int i = ls->fs->bl->firstgoto; |
| 405 | while (i < gl->n) { |
| 406 | if (luaS_eqstr(gl->arr[i].name, lb->name)) |
| 407 | closegoto(ls, i, lb); |
| 408 | else |
| 409 | i++; |
| 410 | } |
| 411 | 411 | } |
| 412 | 412 | |
| 413 | 413 | |
| r30857 | r30858 | |
| 418 | 418 | ** upvalue), close those variables being exited. |
| 419 | 419 | */ |
| 420 | 420 | static void movegotosout (FuncState *fs, BlockCnt *bl) { |
| 421 | | int i = bl->firstgoto; |
| 422 | | Labellist *gl = &fs->ls->dyd->gt; |
| 423 | | /* correct pending gotos to current block and try to close it |
| 424 | | with visible labels */ |
| 425 | | while (i < gl->n) { |
| 426 | | Labeldesc *gt = &gl->arr[i]; |
| 427 | | if (gt->nactvar > bl->nactvar) { |
| 428 | | if (bl->upval) |
| 429 | | luaK_patchclose(fs, gt->pc, bl->nactvar); |
| 430 | | gt->nactvar = bl->nactvar; |
| 431 | | } |
| 432 | | if (!findlabel(fs->ls, i)) |
| 433 | | i++; /* move to next one */ |
| 434 | | } |
| 421 | int i = bl->firstgoto; |
| 422 | Labellist *gl = &fs->ls->dyd->gt; |
| 423 | /* correct pending gotos to current block and try to close it |
| 424 | with visible labels */ |
| 425 | while (i < gl->n) { |
| 426 | Labeldesc *gt = &gl->arr[i]; |
| 427 | if (gt->nactvar > bl->nactvar) { |
| 428 | if (bl->upval) |
| 429 | luaK_patchclose(fs, gt->pc, bl->nactvar); |
| 430 | gt->nactvar = bl->nactvar; |
| 431 | } |
| 432 | if (!findlabel(fs->ls, i)) |
| 433 | i++; /* move to next one */ |
| 434 | } |
| 435 | 435 | } |
| 436 | 436 | |
| 437 | 437 | |
| 438 | 438 | static void enterblock (FuncState *fs, BlockCnt *bl, lu_byte isloop) { |
| 439 | | bl->isloop = isloop; |
| 440 | | bl->nactvar = fs->nactvar; |
| 441 | | bl->firstlabel = fs->ls->dyd->label.n; |
| 442 | | bl->firstgoto = fs->ls->dyd->gt.n; |
| 443 | | bl->upval = 0; |
| 444 | | bl->previous = fs->bl; |
| 445 | | fs->bl = bl; |
| 446 | | lua_assert(fs->freereg == fs->nactvar); |
| 439 | bl->isloop = isloop; |
| 440 | bl->nactvar = fs->nactvar; |
| 441 | bl->firstlabel = fs->ls->dyd->label.n; |
| 442 | bl->firstgoto = fs->ls->dyd->gt.n; |
| 443 | bl->upval = 0; |
| 444 | bl->previous = fs->bl; |
| 445 | fs->bl = bl; |
| 446 | lua_assert(fs->freereg == fs->nactvar); |
| 447 | 447 | } |
| 448 | 448 | |
| 449 | 449 | |
| r30857 | r30858 | |
| 451 | 451 | ** create a label named "break" to resolve break statements |
| 452 | 452 | */ |
| 453 | 453 | static void breaklabel (LexState *ls) { |
| 454 | | TString *n = luaS_new(ls->L, "break"); |
| 455 | | int l = newlabelentry(ls, &ls->dyd->label, n, 0, ls->fs->pc); |
| 456 | | findgotos(ls, &ls->dyd->label.arr[l]); |
| 454 | TString *n = luaS_new(ls->L, "break"); |
| 455 | int l = newlabelentry(ls, &ls->dyd->label, n, 0, ls->fs->pc); |
| 456 | findgotos(ls, &ls->dyd->label.arr[l]); |
| 457 | 457 | } |
| 458 | 458 | |
| 459 | 459 | /* |
| r30857 | r30858 | |
| 461 | 461 | ** message when label name is a reserved word (which can only be 'break') |
| 462 | 462 | */ |
| 463 | 463 | static l_noret undefgoto (LexState *ls, Labeldesc *gt) { |
| 464 | | const char *msg = isreserved(gt->name) |
| 465 | | ? "<%s> at line %d not inside a loop" |
| 466 | | : "no visible label " LUA_QS " for <goto> at line %d"; |
| 467 | | msg = luaO_pushfstring(ls->L, msg, getstr(gt->name), gt->line); |
| 468 | | semerror(ls, msg); |
| 464 | const char *msg = isreserved(gt->name) |
| 465 | ? "<%s> at line %d not inside a loop" |
| 466 | : "no visible label " LUA_QS " for <goto> at line %d"; |
| 467 | msg = luaO_pushfstring(ls->L, msg, getstr(gt->name), gt->line); |
| 468 | semerror(ls, msg); |
| 469 | 469 | } |
| 470 | 470 | |
| 471 | 471 | |
| 472 | 472 | static void leaveblock (FuncState *fs) { |
| 473 | | BlockCnt *bl = fs->bl; |
| 474 | | LexState *ls = fs->ls; |
| 475 | | if (bl->previous && bl->upval) { |
| 476 | | /* create a 'jump to here' to close upvalues */ |
| 477 | | int j = luaK_jump(fs); |
| 478 | | luaK_patchclose(fs, j, bl->nactvar); |
| 479 | | luaK_patchtohere(fs, j); |
| 480 | | } |
| 481 | | if (bl->isloop) |
| 482 | | breaklabel(ls); /* close pending breaks */ |
| 483 | | fs->bl = bl->previous; |
| 484 | | removevars(fs, bl->nactvar); |
| 485 | | lua_assert(bl->nactvar == fs->nactvar); |
| 486 | | fs->freereg = fs->nactvar; /* free registers */ |
| 487 | | ls->dyd->label.n = bl->firstlabel; /* remove local labels */ |
| 488 | | if (bl->previous) /* inner block? */ |
| 489 | | movegotosout(fs, bl); /* update pending gotos to outer block */ |
| 490 | | else if (bl->firstgoto < ls->dyd->gt.n) /* pending gotos in outer block? */ |
| 491 | | undefgoto(ls, &ls->dyd->gt.arr[bl->firstgoto]); /* error */ |
| 473 | BlockCnt *bl = fs->bl; |
| 474 | LexState *ls = fs->ls; |
| 475 | if (bl->previous && bl->upval) { |
| 476 | /* create a 'jump to here' to close upvalues */ |
| 477 | int j = luaK_jump(fs); |
| 478 | luaK_patchclose(fs, j, bl->nactvar); |
| 479 | luaK_patchtohere(fs, j); |
| 480 | } |
| 481 | if (bl->isloop) |
| 482 | breaklabel(ls); /* close pending breaks */ |
| 483 | fs->bl = bl->previous; |
| 484 | removevars(fs, bl->nactvar); |
| 485 | lua_assert(bl->nactvar == fs->nactvar); |
| 486 | fs->freereg = fs->nactvar; /* free registers */ |
| 487 | ls->dyd->label.n = bl->firstlabel; /* remove local labels */ |
| 488 | if (bl->previous) /* inner block? */ |
| 489 | movegotosout(fs, bl); /* update pending gotos to outer block */ |
| 490 | else if (bl->firstgoto < ls->dyd->gt.n) /* pending gotos in outer block? */ |
| 491 | undefgoto(ls, &ls->dyd->gt.arr[bl->firstgoto]); /* error */ |
| 492 | 492 | } |
| 493 | 493 | |
| 494 | 494 | |
| r30857 | r30858 | |
| 496 | 496 | ** adds a new prototype into list of prototypes |
| 497 | 497 | */ |
| 498 | 498 | static Proto *addprototype (LexState *ls) { |
| 499 | | Proto *clp; |
| 500 | | lua_State *L = ls->L; |
| 501 | | FuncState *fs = ls->fs; |
| 502 | | Proto *f = fs->f; /* prototype of current function */ |
| 503 | | if (fs->np >= f->sizep) { |
| 504 | | int oldsize = f->sizep; |
| 505 | | luaM_growvector(L, f->p, fs->np, f->sizep, Proto *, MAXARG_Bx, "functions"); |
| 506 | | while (oldsize < f->sizep) f->p[oldsize++] = NULL; |
| 507 | | } |
| 508 | | f->p[fs->np++] = clp = luaF_newproto(L); |
| 509 | | luaC_objbarrier(L, f, clp); |
| 510 | | return clp; |
| 499 | Proto *clp; |
| 500 | lua_State *L = ls->L; |
| 501 | FuncState *fs = ls->fs; |
| 502 | Proto *f = fs->f; /* prototype of current function */ |
| 503 | if (fs->np >= f->sizep) { |
| 504 | int oldsize = f->sizep; |
| 505 | luaM_growvector(L, f->p, fs->np, f->sizep, Proto *, MAXARG_Bx, "functions"); |
| 506 | while (oldsize < f->sizep) f->p[oldsize++] = NULL; |
| 507 | } |
| 508 | f->p[fs->np++] = clp = luaF_newproto(L); |
| 509 | luaC_objbarrier(L, f, clp); |
| 510 | return clp; |
| 511 | 511 | } |
| 512 | 512 | |
| 513 | 513 | |
| r30857 | r30858 | |
| 518 | 518 | ** are in use at that time. |
| 519 | 519 | */ |
| 520 | 520 | static void codeclosure (LexState *ls, expdesc *v) { |
| 521 | | FuncState *fs = ls->fs->prev; |
| 522 | | init_exp(v, VRELOCABLE, luaK_codeABx(fs, OP_CLOSURE, 0, fs->np - 1)); |
| 523 | | luaK_exp2nextreg(fs, v); /* fix it at the last register */ |
| 521 | FuncState *fs = ls->fs->prev; |
| 522 | init_exp(v, VRELOCABLE, luaK_codeABx(fs, OP_CLOSURE, 0, fs->np - 1)); |
| 523 | luaK_exp2nextreg(fs, v); /* fix it at the last register */ |
| 524 | 524 | } |
| 525 | 525 | |
| 526 | 526 | |
| 527 | 527 | static void open_func (LexState *ls, FuncState *fs, BlockCnt *bl) { |
| 528 | | lua_State *L = ls->L; |
| 529 | | Proto *f; |
| 530 | | fs->prev = ls->fs; /* linked list of funcstates */ |
| 531 | | fs->ls = ls; |
| 532 | | ls->fs = fs; |
| 533 | | fs->pc = 0; |
| 534 | | fs->lasttarget = 0; |
| 535 | | fs->jpc = NO_JUMP; |
| 536 | | fs->freereg = 0; |
| 537 | | fs->nk = 0; |
| 538 | | fs->np = 0; |
| 539 | | fs->nups = 0; |
| 540 | | fs->nlocvars = 0; |
| 541 | | fs->nactvar = 0; |
| 542 | | fs->firstlocal = ls->dyd->actvar.n; |
| 543 | | fs->bl = NULL; |
| 544 | | f = fs->f; |
| 545 | | f->source = ls->source; |
| 546 | | f->maxstacksize = 2; /* registers 0/1 are always valid */ |
| 547 | | fs->h = luaH_new(L); |
| 548 | | /* anchor table of constants (to avoid being collected) */ |
| 549 | | sethvalue2s(L, L->top, fs->h); |
| 550 | | incr_top(L); |
| 551 | | enterblock(fs, bl, 0); |
| 528 | lua_State *L = ls->L; |
| 529 | Proto *f; |
| 530 | fs->prev = ls->fs; /* linked list of funcstates */ |
| 531 | fs->ls = ls; |
| 532 | ls->fs = fs; |
| 533 | fs->pc = 0; |
| 534 | fs->lasttarget = 0; |
| 535 | fs->jpc = NO_JUMP; |
| 536 | fs->freereg = 0; |
| 537 | fs->nk = 0; |
| 538 | fs->np = 0; |
| 539 | fs->nups = 0; |
| 540 | fs->nlocvars = 0; |
| 541 | fs->nactvar = 0; |
| 542 | fs->firstlocal = ls->dyd->actvar.n; |
| 543 | fs->bl = NULL; |
| 544 | f = fs->f; |
| 545 | f->source = ls->source; |
| 546 | f->maxstacksize = 2; /* registers 0/1 are always valid */ |
| 547 | fs->h = luaH_new(L); |
| 548 | /* anchor table of constants (to avoid being collected) */ |
| 549 | sethvalue2s(L, L->top, fs->h); |
| 550 | incr_top(L); |
| 551 | enterblock(fs, bl, 0); |
| 552 | 552 | } |
| 553 | 553 | |
| 554 | 554 | |
| 555 | 555 | static void close_func (LexState *ls) { |
| 556 | | lua_State *L = ls->L; |
| 557 | | FuncState *fs = ls->fs; |
| 558 | | Proto *f = fs->f; |
| 559 | | luaK_ret(fs, 0, 0); /* final return */ |
| 560 | | leaveblock(fs); |
| 561 | | luaM_reallocvector(L, f->code, f->sizecode, fs->pc, Instruction); |
| 562 | | f->sizecode = fs->pc; |
| 563 | | luaM_reallocvector(L, f->lineinfo, f->sizelineinfo, fs->pc, int); |
| 564 | | f->sizelineinfo = fs->pc; |
| 565 | | luaM_reallocvector(L, f->k, f->sizek, fs->nk, TValue); |
| 566 | | f->sizek = fs->nk; |
| 567 | | luaM_reallocvector(L, f->p, f->sizep, fs->np, Proto *); |
| 568 | | f->sizep = fs->np; |
| 569 | | luaM_reallocvector(L, f->locvars, f->sizelocvars, fs->nlocvars, LocVar); |
| 570 | | f->sizelocvars = fs->nlocvars; |
| 571 | | luaM_reallocvector(L, f->upvalues, f->sizeupvalues, fs->nups, Upvaldesc); |
| 572 | | f->sizeupvalues = fs->nups; |
| 573 | | lua_assert(fs->bl == NULL); |
| 574 | | ls->fs = fs->prev; |
| 575 | | /* last token read was anchored in defunct function; must re-anchor it */ |
| 576 | | anchor_token(ls); |
| 577 | | L->top--; /* pop table of constants */ |
| 578 | | luaC_checkGC(L); |
| 556 | lua_State *L = ls->L; |
| 557 | FuncState *fs = ls->fs; |
| 558 | Proto *f = fs->f; |
| 559 | luaK_ret(fs, 0, 0); /* final return */ |
| 560 | leaveblock(fs); |
| 561 | luaM_reallocvector(L, f->code, f->sizecode, fs->pc, Instruction); |
| 562 | f->sizecode = fs->pc; |
| 563 | luaM_reallocvector(L, f->lineinfo, f->sizelineinfo, fs->pc, int); |
| 564 | f->sizelineinfo = fs->pc; |
| 565 | luaM_reallocvector(L, f->k, f->sizek, fs->nk, TValue); |
| 566 | f->sizek = fs->nk; |
| 567 | luaM_reallocvector(L, f->p, f->sizep, fs->np, Proto *); |
| 568 | f->sizep = fs->np; |
| 569 | luaM_reallocvector(L, f->locvars, f->sizelocvars, fs->nlocvars, LocVar); |
| 570 | f->sizelocvars = fs->nlocvars; |
| 571 | luaM_reallocvector(L, f->upvalues, f->sizeupvalues, fs->nups, Upvaldesc); |
| 572 | f->sizeupvalues = fs->nups; |
| 573 | lua_assert(fs->bl == NULL); |
| 574 | ls->fs = fs->prev; |
| 575 | /* last token read was anchored in defunct function; must re-anchor it */ |
| 576 | anchor_token(ls); |
| 577 | L->top--; /* pop table of constants */ |
| 578 | luaC_checkGC(L); |
| 579 | 579 | } |
| 580 | 580 | |
| 581 | 581 | |
| r30857 | r30858 | |
| 591 | 591 | ** so it handled in separate. |
| 592 | 592 | */ |
| 593 | 593 | static int block_follow (LexState *ls, int withuntil) { |
| 594 | | switch (ls->t.token) { |
| 595 | | case TK_ELSE: case TK_ELSEIF: |
| 596 | | case TK_END: case TK_EOS: |
| 597 | | return 1; |
| 598 | | case TK_UNTIL: return withuntil; |
| 599 | | default: return 0; |
| 600 | | } |
| 594 | switch (ls->t.token) { |
| 595 | case TK_ELSE: case TK_ELSEIF: |
| 596 | case TK_END: case TK_EOS: |
| 597 | return 1; |
| 598 | case TK_UNTIL: return withuntil; |
| 599 | default: return 0; |
| 600 | } |
| 601 | 601 | } |
| 602 | 602 | |
| 603 | 603 | |
| 604 | 604 | static void statlist (LexState *ls) { |
| 605 | | /* statlist -> { stat [`;'] } */ |
| 606 | | while (!block_follow(ls, 1)) { |
| 607 | | if (ls->t.token == TK_RETURN) { |
| 608 | | statement(ls); |
| 609 | | return; /* 'return' must be last statement */ |
| 610 | | } |
| 611 | | statement(ls); |
| 612 | | } |
| 605 | /* statlist -> { stat [`;'] } */ |
| 606 | while (!block_follow(ls, 1)) { |
| 607 | if (ls->t.token == TK_RETURN) { |
| 608 | statement(ls); |
| 609 | return; /* 'return' must be last statement */ |
| 610 | } |
| 611 | statement(ls); |
| 612 | } |
| 613 | 613 | } |
| 614 | 614 | |
| 615 | 615 | |
| 616 | 616 | static void fieldsel (LexState *ls, expdesc *v) { |
| 617 | | /* fieldsel -> ['.' | ':'] NAME */ |
| 618 | | FuncState *fs = ls->fs; |
| 619 | | expdesc key; |
| 620 | | luaK_exp2anyregup(fs, v); |
| 621 | | luaX_next(ls); /* skip the dot or colon */ |
| 622 | | checkname(ls, &key); |
| 623 | | luaK_indexed(fs, v, &key); |
| 617 | /* fieldsel -> ['.' | ':'] NAME */ |
| 618 | FuncState *fs = ls->fs; |
| 619 | expdesc key; |
| 620 | luaK_exp2anyregup(fs, v); |
| 621 | luaX_next(ls); /* skip the dot or colon */ |
| 622 | checkname(ls, &key); |
| 623 | luaK_indexed(fs, v, &key); |
| 624 | 624 | } |
| 625 | 625 | |
| 626 | 626 | |
| 627 | 627 | static void yindex (LexState *ls, expdesc *v) { |
| 628 | | /* index -> '[' expr ']' */ |
| 629 | | luaX_next(ls); /* skip the '[' */ |
| 630 | | expr(ls, v); |
| 631 | | luaK_exp2val(ls->fs, v); |
| 632 | | checknext(ls, ']'); |
| 628 | /* index -> '[' expr ']' */ |
| 629 | luaX_next(ls); /* skip the '[' */ |
| 630 | expr(ls, v); |
| 631 | luaK_exp2val(ls->fs, v); |
| 632 | checknext(ls, ']'); |
| 633 | 633 | } |
| 634 | 634 | |
| 635 | 635 | |
| r30857 | r30858 | |
| 641 | 641 | |
| 642 | 642 | |
| 643 | 643 | struct ConsControl { |
| 644 | | expdesc v; /* last list item read */ |
| 645 | | expdesc *t; /* table descriptor */ |
| 646 | | int nh; /* total number of `record' elements */ |
| 647 | | int na; /* total number of array elements */ |
| 648 | | int tostore; /* number of array elements pending to be stored */ |
| 644 | expdesc v; /* last list item read */ |
| 645 | expdesc *t; /* table descriptor */ |
| 646 | int nh; /* total number of `record' elements */ |
| 647 | int na; /* total number of array elements */ |
| 648 | int tostore; /* number of array elements pending to be stored */ |
| 649 | 649 | }; |
| 650 | 650 | |
| 651 | 651 | |
| 652 | 652 | static void recfield (LexState *ls, struct ConsControl *cc) { |
| 653 | | /* recfield -> (NAME | `['exp1`]') = exp1 */ |
| 654 | | FuncState *fs = ls->fs; |
| 655 | | int reg = ls->fs->freereg; |
| 656 | | expdesc key, val; |
| 657 | | int rkkey; |
| 658 | | if (ls->t.token == TK_NAME) { |
| 659 | | checklimit(fs, cc->nh, MAX_INT, "items in a constructor"); |
| 660 | | checkname(ls, &key); |
| 661 | | } |
| 662 | | else /* ls->t.token == '[' */ |
| 663 | | yindex(ls, &key); |
| 664 | | cc->nh++; |
| 665 | | checknext(ls, '='); |
| 666 | | rkkey = luaK_exp2RK(fs, &key); |
| 667 | | expr(ls, &val); |
| 668 | | luaK_codeABC(fs, OP_SETTABLE, cc->t->u.info, rkkey, luaK_exp2RK(fs, &val)); |
| 669 | | fs->freereg = reg; /* free registers */ |
| 653 | /* recfield -> (NAME | `['exp1`]') = exp1 */ |
| 654 | FuncState *fs = ls->fs; |
| 655 | int reg = ls->fs->freereg; |
| 656 | expdesc key, val; |
| 657 | int rkkey; |
| 658 | if (ls->t.token == TK_NAME) { |
| 659 | checklimit(fs, cc->nh, MAX_INT, "items in a constructor"); |
| 660 | checkname(ls, &key); |
| 661 | } |
| 662 | else /* ls->t.token == '[' */ |
| 663 | yindex(ls, &key); |
| 664 | cc->nh++; |
| 665 | checknext(ls, '='); |
| 666 | rkkey = luaK_exp2RK(fs, &key); |
| 667 | expr(ls, &val); |
| 668 | luaK_codeABC(fs, OP_SETTABLE, cc->t->u.info, rkkey, luaK_exp2RK(fs, &val)); |
| 669 | fs->freereg = reg; /* free registers */ |
| 670 | 670 | } |
| 671 | 671 | |
| 672 | 672 | |
| 673 | 673 | static void closelistfield (FuncState *fs, struct ConsControl *cc) { |
| 674 | | if (cc->v.k == VVOID) return; /* there is no list item */ |
| 675 | | luaK_exp2nextreg(fs, &cc->v); |
| 676 | | cc->v.k = VVOID; |
| 677 | | if (cc->tostore == LFIELDS_PER_FLUSH) { |
| 678 | | luaK_setlist(fs, cc->t->u.info, cc->na, cc->tostore); /* flush */ |
| 679 | | cc->tostore = 0; /* no more items pending */ |
| 680 | | } |
| 674 | if (cc->v.k == VVOID) return; /* there is no list item */ |
| 675 | luaK_exp2nextreg(fs, &cc->v); |
| 676 | cc->v.k = VVOID; |
| 677 | if (cc->tostore == LFIELDS_PER_FLUSH) { |
| 678 | luaK_setlist(fs, cc->t->u.info, cc->na, cc->tostore); /* flush */ |
| 679 | cc->tostore = 0; /* no more items pending */ |
| 680 | } |
| 681 | 681 | } |
| 682 | 682 | |
| 683 | 683 | |
| 684 | 684 | static void lastlistfield (FuncState *fs, struct ConsControl *cc) { |
| 685 | | if (cc->tostore == 0) return; |
| 686 | | if (hasmultret(cc->v.k)) { |
| 687 | | luaK_setmultret(fs, &cc->v); |
| 688 | | luaK_setlist(fs, cc->t->u.info, cc->na, LUA_MULTRET); |
| 689 | | cc->na--; /* do not count last expression (unknown number of elements) */ |
| 690 | | } |
| 691 | | else { |
| 692 | | if (cc->v.k != VVOID) |
| 693 | | luaK_exp2nextreg(fs, &cc->v); |
| 694 | | luaK_setlist(fs, cc->t->u.info, cc->na, cc->tostore); |
| 695 | | } |
| 685 | if (cc->tostore == 0) return; |
| 686 | if (hasmultret(cc->v.k)) { |
| 687 | luaK_setmultret(fs, &cc->v); |
| 688 | luaK_setlist(fs, cc->t->u.info, cc->na, LUA_MULTRET); |
| 689 | cc->na--; /* do not count last expression (unknown number of elements) */ |
| 690 | } |
| 691 | else { |
| 692 | if (cc->v.k != VVOID) |
| 693 | luaK_exp2nextreg(fs, &cc->v); |
| 694 | luaK_setlist(fs, cc->t->u.info, cc->na, cc->tostore); |
| 695 | } |
| 696 | 696 | } |
| 697 | 697 | |
| 698 | 698 | |
| 699 | 699 | static void listfield (LexState *ls, struct ConsControl *cc) { |
| 700 | | /* listfield -> exp */ |
| 701 | | expr(ls, &cc->v); |
| 702 | | checklimit(ls->fs, cc->na, MAX_INT, "items in a constructor"); |
| 703 | | cc->na++; |
| 704 | | cc->tostore++; |
| 700 | /* listfield -> exp */ |
| 701 | expr(ls, &cc->v); |
| 702 | checklimit(ls->fs, cc->na, MAX_INT, "items in a constructor"); |
| 703 | cc->na++; |
| 704 | cc->tostore++; |
| 705 | 705 | } |
| 706 | 706 | |
| 707 | 707 | |
| 708 | 708 | static void field (LexState *ls, struct ConsControl *cc) { |
| 709 | | /* field -> listfield | recfield */ |
| 710 | | switch(ls->t.token) { |
| 711 | | case TK_NAME: { /* may be 'listfield' or 'recfield' */ |
| 712 | | if (luaX_lookahead(ls) != '=') /* expression? */ |
| 713 | | listfield(ls, cc); |
| 714 | | else |
| 715 | | recfield(ls, cc); |
| 716 | | break; |
| 717 | | } |
| 718 | | case '[': { |
| 719 | | recfield(ls, cc); |
| 720 | | break; |
| 721 | | } |
| 722 | | default: { |
| 723 | | listfield(ls, cc); |
| 724 | | break; |
| 725 | | } |
| 726 | | } |
| 709 | /* field -> listfield | recfield */ |
| 710 | switch(ls->t.token) { |
| 711 | case TK_NAME: { /* may be 'listfield' or 'recfield' */ |
| 712 | if (luaX_lookahead(ls) != '=') /* expression? */ |
| 713 | listfield(ls, cc); |
| 714 | else |
| 715 | recfield(ls, cc); |
| 716 | break; |
| 717 | } |
| 718 | case '[': { |
| 719 | recfield(ls, cc); |
| 720 | break; |
| 721 | } |
| 722 | default: { |
| 723 | listfield(ls, cc); |
| 724 | break; |
| 725 | } |
| 726 | } |
| 727 | 727 | } |
| 728 | 728 | |
| 729 | 729 | |
| 730 | 730 | static void constructor (LexState *ls, expdesc *t) { |
| 731 | | /* constructor -> '{' [ field { sep field } [sep] ] '}' |
| 732 | | sep -> ',' | ';' */ |
| 733 | | FuncState *fs = ls->fs; |
| 734 | | int line = ls->linenumber; |
| 735 | | int pc = luaK_codeABC(fs, OP_NEWTABLE, 0, 0, 0); |
| 736 | | struct ConsControl cc; |
| 737 | | cc.na = cc.nh = cc.tostore = 0; |
| 738 | | cc.t = t; |
| 739 | | init_exp(t, VRELOCABLE, pc); |
| 740 | | init_exp(&cc.v, VVOID, 0); /* no value (yet) */ |
| 741 | | luaK_exp2nextreg(ls->fs, t); /* fix it at stack top */ |
| 742 | | checknext(ls, '{'); |
| 743 | | do { |
| 744 | | lua_assert(cc.v.k == VVOID || cc.tostore > 0); |
| 745 | | if (ls->t.token == '}') break; |
| 746 | | closelistfield(fs, &cc); |
| 747 | | field(ls, &cc); |
| 748 | | } while (testnext(ls, ',') || testnext(ls, ';')); |
| 749 | | check_match(ls, '}', '{', line); |
| 750 | | lastlistfield(fs, &cc); |
| 751 | | SETARG_B(fs->f->code[pc], luaO_int2fb(cc.na)); /* set initial array size */ |
| 752 | | SETARG_C(fs->f->code[pc], luaO_int2fb(cc.nh)); /* set initial table size */ |
| 731 | /* constructor -> '{' [ field { sep field } [sep] ] '}' |
| 732 | sep -> ',' | ';' */ |
| 733 | FuncState *fs = ls->fs; |
| 734 | int line = ls->linenumber; |
| 735 | int pc = luaK_codeABC(fs, OP_NEWTABLE, 0, 0, 0); |
| 736 | struct ConsControl cc; |
| 737 | cc.na = cc.nh = cc.tostore = 0; |
| 738 | cc.t = t; |
| 739 | init_exp(t, VRELOCABLE, pc); |
| 740 | init_exp(&cc.v, VVOID, 0); /* no value (yet) */ |
| 741 | luaK_exp2nextreg(ls->fs, t); /* fix it at stack top */ |
| 742 | checknext(ls, '{'); |
| 743 | do { |
| 744 | lua_assert(cc.v.k == VVOID || cc.tostore > 0); |
| 745 | if (ls->t.token == '}') break; |
| 746 | closelistfield(fs, &cc); |
| 747 | field(ls, &cc); |
| 748 | } while (testnext(ls, ',') || testnext(ls, ';')); |
| 749 | check_match(ls, '}', '{', line); |
| 750 | lastlistfield(fs, &cc); |
| 751 | SETARG_B(fs->f->code[pc], luaO_int2fb(cc.na)); /* set initial array size */ |
| 752 | SETARG_C(fs->f->code[pc], luaO_int2fb(cc.nh)); /* set initial table size */ |
| 753 | 753 | } |
| 754 | 754 | |
| 755 | 755 | /* }====================================================================== */ |
| r30857 | r30858 | |
| 757 | 757 | |
| 758 | 758 | |
| 759 | 759 | static void parlist (LexState *ls) { |
| 760 | | /* parlist -> [ param { `,' param } ] */ |
| 761 | | FuncState *fs = ls->fs; |
| 762 | | Proto *f = fs->f; |
| 763 | | int nparams = 0; |
| 764 | | f->is_vararg = 0; |
| 765 | | if (ls->t.token != ')') { /* is `parlist' not empty? */ |
| 766 | | do { |
| 767 | | switch (ls->t.token) { |
| 768 | | case TK_NAME: { /* param -> NAME */ |
| 769 | | new_localvar(ls, str_checkname(ls)); |
| 770 | | nparams++; |
| 771 | | break; |
| 772 | | } |
| 773 | | case TK_DOTS: { /* param -> `...' */ |
| 774 | | luaX_next(ls); |
| 775 | | f->is_vararg = 1; |
| 776 | | break; |
| 777 | | } |
| 778 | | default: luaX_syntaxerror(ls, "<name> or " LUA_QL("...") " expected"); |
| 779 | | } |
| 780 | | } while (!f->is_vararg && testnext(ls, ',')); |
| 781 | | } |
| 782 | | adjustlocalvars(ls, nparams); |
| 783 | | f->numparams = cast_byte(fs->nactvar); |
| 784 | | luaK_reserveregs(fs, fs->nactvar); /* reserve register for parameters */ |
| 760 | /* parlist -> [ param { `,' param } ] */ |
| 761 | FuncState *fs = ls->fs; |
| 762 | Proto *f = fs->f; |
| 763 | int nparams = 0; |
| 764 | f->is_vararg = 0; |
| 765 | if (ls->t.token != ')') { /* is `parlist' not empty? */ |
| 766 | do { |
| 767 | switch (ls->t.token) { |
| 768 | case TK_NAME: { /* param -> NAME */ |
| 769 | new_localvar(ls, str_checkname(ls)); |
| 770 | nparams++; |
| 771 | break; |
| 772 | } |
| 773 | case TK_DOTS: { /* param -> `...' */ |
| 774 | luaX_next(ls); |
| 775 | f->is_vararg = 1; |
| 776 | break; |
| 777 | } |
| 778 | default: luaX_syntaxerror(ls, "<name> or " LUA_QL("...") " expected"); |
| 779 | } |
| 780 | } while (!f->is_vararg && testnext(ls, ',')); |
| 781 | } |
| 782 | adjustlocalvars(ls, nparams); |
| 783 | f->numparams = cast_byte(fs->nactvar); |
| 784 | luaK_reserveregs(fs, fs->nactvar); /* reserve register for parameters */ |
| 785 | 785 | } |
| 786 | 786 | |
| 787 | 787 | |
| 788 | 788 | static void body (LexState *ls, expdesc *e, int ismethod, int line) { |
| 789 | | /* body -> `(' parlist `)' block END */ |
| 790 | | FuncState new_fs; |
| 791 | | BlockCnt bl; |
| 792 | | new_fs.f = addprototype(ls); |
| 793 | | new_fs.f->linedefined = line; |
| 794 | | open_func(ls, &new_fs, &bl); |
| 795 | | checknext(ls, '('); |
| 796 | | if (ismethod) { |
| 797 | | new_localvarliteral(ls, "self"); /* create 'self' parameter */ |
| 798 | | adjustlocalvars(ls, 1); |
| 799 | | } |
| 800 | | parlist(ls); |
| 801 | | checknext(ls, ')'); |
| 802 | | statlist(ls); |
| 803 | | new_fs.f->lastlinedefined = ls->linenumber; |
| 804 | | check_match(ls, TK_END, TK_FUNCTION, line); |
| 805 | | codeclosure(ls, e); |
| 806 | | close_func(ls); |
| 789 | /* body -> `(' parlist `)' block END */ |
| 790 | FuncState new_fs; |
| 791 | BlockCnt bl; |
| 792 | new_fs.f = addprototype(ls); |
| 793 | new_fs.f->linedefined = line; |
| 794 | open_func(ls, &new_fs, &bl); |
| 795 | checknext(ls, '('); |
| 796 | if (ismethod) { |
| 797 | new_localvarliteral(ls, "self"); /* create 'self' parameter */ |
| 798 | adjustlocalvars(ls, 1); |
| 799 | } |
| 800 | parlist(ls); |
| 801 | checknext(ls, ')'); |
| 802 | statlist(ls); |
| 803 | new_fs.f->lastlinedefined = ls->linenumber; |
| 804 | check_match(ls, TK_END, TK_FUNCTION, line); |
| 805 | codeclosure(ls, e); |
| 806 | close_func(ls); |
| 807 | 807 | } |
| 808 | 808 | |
| 809 | 809 | |
| 810 | 810 | static int explist (LexState *ls, expdesc *v) { |
| 811 | | /* explist -> expr { `,' expr } */ |
| 812 | | int n = 1; /* at least one expression */ |
| 813 | | expr(ls, v); |
| 814 | | while (testnext(ls, ',')) { |
| 815 | | luaK_exp2nextreg(ls->fs, v); |
| 816 | | expr(ls, v); |
| 817 | | n++; |
| 818 | | } |
| 819 | | return n; |
| 811 | /* explist -> expr { `,' expr } */ |
| 812 | int n = 1; /* at least one expression */ |
| 813 | expr(ls, v); |
| 814 | while (testnext(ls, ',')) { |
| 815 | luaK_exp2nextreg(ls->fs, v); |
| 816 | expr(ls, v); |
| 817 | n++; |
| 818 | } |
| 819 | return n; |
| 820 | 820 | } |
| 821 | 821 | |
| 822 | 822 | |
| 823 | 823 | static void funcargs (LexState *ls, expdesc *f, int line) { |
| 824 | | FuncState *fs = ls->fs; |
| 825 | | expdesc args; |
| 826 | | int base, nparams; |
| 827 | | switch (ls->t.token) { |
| 828 | | case '(': { /* funcargs -> `(' [ explist ] `)' */ |
| 829 | | luaX_next(ls); |
| 830 | | if (ls->t.token == ')') /* arg list is empty? */ |
| 831 | | args.k = VVOID; |
| 832 | | else { |
| 833 | | explist(ls, &args); |
| 834 | | luaK_setmultret(fs, &args); |
| 835 | | } |
| 836 | | check_match(ls, ')', '(', line); |
| 837 | | break; |
| 838 | | } |
| 839 | | case '{': { /* funcargs -> constructor */ |
| 840 | | constructor(ls, &args); |
| 841 | | break; |
| 842 | | } |
| 843 | | case TK_STRING: { /* funcargs -> STRING */ |
| 844 | | codestring(ls, &args, ls->t.seminfo.ts); |
| 845 | | luaX_next(ls); /* must use `seminfo' before `next' */ |
| 846 | | break; |
| 847 | | } |
| 848 | | default: { |
| 849 | | luaX_syntaxerror(ls, "function arguments expected"); |
| 850 | | } |
| 851 | | } |
| 852 | | lua_assert(f->k == VNONRELOC); |
| 853 | | base = f->u.info; /* base register for call */ |
| 854 | | if (hasmultret(args.k)) |
| 855 | | nparams = LUA_MULTRET; /* open call */ |
| 856 | | else { |
| 857 | | if (args.k != VVOID) |
| 858 | | luaK_exp2nextreg(fs, &args); /* close last argument */ |
| 859 | | nparams = fs->freereg - (base+1); |
| 860 | | } |
| 861 | | init_exp(f, VCALL, luaK_codeABC(fs, OP_CALL, base, nparams+1, 2)); |
| 862 | | luaK_fixline(fs, line); |
| 863 | | fs->freereg = base+1; /* call remove function and arguments and leaves |
| 824 | FuncState *fs = ls->fs; |
| 825 | expdesc args; |
| 826 | int base, nparams; |
| 827 | switch (ls->t.token) { |
| 828 | case '(': { /* funcargs -> `(' [ explist ] `)' */ |
| 829 | luaX_next(ls); |
| 830 | if (ls->t.token == ')') /* arg list is empty? */ |
| 831 | args.k = VVOID; |
| 832 | else { |
| 833 | explist(ls, &args); |
| 834 | luaK_setmultret(fs, &args); |
| 835 | } |
| 836 | check_match(ls, ')', '(', line); |
| 837 | break; |
| 838 | } |
| 839 | case '{': { /* funcargs -> constructor */ |
| 840 | constructor(ls, &args); |
| 841 | break; |
| 842 | } |
| 843 | case TK_STRING: { /* funcargs -> STRING */ |
| 844 | codestring(ls, &args, ls->t.seminfo.ts); |
| 845 | luaX_next(ls); /* must use `seminfo' before `next' */ |
| 846 | break; |
| 847 | } |
| 848 | default: { |
| 849 | luaX_syntaxerror(ls, "function arguments expected"); |
| 850 | } |
| 851 | } |
| 852 | lua_assert(f->k == VNONRELOC); |
| 853 | base = f->u.info; /* base register for call */ |
| 854 | if (hasmultret(args.k)) |
| 855 | nparams = LUA_MULTRET; /* open call */ |
| 856 | else { |
| 857 | if (args.k != VVOID) |
| 858 | luaK_exp2nextreg(fs, &args); /* close last argument */ |
| 859 | nparams = fs->freereg - (base+1); |
| 860 | } |
| 861 | init_exp(f, VCALL, luaK_codeABC(fs, OP_CALL, base, nparams+1, 2)); |
| 862 | luaK_fixline(fs, line); |
| 863 | fs->freereg = base+1; /* call remove function and arguments and leaves |
| 864 | 864 | (unless changed) one result */ |
| 865 | 865 | } |
| 866 | 866 | |
| r30857 | r30858 | |
| 875 | 875 | |
| 876 | 876 | |
| 877 | 877 | static void primaryexp (LexState *ls, expdesc *v) { |
| 878 | | /* primaryexp -> NAME | '(' expr ')' */ |
| 879 | | switch (ls->t.token) { |
| 880 | | case '(': { |
| 881 | | int line = ls->linenumber; |
| 882 | | luaX_next(ls); |
| 883 | | expr(ls, v); |
| 884 | | check_match(ls, ')', '(', line); |
| 885 | | luaK_dischargevars(ls->fs, v); |
| 886 | | return; |
| 887 | | } |
| 888 | | case TK_NAME: { |
| 889 | | singlevar(ls, v); |
| 890 | | return; |
| 891 | | } |
| 892 | | default: { |
| 893 | | luaX_syntaxerror(ls, "unexpected symbol"); |
| 894 | | } |
| 895 | | } |
| 878 | /* primaryexp -> NAME | '(' expr ')' */ |
| 879 | switch (ls->t.token) { |
| 880 | case '(': { |
| 881 | int line = ls->linenumber; |
| 882 | luaX_next(ls); |
| 883 | expr(ls, v); |
| 884 | check_match(ls, ')', '(', line); |
| 885 | luaK_dischargevars(ls->fs, v); |
| 886 | return; |
| 887 | } |
| 888 | case TK_NAME: { |
| 889 | singlevar(ls, v); |
| 890 | return; |
| 891 | } |
| 892 | default: { |
| 893 | luaX_syntaxerror(ls, "unexpected symbol"); |
| 894 | } |
| 895 | } |
| 896 | 896 | } |
| 897 | 897 | |
| 898 | 898 | |
| 899 | 899 | static void suffixedexp (LexState *ls, expdesc *v) { |
| 900 | | /* suffixedexp -> |
| 901 | | primaryexp { '.' NAME | '[' exp ']' | ':' NAME funcargs | funcargs } */ |
| 902 | | FuncState *fs = ls->fs; |
| 903 | | int line = ls->linenumber; |
| 904 | | primaryexp(ls, v); |
| 905 | | for (;;) { |
| 906 | | switch (ls->t.token) { |
| 907 | | case '.': { /* fieldsel */ |
| 908 | | fieldsel(ls, v); |
| 909 | | break; |
| 910 | | } |
| 911 | | case '[': { /* `[' exp1 `]' */ |
| 912 | | expdesc key; |
| 913 | | luaK_exp2anyregup(fs, v); |
| 914 | | yindex(ls, &key); |
| 915 | | luaK_indexed(fs, v, &key); |
| 916 | | break; |
| 917 | | } |
| 918 | | case ':': { /* `:' NAME funcargs */ |
| 919 | | expdesc key; |
| 920 | | luaX_next(ls); |
| 921 | | checkname(ls, &key); |
| 922 | | luaK_self(fs, v, &key); |
| 923 | | funcargs(ls, v, line); |
| 924 | | break; |
| 925 | | } |
| 926 | | case '(': case TK_STRING: case '{': { /* funcargs */ |
| 927 | | luaK_exp2nextreg(fs, v); |
| 928 | | funcargs(ls, v, line); |
| 929 | | break; |
| 930 | | } |
| 931 | | default: return; |
| 932 | | } |
| 933 | | } |
| 900 | /* suffixedexp -> |
| 901 | primaryexp { '.' NAME | '[' exp ']' | ':' NAME funcargs | funcargs } */ |
| 902 | FuncState *fs = ls->fs; |
| 903 | int line = ls->linenumber; |
| 904 | primaryexp(ls, v); |
| 905 | for (;;) { |
| 906 | switch (ls->t.token) { |
| 907 | case '.': { /* fieldsel */ |
| 908 | fieldsel(ls, v); |
| 909 | break; |
| 910 | } |
| 911 | case '[': { /* `[' exp1 `]' */ |
| 912 | expdesc key; |
| 913 | luaK_exp2anyregup(fs, v); |
| 914 | yindex(ls, &key); |
| 915 | luaK_indexed(fs, v, &key); |
| 916 | break; |
| 917 | } |
| 918 | case ':': { /* `:' NAME funcargs */ |
| 919 | expdesc key; |
| 920 | luaX_next(ls); |
| 921 | checkname(ls, &key); |
| 922 | luaK_self(fs, v, &key); |
| 923 | funcargs(ls, v, line); |
| 924 | break; |
| 925 | } |
| 926 | case '(': case TK_STRING: case '{': { /* funcargs */ |
| 927 | luaK_exp2nextreg(fs, v); |
| 928 | funcargs(ls, v, line); |
| 929 | break; |
| 930 | } |
| 931 | default: return; |
| 932 | } |
| 933 | } |
| 934 | 934 | } |
| 935 | 935 | |
| 936 | 936 | |
| 937 | 937 | static void simpleexp (LexState *ls, expdesc *v) { |
| 938 | | /* simpleexp -> NUMBER | STRING | NIL | TRUE | FALSE | ... | |
| 939 | | constructor | FUNCTION body | suffixedexp */ |
| 940 | | switch (ls->t.token) { |
| 941 | | case TK_NUMBER: { |
| 942 | | init_exp(v, VKNUM, 0); |
| 943 | | v->u.nval = ls->t.seminfo.r; |
| 944 | | break; |
| 945 | | } |
| 946 | | case TK_STRING: { |
| 947 | | codestring(ls, v, ls->t.seminfo.ts); |
| 948 | | break; |
| 949 | | } |
| 950 | | case TK_NIL: { |
| 951 | | init_exp(v, VNIL, 0); |
| 952 | | break; |
| 953 | | } |
| 954 | | case TK_TRUE: { |
| 955 | | init_exp(v, VTRUE, 0); |
| 956 | | break; |
| 957 | | } |
| 958 | | case TK_FALSE: { |
| 959 | | init_exp(v, VFALSE, 0); |
| 960 | | break; |
| 961 | | } |
| 962 | | case TK_DOTS: { /* vararg */ |
| 963 | | FuncState *fs = ls->fs; |
| 964 | | check_condition(ls, fs->f->is_vararg, |
| 965 | | "cannot use " LUA_QL("...") " outside a vararg function"); |
| 966 | | init_exp(v, VVARARG, luaK_codeABC(fs, OP_VARARG, 0, 1, 0)); |
| 967 | | break; |
| 968 | | } |
| 969 | | case '{': { /* constructor */ |
| 970 | | constructor(ls, v); |
| 971 | | return; |
| 972 | | } |
| 973 | | case TK_FUNCTION: { |
| 974 | | luaX_next(ls); |
| 975 | | body(ls, v, 0, ls->linenumber); |
| 976 | | return; |
| 977 | | } |
| 978 | | default: { |
| 979 | | suffixedexp(ls, v); |
| 980 | | return; |
| 981 | | } |
| 982 | | } |
| 983 | | luaX_next(ls); |
| 938 | /* simpleexp -> NUMBER | STRING | NIL | TRUE | FALSE | ... | |
| 939 | constructor | FUNCTION body | suffixedexp */ |
| 940 | switch (ls->t.token) { |
| 941 | case TK_NUMBER: { |
| 942 | init_exp(v, VKNUM, 0); |
| 943 | v->u.nval = ls->t.seminfo.r; |
| 944 | break; |
| 945 | } |
| 946 | case TK_STRING: { |
| 947 | codestring(ls, v, ls->t.seminfo.ts); |
| 948 | break; |
| 949 | } |
| 950 | case TK_NIL: { |
| 951 | init_exp(v, VNIL, 0); |
| 952 | break; |
| 953 | } |
| 954 | case TK_TRUE: { |
| 955 | init_exp(v, VTRUE, 0); |
| 956 | break; |
| 957 | } |
| 958 | case TK_FALSE: { |
| 959 | init_exp(v, VFALSE, 0); |
| 960 | break; |
| 961 | } |
| 962 | case TK_DOTS: { /* vararg */ |
| 963 | FuncState *fs = ls->fs; |
| 964 | check_condition(ls, fs->f->is_vararg, |
| 965 | "cannot use " LUA_QL("...") " outside a vararg function"); |
| 966 | init_exp(v, VVARARG, luaK_codeABC(fs, OP_VARARG, 0, 1, 0)); |
| 967 | break; |
| 968 | } |
| 969 | case '{': { /* constructor */ |
| 970 | constructor(ls, v); |
| 971 | return; |
| 972 | } |
| 973 | case TK_FUNCTION: { |
| 974 | luaX_next(ls); |
| 975 | body(ls, v, 0, ls->linenumber); |
| 976 | return; |
| 977 | } |
| 978 | default: { |
| 979 | suffixedexp(ls, v); |
| 980 | return; |
| 981 | } |
| 982 | } |
| 983 | luaX_next(ls); |
| 984 | 984 | } |
| 985 | 985 | |
| 986 | 986 | |
| 987 | 987 | static UnOpr getunopr (int op) { |
| 988 | | switch (op) { |
| 989 | | case TK_NOT: return OPR_NOT; |
| 990 | | case '-': return OPR_MINUS; |
| 991 | | case '#': return OPR_LEN; |
| 992 | | default: return OPR_NOUNOPR; |
| 993 | | } |
| 988 | switch (op) { |
| 989 | case TK_NOT: return OPR_NOT; |
| 990 | case '-': return OPR_MINUS; |
| 991 | case '#': return OPR_LEN; |
| 992 | default: return OPR_NOUNOPR; |
| 993 | } |
| 994 | 994 | } |
| 995 | 995 | |
| 996 | 996 | |
| 997 | 997 | static BinOpr getbinopr (int op) { |
| 998 | | switch (op) { |
| 999 | | case '+': return OPR_ADD; |
| 1000 | | case '-': return OPR_SUB; |
| 1001 | | case '*': return OPR_MUL; |
| 1002 | | case '/': return OPR_DIV; |
| 1003 | | case '%': return OPR_MOD; |
| 1004 | | case '^': return OPR_POW; |
| 1005 | | case TK_CONCAT: return OPR_CONCAT; |
| 1006 | | case TK_NE: return OPR_NE; |
| 1007 | | case TK_EQ: return OPR_EQ; |
| 1008 | | case '<': return OPR_LT; |
| 1009 | | case TK_LE: return OPR_LE; |
| 1010 | | case '>': return OPR_GT; |
| 1011 | | case TK_GE: return OPR_GE; |
| 1012 | | case TK_AND: return OPR_AND; |
| 1013 | | case TK_OR: return OPR_OR; |
| 1014 | | default: return OPR_NOBINOPR; |
| 1015 | | } |
| 998 | switch (op) { |
| 999 | case '+': return OPR_ADD; |
| 1000 | case '-': return OPR_SUB; |
| 1001 | case '*': return OPR_MUL; |
| 1002 | case '/': return OPR_DIV; |
| 1003 | case '%': return OPR_MOD; |
| 1004 | case '^': return OPR_POW; |
| 1005 | case TK_CONCAT: return OPR_CONCAT; |
| 1006 | case TK_NE: return OPR_NE; |
| 1007 | case TK_EQ: return OPR_EQ; |
| 1008 | case '<': return OPR_LT; |
| 1009 | case TK_LE: return OPR_LE; |
| 1010 | case '>': return OPR_GT; |
| 1011 | case TK_GE: return OPR_GE; |
| 1012 | case TK_AND: return OPR_AND; |
| 1013 | case TK_OR: return OPR_OR; |
| 1014 | default: return OPR_NOBINOPR; |
| 1015 | } |
| 1016 | 1016 | } |
| 1017 | 1017 | |
| 1018 | 1018 | |
| 1019 | 1019 | static const struct { |
| 1020 | | lu_byte left; /* left priority for each binary operator */ |
| 1021 | | lu_byte right; /* right priority */ |
| 1020 | lu_byte left; /* left priority for each binary operator */ |
| 1021 | lu_byte right; /* right priority */ |
| 1022 | 1022 | } priority[] = { /* ORDER OPR */ |
| 1023 | | {6, 6}, {6, 6}, {7, 7}, {7, 7}, {7, 7}, /* `+' `-' `*' `/' `%' */ |
| 1024 | | {10, 9}, {5, 4}, /* ^, .. (right associative) */ |
| 1025 | | {3, 3}, {3, 3}, {3, 3}, /* ==, <, <= */ |
| 1026 | | {3, 3}, {3, 3}, {3, 3}, /* ~=, >, >= */ |
| 1027 | | {2, 2}, {1, 1} /* and, or */ |
| 1023 | {6, 6}, {6, 6}, {7, 7}, {7, 7}, {7, 7}, /* `+' `-' `*' `/' `%' */ |
| 1024 | {10, 9}, {5, 4}, /* ^, .. (right associative) */ |
| 1025 | {3, 3}, {3, 3}, {3, 3}, /* ==, <, <= */ |
| 1026 | {3, 3}, {3, 3}, {3, 3}, /* ~=, >, >= */ |
| 1027 | {2, 2}, {1, 1} /* and, or */ |
| 1028 | 1028 | }; |
| 1029 | 1029 | |
| 1030 | | #define UNARY_PRIORITY 8 /* priority for unary operators */ |
| 1030 | #define UNARY_PRIORITY 8 /* priority for unary operators */ |
| 1031 | 1031 | |
| 1032 | 1032 | |
| 1033 | 1033 | /* |
| r30857 | r30858 | |
| 1035 | 1035 | ** where `binop' is any binary operator with a priority higher than `limit' |
| 1036 | 1036 | */ |
| 1037 | 1037 | static BinOpr subexpr (LexState *ls, expdesc *v, int limit) { |
| 1038 | | BinOpr op; |
| 1039 | | UnOpr uop; |
| 1040 | | enterlevel(ls); |
| 1041 | | uop = getunopr(ls->t.token); |
| 1042 | | if (uop != OPR_NOUNOPR) { |
| 1043 | | int line = ls->linenumber; |
| 1044 | | luaX_next(ls); |
| 1045 | | subexpr(ls, v, UNARY_PRIORITY); |
| 1046 | | luaK_prefix(ls->fs, uop, v, line); |
| 1047 | | } |
| 1048 | | else simpleexp(ls, v); |
| 1049 | | /* expand while operators have priorities higher than `limit' */ |
| 1050 | | op = getbinopr(ls->t.token); |
| 1051 | | while (op != OPR_NOBINOPR && priority[op].left > limit) { |
| 1052 | | expdesc v2; |
| 1053 | | BinOpr nextop; |
| 1054 | | int line = ls->linenumber; |
| 1055 | | luaX_next(ls); |
| 1056 | | luaK_infix(ls->fs, op, v); |
| 1057 | | /* read sub-expression with higher priority */ |
| 1058 | | nextop = subexpr(ls, &v2, priority[op].right); |
| 1059 | | luaK_posfix(ls->fs, op, v, &v2, line); |
| 1060 | | op = nextop; |
| 1061 | | } |
| 1062 | | leavelevel(ls); |
| 1063 | | return op; /* return first untreated operator */ |
| 1038 | BinOpr op; |
| 1039 | UnOpr uop; |
| 1040 | enterlevel(ls); |
| 1041 | uop = getunopr(ls->t.token); |
| 1042 | if (uop != OPR_NOUNOPR) { |
| 1043 | int line = ls->linenumber; |
| 1044 | luaX_next(ls); |
| 1045 | subexpr(ls, v, UNARY_PRIORITY); |
| 1046 | luaK_prefix(ls->fs, uop, v, line); |
| 1047 | } |
| 1048 | else simpleexp(ls, v); |
| 1049 | /* expand while operators have priorities higher than `limit' */ |
| 1050 | op = getbinopr(ls->t.token); |
| 1051 | while (op != OPR_NOBINOPR && priority[op].left > limit) { |
| 1052 | expdesc v2; |
| 1053 | BinOpr nextop; |
| 1054 | int line = ls->linenumber; |
| 1055 | luaX_next(ls); |
| 1056 | luaK_infix(ls->fs, op, v); |
| 1057 | /* read sub-expression with higher priority */ |
| 1058 | nextop = subexpr(ls, &v2, priority[op].right); |
| 1059 | luaK_posfix(ls->fs, op, v, &v2, line); |
| 1060 | op = nextop; |
| 1061 | } |
| 1062 | leavelevel(ls); |
| 1063 | return op; /* return first untreated operator */ |
| 1064 | 1064 | } |
| 1065 | 1065 | |
| 1066 | 1066 | |
| 1067 | 1067 | static void expr (LexState *ls, expdesc *v) { |
| 1068 | | subexpr(ls, v, 0); |
| 1068 | subexpr(ls, v, 0); |
| 1069 | 1069 | } |
| 1070 | 1070 | |
| 1071 | 1071 | /* }==================================================================== */ |
| r30857 | r30858 | |
| 1080 | 1080 | |
| 1081 | 1081 | |
| 1082 | 1082 | static void block (LexState *ls) { |
| 1083 | | /* block -> statlist */ |
| 1084 | | FuncState *fs = ls->fs; |
| 1085 | | BlockCnt bl; |
| 1086 | | enterblock(fs, &bl, 0); |
| 1087 | | statlist(ls); |
| 1088 | | leaveblock(fs); |
| 1083 | /* block -> statlist */ |
| 1084 | FuncState *fs = ls->fs; |
| 1085 | BlockCnt bl; |
| 1086 | enterblock(fs, &bl, 0); |
| 1087 | statlist(ls); |
| 1088 | leaveblock(fs); |
| 1089 | 1089 | } |
| 1090 | 1090 | |
| 1091 | 1091 | |
| r30857 | r30858 | |
| 1094 | 1094 | ** assignment |
| 1095 | 1095 | */ |
| 1096 | 1096 | struct LHS_assign { |
| 1097 | | struct LHS_assign *prev; |
| 1098 | | expdesc v; /* variable (global, local, upvalue, or indexed) */ |
| 1097 | struct LHS_assign *prev; |
| 1098 | expdesc v; /* variable (global, local, upvalue, or indexed) */ |
| 1099 | 1099 | }; |
| 1100 | 1100 | |
| 1101 | 1101 | |
| r30857 | r30858 | |
| 1106 | 1106 | ** use this safe copy in the previous assignment. |
| 1107 | 1107 | */ |
| 1108 | 1108 | static void check_conflict (LexState *ls, struct LHS_assign *lh, expdesc *v) { |
| 1109 | | FuncState *fs = ls->fs; |
| 1110 | | int extra = fs->freereg; /* eventual position to save local variable */ |
| 1111 | | int conflict = 0; |
| 1112 | | for (; lh; lh = lh->prev) { /* check all previous assignments */ |
| 1113 | | if (lh->v.k == VINDEXED) { /* assigning to a table? */ |
| 1114 | | /* table is the upvalue/local being assigned now? */ |
| 1115 | | if (lh->v.u.ind.vt == v->k && lh->v.u.ind.t == v->u.info) { |
| 1116 | | conflict = 1; |
| 1117 | | lh->v.u.ind.vt = VLOCAL; |
| 1118 | | lh->v.u.ind.t = extra; /* previous assignment will use safe copy */ |
| 1119 | | } |
| 1120 | | /* index is the local being assigned? (index cannot be upvalue) */ |
| 1121 | | if (v->k == VLOCAL && lh->v.u.ind.idx == v->u.info) { |
| 1122 | | conflict = 1; |
| 1123 | | lh->v.u.ind.idx = extra; /* previous assignment will use safe copy */ |
| 1124 | | } |
| 1125 | | } |
| 1126 | | } |
| 1127 | | if (conflict) { |
| 1128 | | /* copy upvalue/local value to a temporary (in position 'extra') */ |
| 1129 | | OpCode op = (v->k == VLOCAL) ? OP_MOVE : OP_GETUPVAL; |
| 1130 | | luaK_codeABC(fs, op, extra, v->u.info, 0); |
| 1131 | | luaK_reserveregs(fs, 1); |
| 1132 | | } |
| 1109 | FuncState *fs = ls->fs; |
| 1110 | int extra = fs->freereg; /* eventual position to save local variable */ |
| 1111 | int conflict = 0; |
| 1112 | for (; lh; lh = lh->prev) { /* check all previous assignments */ |
| 1113 | if (lh->v.k == VINDEXED) { /* assigning to a table? */ |
| 1114 | /* table is the upvalue/local being assigned now? */ |
| 1115 | if (lh->v.u.ind.vt == v->k && lh->v.u.ind.t == v->u.info) { |
| 1116 | conflict = 1; |
| 1117 | lh->v.u.ind.vt = VLOCAL; |
| 1118 | lh->v.u.ind.t = extra; /* previous assignment will use safe copy */ |
| 1119 | } |
| 1120 | /* index is the local being assigned? (index cannot be upvalue) */ |
| 1121 | if (v->k == VLOCAL && lh->v.u.ind.idx == v->u.info) { |
| 1122 | conflict = 1; |
| 1123 | lh->v.u.ind.idx = extra; /* previous assignment will use safe copy */ |
| 1124 | } |
| 1125 | } |
| 1126 | } |
| 1127 | if (conflict) { |
| 1128 | /* copy upvalue/local value to a temporary (in position 'extra') */ |
| 1129 | OpCode op = (v->k == VLOCAL) ? OP_MOVE : OP_GETUPVAL; |
| 1130 | luaK_codeABC(fs, op, extra, v->u.info, 0); |
| 1131 | luaK_reserveregs(fs, 1); |
| 1132 | } |
| 1133 | 1133 | } |
| 1134 | 1134 | |
| 1135 | 1135 | |
| 1136 | 1136 | static void assignment (LexState *ls, struct LHS_assign *lh, int nvars) { |
| 1137 | | expdesc e; |
| 1138 | | check_condition(ls, vkisvar(lh->v.k), "syntax error"); |
| 1139 | | if (testnext(ls, ',')) { /* assignment -> ',' suffixedexp assignment */ |
| 1140 | | struct LHS_assign nv; |
| 1141 | | nv.prev = lh; |
| 1142 | | suffixedexp(ls, &nv.v); |
| 1143 | | if (nv.v.k != VINDEXED) |
| 1144 | | check_conflict(ls, lh, &nv.v); |
| 1145 | | checklimit(ls->fs, nvars + ls->L->nCcalls, LUAI_MAXCCALLS, |
| 1146 | | "C levels"); |
| 1147 | | assignment(ls, &nv, nvars+1); |
| 1148 | | } |
| 1149 | | else { /* assignment -> `=' explist */ |
| 1150 | | int nexps; |
| 1151 | | checknext(ls, '='); |
| 1152 | | nexps = explist(ls, &e); |
| 1153 | | if (nexps != nvars) { |
| 1154 | | adjust_assign(ls, nvars, nexps, &e); |
| 1155 | | if (nexps > nvars) |
| 1156 | | ls->fs->freereg -= nexps - nvars; /* remove extra values */ |
| 1157 | | } |
| 1158 | | else { |
| 1159 | | luaK_setoneret(ls->fs, &e); /* close last expression */ |
| 1160 | | luaK_storevar(ls->fs, &lh->v, &e); |
| 1161 | | return; /* avoid default */ |
| 1162 | | } |
| 1163 | | } |
| 1164 | | init_exp(&e, VNONRELOC, ls->fs->freereg-1); /* default assignment */ |
| 1165 | | luaK_storevar(ls->fs, &lh->v, &e); |
| 1137 | expdesc e; |
| 1138 | check_condition(ls, vkisvar(lh->v.k), "syntax error"); |
| 1139 | if (testnext(ls, ',')) { /* assignment -> ',' suffixedexp assignment */ |
| 1140 | struct LHS_assign nv; |
| 1141 | nv.prev = lh; |
| 1142 | suffixedexp(ls, &nv.v); |
| 1143 | if (nv.v.k != VINDEXED) |
| 1144 | check_conflict(ls, lh, &nv.v); |
| 1145 | checklimit(ls->fs, nvars + ls->L->nCcalls, LUAI_MAXCCALLS, |
| 1146 | "C levels"); |
| 1147 | assignment(ls, &nv, nvars+1); |
| 1148 | } |
| 1149 | else { /* assignment -> `=' explist */ |
| 1150 | int nexps; |
| 1151 | checknext(ls, '='); |
| 1152 | nexps = explist(ls, &e); |
| 1153 | if (nexps != nvars) { |
| 1154 | adjust_assign(ls, nvars, nexps, &e); |
| 1155 | if (nexps > nvars) |
| 1156 | ls->fs->freereg -= nexps - nvars; /* remove extra values */ |
| 1157 | } |
| 1158 | else { |
| 1159 | luaK_setoneret(ls->fs, &e); /* close last expression */ |
| 1160 | luaK_storevar(ls->fs, &lh->v, &e); |
| 1161 | return; /* avoid default */ |
| 1162 | } |
| 1163 | } |
| 1164 | init_exp(&e, VNONRELOC, ls->fs->freereg-1); /* default assignment */ |
| 1165 | luaK_storevar(ls->fs, &lh->v, &e); |
| 1166 | 1166 | } |
| 1167 | 1167 | |
| 1168 | 1168 | |
| 1169 | 1169 | static int cond (LexState *ls) { |
| 1170 | | /* cond -> exp */ |
| 1171 | | expdesc v; |
| 1172 | | expr(ls, &v); /* read condition */ |
| 1173 | | if (v.k == VNIL) v.k = VFALSE; /* `falses' are all equal here */ |
| 1174 | | luaK_goiftrue(ls->fs, &v); |
| 1175 | | return v.f; |
| 1170 | /* cond -> exp */ |
| 1171 | expdesc v; |
| 1172 | expr(ls, &v); /* read condition */ |
| 1173 | if (v.k == VNIL) v.k = VFALSE; /* `falses' are all equal here */ |
| 1174 | luaK_goiftrue(ls->fs, &v); |
| 1175 | return v.f; |
| 1176 | 1176 | } |
| 1177 | 1177 | |
| 1178 | 1178 | |
| 1179 | 1179 | static void gotostat (LexState *ls, int pc) { |
| 1180 | | int line = ls->linenumber; |
| 1181 | | TString *label; |
| 1182 | | int g; |
| 1183 | | if (testnext(ls, TK_GOTO)) |
| 1184 | | label = str_checkname(ls); |
| 1185 | | else { |
| 1186 | | luaX_next(ls); /* skip break */ |
| 1187 | | label = luaS_new(ls->L, "break"); |
| 1188 | | } |
| 1189 | | g = newlabelentry(ls, &ls->dyd->gt, label, line, pc); |
| 1190 | | findlabel(ls, g); /* close it if label already defined */ |
| 1180 | int line = ls->linenumber; |
| 1181 | TString *label; |
| 1182 | int g; |
| 1183 | if (testnext(ls, TK_GOTO)) |
| 1184 | label = str_checkname(ls); |
| 1185 | else { |
| 1186 | luaX_next(ls); /* skip break */ |
| 1187 | label = luaS_new(ls->L, "break"); |
| 1188 | } |
| 1189 | g = newlabelentry(ls, &ls->dyd->gt, label, line, pc); |
| 1190 | findlabel(ls, g); /* close it if label already defined */ |
| 1191 | 1191 | } |
| 1192 | 1192 | |
| 1193 | 1193 | |
| 1194 | 1194 | /* check for repeated labels on the same block */ |
| 1195 | 1195 | static void checkrepeated (FuncState *fs, Labellist *ll, TString *label) { |
| 1196 | | int i; |
| 1197 | | for (i = fs->bl->firstlabel; i < ll->n; i++) { |
| 1198 | | if (luaS_eqstr(label, ll->arr[i].name)) { |
| 1199 | | const char *msg = luaO_pushfstring(fs->ls->L, |
| 1200 | | "label " LUA_QS " already defined on line %d", |
| 1201 | | getstr(label), ll->arr[i].line); |
| 1202 | | semerror(fs->ls, msg); |
| 1203 | | } |
| 1204 | | } |
| 1196 | int i; |
| 1197 | for (i = fs->bl->firstlabel; i < ll->n; i++) { |
| 1198 | if (luaS_eqstr(label, ll->arr[i].name)) { |
| 1199 | const char *msg = luaO_pushfstring(fs->ls->L, |
| 1200 | "label " LUA_QS " already defined on line %d", |
| 1201 | getstr(label), ll->arr[i].line); |
| 1202 | semerror(fs->ls, msg); |
| 1203 | } |
| 1204 | } |
| 1205 | 1205 | } |
| 1206 | 1206 | |
| 1207 | 1207 | |
| 1208 | 1208 | /* skip no-op statements */ |
| 1209 | 1209 | static void skipnoopstat (LexState *ls) { |
| 1210 | | while (ls->t.token == ';' || ls->t.token == TK_DBCOLON) |
| 1211 | | statement(ls); |
| 1210 | while (ls->t.token == ';' || ls->t.token == TK_DBCOLON) |
| 1211 | statement(ls); |
| 1212 | 1212 | } |
| 1213 | 1213 | |
| 1214 | 1214 | |
| 1215 | 1215 | static void labelstat (LexState *ls, TString *label, int line) { |
| 1216 | | /* label -> '::' NAME '::' */ |
| 1217 | | FuncState *fs = ls->fs; |
| 1218 | | Labellist *ll = &ls->dyd->label; |
| 1219 | | int l; /* index of new label being created */ |
| 1220 | | checkrepeated(fs, ll, label); /* check for repeated labels */ |
| 1221 | | checknext(ls, TK_DBCOLON); /* skip double colon */ |
| 1222 | | /* create new entry for this label */ |
| 1223 | | l = newlabelentry(ls, ll, label, line, fs->pc); |
| 1224 | | skipnoopstat(ls); /* skip other no-op statements */ |
| 1225 | | if (block_follow(ls, 0)) { /* label is last no-op statement in the block? */ |
| 1226 | | /* assume that locals are already out of scope */ |
| 1227 | | ll->arr[l].nactvar = fs->bl->nactvar; |
| 1228 | | } |
| 1229 | | findgotos(ls, &ll->arr[l]); |
| 1216 | /* label -> '::' NAME '::' */ |
| 1217 | FuncState *fs = ls->fs; |
| 1218 | Labellist *ll = &ls->dyd->label; |
| 1219 | int l; /* index of new label being created */ |
| 1220 | checkrepeated(fs, ll, label); /* check for repeated labels */ |
| 1221 | checknext(ls, TK_DBCOLON); /* skip double colon */ |
| 1222 | /* create new entry for this label */ |
| 1223 | l = newlabelentry(ls, ll, label, line, fs->pc); |
| 1224 | skipnoopstat(ls); /* skip other no-op statements */ |
| 1225 | if (block_follow(ls, 0)) { /* label is last no-op statement in the block? */ |
| 1226 | /* assume that locals are already out of scope */ |
| 1227 | ll->arr[l].nactvar = fs->bl->nactvar; |
| 1228 | } |
| 1229 | findgotos(ls, &ll->arr[l]); |
| 1230 | 1230 | } |
| 1231 | 1231 | |
| 1232 | 1232 | |
| 1233 | 1233 | static void whilestat (LexState *ls, int line) { |
| 1234 | | /* whilestat -> WHILE cond DO block END */ |
| 1235 | | FuncState *fs = ls->fs; |
| 1236 | | int whileinit; |
| 1237 | | int condexit; |
| 1238 | | BlockCnt bl; |
| 1239 | | luaX_next(ls); /* skip WHILE */ |
| 1240 | | whileinit = luaK_getlabel(fs); |
| 1241 | | condexit = cond(ls); |
| 1242 | | enterblock(fs, &bl, 1); |
| 1243 | | checknext(ls, TK_DO); |
| 1244 | | block(ls); |
| 1245 | | luaK_jumpto(fs, whileinit); |
| 1246 | | check_match(ls, TK_END, TK_WHILE, line); |
| 1247 | | leaveblock(fs); |
| 1248 | | luaK_patchtohere(fs, condexit); /* false conditions finish the loop */ |
| 1234 | /* whilestat -> WHILE cond DO block END */ |
| 1235 | FuncState *fs = ls->fs; |
| 1236 | int whileinit; |
| 1237 | int condexit; |
| 1238 | BlockCnt bl; |
| 1239 | luaX_next(ls); /* skip WHILE */ |
| 1240 | whileinit = luaK_getlabel(fs); |
| 1241 | condexit = cond(ls); |
| 1242 | enterblock(fs, &bl, 1); |
| 1243 | checknext(ls, TK_DO); |
| 1244 | block(ls); |
| 1245 | luaK_jumpto(fs, whileinit); |
| 1246 | check_match(ls, TK_END, TK_WHILE, line); |
| 1247 | leaveblock(fs); |
| 1248 | luaK_patchtohere(fs, condexit); /* false conditions finish the loop */ |
| 1249 | 1249 | } |
| 1250 | 1250 | |
| 1251 | 1251 | |
| 1252 | 1252 | static void repeatstat (LexState *ls, int line) { |
| 1253 | | /* repeatstat -> REPEAT block UNTIL cond */ |
| 1254 | | int condexit; |
| 1255 | | FuncState *fs = ls->fs; |
| 1256 | | int repeat_init = luaK_getlabel(fs); |
| 1257 | | BlockCnt bl1, bl2; |
| 1258 | | enterblock(fs, &bl1, 1); /* loop block */ |
| 1259 | | enterblock(fs, &bl2, 0); /* scope block */ |
| 1260 | | luaX_next(ls); /* skip REPEAT */ |
| 1261 | | statlist(ls); |
| 1262 | | check_match(ls, TK_UNTIL, TK_REPEAT, line); |
| 1263 | | condexit = cond(ls); /* read condition (inside scope block) */ |
| 1264 | | if (bl2.upval) /* upvalues? */ |
| 1265 | | luaK_patchclose(fs, condexit, bl2.nactvar); |
| 1266 | | leaveblock(fs); /* finish scope */ |
| 1267 | | luaK_patchlist(fs, condexit, repeat_init); /* close the loop */ |
| 1268 | | leaveblock(fs); /* finish loop */ |
| 1253 | /* repeatstat -> REPEAT block UNTIL cond */ |
| 1254 | int condexit; |
| 1255 | FuncState *fs = ls->fs; |
| 1256 | int repeat_init = luaK_getlabel(fs); |
| 1257 | BlockCnt bl1, bl2; |
| 1258 | enterblock(fs, &bl1, 1); /* loop block */ |
| 1259 | enterblock(fs, &bl2, 0); /* scope block */ |
| 1260 | luaX_next(ls); /* skip REPEAT */ |
| 1261 | statlist(ls); |
| 1262 | check_match(ls, TK_UNTIL, TK_REPEAT, line); |
| 1263 | condexit = cond(ls); /* read condition (inside scope block) */ |
| 1264 | if (bl2.upval) /* upvalues? */ |
| 1265 | luaK_patchclose(fs, condexit, bl2.nactvar); |
| 1266 | leaveblock(fs); /* finish scope */ |
| 1267 | luaK_patchlist(fs, condexit, repeat_init); /* close the loop */ |
| 1268 | leaveblock(fs); /* finish loop */ |
| 1269 | 1269 | } |
| 1270 | 1270 | |
| 1271 | 1271 | |
| 1272 | 1272 | static int exp1 (LexState *ls) { |
| 1273 | | expdesc e; |
| 1274 | | int reg; |
| 1275 | | expr(ls, &e); |
| 1276 | | luaK_exp2nextreg(ls->fs, &e); |
| 1277 | | lua_assert(e.k == VNONRELOC); |
| 1278 | | reg = e.u.info; |
| 1279 | | return reg; |
| 1273 | expdesc e; |
| 1274 | int reg; |
| 1275 | expr(ls, &e); |
| 1276 | luaK_exp2nextreg(ls->fs, &e); |
| 1277 | lua_assert(e.k == VNONRELOC); |
| 1278 | reg = e.u.info; |
| 1279 | return reg; |
| 1280 | 1280 | } |
| 1281 | 1281 | |
| 1282 | 1282 | |
| 1283 | 1283 | static void forbody (LexState *ls, int base, int line, int nvars, int isnum) { |
| 1284 | | /* forbody -> DO block */ |
| 1285 | | BlockCnt bl; |
| 1286 | | FuncState *fs = ls->fs; |
| 1287 | | int prep, endfor; |
| 1288 | | adjustlocalvars(ls, 3); /* control variables */ |
| 1289 | | checknext(ls, TK_DO); |
| 1290 | | prep = isnum ? luaK_codeAsBx(fs, OP_FORPREP, base, NO_JUMP) : luaK_jump(fs); |
| 1291 | | enterblock(fs, &bl, 0); /* scope for declared variables */ |
| 1292 | | adjustlocalvars(ls, nvars); |
| 1293 | | luaK_reserveregs(fs, nvars); |
| 1294 | | block(ls); |
| 1295 | | leaveblock(fs); /* end of scope for declared variables */ |
| 1296 | | luaK_patchtohere(fs, prep); |
| 1297 | | if (isnum) /* numeric for? */ |
| 1298 | | endfor = luaK_codeAsBx(fs, OP_FORLOOP, base, NO_JUMP); |
| 1299 | | else { /* generic for */ |
| 1300 | | luaK_codeABC(fs, OP_TFORCALL, base, 0, nvars); |
| 1301 | | luaK_fixline(fs, line); |
| 1302 | | endfor = luaK_codeAsBx(fs, OP_TFORLOOP, base + 2, NO_JUMP); |
| 1303 | | } |
| 1304 | | luaK_patchlist(fs, endfor, prep + 1); |
| 1305 | | luaK_fixline(fs, line); |
| 1284 | /* forbody -> DO block */ |
| 1285 | BlockCnt bl; |
| 1286 | FuncState *fs = ls->fs; |
| 1287 | int prep, endfor; |
| 1288 | adjustlocalvars(ls, 3); /* control variables */ |
| 1289 | checknext(ls, TK_DO); |
| 1290 | prep = isnum ? luaK_codeAsBx(fs, OP_FORPREP, base, NO_JUMP) : luaK_jump(fs); |
| 1291 | enterblock(fs, &bl, 0); /* scope for declared variables */ |
| 1292 | adjustlocalvars(ls, nvars); |
| 1293 | luaK_reserveregs(fs, nvars); |
| 1294 | block(ls); |
| 1295 | leaveblock(fs); /* end of scope for declared variables */ |
| 1296 | luaK_patchtohere(fs, prep); |
| 1297 | if (isnum) /* numeric for? */ |
| 1298 | endfor = luaK_codeAsBx(fs, OP_FORLOOP, base, NO_JUMP); |
| 1299 | else { /* generic for */ |
| 1300 | luaK_codeABC(fs, OP_TFORCALL, base, 0, nvars); |
| 1301 | luaK_fixline(fs, line); |
| 1302 | endfor = luaK_codeAsBx(fs, OP_TFORLOOP, base + 2, NO_JUMP); |
| 1303 | } |
| 1304 | luaK_patchlist(fs, endfor, prep + 1); |
| 1305 | luaK_fixline(fs, line); |
| 1306 | 1306 | } |
| 1307 | 1307 | |
| 1308 | 1308 | |
| 1309 | 1309 | static void fornum (LexState *ls, TString *varname, int line) { |
| 1310 | | /* fornum -> NAME = exp1,exp1[,exp1] forbody */ |
| 1311 | | FuncState *fs = ls->fs; |
| 1312 | | int base = fs->freereg; |
| 1313 | | new_localvarliteral(ls, "(for index)"); |
| 1314 | | new_localvarliteral(ls, "(for limit)"); |
| 1315 | | new_localvarliteral(ls, "(for step)"); |
| 1316 | | new_localvar(ls, varname); |
| 1317 | | checknext(ls, '='); |
| 1318 | | exp1(ls); /* initial value */ |
| 1319 | | checknext(ls, ','); |
| 1320 | | exp1(ls); /* limit */ |
| 1321 | | if (testnext(ls, ',')) |
| 1322 | | exp1(ls); /* optional step */ |
| 1323 | | else { /* default step = 1 */ |
| 1324 | | luaK_codek(fs, fs->freereg, luaK_numberK(fs, 1)); |
| 1325 | | luaK_reserveregs(fs, 1); |
| 1326 | | } |
| 1327 | | forbody(ls, base, line, 1, 1); |
| 1310 | /* fornum -> NAME = exp1,exp1[,exp1] forbody */ |
| 1311 | FuncState *fs = ls->fs; |
| 1312 | int base = fs->freereg; |
| 1313 | new_localvarliteral(ls, "(for index)"); |
| 1314 | new_localvarliteral(ls, "(for limit)"); |
| 1315 | new_localvarliteral(ls, "(for step)"); |
| 1316 | new_localvar(ls, varname); |
| 1317 | checknext(ls, '='); |
| 1318 | exp1(ls); /* initial value */ |
| 1319 | checknext(ls, ','); |
| 1320 | exp1(ls); /* limit */ |
| 1321 | if (testnext(ls, ',')) |
| 1322 | exp1(ls); /* optional step */ |
| 1323 | else { /* default step = 1 */ |
| 1324 | luaK_codek(fs, fs->freereg, luaK_numberK(fs, 1)); |
| 1325 | luaK_reserveregs(fs, 1); |
| 1326 | } |
| 1327 | forbody(ls, base, line, 1, 1); |
| 1328 | 1328 | } |
| 1329 | 1329 | |
| 1330 | 1330 | |
| 1331 | 1331 | static void forlist (LexState *ls, TString *indexname) { |
| 1332 | | /* forlist -> NAME {,NAME} IN explist forbody */ |
| 1333 | | FuncState *fs = ls->fs; |
| 1334 | | expdesc e; |
| 1335 | | int nvars = 4; /* gen, state, control, plus at least one declared var */ |
| 1336 | | int line; |
| 1337 | | int base = fs->freereg; |
| 1338 | | /* create control variables */ |
| 1339 | | new_localvarliteral(ls, "(for generator)"); |
| 1340 | | new_localvarliteral(ls, "(for state)"); |
| 1341 | | new_localvarliteral(ls, "(for control)"); |
| 1342 | | /* create declared variables */ |
| 1343 | | new_localvar(ls, indexname); |
| 1344 | | while (testnext(ls, ',')) { |
| 1345 | | new_localvar(ls, str_checkname(ls)); |
| 1346 | | nvars++; |
| 1347 | | } |
| 1348 | | checknext(ls, TK_IN); |
| 1349 | | line = ls->linenumber; |
| 1350 | | adjust_assign(ls, 3, explist(ls, &e), &e); |
| 1351 | | luaK_checkstack(fs, 3); /* extra space to call generator */ |
| 1352 | | forbody(ls, base, line, nvars - 3, 0); |
| 1332 | /* forlist -> NAME {,NAME} IN explist forbody */ |
| 1333 | FuncState *fs = ls->fs; |
| 1334 | expdesc e; |
| 1335 | int nvars = 4; /* gen, state, control, plus at least one declared var */ |
| 1336 | int line; |
| 1337 | int base = fs->freereg; |
| 1338 | /* create control variables */ |
| 1339 | new_localvarliteral(ls, "(for generator)"); |
| 1340 | new_localvarliteral(ls, "(for state)"); |
| 1341 | new_localvarliteral(ls, "(for control)"); |
| 1342 | /* create declared variables */ |
| 1343 | new_localvar(ls, indexname); |
| 1344 | while (testnext(ls, ',')) { |
| 1345 | new_localvar(ls, str_checkname(ls)); |
| 1346 | nvars++; |
| 1347 | } |
| 1348 | checknext(ls, TK_IN); |
| 1349 | line = ls->linenumber; |
| 1350 | adjust_assign(ls, 3, explist(ls, &e), &e); |
| 1351 | luaK_checkstack(fs, 3); /* extra space to call generator */ |
| 1352 | forbody(ls, base, line, nvars - 3, 0); |
| 1353 | 1353 | } |
| 1354 | 1354 | |
| 1355 | 1355 | |
| 1356 | 1356 | static void forstat (LexState *ls, int line) { |
| 1357 | | /* forstat -> FOR (fornum | forlist) END */ |
| 1358 | | FuncState *fs = ls->fs; |
| 1359 | | TString *varname; |
| 1360 | | BlockCnt bl; |
| 1361 | | enterblock(fs, &bl, 1); /* scope for loop and control variables */ |
| 1362 | | luaX_next(ls); /* skip `for' */ |
| 1363 | | varname = str_checkname(ls); /* first variable name */ |
| 1364 | | switch (ls->t.token) { |
| 1365 | | case '=': fornum(ls, varname, line); break; |
| 1366 | | case ',': case TK_IN: forlist(ls, varname); break; |
| 1367 | | default: luaX_syntaxerror(ls, LUA_QL("=") " or " LUA_QL("in") " expected"); |
| 1368 | | } |
| 1369 | | check_match(ls, TK_END, TK_FOR, line); |
| 1370 | | leaveblock(fs); /* loop scope (`break' jumps to this point) */ |
| 1357 | /* forstat -> FOR (fornum | forlist) END */ |
| 1358 | FuncState *fs = ls->fs; |
| 1359 | TString *varname; |
| 1360 | BlockCnt bl; |
| 1361 | enterblock(fs, &bl, 1); /* scope for loop and control variables */ |
| 1362 | luaX_next(ls); /* skip `for' */ |
| 1363 | varname = str_checkname(ls); /* first variable name */ |
| 1364 | switch (ls->t.token) { |
| 1365 | case '=': fornum(ls, varname, line); break; |
| 1366 | case ',': case TK_IN: forlist(ls, varname); break; |
| 1367 | default: luaX_syntaxerror(ls, LUA_QL("=") " or " LUA_QL("in") " expected"); |
| 1368 | } |
| 1369 | check_match(ls, TK_END, TK_FOR, line); |
| 1370 | leaveblock(fs); /* loop scope (`break' jumps to this point) */ |
| 1371 | 1371 | } |
| 1372 | 1372 | |
| 1373 | 1373 | |
| 1374 | 1374 | static void test_then_block (LexState *ls, int *escapelist) { |
| 1375 | | /* test_then_block -> [IF | ELSEIF] cond THEN block */ |
| 1376 | | BlockCnt bl; |
| 1377 | | FuncState *fs = ls->fs; |
| 1378 | | expdesc v; |
| 1379 | | int jf; /* instruction to skip 'then' code (if condition is false) */ |
| 1380 | | luaX_next(ls); /* skip IF or ELSEIF */ |
| 1381 | | expr(ls, &v); /* read condition */ |
| 1382 | | checknext(ls, TK_THEN); |
| 1383 | | if (ls->t.token == TK_GOTO || ls->t.token == TK_BREAK) { |
| 1384 | | luaK_goiffalse(ls->fs, &v); /* will jump to label if condition is true */ |
| 1385 | | enterblock(fs, &bl, 0); /* must enter block before 'goto' */ |
| 1386 | | gotostat(ls, v.t); /* handle goto/break */ |
| 1387 | | skipnoopstat(ls); /* skip other no-op statements */ |
| 1388 | | if (block_follow(ls, 0)) { /* 'goto' is the entire block? */ |
| 1389 | | leaveblock(fs); |
| 1390 | | return; /* and that is it */ |
| 1391 | | } |
| 1392 | | else /* must skip over 'then' part if condition is false */ |
| 1393 | | jf = luaK_jump(fs); |
| 1394 | | } |
| 1395 | | else { /* regular case (not goto/break) */ |
| 1396 | | luaK_goiftrue(ls->fs, &v); /* skip over block if condition is false */ |
| 1397 | | enterblock(fs, &bl, 0); |
| 1398 | | jf = v.f; |
| 1399 | | } |
| 1400 | | statlist(ls); /* `then' part */ |
| 1401 | | leaveblock(fs); |
| 1402 | | if (ls->t.token == TK_ELSE || |
| 1403 | | ls->t.token == TK_ELSEIF) /* followed by 'else'/'elseif'? */ |
| 1404 | | luaK_concat(fs, escapelist, luaK_jump(fs)); /* must jump over it */ |
| 1405 | | luaK_patchtohere(fs, jf); |
| 1375 | /* test_then_block -> [IF | ELSEIF] cond THEN block */ |
| 1376 | BlockCnt bl; |
| 1377 | FuncState *fs = ls->fs; |
| 1378 | expdesc v; |
| 1379 | int jf; /* instruction to skip 'then' code (if condition is false) */ |
| 1380 | luaX_next(ls); /* skip IF or ELSEIF */ |
| 1381 | expr(ls, &v); /* read condition */ |
| 1382 | checknext(ls, TK_THEN); |
| 1383 | if (ls->t.token == TK_GOTO || ls->t.token == TK_BREAK) { |
| 1384 | luaK_goiffalse(ls->fs, &v); /* will jump to label if condition is true */ |
| 1385 | enterblock(fs, &bl, 0); /* must enter block before 'goto' */ |
| 1386 | gotostat(ls, v.t); /* handle goto/break */ |
| 1387 | skipnoopstat(ls); /* skip other no-op statements */ |
| 1388 | if (block_follow(ls, 0)) { /* 'goto' is the entire block? */ |
| 1389 | leaveblock(fs); |
| 1390 | return; /* and that is it */ |
| 1391 | } |
| 1392 | else /* must skip over 'then' part if condition is false */ |
| 1393 | jf = luaK_jump(fs); |
| 1394 | } |
| 1395 | else { /* regular case (not goto/break) */ |
| 1396 | luaK_goiftrue(ls->fs, &v); /* skip over block if condition is false */ |
| 1397 | enterblock(fs, &bl, 0); |
| 1398 | jf = v.f; |
| 1399 | } |
| 1400 | statlist(ls); /* `then' part */ |
| 1401 | leaveblock(fs); |
| 1402 | if (ls->t.token == TK_ELSE || |
| 1403 | ls->t.token == TK_ELSEIF) /* followed by 'else'/'elseif'? */ |
| 1404 | luaK_concat(fs, escapelist, luaK_jump(fs)); /* must jump over it */ |
| 1405 | luaK_patchtohere(fs, jf); |
| 1406 | 1406 | } |
| 1407 | 1407 | |
| 1408 | 1408 | |
| 1409 | 1409 | static void ifstat (LexState *ls, int line) { |
| 1410 | | /* ifstat -> IF cond THEN block {ELSEIF cond THEN block} [ELSE block] END */ |
| 1411 | | FuncState *fs = ls->fs; |
| 1412 | | int escapelist = NO_JUMP; /* exit list for finished parts */ |
| 1413 | | test_then_block(ls, &escapelist); /* IF cond THEN block */ |
| 1414 | | while (ls->t.token == TK_ELSEIF) |
| 1415 | | test_then_block(ls, &escapelist); /* ELSEIF cond THEN block */ |
| 1416 | | if (testnext(ls, TK_ELSE)) |
| 1417 | | block(ls); /* `else' part */ |
| 1418 | | check_match(ls, TK_END, TK_IF, line); |
| 1419 | | luaK_patchtohere(fs, escapelist); /* patch escape list to 'if' end */ |
| 1410 | /* ifstat -> IF cond THEN block {ELSEIF cond THEN block} [ELSE block] END */ |
| 1411 | FuncState *fs = ls->fs; |
| 1412 | int escapelist = NO_JUMP; /* exit list for finished parts */ |
| 1413 | test_then_block(ls, &escapelist); /* IF cond THEN block */ |
| 1414 | while (ls->t.token == TK_ELSEIF) |
| 1415 | test_then_block(ls, &escapelist); /* ELSEIF cond THEN block */ |
| 1416 | if (testnext(ls, TK_ELSE)) |
| 1417 | block(ls); /* `else' part */ |
| 1418 | check_match(ls, TK_END, TK_IF, line); |
| 1419 | luaK_patchtohere(fs, escapelist); /* patch escape list to 'if' end */ |
| 1420 | 1420 | } |
| 1421 | 1421 | |
| 1422 | 1422 | |
| 1423 | 1423 | static void localfunc (LexState *ls) { |
| 1424 | | expdesc b; |
| 1425 | | FuncState *fs = ls->fs; |
| 1426 | | new_localvar(ls, str_checkname(ls)); /* new local variable */ |
| 1427 | | adjustlocalvars(ls, 1); /* enter its scope */ |
| 1428 | | body(ls, &b, 0, ls->linenumber); /* function created in next register */ |
| 1429 | | /* debug information will only see the variable after this point! */ |
| 1430 | | getlocvar(fs, b.u.info)->startpc = fs->pc; |
| 1424 | expdesc b; |
| 1425 | FuncState *fs = ls->fs; |
| 1426 | new_localvar(ls, str_checkname(ls)); /* new local variable */ |
| 1427 | adjustlocalvars(ls, 1); /* enter its scope */ |
| 1428 | body(ls, &b, 0, ls->linenumber); /* function created in next register */ |
| 1429 | /* debug information will only see the variable after this point! */ |
| 1430 | getlocvar(fs, b.u.info)->startpc = fs->pc; |
| 1431 | 1431 | } |
| 1432 | 1432 | |
| 1433 | 1433 | |
| 1434 | 1434 | static void localstat (LexState *ls) { |
| 1435 | | /* stat -> LOCAL NAME {`,' NAME} [`=' explist] */ |
| 1436 | | int nvars = 0; |
| 1437 | | int nexps; |
| 1438 | | expdesc e; |
| 1439 | | do { |
| 1440 | | new_localvar(ls, str_checkname(ls)); |
| 1441 | | nvars++; |
| 1442 | | } while (testnext(ls, ',')); |
| 1443 | | if (testnext(ls, '=')) |
| 1444 | | nexps = explist(ls, &e); |
| 1445 | | else { |
| 1446 | | e.k = VVOID; |
| 1447 | | nexps = 0; |
| 1448 | | } |
| 1449 | | adjust_assign(ls, nvars, nexps, &e); |
| 1450 | | adjustlocalvars(ls, nvars); |
| 1435 | /* stat -> LOCAL NAME {`,' NAME} [`=' explist] */ |
| 1436 | int nvars = 0; |
| 1437 | int nexps; |
| 1438 | expdesc e; |
| 1439 | do { |
| 1440 | new_localvar(ls, str_checkname(ls)); |
| 1441 | nvars++; |
| 1442 | } while (testnext(ls, ',')); |
| 1443 | if (testnext(ls, '=')) |
| 1444 | nexps = explist(ls, &e); |
| 1445 | else { |
| 1446 | e.k = VVOID; |
| 1447 | nexps = 0; |
| 1448 | } |
| 1449 | adjust_assign(ls, nvars, nexps, &e); |
| 1450 | adjustlocalvars(ls, nvars); |
| 1451 | 1451 | } |
| 1452 | 1452 | |
| 1453 | 1453 | |
| 1454 | 1454 | static int funcname (LexState *ls, expdesc *v) { |
| 1455 | | /* funcname -> NAME {fieldsel} [`:' NAME] */ |
| 1456 | | int ismethod = 0; |
| 1457 | | singlevar(ls, v); |
| 1458 | | while (ls->t.token == '.') |
| 1459 | | fieldsel(ls, v); |
| 1460 | | if (ls->t.token == ':') { |
| 1461 | | ismethod = 1; |
| 1462 | | fieldsel(ls, v); |
| 1463 | | } |
| 1464 | | return ismethod; |
| 1455 | /* funcname -> NAME {fieldsel} [`:' NAME] */ |
| 1456 | int ismethod = 0; |
| 1457 | singlevar(ls, v); |
| 1458 | while (ls->t.token == '.') |
| 1459 | fieldsel(ls, v); |
| 1460 | if (ls->t.token == ':') { |
| 1461 | ismethod = 1; |
| 1462 | fieldsel(ls, v); |
| 1463 | } |
| 1464 | return ismethod; |
| 1465 | 1465 | } |
| 1466 | 1466 | |
| 1467 | 1467 | |
| 1468 | 1468 | static void funcstat (LexState *ls, int line) { |
| 1469 | | /* funcstat -> FUNCTION funcname body */ |
| 1470 | | int ismethod; |
| 1471 | | expdesc v, b; |
| 1472 | | luaX_next(ls); /* skip FUNCTION */ |
| 1473 | | ismethod = funcname(ls, &v); |
| 1474 | | body(ls, &b, ismethod, line); |
| 1475 | | luaK_storevar(ls->fs, &v, &b); |
| 1476 | | luaK_fixline(ls->fs, line); /* definition `happens' in the first line */ |
| 1469 | /* funcstat -> FUNCTION funcname body */ |
| 1470 | int ismethod; |
| 1471 | expdesc v, b; |
| 1472 | luaX_next(ls); /* skip FUNCTION */ |
| 1473 | ismethod = funcname(ls, &v); |
| 1474 | body(ls, &b, ismethod, line); |
| 1475 | luaK_storevar(ls->fs, &v, &b); |
| 1476 | luaK_fixline(ls->fs, line); /* definition `happens' in the first line */ |
| 1477 | 1477 | } |
| 1478 | 1478 | |
| 1479 | 1479 | |
| 1480 | 1480 | static void exprstat (LexState *ls) { |
| 1481 | | /* stat -> func | assignment */ |
| 1482 | | FuncState *fs = ls->fs; |
| 1483 | | struct LHS_assign v; |
| 1484 | | suffixedexp(ls, &v.v); |
| 1485 | | if (ls->t.token == '=' || ls->t.token == ',') { /* stat -> assignment ? */ |
| 1486 | | v.prev = NULL; |
| 1487 | | assignment(ls, &v, 1); |
| 1488 | | } |
| 1489 | | else { /* stat -> func */ |
| 1490 | | check_condition(ls, v.v.k == VCALL, "syntax error"); |
| 1491 | | SETARG_C(getcode(fs, &v.v), 1); /* call statement uses no results */ |
| 1492 | | } |
| 1481 | /* stat -> func | assignment */ |
| 1482 | FuncState *fs = ls->fs; |
| 1483 | struct LHS_assign v; |
| 1484 | suffixedexp(ls, &v.v); |
| 1485 | if (ls->t.token == '=' || ls->t.token == ',') { /* stat -> assignment ? */ |
| 1486 | v.prev = NULL; |
| 1487 | assignment(ls, &v, 1); |
| 1488 | } |
| 1489 | else { /* stat -> func */ |
| 1490 | check_condition(ls, v.v.k == VCALL, "syntax error"); |
| 1491 | SETARG_C(getcode(fs, &v.v), 1); /* call statement uses no results */ |
| 1492 | } |
| 1493 | 1493 | } |
| 1494 | 1494 | |
| 1495 | 1495 | |
| 1496 | 1496 | static void retstat (LexState *ls) { |
| 1497 | | /* stat -> RETURN [explist] [';'] */ |
| 1498 | | FuncState *fs = ls->fs; |
| 1499 | | expdesc e; |
| 1500 | | int first, nret; /* registers with returned values */ |
| 1501 | | if (block_follow(ls, 1) || ls->t.token == ';') |
| 1502 | | first = nret = 0; /* return no values */ |
| 1503 | | else { |
| 1504 | | nret = explist(ls, &e); /* optional return values */ |
| 1505 | | if (hasmultret(e.k)) { |
| 1506 | | luaK_setmultret(fs, &e); |
| 1507 | | if (e.k == VCALL && nret == 1) { /* tail call? */ |
| 1508 | | SET_OPCODE(getcode(fs,&e), OP_TAILCALL); |
| 1509 | | lua_assert(GETARG_A(getcode(fs,&e)) == fs->nactvar); |
| 1510 | | } |
| 1511 | | first = fs->nactvar; |
| 1512 | | nret = LUA_MULTRET; /* return all values */ |
| 1513 | | } |
| 1514 | | else { |
| 1515 | | if (nret == 1) /* only one single value? */ |
| 1516 | | first = luaK_exp2anyreg(fs, &e); |
| 1517 | | else { |
| 1518 | | luaK_exp2nextreg(fs, &e); /* values must go to the `stack' */ |
| 1519 | | first = fs->nactvar; /* return all `active' values */ |
| 1520 | | lua_assert(nret == fs->freereg - first); |
| 1521 | | } |
| 1522 | | } |
| 1523 | | } |
| 1524 | | luaK_ret(fs, first, nret); |
| 1525 | | testnext(ls, ';'); /* skip optional semicolon */ |
| 1497 | /* stat -> RETURN [explist] [';'] */ |
| 1498 | FuncState *fs = ls->fs; |
| 1499 | expdesc e; |
| 1500 | int first, nret; /* registers with returned values */ |
| 1501 | if (block_follow(ls, 1) || ls->t.token == ';') |
| 1502 | first = nret = 0; /* return no values */ |
| 1503 | else { |
| 1504 | nret = explist(ls, &e); /* optional return values */ |
| 1505 | if (hasmultret(e.k)) { |
| 1506 | luaK_setmultret(fs, &e); |
| 1507 | if (e.k == VCALL && nret == 1) { /* tail call? */ |
| 1508 | SET_OPCODE(getcode(fs,&e), OP_TAILCALL); |
| 1509 | lua_assert(GETARG_A(getcode(fs,&e)) == fs->nactvar); |
| 1510 | } |
| 1511 | first = fs->nactvar; |
| 1512 | nret = LUA_MULTRET; /* return all values */ |
| 1513 | } |
| 1514 | else { |
| 1515 | if (nret == 1) /* only one single value? */ |
| 1516 | first = luaK_exp2anyreg(fs, &e); |
| 1517 | else { |
| 1518 | luaK_exp2nextreg(fs, &e); /* values must go to the `stack' */ |
| 1519 | first = fs->nactvar; /* return all `active' values */ |
| 1520 | lua_assert(nret == fs->freereg - first); |
| 1521 | } |
| 1522 | } |
| 1523 | } |
| 1524 | luaK_ret(fs, first, nret); |
| 1525 | testnext(ls, ';'); /* skip optional semicolon */ |
| 1526 | 1526 | } |
| 1527 | 1527 | |
| 1528 | 1528 | |
| 1529 | 1529 | static void statement (LexState *ls) { |
| 1530 | | int line = ls->linenumber; /* may be needed for error messages */ |
| 1531 | | enterlevel(ls); |
| 1532 | | switch (ls->t.token) { |
| 1533 | | case ';': { /* stat -> ';' (empty statement) */ |
| 1534 | | luaX_next(ls); /* skip ';' */ |
| 1535 | | break; |
| 1536 | | } |
| 1537 | | case TK_IF: { /* stat -> ifstat */ |
| 1538 | | ifstat(ls, line); |
| 1539 | | break; |
| 1540 | | } |
| 1541 | | case TK_WHILE: { /* stat -> whilestat */ |
| 1542 | | whilestat(ls, line); |
| 1543 | | break; |
| 1544 | | } |
| 1545 | | case TK_DO: { /* stat -> DO block END */ |
| 1546 | | luaX_next(ls); /* skip DO */ |
| 1547 | | block(ls); |
| 1548 | | check_match(ls, TK_END, TK_DO, line); |
| 1549 | | break; |
| 1550 | | } |
| 1551 | | case TK_FOR: { /* stat -> forstat */ |
| 1552 | | forstat(ls, line); |
| 1553 | | break; |
| 1554 | | } |
| 1555 | | case TK_REPEAT: { /* stat -> repeatstat */ |
| 1556 | | repeatstat(ls, line); |
| 1557 | | break; |
| 1558 | | } |
| 1559 | | case TK_FUNCTION: { /* stat -> funcstat */ |
| 1560 | | funcstat(ls, line); |
| 1561 | | break; |
| 1562 | | } |
| 1563 | | case TK_LOCAL: { /* stat -> localstat */ |
| 1564 | | luaX_next(ls); /* skip LOCAL */ |
| 1565 | | if (testnext(ls, TK_FUNCTION)) /* local function? */ |
| 1566 | | localfunc(ls); |
| 1567 | | else |
| 1568 | | localstat(ls); |
| 1569 | | break; |
| 1570 | | } |
| 1571 | | case TK_DBCOLON: { /* stat -> label */ |
| 1572 | | luaX_next(ls); /* skip double colon */ |
| 1573 | | labelstat(ls, str_checkname(ls), line); |
| 1574 | | break; |
| 1575 | | } |
| 1576 | | case TK_RETURN: { /* stat -> retstat */ |
| 1577 | | luaX_next(ls); /* skip RETURN */ |
| 1578 | | retstat(ls); |
| 1579 | | break; |
| 1580 | | } |
| 1581 | | case TK_BREAK: /* stat -> breakstat */ |
| 1582 | | case TK_GOTO: { /* stat -> 'goto' NAME */ |
| 1583 | | gotostat(ls, luaK_jump(ls->fs)); |
| 1584 | | break; |
| 1585 | | } |
| 1586 | | default: { /* stat -> func | assignment */ |
| 1587 | | exprstat(ls); |
| 1588 | | break; |
| 1589 | | } |
| 1590 | | } |
| 1591 | | lua_assert(ls->fs->f->maxstacksize >= ls->fs->freereg && |
| 1592 | | ls->fs->freereg >= ls->fs->nactvar); |
| 1593 | | ls->fs->freereg = ls->fs->nactvar; /* free registers */ |
| 1594 | | leavelevel(ls); |
| 1530 | int line = ls->linenumber; /* may be needed for error messages */ |
| 1531 | enterlevel(ls); |
| 1532 | switch (ls->t.token) { |
| 1533 | case ';': { /* stat -> ';' (empty statement) */ |
| 1534 | luaX_next(ls); /* skip ';' */ |
| 1535 | break; |
| 1536 | } |
| 1537 | case TK_IF: { /* stat -> ifstat */ |
| 1538 | ifstat(ls, line); |
| 1539 | break; |
| 1540 | } |
| 1541 | case TK_WHILE: { /* stat -> whilestat */ |
| 1542 | whilestat(ls, line); |
| 1543 | break; |
| 1544 | } |
| 1545 | case TK_DO: { /* stat -> DO block END */ |
| 1546 | luaX_next(ls); /* skip DO */ |
| 1547 | block(ls); |
| 1548 | check_match(ls, TK_END, TK_DO, line); |
| 1549 | break; |
| 1550 | } |
| 1551 | case TK_FOR: { /* stat -> forstat */ |
| 1552 | forstat(ls, line); |
| 1553 | break; |
| 1554 | } |
| 1555 | case TK_REPEAT: { /* stat -> repeatstat */ |
| 1556 | repeatstat(ls, line); |
| 1557 | break; |
| 1558 | } |
| 1559 | case TK_FUNCTION: { /* stat -> funcstat */ |
| 1560 | funcstat(ls, line); |
| 1561 | break; |
| 1562 | } |
| 1563 | case TK_LOCAL: { /* stat -> localstat */ |
| 1564 | luaX_next(ls); /* skip LOCAL */ |
| 1565 | if (testnext(ls, TK_FUNCTION)) /* local function? */ |
| 1566 | localfunc(ls); |
| 1567 | else |
| 1568 | localstat(ls); |
| 1569 | break; |
| 1570 | } |
| 1571 | case TK_DBCOLON: { /* stat -> label */ |
| 1572 | luaX_next(ls); /* skip double colon */ |
| 1573 | labelstat(ls, str_checkname(ls), line); |
| 1574 | break; |
| 1575 | } |
| 1576 | case TK_RETURN: { /* stat -> retstat */ |
| 1577 | luaX_next(ls); /* skip RETURN */ |
| 1578 | retstat(ls); |
| 1579 | break; |
| 1580 | } |
| 1581 | case TK_BREAK: /* stat -> breakstat */ |
| 1582 | case TK_GOTO: { /* stat -> 'goto' NAME */ |
| 1583 | gotostat(ls, luaK_jump(ls->fs)); |
| 1584 | break; |
| 1585 | } |
| 1586 | default: { /* stat -> func | assignment */ |
| 1587 | exprstat(ls); |
| 1588 | break; |
| 1589 | } |
| 1590 | } |
| 1591 | lua_assert(ls->fs->f->maxstacksize >= ls->fs->freereg && |
| 1592 | ls->fs->freereg >= ls->fs->nactvar); |
| 1593 | ls->fs->freereg = ls->fs->nactvar; /* free registers */ |
| 1594 | leavelevel(ls); |
| 1595 | 1595 | } |
| 1596 | 1596 | |
| 1597 | 1597 | /* }====================================================================== */ |
| r30857 | r30858 | |
| 1602 | 1602 | ** upvalue named LUA_ENV |
| 1603 | 1603 | */ |
| 1604 | 1604 | static void mainfunc (LexState *ls, FuncState *fs) { |
| 1605 | | BlockCnt bl; |
| 1606 | | expdesc v; |
| 1607 | | open_func(ls, fs, &bl); |
| 1608 | | fs->f->is_vararg = 1; /* main function is always vararg */ |
| 1609 | | init_exp(&v, VLOCAL, 0); /* create and... */ |
| 1610 | | newupvalue(fs, ls->envn, &v); /* ...set environment upvalue */ |
| 1611 | | luaX_next(ls); /* read first token */ |
| 1612 | | statlist(ls); /* parse main body */ |
| 1613 | | check(ls, TK_EOS); |
| 1614 | | close_func(ls); |
| 1605 | BlockCnt bl; |
| 1606 | expdesc v; |
| 1607 | open_func(ls, fs, &bl); |
| 1608 | fs->f->is_vararg = 1; /* main function is always vararg */ |
| 1609 | init_exp(&v, VLOCAL, 0); /* create and... */ |
| 1610 | newupvalue(fs, ls->envn, &v); /* ...set environment upvalue */ |
| 1611 | luaX_next(ls); /* read first token */ |
| 1612 | statlist(ls); /* parse main body */ |
| 1613 | check(ls, TK_EOS); |
| 1614 | close_func(ls); |
| 1615 | 1615 | } |
| 1616 | 1616 | |
| 1617 | 1617 | |
| 1618 | 1618 | Closure *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff, |
| 1619 | | Dyndata *dyd, const char *name, int firstchar) { |
| 1620 | | LexState lexstate; |
| 1621 | | FuncState funcstate; |
| 1622 | | Closure *cl = luaF_newLclosure(L, 1); /* create main closure */ |
| 1623 | | /* anchor closure (to avoid being collected) */ |
| 1624 | | setclLvalue(L, L->top, cl); |
| 1625 | | incr_top(L); |
| 1626 | | funcstate.f = cl->l.p = luaF_newproto(L); |
| 1627 | | funcstate.f->source = luaS_new(L, name); /* create and anchor TString */ |
| 1628 | | lexstate.buff = buff; |
| 1629 | | lexstate.dyd = dyd; |
| 1630 | | dyd->actvar.n = dyd->gt.n = dyd->label.n = 0; |
| 1631 | | luaX_setinput(L, &lexstate, z, funcstate.f->source, firstchar); |
| 1632 | | mainfunc(&lexstate, &funcstate); |
| 1633 | | lua_assert(!funcstate.prev && funcstate.nups == 1 && !lexstate.fs); |
| 1634 | | /* all scopes should be correctly finished */ |
| 1635 | | lua_assert(dyd->actvar.n == 0 && dyd->gt.n == 0 && dyd->label.n == 0); |
| 1636 | | return cl; /* it's on the stack too */ |
| 1619 | Dyndata *dyd, const char *name, int firstchar) { |
| 1620 | LexState lexstate; |
| 1621 | FuncState funcstate; |
| 1622 | Closure *cl = luaF_newLclosure(L, 1); /* create main closure */ |
| 1623 | /* anchor closure (to avoid being collected) */ |
| 1624 | setclLvalue(L, L->top, cl); |
| 1625 | incr_top(L); |
| 1626 | funcstate.f = cl->l.p = luaF_newproto(L); |
| 1627 | funcstate.f->source = luaS_new(L, name); /* create and anchor TString */ |
| 1628 | lexstate.buff = buff; |
| 1629 | lexstate.dyd = dyd; |
| 1630 | dyd->actvar.n = dyd->gt.n = dyd->label.n = 0; |
| 1631 | luaX_setinput(L, &lexstate, z, funcstate.f->source, firstchar); |
| 1632 | mainfunc(&lexstate, &funcstate); |
| 1633 | lua_assert(!funcstate.prev && funcstate.nups == 1 && !lexstate.fs); |
| 1634 | /* all scopes should be correctly finished */ |
| 1635 | lua_assert(dyd->actvar.n == 0 && dyd->gt.n == 0 && dyd->label.n == 0); |
| 1636 | return cl; /* it's on the stack too */ |
| 1637 | 1637 | } |
| 1638 | |
trunk/src/lib/lua/lbaselib.c
| r30857 | r30858 | |
| 1 | 1 | /* |
| 2 | | ** $Id: lbaselib.c,v 1.276 2013/02/21 13:44:53 roberto Exp $ |
| 2 | ** $Id: lbaselib.c,v 1.276.1.1 2013/04/12 18:48:47 roberto Exp $ |
| 3 | 3 | ** Basic library |
| 4 | 4 | ** See Copyright Notice in lua.h |
| 5 | 5 | */ |
| r30857 | r30858 | |
| 21 | 21 | |
| 22 | 22 | |
| 23 | 23 | static int luaB_print (lua_State *L) { |
| 24 | | int n = lua_gettop(L); /* number of arguments */ |
| 25 | | int i; |
| 26 | | lua_getglobal(L, "tostring"); |
| 27 | | for (i=1; i<=n; i++) { |
| 28 | | const char *s; |
| 29 | | size_t l; |
| 30 | | lua_pushvalue(L, -1); /* function to be called */ |
| 31 | | lua_pushvalue(L, i); /* value to print */ |
| 32 | | lua_call(L, 1, 1); |
| 33 | | s = lua_tolstring(L, -1, &l); /* get result */ |
| 34 | | if (s == NULL) |
| 35 | | return luaL_error(L, |
| 36 | | LUA_QL("tostring") " must return a string to " LUA_QL("print")); |
| 37 | | if (i>1) luai_writestring("\t", 1); |
| 38 | | luai_writestring(s, l); |
| 39 | | lua_pop(L, 1); /* pop result */ |
| 40 | | } |
| 41 | | luai_writeline(); |
| 42 | | return 0; |
| 24 | int n = lua_gettop(L); /* number of arguments */ |
| 25 | int i; |
| 26 | lua_getglobal(L, "tostring"); |
| 27 | for (i=1; i<=n; i++) { |
| 28 | const char *s; |
| 29 | size_t l; |
| 30 | lua_pushvalue(L, -1); /* function to be called */ |
| 31 | lua_pushvalue(L, i); /* value to print */ |
| 32 | lua_call(L, 1, 1); |
| 33 | s = lua_tolstring(L, -1, &l); /* get result */ |
| 34 | if (s == NULL) |
| 35 | return luaL_error(L, |
| 36 | LUA_QL("tostring") " must return a string to " LUA_QL("print")); |
| 37 | if (i>1) luai_writestring("\t", 1); |
| 38 | luai_writestring(s, l); |
| 39 | lua_pop(L, 1); /* pop result */ |
| 40 | } |
| 41 | luai_writeline(); |
| 42 | return 0; |
| 43 | 43 | } |
| 44 | 44 | |
| 45 | 45 | |
| 46 | | #define SPACECHARS " \f\n\r\t\v" |
| 46 | #define SPACECHARS " \f\n\r\t\v" |
| 47 | 47 | |
| 48 | 48 | static int luaB_tonumber (lua_State *L) { |
| 49 | | if (lua_isnoneornil(L, 2)) { /* standard conversion */ |
| 50 | | int isnum; |
| 51 | | lua_Number n = lua_tonumberx(L, 1, &isnum); |
| 52 | | if (isnum) { |
| 53 | | lua_pushnumber(L, n); |
| 54 | | return 1; |
| 55 | | } /* else not a number; must be something */ |
| 56 | | luaL_checkany(L, 1); |
| 57 | | } |
| 58 | | else { |
| 59 | | size_t l; |
| 60 | | const char *s = luaL_checklstring(L, 1, &l); |
| 61 | | const char *e = s + l; /* end point for 's' */ |
| 62 | | int base = luaL_checkint(L, 2); |
| 63 | | int neg = 0; |
| 64 | | luaL_argcheck(L, 2 <= base && base <= 36, 2, "base out of range"); |
| 65 | | s += strspn(s, SPACECHARS); /* skip initial spaces */ |
| 66 | | if (*s == '-') { s++; neg = 1; } /* handle signal */ |
| 67 | | else if (*s == '+') s++; |
| 68 | | if (isalnum((unsigned char)*s)) { |
| 69 | | lua_Number n = 0; |
| 70 | | do { |
| 71 | | int digit = (isdigit((unsigned char)*s)) ? *s - '0' |
| 72 | | : toupper((unsigned char)*s) - 'A' + 10; |
| 73 | | if (digit >= base) break; /* invalid numeral; force a fail */ |
| 74 | | n = n * (lua_Number)base + (lua_Number)digit; |
| 75 | | s++; |
| 76 | | } while (isalnum((unsigned char)*s)); |
| 77 | | s += strspn(s, SPACECHARS); /* skip trailing spaces */ |
| 78 | | if (s == e) { /* no invalid trailing characters? */ |
| 79 | | lua_pushnumber(L, (neg) ? -n : n); |
| 80 | | return 1; |
| 81 | | } /* else not a number */ |
| 82 | | } /* else not a number */ |
| 83 | | } |
| 84 | | lua_pushnil(L); /* not a number */ |
| 85 | | return 1; |
| 49 | if (lua_isnoneornil(L, 2)) { /* standard conversion */ |
| 50 | int isnum; |
| 51 | lua_Number n = lua_tonumberx(L, 1, &isnum); |
| 52 | if (isnum) { |
| 53 | lua_pushnumber(L, n); |
| 54 | return 1; |
| 55 | } /* else not a number; must be something */ |
| 56 | luaL_checkany(L, 1); |
| 57 | } |
| 58 | else { |
| 59 | size_t l; |
| 60 | const char *s = luaL_checklstring(L, 1, &l); |
| 61 | const char *e = s + l; /* end point for 's' */ |
| 62 | int base = luaL_checkint(L, 2); |
| 63 | int neg = 0; |
| 64 | luaL_argcheck(L, 2 <= base && base <= 36, 2, "base out of range"); |
| 65 | s += strspn(s, SPACECHARS); /* skip initial spaces */ |
| 66 | if (*s == '-') { s++; neg = 1; } /* handle signal */ |
| 67 | else if (*s == '+') s++; |
| 68 | if (isalnum((unsigned char)*s)) { |
| 69 | lua_Number n = 0; |
| 70 | do { |
| 71 | int digit = (isdigit((unsigned char)*s)) ? *s - '0' |
| 72 | : toupper((unsigned char)*s) - 'A' + 10; |
| 73 | if (digit >= base) break; /* invalid numeral; force a fail */ |
| 74 | n = n * (lua_Number)base + (lua_Number)digit; |
| 75 | s++; |
| 76 | } while (isalnum((unsigned char)*s)); |
| 77 | s += strspn(s, SPACECHARS); /* skip trailing spaces */ |
| 78 | if (s == e) { /* no invalid trailing characters? */ |
| 79 | lua_pushnumber(L, (neg) ? -n : n); |
| 80 | return 1; |
| 81 | } /* else not a number */ |
| 82 | } /* else not a number */ |
| 83 | } |
| 84 | lua_pushnil(L); /* not a number */ |
| 85 | return 1; |
| 86 | 86 | } |
| 87 | 87 | |
| 88 | 88 | |
| 89 | 89 | static int luaB_error (lua_State *L) { |
| 90 | | int level = luaL_optint(L, 2, 1); |
| 91 | | lua_settop(L, 1); |
| 92 | | if (lua_isstring(L, 1) && level > 0) { /* add extra information? */ |
| 93 | | luaL_where(L, level); |
| 94 | | lua_pushvalue(L, 1); |
| 95 | | lua_concat(L, 2); |
| 96 | | } |
| 97 | | return lua_error(L); |
| 90 | int level = luaL_optint(L, 2, 1); |
| 91 | lua_settop(L, 1); |
| 92 | if (lua_isstring(L, 1) && level > 0) { /* add extra information? */ |
| 93 | luaL_where(L, level); |
| 94 | lua_pushvalue(L, 1); |
| 95 | lua_concat(L, 2); |
| 96 | } |
| 97 | return lua_error(L); |
| 98 | 98 | } |
| 99 | 99 | |
| 100 | 100 | |
| 101 | 101 | static int luaB_getmetatable (lua_State *L) { |
| 102 | | luaL_checkany(L, 1); |
| 103 | | if (!lua_getmetatable(L, 1)) { |
| 104 | | lua_pushnil(L); |
| 105 | | return 1; /* no metatable */ |
| 106 | | } |
| 107 | | luaL_getmetafield(L, 1, "__metatable"); |
| 108 | | return 1; /* returns either __metatable field (if present) or metatable */ |
| 102 | luaL_checkany(L, 1); |
| 103 | if (!lua_getmetatable(L, 1)) { |
| 104 | lua_pushnil(L); |
| 105 | return 1; /* no metatable */ |
| 106 | } |
| 107 | luaL_getmetafield(L, 1, "__metatable"); |
| 108 | return 1; /* returns either __metatable field (if present) or metatable */ |
| 109 | 109 | } |
| 110 | 110 | |
| 111 | 111 | |
| 112 | 112 | static int luaB_setmetatable (lua_State *L) { |
| 113 | | int t = lua_type(L, 2); |
| 114 | | luaL_checktype(L, 1, LUA_TTABLE); |
| 115 | | luaL_argcheck(L, t == LUA_TNIL || t == LUA_TTABLE, 2, |
| 116 | | "nil or table expected"); |
| 117 | | if (luaL_getmetafield(L, 1, "__metatable")) |
| 118 | | return luaL_error(L, "cannot change a protected metatable"); |
| 119 | | lua_settop(L, 2); |
| 120 | | lua_setmetatable(L, 1); |
| 121 | | return 1; |
| 113 | int t = lua_type(L, 2); |
| 114 | luaL_checktype(L, 1, LUA_TTABLE); |
| 115 | luaL_argcheck(L, t == LUA_TNIL || t == LUA_TTABLE, 2, |
| 116 | "nil or table expected"); |
| 117 | if (luaL_getmetafield(L, 1, "__metatable")) |
| 118 | return luaL_error(L, "cannot change a protected metatable"); |
| 119 | lua_settop(L, 2); |
| 120 | lua_setmetatable(L, 1); |
| 121 | return 1; |
| 122 | 122 | } |
| 123 | 123 | |
| 124 | 124 | |
| 125 | 125 | static int luaB_rawequal (lua_State *L) { |
| 126 | | luaL_checkany(L, 1); |
| 127 | | luaL_checkany(L, 2); |
| 128 | | lua_pushboolean(L, lua_rawequal(L, 1, 2)); |
| 129 | | return 1; |
| 126 | luaL_checkany(L, 1); |
| 127 | luaL_checkany(L, 2); |
| 128 | lua_pushboolean(L, lua_rawequal(L, 1, 2)); |
| 129 | return 1; |
| 130 | 130 | } |
| 131 | 131 | |
| 132 | 132 | |
| 133 | 133 | static int luaB_rawlen (lua_State *L) { |
| 134 | | int t = lua_type(L, 1); |
| 135 | | luaL_argcheck(L, t == LUA_TTABLE || t == LUA_TSTRING, 1, |
| 136 | | "table or string expected"); |
| 137 | | lua_pushinteger(L, lua_rawlen(L, 1)); |
| 138 | | return 1; |
| 134 | int t = lua_type(L, 1); |
| 135 | luaL_argcheck(L, t == LUA_TTABLE || t == LUA_TSTRING, 1, |
| 136 | "table or string expected"); |
| 137 | lua_pushinteger(L, lua_rawlen(L, 1)); |
| 138 | return 1; |
| 139 | 139 | } |
| 140 | 140 | |
| 141 | 141 | |
| 142 | 142 | static int luaB_rawget (lua_State *L) { |
| 143 | | luaL_checktype(L, 1, LUA_TTABLE); |
| 144 | | luaL_checkany(L, 2); |
| 145 | | lua_settop(L, 2); |
| 146 | | lua_rawget(L, 1); |
| 147 | | return 1; |
| 143 | luaL_checktype(L, 1, LUA_TTABLE); |
| 144 | luaL_checkany(L, 2); |
| 145 | lua_settop(L, 2); |
| 146 | lua_rawget(L, 1); |
| 147 | return 1; |
| 148 | 148 | } |
| 149 | 149 | |
| 150 | 150 | static int luaB_rawset (lua_State *L) { |
| 151 | | luaL_checktype(L, 1, LUA_TTABLE); |
| 152 | | luaL_checkany(L, 2); |
| 153 | | luaL_checkany(L, 3); |
| 154 | | lua_settop(L, 3); |
| 155 | | lua_rawset(L, 1); |
| 156 | | return 1; |
| 151 | luaL_checktype(L, 1, LUA_TTABLE); |
| 152 | luaL_checkany(L, 2); |
| 153 | luaL_checkany(L, 3); |
| 154 | lua_settop(L, 3); |
| 155 | lua_rawset(L, 1); |
| 156 | return 1; |
| 157 | 157 | } |
| 158 | 158 | |
| 159 | 159 | |
| 160 | 160 | static int luaB_collectgarbage (lua_State *L) { |
| 161 | | static const char *const opts[] = {"stop", "restart", "collect", |
| 162 | | "count", "step", "setpause", "setstepmul", |
| 163 | | "setmajorinc", "isrunning", "generational", "incremental", NULL}; |
| 164 | | static const int optsnum[] = {LUA_GCSTOP, LUA_GCRESTART, LUA_GCCOLLECT, |
| 165 | | LUA_GCCOUNT, LUA_GCSTEP, LUA_GCSETPAUSE, LUA_GCSETSTEPMUL, |
| 166 | | LUA_GCSETMAJORINC, LUA_GCISRUNNING, LUA_GCGEN, LUA_GCINC}; |
| 167 | | int o = optsnum[luaL_checkoption(L, 1, "collect", opts)]; |
| 168 | | int ex = luaL_optint(L, 2, 0); |
| 169 | | int res = lua_gc(L, o, ex); |
| 170 | | switch (o) { |
| 171 | | case LUA_GCCOUNT: { |
| 172 | | int b = lua_gc(L, LUA_GCCOUNTB, 0); |
| 173 | | lua_pushnumber(L, res + ((lua_Number)b/1024)); |
| 174 | | lua_pushinteger(L, b); |
| 175 | | return 2; |
| 176 | | } |
| 177 | | case LUA_GCSTEP: case LUA_GCISRUNNING: { |
| 178 | | lua_pushboolean(L, res); |
| 179 | | return 1; |
| 180 | | } |
| 181 | | default: { |
| 182 | | lua_pushinteger(L, res); |
| 183 | | return 1; |
| 184 | | } |
| 185 | | } |
| 161 | static const char *const opts[] = {"stop", "restart", "collect", |
| 162 | "count", "step", "setpause", "setstepmul", |
| 163 | "setmajorinc", "isrunning", "generational", "incremental", NULL}; |
| 164 | static const int optsnum[] = {LUA_GCSTOP, LUA_GCRESTART, LUA_GCCOLLECT, |
| 165 | LUA_GCCOUNT, LUA_GCSTEP, LUA_GCSETPAUSE, LUA_GCSETSTEPMUL, |
| 166 | LUA_GCSETMAJORINC, LUA_GCISRUNNING, LUA_GCGEN, LUA_GCINC}; |
| 167 | int o = optsnum[luaL_checkoption(L, 1, "collect", opts)]; |
| 168 | int ex = luaL_optint(L, 2, 0); |
| 169 | int res = lua_gc(L, o, ex); |
| 170 | switch (o) { |
| 171 | case LUA_GCCOUNT: { |
| 172 | int b = lua_gc(L, LUA_GCCOUNTB, 0); |
| 173 | lua_pushnumber(L, res + ((lua_Number)b/1024)); |
| 174 | lua_pushinteger(L, b); |
| 175 | return 2; |
| 176 | } |
| 177 | case LUA_GCSTEP: case LUA_GCISRUNNING: { |
| 178 | lua_pushboolean(L, res); |
| 179 | return 1; |
| 180 | } |
| 181 | default: { |
| 182 | lua_pushinteger(L, res); |
| 183 | return 1; |
| 184 | } |
| 185 | } |
| 186 | 186 | } |
| 187 | 187 | |
| 188 | 188 | |
| 189 | 189 | static int luaB_type (lua_State *L) { |
| 190 | | luaL_checkany(L, 1); |
| 191 | | lua_pushstring(L, luaL_typename(L, 1)); |
| 192 | | return 1; |
| 190 | luaL_checkany(L, 1); |
| 191 | lua_pushstring(L, luaL_typename(L, 1)); |
| 192 | return 1; |
| 193 | 193 | } |
| 194 | 194 | |
| 195 | 195 | |
| 196 | 196 | static int pairsmeta (lua_State *L, const char *method, int iszero, |
| 197 | | lua_CFunction iter) { |
| 198 | | if (!luaL_getmetafield(L, 1, method)) { /* no metamethod? */ |
| 199 | | luaL_checktype(L, 1, LUA_TTABLE); /* argument must be a table */ |
| 200 | | lua_pushcfunction(L, iter); /* will return generator, */ |
| 201 | | lua_pushvalue(L, 1); /* state, */ |
| 202 | | if (iszero) lua_pushinteger(L, 0); /* and initial value */ |
| 203 | | else lua_pushnil(L); |
| 204 | | } |
| 205 | | else { |
| 206 | | lua_pushvalue(L, 1); /* argument 'self' to metamethod */ |
| 207 | | lua_call(L, 1, 3); /* get 3 values from metamethod */ |
| 208 | | } |
| 209 | | return 3; |
| 197 | lua_CFunction iter) { |
| 198 | if (!luaL_getmetafield(L, 1, method)) { /* no metamethod? */ |
| 199 | luaL_checktype(L, 1, LUA_TTABLE); /* argument must be a table */ |
| 200 | lua_pushcfunction(L, iter); /* will return generator, */ |
| 201 | lua_pushvalue(L, 1); /* state, */ |
| 202 | if (iszero) lua_pushinteger(L, 0); /* and initial value */ |
| 203 | else lua_pushnil(L); |
| 204 | } |
| 205 | else { |
| 206 | lua_pushvalue(L, 1); /* argument 'self' to metamethod */ |
| 207 | lua_call(L, 1, 3); /* get 3 values from metamethod */ |
| 208 | } |
| 209 | return 3; |
| 210 | 210 | } |
| 211 | 211 | |
| 212 | 212 | |
| 213 | 213 | static int luaB_next (lua_State *L) { |
| 214 | | luaL_checktype(L, 1, LUA_TTABLE); |
| 215 | | lua_settop(L, 2); /* create a 2nd argument if there isn't one */ |
| 216 | | if (lua_next(L, 1)) |
| 217 | | return 2; |
| 218 | | else { |
| 219 | | lua_pushnil(L); |
| 220 | | return 1; |
| 221 | | } |
| 214 | luaL_checktype(L, 1, LUA_TTABLE); |
| 215 | lua_settop(L, 2); /* create a 2nd argument if there isn't one */ |
| 216 | if (lua_next(L, 1)) |
| 217 | return 2; |
| 218 | else { |
| 219 | lua_pushnil(L); |
| 220 | return 1; |
| 221 | } |
| 222 | 222 | } |
| 223 | 223 | |
| 224 | 224 | |
| 225 | 225 | static int luaB_pairs (lua_State *L) { |
| 226 | | return pairsmeta(L, "__pairs", 0, luaB_next); |
| 226 | return pairsmeta(L, "__pairs", 0, luaB_next); |
| 227 | 227 | } |
| 228 | 228 | |
| 229 | 229 | |
| 230 | 230 | static int ipairsaux (lua_State *L) { |
| 231 | | int i = luaL_checkint(L, 2); |
| 232 | | luaL_checktype(L, 1, LUA_TTABLE); |
| 233 | | i++; /* next value */ |
| 234 | | lua_pushinteger(L, i); |
| 235 | | lua_rawgeti(L, 1, i); |
| 236 | | return (lua_isnil(L, -1)) ? 1 : 2; |
| 231 | int i = luaL_checkint(L, 2); |
| 232 | luaL_checktype(L, 1, LUA_TTABLE); |
| 233 | i++; /* next value */ |
| 234 | lua_pushinteger(L, i); |
| 235 | lua_rawgeti(L, 1, i); |
| 236 | return (lua_isnil(L, -1)) ? 1 : 2; |
| 237 | 237 | } |
| 238 | 238 | |
| 239 | 239 | |
| 240 | 240 | static int luaB_ipairs (lua_State *L) { |
| 241 | | return pairsmeta(L, "__ipairs", 1, ipairsaux); |
| 241 | return pairsmeta(L, "__ipairs", 1, ipairsaux); |
| 242 | 242 | } |
| 243 | 243 | |
| 244 | 244 | |
| 245 | 245 | static int load_aux (lua_State *L, int status, int envidx) { |
| 246 | | if (status == LUA_OK) { |
| 247 | | if (envidx != 0) { /* 'env' parameter? */ |
| 248 | | lua_pushvalue(L, envidx); /* environment for loaded function */ |
| 249 | | if (!lua_setupvalue(L, -2, 1)) /* set it as 1st upvalue */ |
| 250 | | lua_pop(L, 1); /* remove 'env' if not used by previous call */ |
| 251 | | } |
| 252 | | return 1; |
| 253 | | } |
| 254 | | else { /* error (message is on top of the stack) */ |
| 255 | | lua_pushnil(L); |
| 256 | | lua_insert(L, -2); /* put before error message */ |
| 257 | | return 2; /* return nil plus error message */ |
| 258 | | } |
| 246 | if (status == LUA_OK) { |
| 247 | if (envidx != 0) { /* 'env' parameter? */ |
| 248 | lua_pushvalue(L, envidx); /* environment for loaded function */ |
| 249 | if (!lua_setupvalue(L, -2, 1)) /* set it as 1st upvalue */ |
| 250 | lua_pop(L, 1); /* remove 'env' if not used by previous call */ |
| 251 | } |
| 252 | return 1; |
| 253 | } |
| 254 | else { /* error (message is on top of the stack) */ |
| 255 | lua_pushnil(L); |
| 256 | lua_insert(L, -2); /* put before error message */ |
| 257 | return 2; /* return nil plus error message */ |
| 258 | } |
| 259 | 259 | } |
| 260 | 260 | |
| 261 | 261 | |
| 262 | 262 | static int luaB_loadfile (lua_State *L) { |
| 263 | | const char *fname = luaL_optstring(L, 1, NULL); |
| 264 | | const char *mode = luaL_optstring(L, 2, NULL); |
| 265 | | int env = (!lua_isnone(L, 3) ? 3 : 0); /* 'env' index or 0 if no 'env' */ |
| 266 | | int status = luaL_loadfilex(L, fname, mode); |
| 267 | | return load_aux(L, status, env); |
| 263 | const char *fname = luaL_optstring(L, 1, NULL); |
| 264 | const char *mode = luaL_optstring(L, 2, NULL); |
| 265 | int env = (!lua_isnone(L, 3) ? 3 : 0); /* 'env' index or 0 if no 'env' */ |
| 266 | int status = luaL_loadfilex(L, fname, mode); |
| 267 | return load_aux(L, status, env); |
| 268 | 268 | } |
| 269 | 269 | |
| 270 | 270 | |
| r30857 | r30858 | |
| 280 | 280 | ** string to avoid it being collected while parsed. 'load' has four |
| 281 | 281 | ** optional arguments (chunk, source name, mode, and environment). |
| 282 | 282 | */ |
| 283 | | #define RESERVEDSLOT 5 |
| 283 | #define RESERVEDSLOT 5 |
| 284 | 284 | |
| 285 | 285 | |
| 286 | 286 | /* |
| r30857 | r30858 | |
| 290 | 290 | ** reserved slot inside the stack. |
| 291 | 291 | */ |
| 292 | 292 | static const char *generic_reader (lua_State *L, void *ud, size_t *size) { |
| 293 | | (void)(ud); /* not used */ |
| 294 | | luaL_checkstack(L, 2, "too many nested functions"); |
| 295 | | lua_pushvalue(L, 1); /* get function */ |
| 296 | | lua_call(L, 0, 1); /* call it */ |
| 297 | | if (lua_isnil(L, -1)) { |
| 298 | | lua_pop(L, 1); /* pop result */ |
| 299 | | *size = 0; |
| 300 | | return NULL; |
| 301 | | } |
| 302 | | else if (!lua_isstring(L, -1)) |
| 303 | | luaL_error(L, "reader function must return a string"); |
| 304 | | lua_replace(L, RESERVEDSLOT); /* save string in reserved slot */ |
| 305 | | return lua_tolstring(L, RESERVEDSLOT, size); |
| 293 | (void)(ud); /* not used */ |
| 294 | luaL_checkstack(L, 2, "too many nested functions"); |
| 295 | lua_pushvalue(L, 1); /* get function */ |
| 296 | lua_call(L, 0, 1); /* call it */ |
| 297 | if (lua_isnil(L, -1)) { |
| 298 | lua_pop(L, 1); /* pop result */ |
| 299 | *size = 0; |
| 300 | return NULL; |
| 301 | } |
| 302 | else if (!lua_isstring(L, -1)) |
| 303 | luaL_error(L, "reader function must return a string"); |
| 304 | lua_replace(L, RESERVEDSLOT); /* save string in reserved slot */ |
| 305 | return lua_tolstring(L, RESERVEDSLOT, size); |
| 306 | 306 | } |
| 307 | 307 | |
| 308 | 308 | |
| 309 | 309 | static int luaB_load (lua_State *L) { |
| 310 | | int status; |
| 311 | | size_t l; |
| 312 | | const char *s = lua_tolstring(L, 1, &l); |
| 313 | | const char *mode = luaL_optstring(L, 3, "bt"); |
| 314 | | int env = (!lua_isnone(L, 4) ? 4 : 0); /* 'env' index or 0 if no 'env' */ |
| 315 | | if (s != NULL) { /* loading a string? */ |
| 316 | | const char *chunkname = luaL_optstring(L, 2, s); |
| 317 | | status = luaL_loadbufferx(L, s, l, chunkname, mode); |
| 318 | | } |
| 319 | | else { /* loading from a reader function */ |
| 320 | | const char *chunkname = luaL_optstring(L, 2, "=(load)"); |
| 321 | | luaL_checktype(L, 1, LUA_TFUNCTION); |
| 322 | | lua_settop(L, RESERVEDSLOT); /* create reserved slot */ |
| 323 | | status = lua_load(L, generic_reader, NULL, chunkname, mode); |
| 324 | | } |
| 325 | | return load_aux(L, status, env); |
| 310 | int status; |
| 311 | size_t l; |
| 312 | const char *s = lua_tolstring(L, 1, &l); |
| 313 | const char *mode = luaL_optstring(L, 3, "bt"); |
| 314 | int env = (!lua_isnone(L, 4) ? 4 : 0); /* 'env' index or 0 if no 'env' */ |
| 315 | if (s != NULL) { /* loading a string? */ |
| 316 | const char *chunkname = luaL_optstring(L, 2, s); |
| 317 | status = luaL_loadbufferx(L, s, l, chunkname, mode); |
| 318 | } |
| 319 | else { /* loading from a reader function */ |
| 320 | const char *chunkname = luaL_optstring(L, 2, "=(load)"); |
| 321 | luaL_checktype(L, 1, LUA_TFUNCTION); |
| 322 | lua_settop(L, RESERVEDSLOT); /* create reserved slot */ |
| 323 | status = lua_load(L, generic_reader, NULL, chunkname, mode); |
| 324 | } |
| 325 | return load_aux(L, status, env); |
| 326 | 326 | } |
| 327 | 327 | |
| 328 | 328 | /* }====================================================== */ |
| 329 | 329 | |
| 330 | 330 | |
| 331 | 331 | static int dofilecont (lua_State *L) { |
| 332 | | return lua_gettop(L) - 1; |
| 332 | return lua_gettop(L) - 1; |
| 333 | 333 | } |
| 334 | 334 | |
| 335 | 335 | |
| 336 | 336 | static int luaB_dofile (lua_State *L) { |
| 337 | | const char *fname = luaL_optstring(L, 1, NULL); |
| 338 | | lua_settop(L, 1); |
| 339 | | if (luaL_loadfile(L, fname) != LUA_OK) |
| 340 | | return lua_error(L); |
| 341 | | lua_callk(L, 0, LUA_MULTRET, 0, dofilecont); |
| 342 | | return dofilecont(L); |
| 337 | const char *fname = luaL_optstring(L, 1, NULL); |
| 338 | lua_settop(L, 1); |
| 339 | if (luaL_loadfile(L, fname) != LUA_OK) |
| 340 | return lua_error(L); |
| 341 | lua_callk(L, 0, LUA_MULTRET, 0, dofilecont); |
| 342 | return dofilecont(L); |
| 343 | 343 | } |
| 344 | 344 | |
| 345 | 345 | |
| 346 | 346 | static int luaB_assert (lua_State *L) { |
| 347 | | if (!lua_toboolean(L, 1)) |
| 348 | | return luaL_error(L, "%s", luaL_optstring(L, 2, "assertion failed!")); |
| 349 | | return lua_gettop(L); |
| 347 | if (!lua_toboolean(L, 1)) |
| 348 | return luaL_error(L, "%s", luaL_optstring(L, 2, "assertion failed!")); |
| 349 | return lua_gettop(L); |
| 350 | 350 | } |
| 351 | 351 | |
| 352 | 352 | |
| 353 | 353 | static int luaB_select (lua_State *L) { |
| 354 | | int n = lua_gettop(L); |
| 355 | | if (lua_type(L, 1) == LUA_TSTRING && *lua_tostring(L, 1) == '#') { |
| 356 | | lua_pushinteger(L, n-1); |
| 357 | | return 1; |
| 358 | | } |
| 359 | | else { |
| 360 | | int i = luaL_checkint(L, 1); |
| 361 | | if (i < 0) i = n + i; |
| 362 | | else if (i > n) i = n; |
| 363 | | luaL_argcheck(L, 1 <= i, 1, "index out of range"); |
| 364 | | return n - i; |
| 365 | | } |
| 354 | int n = lua_gettop(L); |
| 355 | if (lua_type(L, 1) == LUA_TSTRING && *lua_tostring(L, 1) == '#') { |
| 356 | lua_pushinteger(L, n-1); |
| 357 | return 1; |
| 358 | } |
| 359 | else { |
| 360 | int i = luaL_checkint(L, 1); |
| 361 | if (i < 0) i = n + i; |
| 362 | else if (i > n) i = n; |
| 363 | luaL_argcheck(L, 1 <= i, 1, "index out of range"); |
| 364 | return n - i; |
| 365 | } |
| 366 | 366 | } |
| 367 | 367 | |
| 368 | 368 | |
| 369 | 369 | static int finishpcall (lua_State *L, int status) { |
| 370 | | if (!lua_checkstack(L, 1)) { /* no space for extra boolean? */ |
| 371 | | lua_settop(L, 0); /* create space for return values */ |
| 372 | | lua_pushboolean(L, 0); |
| 373 | | lua_pushstring(L, "stack overflow"); |
| 374 | | return 2; /* return false, msg */ |
| 375 | | } |
| 376 | | lua_pushboolean(L, status); /* first result (status) */ |
| 377 | | lua_replace(L, 1); /* put first result in first slot */ |
| 378 | | return lua_gettop(L); |
| 370 | if (!lua_checkstack(L, 1)) { /* no space for extra boolean? */ |
| 371 | lua_settop(L, 0); /* create space for return values */ |
| 372 | lua_pushboolean(L, 0); |
| 373 | lua_pushstring(L, "stack overflow"); |
| 374 | return 2; /* return false, msg */ |
| 375 | } |
| 376 | lua_pushboolean(L, status); /* first result (status) */ |
| 377 | lua_replace(L, 1); /* put first result in first slot */ |
| 378 | return lua_gettop(L); |
| 379 | 379 | } |
| 380 | 380 | |
| 381 | 381 | |
| 382 | 382 | static int pcallcont (lua_State *L) { |
| 383 | | int status = lua_getctx(L, NULL); |
| 384 | | return finishpcall(L, (status == LUA_YIELD)); |
| 383 | int status = lua_getctx(L, NULL); |
| 384 | return finishpcall(L, (status == LUA_YIELD)); |
| 385 | 385 | } |
| 386 | 386 | |
| 387 | 387 | |
| 388 | 388 | static int luaB_pcall (lua_State *L) { |
| 389 | | int status; |
| 390 | | luaL_checkany(L, 1); |
| 391 | | lua_pushnil(L); |
| 392 | | lua_insert(L, 1); /* create space for status result */ |
| 393 | | status = lua_pcallk(L, lua_gettop(L) - 2, LUA_MULTRET, 0, 0, pcallcont); |
| 394 | | return finishpcall(L, (status == LUA_OK)); |
| 389 | int status; |
| 390 | luaL_checkany(L, 1); |
| 391 | lua_pushnil(L); |
| 392 | lua_insert(L, 1); /* create space for status result */ |
| 393 | status = lua_pcallk(L, lua_gettop(L) - 2, LUA_MULTRET, 0, 0, pcallcont); |
| 394 | return finishpcall(L, (status == LUA_OK)); |
| 395 | 395 | } |
| 396 | 396 | |
| 397 | 397 | |
| 398 | 398 | static int luaB_xpcall (lua_State *L) { |
| 399 | | int status; |
| 400 | | int n = lua_gettop(L); |
| 401 | | luaL_argcheck(L, n >= 2, 2, "value expected"); |
| 402 | | lua_pushvalue(L, 1); /* exchange function... */ |
| 403 | | lua_copy(L, 2, 1); /* ...and error handler */ |
| 404 | | lua_replace(L, 2); |
| 405 | | status = lua_pcallk(L, n - 2, LUA_MULTRET, 1, 0, pcallcont); |
| 406 | | return finishpcall(L, (status == LUA_OK)); |
| 399 | int status; |
| 400 | int n = lua_gettop(L); |
| 401 | luaL_argcheck(L, n >= 2, 2, "value expected"); |
| 402 | lua_pushvalue(L, 1); /* exchange function... */ |
| 403 | lua_copy(L, 2, 1); /* ...and error handler */ |
| 404 | lua_replace(L, 2); |
| 405 | status = lua_pcallk(L, n - 2, LUA_MULTRET, 1, 0, pcallcont); |
| 406 | return finishpcall(L, (status == LUA_OK)); |
| 407 | 407 | } |
| 408 | 408 | |
| 409 | 409 | |
| 410 | 410 | static int luaB_tostring (lua_State *L) { |
| 411 | | luaL_checkany(L, 1); |
| 412 | | luaL_tolstring(L, 1, NULL); |
| 413 | | return 1; |
| 411 | luaL_checkany(L, 1); |
| 412 | luaL_tolstring(L, 1, NULL); |
| 413 | return 1; |
| 414 | 414 | } |
| 415 | 415 | |
| 416 | 416 | |
| 417 | 417 | static const luaL_Reg base_funcs[] = { |
| 418 | | {"assert", luaB_assert}, |
| 419 | | {"collectgarbage", luaB_collectgarbage}, |
| 420 | | {"dofile", luaB_dofile}, |
| 421 | | {"error", luaB_error}, |
| 422 | | {"getmetatable", luaB_getmetatable}, |
| 423 | | {"ipairs", luaB_ipairs}, |
| 424 | | {"loadfile", luaB_loadfile}, |
| 425 | | {"load", luaB_load}, |
| 418 | {"assert", luaB_assert}, |
| 419 | {"collectgarbage", luaB_collectgarbage}, |
| 420 | {"dofile", luaB_dofile}, |
| 421 | {"error", luaB_error}, |
| 422 | {"getmetatable", luaB_getmetatable}, |
| 423 | {"ipairs", luaB_ipairs}, |
| 424 | {"loadfile", luaB_loadfile}, |
| 425 | {"load", luaB_load}, |
| 426 | 426 | #if defined(LUA_COMPAT_LOADSTRING) |
| 427 | | {"loadstring", luaB_load}, |
| 427 | {"loadstring", luaB_load}, |
| 428 | 428 | #endif |
| 429 | | {"next", luaB_next}, |
| 430 | | {"pairs", luaB_pairs}, |
| 431 | | {"pcall", luaB_pcall}, |
| 432 | | {"print", luaB_print}, |
| 433 | | {"rawequal", luaB_rawequal}, |
| 434 | | {"rawlen", luaB_rawlen}, |
| 435 | | {"rawget", luaB_rawget}, |
| 436 | | {"rawset", luaB_rawset}, |
| 437 | | {"select", luaB_select}, |
| 438 | | {"setmetatable", luaB_setmetatable}, |
| 439 | | {"tonumber", luaB_tonumber}, |
| 440 | | {"tostring", luaB_tostring}, |
| 441 | | {"type", luaB_type}, |
| 442 | | {"xpcall", luaB_xpcall}, |
| 443 | | {NULL, NULL} |
| 429 | {"next", luaB_next}, |
| 430 | {"pairs", luaB_pairs}, |
| 431 | {"pcall", luaB_pcall}, |
| 432 | {"print", luaB_print}, |
| 433 | {"rawequal", luaB_rawequal}, |
| 434 | {"rawlen", luaB_rawlen}, |
| 435 | {"rawget", luaB_rawget}, |
| 436 | {"rawset", luaB_rawset}, |
| 437 | {"select", luaB_select}, |
| 438 | {"setmetatable", luaB_setmetatable}, |
| 439 | {"tonumber", luaB_tonumber}, |
| 440 | {"tostring", luaB_tostring}, |
| 441 | {"type", luaB_type}, |
| 442 | {"xpcall", luaB_xpcall}, |
| 443 | {NULL, NULL} |
| 444 | 444 | }; |
| 445 | 445 | |
| 446 | 446 | |
| 447 | 447 | LUAMOD_API int luaopen_base (lua_State *L) { |
| 448 | | /* set global _G */ |
| 449 | | lua_pushglobaltable(L); |
| 450 | | lua_pushglobaltable(L); |
| 451 | | lua_setfield(L, -2, "_G"); |
| 452 | | /* open lib into global table */ |
| 453 | | luaL_setfuncs(L, base_funcs, 0); |
| 454 | | lua_pushliteral(L, LUA_VERSION); |
| 455 | | lua_setfield(L, -2, "_VERSION"); /* set global _VERSION */ |
| 456 | | return 1; |
| 448 | /* set global _G */ |
| 449 | lua_pushglobaltable(L); |
| 450 | lua_pushglobaltable(L); |
| 451 | lua_setfield(L, -2, "_G"); |
| 452 | /* open lib into global table */ |
| 453 | luaL_setfuncs(L, base_funcs, 0); |
| 454 | lua_pushliteral(L, LUA_VERSION); |
| 455 | lua_setfield(L, -2, "_VERSION"); /* set global _VERSION */ |
| 456 | return 1; |
| 457 | 457 | } |
| 458 | |
trunk/src/lib/lua/lua.c
| r30857 | r30858 | |
| 1 | 1 | /* |
| 2 | | ** $Id: lua.c,v 1.206 2012/09/29 20:07:06 roberto Exp $ |
| 2 | ** $Id: lua.c,v 1.206.1.1 2013/04/12 18:48:47 roberto Exp $ |
| 3 | 3 | ** Lua stand-alone interpreter |
| 4 | 4 | ** See Copyright Notice in lua.h |
| 5 | 5 | */ |
| r30857 | r30858 | |
| 19 | 19 | |
| 20 | 20 | |
| 21 | 21 | #if !defined(LUA_PROMPT) |
| 22 | | #define LUA_PROMPT "> " |
| 23 | | #define LUA_PROMPT2 ">> " |
| 22 | #define LUA_PROMPT "> " |
| 23 | #define LUA_PROMPT2 ">> " |
| 24 | 24 | #endif |
| 25 | 25 | |
| 26 | 26 | #if !defined(LUA_PROGNAME) |
| 27 | | #define LUA_PROGNAME "lua" |
| 27 | #define LUA_PROGNAME "lua" |
| 28 | 28 | #endif |
| 29 | 29 | |
| 30 | 30 | #if !defined(LUA_MAXINPUT) |
| 31 | | #define LUA_MAXINPUT 512 |
| 31 | #define LUA_MAXINPUT 512 |
| 32 | 32 | #endif |
| 33 | 33 | |
| 34 | 34 | #if !defined(LUA_INIT) |
| 35 | | #define LUA_INIT "LUA_INIT" |
| 35 | #define LUA_INIT "LUA_INIT" |
| 36 | 36 | #endif |
| 37 | 37 | |
| 38 | 38 | #define LUA_INITVERSION \ |
| r30857 | r30858 | |
| 45 | 45 | */ |
| 46 | 46 | #if defined(LUA_USE_ISATTY) |
| 47 | 47 | #include <unistd.h> |
| 48 | | #define lua_stdin_is_tty() isatty(0) |
| 48 | #define lua_stdin_is_tty() isatty(0) |
| 49 | 49 | #elif defined(LUA_WIN) |
| 50 | 50 | #include <io.h> |
| 51 | 51 | #include <stdio.h> |
| 52 | | #define lua_stdin_is_tty() _isatty(_fileno(stdin)) |
| 52 | #define lua_stdin_is_tty() _isatty(_fileno(stdin)) |
| 53 | 53 | #else |
| 54 | | #define lua_stdin_is_tty() 1 /* assume stdin is a tty */ |
| 54 | #define lua_stdin_is_tty() 1 /* assume stdin is a tty */ |
| 55 | 55 | #endif |
| 56 | 56 | |
| 57 | 57 | |
| r30857 | r30858 | |
| 66 | 66 | #include <stdio.h> |
| 67 | 67 | #include <readline/readline.h> |
| 68 | 68 | #include <readline/history.h> |
| 69 | | #define lua_readline(L,b,p) ((void)L, ((b)=readline(p)) != NULL) |
| 69 | #define lua_readline(L,b,p) ((void)L, ((b)=readline(p)) != NULL) |
| 70 | 70 | #define lua_saveline(L,idx) \ |
| 71 | | if (lua_rawlen(L,idx) > 0) /* non-empty line? */ \ |
| 72 | | add_history(lua_tostring(L, idx)); /* add it to history */ |
| 73 | | #define lua_freeline(L,b) ((void)L, free(b)) |
| 71 | if (lua_rawlen(L,idx) > 0) /* non-empty line? */ \ |
| 72 | add_history(lua_tostring(L, idx)); /* add it to history */ |
| 73 | #define lua_freeline(L,b) ((void)L, free(b)) |
| 74 | 74 | |
| 75 | 75 | #elif !defined(lua_readline) |
| 76 | 76 | |
| 77 | 77 | #define lua_readline(L,b,p) \ |
| 78 | | ((void)L, fputs(p, stdout), fflush(stdout), /* show prompt */ \ |
| 79 | | fgets(b, LUA_MAXINPUT, stdin) != NULL) /* get line */ |
| 80 | | #define lua_saveline(L,idx) { (void)L; (void)idx; } |
| 81 | | #define lua_freeline(L,b) { (void)L; (void)b; } |
| 78 | ((void)L, fputs(p, stdout), fflush(stdout), /* show prompt */ \ |
| 79 | fgets(b, LUA_MAXINPUT, stdin) != NULL) /* get line */ |
| 80 | #define lua_saveline(L,idx) { (void)L; (void)idx; } |
| 81 | #define lua_freeline(L,b) { (void)L; (void)b; } |
| 82 | 82 | |
| 83 | 83 | #endif |
| 84 | 84 | |
| r30857 | r30858 | |
| 92 | 92 | |
| 93 | 93 | |
| 94 | 94 | static void lstop (lua_State *L, lua_Debug *ar) { |
| 95 | | (void)ar; /* unused arg. */ |
| 96 | | lua_sethook(L, NULL, 0, 0); |
| 97 | | luaL_error(L, "interrupted!"); |
| 95 | (void)ar; /* unused arg. */ |
| 96 | lua_sethook(L, NULL, 0, 0); |
| 97 | luaL_error(L, "interrupted!"); |
| 98 | 98 | } |
| 99 | 99 | |
| 100 | 100 | |
| 101 | 101 | static void laction (int i) { |
| 102 | | signal(i, SIG_DFL); /* if another SIGINT happens before lstop, |
| 102 | signal(i, SIG_DFL); /* if another SIGINT happens before lstop, |
| 103 | 103 | terminate process (default action) */ |
| 104 | | lua_sethook(globalL, lstop, LUA_MASKCALL | LUA_MASKRET | LUA_MASKCOUNT, 1); |
| 104 | lua_sethook(globalL, lstop, LUA_MASKCALL | LUA_MASKRET | LUA_MASKCOUNT, 1); |
| 105 | 105 | } |
| 106 | 106 | |
| 107 | 107 | |
| 108 | 108 | static void print_usage (const char *badoption) { |
| 109 | | luai_writestringerror("%s: ", progname); |
| 110 | | if (badoption[1] == 'e' || badoption[1] == 'l') |
| 111 | | luai_writestringerror("'%s' needs argument\n", badoption); |
| 112 | | else |
| 113 | | luai_writestringerror("unrecognized option '%s'\n", badoption); |
| 114 | | luai_writestringerror( |
| 115 | | "usage: %s [options] [script [args]]\n" |
| 116 | | "Available options are:\n" |
| 117 | | " -e stat execute string " LUA_QL("stat") "\n" |
| 118 | | " -i enter interactive mode after executing " LUA_QL("script") "\n" |
| 119 | | " -l name require library " LUA_QL("name") "\n" |
| 120 | | " -v show version information\n" |
| 121 | | " -E ignore environment variables\n" |
| 122 | | " -- stop handling options\n" |
| 123 | | " - stop handling options and execute stdin\n" |
| 124 | | , |
| 125 | | progname); |
| 109 | luai_writestringerror("%s: ", progname); |
| 110 | if (badoption[1] == 'e' || badoption[1] == 'l') |
| 111 | luai_writestringerror("'%s' needs argument\n", badoption); |
| 112 | else |
| 113 | luai_writestringerror("unrecognized option '%s'\n", badoption); |
| 114 | luai_writestringerror( |
| 115 | "usage: %s [options] [script [args]]\n" |
| 116 | "Available options are:\n" |
| 117 | " -e stat execute string " LUA_QL("stat") "\n" |
| 118 | " -i enter interactive mode after executing " LUA_QL("script") "\n" |
| 119 | " -l name require library " LUA_QL("name") "\n" |
| 120 | " -v show version information\n" |
| 121 | " -E ignore environment variables\n" |
| 122 | " -- stop handling options\n" |
| 123 | " - stop handling options and execute stdin\n" |
| 124 | , |
| 125 | progname); |
| 126 | 126 | } |
| 127 | 127 | |
| 128 | 128 | |
| 129 | 129 | static void l_message (const char *pname, const char *msg) { |
| 130 | | if (pname) luai_writestringerror("%s: ", pname); |
| 131 | | luai_writestringerror("%s\n", msg); |
| 130 | if (pname) luai_writestringerror("%s: ", pname); |
| 131 | luai_writestringerror("%s\n", msg); |
| 132 | 132 | } |
| 133 | 133 | |
| 134 | 134 | |
| 135 | 135 | static int report (lua_State *L, int status) { |
| 136 | | if (status != LUA_OK && !lua_isnil(L, -1)) { |
| 137 | | const char *msg = lua_tostring(L, -1); |
| 138 | | if (msg == NULL) msg = "(error object is not a string)"; |
| 139 | | l_message(progname, msg); |
| 140 | | lua_pop(L, 1); |
| 141 | | /* force a complete garbage collection in case of errors */ |
| 142 | | lua_gc(L, LUA_GCCOLLECT, 0); |
| 143 | | } |
| 144 | | return status; |
| 136 | if (status != LUA_OK && !lua_isnil(L, -1)) { |
| 137 | const char *msg = lua_tostring(L, -1); |
| 138 | if (msg == NULL) msg = "(error object is not a string)"; |
| 139 | l_message(progname, msg); |
| 140 | lua_pop(L, 1); |
| 141 | /* force a complete garbage collection in case of errors */ |
| 142 | lua_gc(L, LUA_GCCOLLECT, 0); |
| 143 | } |
| 144 | return status; |
| 145 | 145 | } |
| 146 | 146 | |
| 147 | 147 | |
| 148 | 148 | /* the next function is called unprotected, so it must avoid errors */ |
| 149 | 149 | static void finalreport (lua_State *L, int status) { |
| 150 | | if (status != LUA_OK) { |
| 151 | | const char *msg = (lua_type(L, -1) == LUA_TSTRING) ? lua_tostring(L, -1) |
| 152 | | : NULL; |
| 153 | | if (msg == NULL) msg = "(error object is not a string)"; |
| 154 | | l_message(progname, msg); |
| 155 | | lua_pop(L, 1); |
| 156 | | } |
| 150 | if (status != LUA_OK) { |
| 151 | const char *msg = (lua_type(L, -1) == LUA_TSTRING) ? lua_tostring(L, -1) |
| 152 | : NULL; |
| 153 | if (msg == NULL) msg = "(error object is not a string)"; |
| 154 | l_message(progname, msg); |
| 155 | lua_pop(L, 1); |
| 156 | } |
| 157 | 157 | } |
| 158 | 158 | |
| 159 | 159 | |
| 160 | 160 | static int traceback (lua_State *L) { |
| 161 | | const char *msg = lua_tostring(L, 1); |
| 162 | | if (msg) |
| 163 | | luaL_traceback(L, L, msg, 1); |
| 164 | | else if (!lua_isnoneornil(L, 1)) { /* is there an error object? */ |
| 165 | | if (!luaL_callmeta(L, 1, "__tostring")) /* try its 'tostring' metamethod */ |
| 166 | | lua_pushliteral(L, "(no error message)"); |
| 167 | | } |
| 168 | | return 1; |
| 161 | const char *msg = lua_tostring(L, 1); |
| 162 | if (msg) |
| 163 | luaL_traceback(L, L, msg, 1); |
| 164 | else if (!lua_isnoneornil(L, 1)) { /* is there an error object? */ |
| 165 | if (!luaL_callmeta(L, 1, "__tostring")) /* try its 'tostring' metamethod */ |
| 166 | lua_pushliteral(L, "(no error message)"); |
| 167 | } |
| 168 | return 1; |
| 169 | 169 | } |
| 170 | 170 | |
| 171 | 171 | |
| 172 | 172 | static int docall (lua_State *L, int narg, int nres) { |
| 173 | | int status; |
| 174 | | int base = lua_gettop(L) - narg; /* function index */ |
| 175 | | lua_pushcfunction(L, traceback); /* push traceback function */ |
| 176 | | lua_insert(L, base); /* put it under chunk and args */ |
| 177 | | globalL = L; /* to be available to 'laction' */ |
| 178 | | signal(SIGINT, laction); |
| 179 | | status = lua_pcall(L, narg, nres, base); |
| 180 | | signal(SIGINT, SIG_DFL); |
| 181 | | lua_remove(L, base); /* remove traceback function */ |
| 182 | | return status; |
| 173 | int status; |
| 174 | int base = lua_gettop(L) - narg; /* function index */ |
| 175 | lua_pushcfunction(L, traceback); /* push traceback function */ |
| 176 | lua_insert(L, base); /* put it under chunk and args */ |
| 177 | globalL = L; /* to be available to 'laction' */ |
| 178 | signal(SIGINT, laction); |
| 179 | status = lua_pcall(L, narg, nres, base); |
| 180 | signal(SIGINT, SIG_DFL); |
| 181 | lua_remove(L, base); /* remove traceback function */ |
| 182 | return status; |
| 183 | 183 | } |
| 184 | 184 | |
| 185 | 185 | |
| 186 | 186 | static void print_version (void) { |
| 187 | | luai_writestring(LUA_COPYRIGHT, strlen(LUA_COPYRIGHT)); |
| 188 | | luai_writeline(); |
| 187 | luai_writestring(LUA_COPYRIGHT, strlen(LUA_COPYRIGHT)); |
| 188 | luai_writeline(); |
| 189 | 189 | } |
| 190 | 190 | |
| 191 | 191 | |
| 192 | 192 | static int getargs (lua_State *L, char **argv, int n) { |
| 193 | | int narg; |
| 194 | | int i; |
| 195 | | int argc = 0; |
| 196 | | while (argv[argc]) argc++; /* count total number of arguments */ |
| 197 | | narg = argc - (n + 1); /* number of arguments to the script */ |
| 198 | | luaL_checkstack(L, narg + 3, "too many arguments to script"); |
| 199 | | for (i=n+1; i < argc; i++) |
| 200 | | lua_pushstring(L, argv[i]); |
| 201 | | lua_createtable(L, narg, n + 1); |
| 202 | | for (i=0; i < argc; i++) { |
| 203 | | lua_pushstring(L, argv[i]); |
| 204 | | lua_rawseti(L, -2, i - n); |
| 205 | | } |
| 206 | | return narg; |
| 193 | int narg; |
| 194 | int i; |
| 195 | int argc = 0; |
| 196 | while (argv[argc]) argc++; /* count total number of arguments */ |
| 197 | narg = argc - (n + 1); /* number of arguments to the script */ |
| 198 | luaL_checkstack(L, narg + 3, "too many arguments to script"); |
| 199 | for (i=n+1; i < argc; i++) |
| 200 | lua_pushstring(L, argv[i]); |
| 201 | lua_createtable(L, narg, n + 1); |
| 202 | for (i=0; i < argc; i++) { |
| 203 | lua_pushstring(L, argv[i]); |
| 204 | lua_rawseti(L, -2, i - n); |
| 205 | } |
| 206 | return narg; |
| 207 | 207 | } |
| 208 | 208 | |
| 209 | 209 | |
| 210 | 210 | static int dofile (lua_State *L, const char *name) { |
| 211 | | int status = luaL_loadfile(L, name); |
| 212 | | if (status == LUA_OK) status = docall(L, 0, 0); |
| 213 | | return report(L, status); |
| 211 | int status = luaL_loadfile(L, name); |
| 212 | if (status == LUA_OK) status = docall(L, 0, 0); |
| 213 | return report(L, status); |
| 214 | 214 | } |
| 215 | 215 | |
| 216 | 216 | |
| 217 | 217 | static int dostring (lua_State *L, const char *s, const char *name) { |
| 218 | | int status = luaL_loadbuffer(L, s, strlen(s), name); |
| 219 | | if (status == LUA_OK) status = docall(L, 0, 0); |
| 220 | | return report(L, status); |
| 218 | int status = luaL_loadbuffer(L, s, strlen(s), name); |
| 219 | if (status == LUA_OK) status = docall(L, 0, 0); |
| 220 | return report(L, status); |
| 221 | 221 | } |
| 222 | 222 | |
| 223 | 223 | |
| 224 | 224 | static int dolibrary (lua_State *L, const char *name) { |
| 225 | | int status; |
| 226 | | lua_getglobal(L, "require"); |
| 227 | | lua_pushstring(L, name); |
| 228 | | status = docall(L, 1, 1); /* call 'require(name)' */ |
| 229 | | if (status == LUA_OK) |
| 230 | | lua_setglobal(L, name); /* global[name] = require return */ |
| 231 | | return report(L, status); |
| 225 | int status; |
| 226 | lua_getglobal(L, "require"); |
| 227 | lua_pushstring(L, name); |
| 228 | status = docall(L, 1, 1); /* call 'require(name)' */ |
| 229 | if (status == LUA_OK) |
| 230 | lua_setglobal(L, name); /* global[name] = require return */ |
| 231 | return report(L, status); |
| 232 | 232 | } |
| 233 | 233 | |
| 234 | 234 | |
| 235 | 235 | static const char *get_prompt (lua_State *L, int firstline) { |
| 236 | | const char *p; |
| 237 | | lua_getglobal(L, firstline ? "_PROMPT" : "_PROMPT2"); |
| 238 | | p = lua_tostring(L, -1); |
| 239 | | if (p == NULL) p = (firstline ? LUA_PROMPT : LUA_PROMPT2); |
| 240 | | return p; |
| 236 | const char *p; |
| 237 | lua_getglobal(L, firstline ? "_PROMPT" : "_PROMPT2"); |
| 238 | p = lua_tostring(L, -1); |
| 239 | if (p == NULL) p = (firstline ? LUA_PROMPT : LUA_PROMPT2); |
| 240 | return p; |
| 241 | 241 | } |
| 242 | 242 | |
| 243 | 243 | /* mark in error messages for incomplete statements */ |
| 244 | | #define EOFMARK "<eof>" |
| 245 | | #define marklen (sizeof(EOFMARK)/sizeof(char) - 1) |
| 244 | #define EOFMARK "<eof>" |
| 245 | #define marklen (sizeof(EOFMARK)/sizeof(char) - 1) |
| 246 | 246 | |
| 247 | 247 | static int incomplete (lua_State *L, int status) { |
| 248 | | if (status == LUA_ERRSYNTAX) { |
| 249 | | size_t lmsg; |
| 250 | | const char *msg = lua_tolstring(L, -1, &lmsg); |
| 251 | | if (lmsg >= marklen && strcmp(msg + lmsg - marklen, EOFMARK) == 0) { |
| 252 | | lua_pop(L, 1); |
| 253 | | return 1; |
| 254 | | } |
| 255 | | } |
| 256 | | return 0; /* else... */ |
| 248 | if (status == LUA_ERRSYNTAX) { |
| 249 | size_t lmsg; |
| 250 | const char *msg = lua_tolstring(L, -1, &lmsg); |
| 251 | if (lmsg >= marklen && strcmp(msg + lmsg - marklen, EOFMARK) == 0) { |
| 252 | lua_pop(L, 1); |
| 253 | return 1; |
| 254 | } |
| 255 | } |
| 256 | return 0; /* else... */ |
| 257 | 257 | } |
| 258 | 258 | |
| 259 | 259 | |
| 260 | 260 | static int pushline (lua_State *L, int firstline) { |
| 261 | | char buffer[LUA_MAXINPUT]; |
| 262 | | char *b = buffer; |
| 263 | | size_t l; |
| 264 | | const char *prmt = get_prompt(L, firstline); |
| 265 | | int readstatus = lua_readline(L, b, prmt); |
| 266 | | lua_pop(L, 1); /* remove result from 'get_prompt' */ |
| 267 | | if (readstatus == 0) |
| 268 | | return 0; /* no input */ |
| 269 | | l = strlen(b); |
| 270 | | if (l > 0 && b[l-1] == '\n') /* line ends with newline? */ |
| 271 | | b[l-1] = '\0'; /* remove it */ |
| 272 | | if (firstline && b[0] == '=') /* first line starts with `=' ? */ |
| 273 | | lua_pushfstring(L, "return %s", b+1); /* change it to `return' */ |
| 274 | | else |
| 275 | | lua_pushstring(L, b); |
| 276 | | lua_freeline(L, b); |
| 277 | | return 1; |
| 261 | char buffer[LUA_MAXINPUT]; |
| 262 | char *b = buffer; |
| 263 | size_t l; |
| 264 | const char *prmt = get_prompt(L, firstline); |
| 265 | int readstatus = lua_readline(L, b, prmt); |
| 266 | lua_pop(L, 1); /* remove result from 'get_prompt' */ |
| 267 | if (readstatus == 0) |
| 268 | return 0; /* no input */ |
| 269 | l = strlen(b); |
| 270 | if (l > 0 && b[l-1] == '\n') /* line ends with newline? */ |
| 271 | b[l-1] = '\0'; /* remove it */ |
| 272 | if (firstline && b[0] == '=') /* first line starts with `=' ? */ |
| 273 | lua_pushfstring(L, "return %s", b+1); /* change it to `return' */ |
| 274 | else |
| 275 | lua_pushstring(L, b); |
| 276 | lua_freeline(L, b); |
| 277 | return 1; |
| 278 | 278 | } |
| 279 | 279 | |
| 280 | 280 | |
| 281 | 281 | static int loadline (lua_State *L) { |
| 282 | | int status; |
| 283 | | lua_settop(L, 0); |
| 284 | | if (!pushline(L, 1)) |
| 285 | | return -1; /* no input */ |
| 286 | | for (;;) { /* repeat until gets a complete line */ |
| 287 | | size_t l; |
| 288 | | const char *line = lua_tolstring(L, 1, &l); |
| 289 | | status = luaL_loadbuffer(L, line, l, "=stdin"); |
| 290 | | if (!incomplete(L, status)) break; /* cannot try to add lines? */ |
| 291 | | if (!pushline(L, 0)) /* no more input? */ |
| 292 | | return -1; |
| 293 | | lua_pushliteral(L, "\n"); /* add a new line... */ |
| 294 | | lua_insert(L, -2); /* ...between the two lines */ |
| 295 | | lua_concat(L, 3); /* join them */ |
| 296 | | } |
| 297 | | lua_saveline(L, 1); |
| 298 | | lua_remove(L, 1); /* remove line */ |
| 299 | | return status; |
| 282 | int status; |
| 283 | lua_settop(L, 0); |
| 284 | if (!pushline(L, 1)) |
| 285 | return -1; /* no input */ |
| 286 | for (;;) { /* repeat until gets a complete line */ |
| 287 | size_t l; |
| 288 | const char *line = lua_tolstring(L, 1, &l); |
| 289 | status = luaL_loadbuffer(L, line, l, "=stdin"); |
| 290 | if (!incomplete(L, status)) break; /* cannot try to add lines? */ |
| 291 | if (!pushline(L, 0)) /* no more input? */ |
| 292 | return -1; |
| 293 | lua_pushliteral(L, "\n"); /* add a new line... */ |
| 294 | lua_insert(L, -2); /* ...between the two lines */ |
| 295 | lua_concat(L, 3); /* join them */ |
| 296 | } |
| 297 | lua_saveline(L, 1); |
| 298 | lua_remove(L, 1); /* remove line */ |
| 299 | return status; |
| 300 | 300 | } |
| 301 | 301 | |
| 302 | 302 | |
| 303 | 303 | static void dotty (lua_State *L) { |
| 304 | | int status; |
| 305 | | const char *oldprogname = progname; |
| 306 | | progname = NULL; |
| 307 | | while ((status = loadline(L)) != -1) { |
| 308 | | if (status == LUA_OK) status = docall(L, 0, LUA_MULTRET); |
| 309 | | report(L, status); |
| 310 | | if (status == LUA_OK && lua_gettop(L) > 0) { /* any result to print? */ |
| 311 | | luaL_checkstack(L, LUA_MINSTACK, "too many results to print"); |
| 312 | | lua_getglobal(L, "print"); |
| 313 | | lua_insert(L, 1); |
| 314 | | if (lua_pcall(L, lua_gettop(L)-1, 0, 0) != LUA_OK) |
| 315 | | l_message(progname, lua_pushfstring(L, |
| 316 | | "error calling " LUA_QL("print") " (%s)", |
| 317 | | lua_tostring(L, -1))); |
| 318 | | } |
| 319 | | } |
| 320 | | lua_settop(L, 0); /* clear stack */ |
| 321 | | luai_writeline(); |
| 322 | | progname = oldprogname; |
| 304 | int status; |
| 305 | const char *oldprogname = progname; |
| 306 | progname = NULL; |
| 307 | while ((status = loadline(L)) != -1) { |
| 308 | if (status == LUA_OK) status = docall(L, 0, LUA_MULTRET); |
| 309 | report(L, status); |
| 310 | if (status == LUA_OK && lua_gettop(L) > 0) { /* any result to print? */ |
| 311 | luaL_checkstack(L, LUA_MINSTACK, "too many results to print"); |
| 312 | lua_getglobal(L, "print"); |
| 313 | lua_insert(L, 1); |
| 314 | if (lua_pcall(L, lua_gettop(L)-1, 0, 0) != LUA_OK) |
| 315 | l_message(progname, lua_pushfstring(L, |
| 316 | "error calling " LUA_QL("print") " (%s)", |
| 317 | lua_tostring(L, -1))); |
| 318 | } |
| 319 | } |
| 320 | lua_settop(L, 0); /* clear stack */ |
| 321 | luai_writeline(); |
| 322 | progname = oldprogname; |
| 323 | 323 | } |
| 324 | 324 | |
| 325 | 325 | |
| 326 | 326 | static int handle_script (lua_State *L, char **argv, int n) { |
| 327 | | int status; |
| 328 | | const char *fname; |
| 329 | | int narg = getargs(L, argv, n); /* collect arguments */ |
| 330 | | lua_setglobal(L, "arg"); |
| 331 | | fname = argv[n]; |
| 332 | | if (strcmp(fname, "-") == 0 && strcmp(argv[n-1], "--") != 0) |
| 333 | | fname = NULL; /* stdin */ |
| 334 | | status = luaL_loadfile(L, fname); |
| 335 | | lua_insert(L, -(narg+1)); |
| 336 | | if (status == LUA_OK) |
| 337 | | status = docall(L, narg, LUA_MULTRET); |
| 338 | | else |
| 339 | | lua_pop(L, narg); |
| 340 | | return report(L, status); |
| 327 | int status; |
| 328 | const char *fname; |
| 329 | int narg = getargs(L, argv, n); /* collect arguments */ |
| 330 | lua_setglobal(L, "arg"); |
| 331 | fname = argv[n]; |
| 332 | if (strcmp(fname, "-") == 0 && strcmp(argv[n-1], "--") != 0) |
| 333 | fname = NULL; /* stdin */ |
| 334 | status = luaL_loadfile(L, fname); |
| 335 | lua_insert(L, -(narg+1)); |
| 336 | if (status == LUA_OK) |
| 337 | status = docall(L, narg, LUA_MULTRET); |
| 338 | else |
| 339 | lua_pop(L, narg); |
| 340 | return report(L, status); |
| 341 | 341 | } |
| 342 | 342 | |
| 343 | 343 | |
| 344 | 344 | /* check that argument has no extra characters at the end */ |
| 345 | | #define noextrachars(x) {if ((x)[2] != '\0') return -1;} |
| 345 | #define noextrachars(x) {if ((x)[2] != '\0') return -1;} |
| 346 | 346 | |
| 347 | 347 | |
| 348 | 348 | /* indices of various argument indicators in array args */ |
| 349 | | #define has_i 0 /* -i */ |
| 350 | | #define has_v 1 /* -v */ |
| 351 | | #define has_e 2 /* -e */ |
| 352 | | #define has_E 3 /* -E */ |
| 349 | #define has_i 0 /* -i */ |
| 350 | #define has_v 1 /* -v */ |
| 351 | #define has_e 2 /* -e */ |
| 352 | #define has_E 3 /* -E */ |
| 353 | 353 | |
| 354 | | #define num_has 4 /* number of 'has_*' */ |
| 354 | #define num_has 4 /* number of 'has_*' */ |
| 355 | 355 | |
| 356 | 356 | |
| 357 | 357 | static int collectargs (char **argv, int *args) { |
| 358 | | int i; |
| 359 | | for (i = 1; argv[i] != NULL; i++) { |
| 360 | | if (argv[i][0] != '-') /* not an option? */ |
| 361 | | return i; |
| 362 | | switch (argv[i][1]) { /* option */ |
| 363 | | case '-': |
| 364 | | noextrachars(argv[i]); |
| 365 | | return (argv[i+1] != NULL ? i+1 : 0); |
| 366 | | case '\0': |
| 367 | | return i; |
| 368 | | case 'E': |
| 369 | | args[has_E] = 1; |
| 370 | | break; |
| 371 | | case 'i': |
| 372 | | noextrachars(argv[i]); |
| 373 | | args[has_i] = 1; /* go through */ |
| 374 | | case 'v': |
| 375 | | noextrachars(argv[i]); |
| 376 | | args[has_v] = 1; |
| 377 | | break; |
| 378 | | case 'e': |
| 379 | | args[has_e] = 1; /* go through */ |
| 380 | | case 'l': /* both options need an argument */ |
| 381 | | if (argv[i][2] == '\0') { /* no concatenated argument? */ |
| 382 | | i++; /* try next 'argv' */ |
| 383 | | if (argv[i] == NULL || argv[i][0] == '-') |
| 384 | | return -(i - 1); /* no next argument or it is another option */ |
| 385 | | } |
| 386 | | break; |
| 387 | | default: /* invalid option; return its index... */ |
| 388 | | return -i; /* ...as a negative value */ |
| 389 | | } |
| 390 | | } |
| 391 | | return 0; |
| 358 | int i; |
| 359 | for (i = 1; argv[i] != NULL; i++) { |
| 360 | if (argv[i][0] != '-') /* not an option? */ |
| 361 | return i; |
| 362 | switch (argv[i][1]) { /* option */ |
| 363 | case '-': |
| 364 | noextrachars(argv[i]); |
| 365 | return (argv[i+1] != NULL ? i+1 : 0); |
| 366 | case '\0': |
| 367 | return i; |
| 368 | case 'E': |
| 369 | args[has_E] = 1; |
| 370 | break; |
| 371 | case 'i': |
| 372 | noextrachars(argv[i]); |
| 373 | args[has_i] = 1; /* go through */ |
| 374 | case 'v': |
| 375 | noextrachars(argv[i]); |
| 376 | args[has_v] = 1; |
| 377 | break; |
| 378 | case 'e': |
| 379 | args[has_e] = 1; /* go through */ |
| 380 | case 'l': /* both options need an argument */ |
| 381 | if (argv[i][2] == '\0') { /* no concatenated argument? */ |
| 382 | i++; /* try next 'argv' */ |
| 383 | if (argv[i] == NULL || argv[i][0] == '-') |
| 384 | return -(i - 1); /* no next argument or it is another option */ |
| 385 | } |
| 386 | break; |
| 387 | default: /* invalid option; return its index... */ |
| 388 | return -i; /* ...as a negative value */ |
| 389 | } |
| 390 | } |
| 391 | return 0; |
| 392 | 392 | } |
| 393 | 393 | |
| 394 | 394 | |
| 395 | 395 | static int runargs (lua_State *L, char **argv, int n) { |
| 396 | | int i; |
| 397 | | for (i = 1; i < n; i++) { |
| 398 | | lua_assert(argv[i][0] == '-'); |
| 399 | | switch (argv[i][1]) { /* option */ |
| 400 | | case 'e': { |
| 401 | | const char *chunk = argv[i] + 2; |
| 402 | | if (*chunk == '\0') chunk = argv[++i]; |
| 403 | | lua_assert(chunk != NULL); |
| 404 | | if (dostring(L, chunk, "=(command line)") != LUA_OK) |
| 405 | | return 0; |
| 406 | | break; |
| 407 | | } |
| 408 | | case 'l': { |
| 409 | | const char *filename = argv[i] + 2; |
| 410 | | if (*filename == '\0') filename = argv[++i]; |
| 411 | | lua_assert(filename != NULL); |
| 412 | | if (dolibrary(L, filename) != LUA_OK) |
| 413 | | return 0; /* stop if file fails */ |
| 414 | | break; |
| 415 | | } |
| 416 | | default: break; |
| 417 | | } |
| 418 | | } |
| 419 | | return 1; |
| 396 | int i; |
| 397 | for (i = 1; i < n; i++) { |
| 398 | lua_assert(argv[i][0] == '-'); |
| 399 | switch (argv[i][1]) { /* option */ |
| 400 | case 'e': { |
| 401 | const char *chunk = argv[i] + 2; |
| 402 | if (*chunk == '\0') chunk = argv[++i]; |
| 403 | lua_assert(chunk != NULL); |
| 404 | if (dostring(L, chunk, "=(command line)") != LUA_OK) |
| 405 | return 0; |
| 406 | break; |
| 407 | } |
| 408 | case 'l': { |
| 409 | const char *filename = argv[i] + 2; |
| 410 | if (*filename == '\0') filename = argv[++i]; |
| 411 | lua_assert(filename != NULL); |
| 412 | if (dolibrary(L, filename) != LUA_OK) |
| 413 | return 0; /* stop if file fails */ |
| 414 | break; |
| 415 | } |
| 416 | default: break; |
| 417 | } |
| 418 | } |
| 419 | return 1; |
| 420 | 420 | } |
| 421 | 421 | |
| 422 | 422 | |
| 423 | 423 | static int handle_luainit (lua_State *L) { |
| 424 | | const char *name = "=" LUA_INITVERSION; |
| 425 | | const char *init = getenv(name + 1); |
| 426 | | if (init == NULL) { |
| 427 | | name = "=" LUA_INIT; |
| 428 | | init = getenv(name + 1); /* try alternative name */ |
| 429 | | } |
| 430 | | if (init == NULL) return LUA_OK; |
| 431 | | else if (init[0] == '@') |
| 432 | | return dofile(L, init+1); |
| 433 | | else |
| 434 | | return dostring(L, init, name); |
| 424 | const char *name = "=" LUA_INITVERSION; |
| 425 | const char *init = getenv(name + 1); |
| 426 | if (init == NULL) { |
| 427 | name = "=" LUA_INIT; |
| 428 | init = getenv(name + 1); /* try alternative name */ |
| 429 | } |
| 430 | if (init == NULL) return LUA_OK; |
| 431 | else if (init[0] == '@') |
| 432 | return dofile(L, init+1); |
| 433 | else |
| 434 | return dostring(L, init, name); |
| 435 | 435 | } |
| 436 | 436 | |
| 437 | 437 | |
| 438 | 438 | static int pmain (lua_State *L) { |
| 439 | | int argc = (int)lua_tointeger(L, 1); |
| 440 | | char **argv = (char **)lua_touserdata(L, 2); |
| 441 | | int script; |
| 442 | | int args[num_has]; |
| 443 | | args[has_i] = args[has_v] = args[has_e] = args[has_E] = 0; |
| 444 | | if (argv[0] && argv[0][0]) progname = argv[0]; |
| 445 | | script = collectargs(argv, args); |
| 446 | | if (script < 0) { /* invalid arg? */ |
| 447 | | print_usage(argv[-script]); |
| 448 | | return 0; |
| 449 | | } |
| 450 | | if (args[has_v]) print_version(); |
| 451 | | if (args[has_E]) { /* option '-E'? */ |
| 452 | | lua_pushboolean(L, 1); /* signal for libraries to ignore env. vars. */ |
| 453 | | lua_setfield(L, LUA_REGISTRYINDEX, "LUA_NOENV"); |
| 454 | | } |
| 455 | | /* open standard libraries */ |
| 456 | | luaL_checkversion(L); |
| 457 | | lua_gc(L, LUA_GCSTOP, 0); /* stop collector during initialization */ |
| 458 | | luaL_openlibs(L); /* open libraries */ |
| 459 | | lua_gc(L, LUA_GCRESTART, 0); |
| 460 | | if (!args[has_E] && handle_luainit(L) != LUA_OK) |
| 461 | | return 0; /* error running LUA_INIT */ |
| 462 | | /* execute arguments -e and -l */ |
| 463 | | if (!runargs(L, argv, (script > 0) ? script : argc)) return 0; |
| 464 | | /* execute main script (if there is one) */ |
| 465 | | if (script && handle_script(L, argv, script) != LUA_OK) return 0; |
| 466 | | if (args[has_i]) /* -i option? */ |
| 467 | | dotty(L); |
| 468 | | else if (script == 0 && !args[has_e] && !args[has_v]) { /* no arguments? */ |
| 469 | | if (lua_stdin_is_tty()) { |
| 470 | | print_version(); |
| 471 | | dotty(L); |
| 472 | | } |
| 473 | | else dofile(L, NULL); /* executes stdin as a file */ |
| 474 | | } |
| 475 | | lua_pushboolean(L, 1); /* signal no errors */ |
| 476 | | return 1; |
| 439 | int argc = (int)lua_tointeger(L, 1); |
| 440 | char **argv = (char **)lua_touserdata(L, 2); |
| 441 | int script; |
| 442 | int args[num_has]; |
| 443 | args[has_i] = args[has_v] = args[has_e] = args[has_E] = 0; |
| 444 | if (argv[0] && argv[0][0]) progname = argv[0]; |
| 445 | script = collectargs(argv, args); |
| 446 | if (script < 0) { /* invalid arg? */ |
| 447 | print_usage(argv[-script]); |
| 448 | return 0; |
| 449 | } |
| 450 | if (args[has_v]) print_version(); |
| 451 | if (args[has_E]) { /* option '-E'? */ |
| 452 | lua_pushboolean(L, 1); /* signal for libraries to ignore env. vars. */ |
| 453 | lua_setfield(L, LUA_REGISTRYINDEX, "LUA_NOENV"); |
| 454 | } |
| 455 | /* open standard libraries */ |
| 456 | luaL_checkversion(L); |
| 457 | lua_gc(L, LUA_GCSTOP, 0); /* stop collector during initialization */ |
| 458 | luaL_openlibs(L); /* open libraries */ |
| 459 | lua_gc(L, LUA_GCRESTART, 0); |
| 460 | if (!args[has_E] && handle_luainit(L) != LUA_OK) |
| 461 | return 0; /* error running LUA_INIT */ |
| 462 | /* execute arguments -e and -l */ |
| 463 | if (!runargs(L, argv, (script > 0) ? script : argc)) return 0; |
| 464 | /* execute main script (if there is one) */ |
| 465 | if (script && handle_script(L, argv, script) != LUA_OK) return 0; |
| 466 | if (args[has_i]) /* -i option? */ |
| 467 | dotty(L); |
| 468 | else if (script == 0 && !args[has_e] && !args[has_v]) { /* no arguments? */ |
| 469 | if (lua_stdin_is_tty()) { |
| 470 | print_version(); |
| 471 | dotty(L); |
| 472 | } |
| 473 | else dofile(L, NULL); /* executes stdin as a file */ |
| 474 | } |
| 475 | lua_pushboolean(L, 1); /* signal no errors */ |
| 476 | return 1; |
| 477 | 477 | } |
| 478 | 478 | |
| 479 | 479 | |
| 480 | 480 | int main (int argc, char **argv) { |
| 481 | | int status, result; |
| 482 | | lua_State *L = luaL_newstate(); /* create state */ |
| 483 | | if (L == NULL) { |
| 484 | | l_message(argv[0], "cannot create state: not enough memory"); |
| 485 | | return EXIT_FAILURE; |
| 486 | | } |
| 487 | | /* call 'pmain' in protected mode */ |
| 488 | | lua_pushcfunction(L, &pmain); |
| 489 | | lua_pushinteger(L, argc); /* 1st argument */ |
| 490 | | lua_pushlightuserdata(L, argv); /* 2nd argument */ |
| 491 | | status = lua_pcall(L, 2, 1, 0); |
| 492 | | result = lua_toboolean(L, -1); /* get result */ |
| 493 | | finalreport(L, status); |
| 494 | | lua_close(L); |
| 495 | | return (result && status == LUA_OK) ? EXIT_SUCCESS : EXIT_FAILURE; |
| 481 | int status, result; |
| 482 | lua_State *L = luaL_newstate(); /* create state */ |
| 483 | if (L == NULL) { |
| 484 | l_message(argv[0], "cannot create state: not enough memory"); |
| 485 | return EXIT_FAILURE; |
| 486 | } |
| 487 | /* call 'pmain' in protected mode */ |
| 488 | lua_pushcfunction(L, &pmain); |
| 489 | lua_pushinteger(L, argc); /* 1st argument */ |
| 490 | lua_pushlightuserdata(L, argv); /* 2nd argument */ |
| 491 | status = lua_pcall(L, 2, 1, 0); |
| 492 | result = lua_toboolean(L, -1); /* get result */ |
| 493 | finalreport(L, status); |
| 494 | lua_close(L); |
| 495 | return (result && status == LUA_OK) ? EXIT_SUCCESS : EXIT_FAILURE; |
| 496 | 496 | } |
| 497 | |
trunk/src/lib/lua/lobject.c
| r30857 | r30858 | |
| 1 | 1 | /* |
| 2 | | ** $Id: lobject.c,v 2.58 2013/02/20 14:08:56 roberto Exp $ |
| 2 | ** $Id: lobject.c,v 2.58.1.1 2013/04/12 18:48:47 roberto Exp $ |
| 3 | 3 | ** Some generic functions over Lua objects |
| 4 | 4 | ** See Copyright Notice in lua.h |
| 5 | 5 | */ |
| r30857 | r30858 | |
| 34 | 34 | ** eeeee != 0 and (xxx) otherwise. |
| 35 | 35 | */ |
| 36 | 36 | int luaO_int2fb (unsigned int x) { |
| 37 | | int e = 0; /* exponent */ |
| 38 | | if (x < 8) return x; |
| 39 | | while (x >= 0x10) { |
| 40 | | x = (x+1) >> 1; |
| 41 | | e++; |
| 42 | | } |
| 43 | | return ((e+1) << 3) | (cast_int(x) - 8); |
| 37 | int e = 0; /* exponent */ |
| 38 | if (x < 8) return x; |
| 39 | while (x >= 0x10) { |
| 40 | x = (x+1) >> 1; |
| 41 | e++; |
| 42 | } |
| 43 | return ((e+1) << 3) | (cast_int(x) - 8); |
| 44 | 44 | } |
| 45 | 45 | |
| 46 | 46 | |
| 47 | 47 | /* converts back */ |
| 48 | 48 | int luaO_fb2int (int x) { |
| 49 | | int e = (x >> 3) & 0x1f; |
| 50 | | if (e == 0) return x; |
| 51 | | else return ((x & 7) + 8) << (e - 1); |
| 49 | int e = (x >> 3) & 0x1f; |
| 50 | if (e == 0) return x; |
| 51 | else return ((x & 7) + 8) << (e - 1); |
| 52 | 52 | } |
| 53 | 53 | |
| 54 | 54 | |
| 55 | 55 | int luaO_ceillog2 (unsigned int x) { |
| 56 | | static const lu_byte log_2[256] = { |
| 57 | | 0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5, |
| 58 | | 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, |
| 59 | | 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, |
| 60 | | 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, |
| 61 | | 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, |
| 62 | | 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, |
| 63 | | 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, |
| 64 | | 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8 |
| 65 | | }; |
| 66 | | int l = 0; |
| 67 | | x--; |
| 68 | | while (x >= 256) { l += 8; x >>= 8; } |
| 69 | | return l + log_2[x]; |
| 56 | static const lu_byte log_2[256] = { |
| 57 | 0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5, |
| 58 | 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, |
| 59 | 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, |
| 60 | 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, |
| 61 | 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, |
| 62 | 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, |
| 63 | 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, |
| 64 | 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8 |
| 65 | }; |
| 66 | int l = 0; |
| 67 | x--; |
| 68 | while (x >= 256) { l += 8; x >>= 8; } |
| 69 | return l + log_2[x]; |
| 70 | 70 | } |
| 71 | 71 | |
| 72 | 72 | |
| 73 | 73 | lua_Number luaO_arith (int op, lua_Number v1, lua_Number v2) { |
| 74 | | switch (op) { |
| 75 | | case LUA_OPADD: return luai_numadd(NULL, v1, v2); |
| 76 | | case LUA_OPSUB: return luai_numsub(NULL, v1, v2); |
| 77 | | case LUA_OPMUL: return luai_nummul(NULL, v1, v2); |
| 78 | | case LUA_OPDIV: return luai_numdiv(NULL, v1, v2); |
| 79 | | case LUA_OPMOD: return luai_nummod(NULL, v1, v2); |
| 80 | | case LUA_OPPOW: return luai_numpow(NULL, v1, v2); |
| 81 | | case LUA_OPUNM: return luai_numunm(NULL, v1); |
| 82 | | default: lua_assert(0); return 0; |
| 83 | | } |
| 74 | switch (op) { |
| 75 | case LUA_OPADD: return luai_numadd(NULL, v1, v2); |
| 76 | case LUA_OPSUB: return luai_numsub(NULL, v1, v2); |
| 77 | case LUA_OPMUL: return luai_nummul(NULL, v1, v2); |
| 78 | case LUA_OPDIV: return luai_numdiv(NULL, v1, v2); |
| 79 | case LUA_OPMOD: return luai_nummod(NULL, v1, v2); |
| 80 | case LUA_OPPOW: return luai_numpow(NULL, v1, v2); |
| 81 | case LUA_OPUNM: return luai_numunm(NULL, v1); |
| 82 | default: lua_assert(0); return 0; |
| 83 | } |
| 84 | 84 | } |
| 85 | 85 | |
| 86 | 86 | |
| 87 | 87 | int luaO_hexavalue (int c) { |
| 88 | | if (lisdigit(c)) return c - '0'; |
| 89 | | else return ltolower(c) - 'a' + 10; |
| 88 | if (lisdigit(c)) return c - '0'; |
| 89 | else return ltolower(c) - 'a' + 10; |
| 90 | 90 | } |
| 91 | 91 | |
| 92 | 92 | |
| r30857 | r30858 | |
| 96 | 96 | |
| 97 | 97 | |
| 98 | 98 | static int isneg (const char **s) { |
| 99 | | if (**s == '-') { (*s)++; return 1; } |
| 100 | | else if (**s == '+') (*s)++; |
| 101 | | return 0; |
| 99 | if (**s == '-') { (*s)++; return 1; } |
| 100 | else if (**s == '+') (*s)++; |
| 101 | return 0; |
| 102 | 102 | } |
| 103 | 103 | |
| 104 | 104 | |
| 105 | 105 | static lua_Number readhexa (const char **s, lua_Number r, int *count) { |
| 106 | | for (; lisxdigit(cast_uchar(**s)); (*s)++) { /* read integer part */ |
| 107 | | r = (r * cast_num(16.0)) + cast_num(1.0*luaO_hexavalue(cast_uchar(**s))); |
| 108 | | (*count)++; |
| 109 | | } |
| 110 | | return r; |
| 106 | for (; lisxdigit(cast_uchar(**s)); (*s)++) { /* read integer part */ |
| 107 | r = (r * cast_num(16.0)) + cast_num(1.0*luaO_hexavalue(cast_uchar(**s))); |
| 108 | (*count)++; |
| 109 | } |
| 110 | return r; |
| 111 | 111 | } |
| 112 | 112 | |
| 113 | 113 | |
| r30857 | r30858 | |
| 116 | 116 | ** C99 specification for 'strtod' |
| 117 | 117 | */ |
| 118 | 118 | static lua_Number lua_strx2number (const char *s, char **endptr) { |
| 119 | | lua_Number r = 0.0; |
| 120 | | int e = 0, i = 0; |
| 121 | | int neg = 0; /* 1 if number is negative */ |
| 122 | | *endptr = cast(char *, s); /* nothing is valid yet */ |
| 123 | | while (lisspace(cast_uchar(*s))) s++; /* skip initial spaces */ |
| 124 | | neg = isneg(&s); /* check signal */ |
| 125 | | if (!(*s == '0' && (*(s + 1) == 'x' || *(s + 1) == 'X'))) /* check '0x' */ |
| 126 | | return 0.0; /* invalid format (no '0x') */ |
| 127 | | s += 2; /* skip '0x' */ |
| 128 | | r = readhexa(&s, r, &i); /* read integer part */ |
| 129 | | if (*s == '.') { |
| 130 | | s++; /* skip dot */ |
| 131 | | r = readhexa(&s, r, &e); /* read fractional part */ |
| 132 | | } |
| 133 | | if (i == 0 && e == 0) |
| 134 | | return 0.0; /* invalid format (no digit) */ |
| 135 | | e *= -4; /* each fractional digit divides value by 2^-4 */ |
| 136 | | *endptr = cast(char *, s); /* valid up to here */ |
| 137 | | if (*s == 'p' || *s == 'P') { /* exponent part? */ |
| 138 | | int exp1 = 0; |
| 139 | | int neg1; |
| 140 | | s++; /* skip 'p' */ |
| 141 | | neg1 = isneg(&s); /* signal */ |
| 142 | | if (!lisdigit(cast_uchar(*s))) |
| 143 | | goto ret; /* must have at least one digit */ |
| 144 | | while (lisdigit(cast_uchar(*s))) /* read exponent */ |
| 145 | | exp1 = exp1 * 10 + *(s++) - '0'; |
| 146 | | if (neg1) exp1 = -exp1; |
| 147 | | e += exp1; |
| 148 | | } |
| 149 | | *endptr = cast(char *, s); /* valid up to here */ |
| 150 | | ret: |
| 151 | | if (neg) r = -r; |
| 152 | | return l_mathop(ldexp)(r, e); |
| 119 | lua_Number r = 0.0; |
| 120 | int e = 0, i = 0; |
| 121 | int neg = 0; /* 1 if number is negative */ |
| 122 | *endptr = cast(char *, s); /* nothing is valid yet */ |
| 123 | while (lisspace(cast_uchar(*s))) s++; /* skip initial spaces */ |
| 124 | neg = isneg(&s); /* check signal */ |
| 125 | if (!(*s == '0' && (*(s + 1) == 'x' || *(s + 1) == 'X'))) /* check '0x' */ |
| 126 | return 0.0; /* invalid format (no '0x') */ |
| 127 | s += 2; /* skip '0x' */ |
| 128 | r = readhexa(&s, r, &i); /* read integer part */ |
| 129 | if (*s == '.') { |
| 130 | s++; /* skip dot */ |
| 131 | r = readhexa(&s, r, &e); /* read fractional part */ |
| 132 | } |
| 133 | if (i == 0 && e == 0) |
| 134 | return 0.0; /* invalid format (no digit) */ |
| 135 | e *= -4; /* each fractional digit divides value by 2^-4 */ |
| 136 | *endptr = cast(char *, s); /* valid up to here */ |
| 137 | if (*s == 'p' || *s == 'P') { /* exponent part? */ |
| 138 | int exp1 = 0; |
| 139 | int neg1; |
| 140 | s++; /* skip 'p' */ |
| 141 | neg1 = isneg(&s); /* signal */ |
| 142 | if (!lisdigit(cast_uchar(*s))) |
| 143 | goto ret; /* must have at least one digit */ |
| 144 | while (lisdigit(cast_uchar(*s))) /* read exponent */ |
| 145 | exp1 = exp1 * 10 + *(s++) - '0'; |
| 146 | if (neg1) exp1 = -exp1; |
| 147 | e += exp1; |
| 148 | } |
| 149 | *endptr = cast(char *, s); /* valid up to here */ |
| 150 | ret: |
| 151 | if (neg) r = -r; |
| 152 | return l_mathop(ldexp)(r, e); |
| 153 | 153 | } |
| 154 | 154 | |
| 155 | 155 | #endif |
| 156 | 156 | |
| 157 | 157 | |
| 158 | 158 | int luaO_str2d (const char *s, size_t len, lua_Number *result) { |
| 159 | | char *endptr; |
| 160 | | if (strpbrk(s, "nN")) /* reject 'inf' and 'nan' */ |
| 161 | | return 0; |
| 162 | | else if (strpbrk(s, "xX")) /* hexa? */ |
| 163 | | *result = lua_strx2number(s, &endptr); |
| 164 | | else |
| 165 | | *result = lua_str2number(s, &endptr); |
| 166 | | if (endptr == s) return 0; /* nothing recognized */ |
| 167 | | while (lisspace(cast_uchar(*endptr))) endptr++; |
| 168 | | return (endptr == s + len); /* OK if no trailing characters */ |
| 159 | char *endptr; |
| 160 | if (strpbrk(s, "nN")) /* reject 'inf' and 'nan' */ |
| 161 | return 0; |
| 162 | else if (strpbrk(s, "xX")) /* hexa? */ |
| 163 | *result = lua_strx2number(s, &endptr); |
| 164 | else |
| 165 | *result = lua_str2number(s, &endptr); |
| 166 | if (endptr == s) return 0; /* nothing recognized */ |
| 167 | while (lisspace(cast_uchar(*endptr))) endptr++; |
| 168 | return (endptr == s + len); /* OK if no trailing characters */ |
| 169 | 169 | } |
| 170 | 170 | |
| 171 | 171 | |
| 172 | 172 | |
| 173 | 173 | static void pushstr (lua_State *L, const char *str, size_t l) { |
| 174 | | setsvalue2s(L, L->top++, luaS_newlstr(L, str, l)); |
| 174 | setsvalue2s(L, L->top++, luaS_newlstr(L, str, l)); |
| 175 | 175 | } |
| 176 | 176 | |
| 177 | 177 | |
| 178 | 178 | /* this function handles only `%d', `%c', %f, %p, and `%s' formats */ |
| 179 | 179 | const char *luaO_pushvfstring (lua_State *L, const char *fmt, va_list argp) { |
| 180 | | int n = 0; |
| 181 | | for (;;) { |
| 182 | | const char *e = strchr(fmt, '%'); |
| 183 | | if (e == NULL) break; |
| 184 | | luaD_checkstack(L, 2); /* fmt + item */ |
| 185 | | pushstr(L, fmt, e - fmt); |
| 186 | | switch (*(e+1)) { |
| 187 | | case 's': { |
| 188 | | const char *s = va_arg(argp, char *); |
| 189 | | if (s == NULL) s = "(null)"; |
| 190 | | pushstr(L, s, strlen(s)); |
| 191 | | break; |
| 192 | | } |
| 193 | | case 'c': { |
| 194 | | char buff; |
| 195 | | buff = cast(char, va_arg(argp, int)); |
| 196 | | pushstr(L, &buff, 1); |
| 197 | | break; |
| 198 | | } |
| 199 | | case 'd': { |
| 200 | | setnvalue(L->top++, cast_num(va_arg(argp, int))); |
| 201 | | break; |
| 202 | | } |
| 203 | | case 'f': { |
| 204 | | setnvalue(L->top++, cast_num(va_arg(argp, l_uacNumber))); |
| 205 | | break; |
| 206 | | } |
| 207 | | case 'p': { |
| 208 | | char buff[4*sizeof(void *) + 8]; /* should be enough space for a `%p' */ |
| 209 | | int l = sprintf(buff, "%p", va_arg(argp, void *)); |
| 210 | | pushstr(L, buff, l); |
| 211 | | break; |
| 212 | | } |
| 213 | | case '%': { |
| 214 | | pushstr(L, "%", 1); |
| 215 | | break; |
| 216 | | } |
| 217 | | default: { |
| 218 | | luaG_runerror(L, |
| 219 | | "invalid option " LUA_QL("%%%c") " to " LUA_QL("lua_pushfstring"), |
| 220 | | *(e + 1)); |
| 221 | | } |
| 222 | | } |
| 223 | | n += 2; |
| 224 | | fmt = e+2; |
| 225 | | } |
| 226 | | luaD_checkstack(L, 1); |
| 227 | | pushstr(L, fmt, strlen(fmt)); |
| 228 | | if (n > 0) luaV_concat(L, n + 1); |
| 229 | | return svalue(L->top - 1); |
| 180 | int n = 0; |
| 181 | for (;;) { |
| 182 | const char *e = strchr(fmt, '%'); |
| 183 | if (e == NULL) break; |
| 184 | luaD_checkstack(L, 2); /* fmt + item */ |
| 185 | pushstr(L, fmt, e - fmt); |
| 186 | switch (*(e+1)) { |
| 187 | case 's': { |
| 188 | const char *s = va_arg(argp, char *); |
| 189 | if (s == NULL) s = "(null)"; |
| 190 | pushstr(L, s, strlen(s)); |
| 191 | break; |
| 192 | } |
| 193 | case 'c': { |
| 194 | char buff; |
| 195 | buff = cast(char, va_arg(argp, int)); |
| 196 | pushstr(L, &buff, 1); |
| 197 | break; |
| 198 | } |
| 199 | case 'd': { |
| 200 | setnvalue(L->top++, cast_num(va_arg(argp, int))); |
| 201 | break; |
| 202 | } |
| 203 | case 'f': { |
| 204 | setnvalue(L->top++, cast_num(va_arg(argp, l_uacNumber))); |
| 205 | break; |
| 206 | } |
| 207 | case 'p': { |
| 208 | char buff[4*sizeof(void *) + 8]; /* should be enough space for a `%p' */ |
| 209 | int l = sprintf(buff, "%p", va_arg(argp, void *)); |
| 210 | pushstr(L, buff, l); |
| 211 | break; |
| 212 | } |
| 213 | case '%': { |
| 214 | pushstr(L, "%", 1); |
| 215 | break; |
| 216 | } |
| 217 | default: { |
| 218 | luaG_runerror(L, |
| 219 | "invalid option " LUA_QL("%%%c") " to " LUA_QL("lua_pushfstring"), |
| 220 | *(e + 1)); |
| 221 | } |
| 222 | } |
| 223 | n += 2; |
| 224 | fmt = e+2; |
| 225 | } |
| 226 | luaD_checkstack(L, 1); |
| 227 | pushstr(L, fmt, strlen(fmt)); |
| 228 | if (n > 0) luaV_concat(L, n + 1); |
| 229 | return svalue(L->top - 1); |
| 230 | 230 | } |
| 231 | 231 | |
| 232 | 232 | |
| 233 | 233 | const char *luaO_pushfstring (lua_State *L, const char *fmt, ...) { |
| 234 | | const char *msg; |
| 235 | | va_list argp; |
| 236 | | va_start(argp, fmt); |
| 237 | | msg = luaO_pushvfstring(L, fmt, argp); |
| 238 | | va_end(argp); |
| 239 | | return msg; |
| 234 | const char *msg; |
| 235 | va_list argp; |
| 236 | va_start(argp, fmt); |
| 237 | msg = luaO_pushvfstring(L, fmt, argp); |
| 238 | va_end(argp); |
| 239 | return msg; |
| 240 | 240 | } |
| 241 | 241 | |
| 242 | 242 | |
| 243 | 243 | /* number of chars of a literal string without the ending \0 */ |
| 244 | | #define LL(x) (sizeof(x)/sizeof(char) - 1) |
| 244 | #define LL(x) (sizeof(x)/sizeof(char) - 1) |
| 245 | 245 | |
| 246 | | #define RETS "..." |
| 247 | | #define PRE "[string \"" |
| 248 | | #define POS "\"]" |
| 246 | #define RETS "..." |
| 247 | #define PRE "[string \"" |
| 248 | #define POS "\"]" |
| 249 | 249 | |
| 250 | | #define addstr(a,b,l) ( memcpy(a,b,(l) * sizeof(char)), a += (l) ) |
| 250 | #define addstr(a,b,l) ( memcpy(a,b,(l) * sizeof(char)), a += (l) ) |
| 251 | 251 | |
| 252 | 252 | void luaO_chunkid (char *out, const char *source, size_t bufflen) { |
| 253 | | size_t l = strlen(source); |
| 254 | | if (*source == '=') { /* 'literal' source */ |
| 255 | | if (l <= bufflen) /* small enough? */ |
| 256 | | memcpy(out, source + 1, l * sizeof(char)); |
| 257 | | else { /* truncate it */ |
| 258 | | addstr(out, source + 1, bufflen - 1); |
| 259 | | *out = '\0'; |
| 260 | | } |
| 261 | | } |
| 262 | | else if (*source == '@') { /* file name */ |
| 263 | | if (l <= bufflen) /* small enough? */ |
| 264 | | memcpy(out, source + 1, l * sizeof(char)); |
| 265 | | else { /* add '...' before rest of name */ |
| 266 | | addstr(out, RETS, LL(RETS)); |
| 267 | | bufflen -= LL(RETS); |
| 268 | | memcpy(out, source + 1 + l - bufflen, bufflen * sizeof(char)); |
| 269 | | } |
| 270 | | } |
| 271 | | else { /* string; format as [string "source"] */ |
| 272 | | const char *nl = strchr(source, '\n'); /* find first new line (if any) */ |
| 273 | | addstr(out, PRE, LL(PRE)); /* add prefix */ |
| 274 | | bufflen -= LL(PRE RETS POS) + 1; /* save space for prefix+suffix+'\0' */ |
| 275 | | if (l < bufflen && nl == NULL) { /* small one-line source? */ |
| 276 | | addstr(out, source, l); /* keep it */ |
| 277 | | } |
| 278 | | else { |
| 279 | | if (nl != NULL) l = nl - source; /* stop at first newline */ |
| 280 | | if (l > bufflen) l = bufflen; |
| 281 | | addstr(out, source, l); |
| 282 | | addstr(out, RETS, LL(RETS)); |
| 283 | | } |
| 284 | | memcpy(out, POS, (LL(POS) + 1) * sizeof(char)); |
| 285 | | } |
| 253 | size_t l = strlen(source); |
| 254 | if (*source == '=') { /* 'literal' source */ |
| 255 | if (l <= bufflen) /* small enough? */ |
| 256 | memcpy(out, source + 1, l * sizeof(char)); |
| 257 | else { /* truncate it */ |
| 258 | addstr(out, source + 1, bufflen - 1); |
| 259 | *out = '\0'; |
| 260 | } |
| 261 | } |
| 262 | else if (*source == '@') { /* file name */ |
| 263 | if (l <= bufflen) /* small enough? */ |
| 264 | memcpy(out, source + 1, l * sizeof(char)); |
| 265 | else { /* add '...' before rest of name */ |
| 266 | addstr(out, RETS, LL(RETS)); |
| 267 | bufflen -= LL(RETS); |
| 268 | memcpy(out, source + 1 + l - bufflen, bufflen * sizeof(char)); |
| 269 | } |
| 270 | } |
| 271 | else { /* string; format as [string "source"] */ |
| 272 | const char *nl = strchr(source, '\n'); /* find first new line (if any) */ |
| 273 | addstr(out, PRE, LL(PRE)); /* add prefix */ |
| 274 | bufflen -= LL(PRE RETS POS) + 1; /* save space for prefix+suffix+'\0' */ |
| 275 | if (l < bufflen && nl == NULL) { /* small one-line source? */ |
| 276 | addstr(out, source, l); /* keep it */ |
| 277 | } |
| 278 | else { |
| 279 | if (nl != NULL) l = nl - source; /* stop at first newline */ |
| 280 | if (l > bufflen) l = bufflen; |
| 281 | addstr(out, source, l); |
| 282 | addstr(out, RETS, LL(RETS)); |
| 283 | } |
| 284 | memcpy(out, POS, (LL(POS) + 1) * sizeof(char)); |
| 285 | } |
| 286 | 286 | } |
| 287 | |