History

Lua 5.2.0-beta-rc1

Lua Team committed 15 years ago

Commit 30837cc1 parent 9bce00553 files · +2418 −1456Browse files

Showing the changes to src (48 of 53 files). Show all

Unified · Split

48 files
  1. src/Makefile +2 −2
  2. src/lapi.c +88 −74
  3. src/lauxlib.c +77 −13
  4. src/lauxlib.h +5 −2
  5. src/lbaselib.c +76 −108
  6. src/lbitlib.c +67 −21
  7. src/lcode.c +42 −38
  8. src/lcode.h +3 −4
  9. src/ldblib.c +8 −19
  10. src/ldebug.c +74 −36
  11. src/ldebug.h +4 −1
  12. src/ldo.c +64 −66
  13. src/ldump.c +3 −3
  14. src/lgc.c +79 −58
  15. src/lgc.h +8 −9
  16. src/linit.c +5 −5
  17. src/liolib.c +34 −57
  18. src/llex.c +13 −17
  19. src/llex.h +7 −7
  20. src/llimits.h +15 −10
  21. src/lmem.c +5 −9
  22. src/loadlib.c +43 −30
  23. src/lobject.c +86 −38
  24. src/lobject.h +241 −87
  25. src/lopcodes.c +5 −5
  26. src/lopcodes.h +6 −7
  27. src/loslib.c +11 −20
  28. src/lparser.c +320 −145
  29. src/lparser.h +34 −11
  30. src/lstate.c +12 −8
  31. src/lstate.h +11 −7
  32. src/lstring.c +4 −3
  33. src/lstrlib.c +51 −22
  34. src/ltable.c +10 −8
  35. src/ltablib.c +4 −4
  36. src/ltm.c +4 −4
  37. src/ltm.h +2 −2
  38. src/lua.c +10 −11
  39. src/lua.h +4 −4
  40. src/luac.c +17 −12
  41. src/luaconf.h +57 −6
  42. src/lualib.h +2 −2
  43. src/lundump.c +30 −23
  44. src/lundump.h +7 −4
  45. src/lvm.c +97 −53
  46. src/lvm.h +7 −4
  47. src/lzio.c +12 −18
  48. src/lzio.h +2 −3
src/Makefile+2−2
@@ -126,7 +126,7 @@ lbaselib.o: lbaselib.c lua.h luaconf.h lauxlib.h lualib.h · 125 unmodified lines
126lbitlib.o: lbitlib.c lua.h luaconf.h lauxlib.h lualib.h126lbitlib.o: lbitlib.c lua.h luaconf.h lauxlib.h lualib.h
127lcode.o: lcode.c lua.h luaconf.h lcode.h llex.h lobject.h llimits.h \127lcode.o: lcode.c lua.h luaconf.h lcode.h llex.h lobject.h llimits.h \
128 lzio.h lmem.h lopcodes.h lparser.h ldebug.h lstate.h ltm.h ldo.h lgc.h \128 lzio.h lmem.h lopcodes.h lparser.h ldebug.h lstate.h ltm.h ldo.h lgc.h \
129 lstring.h ltable.h129 lstring.h ltable.h lvm.h
130lcorolib.o: lcorolib.c lua.h luaconf.h lauxlib.h lualib.h130lcorolib.o: lcorolib.c lua.h luaconf.h lauxlib.h lualib.h
131lctype.o: lctype.c lctype.h lua.h luaconf.h llimits.h131lctype.o: lctype.c lctype.h lua.h luaconf.h llimits.h
132ldblib.o: ldblib.c lua.h luaconf.h lauxlib.h lualib.h132ldblib.o: ldblib.c lua.h luaconf.h lauxlib.h lualib.h
@@ -164,7 +164,7 @@ lstring.o: lstring.c lua.h luaconf.h lmem.h llimits.h lobject.h lstate.h \ · 31 unmodified lines
164 ltm.h lzio.h lstring.h lgc.h164 ltm.h lzio.h lstring.h lgc.h
165lstrlib.o: lstrlib.c lua.h luaconf.h lauxlib.h lualib.h165lstrlib.o: lstrlib.c lua.h luaconf.h lauxlib.h lualib.h
166ltable.o: ltable.c lua.h luaconf.h ldebug.h lstate.h lobject.h llimits.h \166ltable.o: ltable.c lua.h luaconf.h ldebug.h lstate.h lobject.h llimits.h \
167 ltm.h lzio.h lmem.h ldo.h lgc.h lstring.h ltable.h167 ltm.h lzio.h lmem.h ldo.h lgc.h lstring.h ltable.h lvm.h
168ltablib.o: ltablib.c lua.h luaconf.h lauxlib.h lualib.h168ltablib.o: ltablib.c lua.h luaconf.h lauxlib.h lualib.h
169ltm.o: ltm.c lua.h luaconf.h lobject.h llimits.h lstate.h ltm.h lzio.h \169ltm.o: ltm.c lua.h luaconf.h lobject.h llimits.h lstate.h ltm.h lzio.h \
170 lmem.h lstring.h lgc.h ltable.h170 lmem.h lstring.h lgc.h ltable.h
src/lapi.c+88−74
@@ -1,5 +1,5 @@
1/*1/*
2** $Id: lapi.c,v 2.140 2010/11/03 15:16:17 roberto Exp $2** $Id: lapi.c,v 2.149 2011/06/13 14:13:06 roberto Exp $
3** Lua API3** Lua API
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -59,9 +59,9 @@ static TValue *index2addr (lua_State *L, int idx) { · 53 unmodified lines
59 if (ttislcf(ci->func)) /* light C function? */59 if (ttislcf(ci->func)) /* light C function? */
60 return cast(TValue *, luaO_nilobject); /* it has no upvalues */60 return cast(TValue *, luaO_nilobject); /* it has no upvalues */
61 else {61 else {
62 Closure *func = clvalue(ci->func);62 CClosure *func = clCvalue(ci->func);
63 return (idx <= func->c.nupvalues)63 return (idx <= func->nupvalues)
64 ? &func->c.upvalue[idx-1]64 ? &func->upvalue[idx-1]
65 : cast(TValue *, luaO_nilobject);65 : cast(TValue *, luaO_nilobject);
66 }66 }
67 }67 }
@@ -195,10 +195,8 @@ static void moveto (lua_State *L, TValue *fr, int idx) { · 127 unmodified lines
195 TValue *to = index2addr(L, idx);195 TValue *to = index2addr(L, idx);
196 api_checkvalidindex(L, to);196 api_checkvalidindex(L, to);
197 setobj(L, to, fr);197 setobj(L, to, fr);
198 if (idx < LUA_REGISTRYINDEX) { /* function upvalue? */198 if (idx < LUA_REGISTRYINDEX) /* function upvalue? */
199 lua_assert(ttisclosure(L->ci->func));199 luaC_barrier(L, clCvalue(L->ci->func), fr);
200 luaC_barrier(L, clvalue(L->ci->func), fr);
201 }
202 /* LUA_REGISTRYINDEX does not need gc barrier200 /* LUA_REGISTRYINDEX does not need gc barrier
203 (collector revisits it before finishing collection) */201 (collector revisits it before finishing collection) */
204}202}
@@ -251,7 +249,7 @@ LUA_API const char *lua_typename (lua_State *L, int t) { · 46 unmodified lines
251 249
252LUA_API int lua_iscfunction (lua_State *L, int idx) {250LUA_API int lua_iscfunction (lua_State *L, int idx) {
253 StkId o = index2addr(L, idx);251 StkId o = index2addr(L, idx);
254 return (ttislcf(o) || (ttisclosure(o) && clvalue(o)->c.isC));252 return (ttislcf(o) || (ttisCclosure(o)));
255}253}
256 254
257 255
@@ -278,20 +276,28 @@ LUA_API int lua_rawequal (lua_State *L, int index1, int index2) { · 20 unmodified lines
278 StkId o1 = index2addr(L, index1);276 StkId o1 = index2addr(L, index1);
279 StkId o2 = index2addr(L, index2);277 StkId o2 = index2addr(L, index2);
280 return (o1 == luaO_nilobject || o2 == luaO_nilobject) ? 0278 return (o1 == luaO_nilobject || o2 == luaO_nilobject) ? 0
281 : luaO_rawequalObj(o1, o2);279 : luaV_rawequalobj(o1, o2);
282}280}
283 281
284 282
285LUA_API void lua_arith (lua_State *L, int op) {283LUA_API void lua_arith (lua_State *L, int op) {
284 StkId o1; /* 1st operand */
285 StkId o2; /* 2nd operand */
286 lua_lock(L);286 lua_lock(L);
287 api_checknelems(L, 2);287 if (op != LUA_OPUNM) /* all other operations expect two operands */
288 if (ttisnumber(L->top - 2) && ttisnumber(L->top - 1)) {288 api_checknelems(L, 2);
289 changenvalue(L->top - 2,289 else { /* for unary minus, add fake 2nd operand */
290 luaO_arith(op, nvalue(L->top - 2), nvalue(L->top - 1)));290 api_checknelems(L, 1);
291 setobjs2s(L, L->top, L->top - 1);
292 L->top++;
293 }
294 o1 = L->top - 2;
295 o2 = L->top - 1;
296 if (ttisnumber(o1) && ttisnumber(o2)) {
297 changenvalue(o1, luaO_arith(op, nvalue(o1), nvalue(o2)));
291 }298 }
292 else299 else
293 luaV_arith(L, L->top - 2, L->top - 2, L->top - 1,300 luaV_arith(L, o1, o1, o2, cast(TMS, op - LUA_OPADD + TM_ADD));
294 cast(TMS, op - LUA_OPADD + TM_ADD));
295 L->top--;301 L->top--;
296 lua_unlock(L);302 lua_unlock(L);
297}303}
@@ -390,7 +396,7 @@ LUA_API const char *lua_tolstring (lua_State *L, int idx, size_t *len) { · 92 unmodified lines
390 396
391LUA_API size_t lua_rawlen (lua_State *L, int idx) {397LUA_API size_t lua_rawlen (lua_State *L, int idx) {
392 StkId o = index2addr(L, idx);398 StkId o = index2addr(L, idx);
393 switch (ttype(o)) {399 switch (ttypenv(o)) {
394 case LUA_TSTRING: return tsvalue(o)->len;400 case LUA_TSTRING: return tsvalue(o)->len;
395 case LUA_TUSERDATA: return uvalue(o)->len;401 case LUA_TUSERDATA: return uvalue(o)->len;
396 case LUA_TTABLE: return luaH_getn(hvalue(o));402 case LUA_TTABLE: return luaH_getn(hvalue(o));
@@ -402,15 +408,15 @@ LUA_API size_t lua_rawlen (lua_State *L, int idx) { · 5 unmodified lines
402LUA_API lua_CFunction lua_tocfunction (lua_State *L, int idx) {408LUA_API lua_CFunction lua_tocfunction (lua_State *L, int idx) {
403 StkId o = index2addr(L, idx);409 StkId o = index2addr(L, idx);
404 if (ttislcf(o)) return fvalue(o);410 if (ttislcf(o)) return fvalue(o);
405 else if (ttisclosure(o) && clvalue(o)->c.isC)411 else if (ttisCclosure(o))
406 return clvalue(o)->c.f;412 return clCvalue(o)->f;
407 else return NULL; /* not a C function */413 else return NULL; /* not a C function */
408}414}
409 415
410 416
411LUA_API void *lua_touserdata (lua_State *L, int idx) {417LUA_API void *lua_touserdata (lua_State *L, int idx) {
412 StkId o = index2addr(L, idx);418 StkId o = index2addr(L, idx);
413 switch (ttype(o)) {419 switch (ttypenv(o)) {
414 case LUA_TUSERDATA: return (rawuvalue(o) + 1);420 case LUA_TUSERDATA: return (rawuvalue(o) + 1);
415 case LUA_TLIGHTUSERDATA: return pvalue(o);421 case LUA_TLIGHTUSERDATA: return pvalue(o);
416 default: return NULL;422 default: return NULL;
@@ -428,7 +434,8 @@ LUA_API const void *lua_topointer (lua_State *L, int idx) { · 11 unmodified lines
428 StkId o = index2addr(L, idx);434 StkId o = index2addr(L, idx);
429 switch (ttype(o)) {435 switch (ttype(o)) {
430 case LUA_TTABLE: return hvalue(o);436 case LUA_TTABLE: return hvalue(o);
431 case LUA_TFUNCTION: return clvalue(o);437 case LUA_TLCL: return clLvalue(o);
438 case LUA_TCCL: return clCvalue(o);
432 case LUA_TLCF: return cast(void *, cast(size_t, fvalue(o)));439 case LUA_TLCF: return cast(void *, cast(size_t, fvalue(o)));
433 case LUA_TTHREAD: return thvalue(o);440 case LUA_TTHREAD: return thvalue(o);
434 case LUA_TUSERDATA:441 case LUA_TUSERDATA:
@@ -456,6 +463,8 @@ LUA_API void lua_pushnil (lua_State *L) { · 21 unmodified lines
456LUA_API void lua_pushnumber (lua_State *L, lua_Number n) {463LUA_API void lua_pushnumber (lua_State *L, lua_Number n) {
457 lua_lock(L);464 lua_lock(L);
458 setnvalue(L->top, n);465 setnvalue(L->top, n);
466 luai_checknum(L, L->top,
467 luaG_runerror(L, "C API - attempt to push a signaling NaN"));
459 api_incr_top(L);468 api_incr_top(L);
460 lua_unlock(L);469 lua_unlock(L);
461}470}
@@ -548,7 +557,7 @@ LUA_API void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n) { · 86 unmodified lines
548 L->top -= n;557 L->top -= n;
549 while (n--)558 while (n--)
550 setobj2n(L, &cl->c.upvalue[n], L->top + n);559 setobj2n(L, &cl->c.upvalue[n], L->top + n);
551 setclvalue(L, L->top, cl);560 setclCvalue(L, L->top, cl);
552 }561 }
553 api_incr_top(L);562 api_incr_top(L);
554 lua_unlock(L);563 lua_unlock(L);
@@ -648,7 +657,7 @@ LUA_API int lua_getmetatable (lua_State *L, int objindex) { · 93 unmodified lines
648 int res;657 int res;
649 lua_lock(L);658 lua_lock(L);
650 obj = index2addr(L, objindex);659 obj = index2addr(L, objindex);
651 switch (ttype(obj)) {660 switch (ttypenv(obj)) {
652 case LUA_TTABLE:661 case LUA_TTABLE:
653 mt = hvalue(obj)->metatable;662 mt = hvalue(obj)->metatable;
654 break;663 break;
@@ -755,18 +764,19 @@ LUA_API int lua_setmetatable (lua_State *L, int objindex) { · 100 unmodified lines
755 api_check(L, ttistable(L->top - 1), "table expected");764 api_check(L, ttistable(L->top - 1), "table expected");
756 mt = hvalue(L->top - 1);765 mt = hvalue(L->top - 1);
757 }766 }
758 switch (ttype(obj)) {767 switch (ttypenv(obj)) {
759 case LUA_TTABLE: {768 case LUA_TTABLE: {
760 hvalue(obj)->metatable = mt;769 hvalue(obj)->metatable = mt;
761 if (mt)770 if (mt)
762 luaC_objbarrierback(L, gcvalue(obj), mt);771 luaC_objbarrierback(L, gcvalue(obj), mt);
772 luaC_checkfinalizer(L, gcvalue(obj), mt);
763 break;773 break;
764 }774 }
765 case LUA_TUSERDATA: {775 case LUA_TUSERDATA: {
766 uvalue(obj)->metatable = mt;776 uvalue(obj)->metatable = mt;
767 if (mt) {777 if (mt) {
768 luaC_objbarrier(L, rawuvalue(obj), mt);778 luaC_objbarrier(L, rawuvalue(obj), mt);
769 luaC_checkfinalizer(L, rawuvalue(obj));779 luaC_checkfinalizer(L, gcvalue(obj), mt);
770 }780 }
771 break;781 break;
772 }782 }
@@ -912,15 +922,14 @@ LUA_API int lua_load (lua_State *L, lua_Reader reader, void *data, · 139 unmodified lines
912 luaZ_init(L, &z, reader, data);922 luaZ_init(L, &z, reader, data);
913 status = luaD_protectedparser(L, &z, chunkname);923 status = luaD_protectedparser(L, &z, chunkname);
914 if (status == LUA_OK) { /* no errors? */924 if (status == LUA_OK) { /* no errors? */
915 Closure *f = clvalue(L->top - 1); /* get newly created function */925 LClosure *f = clLvalue(L->top - 1); /* get newly created function */
916 lua_assert(!f->c.isC);926 if (f->nupvalues == 1) { /* does it have one upvalue? */
917 if (f->l.nupvalues == 1) { /* does it have one upvalue? */
918 /* get global table from registry */927 /* get global table from registry */
919 Table *reg = hvalue(&G(L)->l_registry);928 Table *reg = hvalue(&G(L)->l_registry);
920 const TValue *gt = luaH_getint(reg, LUA_RIDX_GLOBALS);929 const TValue *gt = luaH_getint(reg, LUA_RIDX_GLOBALS);
921 /* set global table as 1st upvalue of 'f' (may be LUA_ENV) */930 /* set global table as 1st upvalue of 'f' (may be LUA_ENV) */
922 setobj(L, f->l.upvals[0]->v, gt);931 setobj(L, f->upvals[0]->v, gt);
923 luaC_barrier(L, f->l.upvals[0], gt);932 luaC_barrier(L, f->upvals[0], gt);
924 }933 }
925 }934 }
926 lua_unlock(L);935 lua_unlock(L);
@@ -959,11 +968,12 @@ LUA_API int lua_gc (lua_State *L, int what, int data) { · 32 unmodified lines
959 g = G(L);968 g = G(L);
960 switch (what) {969 switch (what) {
961 case LUA_GCSTOP: {970 case LUA_GCSTOP: {
962 stopgc(g);971 g->gcrunning = 0;
963 break;972 break;
964 }973 }
965 case LUA_GCRESTART: {974 case LUA_GCRESTART: {
966 g->GCdebt = 0;975 luaE_setdebt(g, 0);
976 g->gcrunning = 1;
967 break;977 break;
968 }978 }
969 case LUA_GCCOLLECT: {979 case LUA_GCCOLLECT: {
@@ -972,30 +982,27 @@ LUA_API int lua_gc (lua_State *L, int what, int data) { · 2 unmodified lines
972 }982 }
973 case LUA_GCCOUNT: {983 case LUA_GCCOUNT: {
974 /* GC values are expressed in Kbytes: #bytes/2^10 */984 /* GC values are expressed in Kbytes: #bytes/2^10 */
975 res = cast_int(g->totalbytes >> 10);985 res = cast_int(gettotalbytes(g) >> 10);
976 break;986 break;
977 }987 }
978 case LUA_GCCOUNTB: {988 case LUA_GCCOUNTB: {
979 res = cast_int(g->totalbytes & 0x3ff);989 res = cast_int(gettotalbytes(g) & 0x3ff);
980 break;990 break;
981 }991 }
982 case LUA_GCSTEP: {992 case LUA_GCSTEP: {
983 int stopped = gcstopped(g);
984 if (g->gckind == KGC_GEN) { /* generational mode? */993 if (g->gckind == KGC_GEN) { /* generational mode? */
985 res = (g->lastmajormem == 0); /* 1 if will do major collection */994 res = (g->lastmajormem == 0); /* 1 if will do major collection */
986 luaC_step(L); /* do a single step */995 luaC_forcestep(L); /* do a single step */
987 }996 }
988 else {997 else {
989 while (data-- >= 0) {998 while (data-- >= 0) {
990 luaC_step(L);999 luaC_forcestep(L);
991 if (g->gcstate == GCSpause) { /* end of cycle? */1000 if (g->gcstate == GCSpause) { /* end of cycle? */
992 res = 1; /* signal it */1001 res = 1; /* signal it */
993 break;1002 break;
994 }1003 }
995 }1004 }
996 }1005 }
997 if (stopped) /* collector was stopped? */
998 stopgc(g); /* keep it that way */
999 break;1006 break;
1000 }1007 }
1001 case LUA_GCSETPAUSE: {1008 case LUA_GCSETPAUSE: {
@@ -1014,7 +1021,7 @@ LUA_API int lua_gc (lua_State *L, int what, int data) { · 12 unmodified lines
1014 break;1021 break;
1015 }1022 }
1016 case LUA_GCISRUNNING: {1023 case LUA_GCISRUNNING: {
1017 res = !gcstopped(g);1024 res = g->gcrunning;
1018 break;1025 break;
1019 }1026 }
1020 case LUA_GCGEN: { /* change collector to generational mode */1027 case LUA_GCGEN: { /* change collector to generational mode */
@@ -1124,25 +1131,27 @@ LUA_API void *lua_newuserdata (lua_State *L, size_t size) { · 103 unmodified lines
1124 1131
1125static const char *aux_upvalue (StkId fi, int n, TValue **val,1132static const char *aux_upvalue (StkId fi, int n, TValue **val,
1126 GCObject **owner) {1133 GCObject **owner) {
1127 Closure *f;1134 switch (ttype(fi)) {
1128 if (!ttisclosure(fi)) return NULL;1135 case LUA_TCCL: { /* C closure */
1129 f = clvalue(fi);1136 CClosure *f = clCvalue(fi);
1130 if (f->c.isC) {1137 if (!(1 <= n && n <= f->nupvalues)) return NULL;
1131 if (!(1 <= n && n <= f->c.nupvalues)) return NULL;1138 *val = &f->upvalue[n-1];
1132 *val = &f->c.upvalue[n-1];1139 if (owner) *owner = obj2gco(f);
1133 if (owner) *owner = obj2gco(f);1140 return "";
1134 return "";1141 }
1135 }1142 case LUA_TLCL: { /* Lua closure */
1136 else {1143 LClosure *f = clLvalue(fi);
1137 const char *name;1144 const char *name;
1138 Proto *p = f->l.p;1145 Proto *p = f->p;
1139 if (!(1 <= n && n <= p->sizeupvalues)) return NULL;1146 if (!(1 <= n && n <= p->sizeupvalues)) return NULL;
1140 *val = f->l.upvals[n-1]->v;1147 *val = f->upvals[n-1]->v;
1141 if (owner) *owner = obj2gco(f->l.upvals[n - 1]);1148 if (owner) *owner = obj2gco(f->upvals[n - 1]);
1142 name = getstr(p->upvalues[n-1].name);1149 name = getstr(p->upvalues[n-1].name);
1143 if (name == NULL) /* no debug information? */1150 if (name == NULL) /* no debug information? */
1144 name = "";1151 name = "";
1145 return name;1152 return name;
1153 }
1154 default: return NULL; /* not a closure */
1146 }1155 }
1147}1156}
1148 1157
@@ -1180,34 +1189,39 @@ LUA_API const char *lua_setupvalue (lua_State *L, int funcindex, int n) { · 31 unmodified lines
1180}1189}
1181 1190
1182 1191
1183static UpVal **getupvalref (lua_State *L, int fidx, int n, Closure **pf) {1192static UpVal **getupvalref (lua_State *L, int fidx, int n, LClosure **pf) {
1184 Closure *f;1193 LClosure *f;
1185 StkId fi = index2addr(L, fidx);1194 StkId fi = index2addr(L, fidx);
1186 api_check(L, ttisclosure(fi), "Lua function expected");1195 api_check(L, ttisLclosure(fi), "Lua function expected");
1187 f = clvalue(fi);1196 f = clLvalue(fi);
1188 api_check(L, !f->c.isC, "Lua function expected");1197 api_check(L, (1 <= n && n <= f->p->sizeupvalues), "invalid upvalue index");
1189 api_check(L, (1 <= n && n <= f->l.p->sizeupvalues), "invalid upvalue index");
1190 if (pf) *pf = f;1198 if (pf) *pf = f;
1191 return &f->l.upvals[n - 1]; /* get its upvalue pointer */1199 return &f->upvals[n - 1]; /* get its upvalue pointer */
1192}1200}
1193 1201
1194 1202
1195LUA_API void *lua_upvalueid (lua_State *L, int fidx, int n) {1203LUA_API void *lua_upvalueid (lua_State *L, int fidx, int n) {
1196 Closure *f;
1197 StkId fi = index2addr(L, fidx);1204 StkId fi = index2addr(L, fidx);
1198 api_check(L, ttisclosure(fi), "function expected");1205 switch (ttype(fi)) {
1199 f = clvalue(fi);1206 case LUA_TLCL: { /* lua closure */
1200 if (f->c.isC) {1207 return *getupvalref(L, fidx, n, NULL);
1201 api_check(L, 1 <= n && n <= f->c.nupvalues, "invalid upvalue index");1208 }
1202 return &f->c.upvalue[n - 1];1209 case LUA_TCCL: { /* C closure */
1210 CClosure *f = clCvalue(fi);
1211 api_check(L, 1 <= n && n <= f->nupvalues, "invalid upvalue index");
1212 return &f->upvalue[n - 1];
1213 }
1214 default: {
1215 api_check(L, 0, "closure expected");
1216 return NULL;
1217 }
1203 }1218 }
1204 else return *getupvalref(L, fidx, n, NULL);
1205}1219}
1206 1220
1207 1221
1208LUA_API void lua_upvaluejoin (lua_State *L, int fidx1, int n1,1222LUA_API void lua_upvaluejoin (lua_State *L, int fidx1, int n1,
1209 int fidx2, int n2) {1223 int fidx2, int n2) {
1210 Closure *f1;1224 LClosure *f1;
1211 UpVal **up1 = getupvalref(L, fidx1, n1, &f1);1225 UpVal **up1 = getupvalref(L, fidx1, n1, &f1);
1212 UpVal **up2 = getupvalref(L, fidx2, n2, NULL);1226 UpVal **up2 = getupvalref(L, fidx2, n2, NULL);
1213 *up1 = *up2;1227 *up1 = *up2;
src/lauxlib.c+77−13
@@ -1,5 +1,5 @@
1/*1/*
2** $Id: lauxlib.c,v 1.227 2010/11/10 18:05:36 roberto Exp $2** $Id: lauxlib.c,v 1.232 2011/05/03 16:01:57 roberto Exp $
3** Auxiliary functions for building Lua libraries3** Auxiliary functions for building Lua libraries
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -203,6 +203,64 @@ LUALIB_API int luaL_error (lua_State *L, const char *fmt, ...) { · 197 unmodified lines
203 return lua_error(L);203 return lua_error(L);
204}204}
205 205
206
207LUALIB_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_pushfstring(L, "%s", strerror(en));
219 lua_pushinteger(L, en);
220 return 3;
221 }
222}
223
224
225#if !defined(inspectstat) /* { */
226
227#if defined(LUA_USE_POSIX)
228
229#include <sys/wait.h>
230
231/*
232** use appropriate macros to interpret 'pclose' return status
233*/
234#define inspectstat(stat,what) \
235 if (WIFEXITED(stat)) { stat = WEXITSTATUS(stat); } \
236 else if (WIFSIGNALED(stat)) { stat = WTERMSIG(stat); what = "signal"; }
237
238#else
239
240#define inspectstat(stat,what) /* no op */
241
242#endif
243
244#endif /* } */
245
246
247LUALIB_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 return luaL_fileresult(L, 1, NULL);
255 else { /* return nil,what,code */
256 lua_pushnil(L);
257 lua_pushstring(L, what);
258 lua_pushinteger(L, stat);
259 return 3;
260 }
261 }
262}
263
206/* }====================================================== */264/* }====================================================== */
207 265
208 266
@@ -384,8 +442,10 @@ LUALIB_API char *luaL_prepbuffsize (luaL_Buffer *B, size_t sz) { · 175 unmodified lines
384 newsize = B->n + sz;442 newsize = B->n + sz;
385 if (newsize < B->n || newsize - B->n < sz)443 if (newsize < B->n || newsize - B->n < sz)
386 luaL_error(L, "buffer too large");444 luaL_error(L, "buffer too large");
387 newbuff = (char *)lua_newuserdata(L, newsize); /* create larger buffer */445 /* create larger buffer */
388 memcpy(newbuff, B->b, B->n); /* move content to new buffer */446 newbuff = (char *)lua_newuserdata(L, newsize * sizeof(char));
447 /* move content to new buffer */
448 memcpy(newbuff, B->b, B->n * sizeof(char));
389 if (buffonstack(B))449 if (buffonstack(B))
390 lua_remove(L, -2); /* remove old buffer */450 lua_remove(L, -2); /* remove old buffer */
391 B->b = newbuff;451 B->b = newbuff;
@@ -397,7 +457,7 @@ LUALIB_API char *luaL_prepbuffsize (luaL_Buffer *B, size_t sz) { · 5 unmodified lines
397 457
398LUALIB_API void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l) {458LUALIB_API void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l) {
399 char *b = luaL_prepbuffsize(B, l);459 char *b = luaL_prepbuffsize(B, l);
400 memcpy(b, s, l);460 memcpy(b, s, l * sizeof(char));
401 luaL_addsize(B, l);461 luaL_addsize(B, l);
402}462}
403 463
@@ -700,8 +760,8 @@ LUALIB_API const char *luaL_tolstring (lua_State *L, int idx, size_t *len) { · 296 unmodified lines
700*/760*/
701#if defined(LUA_COMPAT_MODULE)761#if defined(LUA_COMPAT_MODULE)
702 762
703static const char *luaL_findtablex (lua_State *L, int idx,763static const char *luaL_findtable (lua_State *L, int idx,
704 const char *fname, int szhint) {764 const char *fname, int szhint) {
705 const char *e;765 const char *e;
706 if (idx) lua_pushvalue(L, idx);766 if (idx) lua_pushvalue(L, idx);
707 do {767 do {
@@ -745,13 +805,13 @@ static int libsize (const luaL_Reg *l) { · 37 unmodified lines
745*/805*/
746LUALIB_API void luaL_pushmodule (lua_State *L, const char *modname,806LUALIB_API void luaL_pushmodule (lua_State *L, const char *modname,
747 int sizehint) {807 int sizehint) {
748 luaL_findtablex(L, LUA_REGISTRYINDEX, "_LOADED", 1); /* get _LOADED table */808 luaL_findtable(L, LUA_REGISTRYINDEX, "_LOADED", 1); /* get _LOADED table */
749 lua_getfield(L, -1, modname); /* get _LOADED[modname] */809 lua_getfield(L, -1, modname); /* get _LOADED[modname] */
750 if (!lua_istable(L, -1)) { /* not found? */810 if (!lua_istable(L, -1)) { /* not found? */
751 lua_pop(L, 1); /* remove previous result */811 lua_pop(L, 1); /* remove previous result */
752 /* try global variable (and create one if it does not exist) */812 /* try global variable (and create one if it does not exist) */
753 lua_pushglobaltable(L);813 lua_pushglobaltable(L);
754 if (luaL_findtablex(L, 0, modname, sizehint) != NULL)814 if (luaL_findtable(L, 0, modname, sizehint) != NULL)
755 luaL_error(L, "name conflict for module " LUA_QS, modname);815 luaL_error(L, "name conflict for module " LUA_QS, modname);
756 lua_pushvalue(L, -1);816 lua_pushvalue(L, -1);
757 lua_setfield(L, -3, modname); /* _LOADED[modname] = new table */817 lua_setfield(L, -3, modname); /* _LOADED[modname] = new table */
@@ -767,7 +827,10 @@ LUALIB_API void luaL_openlib (lua_State *L, const char *libname, · 9 unmodified lines
767 luaL_pushmodule(L, libname, libsize(l)); /* get/create library table */827 luaL_pushmodule(L, libname, libsize(l)); /* get/create library table */
768 lua_insert(L, -(nup + 1)); /* move library table to below upvalues */828 lua_insert(L, -(nup + 1)); /* move library table to below upvalues */
769 }829 }
770 luaL_setfuncs(L, l, nup);830 if (l)
831 luaL_setfuncs(L, l, nup);
832 else
833 lua_pop(L, nup); /* remove upvalues */
771}834}
772 835
773#endif836#endif
@@ -780,7 +843,7 @@ LUALIB_API void luaL_openlib (lua_State *L, const char *libname, · 6 unmodified lines
780*/843*/
781LUALIB_API void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup) {844LUALIB_API void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup) {
782 luaL_checkstack(L, nup, "too many upvalues");845 luaL_checkstack(L, nup, "too many upvalues");
783 for (; l && l->name; l++) { /* fill the table with given functions */846 for (; l->name != NULL; l++) { /* fill the table with given functions */
784 int i;847 int i;
785 for (i = 0; i < nup; i++) /* copy upvalues to the top */848 for (i = 0; i < nup; i++) /* copy upvalues to the top */
786 lua_pushvalue(L, -nup);849 lua_pushvalue(L, -nup);
@@ -795,15 +858,16 @@ LUALIB_API void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup) { · 8 unmodified lines
795** ensure that stack[idx][fname] has a table and push that table858** ensure that stack[idx][fname] has a table and push that table
796** into the stack859** into the stack
797*/860*/
798LUALIB_API void luaL_findtable (lua_State *L, int idx, const char *fname) {861LUALIB_API int luaL_getsubtable (lua_State *L, int idx, const char *fname) {
799 lua_getfield(L, idx, fname);862 lua_getfield(L, idx, fname);
800 if (lua_istable(L, -1)) return; /* table already there */863 if (lua_istable(L, -1)) return 1; /* table already there */
801 else {864 else {
802 idx = lua_absindex(L, idx);865 idx = lua_absindex(L, idx);
803 lua_pop(L, 1); /* remove previous result */866 lua_pop(L, 1); /* remove previous result */
804 lua_newtable(L);867 lua_newtable(L);
805 lua_pushvalue(L, -1); /* copy to be left at top */868 lua_pushvalue(L, -1); /* copy to be left at top */
806 lua_setfield(L, idx, fname); /* assign new table to field */869 lua_setfield(L, idx, fname); /* assign new table to field */
870 return 0; /* false, because did not find table there */
807 }871 }
808}872}
809 873
@@ -819,7 +883,7 @@ LUALIB_API void luaL_requiref (lua_State *L, const char *modname, · 9 unmodified lines
819 lua_pushcfunction(L, openf);883 lua_pushcfunction(L, openf);
820 lua_pushstring(L, modname); /* argument to open function */884 lua_pushstring(L, modname); /* argument to open function */
821 lua_call(L, 1, 1); /* open module */885 lua_call(L, 1, 1); /* open module */
822 luaL_findtable(L, LUA_REGISTRYINDEX, "_LOADED");886 luaL_getsubtable(L, LUA_REGISTRYINDEX, "_LOADED");
823 lua_pushvalue(L, -2); /* make copy of module (call result) */887 lua_pushvalue(L, -2); /* make copy of module (call result) */
824 lua_setfield(L, -2, modname); /* _LOADED[modname] = module */888 lua_setfield(L, -2, modname); /* _LOADED[modname] = module */
825 lua_pop(L, 1); /* remove _LOADED table */889 lua_pop(L, 1); /* remove _LOADED table */
src/lauxlib.h+5−2
@@ -1,5 +1,5 @@
1/*1/*
2** $Id: lauxlib.h,v 1.113 2010/11/16 19:20:01 roberto Exp $2** $Id: lauxlib.h,v 1.116 2011/04/08 19:17:36 roberto Exp $
3** Auxiliary functions for building Lua libraries3** Auxiliary functions for building Lua libraries
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -62,6 +62,9 @@ LUALIB_API int (luaL_error) (lua_State *L, const char *fmt, ...); · 56 unmodified lines
62LUALIB_API int (luaL_checkoption) (lua_State *L, int narg, const char *def,62LUALIB_API int (luaL_checkoption) (lua_State *L, int narg, const char *def,
63 const char *const lst[]);63 const char *const lst[]);
64 64
65LUALIB_API int (luaL_fileresult) (lua_State *L, int stat, const char *fname);
66LUALIB_API int (luaL_execresult) (lua_State *L, int stat);
67
65/* pre-defined references */68/* pre-defined references */
66#define LUA_NOREF (-2)69#define LUA_NOREF (-2)
67#define LUA_REFNIL (-1)70#define LUA_REFNIL (-1)
@@ -83,7 +86,7 @@ LUALIB_API const char *(luaL_gsub) (lua_State *L, const char *s, const char *p, · 15 unmodified lines
83 86
84LUALIB_API void (luaL_setfuncs) (lua_State *L, const luaL_Reg *l, int nup);87LUALIB_API void (luaL_setfuncs) (lua_State *L, const luaL_Reg *l, int nup);
85 88
86LUALIB_API void (luaL_findtable) (lua_State *L, int idx, const char *fname);89LUALIB_API int (luaL_getsubtable) (lua_State *L, int idx, const char *fname);
87 90
88LUALIB_API void (luaL_traceback) (lua_State *L, lua_State *L1,91LUALIB_API void (luaL_traceback) (lua_State *L, lua_State *L1,
89 const char *msg, int level);92 const char *msg, int level);
src/lbaselib.c+76−108
@@ -1,5 +1,5 @@
1/*1/*
2** $Id: lbaselib.c,v 1.251 2010/10/28 15:36:30 roberto Exp $2** $Id: lbaselib.c,v 1.261 2011/05/26 16:09:40 roberto Exp $
3** Basic library3** Basic library
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -32,44 +32,54 @@ static int luaB_print (lua_State *L) { · 26 unmodified lines
32 lua_call(L, 1, 1);32 lua_call(L, 1, 1);
33 s = lua_tolstring(L, -1, &l); /* get result */33 s = lua_tolstring(L, -1, &l); /* get result */
34 if (s == NULL)34 if (s == NULL)
35 return luaL_error(L, LUA_QL("tostring") " must return a string to "35 return luaL_error(L,
36 LUA_QL("print"));36 LUA_QL("tostring") " must return a string to " LUA_QL("print"));
37 if (i>1) luai_writestring("\t", 1);37 if (i>1) luai_writestring("\t", 1);
38 luai_writestring(s, l);38 luai_writestring(s, l);
39 lua_pop(L, 1); /* pop result */39 lua_pop(L, 1); /* pop result */
40 }40 }
41 luai_writestring("\n", 1);41 luai_writeline();
42 return 0;42 return 0;
43}43}
44 44
45 45
46#define SPACECHARS " \f\n\r\t\v"
47
46static int luaB_tonumber (lua_State *L) {48static int luaB_tonumber (lua_State *L) {
47 int base = luaL_optint(L, 2, 10);49 int base = luaL_optint(L, 2, 10);
50 luaL_argcheck(L, 2 <= base && base <= 36, 2, "base out of range");
48 if (base == 10) { /* standard conversion */51 if (base == 10) { /* standard conversion */
49 luaL_checkany(L, 1);52 luaL_checkany(L, 1);
50 if (lua_isnumber(L, 1)) {53 if (lua_isnumber(L, 1)) {
51 lua_pushnumber(L, lua_tonumber(L, 1));54 lua_pushnumber(L, lua_tonumber(L, 1));
52 return 1;55 return 1;
53 }56 } /* else not a number */
54 }57 }
55 else {58 else {
56 const char *s1 = luaL_checkstring(L, 1);59 size_t l;
57 char *s2;60 const char *s = luaL_checklstring(L, 1, &l);
58 unsigned long n;61 const char *e = s + l; /* end point for 's' */
59 int neg = 0;62 int neg = 0;
60 luaL_argcheck(L, 2 <= base && base <= 36, 2, "base out of range");63 s += strspn(s, SPACECHARS); /* skip initial spaces */
61 while (isspace((unsigned char)(*s1))) s1++; /* skip initial spaces */64 if (*s == '-') { s++; neg = 1; } /* handle signal */
62 if (*s1 == '-') { s1++; neg = 1; }65 else if (*s == '+') s++;
63 n = strtoul(s1, &s2, base);66 if (isalnum((unsigned char)*s)) {
64 if (s1 != s2) { /* at least one valid digit? */67 lua_Number n = 0;
65 while (isspace((unsigned char)(*s2))) s2++; /* skip trailing spaces */68 do {
66 if (*s2 == '\0') { /* no invalid trailing characters? */69 int digit = (isdigit((unsigned char)*s)) ? *s - '0'
67 lua_pushnumber(L, (neg) ? -(lua_Number)n : (lua_Number)n);70 : toupper((unsigned char)*s) - 'A' + 10;
71 if (digit >= base) break; /* invalid numeral; force a fail */
72 n = n * (lua_Number)base + (lua_Number)digit;
73 s++;
74 } while (isalnum((unsigned char)*s));
75 s += strspn(s, SPACECHARS); /* skip trailing spaces */
76 if (s == e) { /* no invalid trailing characters? */
77 lua_pushnumber(L, (neg) ? -n : n);
68 return 1;78 return 1;
69 }79 } /* else not a number */
70 }80 } /* else not a number */
71 }81 }
72 lua_pushnil(L); /* else not a number */82 lua_pushnil(L); /* not a number */
73 return 1;83 return 1;
74}84}
75 85
@@ -110,12 +120,10 @@ static int luaB_setmetatable (lua_State *L) { · 34 unmodified lines
110}120}
111 121
112 122
113static int luaB_getfenv (lua_State *L) {123static int luaB_deprecated (lua_State *L) {
114 return luaL_error(L, "getfenv/setfenv deprecated");124 return luaL_error(L, "deprecated function");
115}125}
116 126
117#define luaB_setfenv luaB_getfenv
118
119 127
120static int luaB_rawequal (lua_State *L) {128static int luaB_rawequal (lua_State *L) {
121 luaL_checkany(L, 1);129 luaL_checkany(L, 1);
@@ -125,6 +133,15 @@ static int luaB_rawequal (lua_State *L) { · 3 unmodified lines
125}133}
126 134
127 135
136static int luaB_rawlen (lua_State *L) {
137 int t = lua_type(L, 1);
138 luaL_argcheck(L, t == LUA_TTABLE || t == LUA_TSTRING, 1,
139 "table or string expected");
140 lua_pushinteger(L, lua_rawlen(L, 1));
141 return 1;
142}
143
144
128static int luaB_rawget (lua_State *L) {145static int luaB_rawget (lua_State *L) {
129 luaL_checktype(L, 1, LUA_TTABLE);146 luaL_checktype(L, 1, LUA_TTABLE);
130 luaL_checkany(L, 2);147 luaL_checkany(L, 2);
@@ -251,6 +268,11 @@ static int luaB_loadfile (lua_State *L) { · 120 unmodified lines
251** =======================================================268** =======================================================
252*/269*/
253 270
271/*
272** check whether a chunk (prefix in 's') satisfies given 'mode'
273** ('t' for text, 'b' for binary). Returns error message (also
274** pushed on the stack) in case of errors.
275*/
254static const char *checkrights (lua_State *L, const char *mode, const char *s) {276static const char *checkrights (lua_State *L, const char *mode, const char *s) {
255 if (strchr(mode, 'b') == NULL && *s == LUA_SIGNATURE[0])277 if (strchr(mode, 'b') == NULL && *s == LUA_SIGNATURE[0])
256 return lua_pushstring(L, "attempt to load a binary chunk");278 return lua_pushstring(L, "attempt to load a binary chunk");
@@ -261,10 +283,11 @@ static const char *checkrights (lua_State *L, const char *mode, const char *s) { · 4 unmodified lines
261 283
262 284
263/*285/*
264** reserves a slot, above all arguments, to hold a copy of the returned286** reserved slot, above all arguments, to hold a copy of the returned
265** string to avoid it being collected while parsed287** string to avoid it being collected while parsed. 'load' has four
288** optional arguments (chunk, source name, mode, and environment).
266*/289*/
267#define RESERVEDSLOT 4290#define RESERVEDSLOT 5
268 291
269 292
270/*293/*
@@ -273,25 +296,20 @@ static const char *checkrights (lua_State *L, const char *mode, const char *s) { · 2 unmodified lines
273** stack top. Instead, it keeps its resulting string in a296** stack top. Instead, it keeps its resulting string in a
274** reserved slot inside the stack.297** reserved slot inside the stack.
275*/298*/
276typedef struct { /* reader state */
277 int f; /* position of reader function on stack */
278 const char *mode; /* allowed modes (binary/text) */
279} Readstat;
280
281static const char *generic_reader (lua_State *L, void *ud, size_t *size) {299static const char *generic_reader (lua_State *L, void *ud, size_t *size) {
282 const char *s;300 const char *s;
283 Readstat *stat = (Readstat *)ud;301 const char **mode = (const char **)ud;
284 luaL_checkstack(L, 2, "too many nested functions");302 luaL_checkstack(L, 2, "too many nested functions");
285 lua_pushvalue(L, stat->f); /* get function */303 lua_pushvalue(L, 1); /* get function */
286 lua_call(L, 0, 1); /* call it */304 lua_call(L, 0, 1); /* call it */
287 if (lua_isnil(L, -1)) {305 if (lua_isnil(L, -1)) {
288 *size = 0;306 *size = 0;
289 return NULL;307 return NULL;
290 }308 }
291 else if ((s = lua_tostring(L, -1)) != NULL) {309 else if ((s = lua_tostring(L, -1)) != NULL) {
292 if (stat->mode != NULL) { /* first time? */310 if (*mode != NULL) { /* first time? */
293 s = checkrights(L, stat->mode, s); /* check mode */311 s = checkrights(L, *mode, s); /* check mode */
294 stat->mode = NULL; /* to avoid further checks */312 *mode = NULL; /* to avoid further checks */
295 if (s) luaL_error(L, s);313 if (s) luaL_error(L, s);
296 }314 }
297 lua_replace(L, RESERVEDSLOT); /* save string in reserved slot */315 lua_replace(L, RESERVEDSLOT); /* save string in reserved slot */
@@ -304,52 +322,38 @@ static const char *generic_reader (lua_State *L, void *ud, size_t *size) { · 6 unmodified lines
304}322}
305 323
306 324
307static int luaB_load_aux (lua_State *L, int farg) {325static int luaB_load (lua_State *L) {
308 int status;326 int status;
309 Readstat stat;
310 size_t l;327 size_t l;
311 const char *s = lua_tolstring(L, farg, &l);328 int top = lua_gettop(L);
312 stat.mode = luaL_optstring(L, farg + 2, "bt");329 const char *s = lua_tolstring(L, 1, &l);
330 const char *mode = luaL_optstring(L, 3, "bt");
313 if (s != NULL) { /* loading a string? */331 if (s != NULL) { /* loading a string? */
314 const char *chunkname = luaL_optstring(L, farg + 1, s);332 const char *chunkname = luaL_optstring(L, 2, s);
315 status = (checkrights(L, stat.mode, s) != NULL)333 status = (checkrights(L, mode, s) != NULL)
316 || luaL_loadbuffer(L, s, l, chunkname);334 || luaL_loadbuffer(L, s, l, chunkname);
317 }335 }
318 else { /* loading from a reader function */336 else { /* loading from a reader function */
319 const char *chunkname = luaL_optstring(L, farg + 1, "=(load)");337 const char *chunkname = luaL_optstring(L, 2, "=(load)");
320 luaL_checktype(L, farg, LUA_TFUNCTION);338 luaL_checktype(L, 1, LUA_TFUNCTION);
321 stat.f = farg;
322 lua_settop(L, RESERVEDSLOT); /* create reserved slot */339 lua_settop(L, RESERVEDSLOT); /* create reserved slot */
323 status = lua_load(L, generic_reader, &stat, chunkname);340 status = lua_load(L, generic_reader, &mode, chunkname);
341 }
342 if (status == LUA_OK && top >= 4) { /* is there an 'env' argument */
343 lua_pushvalue(L, 4); /* environment for loaded function */
344 lua_setupvalue(L, -2, 1); /* set it as 1st upvalue */
324 }345 }
325 return load_aux(L, status);346 return load_aux(L, status);
326}347}
327 348
328 349
329static int luaB_load (lua_State *L) {350#if defined(LUA_COMPAT_LOADSTRING)
330 return luaB_load_aux(L, 1);351#define luaB_loadstring luaB_load
331}352#else
332 353#define luaB_loadstring luaB_deprecated
333 354#endif
334static int luaB_loadin (lua_State *L) {
335 int n;
336 luaL_checkany(L, 1);
337 n = luaB_load_aux(L, 2);
338 if (n == 1) { /* success? */
339 lua_pushvalue(L, 1); /* environment for loaded function */
340 if (lua_setupvalue(L, -2, 1) == NULL)
341 luaL_error(L, "loaded chunk does not have an upvalue");
342 }
343 return n;
344}
345 355
346 356
347static int luaB_loadstring (lua_State *L) {
348 lua_settop(L, 2);
349 lua_pushliteral(L, "tb");
350 return luaB_load(L); /* dostring(s, n) == load(s, n, "tb") */
351
352}
353/* }====================================================== */357/* }====================================================== */
354 358
355 359
@@ -391,7 +395,7 @@ static int luaB_select (lua_State *L) { · 35 unmodified lines
391 395
392 396
393static int pcallcont (lua_State *L) {397static int pcallcont (lua_State *L) {
394 int errfunc; /* call has an error function in bottom of the stack */398 int errfunc = 0; /* =0 to avoid warnings */
395 int status = lua_getctx(L, &errfunc);399 int status = lua_getctx(L, &errfunc);
396 lua_assert(status != LUA_OK);400 lua_assert(status != LUA_OK);
397 lua_pushboolean(L, (status == LUA_YIELD)); /* first result (status) */401 lua_pushboolean(L, (status == LUA_YIELD)); /* first result (status) */
@@ -436,55 +440,27 @@ static int luaB_tostring (lua_State *L) { · 38 unmodified lines
436}440}
437 441
438 442
439static int luaB_newproxy (lua_State *L) {
440 lua_settop(L, 1);
441 lua_newuserdata(L, 0); /* create proxy */
442 if (lua_toboolean(L, 1) == 0)
443 return 1; /* no metatable */
444 else if (lua_isboolean(L, 1)) {
445 lua_createtable(L, 0, 1); /* create a new metatable `m' ... */
446 lua_pushboolean(L, 1);
447 lua_setfield(L, -2, "__gc"); /* ... m.__gc = false (HACK!!)... */
448 lua_pushvalue(L, -1); /* ... and mark `m' as a valid metatable */
449 lua_pushboolean(L, 1);
450 lua_rawset(L, lua_upvalueindex(1)); /* weaktable[m] = true */
451 }
452 else {
453 int validproxy = 0; /* to check if weaktable[metatable(u)] == true */
454 if (lua_getmetatable(L, 1)) {
455 lua_rawget(L, lua_upvalueindex(1));
456 validproxy = lua_toboolean(L, -1);
457 lua_pop(L, 1); /* remove value */
458 }
459 luaL_argcheck(L, validproxy, 1, "boolean or proxy expected");
460 lua_getmetatable(L, 1); /* metatable is valid; get it */
461 }
462 lua_setmetatable(L, 2);
463 return 1;
464}
465
466
467static const luaL_Reg base_funcs[] = {443static const luaL_Reg base_funcs[] = {
468 {"assert", luaB_assert},444 {"assert", luaB_assert},
469 {"collectgarbage", luaB_collectgarbage},445 {"collectgarbage", luaB_collectgarbage},
470 {"dofile", luaB_dofile},446 {"dofile", luaB_dofile},
471 {"error", luaB_error},447 {"error", luaB_error},
472 {"getfenv", luaB_getfenv},448 {"getfenv", luaB_deprecated},
473 {"getmetatable", luaB_getmetatable},449 {"getmetatable", luaB_getmetatable},
474 {"ipairs", luaB_ipairs},450 {"ipairs", luaB_ipairs},
475 {"loadfile", luaB_loadfile},451 {"loadfile", luaB_loadfile},
476 {"load", luaB_load},452 {"load", luaB_load},
477 {"loadin", luaB_loadin},
478 {"loadstring", luaB_loadstring},453 {"loadstring", luaB_loadstring},
479 {"next", luaB_next},454 {"next", luaB_next},
480 {"pairs", luaB_pairs},455 {"pairs", luaB_pairs},
481 {"pcall", luaB_pcall},456 {"pcall", luaB_pcall},
482 {"print", luaB_print},457 {"print", luaB_print},
483 {"rawequal", luaB_rawequal},458 {"rawequal", luaB_rawequal},
459 {"rawlen", luaB_rawlen},
484 {"rawget", luaB_rawget},460 {"rawget", luaB_rawget},
485 {"rawset", luaB_rawset},461 {"rawset", luaB_rawset},
486 {"select", luaB_select},462 {"select", luaB_select},
487 {"setfenv", luaB_setfenv},463 {"setfenv", luaB_deprecated},
488 {"setmetatable", luaB_setmetatable},464 {"setmetatable", luaB_setmetatable},
489 {"tonumber", luaB_tonumber},465 {"tonumber", luaB_tonumber},
490 {"tostring", luaB_tostring},466 {"tostring", luaB_tostring},
@@ -503,14 +479,6 @@ LUAMOD_API int luaopen_base (lua_State *L) { · 12 unmodified lines
503 luaL_setfuncs(L, base_funcs, 0);479 luaL_setfuncs(L, base_funcs, 0);
504 lua_pushliteral(L, LUA_VERSION);480 lua_pushliteral(L, LUA_VERSION);
505 lua_setfield(L, -2, "_VERSION"); /* set global _VERSION */481 lua_setfield(L, -2, "_VERSION"); /* set global _VERSION */
506 /* `newproxy' needs a weaktable as upvalue */
507 lua_createtable(L, 0, 1); /* new table `w' */
508 lua_pushvalue(L, -1); /* `w' will be its own metatable */
509 lua_setmetatable(L, -2);
510 lua_pushliteral(L, "kv");
511 lua_setfield(L, -2, "__mode"); /* metatable(w).__mode = "kv" */
512 lua_pushcclosure(L, luaB_newproxy, 1);
513 lua_setfield(L, -2, "newproxy"); /* set global `newproxy' */
514 return 1;482 return 1;
515}483}
516 484
src/lbitlib.c+67−21
@@ -1,5 +1,5 @@
1/*1/*
2** $Id: lbitlib.c,v 1.13 2010/11/22 18:06:33 roberto Exp $2** $Id: lbitlib.c,v 1.15 2010/12/17 13:26:38 roberto Exp $
3** Standard library for bitwise operations3** Standard library for bitwise operations
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -14,25 +14,30 @@ · 8 unmodified lines
14 14
15 15
16/* number of bits to consider in a number */16/* number of bits to consider in a number */
17#define NBITS 3217#if !defined(LUA_NBITS)
18#define LUA_NBITS 32
19#endif
18 20
19#define ALLONES (~(((~(lua_Unsigned)0) << (NBITS - 1)) << 1))
20 21
21/* mask to trim extra bits */22#define ALLONES (~(((~(lua_Unsigned)0) << (LUA_NBITS - 1)) << 1))
23
24/* macro to trim extra bits */
22#define trim(x) ((x) & ALLONES)25#define trim(x) ((x) & ALLONES)
23 26
24 27
25typedef lua_Unsigned b_uint;28/* builds a number with 'n' ones (1 <= n <= LUA_NBITS) */
29#define mask(n) (~((ALLONES << 1) << ((n) - 1)))
30
26 31
32typedef lua_Unsigned b_uint;
27 33
28#define getuintarg(L,arg) luaL_checkunsigned(L,arg)
29 34
30 35
31static b_uint andaux (lua_State *L) {36static b_uint andaux (lua_State *L) {
32 int i, n = lua_gettop(L);37 int i, n = lua_gettop(L);
33 b_uint r = ~(b_uint)0;38 b_uint r = ~(b_uint)0;
34 for (i = 1; i <= n; i++)39 for (i = 1; i <= n; i++)
35 r &= getuintarg(L, i);40 r &= luaL_checkunsigned(L, i);
36 return trim(r);41 return trim(r);
37}42}
38 43
@@ -55,7 +60,7 @@ static int b_or (lua_State *L) { · 16 unmodified lines
55 int i, n = lua_gettop(L);60 int i, n = lua_gettop(L);
56 b_uint r = 0;61 b_uint r = 0;
57 for (i = 1; i <= n; i++)62 for (i = 1; i <= n; i++)
58 r |= getuintarg(L, i);63 r |= luaL_checkunsigned(L, i);
59 lua_pushunsigned(L, trim(r));64 lua_pushunsigned(L, trim(r));
60 return 1;65 return 1;
61}66}
@@ -65,14 +70,14 @@ static int b_xor (lua_State *L) { · 3 unmodified lines
65 int i, n = lua_gettop(L);70 int i, n = lua_gettop(L);
66 b_uint r = 0;71 b_uint r = 0;
67 for (i = 1; i <= n; i++)72 for (i = 1; i <= n; i++)
68 r ^= getuintarg(L, i);73 r ^= luaL_checkunsigned(L, i);
69 lua_pushunsigned(L, trim(r));74 lua_pushunsigned(L, trim(r));
70 return 1;75 return 1;
71}76}
72 77
73 78
74static int b_not (lua_State *L) {79static int b_not (lua_State *L) {
75 b_uint r = ~getuintarg(L, 1);80 b_uint r = ~luaL_checkunsigned(L, 1);
76 lua_pushunsigned(L, trim(r));81 lua_pushunsigned(L, trim(r));
77 return 1;82 return 1;
78}83}
@@ -82,11 +87,11 @@ static int b_shift (lua_State *L, b_uint r, int i) { · 3 unmodified lines
82 if (i < 0) { /* shift right? */87 if (i < 0) { /* shift right? */
83 i = -i;88 i = -i;
84 r = trim(r);89 r = trim(r);
85 if (i >= NBITS) r = 0;90 if (i >= LUA_NBITS) r = 0;
86 else r >>= i;91 else r >>= i;
87 }92 }
88 else { /* shift left */93 else { /* shift left */
89 if (i >= NBITS) r = 0;94 if (i >= LUA_NBITS) r = 0;
90 else r <<= i;95 else r <<= i;
91 r = trim(r);96 r = trim(r);
92 }97 }
@@ -96,22 +101,22 @@ static int b_shift (lua_State *L, b_uint r, int i) { · 3 unmodified lines
96 101
97 102
98static int b_lshift (lua_State *L) {103static int b_lshift (lua_State *L) {
99 return b_shift(L, getuintarg(L, 1), luaL_checkint(L, 2));104 return b_shift(L, luaL_checkunsigned(L, 1), luaL_checkint(L, 2));
100}105}
101 106
102 107
103static int b_rshift (lua_State *L) {108static int b_rshift (lua_State *L) {
104 return b_shift(L, getuintarg(L, 1), -luaL_checkint(L, 2));109 return b_shift(L, luaL_checkunsigned(L, 1), -luaL_checkint(L, 2));
105}110}
106 111
107 112
108static int b_arshift (lua_State *L) {113static int b_arshift (lua_State *L) {
109 b_uint r = getuintarg(L, 1);114 b_uint r = luaL_checkunsigned(L, 1);
110 int i = luaL_checkint(L, 2);115 int i = luaL_checkint(L, 2);
111 if (i < 0 || !(r & ((b_uint)1 << (NBITS - 1))))116 if (i < 0 || !(r & ((b_uint)1 << (LUA_NBITS - 1))))
112 return b_shift(L, r, -i);117 return b_shift(L, r, -i);
113 else { /* arithmetic shift for 'negative' number */118 else { /* arithmetic shift for 'negative' number */
114 if (i >= NBITS) r = ALLONES;119 if (i >= LUA_NBITS) r = ALLONES;
115 else120 else
116 r = trim((r >> i) | ~(~(b_uint)0 >> i)); /* add signal bit */121 r = trim((r >> i) | ~(~(b_uint)0 >> i)); /* add signal bit */
117 lua_pushunsigned(L, r);122 lua_pushunsigned(L, r);
@@ -121,10 +126,10 @@ static int b_arshift (lua_State *L) { · 3 unmodified lines
121 126
122 127
123static int b_rot (lua_State *L, int i) {128static int b_rot (lua_State *L, int i) {
124 b_uint r = getuintarg(L, 1);129 b_uint r = luaL_checkunsigned(L, 1);
125 i &= (NBITS - 1); /* i = i % NBITS */130 i &= (LUA_NBITS - 1); /* i = i % NBITS */
126 r = trim(r);131 r = trim(r);
127 r = (r << i) | (r >> (NBITS - i));132 r = (r << i) | (r >> (LUA_NBITS - i));
128 lua_pushunsigned(L, trim(r));133 lua_pushunsigned(L, trim(r));
129 return 1;134 return 1;
130}135}
@@ -140,17 +145,58 @@ static int b_rrot (lua_State *L) { · 9 unmodified lines
140}145}
141 146
142 147
148/*
149** get field and width arguments for field-manipulation functions,
150** checking whether they are valid
151*/
152static int fieldargs (lua_State *L, int farg, int *width) {
153 int f = luaL_checkint(L, farg);
154 int w = luaL_optint(L, farg + 1, 1);
155 luaL_argcheck(L, 0 <= f, farg, "field cannot be netative");
156 luaL_argcheck(L, 0 < w, farg + 1, "width must be positive");
157 if (f + w > LUA_NBITS)
158 luaL_error(L, "trying to access non-existent bits");
159 *width = w;
160 return f;
161}
162
163
164static int b_extract (lua_State *L) {
165 int w;
166 b_uint r = luaL_checkunsigned(L, 1);
167 int f = fieldargs(L, 2, &w);
168 r = (r >> f) & mask(w);
169 lua_pushunsigned(L, r);
170 return 1;
171}
172
173
174static int b_replace (lua_State *L) {
175 int w;
176 b_uint r = luaL_checkunsigned(L, 1);
177 b_uint v = luaL_checkunsigned(L, 2);
178 int f = fieldargs(L, 3, &w);
179 int m = mask(w);
180 v &= m; /* erase bits outside given width */
181 r = (r & ~(m << f)) | (v << f);
182 lua_pushunsigned(L, r);
183 return 1;
184}
185
186
143static const luaL_Reg bitlib[] = {187static const luaL_Reg bitlib[] = {
144 {"arshift", b_arshift},188 {"arshift", b_arshift},
145 {"band", b_and},189 {"band", b_and},
146 {"bnot", b_not},190 {"bnot", b_not},
147 {"bor", b_or},191 {"bor", b_or},
148 {"bxor", b_xor},192 {"bxor", b_xor},
193 {"btest", b_test},
194 {"extract", b_extract},
149 {"lrotate", b_lrot},195 {"lrotate", b_lrot},
150 {"lshift", b_lshift},196 {"lshift", b_lshift},
197 {"replace", b_replace},
151 {"rrotate", b_rrot},198 {"rrotate", b_rrot},
152 {"rshift", b_rshift},199 {"rshift", b_rshift},
153 {"btest", b_test},
154 {NULL, NULL}200 {NULL, NULL}
155};201};
156 202
src/lcode.c+42−38
@@ -1,5 +1,5 @@
1/*1/*
2** $Id: lcode.c,v 2.49 2010/07/07 16:27:29 roberto Exp $2** $Id: lcode.c,v 2.56 2011/05/31 18:27:56 roberto Exp $
3** Code generator for Lua3** Code generator for Lua
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -23,6 +23,7 @@ · 17 unmodified lines
23#include "lparser.h"23#include "lparser.h"
24#include "lstring.h"24#include "lstring.h"
25#include "ltable.h"25#include "ltable.h"
26#include "lvm.h"
26 27
27 28
28#define hasjumps(e) ((e)->t != (e)->f)29#define hasjumps(e) ((e)->t != (e)->f)
@@ -35,19 +36,23 @@ static int isnumeral(expdesc *e) { · 6 unmodified lines
35 36
36void luaK_nil (FuncState *fs, int from, int n) {37void luaK_nil (FuncState *fs, int from, int n) {
37 Instruction *previous;38 Instruction *previous;
39 int l = from + n - 1; /* last register to set nil */
38 if (fs->pc > fs->lasttarget) { /* no jumps to current position? */40 if (fs->pc > fs->lasttarget) { /* no jumps to current position? */
39 previous = &fs->f->code[fs->pc-1];41 previous = &fs->f->code[fs->pc-1];
40 if (GET_OPCODE(*previous) == OP_LOADNIL) {42 if (GET_OPCODE(*previous) == OP_LOADNIL) {
41 int pfrom = GETARG_A(*previous);43 int pfrom = GETARG_A(*previous);
42 int pto = GETARG_B(*previous);44 int pl = pfrom + GETARG_B(*previous);
43 if (pfrom <= from && from <= pto+1) { /* can connect both? */45 if ((pfrom <= from && from <= pl + 1) ||
44 if (from+n-1 > pto)46 (from <= pfrom && pfrom <= l + 1)) { /* can connect both? */
45 SETARG_B(*previous, from+n-1);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);
46 return;51 return;
47 }52 }
48 }53 } /* else go through */
49 }54 }
50 luaK_codeABC(fs, OP_LOADNIL, from, from+n-1, 0); /* else no optimization */55 luaK_codeABC(fs, OP_LOADNIL, from, n - 1, 0); /* else no optimization */
51}56}
52 57
53 58
@@ -171,6 +176,19 @@ void luaK_patchlist (FuncState *fs, int list, int target) { · 117 unmodified lines
171}176}
172 177
173 178
179LUAI_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 }
189}
190
191
174void luaK_patchtohere (FuncState *fs, int list) {192void luaK_patchtohere (FuncState *fs, int list) {
175 luaK_getlabel(fs);193 luaK_getlabel(fs);
176 luaK_concat(fs, &fs->jpc, list);194 luaK_concat(fs, &fs->jpc, list);
@@ -229,11 +247,11 @@ static int codeextraarg (FuncState *fs, int a) { · 52 unmodified lines
229}247}
230 248
231 249
232int luaK_codeABxX (FuncState *fs, OpCode o, int reg, int k) {250int luaK_codek (FuncState *fs, int reg, int k) {
233 if (k < MAXARG_Bx)251 if (k <= MAXARG_Bx)
234 return luaK_codeABx(fs, o, reg, k + 1);252 return luaK_codeABx(fs, OP_LOADK, reg, k);
235 else {253 else {
236 int p = luaK_codeABx(fs, o, reg, 0);254 int p = luaK_codeABx(fs, OP_LOADKX, reg, 0);
237 codeextraarg(fs, k);255 codeextraarg(fs, k);
238 return p;256 return p;
239 }257 }
@@ -278,7 +296,7 @@ static int addk (FuncState *fs, TValue *key, TValue *v) { · 38 unmodified lines
278 if (ttisnumber(idx)) {296 if (ttisnumber(idx)) {
279 lua_Number n = nvalue(idx);297 lua_Number n = nvalue(idx);
280 lua_number2int(k, n);298 lua_number2int(k, n);
281 if (luaO_rawequalObj(&f->k[k], v))299 if (luaV_rawequalobj(&f->k[k], v))
282 return k;300 return k;
283 /* else may be a collision (e.g., between 0.0 and "\0\0\0\0\0\0\0\0");301 /* else may be a collision (e.g., between 0.0 and "\0\0\0\0\0\0\0\0");
284 go through and create a new entry for this value */302 go through and create a new entry for this value */
@@ -564,15 +582,15 @@ void luaK_storevar (FuncState *fs, expdesc *var, expdesc *ex) { · 279 unmodified lines
564 582
565 583
566void luaK_self (FuncState *fs, expdesc *e, expdesc *key) {584void luaK_self (FuncState *fs, expdesc *e, expdesc *key) {
567 int func;585 int ereg;
568 luaK_exp2anyreg(fs, e);586 luaK_exp2anyreg(fs, e);
587 ereg = e->u.info; /* register where 'e' was placed */
569 freeexp(fs, e);588 freeexp(fs, e);
570 func = fs->freereg;589 e->u.info = fs->freereg; /* base register for op_self */
571 luaK_codeABC(fs, OP_SELF, func, e->u.info, luaK_exp2RK(fs, key));
572 freeexp(fs, key);
573 luaK_reserveregs(fs, 2);
574 e->u.info = func;
575 e->k = VNONRELOC;590 e->k = VNONRELOC;
591 luaK_reserveregs(fs, 2); /* function and 'self' produced by op_self */
592 luaK_codeABC(fs, OP_SELF, e->u.info, ereg, luaK_exp2RK(fs, key));
593 freeexp(fs, key);
576}594}
577 595
578 596
@@ -603,21 +621,14 @@ void luaK_goiftrue (FuncState *fs, expdesc *e) { · 24 unmodified lines
603 int pc; /* pc of last jump */621 int pc; /* pc of last jump */
604 luaK_dischargevars(fs, e);622 luaK_dischargevars(fs, e);
605 switch (e->k) {623 switch (e->k) {
606 case VK: case VKNUM: case VTRUE: {
607 pc = NO_JUMP; /* always true; do nothing */
608 break;
609 }
610 case VJMP: {624 case VJMP: {
611 invertjump(fs, e);625 invertjump(fs, e);
612 pc = e->u.info;626 pc = e->u.info;
613 break;627 break;
614 }628 }
615 case VFALSE: {629 case VK: case VKNUM: case VTRUE: {
616 if (!hasjumps(e)) {630 pc = NO_JUMP; /* always true; do nothing */
617 pc = luaK_jump(fs); /* always jump */631 break;
618 break;
619 }
620 /* else go through */
621 }632 }
622 default: {633 default: {
623 pc = jumponcond(fs, e, 0);634 pc = jumponcond(fs, e, 0);
@@ -634,20 +645,13 @@ static void luaK_goiffalse (FuncState *fs, expdesc *e) { · 10 unmodified lines
634 int pc; /* pc of last jump */645 int pc; /* pc of last jump */
635 luaK_dischargevars(fs, e);646 luaK_dischargevars(fs, e);
636 switch (e->k) {647 switch (e->k) {
637 case VNIL: case VFALSE: {
638 pc = NO_JUMP; /* always false; do nothing */
639 break;
640 }
641 case VJMP: {648 case VJMP: {
642 pc = e->u.info;649 pc = e->u.info;
643 break;650 break;
644 }651 }
645 case VTRUE: {652 case VNIL: case VFALSE: {
646 if (!hasjumps(e)) {653 pc = NO_JUMP; /* always false; do nothing */
647 pc = luaK_jump(fs); /* always jump */654 break;
648 break;
649 }
650 /* else go through */
651 }655 }
652 default: {656 default: {
653 pc = jumponcond(fs, e, 1);657 pc = jumponcond(fs, e, 1);
src/lcode.h+3−4
@@ -1,5 +1,5 @@
1/*1/*
2** $Id: lcode.h,v 1.55 2010/07/02 20:42:40 roberto Exp $2** $Id: lcode.h,v 1.57 2011/04/07 18:14:12 roberto Exp $
3** Code generator for Lua3** Code generator for Lua
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -44,11 +44,9 @@ typedef enum UnOpr { OPR_MINUS, OPR_NOT, OPR_LEN, OPR_NOUNOPR } UnOpr; · 38 unmodified lines
44 44
45#define luaK_jumpto(fs,t) luaK_patchlist(fs, luaK_jump(fs), t)45#define luaK_jumpto(fs,t) luaK_patchlist(fs, luaK_jump(fs), t)
46 46
47#define luaK_codek(fs,reg,k) luaK_codeABxX(fs, OP_LOADK, reg, k)
48
49LUAI_FUNC int luaK_codeABx (FuncState *fs, OpCode o, int A, unsigned int Bx);47LUAI_FUNC int luaK_codeABx (FuncState *fs, OpCode o, int A, unsigned int Bx);
50LUAI_FUNC int luaK_codeABC (FuncState *fs, OpCode o, int A, int B, int C);48LUAI_FUNC int luaK_codeABC (FuncState *fs, OpCode o, int A, int B, int C);
51LUAI_FUNC int luaK_codeABxX (FuncState *fs, OpCode o, int reg, int k);49LUAI_FUNC int luaK_codek (FuncState *fs, int reg, int k);
52LUAI_FUNC void luaK_fixline (FuncState *fs, int line);50LUAI_FUNC void luaK_fixline (FuncState *fs, int line);
53LUAI_FUNC void luaK_nil (FuncState *fs, int from, int n);51LUAI_FUNC void luaK_nil (FuncState *fs, int from, int n);
54LUAI_FUNC void luaK_reserveregs (FuncState *fs, int n);52LUAI_FUNC void luaK_reserveregs (FuncState *fs, int n);
@@ -71,6 +69,7 @@ LUAI_FUNC int luaK_jump (FuncState *fs); · 16 unmodified lines
71LUAI_FUNC void luaK_ret (FuncState *fs, int first, int nret);69LUAI_FUNC void luaK_ret (FuncState *fs, int first, int nret);
72LUAI_FUNC void luaK_patchlist (FuncState *fs, int list, int target);70LUAI_FUNC void luaK_patchlist (FuncState *fs, int list, int target);
73LUAI_FUNC void luaK_patchtohere (FuncState *fs, int list);71LUAI_FUNC void luaK_patchtohere (FuncState *fs, int list);
72LUAI_FUNC void luaK_patchclose (FuncState *fs, int list, int level);
74LUAI_FUNC void luaK_concat (FuncState *fs, int *l1, int l2);73LUAI_FUNC void luaK_concat (FuncState *fs, int *l1, int l2);
75LUAI_FUNC int luaK_getlabel (FuncState *fs);74LUAI_FUNC int luaK_getlabel (FuncState *fs);
76LUAI_FUNC void luaK_prefix (FuncState *fs, UnOpr op, expdesc *v, int line);75LUAI_FUNC void luaK_prefix (FuncState *fs, UnOpr op, expdesc *v, int line);
src/ldblib.c+8−19
@@ -1,5 +1,5 @@
1/*1/*
2** $Id: ldblib.c,v 1.126 2010/11/16 18:01:28 roberto Exp $2** $Id: ldblib.c,v 1.130 2011/04/08 19:17:36 roberto Exp $
3** Interface from Lua to its debug API3** Interface from Lua to its debug API
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -18,6 +18,9 @@ · 12 unmodified lines
18#include "lualib.h"18#include "lualib.h"
19 19
20 20
21#define HOOKKEY "_HKEY"
22
23
21 24
22static int db_getregistry (lua_State *L) {25static int db_getregistry (lua_State *L) {
23 lua_pushvalue(L, LUA_REGISTRYINDEX);26 lua_pushvalue(L, LUA_REGISTRYINDEX);
@@ -39,8 +42,8 @@ static int db_setmetatable (lua_State *L) { · 15 unmodified lines
39 luaL_argcheck(L, t == LUA_TNIL || t == LUA_TTABLE, 2,42 luaL_argcheck(L, t == LUA_TNIL || t == LUA_TTABLE, 2,
40 "nil or table expected");43 "nil or table expected");
41 lua_settop(L, 2);44 lua_settop(L, 2);
42 lua_pushboolean(L, lua_setmetatable(L, 1));45 lua_setmetatable(L, 1);
43 return 1;46 return 1; /* return 1st argument */
44}47}
45 48
46 49
@@ -250,14 +253,13 @@ static int db_upvaluejoin (lua_State *L) { · 203 unmodified lines
250}253}
251 254
252 255
253static const char KEY_HOOK = 'h';256#define gethooktable(L) luaL_getsubtable(L, LUA_REGISTRYINDEX, HOOKKEY);
254 257
255 258
256static void hookf (lua_State *L, lua_Debug *ar) {259static void hookf (lua_State *L, lua_Debug *ar) {
257 static const char *const hooknames[] =260 static const char *const hooknames[] =
258 {"call", "return", "line", "count", "tail call"};261 {"call", "return", "line", "count", "tail call"};
259 lua_pushlightuserdata(L, (void *)&KEY_HOOK);262 gethooktable(L);
260 lua_rawget(L, LUA_REGISTRYINDEX);
261 lua_pushlightuserdata(L, L);263 lua_pushlightuserdata(L, L);
262 lua_rawget(L, -2);264 lua_rawget(L, -2);
263 if (lua_isfunction(L, -1)) {265 if (lua_isfunction(L, -1)) {
@@ -291,19 +293,6 @@ static char *unmakemask (int mask, char *smask) { · 27 unmodified lines
291}293}
292 294
293 295
294static void gethooktable (lua_State *L) {
295 lua_pushlightuserdata(L, (void *)&KEY_HOOK);
296 lua_rawget(L, LUA_REGISTRYINDEX);
297 if (!lua_istable(L, -1)) {
298 lua_pop(L, 1);
299 lua_createtable(L, 0, 1);
300 lua_pushlightuserdata(L, (void *)&KEY_HOOK);
301 lua_pushvalue(L, -2);
302 lua_rawset(L, LUA_REGISTRYINDEX);
303 }
304}
305
306
307static int db_sethook (lua_State *L) {296static int db_sethook (lua_State *L) {
308 int arg, mask, count;297 int arg, mask, count;
309 lua_Hook func;298 lua_Hook func;
src/ldebug.c+74−36
@@ -1,5 +1,5 @@
1/*1/*
2** $Id: ldebug.c,v 2.74 2010/10/11 20:24:42 roberto Exp $2** $Id: ldebug.c,v 2.82 2011/06/02 19:31:40 roberto Exp $
3** Debug Interface3** Debug Interface
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -35,12 +35,12 @@ static const char *getfuncname (lua_State *L, CallInfo *ci, const char **name); · 29 unmodified lines
35 35
36static int currentpc (CallInfo *ci) {36static int currentpc (CallInfo *ci) {
37 lua_assert(isLua(ci));37 lua_assert(isLua(ci));
38 return pcRel(ci->u.l.savedpc, ci_func(ci)->l.p);38 return pcRel(ci->u.l.savedpc, ci_func(ci)->p);
39}39}
40 40
41 41
42static int currentline (CallInfo *ci) {42static int currentline (CallInfo *ci) {
43 return getfuncline(ci_func(ci)->l.p, currentpc(ci));43 return getfuncline(ci_func(ci)->p, currentpc(ci));
44}44}
45 45
46 46
@@ -94,13 +94,28 @@ LUA_API int lua_getstack (lua_State *L, int level, lua_Debug *ar) { · 47 unmodified lines
94}94}
95 95
96 96
97static const char *findvararg (CallInfo *ci, int n, StkId *pos) {
98 int nparams = clLvalue(ci->func)->p->numparams;
99 if (n >= ci->u.l.base - ci->func - nparams)
100 return NULL; /* no such vararg */
101 else {
102 *pos = ci->func + nparams + n;
103 return "(*vararg)"; /* generic name for any vararg */
104 }
105}
106
107
97static const char *findlocal (lua_State *L, CallInfo *ci, int n,108static const char *findlocal (lua_State *L, CallInfo *ci, int n,
98 StkId *pos) {109 StkId *pos) {
99 const char *name = NULL;110 const char *name = NULL;
100 StkId base;111 StkId base;
101 if (isLua(ci)) {112 if (isLua(ci)) {
102 base = ci->u.l.base;113 if (n < 0) /* access to vararg values? */
103 name = luaF_getlocalname(ci_func(ci)->l.p, n, currentpc(ci));114 return findvararg(ci, -n, pos);
115 else {
116 base = ci->u.l.base;
117 name = luaF_getlocalname(ci_func(ci)->p, n, currentpc(ci));
118 }
104 }119 }
105 else120 else
106 base = ci->func + 1;121 base = ci->func + 1;
@@ -108,10 +123,8 @@ static const char *findlocal (lua_State *L, CallInfo *ci, int n, · 1 unmodified line
108 StkId limit = (ci == L->ci) ? L->top : ci->next->func;123 StkId limit = (ci == L->ci) ? L->top : ci->next->func;
109 if (limit - base >= n && n > 0) /* is 'n' inside 'ci' stack? */124 if (limit - base >= n && n > 0) /* is 'n' inside 'ci' stack? */
110 name = "(*temporary)"; /* generic name for any valid slot */125 name = "(*temporary)"; /* generic name for any valid slot */
111 else {126 else
112 *pos = base; /* to avoid warnings */
113 return NULL; /* no name */127 return NULL; /* no name */
114 }
115 }128 }
116 *pos = base + (n - 1);129 *pos = base + (n - 1);
117 return name;130 return name;
@@ -125,10 +138,10 @@ LUA_API const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n) { · 7 unmodified lines
125 if (!isLfunction(L->top - 1)) /* not a Lua function? */138 if (!isLfunction(L->top - 1)) /* not a Lua function? */
126 name = NULL;139 name = NULL;
127 else /* consider live variables at function start (parameters) */140 else /* consider live variables at function start (parameters) */
128 name = luaF_getlocalname(clvalue(L->top - 1)->l.p, n, 0);141 name = luaF_getlocalname(clLvalue(L->top - 1)->p, n, 0);
129 }142 }
130 else { /* active function; get information through 'ar' */143 else { /* active function; get information through 'ar' */
131 StkId pos;144 StkId pos = 0; /* to avoid warnings */
132 name = findlocal(L, ar->i_ci, n, &pos);145 name = findlocal(L, ar->i_ci, n, &pos);
133 if (name) {146 if (name) {
134 setobj2s(L, L->top, pos);147 setobj2s(L, L->top, pos);
@@ -141,11 +154,11 @@ LUA_API const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n) { · 6 unmodified lines
141 154
142 155
143LUA_API const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n) {156LUA_API const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n) {
144 StkId pos;157 StkId pos = 0; /* to avoid warnings */
145 const char *name = findlocal(L, ar->i_ci, n, &pos);158 const char *name = findlocal(L, ar->i_ci, n, &pos);
146 lua_lock(L);159 lua_lock(L);
147 if (name)160 if (name)
148 setobjs2s(L, pos, L->top - 1);161 setobjs2s(L, pos, L->top - 1);
149 L->top--; /* pop value */162 L->top--; /* pop value */
150 lua_unlock(L);163 lua_unlock(L);
151 return name;164 return name;
@@ -243,7 +256,7 @@ LUA_API int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar) { · 91 unmodified lines
243 if (*what == '>') {256 if (*what == '>') {
244 ci = NULL;257 ci = NULL;
245 func = L->top - 1;258 func = L->top - 1;
246 luai_apicheck(L, ttisfunction(func));259 api_check(L, ttisfunction(func), "function expected");
247 what++; /* skip the '>' */260 what++; /* skip the '>' */
248 L->top--; /* pop function */261 L->top--; /* pop function */
249 }262 }
@@ -271,21 +284,38 @@ LUA_API int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar) { · 21 unmodified lines
271** =======================================================284** =======================================================
272*/285*/
273 286
287static const char *getobjname (lua_State *L, CallInfo *ci, int reg,
288 const char **name);
274 289
275static void kname (Proto *p, int c, int reg, const char *what,290
276 const char **name) {291/*
277 if (c == reg && what && *what == 'c')292** find a "name" for the RK value 'c'
278 return; /* index is a constant; name already correct */293*/
279 else if (ISK(c) && ttisstring(&p->k[INDEXK(c)]))294static void kname (lua_State *L, CallInfo *ci, int c, int oreg,
280 *name = svalue(&p->k[INDEXK(c)]);295 const char *what, const char **name) {
281 else296 if (ISK(c)) { /* is 'c' a constant? */
282 *name = "?";297 TValue *kvalue = &ci_func(ci)->p->k[INDEXK(c)];
298 if (ttisstring(kvalue)) { /* literal constant? */
299 *name = svalue(kvalue); /* it is its own name */
300 return;
301 }
302 /* else no reasonable name found */
303 }
304 else { /* 'c' is a register */
305 if (c != oreg) /* not the original register? */
306 what = getobjname(L, ci, c, name); /* search for 'c' */
307 if (what && *what == 'c') { /* found a constant name? */
308 return; /* 'name' already filled */
309 }
310 /* else no reasonable name found */
311 }
312 *name = "?"; /* no reasonable name found */
283}313}
284 314
285 315
286static const char *getobjname (lua_State *L, CallInfo *ci, int reg,316static const char *getobjname (lua_State *L, CallInfo *ci, int reg,
287 const char **name) {317 const char **name) {
288 Proto *p = ci_func(ci)->l.p;318 Proto *p = ci_func(ci)->p;
289 const char *what = NULL;319 const char *what = NULL;
290 int lastpc = currentpc(ci);320 int lastpc = currentpc(ci);
291 int pc;321 int pc;
@@ -312,10 +342,10 @@ static const char *getobjname (lua_State *L, CallInfo *ci, int reg, · 20 unmodified lines
312 if (reg == a) {342 if (reg == a) {
313 int k = GETARG_C(i); /* key index */343 int k = GETARG_C(i); /* key index */
314 int t = GETARG_B(i);344 int t = GETARG_B(i);
315 const char *vn = (op == OP_GETTABLE) /* name of indexed variable */ 345 const char *vn = (op == OP_GETTABLE) /* name of indexed variable */
316 ? luaF_getlocalname(p, t + 1, pc)346 ? luaF_getlocalname(p, t + 1, pc)
317 : getstr(p->upvalues[t].name);347 : getstr(p->upvalues[t].name);
318 kname(p, k, a, what, name);348 kname(L, ci, k, a, what, name);
319 what = (vn && strcmp(vn, LUA_ENV) == 0) ? "global" : "field";349 what = (vn && strcmp(vn, LUA_ENV) == 0) ? "global" : "field";
320 }350 }
321 break;351 break;
@@ -329,10 +359,11 @@ static const char *getobjname (lua_State *L, CallInfo *ci, int reg, · 7 unmodified lines
329 }359 }
330 break;360 break;
331 }361 }
332 case OP_LOADK: {362 case OP_LOADK:
363 case OP_LOADKX: {
333 if (reg == a) {364 if (reg == a) {
334 int b = GETARG_Bx(i);365 int b = (op == OP_LOADK) ? GETARG_Bx(i)
335 b = (b > 0) ? b - 1 : GETARG_Ax(p->code[pc + 1]);366 : GETARG_Ax(p->code[pc + 1]);
336 if (ttisstring(&p->k[b])) {367 if (ttisstring(&p->k[b])) {
337 what = "constant";368 what = "constant";
338 *name = svalue(&p->k[b]);369 *name = svalue(&p->k[b]);
@@ -341,15 +372,15 @@ static const char *getobjname (lua_State *L, CallInfo *ci, int reg, · 2 unmodified lines
341 break;372 break;
342 }373 }
343 case OP_LOADNIL: {374 case OP_LOADNIL: {
344 int b = GETARG_B(i); /* move from 'b' to 'a' */375 int b = GETARG_B(i);
345 if (a <= reg && reg <= b) /* set registers from 'a' to 'b' */376 if (a <= reg && reg <= a + b) /* set registers from 'a' to 'a+b' */
346 what = NULL;377 what = NULL;
347 break;378 break;
348 }379 }
349 case OP_SELF: {380 case OP_SELF: {
350 if (reg == a) {381 if (reg == a) {
351 int k = GETARG_C(i); /* key index */382 int k = GETARG_C(i); /* key index */
352 kname(p, k, a, what, name);383 kname(L, ci, k, a, what, name);
353 what = "method";384 what = "method";
354 }385 }
355 break;386 break;
@@ -371,6 +402,10 @@ static const char *getobjname (lua_State *L, CallInfo *ci, int reg, · 15 unmodified lines
371 pc += b; /* do the jump */402 pc += b; /* do the jump */
372 break;403 break;
373 }404 }
405 case OP_TEST: {
406 if (reg == a) what = NULL; /* jumped code can change 'a' */
407 break;
408 }
374 default:409 default:
375 if (testAMode(op) && reg == a) what = NULL;410 if (testAMode(op) && reg == a) what = NULL;
376 break;411 break;
@@ -386,9 +421,9 @@ static const char *getfuncname (lua_State *L, CallInfo *ci, const char **name) { · 9 unmodified lines
386 if ((ci->callstatus & CIST_TAIL) || !isLua(ci->previous))421 if ((ci->callstatus & CIST_TAIL) || !isLua(ci->previous))
387 return NULL; /* calling function is not Lua (or is unknown) */422 return NULL; /* calling function is not Lua (or is unknown) */
388 ci = ci->previous; /* calling function */423 ci = ci->previous; /* calling function */
389 i = ci_func(ci)->l.p->code[currentpc(ci)];424 i = ci_func(ci)->p->code[currentpc(ci)];
390 if (GET_OPCODE(i) == OP_EXTRAARG) /* extra argument? */425 if (GET_OPCODE(i) == OP_EXTRAARG) /* extra argument? */
391 i = ci_func(ci)->l.p->code[currentpc(ci) - 1]; /* get 'real' instruction */426 i = ci_func(ci)->p->code[currentpc(ci) - 1]; /* get 'real' instruction */
392 switch (GET_OPCODE(i)) {427 switch (GET_OPCODE(i)) {
393 case OP_CALL:428 case OP_CALL:
394 case OP_TAILCALL:429 case OP_TAILCALL:
@@ -425,7 +460,10 @@ static const char *getfuncname (lua_State *L, CallInfo *ci, const char **name) { · 30 unmodified lines
425 460
426 461
427 462
428/* only ANSI way to check whether a pointer points to an array */463/*
464** only ANSI way to check whether a pointer points to an array
465** (used only for error messages, so efficiency is not a big concern)
466*/
429static int isinstack (CallInfo *ci, const TValue *o) {467static int isinstack (CallInfo *ci, const TValue *o) {
430 StkId p;468 StkId p;
431 for (p = ci->u.l.base; p < ci->top; p++)469 for (p = ci->u.l.base; p < ci->top; p++)
@@ -436,7 +474,7 @@ static int isinstack (CallInfo *ci, const TValue *o) { · 4 unmodified lines
436 474
437static const char *getupvalname (CallInfo *ci, const TValue *o,475static const char *getupvalname (CallInfo *ci, const TValue *o,
438 const char **name) {476 const char **name) {
439 LClosure *c = &ci_func(ci)->l;477 LClosure *c = ci_func(ci);
440 int i;478 int i;
441 for (i = 0; i < c->nupvalues; i++) {479 for (i = 0; i < c->nupvalues; i++) {
442 if (c->upvals[i]->v == o) {480 if (c->upvals[i]->v == o) {
@@ -455,7 +493,7 @@ void luaG_typeerror (lua_State *L, const TValue *o, const char *op) { · 12 unmodified lines
455 const char *kind = NULL;493 const char *kind = NULL;
456 if (isLua(ci)) {494 if (isLua(ci)) {
457 kind = getupvalname(ci, o, &name); /* check whether 'o' is an upvalue */495 kind = getupvalname(ci, o, &name); /* check whether 'o' is an upvalue */
458 if (!kind && isinstack(ci, o)) /* no? try a register */ 496 if (!kind && isinstack(ci, o)) /* no? try a register */
459 kind = getobjname(L, ci, cast_int(o - ci->u.l.base), &name);497 kind = getobjname(L, ci, cast_int(o - ci->u.l.base), &name);
460 }498 }
461 if (kind)499 if (kind)
@@ -497,7 +535,7 @@ static void addinfo (lua_State *L, const char *msg) { · 35 unmodified lines
497 if (isLua(ci)) { /* is Lua code? */535 if (isLua(ci)) { /* is Lua code? */
498 char buff[LUA_IDSIZE]; /* add file:line information */536 char buff[LUA_IDSIZE]; /* add file:line information */
499 int line = currentline(ci);537 int line = currentline(ci);
500 TString *src = ci_func(ci)->l.p->source;538 TString *src = ci_func(ci)->p->source;
501 if (src)539 if (src)
502 luaO_chunkid(buff, getstr(src), LUA_IDSIZE);540 luaO_chunkid(buff, getstr(src), LUA_IDSIZE);
503 else { /* no source available; use "?" instead */541 else { /* no source available; use "?" instead */
src/ldebug.h+4−1
@@ -1,5 +1,5 @@
1/*1/*
2** $Id: ldebug.h,v 2.5 2009/06/10 16:57:53 roberto Exp $2** $Id: ldebug.h,v 2.6 2011/06/02 19:31:40 roberto Exp $
3** Auxiliary functions from Debug Interface module3** Auxiliary functions from Debug Interface module
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -17,6 +17,9 @@ · 11 unmodified lines
17 17
18#define resethookcount(L) (L->hookcount = L->basehookcount)18#define resethookcount(L) (L->hookcount = L->basehookcount)
19 19
20/* Active Lua function (given call info) */
21#define ci_func(ci) (clLvalue((ci)->func))
22
20 23
21LUAI_FUNC void luaG_typeerror (lua_State *L, const TValue *o,24LUAI_FUNC void luaG_typeerror (lua_State *L, const TValue *o,
22 const char *opname);25 const char *opname);
src/ldo.c+64−66
@@ -1,5 +1,5 @@
1/*1/*
2** $Id: ldo.c,v 2.90 2010/10/25 19:01:37 roberto Exp $2** $Id: ldo.c,v 2.95 2011/06/02 19:31:40 roberto Exp $
3** Stack and Call structure of Lua3** Stack and Call structure of Lua
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -293,65 +293,59 @@ static StkId tryfuncTM (lua_State *L, StkId func) { · 287 unmodified lines
293** returns true if function has been executed (C function)293** returns true if function has been executed (C function)
294*/294*/
295int luaD_precall (lua_State *L, StkId func, int nresults) {295int luaD_precall (lua_State *L, StkId func, int nresults) {
296 Closure *cl;
297 lua_CFunction f;296 lua_CFunction f;
298 ptrdiff_t funcr;297 CallInfo *ci;
299 if (!ttisfunction(func)) /* `func' is not a function? */298 int n; /* number of arguments (Lua) or returns (C) */
300 func = tryfuncTM(L, func); /* check the `function' tag method */299 ptrdiff_t funcr = savestack(L, func);
301 funcr = savestack(L, func);300 switch (ttype(func)) {
302 if (ttislcf(func)) { /* light C function? */301 case LUA_TLCF: /* light C function */
303 f = fvalue(func); /* get it */302 f = fvalue(func);
304 goto isCfunc; /* go to call it */303 goto Cfunc;
305 }304 case LUA_TCCL: { /* C closure */
306 cl = clvalue(func);305 f = clCvalue(func)->f;
307 if (cl->c.isC) { /* C closure? */306 Cfunc:
308 CallInfo *ci;307 luaD_checkstack(L, LUA_MINSTACK); /* ensure minimum stack size */
309 int n;308 ci = next_ci(L); /* now 'enter' new function */
310 f = cl->c.f;309 ci->nresults = nresults;
311 isCfunc: /* call C function 'f' */310 ci->func = restorestack(L, funcr);
312 luaD_checkstack(L, LUA_MINSTACK); /* ensure minimum stack size */311 ci->top = L->top + LUA_MINSTACK;
313 ci = next_ci(L); /* now 'enter' new function */312 lua_assert(ci->top <= L->stack_last);
314 ci->nresults = nresults;313 ci->callstatus = 0;
315 ci->func = restorestack(L, funcr);314 if (L->hookmask & LUA_MASKCALL)
316 ci->top = L->top + LUA_MINSTACK;315 luaD_hook(L, LUA_HOOKCALL, -1);
317 lua_assert(ci->top <= L->stack_last);316 lua_unlock(L);
318 ci->callstatus = 0;317 n = (*f)(L); /* do the actual call */
319 if (L->hookmask & LUA_MASKCALL)318 lua_lock(L);
320 luaD_hook(L, LUA_HOOKCALL, -1);319 api_checknelems(L, n);
321 lua_unlock(L);320 luaD_poscall(L, L->top - n);
322 n = (*f)(L); /* do the actual call */321 return 1;
323 lua_lock(L);322 }
324 api_checknelems(L, n);323 case LUA_TLCL: { /* Lua function: prepare its call */
325 luaD_poscall(L, L->top - n);324 StkId base;
326 return 1;325 Proto *p = clLvalue(func)->p;
327 }326 luaD_checkstack(L, p->maxstacksize);
328 else { /* Lua function: prepare its call */327 func = restorestack(L, funcr);
329 CallInfo *ci;328 n = cast_int(L->top - func) - 1; /* number of real arguments */
330 int nparams, nargs;329 for (; n < p->numparams; n++)
331 StkId base;330 setnilvalue(L->top++); /* complete missing arguments */
332 Proto *p = cl->l.p;331 base = (!p->is_vararg) ? func + 1 : adjust_varargs(L, p, n);
333 luaD_checkstack(L, p->maxstacksize);332 ci = next_ci(L); /* now 'enter' new function */
334 func = restorestack(L, funcr);333 ci->nresults = nresults;
335 nargs = cast_int(L->top - func) - 1; /* number of real arguments */334 ci->func = func;
336 nparams = p->numparams; /* number of expected parameters */335 ci->u.l.base = base;
337 for (; nargs < nparams; nargs++)336 ci->top = base + p->maxstacksize;
338 setnilvalue(L->top++); /* complete missing arguments */337 lua_assert(ci->top <= L->stack_last);
339 if (!p->is_vararg) /* no varargs? */338 ci->u.l.savedpc = p->code; /* starting point */
340 base = func + 1;339 ci->callstatus = CIST_LUA;
341 else /* vararg function */340 L->top = ci->top;
342 base = adjust_varargs(L, p, nargs);341 if (L->hookmask & LUA_MASKCALL)
343 ci = next_ci(L); /* now 'enter' new function */342 callhook(L, ci);
344 ci->nresults = nresults;343 return 0;
345 ci->func = func;344 }
346 ci->u.l.base = base;345 default: { /* not a function */
347 ci->top = base + p->maxstacksize;346 func = tryfuncTM(L, func); /* retry with 'function' tag method */
348 lua_assert(ci->top <= L->stack_last);347 return luaD_precall(L, func, nresults);
349 ci->u.l.savedpc = p->code; /* starting point */348 }
350 ci->callstatus = CIST_LUA;
351 L->top = ci->top;
352 if (L->hookmask & LUA_MASKCALL)
353 callhook(L, ci);
354 return 0;
355 }349 }
356}350}
357 351
@@ -615,8 +609,8 @@ int luaD_pcall (lua_State *L, Pfunc func, void *u, · 257 unmodified lines
615*/609*/
616struct SParser { /* data to `f_parser' */610struct SParser { /* data to `f_parser' */
617 ZIO *z;611 ZIO *z;
618 Mbuffer buff; /* buffer to be used by the scanner */612 Mbuffer buff; /* dynamic structure used by the scanner */
619 Varlist varl; /* list of local variables (to be used by the parser) */613 Dyndata dyd; /* dynamic structures used by the parser */
620 const char *name;614 const char *name;
621};615};
622 616
@@ -625,14 +619,14 @@ static void f_parser (lua_State *L, void *ud) { · 2 unmodified lines
625 Proto *tf;619 Proto *tf;
626 Closure *cl;620 Closure *cl;
627 struct SParser *p = cast(struct SParser *, ud);621 struct SParser *p = cast(struct SParser *, ud);
628 int c = luaZ_lookahead(p->z);622 int c = zgetc(p->z); /* read first character */
629 tf = (c == LUA_SIGNATURE[0])623 tf = (c == LUA_SIGNATURE[0])
630 ? luaU_undump(L, p->z, &p->buff, p->name)624 ? luaU_undump(L, p->z, &p->buff, p->name)
631 : luaY_parser(L, p->z, &p->buff, &p->varl, p->name);625 : luaY_parser(L, p->z, &p->buff, &p->dyd, p->name, c);
632 setptvalue2s(L, L->top, tf);626 setptvalue2s(L, L->top, tf);
633 incr_top(L);627 incr_top(L);
634 cl = luaF_newLclosure(L, tf);628 cl = luaF_newLclosure(L, tf);
635 setclvalue(L, L->top - 1, cl);629 setclLvalue(L, L->top - 1, cl);
636 for (i = 0; i < tf->sizeupvalues; i++) /* initialize upvalues */630 for (i = 0; i < tf->sizeupvalues; i++) /* initialize upvalues */
637 cl->l.upvals[i] = luaF_newupval(L);631 cl->l.upvals[i] = luaF_newupval(L);
638}632}
@@ -643,11 +637,15 @@ int luaD_protectedparser (lua_State *L, ZIO *z, const char *name) { · 4 unmodified lines
643 int status;637 int status;
644 L->nny++; /* cannot yield during parsing */638 L->nny++; /* cannot yield during parsing */
645 p.z = z; p.name = name;639 p.z = z; p.name = name;
646 p.varl.actvar = NULL; p.varl.nactvar = p.varl.actvarsize = 0;640 p.dyd.actvar.arr = NULL; p.dyd.actvar.size = 0;
641 p.dyd.gt.arr = NULL; p.dyd.gt.size = 0;
642 p.dyd.label.arr = NULL; p.dyd.label.size = 0;
647 luaZ_initbuffer(L, &p.buff);643 luaZ_initbuffer(L, &p.buff);
648 status = luaD_pcall(L, f_parser, &p, savestack(L, L->top), L->errfunc);644 status = luaD_pcall(L, f_parser, &p, savestack(L, L->top), L->errfunc);
649 luaZ_freebuffer(L, &p.buff);645 luaZ_freebuffer(L, &p.buff);
650 luaM_freearray(L, p.varl.actvar, p.varl.actvarsize);646 luaM_freearray(L, p.dyd.actvar.arr, p.dyd.actvar.size);
647 luaM_freearray(L, p.dyd.gt.arr, p.dyd.gt.size);
648 luaM_freearray(L, p.dyd.label.arr, p.dyd.label.size);
651 L->nny--;649 L->nny--;
652 return status;650 return status;
653}651}
src/ldump.c+3−3
@@ -1,5 +1,5 @@
1/*1/*
2** $Id: ldump.c,v 1.17 2010/10/13 21:04:52 lhf Exp $2** $Id: ldump.c,v 1.18 2011/05/06 13:35:17 lhf Exp $
3** save precompiled Lua chunks3** save precompiled Lua chunks
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -69,7 +69,7 @@ static void DumpString(const TString* s, DumpState* D) · 63 unmodified lines
69 {69 {
70 size_t size=s->tsv.len+1; /* include trailing '\0' */70 size_t size=s->tsv.len+1; /* include trailing '\0' */
71 DumpVar(size,D);71 DumpVar(size,D);
72 DumpBlock(getstr(s),size,D);72 DumpBlock(getstr(s),size*sizeof(char),D);
73 }73 }
74}74}
75 75
@@ -150,7 +150,7 @@ static void DumpFunction(const Proto* f, DumpState* D) · 74 unmodified lines
150 150
151static void DumpHeader(DumpState* D)151static void DumpHeader(DumpState* D)
152{152{
153 char h[LUAC_HEADERSIZE];153 lu_byte h[LUAC_HEADERSIZE];
154 luaU_header(h);154 luaU_header(h);
155 DumpBlock(h,LUAC_HEADERSIZE,D);155 DumpBlock(h,LUAC_HEADERSIZE,D);
156}156}
src/lgc.c+79−58
@@ -1,5 +1,5 @@
1/*1/*
2** $Id: lgc.c,v 2.103 2010/10/25 19:01:37 roberto Exp $2** $Id: lgc.c,v 2.109 2011/05/05 19:42:25 roberto Exp $
3** Garbage Collector3** Garbage Collector
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -51,7 +51,7 @@ · 45 unmodified lines
51** standard negative debt for GC; a reasonable "time" to wait before51** standard negative debt for GC; a reasonable "time" to wait before
52** starting a new cycle52** starting a new cycle
53*/53*/
54#define stddebt(g) (-cast(l_mem, g->totalbytes/100) * g->gcpause)54#define stddebt(g) (-cast(l_mem, gettotalbytes(g)/100) * g->gcpause)
55 55
56 56
57/*57/*
@@ -68,11 +68,15 @@ · 10 unmodified lines
68#define stringmark(s) ((void)((s) && resetbits((s)->tsv.marked, WHITEBITS)))68#define stringmark(s) ((void)((s) && resetbits((s)->tsv.marked, WHITEBITS)))
69 69
70 70
71#define isfinalized(u) testbit((u)->marked, FINALIZEDBIT)71#define isfinalized(x) testbit(gch(x)->marked, FINALIZEDBIT)
72 72
73#define checkdeadkey(n) lua_assert(!ttisdeadkey(gkey(n)) || ttisnil(gval(n)))73#define checkdeadkey(n) lua_assert(!ttisdeadkey(gkey(n)) || ttisnil(gval(n)))
74 74
75 75
76#define checkconsistency(obj) \
77 lua_longassert(!iscollectable(obj) || righttt(obj))
78
79
76#define markvalue(g,o) { checkconsistency(o); \80#define markvalue(g,o) { checkconsistency(o); \
77 if (valiswhite(o)) reallymarkobject(g,gcvalue(o)); }81 if (valiswhite(o)) reallymarkobject(g,gcvalue(o)); }
78 82
@@ -114,12 +118,11 @@ static void removeentry (Node *n) { · 35 unmodified lines
114*/118*/
115static int iscleared (const TValue *o, int iskey) {119static int iscleared (const TValue *o, int iskey) {
116 if (!iscollectable(o)) return 0;120 if (!iscollectable(o)) return 0;
117 if (ttisstring(o)) {121 else if (ttisstring(o)) {
118 stringmark(rawtsvalue(o)); /* strings are `values', so are never weak */122 stringmark(rawtsvalue(o)); /* strings are `values', so are never weak */
119 return 0;123 return 0;
120 }124 }
121 return iswhite(gcvalue(o)) ||125 else return iswhite(gcvalue(o)) || (!iskey && isfinalized(gcvalue(o)));
122 (ttisuserdata(o) && (!iskey && isfinalized(uvalue(o))));
123}126}
124 127
125 128
@@ -319,8 +322,7 @@ static void remarkupvals (global_State *g) { · 193 unmodified lines
319** mark root set and reset all gray lists, to start a new322** mark root set and reset all gray lists, to start a new
320** incremental (or full) collection323** incremental (or full) collection
321*/324*/
322static void markroot (lua_State *L) {325static void markroot (global_State *g) {
323 global_State *g = G(L);
324 g->gray = g->grayagain = NULL;326 g->gray = g->grayagain = NULL;
325 g->weak = g->allweak = g->ephemeron = NULL;327 g->weak = g->allweak = g->ephemeron = NULL;
326 markobject(g, g->mainthread);328 markobject(g, g->mainthread);
@@ -635,6 +637,7 @@ static GCObject **sweeplist (lua_State *L, GCObject **p, lu_mem count) { · 308 unmodified lines
635 int ow = otherwhite(g);637 int ow = otherwhite(g);
636 int toclear, toset; /* bits to clear and to set in all live objects */638 int toclear, toset; /* bits to clear and to set in all live objects */
637 int tostop; /* stop sweep when this is true */639 int tostop; /* stop sweep when this is true */
640 l_mem debt = g->GCdebt; /* current debt */
638 if (isgenerational(g)) { /* generational mode? */641 if (isgenerational(g)) { /* generational mode? */
639 toclear = ~0; /* clear nothing */642 toclear = ~0; /* clear nothing */
640 toset = bitmask(OLDBIT); /* set the old bit of all surviving objects */643 toset = bitmask(OLDBIT); /* set the old bit of all surviving objects */
@@ -657,13 +660,15 @@ static GCObject **sweeplist (lua_State *L, GCObject **p, lu_mem count) { · 16 unmodified lines
657 sweepthread(L, gco2th(curr)); /* sweep thread's upvalues */660 sweepthread(L, gco2th(curr)); /* sweep thread's upvalues */
658 if (testbits(marked, tostop)) {661 if (testbits(marked, tostop)) {
659 static GCObject *nullp = NULL;662 static GCObject *nullp = NULL;
660 return &nullp; /* stop sweeping this list */663 p = &nullp; /* stop sweeping this list */
664 break;
661 }665 }
662 /* update marks */666 /* update marks */
663 gch(curr)->marked = cast_byte((marked & toclear) | toset);667 gch(curr)->marked = cast_byte((marked & toclear) | toset);
664 p = &gch(curr)->next; /* go to next element */668 p = &gch(curr)->next; /* go to next element */
665 }669 }
666 }670 }
671 luaE_setdebt(g, debt); /* sweeping should not change debt */
667 return p;672 return p;
668}673}
669 674
@@ -687,19 +692,17 @@ static void checkSizes (lua_State *L) { · 17 unmodified lines
687}692}
688 693
689 694
690static Udata *udata2finalize (global_State *g) {695static GCObject *udata2finalize (global_State *g) {
691 GCObject *o = g->tobefnz; /* get first element */696 GCObject *o = g->tobefnz; /* get first element */
692 Udata *u = rawgco2u(o);697 lua_assert(isfinalized(o));
693 lua_assert(isfinalized(&u->uv));698 g->tobefnz = gch(o)->next; /* remove it from 'tobefnz' list */
694 lua_assert(!isold(o));699 gch(o)->next = g->allgc; /* return it to 'allgc' list */
695 g->tobefnz = u->uv.next; /* remove it from 'tobefnz' list */
696 u->uv.next = g->allgc; /* return it to 'allgc' list */
697 g->allgc = o;700 g->allgc = o;
698 resetbit(u->uv.marked, SEPARATED); /* mark that it is not in 'tobefnz' */701 resetbit(gch(o)->marked, SEPARATED); /* mark that it is not in 'tobefnz' */
699 resetoldbit(o); /* see MOVE OLD rule */702 lua_assert(!isold(o)); /* see MOVE OLD rule */
700 if (!keepinvariant(g)) /* not keeping invariant? */703 if (!keepinvariant(g)) /* not keeping invariant? */
701 makewhite(g, o); /* "sweep" object */704 makewhite(g, o); /* "sweep" object */
702 return u;705 return o;
703}706}
704 707
705 708
@@ -711,20 +714,22 @@ static void dothecall (lua_State *L, void *ud) { · 5 unmodified lines
711 714
712static void GCTM (lua_State *L, int propagateerrors) {715static void GCTM (lua_State *L, int propagateerrors) {
713 global_State *g = G(L);716 global_State *g = G(L);
714 Udata *udata = udata2finalize(g);717 const TValue *tm;
715 const TValue *tm = gfasttm(g, udata->uv.metatable, TM_GC);718 TValue v;
719 setgcovalue(L, &v, udata2finalize(g));
720 tm = luaT_gettmbyobj(L, &v, TM_GC);
716 if (tm != NULL && ttisfunction(tm)) { /* is there a finalizer? */721 if (tm != NULL && ttisfunction(tm)) { /* is there a finalizer? */
717 int status;722 int status;
718 lu_byte oldah = L->allowhook;723 lu_byte oldah = L->allowhook;
719 lu_mem oldd = g->GCdebt;724 int running = g->gcrunning;
720 L->allowhook = 0; /* stop debug hooks during GC tag method */725 L->allowhook = 0; /* stop debug hooks during GC tag method */
721 stopgc(g); /* avoid GC steps */726 g->gcrunning = 0; /* avoid GC steps */
722 setobj2s(L, L->top, tm); /* push finalizer... */727 setobj2s(L, L->top, tm); /* push finalizer... */
723 setuvalue(L, L->top+1, udata); /* ... and its argument */728 setobj2s(L, L->top + 1, &v); /* ... and its argument */
724 L->top += 2; /* and (next line) call the finalizer */729 L->top += 2; /* and (next line) call the finalizer */
725 status = luaD_pcall(L, dothecall, NULL, savestack(L, L->top - 2), 0);730 status = luaD_pcall(L, dothecall, NULL, savestack(L, L->top - 2), 0);
726 L->allowhook = oldah; /* restore hooks */731 L->allowhook = oldah; /* restore hooks */
727 g->GCdebt = oldd; /* restore threshold */732 g->gcrunning = running; /* restore state */
728 if (status != LUA_OK && propagateerrors) { /* error while running __gc? */733 if (status != LUA_OK && propagateerrors) { /* error while running __gc? */
729 if (status == LUA_ERRRUN) { /* is there an error msg.? */734 if (status == LUA_ERRRUN) { /* is there an error msg.? */
730 luaO_pushfstring(L, "error in __gc tag method (%s)",735 luaO_pushfstring(L, "error in __gc tag method (%s)",
@@ -738,25 +743,25 @@ static void GCTM (lua_State *L, int propagateerrors) { · 7 unmodified lines
738 743
739 744
740/*745/*
741** move all unreachable udata that need finalization from list 'udgc' to746** move all unreachable objects that need finalization from list 'finobj'
742** list 'tobefnz'747** to list 'tobefnz'
743*/748*/
744void luaC_separateudata (lua_State *L, int all) {749void luaC_separateudata (lua_State *L, int all) {
745 global_State *g = G(L);750 global_State *g = G(L);
746 GCObject **p = &g->udgc;751 GCObject **p = &g->finobj;
747 GCObject *curr;752 GCObject *curr;
748 GCObject **lastnext = &g->tobefnz;753 GCObject **lastnext = &g->tobefnz;
749 /* find last 'next' field in 'tobefnz' list (to add elements in its end) */754 /* find last 'next' field in 'tobefnz' list (to add elements in its end) */
750 while (*lastnext != NULL)755 while (*lastnext != NULL)
751 lastnext = &gch(*lastnext)->next;756 lastnext = &gch(*lastnext)->next;
752 while ((curr = *p) != NULL) { /* traverse all finalizable objects */757 while ((curr = *p) != NULL) { /* traverse all finalizable objects */
753 lua_assert(gch(curr)->tt == LUA_TUSERDATA && !isfinalized(gco2u(curr)));758 lua_assert(!isfinalized(curr));
754 lua_assert(testbit(gch(curr)->marked, SEPARATED));759 lua_assert(testbit(gch(curr)->marked, SEPARATED));
755 if (!(all || iswhite(curr))) /* not being collected? */760 if (!(all || iswhite(curr))) /* not being collected? */
756 p = &gch(curr)->next; /* don't bother with it */761 p = &gch(curr)->next; /* don't bother with it */
757 else {762 else {
758 l_setbit(gch(curr)->marked, FINALIZEDBIT); /* won't be finalized again */763 l_setbit(gch(curr)->marked, FINALIZEDBIT); /* won't be finalized again */
759 *p = gch(curr)->next; /* remove 'curr' from 'udgc' list */764 *p = gch(curr)->next; /* remove 'curr' from 'finobj' list */
760 gch(curr)->next = *lastnext; /* link at the end of 'tobefnz' list */765 gch(curr)->next = *lastnext; /* link at the end of 'tobefnz' list */
761 *lastnext = curr;766 *lastnext = curr;
762 lastnext = &gch(curr)->next;767 lastnext = &gch(curr)->next;
@@ -766,23 +771,23 @@ void luaC_separateudata (lua_State *L, int all) { · 3 unmodified lines
766 771
767 772
768/*773/*
769** if userdata 'u' has a finalizer, remove it from 'allgc' list (must774** if object 'o' has a finalizer, remove it from 'allgc' list (must
770** search the list to find it) and link it in 'udgc' list.775** search the list to find it) and link it in 'finobj' list.
771*/776*/
772void luaC_checkfinalizer (lua_State *L, Udata *u) {777void luaC_checkfinalizer (lua_State *L, GCObject *o, Table *mt) {
773 global_State *g = G(L);778 global_State *g = G(L);
774 if (testbit(u->uv.marked, SEPARATED) || /* udata is already separated... */779 if (testbit(gch(o)->marked, SEPARATED) || /* obj. is already separated... */
775 isfinalized(&u->uv) || /* ... or is finalized... */780 isfinalized(o) || /* ... or is finalized... */
776 gfasttm(g, u->uv.metatable, TM_GC) == NULL) /* or has no finalizer? */781 gfasttm(g, mt, TM_GC) == NULL) /* or has no finalizer? */
777 return; /* nothing to be done */782 return; /* nothing to be done */
778 else { /* move 'u' to 'udgc' list */783 else { /* move 'o' to 'finobj' list */
779 GCObject **p;784 GCObject **p;
780 for (p = &g->allgc; *p != obj2gco(u); p = &gch(*p)->next) ;785 for (p = &g->allgc; *p != o; p = &gch(*p)->next) ;
781 *p = u->uv.next; /* remove 'u' from root list */786 *p = gch(o)->next; /* remove 'o' from root list */
782 u->uv.next = g->udgc; /* link it in list 'udgc' */787 gch(o)->next = g->finobj; /* link it in list 'finobj' */
783 g->udgc = obj2gco(u);788 g->finobj = o;
784 l_setbit(u->uv.marked, SEPARATED); /* mark it as such */789 l_setbit(gch(o)->marked, SEPARATED); /* mark it as such */
785 resetoldbit(obj2gco(u)); /* see MOVE OLD rule */790 resetoldbit(o); /* see MOVE OLD rule */
786 }791 }
787}792}
788 793
@@ -808,7 +813,7 @@ void luaC_changemode (lua_State *L, int mode) { · 19 unmodified lines
808 if (mode == KGC_GEN) { /* change to generational mode */813 if (mode == KGC_GEN) { /* change to generational mode */
809 /* make sure gray lists are consistent */814 /* make sure gray lists are consistent */
810 luaC_runtilstate(L, bitmask(GCSpropagate));815 luaC_runtilstate(L, bitmask(GCSpropagate));
811 g->lastmajormem = g->totalbytes;816 g->lastmajormem = gettotalbytes(g);
812 g->gckind = KGC_GEN;817 g->gckind = KGC_GEN;
813 }818 }
814 else { /* change to incremental mode */819 else { /* change to incremental mode */
@@ -823,10 +828,14 @@ void luaC_changemode (lua_State *L, int mode) { · 8 unmodified lines
823 828
824 829
825/*830/*
826** call all pending finalizers */831** call all pending finalizers
832*/
827static void callallpendingfinalizers (lua_State *L, int propagateerrors) {833static void callallpendingfinalizers (lua_State *L, int propagateerrors) {
828 global_State *g = G(L);834 global_State *g = G(L);
829 while (g->tobefnz) GCTM(L, propagateerrors);835 while (g->tobefnz) {
836 resetoldbit(g->tobefnz);
837 GCTM(L, propagateerrors);
838 }
830}839}
831 840
832 841
@@ -837,8 +846,8 @@ void luaC_freeallobjects (lua_State *L) { · 4 unmodified lines
837 /* following "white" makes all objects look dead */846 /* following "white" makes all objects look dead */
838 g->currentwhite = WHITEBITS;847 g->currentwhite = WHITEBITS;
839 g->gckind = KGC_NORMAL;848 g->gckind = KGC_NORMAL;
840 sweepwholelist(L, &g->udgc);849 sweepwholelist(L, &g->finobj);
841 lua_assert(g->udgc == NULL);850 lua_assert(g->finobj == NULL);
842 sweepwholelist(L, &g->allgc);851 sweepwholelist(L, &g->allgc);
843 lua_assert(g->allgc == NULL);852 lua_assert(g->allgc == NULL);
844 for (i = 0; i < g->strt.size; i++) /* free all string lists */853 for (i = 0; i < g->strt.size; i++) /* free all string lists */
@@ -883,7 +892,7 @@ static l_mem singlestep (lua_State *L) { · 38 unmodified lines
883 switch (g->gcstate) {892 switch (g->gcstate) {
884 case GCSpause: {893 case GCSpause: {
885 if (!isgenerational(g))894 if (!isgenerational(g))
886 markroot(L); /* start a new collection */895 markroot(g); /* start a new collection */
887 /* in any case, root must be marked */896 /* in any case, root must be marked */
888 lua_assert(!iswhite(obj2gco(g->mainthread))897 lua_assert(!iswhite(obj2gco(g->mainthread))
889 && !iswhite(gcvalue(&g->l_registry)));898 && !iswhite(gcvalue(&g->l_registry)));
@@ -905,7 +914,7 @@ static l_mem singlestep (lua_State *L) { · 15 unmodified lines
905 return GCSWEEPCOST;914 return GCSWEEPCOST;
906 }915 }
907 else { /* no more strings to sweep */916 else { /* no more strings to sweep */
908 g->sweepgc = &g->udgc; /* prepare to sweep userdata */917 g->sweepgc = &g->finobj; /* prepare to sweep finalizable objects */
909 g->gcstate = GCSsweepudata;918 g->gcstate = GCSsweepudata;
910 return 0;919 return 0;
911 }920 }
@@ -955,15 +964,15 @@ static void generationalcollection (lua_State *L) { · 43 unmodified lines
955 global_State *g = G(L);964 global_State *g = G(L);
956 if (g->lastmajormem == 0) { /* signal for another major collection? */965 if (g->lastmajormem == 0) { /* signal for another major collection? */
957 luaC_fullgc(L, 0); /* perform a full regular collection */966 luaC_fullgc(L, 0); /* perform a full regular collection */
958 g->lastmajormem = g->totalbytes; /* update control */967 g->lastmajormem = gettotalbytes(g); /* update control */
959 }968 }
960 else {969 else {
961 luaC_runtilstate(L, ~bitmask(GCSpause)); /* run complete cycle */970 luaC_runtilstate(L, ~bitmask(GCSpause)); /* run complete cycle */
962 luaC_runtilstate(L, bitmask(GCSpause));971 luaC_runtilstate(L, bitmask(GCSpause));
963 if (g->totalbytes > g->lastmajormem/100 * g->gcmajorinc)972 if (gettotalbytes(g) > g->lastmajormem/100 * g->gcmajorinc)
964 g->lastmajormem = 0; /* signal for a major collection */973 g->lastmajormem = 0; /* signal for a major collection */
965 }974 }
966 g->GCdebt = stddebt(g);975 luaE_setdebt(g, stddebt(g));
967}976}
968 977
969 978
@@ -974,21 +983,33 @@ static void step (lua_State *L) { · 4 unmodified lines
974 lim -= singlestep(L);983 lim -= singlestep(L);
975 } while (lim > 0 && g->gcstate != GCSpause);984 } while (lim > 0 && g->gcstate != GCSpause);
976 if (g->gcstate != GCSpause)985 if (g->gcstate != GCSpause)
977 g->GCdebt -= GCSTEPSIZE;986 luaE_setdebt(g, g->GCdebt - GCSTEPSIZE);
978 else987 else
979 g->GCdebt = stddebt(g);988 luaE_setdebt(g, stddebt(g));
980}989}
981 990
982 991
983void luaC_step (lua_State *L) {992/*
993** performs a basic GC step even if the collector is stopped
994*/
995void luaC_forcestep (lua_State *L) {
996 global_State *g = G(L);
984 int i;997 int i;
985 if (isgenerational(G(L))) generationalcollection(L);998 if (isgenerational(g)) generationalcollection(L);
986 else step(L);999 else step(L);
987 for (i = 0; i < GCFINALIZENUM && G(L)->tobefnz; i++)1000 for (i = 0; i < GCFINALIZENUM && g->tobefnz; i++)
988 GCTM(L, 1); /* Call a few pending finalizers */1001 GCTM(L, 1); /* Call a few pending finalizers */
989}1002}
990 1003
991 1004
1005/*
1006** performs a basic GC step only if collector is running
1007*/
1008void luaC_step (lua_State *L) {
1009 if (G(L)->gcrunning) luaC_forcestep(L);
1010}
1011
1012
992/*1013/*
993** performs a full GC cycle; if "isemergency", does not call1014** performs a full GC cycle; if "isemergency", does not call
994** finalizers (which could change stack positions)1015** finalizers (which could change stack positions)
@@ -1016,7 +1037,7 @@ void luaC_fullgc (lua_State *L, int isemergency) { · 21 unmodified lines
1016 luaC_runtilstate(L, bitmask(GCSpropagate));1037 luaC_runtilstate(L, bitmask(GCSpropagate));
1017 }1038 }
1018 g->gckind = origkind;1039 g->gckind = origkind;
1019 g->GCdebt = stddebt(g);1040 luaE_setdebt(g, stddebt(g));
1020 if (!isemergency) /* do not run finalizers during emergency GC */1041 if (!isemergency) /* do not run finalizers during emergency GC */
1021 callallpendingfinalizers(L, 1);1042 callallpendingfinalizers(L, 1);
1022}1043}
src/lgc.h+8−9
@@ -1,5 +1,5 @@
1/*1/*
2** $Id: lgc.h,v 2.44 2010/06/30 14:11:17 roberto Exp $2** $Id: lgc.h,v 2.50 2011/01/26 16:30:02 roberto Exp $
3** Garbage Collector3** Garbage Collector
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -52,10 +52,6 @@ · 46 unmodified lines
52#define keepinvariant(g) (isgenerational(g) || g->gcstate <= GCSatomic)52#define keepinvariant(g) (isgenerational(g) || g->gcstate <= GCSatomic)
53 53
54 54
55#define gcstopped(g) ((g)->GCdebt == MIN_LMEM)
56#define stopgc(g) ((g)->GCdebt = MIN_LMEM)
57
58
59/*55/*
60** some useful bit tricks56** some useful bit tricks
61*/57*/
@@ -76,8 +72,8 @@ · 14 unmodified lines
76#define WHITE0BIT 0 /* object is white (type 0) */72#define WHITE0BIT 0 /* object is white (type 0) */
77#define WHITE1BIT 1 /* object is white (type 1) */73#define WHITE1BIT 1 /* object is white (type 1) */
78#define BLACKBIT 2 /* object is black */74#define BLACKBIT 2 /* object is black */
79#define FINALIZEDBIT 3 /* for userdata: has been finalized */75#define FINALIZEDBIT 3 /* object has been separated for finalization */
80#define SEPARATED 4 /* " ": it's in 'udgc' list or in 'tobefnz' */76#define SEPARATED 4 /* object is in 'finobj' list or in 'tobefnz' */
81#define FIXEDBIT 5 /* object is fixed (should not be collected) */77#define FIXEDBIT 5 /* object is fixed (should not be collected) */
82#define OLDBIT 6 /* object is old (only in generational mode) */78#define OLDBIT 6 /* object is old (only in generational mode) */
83/* bit 7 is currently used by tests (luaL_checkmemory) */79/* bit 7 is currently used by tests (luaL_checkmemory) */
@@ -108,7 +104,9 @@ · 24 unmodified lines
108#define luaC_white(g) cast(lu_byte, (g)->currentwhite & WHITEBITS)104#define luaC_white(g) cast(lu_byte, (g)->currentwhite & WHITEBITS)
109 105
110 106
111#define luaC_checkGC(L) {condchangemem(L); if (G(L)->GCdebt > 0) luaC_step(L);}107#define luaC_condGC(L,c) \
108 {if (G(L)->GCdebt > 0) {c;}; condchangemem(L);}
109#define luaC_checkGC(L) luaC_condGC(L, luaC_step(L);)
112 110
113 111
114#define luaC_barrier(L,p,v) { if (valiswhite(v) && isblack(obj2gco(p))) \112#define luaC_barrier(L,p,v) { if (valiswhite(v) && isblack(obj2gco(p))) \
@@ -130,6 +128,7 @@ · 15 unmodified lines
130LUAI_FUNC void luaC_separateudata (lua_State *L, int all);128LUAI_FUNC void luaC_separateudata (lua_State *L, int all);
131LUAI_FUNC void luaC_freeallobjects (lua_State *L);129LUAI_FUNC void luaC_freeallobjects (lua_State *L);
132LUAI_FUNC void luaC_step (lua_State *L);130LUAI_FUNC void luaC_step (lua_State *L);
131LUAI_FUNC void luaC_forcestep (lua_State *L);
133LUAI_FUNC void luaC_runtilstate (lua_State *L, int statesmask);132LUAI_FUNC void luaC_runtilstate (lua_State *L, int statesmask);
134LUAI_FUNC void luaC_fullgc (lua_State *L, int isemergency);133LUAI_FUNC void luaC_fullgc (lua_State *L, int isemergency);
135LUAI_FUNC GCObject *luaC_newobj (lua_State *L, int tt, size_t sz,134LUAI_FUNC GCObject *luaC_newobj (lua_State *L, int tt, size_t sz,
@@ -137,7 +136,7 @@ LUAI_FUNC GCObject *luaC_newobj (lua_State *L, int tt, size_t sz, · 1 unmodified line
137LUAI_FUNC void luaC_barrier_ (lua_State *L, GCObject *o, GCObject *v);136LUAI_FUNC void luaC_barrier_ (lua_State *L, GCObject *o, GCObject *v);
138LUAI_FUNC void luaC_barrierback_ (lua_State *L, GCObject *o);137LUAI_FUNC void luaC_barrierback_ (lua_State *L, GCObject *o);
139LUAI_FUNC void luaC_barrierproto_ (lua_State *L, Proto *p, Closure *c);138LUAI_FUNC void luaC_barrierproto_ (lua_State *L, Proto *p, Closure *c);
140LUAI_FUNC void luaC_checkfinalizer (lua_State *L, Udata *u);139LUAI_FUNC void luaC_checkfinalizer (lua_State *L, GCObject *o, Table *mt);
141LUAI_FUNC void luaC_checkupvalcolor (global_State *g, UpVal *uv);140LUAI_FUNC void luaC_checkupvalcolor (global_State *g, UpVal *uv);
142LUAI_FUNC void luaC_changemode (lua_State *L, int mode);141LUAI_FUNC void luaC_changemode (lua_State *L, int mode);
143 142
src/linit.c+5−5
@@ -1,16 +1,16 @@
1/*1/*
2** $Id: linit.c,v 1.30 2010/11/12 15:48:30 roberto Exp $2** $Id: linit.c,v 1.32 2011/04/08 19:17:36 roberto Exp $
3** Initialization of libraries for lua.c and other clients 3** Initialization of libraries for lua.c and other clients
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
6 6
7 7
8/* 8/*
9** If you embed Lua in your program and need to open the standard9** If you embed Lua in your program and need to open the standard
10** libraries, call luaL_openlibs in your program. If you need a10** libraries, call luaL_openlibs in your program. If you need a
11** different set of libraries, copy this file to your project and edit11** different set of libraries, copy this file to your project and edit
12** it to suit your needs.12** it to suit your needs.
13*/ 13*/
14 14
15 15
16#define linit_c16#define linit_c
@@ -57,7 +57,7 @@ LUALIB_API void luaL_openlibs (lua_State *L) { · 40 unmodified lines
57 lua_pop(L, 1); /* remove lib */57 lua_pop(L, 1); /* remove lib */
58 }58 }
59 /* add open functions from 'preloadedlibs' into 'package.preload' table */59 /* add open functions from 'preloadedlibs' into 'package.preload' table */
60 luaL_findtable(L, LUA_REGISTRYINDEX, "_PRELOAD");60 luaL_getsubtable(L, LUA_REGISTRYINDEX, "_PRELOAD");
61 for (lib = preloadedlibs; lib->func; lib++) {61 for (lib = preloadedlibs; lib->func; lib++) {
62 lua_pushcfunction(L, lib->func);62 lua_pushcfunction(L, lib->func);
63 lua_setfield(L, -2, lib->name);63 lua_setfield(L, -2, lib->name);
src/liolib.c+34−57
@@ -1,5 +1,5 @@
1/*1/*
2** $Id: liolib.c,v 2.95 2010/11/10 18:05:36 roberto Exp $2** $Id: liolib.c,v 2.99 2011/03/03 16:34:46 roberto Exp $
3** Standard I/O (and system) library3** Standard I/O (and system) library
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -26,28 +26,29 @@ · 20 unmodified lines
26** lua_popen spawns a new process connected to the current one through26** lua_popen spawns a new process connected to the current one through
27** the file streams.27** the file streams.
28*/28*/
29#if !defined(lua_popen)29#if !defined(lua_popen) /* { */
30 30
31#if defined(LUA_USE_POPEN)31#if defined(LUA_USE_POPEN) /* { */
32 32
33#define lua_popen(L,c,m) ((void)L, fflush(NULL), popen(c,m))33#define lua_popen(L,c,m) ((void)L, fflush(NULL), popen(c,m))
34#define lua_pclose(L,file) ((void)L, pclose(file))34#define lua_pclose(L,file) ((void)L, pclose(file))
35 35
36#elif defined(LUA_WIN)36#elif defined(LUA_WIN) /* }{ */
37 37
38#define lua_popen(L,c,m) ((void)L, _popen(c,m))38#define lua_popen(L,c,m) ((void)L, _popen(c,m))
39#define lua_pclose(L,file) ((void)L, _pclose(file))39#define lua_pclose(L,file) ((void)L, _pclose(file))
40 40
41#else
42 41
43#define lua_popen(L,c,m) ((void)((void)c, m), \42#else /* }{ */
44 luaL_error(L, LUA_QL("popen") " not supported"), (FILE*)0)
45#define lua_pclose(L,file) ((void)((void)L, file), -1)
46 43
47#endif44#define lua_popen(L,c,m) ((void)((void)c, m), \
45 luaL_error(L, LUA_QL("popen") " not supported"), (FILE*)0)
46#define lua_pclose(L,file) ((void)((void)L, file), -1)
48 47
49#endif
50 48
49#endif /* } */
50
51#endif /* } */
51 52
52 53
53#define IO_INPUT 154#define IO_INPUT 1
@@ -57,24 +58,6 @@ · 3 unmodified lines
57static const char *const fnames[] = {"input", "output"};58static const char *const fnames[] = {"input", "output"};
58 59
59 60
60static int pushresult (lua_State *L, int i, const char *filename) {
61 int en = errno; /* calls to Lua API may change this value */
62 if (i) {
63 lua_pushboolean(L, 1);
64 return 1;
65 }
66 else {
67 lua_pushnil(L);
68 if (filename)
69 lua_pushfstring(L, "%s: %s", filename, strerror(en));
70 else
71 lua_pushfstring(L, "%s", strerror(en));
72 lua_pushinteger(L, en);
73 return 3;
74 }
75}
76
77
78static void fileerror (lua_State *L, int arg, const char *filename) {61static void fileerror (lua_State *L, int arg, const char *filename) {
79 lua_pushfstring(L, "%s: %s", filename, strerror(errno));62 lua_pushfstring(L, "%s: %s", filename, strerror(errno));
80 luaL_argerror(L, arg, lua_tostring(L, -1));63 luaL_argerror(L, arg, lua_tostring(L, -1));
@@ -143,13 +126,8 @@ static int io_noclose (lua_State *L) { · 62 unmodified lines
143static int io_pclose (lua_State *L) {126static int io_pclose (lua_State *L) {
144 FILE **p = tofilep(L);127 FILE **p = tofilep(L);
145 int stat = lua_pclose(L, *p);128 int stat = lua_pclose(L, *p);
146 *p = NULL;129 *p = NULL; /* mark stream as closed (for GC) */
147 if (stat == -1) /* error? */130 return luaL_execresult(L, stat);
148 return pushresult(L, 0, NULL);
149 else {
150 lua_pushinteger(L, stat);
151 return 1; /* return status */
152 }
153}131}
154 132
155 133
@@ -159,8 +137,8 @@ static int io_pclose (lua_State *L) { · 3 unmodified lines
159static int io_fclose (lua_State *L) {137static int io_fclose (lua_State *L) {
160 FILE **p = tofilep(L);138 FILE **p = tofilep(L);
161 int ok = (fclose(*p) == 0);139 int ok = (fclose(*p) == 0);
162 *p = NULL;140 *p = NULL; /* mark stream as closed (for GC) */
163 return pushresult(L, ok, NULL);141 return luaL_fileresult(L, ok, NULL);
164}142}
165 143
166 144
@@ -181,8 +159,7 @@ static int io_close (lua_State *L) { · 14 unmodified lines
181 159
182static int io_gc (lua_State *L) {160static int io_gc (lua_State *L) {
183 FILE *f = *tofilep(L);161 FILE *f = *tofilep(L);
184 /* ignore closed files */162 if (f != NULL) /* ignore closed files */
185 if (f != NULL)
186 aux_close(L);163 aux_close(L);
187 return 0;164 return 0;
188}165}
@@ -205,14 +182,14 @@ static int io_open (lua_State *L) { · 16 unmodified lines
205 int i = 0;182 int i = 0;
206 /* check whether 'mode' matches '[rwa]%+?b?' */183 /* check whether 'mode' matches '[rwa]%+?b?' */
207 if (!(mode[i] != '\0' && strchr("rwa", mode[i++]) != NULL &&184 if (!(mode[i] != '\0' && strchr("rwa", mode[i++]) != NULL &&
208 (mode[i] != '+' || ++i) && /* skip if char is '+' */185 (mode[i] != '+' || ++i) && /* skip if char is '+' */
209 (mode[i] != 'b' || ++i) && /* skip if char is 'b' */186 (mode[i] != 'b' || ++i) && /* skip if char is 'b' */
210 (mode[i] == '\0')))187 (mode[i] == '\0')))
211 luaL_error(L, "invalid mode " LUA_QL("%s")188 luaL_error(L, "invalid mode " LUA_QL("%s")
212 " (should match " LUA_QL("[rwa]%%+?b?") ")", mode);189 " (should match " LUA_QL("[rwa]%%+?b?") ")", mode);
213 pf = newfile(L);190 pf = newfile(L);
214 *pf = fopen(filename, mode);191 *pf = fopen(filename, mode);
215 return (*pf == NULL) ? pushresult(L, 0, filename) : 1;192 return (*pf == NULL) ? luaL_fileresult(L, 0, filename) : 1;
216}193}
217 194
218 195
@@ -225,14 +202,14 @@ static int io_popen (lua_State *L) { · 6 unmodified lines
225 const char *mode = luaL_optstring(L, 2, "r");202 const char *mode = luaL_optstring(L, 2, "r");
226 FILE **pf = newfile(L);203 FILE **pf = newfile(L);
227 *pf = lua_popen(L, filename, mode);204 *pf = lua_popen(L, filename, mode);
228 return (*pf == NULL) ? pushresult(L, 0, filename) : 1;205 return (*pf == NULL) ? luaL_fileresult(L, 0, filename) : 1;
229}206}
230 207
231 208
232static int io_tmpfile (lua_State *L) {209static int io_tmpfile (lua_State *L) {
233 FILE **pf = newfile(L);210 FILE **pf = newfile(L);
234 *pf = tmpfile();211 *pf = tmpfile();
235 return (*pf == NULL) ? pushresult(L, 0, NULL) : 1;212 return (*pf == NULL) ? luaL_fileresult(L, 0, NULL) : 1;
236}213}
237 214
238 215
@@ -305,7 +282,7 @@ static int io_lines (lua_State *L) { · 66 unmodified lines
305 if (lua_isnone(L, 1)) lua_pushnil(L); /* at least one argument */282 if (lua_isnone(L, 1)) lua_pushnil(L); /* at least one argument */
306 if (lua_isnil(L, 1)) { /* no file name? */283 if (lua_isnil(L, 1)) { /* no file name? */
307 lua_rawgeti(L, lua_upvalueindex(1), IO_INPUT); /* get default input */284 lua_rawgeti(L, lua_upvalueindex(1), IO_INPUT); /* get default input */
308 lua_replace(L, 1); /* put it at index 1 */285 lua_replace(L, 1); /* put it at index 1 */
309 tofile(L); /* check that it's a valid file handle */286 tofile(L); /* check that it's a valid file handle */
310 toclose = 0; /* do not close it after iteration */287 toclose = 0; /* do not close it after iteration */
311 }288 }
@@ -315,7 +292,7 @@ static int io_lines (lua_State *L) { · 3 unmodified lines
315 *pf = fopen(filename, "r");292 *pf = fopen(filename, "r");
316 if (*pf == NULL)293 if (*pf == NULL)
317 fileerror(L, 1, filename);294 fileerror(L, 1, filename);
318 lua_replace(L, 1); /* put file at index 1 */295 lua_replace(L, 1); /* put file at index 1 */
319 toclose = 1; /* close it after iteration */296 toclose = 1; /* close it after iteration */
320 }297 }
321 aux_lines(L, toclose);298 aux_lines(L, toclose);
@@ -443,7 +420,7 @@ static int g_read (lua_State *L, FILE *f, int first) { · 121 unmodified lines
443 }420 }
444 }421 }
445 if (ferror(f))422 if (ferror(f))
446 return pushresult(L, 0, NULL);423 return luaL_fileresult(L, 0, NULL);
447 if (!success) {424 if (!success) {
448 lua_pop(L, 1); /* remove last result */425 lua_pop(L, 1); /* remove last result */
449 lua_pushnil(L); /* push nil instead */426 lua_pushnil(L); /* push nil instead */
@@ -507,7 +484,7 @@ static int g_write (lua_State *L, FILE *f, int arg) { · 57 unmodified lines
507 }484 }
508 }485 }
509 if (status) return 1; /* file handle already on stack top */486 if (status) return 1; /* file handle already on stack top */
510 else return pushresult(L, status, NULL);487 else return luaL_fileresult(L, status, NULL);
511}488}
512 489
513 490
@@ -517,7 +494,7 @@ static int io_write (lua_State *L) { · 3 unmodified lines
517 494
518 495
519static int f_write (lua_State *L) {496static int f_write (lua_State *L) {
520 FILE * f = tofile(L); 497 FILE * f = tofile(L);
521 lua_pushvalue(L, 1); /* push file at the stack top (to be returned) */498 lua_pushvalue(L, 1); /* push file at the stack top (to be returned) */
522 return g_write(L, f, 2);499 return g_write(L, f, 2);
523}500}
@@ -531,7 +508,7 @@ static int f_seek (lua_State *L) { · 7 unmodified lines
531 long offset = luaL_optlong(L, 3, 0);508 long offset = luaL_optlong(L, 3, 0);
532 op = fseek(f, offset, mode[op]);509 op = fseek(f, offset, mode[op]);
533 if (op)510 if (op)
534 return pushresult(L, 0, NULL); /* error */511 return luaL_fileresult(L, 0, NULL); /* error */
535 else {512 else {
536 lua_pushinteger(L, ftell(f));513 lua_pushinteger(L, ftell(f));
537 return 1;514 return 1;
@@ -546,18 +523,18 @@ static int f_setvbuf (lua_State *L) { · 8 unmodified lines
546 int op = luaL_checkoption(L, 2, NULL, modenames);523 int op = luaL_checkoption(L, 2, NULL, modenames);
547 lua_Integer sz = luaL_optinteger(L, 3, LUAL_BUFFERSIZE);524 lua_Integer sz = luaL_optinteger(L, 3, LUAL_BUFFERSIZE);
548 int res = setvbuf(f, NULL, mode[op], sz);525 int res = setvbuf(f, NULL, mode[op], sz);
549 return pushresult(L, res == 0, NULL);526 return luaL_fileresult(L, res == 0, NULL);
550}527}
551 528
552 529
553 530
554static int io_flush (lua_State *L) {531static int io_flush (lua_State *L) {
555 return pushresult(L, fflush(getiofile(L, IO_OUTPUT)) == 0, NULL);532 return luaL_fileresult(L, fflush(getiofile(L, IO_OUTPUT)) == 0, NULL);
556}533}
557 534
558 535
559static int f_flush (lua_State *L) {536static int f_flush (lua_State *L) {
560 return pushresult(L, fflush(tofile(L)) == 0, NULL);537 return luaL_fileresult(L, fflush(tofile(L)) == 0, NULL);
561}538}
562 539
563 540
src/llex.c+13−17
@@ -1,5 +1,5 @@
1/*1/*
2** $Id: llex.c,v 2.41 2010/11/18 18:38:44 roberto Exp $2** $Id: llex.c,v 2.47 2011/05/03 15:51:16 roberto Exp $
3** Lexical Analyzer3** Lexical Analyzer
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -35,7 +35,7 @@ · 29 unmodified lines
35/* ORDER RESERVED */35/* ORDER RESERVED */
36static const char *const luaX_tokens [] = {36static const char *const luaX_tokens [] = {
37 "and", "break", "do", "else", "elseif",37 "and", "break", "do", "else", "elseif",
38 "end", "false", "for", "function", "if",38 "end", "false", "for", "function", "goto", "if",
39 "in", "local", "nil", "not", "or", "repeat",39 "in", "local", "nil", "not", "or", "repeat",
40 "return", "then", "true", "until", "while",40 "return", "then", "true", "until", "while",
41 "..", "...", "==", ">=", "<=", "~=", "<eof>",41 "..", "...", "==", ">=", "<=", "~=", "<eof>",
@@ -67,7 +67,6 @@ void luaX_init (lua_State *L) { · 25 unmodified lines
67 for (i=0; i<NUM_RESERVED; i++) {67 for (i=0; i<NUM_RESERVED; i++) {
68 TString *ts = luaS_new(L, luaX_tokens[i]);68 TString *ts = luaS_new(L, luaX_tokens[i]);
69 luaS_fix(ts); /* reserved words are never collected */69 luaS_fix(ts); /* reserved words are never collected */
70 lua_assert(strlen(luaX_tokens[i])+1 <= TOKEN_LEN);
71 ts->tsv.reserved = cast_byte(i+1); /* reserved word */70 ts->tsv.reserved = cast_byte(i+1); /* reserved word */
72 }71 }
73}72}
@@ -127,7 +126,7 @@ TString *luaX_newstring (LexState *ls, const char *str, size_t l) { · 53 unmodified lines
127 TValue *o; /* entry for `str' */126 TValue *o; /* entry for `str' */
128 TString *ts = luaS_newlstr(L, str, l); /* create new string */127 TString *ts = luaS_newlstr(L, str, l); /* create new string */
129 setsvalue2s(L, L->top++, ts); /* temporarily anchor it in stack */128 setsvalue2s(L, L->top++, ts); /* temporarily anchor it in stack */
130 o = luaH_setstr(L, ls->fs->h, ts); 129 o = luaH_setstr(L, ls->fs->h, ts);
131 if (ttisnil(o)) {130 if (ttisnil(o)) {
132 setbvalue(o, 1); /* t[string] = true */131 setbvalue(o, 1); /* t[string] = true */
133 luaC_checkGC(L);132 luaC_checkGC(L);
@@ -152,9 +151,11 @@ static void inclinenumber (LexState *ls) { · 18 unmodified lines
152}151}
153 152
154 153
155void luaX_setinput (lua_State *L, LexState *ls, ZIO *z, TString *source) {154void luaX_setinput (lua_State *L, LexState *ls, ZIO *z, TString *source,
155 int firstchar) {
156 ls->decpoint = '.';156 ls->decpoint = '.';
157 ls->L = L;157 ls->L = L;
158 ls->current = firstchar;
158 ls->lookahead.token = TK_EOS; /* no look-ahead token */159 ls->lookahead.token = TK_EOS; /* no look-ahead token */
159 ls->z = z;160 ls->z = z;
160 ls->fs = NULL;161 ls->fs = NULL;
@@ -164,7 +165,6 @@ void luaX_setinput (lua_State *L, LexState *ls, ZIO *z, TString *source) { · 3 unmodified lines
164 ls->envn = luaS_new(L, LUA_ENV); /* create env name */165 ls->envn = luaS_new(L, LUA_ENV); /* create env name */
165 luaS_fix(ls->envn); /* never collect this name */166 luaS_fix(ls->envn); /* never collect this name */
166 luaZ_resizebuffer(ls->L, ls->buff, LUA_MINBUFFER); /* initialize buffer */167 luaZ_resizebuffer(ls->L, ls->buff, LUA_MINBUFFER); /* initialize buffer */
167 next(ls); /* read first char */
168}168}
169 169
170 170
@@ -185,7 +185,7 @@ static int check_next (LexState *ls, const char *set) { · 14 unmodified lines
185}185}
186 186
187 187
188/* 188/*
189** change all characters 'from' in buffer to 'to'189** change all characters 'from' in buffer to 'to'
190*/190*/
191static void buffreplace (LexState *ls, char from, char to) {191static void buffreplace (LexState *ls, char from, char to) {
@@ -200,6 +200,9 @@ static void buffreplace (LexState *ls, char from, char to) { · 8 unmodified lines
200#define getlocaledecpoint() (localeconv()->decimal_point[0])200#define getlocaledecpoint() (localeconv()->decimal_point[0])
201#endif201#endif
202 202
203
204#define buff2d(b,e) luaO_str2d(luaZ_buffer(b), luaZ_bufflen(b) - 1, e)
205
203/*206/*
204** in case of format error, try to change decimal point separator to207** in case of format error, try to change decimal point separator to
205** the one defined in the current locale and check again208** the one defined in the current locale and check again
@@ -208,7 +211,7 @@ static void trydecpoint (LexState *ls, SemInfo *seminfo) { · 2 unmodified lines
208 char old = ls->decpoint;211 char old = ls->decpoint;
209 ls->decpoint = getlocaledecpoint();212 ls->decpoint = getlocaledecpoint();
210 buffreplace(ls, old, ls->decpoint); /* try new decimal separator */213 buffreplace(ls, old, ls->decpoint); /* try new decimal separator */
211 if (!luaO_str2d(luaZ_buffer(ls->buff), &seminfo->r)) {214 if (!buff2d(ls->buff, &seminfo->r)) {
212 /* format error with correct decimal point: no more options */215 /* format error with correct decimal point: no more options */
213 buffreplace(ls, ls->decpoint, '.'); /* undo change (for error message) */216 buffreplace(ls, ls->decpoint, '.'); /* undo change (for error message) */
214 lexerror(ls, "malformed number", TK_NUMBER);217 lexerror(ls, "malformed number", TK_NUMBER);
@@ -226,7 +229,7 @@ static void read_numeral (LexState *ls, SemInfo *seminfo) { · 11 unmodified lines
226 } while (lislalnum(ls->current) || ls->current == '.');229 } while (lislalnum(ls->current) || ls->current == '.');
227 save(ls, '\0');230 save(ls, '\0');
228 buffreplace(ls, '.', ls->decpoint); /* follow locale for decimal point */231 buffreplace(ls, '.', ls->decpoint); /* follow locale for decimal point */
229 if (!luaO_str2d(luaZ_buffer(ls->buff), &seminfo->r)) /* format error? */232 if (!buff2d(ls->buff, &seminfo->r)) /* format error? */
230 trydecpoint(ls, seminfo); /* try to update decimal point separator */233 trydecpoint(ls, seminfo); /* try to update decimal point separator */
231}234}
232 235
@@ -283,13 +286,6 @@ static void read_long_string (LexState *ls, SemInfo *seminfo, int sep) { · 50 unmodified lines
283}286}
284 287
285 288
286static int hexavalue (int c) {
287 if (lisdigit(c)) return c - '0';
288 else if (lisupper(c)) return c - 'A' + 10;
289 else return c - 'a' + 10;
290}
291
292
293static int readhexaesc (LexState *ls) {289static int readhexaesc (LexState *ls) {
294 int c1, c2 = EOZ;290 int c1, c2 = EOZ;
295 if (!lisxdigit(c1 = next(ls)) || !lisxdigit(c2 = next(ls))) {291 if (!lisxdigit(c1 = next(ls)) || !lisxdigit(c2 = next(ls))) {
@@ -299,7 +295,7 @@ static int readhexaesc (LexState *ls) { · 3 unmodified lines
299 if (c2 != EOZ) save(ls, c2);295 if (c2 != EOZ) save(ls, c2);
300 lexerror(ls, "hexadecimal digit expected", TK_STRING);296 lexerror(ls, "hexadecimal digit expected", TK_STRING);
301 }297 }
302 return (hexavalue(c1) << 4) + hexavalue(c2);298 return (luaO_hexavalue(c1) << 4) + luaO_hexavalue(c2);
303}299}
304 300
305 301
src/llex.h+7−7
@@ -1,5 +1,5 @@
1/*1/*
2** $Id: llex.h,v 1.65 2010/04/05 16:35:37 roberto Exp $2** $Id: llex.h,v 1.70 2011/05/03 15:51:16 roberto Exp $
3** Lexical Analyzer3** Lexical Analyzer
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -13,8 +13,6 @@ · 7 unmodified lines
13 13
14#define FIRST_RESERVED 25714#define FIRST_RESERVED 257
15 15
16/* maximum length of a reserved word */
17#define TOKEN_LEN (sizeof("function")/sizeof(char))
18 16
19 17
20/*18/*
@@ -25,7 +23,7 @@ enum RESERVED { · 4 unmodified lines
25 /* terminal symbols denoted by reserved words */23 /* terminal symbols denoted by reserved words */
26 TK_AND = FIRST_RESERVED, TK_BREAK,24 TK_AND = FIRST_RESERVED, TK_BREAK,
27 TK_DO, TK_ELSE, TK_ELSEIF, TK_END, TK_FALSE, TK_FOR, TK_FUNCTION,25 TK_DO, TK_ELSE, TK_ELSEIF, TK_END, TK_FALSE, TK_FOR, TK_FUNCTION,
28 TK_IF, TK_IN, TK_LOCAL, TK_NIL, TK_NOT, TK_OR, TK_REPEAT,26 TK_GOTO, TK_IF, TK_IN, TK_LOCAL, TK_NIL, TK_NOT, TK_OR, TK_REPEAT,
29 TK_RETURN, TK_THEN, TK_TRUE, TK_UNTIL, TK_WHILE,27 TK_RETURN, TK_THEN, TK_TRUE, TK_UNTIL, TK_WHILE,
30 /* other terminal symbols */28 /* other terminal symbols */
31 TK_CONCAT, TK_DOTS, TK_EQ, TK_GE, TK_LE, TK_NE, TK_EOS,29 TK_CONCAT, TK_DOTS, TK_EQ, TK_GE, TK_LE, TK_NE, TK_EOS,
@@ -48,17 +46,19 @@ typedef struct Token { · 16 unmodified lines
48} Token;46} Token;
49 47
50 48
49/* state of the lexer plus state of the parser when shared by all
50 functions */
51typedef struct LexState {51typedef struct LexState {
52 int current; /* current character (charint) */52 int current; /* current character (charint) */
53 int linenumber; /* input line counter */53 int linenumber; /* input line counter */
54 int lastline; /* line of last token `consumed' */54 int lastline; /* line of last token `consumed' */
55 Token t; /* current token */55 Token t; /* current token */
56 Token lookahead; /* look ahead token */56 Token lookahead; /* look ahead token */
57 struct FuncState *fs; /* `FuncState' is private to the parser */57 struct FuncState *fs; /* current function (parser) */
58 struct lua_State *L;58 struct lua_State *L;
59 ZIO *z; /* input stream */59 ZIO *z; /* input stream */
60 Mbuffer *buff; /* buffer for tokens */60 Mbuffer *buff; /* buffer for tokens */
61 struct Varlist *varl; /* list of all active local variables */61 struct Dyndata *dyd; /* dynamic structures used by the parser */
62 TString *source; /* current source name */62 TString *source; /* current source name */
63 TString *envn; /* environment variable name */63 TString *envn; /* environment variable name */
64 char decpoint; /* locale decimal point */64 char decpoint; /* locale decimal point */
@@ -67,7 +67,7 @@ typedef struct LexState { · 2 unmodified lines
67 67
68LUAI_FUNC void luaX_init (lua_State *L);68LUAI_FUNC void luaX_init (lua_State *L);
69LUAI_FUNC void luaX_setinput (lua_State *L, LexState *ls, ZIO *z,69LUAI_FUNC void luaX_setinput (lua_State *L, LexState *ls, ZIO *z,
70 TString *source);70 TString *source, int firstchar);
71LUAI_FUNC TString *luaX_newstring (LexState *ls, const char *str, size_t l);71LUAI_FUNC TString *luaX_newstring (LexState *ls, const char *str, size_t l);
72LUAI_FUNC void luaX_next (LexState *ls);72LUAI_FUNC void luaX_next (LexState *ls);
73LUAI_FUNC int luaX_lookahead (LexState *ls);73LUAI_FUNC int luaX_lookahead (LexState *ls);
src/llimits.h+15−10
@@ -1,5 +1,5 @@
1/*1/*
2** $Id: llimits.h,v 1.84 2010/11/08 16:33:20 roberto Exp $2** $Id: llimits.h,v 1.89 2011/05/05 19:43:14 roberto Exp $
3** Limits, basic types, and some other `installation-dependent' definitions3** Limits, basic types, and some other `installation-dependent' definitions
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -59,9 +59,12 @@ typedef LUAI_UACNUMBER l_uacNumber; · 53 unmodified lines
59/* internal assertions for in-house debugging */59/* internal assertions for in-house debugging */
60#if defined(lua_assert)60#if defined(lua_assert)
61#define check_exp(c,e) (lua_assert(c), (e))61#define check_exp(c,e) (lua_assert(c), (e))
62/* to avoid problems with conditions too long */
63#define lua_longassert(c) { if (!(c)) lua_assert(0); }
62#else64#else
63#define lua_assert(c) /* empty */65#define lua_assert(c) /* empty */
64#define check_exp(c,e) (e)66#define check_exp(c,e) (e)
67#define lua_longassert(c) /* empty */
65#endif68#endif
66 69
67/*70/*
@@ -87,6 +90,7 @@ typedef LUAI_UACNUMBER l_uacNumber; · 19 unmodified lines
87#define cast_byte(i) cast(lu_byte, (i))90#define cast_byte(i) cast(lu_byte, (i))
88#define cast_num(i) cast(lua_Number, (i))91#define cast_num(i) cast(lua_Number, (i))
89#define cast_int(i) cast(int, (i))92#define cast_int(i) cast(int, (i))
93#define cast_uchar(i) cast(unsigned char, (i))
90 94
91 95
92/*96/*
@@ -173,6 +177,9 @@ typedef lu_int32 Instruction; · 80 unmodified lines
173** lua_number2integer is a macro to convert lua_Number to lua_Integer.177** lua_number2integer is a macro to convert lua_Number to lua_Integer.
174** lua_number2unsigned is a macro to convert a lua_Number to a lua_Unsigned.178** lua_number2unsigned is a macro to convert a lua_Number to a lua_Unsigned.
175** lua_unsigned2number is a macro to convert a lua_Unsigned to a lua_Number.179** lua_unsigned2number is a macro to convert a lua_Unsigned to a lua_Number.
180** luai_hashnum is a macro to hash a lua_Number value into an integer.
181** The hash must be deterministic and give reasonable values for
182** both small and large values (outside the range of integers).
176*/183*/
177 184
178#if defined(MS_ASMTRICK) /* { */185#if defined(MS_ASMTRICK) /* { */
@@ -203,6 +210,10 @@ union luai_Cast { double l_d; LUA_INT32 l_p[2]; }; · 24 unmodified lines
203 volatile union luai_Cast u; u.l_d = (n) + 6755399441055744.0; \210 volatile union luai_Cast u; u.l_d = (n) + 6755399441055744.0; \
204 (i) = (t)u.l_p[LUA_IEEEENDIAN]; }211 (i) = (t)u.l_p[LUA_IEEEENDIAN]; }
205 212
213#define luai_hashnum(i,n) \
214 { volatile union luai_Cast u; u.l_d = (n) + 1.0; /* avoid -0 */ \
215 (i) = u.l_p[0] + u.l_p[1]; } /* add double bits for his hash */
216
206#define lua_number2int(i,n) lua_number2int32(i, n, int)217#define lua_number2int(i,n) lua_number2int32(i, n, int)
207#define lua_number2integer(i,n) lua_number2int32(i, n, lua_Integer)218#define lua_number2integer(i,n) lua_number2int32(i, n, lua_Integer)
208#define lua_number2unsigned(i,n) lua_number2int32(i, n, lua_Unsigned)219#define lua_number2unsigned(i,n) lua_number2int32(i, n, lua_Unsigned)
@@ -241,14 +252,8 @@ union luai_Cast { double l_d; LUA_INT32 l_p[2]; }; · 32 unmodified lines
241#endif252#endif
242 253
243 254
244/*
245** luai_hashnum is a macro do hash a lua_Number value into an integer.
246** The hash must be deterministic and give reasonable values for
247** both small and large values (outside the range of integers).
248** It is used only in ltable.c.
249*/
250 255
251#if !defined(luai_hashnum) /* { */256#if (defined(ltable_c) || defined(luaall_c)) && !defined(luai_hashnum)
252 257
253#include <float.h>258#include <float.h>
254#include <math.h>259#include <math.h>
@@ -257,7 +262,7 @@ union luai_Cast { double l_d; LUA_INT32 l_p[2]; }; · 2 unmodified lines
257 n = frexp(n, &e) * (lua_Number)(INT_MAX - DBL_MAX_EXP); \262 n = frexp(n, &e) * (lua_Number)(INT_MAX - DBL_MAX_EXP); \
258 lua_number2int(i, n); i += e; }263 lua_number2int(i, n); i += e; }
259 264
260#endif /* } */265#endif
261 266
262 267
263 268
@@ -275,7 +280,7 @@ union luai_Cast { double l_d; LUA_INT32 l_p[2]; }; · 11 unmodified lines
275#define condchangemem(L) condmovestack(L)280#define condchangemem(L) condmovestack(L)
276#else281#else
277#define condchangemem(L) \282#define condchangemem(L) \
278 ((void)(gcstopped(G(L)) || (luaC_fullgc(L, 0), 1)))283 ((void)(!(G(L)->gcrunning) || (luaC_fullgc(L, 0), 1)))
279#endif284#endif
280 285
281#endif286#endif
src/lmem.c+5−9
@@ -1,5 +1,5 @@
1/*1/*
2** $Id: lmem.c,v 1.79 2010/05/05 18:49:56 roberto Exp $2** $Id: lmem.c,v 1.81 2010/12/20 19:40:07 roberto Exp $
3** Interface to Memory Manager3** Interface to Memory Manager
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -79,14 +79,14 @@ void *luaM_realloc_ (lua_State *L, void *block, size_t osize, size_t nsize) { · 73 unmodified lines
79 size_t realosize = (block) ? osize : 0;79 size_t realosize = (block) ? osize : 0;
80 lua_assert((realosize == 0) == (block == NULL));80 lua_assert((realosize == 0) == (block == NULL));
81#if defined(HARDMEMTESTS)81#if defined(HARDMEMTESTS)
82 if (nsize > realosize && !gcstopped(g))82 if (nsize > realosize && g->gcrunning)
83 luaC_fullgc(L, 1); /* force a GC whenever possible */83 luaC_fullgc(L, 1); /* force a GC whenever possible */
84#endif84#endif
85 newblock = (*g->frealloc)(g->ud, block, osize, nsize);85 newblock = (*g->frealloc)(g->ud, block, osize, nsize);
86 if (newblock == NULL && nsize > 0) {86 if (newblock == NULL && nsize > 0) {
87 api_check(L, nsize > realosize,87 api_check(L, nsize > realosize,
88 "realloc cannot fail when shrinking a block");88 "realloc cannot fail when shrinking a block");
89 if (!gcstopped(g)) {89 if (g->gcrunning) {
90 luaC_fullgc(L, 1); /* try to free some memory... */90 luaC_fullgc(L, 1); /* try to free some memory... */
91 newblock = (*g->frealloc)(g->ud, block, osize, nsize); /* try again */91 newblock = (*g->frealloc)(g->ud, block, osize, nsize); /* try again */
92 }92 }
@@ -94,9 +94,7 @@ void *luaM_realloc_ (lua_State *L, void *block, size_t osize, size_t nsize) { · 1 unmodified line
94 luaD_throw(L, LUA_ERRMEM);94 luaD_throw(L, LUA_ERRMEM);
95 }95 }
96 lua_assert((nsize == 0) == (newblock == NULL));96 lua_assert((nsize == 0) == (newblock == NULL));
97 g->totalbytes = (g->totalbytes - realosize) + nsize;97 g->GCdebt = (g->GCdebt + nsize) - realosize;
98 if (!gcstopped(g))
99 g->GCdebt += nsize; /* give some credit to garbage collector */
100#if defined(TRACEMEM)98#if defined(TRACEMEM)
101 { /* auxiliary patch to monitor garbage collection.99 { /* auxiliary patch to monitor garbage collection.
102 ** To plot, gnuplot with following command:100 ** To plot, gnuplot with following command:
@@ -108,9 +106,7 @@ void *luaM_realloc_ (lua_State *L, void *block, size_t osize, size_t nsize) { · 5 unmodified lines
108 if ((total % 200) == 0) {106 if ((total % 200) == 0) {
109 if (f == NULL) f = fopen(TRACEMEM, "w");107 if (f == NULL) f = fopen(TRACEMEM, "w");
110 fprintf(f, "%lu %u %d %d\n", total,108 fprintf(f, "%lu %u %d %d\n", total,
111 g->totalbytes,109 g->totalbytes, g->GCdebt, g->gcstate * 1000);
112 gcstopped(g) ? 0 : g->GCdebt,
113 g->gcstate * 1000);
114 }110 }
115 }111 }
116#endif112#endif
src/loadlib.c+43−30
@@ -1,5 +1,5 @@
1/*1/*
2** $Id: loadlib.c,v 1.94 2010/11/10 20:00:04 roberto Exp $2** $Id: loadlib.c,v 1.98 2011/04/08 19:17:36 roberto Exp $
3** Dynamic library loader for Lua3** Dynamic library loader for Lua
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5**5**
@@ -164,7 +164,7 @@ static void pusherror (lua_State *L) { · 158 unmodified lines
164 int error = GetLastError();164 int error = GetLastError();
165 char buffer[128];165 char buffer[128];
166 if (FormatMessageA(FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM,166 if (FormatMessageA(FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM,
167 NULL, error, 0, buffer, sizeof(buffer), NULL))167 NULL, error, 0, buffer, sizeof(buffer)/sizeof(char), NULL))
168 lua_pushstring(L, buffer);168 lua_pushstring(L, buffer);
169 else169 else
170 lua_pushfstring(L, "system error %d\n", error);170 lua_pushfstring(L, "system error %d\n", error);
@@ -321,8 +321,10 @@ static const char *pushnexttemplate (lua_State *L, const char *path) { · 150 unmodified lines
321 321
322 322
323static const char *searchpath (lua_State *L, const char *name,323static const char *searchpath (lua_State *L, const char *name,
324 const char *path) {324 const char *path,
325 name = luaL_gsub(L, name, ".", LUA_DIRSEP);325 const char *sep) {
326 if (*sep != '\0') /* non-empty separator? */
327 name = luaL_gsub(L, name, sep, LUA_DIRSEP); /* replace it by proper one */
326 lua_pushliteral(L, ""); /* error accumulator */328 lua_pushliteral(L, ""); /* error accumulator */
327 while ((path = pushnexttemplate(L, path)) != NULL) {329 while ((path = pushnexttemplate(L, path)) != NULL) {
328 const char *filename = luaL_gsub(L, lua_tostring(L, -1),330 const char *filename = luaL_gsub(L, lua_tostring(L, -1),
@@ -339,7 +341,9 @@ static const char *searchpath (lua_State *L, const char *name, · 10 unmodified lines
339 341
340 342
341static int ll_searchpath (lua_State *L) {343static int ll_searchpath (lua_State *L) {
342 const char *f = searchpath(L, luaL_checkstring(L, 1), luaL_checkstring(L, 2));344 const char *f = searchpath(L, luaL_checkstring(L, 1),
345 luaL_checkstring(L, 2),
346 luaL_optstring(L, 3, "."));
343 if (f != NULL) return 1;347 if (f != NULL) return 1;
344 else { /* error message is on top of the stack */348 else { /* error message is on top of the stack */
345 lua_pushnil(L);349 lua_pushnil(L);
@@ -356,13 +360,19 @@ static const char *findfile (lua_State *L, const char *name, · 10 unmodified lines
356 path = lua_tostring(L, -1);360 path = lua_tostring(L, -1);
357 if (path == NULL)361 if (path == NULL)
358 luaL_error(L, LUA_QL("package.%s") " must be a string", pname);362 luaL_error(L, LUA_QL("package.%s") " must be a string", pname);
359 return searchpath(L, name, path);363 return searchpath(L, name, path, ".");
360}364}
361 365
362 366
363static void loaderror (lua_State *L, const char *filename) {367static int checkload (lua_State *L, int stat, const char *filename) {
364 luaL_error(L, "error loading module " LUA_QS " from file " LUA_QS ":\n\t%s",368 if (stat) { /* module loaded successfully? */
365 lua_tostring(L, 1), filename, lua_tostring(L, -1));369 lua_pushstring(L, filename); /* will be 2nd argument to module */
370 return 2; /* return open function and file name */
371 }
372 else
373 return luaL_error(L, "error loading module " LUA_QS
374 " from file " LUA_QS ":\n\t%s",
375 lua_tostring(L, 1), filename, lua_tostring(L, -1));
366}376}
367 377
368 378
@@ -370,10 +380,8 @@ static int loader_Lua (lua_State *L) { · 1 unmodified line
370 const char *filename;380 const char *filename;
371 const char *name = luaL_checkstring(L, 1);381 const char *name = luaL_checkstring(L, 1);
372 filename = findfile(L, name, "path");382 filename = findfile(L, name, "path");
373 if (filename == NULL) return 1; /* library not found in this path */383 if (filename == NULL) return 1; /* module not found in this path */
374 if (luaL_loadfile(L, filename) != LUA_OK)384 return checkload(L, (luaL_loadfile(L, filename) == LUA_OK), filename);
375 loaderror(L, filename);
376 return 1; /* library loaded successfully */
377}385}
378 386
379 387
@@ -398,10 +406,8 @@ static int loadfunc (lua_State *L, const char *filename, const char *modname) { · 18 unmodified lines
398static int loader_C (lua_State *L) {406static int loader_C (lua_State *L) {
399 const char *name = luaL_checkstring(L, 1);407 const char *name = luaL_checkstring(L, 1);
400 const char *filename = findfile(L, name, "cpath");408 const char *filename = findfile(L, name, "cpath");
401 if (filename == NULL) return 1; /* library not found in this path */409 if (filename == NULL) return 1; /* module not found in this path */
402 if (loadfunc(L, filename, name) != 0)410 return checkload(L, (loadfunc(L, filename, name) == 0), filename);
403 loaderror(L, filename);
404 return 1; /* library loaded successfully */
405}411}
406 412
407 413
@@ -415,12 +421,16 @@ static int loader_Croot (lua_State *L) { · 7 unmodified lines
415 filename = findfile(L, lua_tostring(L, -1), "cpath");421 filename = findfile(L, lua_tostring(L, -1), "cpath");
416 if (filename == NULL) return 1; /* root not found */422 if (filename == NULL) return 1; /* root not found */
417 if ((stat = loadfunc(L, filename, name)) != 0) {423 if ((stat = loadfunc(L, filename, name)) != 0) {
418 if (stat != ERRFUNC) loaderror(L, filename); /* real error */424 if (stat != ERRFUNC)
419 lua_pushfstring(L, "\n\tno module " LUA_QS " in file " LUA_QS,425 return checkload(L, 0, filename); /* real error */
420 name, filename);426 else { /* open function not found */
421 return 1; /* function not found */427 lua_pushfstring(L, "\n\tno module " LUA_QS " in file " LUA_QS,
428 name, filename);
429 return 1;
430 }
422 }431 }
423 return 1;432 lua_pushstring(L, filename); /* will be 2nd argument to module */
433 return 2;
424}434}
425 435
426 436
@@ -453,16 +463,19 @@ static int ll_require (lua_State *L) { · 26 unmodified lines
453 luaL_error(L, "module " LUA_QS " not found:%s",463 luaL_error(L, "module " LUA_QS " not found:%s",
454 name, lua_tostring(L, -2));464 name, lua_tostring(L, -2));
455 lua_pushstring(L, name);465 lua_pushstring(L, name);
456 lua_call(L, 1, 1); /* call it */466 lua_call(L, 1, 2); /* call it */
457 if (lua_isfunction(L, -1)) /* did it find module? */467 if (lua_isfunction(L, -2)) /* did it find module? */
458 break; /* module loaded successfully */468 break; /* module loaded successfully */
459 else if (lua_isstring(L, -1)) /* loader returned error message? */469 else if (lua_isstring(L, -2)) { /* loader returned error message? */
460 lua_concat(L, 2); /* accumulate it */470 lua_pop(L, 1); /* remove extra return */
471 lua_concat(L, 2); /* accumulate error message */
472 }
461 else473 else
462 lua_pop(L, 1);474 lua_pop(L, 2); /* remove both returns */
463 }475 }
464 lua_pushstring(L, name); /* pass name as argument to module */476 lua_pushstring(L, name); /* pass name as argument to module */
465 lua_call(L, 1, 1); /* run loaded module */477 lua_insert(L, -2); /* name is 1st argument (before search data) */
478 lua_call(L, 2, 1); /* run loaded module */
466 if (!lua_isnil(L, -1)) /* non-nil return? */479 if (!lua_isnil(L, -1)) /* non-nil return? */
467 lua_setfield(L, 2, name); /* _LOADED[name] = returned value */480 lua_setfield(L, 2, name); /* _LOADED[name] = returned value */
468 lua_getfield(L, 2, name);481 lua_getfield(L, 2, name);
@@ -639,10 +652,10 @@ LUAMOD_API int luaopen_package (lua_State *L) { · 170 unmodified lines
639 LUA_EXEC_DIR "\n" LUA_IGMARK "\n");652 LUA_EXEC_DIR "\n" LUA_IGMARK "\n");
640 lua_setfield(L, -2, "config");653 lua_setfield(L, -2, "config");
641 /* set field `loaded' */654 /* set field `loaded' */
642 luaL_findtable(L, LUA_REGISTRYINDEX, "_LOADED");655 luaL_getsubtable(L, LUA_REGISTRYINDEX, "_LOADED");
643 lua_setfield(L, -2, "loaded");656 lua_setfield(L, -2, "loaded");
644 /* set field `preload' */657 /* set field `preload' */
645 luaL_findtable(L, LUA_REGISTRYINDEX, "_PRELOAD");658 luaL_getsubtable(L, LUA_REGISTRYINDEX, "_PRELOAD");
646 lua_setfield(L, -2, "preload");659 lua_setfield(L, -2, "preload");
647 lua_pushglobaltable(L);660 lua_pushglobaltable(L);
648 lua_pushvalue(L, -2); /* set 'package' as upvalue for next lib */661 lua_pushvalue(L, -2); /* set 'package' as upvalue for next lib */
src/lobject.c+86−38
@@ -1,5 +1,5 @@
1/*1/*
2** $Id: lobject.c,v 2.43 2010/10/29 15:54:55 roberto Exp $2** $Id: lobject.c,v 2.49 2011/05/31 18:24:36 roberto Exp $
3** Some generic functions over Lua objects3** Some generic functions over Lua objects
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -70,28 +70,6 @@ int luaO_ceillog2 (unsigned int x) { · 64 unmodified lines
70}70}
71 71
72 72
73int luaO_rawequalObj (const TValue *t1, const TValue *t2) {
74 if (ttype(t1) != ttype(t2)) return 0;
75 else switch (ttype(t1)) {
76 case LUA_TNIL:
77 return 1;
78 case LUA_TNUMBER:
79 return luai_numeq(nvalue(t1), nvalue(t2));
80 case LUA_TBOOLEAN:
81 return bvalue(t1) == bvalue(t2); /* boolean true must be 1 !! */
82 case LUA_TLIGHTUSERDATA:
83 return pvalue(t1) == pvalue(t2);
84 case LUA_TSTRING:
85 return rawtsvalue(t1) == rawtsvalue(t2);
86 case LUA_TLCF:
87 return fvalue(t1) == fvalue(t2);
88 default:
89 lua_assert(iscollectable(t1));
90 return gcvalue(t1) == gcvalue(t2);
91 }
92}
93
94
95lua_Number luaO_arith (int op, lua_Number v1, lua_Number v2) {73lua_Number luaO_arith (int op, lua_Number v1, lua_Number v2) {
96 switch (op) {74 switch (op) {
97 case LUA_OPADD: return luai_numadd(NULL, v1, v2);75 case LUA_OPADD: return luai_numadd(NULL, v1, v2);
@@ -106,19 +84,87 @@ lua_Number luaO_arith (int op, lua_Number v1, lua_Number v2) { · 8 unmodified lines
106}84}
107 85
108 86
109static int checkend (const char *s, const char *endptr) {87int luaO_hexavalue (int c) {
110 if (endptr == s) return 0; /* no characters converted */88 if (lisdigit(c)) return c - '0';
111 while (lisspace(cast(unsigned char, *endptr))) endptr++;89 else if (lisupper(c)) return c - 'A' + 10;
112 return (*endptr == '\0'); /* OK if no trailing characters */90 else return c - 'a' + 10;
91}
92
93
94#if !defined(lua_strx2number)
95
96#include <math.h>
97
98
99static int isneg (const char **s) {
100 if (**s == '-') { (*s)++; return 1; }
101 else if (**s == '+') (*s)++;
102 return 0;
113}103}
114 104
115 105
116int luaO_str2d (const char *s, lua_Number *result) {106static lua_Number readhexa (const char **s, lua_Number r, int *count) {
107 while (lisxdigit(cast_uchar(**s))) { /* read integer part */
108 r = (r * 16.0) + (double)luaO_hexavalue(*(*s)++);
109 (*count)++;
110 }
111 return r;
112}
113
114
115/*
116** convert an hexadecimal numeric string to a number, following
117** C99 specification for 'strtod'
118*/
119static lua_Number lua_strx2number (const char *s, char **endptr) {
120 lua_Number r = 0.0;
121 int e = 0, i = 0;
122 int neg = 0; /* 1 if number is negative */
123 *endptr = cast(char *, s); /* nothing is valid yet */
124 while (lisspace(cast_uchar(*s))) s++; /* skip initial spaces */
125 neg = isneg(&s); /* check signal */
126 if (!(*s == '0' && (*(s + 1) == 'x' || *(s + 1) == 'X'))) /* check '0x' */
127 return 0.0; /* invalid format (no '0x') */
128 s += 2; /* skip '0x' */
129 r = readhexa(&s, r, &i); /* read integer part */
130 if (*s == '.') {
131 s++; /* skip dot */
132 r = readhexa(&s, r, &e); /* read fractional part */
133 }
134 if (i == 0 && e == 0)
135 return 0.0; /* invalid format (no digit) */
136 e *= -4; /* each fractional digit divides value by 2^-4 */
137 *endptr = cast(char *, s); /* valid up to here */
138 if (*s == 'p' || *s == 'P') { /* exponent part? */
139 int exp1 = 0;
140 int neg1;
141 s++; /* skip 'p' */
142 neg1 = isneg(&s); /* signal */
143 if (!lisdigit(cast_uchar(*s)))
144 goto ret; /* must have at least one digit */
145 while (lisdigit(cast_uchar(*s))) /* read exponent */
146 exp1 = exp1 * 10 + *(s++) - '0';
147 if (neg1) exp1 = -exp1;
148 e += exp1;
149 }
150 *endptr = cast(char *, s); /* valid up to here */
151 ret:
152 if (neg) r = -r;
153 return ldexp(r, e);
154}
155
156#endif
157
158
159int luaO_str2d (const char *s, size_t len, lua_Number *result) {
117 char *endptr;160 char *endptr;
118 *result = lua_str2number(s, &endptr);161 if (strpbrk(s, "xX")) /* hexa? */
119 if (checkend(s, endptr)) return 1; /* conversion OK? */162 *result = lua_strx2number(s, &endptr);
120 *result = cast_num(strtoul(s, &endptr, 0)); /* try hexadecimal */163 else
121 return checkend(s, endptr);164 *result = lua_str2number(s, &endptr);
165 if (endptr == s) return 0; /* nothing recognized */
166 while (lisspace(cast_uchar(*endptr))) endptr++;
167 return (endptr == s + len); /* OK if no trailing characters */
122}168}
123 169
124 170
@@ -196,19 +242,20 @@ const char *luaO_pushfstring (lua_State *L, const char *fmt, ...) { · 71 unmodified lines
196}242}
197 243
198 244
245/* number of chars of a literal string without the ending \0 */
246#define LL(x) (sizeof(x)/sizeof(char) - 1)
199 247
200#define LL(x) (sizeof(x) - 1)
201#define RETS "..."248#define RETS "..."
202#define PRE "[string \""249#define PRE "[string \""
203#define POS "\"]"250#define POS "\"]"
204 251
205#define addstr(a,b,l) ( memcpy(a,b,l), a += (l) )252#define addstr(a,b,l) ( memcpy(a,b,(l) * sizeof(char)), a += (l) )
206 253
207void luaO_chunkid (char *out, const char *source, size_t bufflen) {254void luaO_chunkid (char *out, const char *source, size_t bufflen) {
208 size_t l = strlen(source);255 size_t l = strlen(source);
209 if (*source == '=') { /* 'literal' source */256 if (*source == '=') { /* 'literal' source */
210 if (l <= bufflen) /* small enough? */257 if (l <= bufflen) /* small enough? */
211 memcpy(out, source + 1, l);258 memcpy(out, source + 1, l * sizeof(char));
212 else { /* truncate it */259 else { /* truncate it */
213 addstr(out, source + 1, bufflen - 1);260 addstr(out, source + 1, bufflen - 1);
214 *out = '\0';261 *out = '\0';
@@ -216,11 +263,11 @@ void luaO_chunkid (char *out, const char *source, size_t bufflen) { · 1 unmodified line
216 }263 }
217 else if (*source == '@') { /* file name */264 else if (*source == '@') { /* file name */
218 if (l <= bufflen) /* small enough? */265 if (l <= bufflen) /* small enough? */
219 memcpy(out, source + 1, l);266 memcpy(out, source + 1, l * sizeof(char));
220 else { /* add '...' before rest of name */267 else { /* add '...' before rest of name */
221 addstr(out, RETS, LL(RETS));268 addstr(out, RETS, LL(RETS));
222 bufflen -= LL(RETS);269 bufflen -= LL(RETS);
223 memcpy(out, source + 1 + l - bufflen, bufflen);270 memcpy(out, source + 1 + l - bufflen, bufflen * sizeof(char));
224 }271 }
225 }272 }
226 else { /* string; format as [string "source"] */273 else { /* string; format as [string "source"] */
@@ -236,6 +283,7 @@ void luaO_chunkid (char *out, const char *source, size_t bufflen) { · 9 unmodified lines
236 addstr(out, source, l);283 addstr(out, source, l);
237 addstr(out, RETS, LL(RETS));284 addstr(out, RETS, LL(RETS));
238 }285 }
239 memcpy(out, POS, LL(POS) + 1);286 memcpy(out, POS, (LL(POS) + 1) * sizeof(char));
240 }287 }
241}288}
289
src/lobject.h+241−87
@@ -1,5 +1,5 @@
1/*1/*
2** $Id: lobject.h,v 2.42 2010/07/26 15:53:23 roberto Exp $2** $Id: lobject.h,v 2.60 2011/06/13 14:13:06 roberto Exp $
3** Type definitions for Lua objects3** Type definitions for Lua objects
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -23,12 +23,38 @@ · 17 unmodified lines
23#define LUA_TUPVAL (LUA_NUMTAGS+1)23#define LUA_TUPVAL (LUA_NUMTAGS+1)
24#define LUA_TDEADKEY (LUA_NUMTAGS+2)24#define LUA_TDEADKEY (LUA_NUMTAGS+2)
25 25
26/*
27** number of all possible tags (including LUA_TNONE but excluding DEADKEY)
28*/
29#define LUA_TOTALTAGS (LUA_TUPVAL+2)
30
31
32/*
33** tags for Tagged Values have the following use of bits:
34** bits 0-3: actual tag (a LUA_T* value)
35** bits 4-5: variant bits
36** bit 6: whether value is collectable
37*/
26 38
27/*39/*
28** Variant tag for light C functions (negative to be considered40** LUA_TFUNCTION variants:
29** non collectable by 'iscollectable')41** 0 - Lua function
42** 1 - light C function
43** 2 - regular C function (closure)
30*/44*/
31#define LUA_TLCF (~0x0F | LUA_TFUNCTION)45
46/* Variant tags for functions */
47#define LUA_TLCL (LUA_TFUNCTION | (0 << 4)) /* Lua closure */
48#define LUA_TLCF (LUA_TFUNCTION | (1 << 4)) /* light C function */
49#define LUA_TCCL (LUA_TFUNCTION | (2 << 4)) /* C closure */
50
51
52/* Bit mark for collectable types */
53#define BIT_ISCOLLECTABLE (1 << 6)
54
55/* mark a tag as collectable */
56#define ctb(t) ((t) | BIT_ISCOLLECTABLE)
57
32 58
33/*59/*
34** Union of all collectable objects60** Union of all collectable objects
@@ -55,13 +81,10 @@ typedef struct GCheader { · 20 unmodified lines
55/*81/*
56** Union of all Lua values82** Union of all Lua values
57*/83*/
58typedef union {84typedef union Value Value;
59 GCObject *gc; /* collectable objects */85
60 void *p; /* light userdata */86
61 lua_Number n; /* numbers */87#define numfield lua_Number n; /* numbers */
62 int b; /* booleans */
63 lua_CFunction f; /* light C functions */
64} Value;
65 88
66 89
67 90
@@ -72,125 +95,143 @@ typedef union { · 4 unmodified lines
72 95
73#define TValuefields Value value_; int tt_96#define TValuefields Value value_; int tt_
74 97
75typedef struct lua_TValue {98typedef struct lua_TValue TValue;
76 TValuefields;
77} TValue;
78 99
79 100
80/* macro defining a nil value */101/* macro defining a nil value */
81#define NILCONSTANT {NULL}, LUA_TNIL102#define NILCONSTANT {NULL}, LUA_TNIL
82 103
83 104
84/*105#define val_(o) ((o)->value_)
85** type tag of a TValue106#define num_(o) (val_(o).n)
86*/
87#define ttype(o) ((o)->tt_)
88 107
89 108
90/*109/* raw type tag of a TValue */
91** type tag of a TValue with no variants110#define rttype(o) ((o)->tt_)
92*/111
93#define ttypenv(o) (ttype(o) & 0x0F)112/* type tag of a TValue (bits 0-3 for tags + variant bits 4-5) */
113#define ttype(o) (rttype(o) & 0x3F)
114
115
116/* type tag of a TValue with no variants (bits 0-3) */
117#define ttypenv(o) (rttype(o) & 0x0F)
94 118
95 119
96/* Macros to test type */120/* Macros to test type */
97#define ttisnil(o) (ttype(o) == LUA_TNIL)121#define checktag(o,t) (rttype(o) == (t))
98#define ttisnumber(o) (ttype(o) == LUA_TNUMBER)122#define ttisnumber(o) checktag((o), LUA_TNUMBER)
99#define ttisstring(o) (ttype(o) == LUA_TSTRING)123#define ttisnil(o) checktag((o), LUA_TNIL)
100#define ttistable(o) (ttype(o) == LUA_TTABLE)124#define ttisboolean(o) checktag((o), LUA_TBOOLEAN)
101#define ttisfunction(o) (ttypenv(o) == LUA_TFUNCTION)125#define ttislightuserdata(o) checktag((o), LUA_TLIGHTUSERDATA)
102#define ttisclosure(o) (ttype(o) == LUA_TFUNCTION)126#define ttisstring(o) checktag((o), ctb(LUA_TSTRING))
103#define ttislcf(o) (ttype(o) == LUA_TLCF)127#define ttistable(o) checktag((o), ctb(LUA_TTABLE))
104#define ttisboolean(o) (ttype(o) == LUA_TBOOLEAN)128#define ttisfunction(o) (ttypenv(o) == LUA_TFUNCTION)
105#define ttisuserdata(o) (ttype(o) == LUA_TUSERDATA)129#define ttisclosure(o) ((rttype(o) & 0x1F) == LUA_TFUNCTION)
106#define ttisthread(o) (ttype(o) == LUA_TTHREAD)130#define ttisCclosure(o) checktag((o), ctb(LUA_TCCL))
107#define ttislightuserdata(o) (ttype(o) == LUA_TLIGHTUSERDATA)131#define ttisLclosure(o) checktag((o), ctb(LUA_TLCL))
108#define ttisdeadkey(o) (ttype(o) == LUA_TDEADKEY)132#define ttislcf(o) checktag((o), LUA_TLCF)
133#define ttisuserdata(o) checktag((o), ctb(LUA_TUSERDATA))
134#define ttisthread(o) checktag((o), ctb(LUA_TTHREAD))
135#define ttisdeadkey(o) checktag((o), ctb(LUA_TDEADKEY))
136
137#define ttisequal(o1,o2) (rttype(o1) == rttype(o2))
109 138
110/* Macros to access values */139/* Macros to access values */
111#define gcvalue(o) check_exp(iscollectable(o), (o)->value_.gc)140#define nvalue(o) check_exp(ttisnumber(o), num_(o))
112#define pvalue(o) check_exp(ttislightuserdata(o), (o)->value_.p)141#define gcvalue(o) check_exp(iscollectable(o), val_(o).gc)
113#define nvalue(o) check_exp(ttisnumber(o), (o)->value_.n)142#define pvalue(o) check_exp(ttislightuserdata(o), val_(o).p)
114#define rawtsvalue(o) check_exp(ttisstring(o), &(o)->value_.gc->ts)143#define rawtsvalue(o) check_exp(ttisstring(o), &val_(o).gc->ts)
115#define tsvalue(o) (&rawtsvalue(o)->tsv)144#define tsvalue(o) (&rawtsvalue(o)->tsv)
116#define rawuvalue(o) check_exp(ttisuserdata(o), &(o)->value_.gc->u)145#define rawuvalue(o) check_exp(ttisuserdata(o), &val_(o).gc->u)
117#define uvalue(o) (&rawuvalue(o)->uv)146#define uvalue(o) (&rawuvalue(o)->uv)
118#define clvalue(o) check_exp(ttisclosure(o), &(o)->value_.gc->cl)147#define clvalue(o) check_exp(ttisclosure(o), &val_(o).gc->cl)
119#define fvalue(o) check_exp(ttislcf(o), (o)->value_.f)148#define clLvalue(o) check_exp(ttisLclosure(o), &val_(o).gc->cl.l)
120#define hvalue(o) check_exp(ttistable(o), &(o)->value_.gc->h)149#define clCvalue(o) check_exp(ttisCclosure(o), &val_(o).gc->cl.c)
121#define bvalue(o) check_exp(ttisboolean(o), (o)->value_.b)150#define fvalue(o) check_exp(ttislcf(o), val_(o).f)
122#define thvalue(o) check_exp(ttisthread(o), &(o)->value_.gc->th)151#define hvalue(o) check_exp(ttistable(o), &val_(o).gc->h)
152#define bvalue(o) check_exp(ttisboolean(o), val_(o).b)
153#define thvalue(o) check_exp(ttisthread(o), &val_(o).gc->th)
123 154
124#define l_isfalse(o) (ttisnil(o) || (ttisboolean(o) && bvalue(o) == 0))155#define l_isfalse(o) (ttisnil(o) || (ttisboolean(o) && bvalue(o) == 0))
125 156
126 157
127#define iscollectable(o) (ttype(o) >= LUA_TSTRING)158#define iscollectable(o) (rttype(o) & BIT_ISCOLLECTABLE)
128 159
129 160
130/* Macros for internal tests */161/* Macros for internal tests */
131#define righttt(obj) (ttype(obj) == gcvalue(obj)->gch.tt)162#define righttt(obj) (ttypenv(obj) == gcvalue(obj)->gch.tt)
132
133#define checkconsistency(obj) lua_assert(!iscollectable(obj) || righttt(obj))
134 163
135#define checkliveness(g,obj) \164#define checkliveness(g,obj) \
136 lua_assert(!iscollectable(obj) || (righttt(obj) && !isdead(g,gcvalue(obj))))165 lua_longassert(!iscollectable(obj) || \
166 (righttt(obj) && !isdead(g,gcvalue(obj))))
137 167
138 168
139/* Macros to set values */169/* Macros to set values */
140#define setnilvalue(obj) ((obj)->tt_=LUA_TNIL)170#define settt_(o,t) ((o)->tt_=(t))
141 171
142#define setnvalue(obj,x) \172#define setnvalue(obj,x) \
143 { TValue *i_o=(obj); i_o->value_.n=(x); i_o->tt_=LUA_TNUMBER; }173 { TValue *io=(obj); num_(io)=(x); settt_(io, LUA_TNUMBER); }
144 174
145#define setfvalue(obj,x) \175#define changenvalue(o,x) check_exp(ttisnumber(o), num_(o)=(x))
146 { TValue *i_o=(obj); i_o->value_.f=(x); i_o->tt_=LUA_TLCF; }
147 176
148#define changenvalue(o,x) check_exp((o)->tt_==LUA_TNUMBER, (o)->value_.n=(x))177#define setnilvalue(obj) settt_(obj, LUA_TNIL)
178
179#define setfvalue(obj,x) \
180 { TValue *io=(obj); val_(io).f=(x); settt_(io, LUA_TLCF); }
149 181
150#define setpvalue(obj,x) \182#define setpvalue(obj,x) \
151 { TValue *i_o=(obj); i_o->value_.p=(x); i_o->tt_=LUA_TLIGHTUSERDATA; }183 { TValue *io=(obj); val_(io).p=(x); settt_(io, LUA_TLIGHTUSERDATA); }
152 184
153#define setbvalue(obj,x) \185#define setbvalue(obj,x) \
154 { TValue *i_o=(obj); i_o->value_.b=(x); i_o->tt_=LUA_TBOOLEAN; }186 { TValue *io=(obj); val_(io).b=(x); settt_(io, LUA_TBOOLEAN); }
187
188#define setgcovalue(L,obj,x) \
189 { TValue *io=(obj); GCObject *i_g=(x); \
190 val_(io).gc=i_g; settt_(io, ctb(gch(i_g)->tt)); }
155 191
156#define setsvalue(L,obj,x) \192#define setsvalue(L,obj,x) \
157 { TValue *i_o=(obj); \193 { TValue *io=(obj); \
158 i_o->value_.gc=cast(GCObject *, (x)); i_o->tt_=LUA_TSTRING; \194 val_(io).gc=cast(GCObject *, (x)); settt_(io, ctb(LUA_TSTRING)); \
159 checkliveness(G(L),i_o); }195 checkliveness(G(L),io); }
160 196
161#define setuvalue(L,obj,x) \197#define setuvalue(L,obj,x) \
162 { TValue *i_o=(obj); \198 { TValue *io=(obj); \
163 i_o->value_.gc=cast(GCObject *, (x)); i_o->tt_=LUA_TUSERDATA; \199 val_(io).gc=cast(GCObject *, (x)); settt_(io, ctb(LUA_TUSERDATA)); \
164 checkliveness(G(L),i_o); }200 checkliveness(G(L),io); }
165 201
166#define setthvalue(L,obj,x) \202#define setthvalue(L,obj,x) \
167 { TValue *i_o=(obj); \203 { TValue *io=(obj); \
168 i_o->value_.gc=cast(GCObject *, (x)); i_o->tt_=LUA_TTHREAD; \204 val_(io).gc=cast(GCObject *, (x)); settt_(io, ctb(LUA_TTHREAD)); \
169 checkliveness(G(L),i_o); }205 checkliveness(G(L),io); }
206
207#define setclLvalue(L,obj,x) \
208 { TValue *io=(obj); \
209 val_(io).gc=cast(GCObject *, (x)); settt_(io, ctb(LUA_TLCL)); \
210 checkliveness(G(L),io); }
170 211
171#define setclvalue(L,obj,x) \212#define setclCvalue(L,obj,x) \
172 { TValue *i_o=(obj); \213 { TValue *io=(obj); \
173 i_o->value_.gc=cast(GCObject *, (x)); i_o->tt_=LUA_TFUNCTION; \214 val_(io).gc=cast(GCObject *, (x)); settt_(io, ctb(LUA_TCCL)); \
174 checkliveness(G(L),i_o); }215 checkliveness(G(L),io); }
175 216
176#define sethvalue(L,obj,x) \217#define sethvalue(L,obj,x) \
177 { TValue *i_o=(obj); \218 { TValue *io=(obj); \
178 i_o->value_.gc=cast(GCObject *, (x)); i_o->tt_=LUA_TTABLE; \219 val_(io).gc=cast(GCObject *, (x)); settt_(io, ctb(LUA_TTABLE)); \
179 checkliveness(G(L),i_o); }220 checkliveness(G(L),io); }
180 221
181#define setptvalue(L,obj,x) \222#define setptvalue(L,obj,x) \
182 { TValue *i_o=(obj); \223 { TValue *io=(obj); \
183 i_o->value_.gc=cast(GCObject *, (x)); i_o->tt_=LUA_TPROTO; \224 val_(io).gc=cast(GCObject *, (x)); settt_(io, ctb(LUA_TPROTO)); \
184 checkliveness(G(L),i_o); }225 checkliveness(G(L),io); }
185 226
186#define setdeadvalue(obj) ((obj)->tt_=LUA_TDEADKEY)227#define setdeadvalue(obj) settt_(obj, ctb(LUA_TDEADKEY))
187 228
188 229
189 230
190#define setobj(L,obj1,obj2) \231#define setobj(L,obj1,obj2) \
191 { const TValue *o2=(obj2); TValue *o1=(obj1); \232 { const TValue *io2=(obj2); TValue *io1=(obj1); \
192 o1->value_ = o2->value_; o1->tt_=o2->tt_; \233 io1->value_ = io2->value_; io1->tt_ = io2->tt_; \
193 checkliveness(G(L),o1); }234 checkliveness(G(L),io1); }
194 235
195 236
196/*237/*
@@ -214,9 +255,121 @@ typedef struct lua_TValue { · 17 unmodified lines
214 255
215 256
216 257
258
259/*
260** {======================================================
261** NaN Trick
262** =======================================================
263*/
264
265#if defined(LUA_NANTRICKLE) || defined(LUA_NANTRICKBE)
266
267/*
268** numbers are represented in the 'd_' field. All other values have the
269** value (NNMARK | tag) in 'tt_'. A number with such pattern would be
270** a "signaled NaN", which is never generated by regular operations by
271** the CPU (nor by 'strtod')
272*/
273#if !defined(NNMARK)
274#define NNMARK 0x7FF7A500
275#endif
276
277#undef TValuefields
278#if defined(LUA_NANTRICKLE)
279/* little endian */
280#define TValuefields \
281 union { struct { Value v_; int tt_; } i; double d_; } u
282#else
283/* big endian */
284#define TValuefields \
285 union { struct { int tt_; Value v_; } i; double d_; } u
286#endif
287
288#undef numfield
289#define numfield /* no such field; numbers are the entire struct */
290
291/* basic check to distinguish numbers from non-numbers */
292#undef ttisnumber
293#define ttisnumber(o) (((o)->u.i.tt_ & 0x7fffff00) != NNMARK)
294
295#define tag2tt(t) (NNMARK | (t))
296
297#undef NILCONSTANT
298#define NILCONSTANT {{{NULL}, tag2tt(LUA_TNIL)}}
299
300#undef val_
301#define val_(o) ((o)->u.i.v_)
302#undef num_
303#define num_(o) ((o)->u.d_)
304
305#undef rttype
306#define rttype(o) (ttisnumber(o) ? LUA_TNUMBER : (o)->u.i.tt_ & 0xff)
307
308#undef settt_
309#define settt_(o,t) ((o)->u.i.tt_=tag2tt(t))
310
311#undef setnvalue
312#define setnvalue(obj,x) \
313 { TValue *io_=(obj); num_(io_)=(x); lua_assert(ttisnumber(io_)); }
314
315#undef setobj
316#define setobj(L,obj1,obj2) \
317 { const TValue *o2_=(obj2); TValue *o1_=(obj1); \
318 o1_->u = o2_->u; \
319 checkliveness(G(L),o1_); }
320
321
322/*
323** these redefinitions are not mandatory, but these forms are more efficient
324*/
325
326#undef checktag
327#define checktag(o,t) ((o)->u.i.tt_ == tag2tt(t))
328
329#undef ttisequal
330#define ttisequal(o1,o2) \
331 (ttisnumber(o1) ? ttisnumber(o2) : ((o1)->u.i.tt_ == (o2)->u.i.tt_))
332
333
334
335#define luai_checknum(L,o,c) { if (!ttisnumber(o)) c; }
336
337
338#else
339
340#define luai_checknum(L,o,c) { /* empty */ }
341
342#endif
343/* }====================================================== */
344
345
346
347/*
348** {======================================================
349** types and prototypes
350** =======================================================
351*/
352
353
354union Value {
355 GCObject *gc; /* collectable objects */
356 void *p; /* light userdata */
357 int b; /* booleans */
358 lua_CFunction f; /* light C functions */
359 numfield /* numbers */
360};
361
362
363struct lua_TValue {
364 TValuefields;
365};
366
367
217typedef TValue *StkId; /* index to stack elements */368typedef TValue *StkId; /* index to stack elements */
218 369
219 370
371
372
220/*373/*
221** Header for string value; string bytes follow the end of this structure374** Header for string value; string bytes follow the end of this structure
222*/375*/
@@ -226,7 +379,7 @@ typedef union TString { · 3 unmodified lines
226 CommonHeader;379 CommonHeader;
227 lu_byte reserved;380 lu_byte reserved;
228 unsigned int hash;381 unsigned int hash;
229 size_t len;382 size_t len; /* number of characters in string */
230 } tsv;383 } tsv;
231} TString;384} TString;
232 385
@@ -247,7 +400,7 @@ typedef union Udata { · 14 unmodified lines
247 CommonHeader;400 CommonHeader;
248 struct Table *metatable;401 struct Table *metatable;
249 struct Table *env;402 struct Table *env;
250 size_t len;403 size_t len; /* number of bytes */
251 } uv;404 } uv;
252} Udata;405} Udata;
253 406
@@ -346,9 +499,9 @@ typedef union Closure { · 92 unmodified lines
346} Closure;499} Closure;
347 500
348 501
349#define isLfunction(o) (ttisclosure(o) && !clvalue(o)->c.isC)502#define isLfunction(o) ttisLclosure(o)
350 503
351#define getproto(o) (clvalue(o)->l.p)504#define getproto(o) (clLvalue(o)->p)
352 505
353 506
354/*507/*
@@ -403,12 +556,13 @@ typedef struct Table { · 48 unmodified lines
403 556
404LUAI_DDEC const TValue luaO_nilobject_;557LUAI_DDEC const TValue luaO_nilobject_;
405 558
559
406LUAI_FUNC int luaO_int2fb (unsigned int x);560LUAI_FUNC int luaO_int2fb (unsigned int x);
407LUAI_FUNC int luaO_fb2int (int x);561LUAI_FUNC int luaO_fb2int (int x);
408LUAI_FUNC int luaO_ceillog2 (lu_int32 x);562LUAI_FUNC int luaO_ceillog2 (unsigned int x);
409LUAI_FUNC lua_Number luaO_arith (int op, lua_Number v1, lua_Number v2);563LUAI_FUNC lua_Number luaO_arith (int op, lua_Number v1, lua_Number v2);
410LUAI_FUNC int luaO_rawequalObj (const TValue *t1, const TValue *t2);564LUAI_FUNC int luaO_str2d (const char *s, size_t len, lua_Number *result);
411LUAI_FUNC int luaO_str2d (const char *s, lua_Number *result);565LUAI_FUNC int luaO_hexavalue (int c);
412LUAI_FUNC const char *luaO_pushvfstring (lua_State *L, const char *fmt,566LUAI_FUNC const char *luaO_pushvfstring (lua_State *L, const char *fmt,
413 va_list argp);567 va_list argp);
414LUAI_FUNC const char *luaO_pushfstring (lua_State *L, const char *fmt, ...);568LUAI_FUNC const char *luaO_pushfstring (lua_State *L, const char *fmt, ...);
src/lopcodes.c+5−5
@@ -1,5 +1,5 @@
1/*1/*
2** $Id: lopcodes.c,v 1.44 2010/10/13 16:45:54 roberto Exp $2** $Id: lopcodes.c,v 1.48 2011/04/19 16:22:13 roberto Exp $
3** See Copyright Notice in lua.h3** See Copyright Notice in lua.h
4*/4*/
5 5
@@ -16,6 +16,7 @@ · 10 unmodified lines
16LUAI_DDEF const char *const luaP_opnames[NUM_OPCODES+1] = {16LUAI_DDEF const char *const luaP_opnames[NUM_OPCODES+1] = {
17 "MOVE",17 "MOVE",
18 "LOADK",18 "LOADK",
19 "LOADKX",
19 "LOADBOOL",20 "LOADBOOL",
20 "LOADNIL",21 "LOADNIL",
21 "GETUPVAL",22 "GETUPVAL",
@@ -50,7 +51,6 @@ LUAI_DDEF const char *const luaP_opnames[NUM_OPCODES+1] = { · 28 unmodified lines
50 "TFORCALL",51 "TFORCALL",
51 "TFORLOOP",52 "TFORLOOP",
52 "SETLIST",53 "SETLIST",
53 "CLOSE",
54 "CLOSURE",54 "CLOSURE",
55 "VARARG",55 "VARARG",
56 "EXTRAARG",56 "EXTRAARG",
@@ -64,8 +64,9 @@ LUAI_DDEF const lu_byte luaP_opmodes[NUM_OPCODES] = { · 7 unmodified lines
64/* T A B C mode opcode */64/* T A B C mode opcode */
65 opmode(0, 1, OpArgR, OpArgN, iABC) /* OP_MOVE */65 opmode(0, 1, OpArgR, OpArgN, iABC) /* OP_MOVE */
66 ,opmode(0, 1, OpArgK, OpArgN, iABx) /* OP_LOADK */66 ,opmode(0, 1, OpArgK, OpArgN, iABx) /* OP_LOADK */
67 ,opmode(0, 1, OpArgN, OpArgN, iABx) /* OP_LOADKX */
67 ,opmode(0, 1, OpArgU, OpArgU, iABC) /* OP_LOADBOOL */68 ,opmode(0, 1, OpArgU, OpArgU, iABC) /* OP_LOADBOOL */
68 ,opmode(0, 1, OpArgR, OpArgN, iABC) /* OP_LOADNIL */69 ,opmode(0, 1, OpArgU, OpArgN, iABC) /* OP_LOADNIL */
69 ,opmode(0, 1, OpArgU, OpArgN, iABC) /* OP_GETUPVAL */70 ,opmode(0, 1, OpArgU, OpArgN, iABC) /* OP_GETUPVAL */
70 ,opmode(0, 1, OpArgU, OpArgK, iABC) /* OP_GETTABUP */71 ,opmode(0, 1, OpArgU, OpArgK, iABC) /* OP_GETTABUP */
71 ,opmode(0, 1, OpArgR, OpArgK, iABC) /* OP_GETTABLE */72 ,opmode(0, 1, OpArgR, OpArgK, iABC) /* OP_GETTABLE */
@@ -88,7 +89,7 @@ LUAI_DDEF const lu_byte luaP_opmodes[NUM_OPCODES] = { · 16 unmodified lines
88 ,opmode(1, 0, OpArgK, OpArgK, iABC) /* OP_EQ */89 ,opmode(1, 0, OpArgK, OpArgK, iABC) /* OP_EQ */
89 ,opmode(1, 0, OpArgK, OpArgK, iABC) /* OP_LT */90 ,opmode(1, 0, OpArgK, OpArgK, iABC) /* OP_LT */
90 ,opmode(1, 0, OpArgK, OpArgK, iABC) /* OP_LE */91 ,opmode(1, 0, OpArgK, OpArgK, iABC) /* OP_LE */
91 ,opmode(1, 1, OpArgR, OpArgU, iABC) /* OP_TEST */92 ,opmode(1, 0, OpArgN, OpArgU, iABC) /* OP_TEST */
92 ,opmode(1, 1, OpArgR, OpArgU, iABC) /* OP_TESTSET */93 ,opmode(1, 1, OpArgR, OpArgU, iABC) /* OP_TESTSET */
93 ,opmode(0, 1, OpArgU, OpArgU, iABC) /* OP_CALL */94 ,opmode(0, 1, OpArgU, OpArgU, iABC) /* OP_CALL */
94 ,opmode(0, 1, OpArgU, OpArgU, iABC) /* OP_TAILCALL */95 ,opmode(0, 1, OpArgU, OpArgU, iABC) /* OP_TAILCALL */
@@ -98,7 +99,6 @@ LUAI_DDEF const lu_byte luaP_opmodes[NUM_OPCODES] = { · 3 unmodified lines
98 ,opmode(0, 0, OpArgN, OpArgU, iABC) /* OP_TFORCALL */99 ,opmode(0, 0, OpArgN, OpArgU, iABC) /* OP_TFORCALL */
99 ,opmode(0, 1, OpArgR, OpArgN, iAsBx) /* OP_TFORLOOP */100 ,opmode(0, 1, OpArgR, OpArgN, iAsBx) /* OP_TFORLOOP */
100 ,opmode(0, 0, OpArgU, OpArgU, iABC) /* OP_SETLIST */101 ,opmode(0, 0, OpArgU, OpArgU, iABC) /* OP_SETLIST */
101 ,opmode(0, 0, OpArgN, OpArgN, iABC) /* OP_CLOSE */
102 ,opmode(0, 1, OpArgU, OpArgN, iABx) /* OP_CLOSURE */102 ,opmode(0, 1, OpArgU, OpArgN, iABx) /* OP_CLOSURE */
103 ,opmode(0, 1, OpArgU, OpArgN, iABC) /* OP_VARARG */103 ,opmode(0, 1, OpArgU, OpArgN, iABC) /* OP_VARARG */
104 ,opmode(0, 0, OpArgU, OpArgU, iAx) /* OP_EXTRAARG */104 ,opmode(0, 0, OpArgU, OpArgU, iAx) /* OP_EXTRAARG */
src/lopcodes.h+6−7
@@ -1,5 +1,5 @@
1/*1/*
2** $Id: lopcodes.h,v 1.137 2010/10/25 12:24:55 roberto Exp $2** $Id: lopcodes.h,v 1.141 2011/04/19 16:22:13 roberto Exp $
3** Opcodes for Lua virtual machine3** Opcodes for Lua virtual machine
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -167,9 +167,10 @@ typedef enum { · 161 unmodified lines
167name args description167name args description
168------------------------------------------------------------------------*/168------------------------------------------------------------------------*/
169OP_MOVE,/* A B R(A) := R(B) */169OP_MOVE,/* A B R(A) := R(B) */
170OP_LOADK,/* A Bx R(A) := Kst(Bx - 1) */170OP_LOADK,/* A Bx R(A) := Kst(Bx) */
171OP_LOADKX,/* A R(A) := Kst(extra arg) */
171OP_LOADBOOL,/* A B C R(A) := (Bool)B; if (C) pc++ */172OP_LOADBOOL,/* A B C R(A) := (Bool)B; if (C) pc++ */
172OP_LOADNIL,/* A B R(A) := ... := R(B) := nil */173OP_LOADNIL,/* A B R(A), R(A+1), ..., R(A+B) := nil */
173OP_GETUPVAL,/* A B R(A) := UpValue[B] */174OP_GETUPVAL,/* A B R(A) := UpValue[B] */
174 175
175OP_GETTABUP,/* A B C R(A) := UpValue[B][RK(C)] */176OP_GETTABUP,/* A B C R(A) := UpValue[B][RK(C)] */
@@ -195,8 +196,7 @@ OP_LEN,/* A B R(A) := length of R(B) */ · 19 unmodified lines
195 196
196OP_CONCAT,/* A B C R(A) := R(B).. ... ..R(C) */197OP_CONCAT,/* A B C R(A) := R(B).. ... ..R(C) */
197 198
198OP_JMP,/* sBx pc+=sBx */199OP_JMP,/* A sBx pc+=sBx; if (A) close all upvalues >= R(A) + 1 */
199
200OP_EQ,/* A B C if ((RK(B) == RK(C)) ~= A) then pc++ */200OP_EQ,/* A B C if ((RK(B) == RK(C)) ~= A) then pc++ */
201OP_LT,/* A B C if ((RK(B) < RK(C)) ~= A) then pc++ */201OP_LT,/* A B C if ((RK(B) < RK(C)) ~= A) then pc++ */
202OP_LE,/* A B C if ((RK(B) <= RK(C)) ~= A) then pc++ */202OP_LE,/* A B C if ((RK(B) <= RK(C)) ~= A) then pc++ */
@@ -217,7 +217,6 @@ OP_TFORLOOP,/* A sBx if R(A+1) ~= nil then { R(A)=R(A+1); pc += sBx }*/ · 14 unmodified lines
217 217
218OP_SETLIST,/* A B C R(A)[(C-1)*FPF+i] := R(A+i), 1 <= i <= B */218OP_SETLIST,/* A B C R(A)[(C-1)*FPF+i] := R(A+i), 1 <= i <= B */
219 219
220OP_CLOSE,/* A close all variables in the stack up to (>=) R(A)*/
221OP_CLOSURE,/* A Bx R(A) := closure(KPROTO[Bx]) */220OP_CLOSURE,/* A Bx R(A) := closure(KPROTO[Bx]) */
222 221
223OP_VARARG,/* A B R(A), R(A+1), ..., R(A+B-2) = vararg */222OP_VARARG,/* A B R(A), R(A+1), ..., R(A+B-2) = vararg */
@@ -244,7 +243,7 @@ OP_EXTRAARG/* Ax extra (larger) argument for previous opcode */ · 20 unmodified lines
244 (*) In OP_SETLIST, if (B == 0) then B = `top'; if (C == 0) then next243 (*) In OP_SETLIST, if (B == 0) then B = `top'; if (C == 0) then next
245 'instruction' is EXTRAARG(real C).244 'instruction' is EXTRAARG(real C).
246 245
247 (*) In OP_LOADK, if (Bx == 0) then next 'instruction' is EXTRAARG(real Bx).246 (*) In OP_LOADKX, the next 'instruction' is always EXTRAARG.
248 247
249 (*) For comparisons, A specifies what condition the test should accept248 (*) For comparisons, A specifies what condition the test should accept
250 (true or false).249 (true or false).
src/loslib.c+11−20
@@ -1,5 +1,5 @@
1/*1/*
2** $Id: loslib.c,v 1.32 2010/10/05 12:18:03 roberto Exp $2** $Id: loslib.c,v 1.34 2011/03/03 16:34:46 roberto Exp $
3** Standard Operating System library3** Standard Operating System library
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -59,37 +59,28 @@ · 53 unmodified lines
59 59
60 60
61 61
62static int os_pushresult (lua_State *L, int i, const char *filename) {62static int os_execute (lua_State *L) {
63 int en = errno; /* calls to Lua API may change this value */63 const char *cmd = luaL_optstring(L, 1, NULL);
64 if (i) {64 int stat = system(cmd);
65 lua_pushboolean(L, 1);65 if (cmd != NULL)
66 return 1;66 return luaL_execresult(L, stat);
67 }
68 else {67 else {
69 lua_pushnil(L);68 lua_pushboolean(L, stat); /* true if there is a shell */
70 lua_pushfstring(L, "%s: %s", filename, strerror(en));69 return 1;
71 lua_pushinteger(L, en);
72 return 3;
73 }70 }
74}71}
75 72
76 73
77static int os_execute (lua_State *L) {
78 lua_pushinteger(L, system(luaL_optstring(L, 1, NULL)));
79 return 1;
80}
81
82
83static int os_remove (lua_State *L) {74static int os_remove (lua_State *L) {
84 const char *filename = luaL_checkstring(L, 1);75 const char *filename = luaL_checkstring(L, 1);
85 return os_pushresult(L, remove(filename) == 0, filename);76 return luaL_fileresult(L, remove(filename) == 0, filename);
86}77}
87 78
88 79
89static int os_rename (lua_State *L) {80static int os_rename (lua_State *L) {
90 const char *fromname = luaL_checkstring(L, 1);81 const char *fromname = luaL_checkstring(L, 1);
91 const char *toname = luaL_checkstring(L, 2);82 const char *toname = luaL_checkstring(L, 2);
92 return os_pushresult(L, rename(fromname, toname) == 0, fromname);83 return luaL_fileresult(L, rename(fromname, toname) == 0, fromname);
93}84}
94 85
95 86
@@ -182,7 +173,7 @@ static const char *checkoption (lua_State *L, const char *conv, char *buff) { · 86 unmodified lines
182 return conv; /* to avoid warnings */173 return conv; /* to avoid warnings */
183}174}
184 175
185 176
186static int os_date (lua_State *L) {177static int os_date (lua_State *L) {
187 const char *s = luaL_optstring(L, 1, "%c");178 const char *s = luaL_optstring(L, 1, "%c");
188 time_t t = luaL_opt(L, (time_t)luaL_checknumber, 2, time(NULL));179 time_t t = luaL_opt(L, (time_t)luaL_checknumber, 2, time(NULL));
src/lparser.c+320−145
@@ -1,5 +1,5 @@
1/*1/*
2** $Id: lparser.c,v 2.92 2010/09/07 19:21:39 roberto Exp $2** $Id: lparser.c,v 2.109 2011/05/02 17:33:01 roberto Exp $
3** Lua Parser3** Lua Parser
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -41,10 +41,11 @@ · 35 unmodified lines
41*/41*/
42typedef struct BlockCnt {42typedef struct BlockCnt {
43 struct BlockCnt *previous; /* chain */43 struct BlockCnt *previous; /* chain */
44 int breaklist; /* list of jumps out of this loop */44 int firstlabel; /* index of first label in this block */
45 lu_byte nactvar; /* # active locals outside the breakable structure */45 int firstgoto; /* index of first pending goto in this block */
46 lu_byte nactvar; /* # active locals outside the block */
46 lu_byte upval; /* true if some variable in the block is an upvalue */47 lu_byte upval; /* true if some variable in the block is an upvalue */
47 lu_byte isbreakable; /* true if `block' is a loop */48 lu_byte isloop; /* true if `block' is a loop */
48} BlockCnt;49} BlockCnt;
49 50
50 51
@@ -52,7 +53,7 @@ typedef struct BlockCnt { · 1 unmodified line
52/*53/*
53** prototypes for recursive non-terminal functions54** prototypes for recursive non-terminal functions
54*/55*/
55static void chunk (LexState *ls);56static void statement (LexState *ls);
56static void expr (LexState *ls, expdesc *v);57static void expr (LexState *ls, expdesc *v);
57 58
58 59
@@ -66,6 +67,13 @@ static void anchor_token (LexState *ls) { · 7 unmodified lines
66}67}
67 68
68 69
70/* semantic error */
71static void semerror (LexState *ls, const char *msg) {
72 ls->t.token = 0; /* remove 'near to' from final message */
73 luaX_syntaxerror(ls, msg);
74}
75
76
69static void error_expected (LexState *ls, int token) {77static void error_expected (LexState *ls, int token) {
70 luaX_syntaxerror(ls,78 luaX_syntaxerror(ls,
71 luaO_pushfstring(ls->L, "%s expected", luaX_token2str(ls, token)));79 luaO_pushfstring(ls->L, "%s expected", luaX_token2str(ls, token)));
@@ -103,6 +111,7 @@ static void check (LexState *ls, int c) { · 31 unmodified lines
103 error_expected(ls, c);111 error_expected(ls, c);
104}112}
105 113
114
106static void checknext (LexState *ls, int c) {115static void checknext (LexState *ls, int c) {
107 check(ls, c);116 check(ls, c);
108 luaX_next(ls);117 luaX_next(ls);
@@ -167,13 +176,13 @@ static int registerlocalvar (LexState *ls, TString *varname) { · 58 unmodified lines
167 176
168static void new_localvar (LexState *ls, TString *name) {177static void new_localvar (LexState *ls, TString *name) {
169 FuncState *fs = ls->fs;178 FuncState *fs = ls->fs;
170 Varlist *vl = ls->varl;179 Dyndata *dyd = ls->dyd;
171 int reg = registerlocalvar(ls, name);180 int reg = registerlocalvar(ls, name);
172 checklimit(fs, vl->nactvar + 1 - fs->firstlocal,181 checklimit(fs, dyd->actvar.n + 1 - fs->firstlocal,
173 MAXVARS, "local variables");182 MAXVARS, "local variables");
174 luaM_growvector(ls->L, vl->actvar, vl->nactvar + 1,183 luaM_growvector(ls->L, dyd->actvar.arr, dyd->actvar.n + 1,
175 vl->actvarsize, vardesc, MAX_INT, "local variables");184 dyd->actvar.size, Vardesc, MAX_INT, "local variables");
176 vl->actvar[vl->nactvar++].idx = cast(unsigned short, reg);185 dyd->actvar.arr[dyd->actvar.n++].idx = cast(unsigned short, reg);
177}186}
178 187
179 188
@@ -186,7 +195,7 @@ static void new_localvarliteral_ (LexState *ls, const char *name, size_t sz) { · 6 unmodified lines
186 195
187 196
188static LocVar *getlocvar (FuncState *fs, int i) {197static LocVar *getlocvar (FuncState *fs, int i) {
189 int idx = fs->ls->varl->actvar[fs->firstlocal + i].idx;198 int idx = fs->ls->dyd->actvar.arr[fs->firstlocal + i].idx;
190 lua_assert(idx < fs->nlocvars);199 lua_assert(idx < fs->nlocvars);
191 return &fs->f->locvars[idx];200 return &fs->f->locvars[idx];
192}201}
@@ -202,7 +211,7 @@ static void adjustlocalvars (LexState *ls, int nvars) { · 9 unmodified lines
202 211
203 212
204static void removevars (FuncState *fs, int tolevel) {213static void removevars (FuncState *fs, int tolevel) {
205 fs->ls->varl->nactvar -= (fs->nactvar - tolevel);214 fs->ls->dyd->actvar.n -= (fs->nactvar - tolevel);
206 while (fs->nactvar > tolevel)215 while (fs->nactvar > tolevel)
207 getlocvar(fs, --fs->nactvar)->endpc = fs->pc;216 getlocvar(fs, --fs->nactvar)->endpc = fs->pc;
208}217}
@@ -245,12 +254,12 @@ static int searchvar (FuncState *fs, TString *n) { · 36 unmodified lines
245 254
246/*255/*
247 Mark block where variable at given level was defined256 Mark block where variable at given level was defined
248 (to emit OP_CLOSE later).257 (to emit close instructions later).
249*/258*/
250static void markupval (FuncState *fs, int level) {259static void markupval (FuncState *fs, int level) {
251 BlockCnt *bl = fs->bl;260 BlockCnt *bl = fs->bl;
252 while (bl && bl->nactvar > level) bl = bl->previous;261 while (bl->nactvar > level) bl = bl->previous;
253 if (bl) bl->upval = 1;262 bl->upval = 1;
254}263}
255 264
256 265
@@ -327,10 +336,107 @@ static void enterlevel (LexState *ls) { · 70 unmodified lines
327#define leavelevel(ls) (G((ls)->L)->nCcalls--)336#define leavelevel(ls) (G((ls)->L)->nCcalls--)
328 337
329 338
330static void enterblock (FuncState *fs, BlockCnt *bl, lu_byte isbreakable) {339static void closegoto (LexState *ls, int g, Labeldesc *label) {
331 bl->breaklist = NO_JUMP;340 int i;
332 bl->isbreakable = isbreakable;341 FuncState *fs = ls->fs;
342 Labellist *gl = &ls->dyd->gt;
343 Labeldesc *gt = &gl->arr[g];
344 lua_assert(eqstr(gt->name, label->name));
345 if (gt->nactvar < label->nactvar) {
346 const char *msg = luaO_pushfstring(ls->L,
347 "<goto %s> at line %d jumps into the scope of local " LUA_QS,
348 getstr(gt->name), gt->line, getstr(getlocvar(fs, gt->nactvar)->varname));
349 semerror(ls, msg);
350 }
351 luaK_patchlist(fs, gt->pc, label->pc);
352 /* remove goto from pending list */
353 for (i = g; i < gl->n - 1; i++)
354 gl->arr[i] = gl->arr[i + 1];
355 gl->n--;
356}
357
358
359/*
360** try to close a goto with existing labels; this solves backward jumps
361*/
362static int findlabel (LexState *ls, int g) {
363 int i;
364 BlockCnt *bl = ls->fs->bl;
365 Dyndata *dyd = ls->dyd;
366 Labeldesc *gt = &dyd->gt.arr[g];
367 /* check labels in current block for a match */
368 for (i = bl->firstlabel; i < dyd->label.n; i++) {
369 Labeldesc *lb = &dyd->label.arr[i];
370 if (eqstr(lb->name, gt->name)) { /* correct label? */
371 if (gt->nactvar > lb->nactvar &&
372 (bl->upval || dyd->label.n > bl->firstlabel))
373 luaK_patchclose(ls->fs, gt->pc, lb->nactvar);
374 closegoto(ls, g, lb); /* close it */
375 return 1;
376 }
377 }
378 return 0; /* label not found; cannot close goto */
379}
380
381
382static int newlabelentry (LexState *ls, Labellist *l, TString *name,
383 int line, int pc) {
384 int n = l->n;
385 luaM_growvector(ls->L, l->arr, n, l->size, Labeldesc, MAX_INT, "labels");
386 l->arr[n].name = name;
387 l->arr[n].line = line;
388 l->arr[n].nactvar = ls->fs->nactvar;
389 l->arr[n].pc = pc;
390 l->n++;
391 return n;
392}
393
394
395/*
396** check whether new label 'lb' matches any pending gotos in current
397** block; solves forward jumps
398*/
399static void findgotos (LexState *ls, Labeldesc *lb) {
400 Labellist *gl = &ls->dyd->gt;
401 int i = ls->fs->bl->firstgoto;
402 while (i < gl->n) {
403 if (eqstr(gl->arr[i].name, lb->name))
404 closegoto(ls, i, lb);
405 else
406 i++;
407 }
408}
409
410
411/*
412** "export" pending gotos to outer level, to check them against
413** outer labels; if the block being exited has upvalues, and
414** the goto exists the scope of any variable (which can be the
415** upvalue), close those variables being exited.
416*/
417static void movegotosout (FuncState *fs, BlockCnt *bl) {
418 int i = bl->firstgoto;
419 Labellist *gl = &fs->ls->dyd->gt;
420 /* correct pending gotos to current block and try to close it
421 with visible labels */
422 while (i < gl->n) {
423 Labeldesc *gt = &gl->arr[i];
424 if (gt->nactvar > bl->nactvar) {
425 if (bl->upval)
426 luaK_patchclose(fs, gt->pc, bl->nactvar);
427 gt->nactvar = bl->nactvar;
428 }
429 if (!findlabel(fs->ls, i))
430 i++; /* move to next one */
431 }
432}
433
434
435static void enterblock (FuncState *fs, BlockCnt *bl, lu_byte isloop) {
436 bl->isloop = isloop;
333 bl->nactvar = fs->nactvar;437 bl->nactvar = fs->nactvar;
438 bl->firstlabel = fs->ls->dyd->label.n;
439 bl->firstgoto = fs->ls->dyd->gt.n;
334 bl->upval = 0;440 bl->upval = 0;
335 bl->previous = fs->bl;441 bl->previous = fs->bl;
336 fs->bl = bl;442 fs->bl = bl;
@@ -338,17 +444,48 @@ static void enterblock (FuncState *fs, BlockCnt *bl, lu_byte isbreakable) { · 1 unmodified line
338}444}
339 445
340 446
447/*
448** create a label named "break" to resolve break statements
449*/
450static void breaklabel (LexState *ls) {
451 TString *n = luaS_new(ls->L, "break");
452 int l = newlabelentry(ls, &ls->dyd->label, n, 0, ls->fs->pc);
453 findgotos(ls, &ls->dyd->label.arr[l]);
454}
455
456/*
457** generates an error for an undefined 'goto'; choose appropriate
458** message when label name is a reserved word (which can only be 'break')
459*/
460static void undefgoto (LexState *ls, Labeldesc *gt) {
461 const char *msg = (gt->name->tsv.reserved > 0)
462 ? "<%s> at line %d not inside a loop"
463 : "label " LUA_QS " (<goto> at line %d) undefined";
464 msg = luaO_pushfstring(ls->L, msg, getstr(gt->name), gt->line);
465 semerror(ls, msg);
466}
467
468
341static void leaveblock (FuncState *fs) {469static void leaveblock (FuncState *fs) {
342 BlockCnt *bl = fs->bl;470 BlockCnt *bl = fs->bl;
471 LexState *ls = fs->ls;
472 if (bl->previous && bl->upval) {
473 /* create a 'jump to here' to close upvalues */
474 int j = luaK_jump(fs);
475 luaK_patchclose(fs, j, bl->nactvar);
476 luaK_patchtohere(fs, j);
477 }
478 if (bl->isloop)
479 breaklabel(ls); /* close pending breaks */
343 fs->bl = bl->previous;480 fs->bl = bl->previous;
344 removevars(fs, bl->nactvar);481 removevars(fs, bl->nactvar);
345 if (bl->upval)
346 luaK_codeABC(fs, OP_CLOSE, bl->nactvar, 0, 0);
347 /* a block either controls scope or breaks (never both) */
348 lua_assert(!bl->isbreakable || !bl->upval);
349 lua_assert(bl->nactvar == fs->nactvar);482 lua_assert(bl->nactvar == fs->nactvar);
350 fs->freereg = fs->nactvar; /* free registers */483 fs->freereg = fs->nactvar; /* free registers */
351 luaK_patchtohere(fs, bl->breaklist);484 ls->dyd->label.n = bl->firstlabel; /* remove local labels */
485 if (bl->previous) /* inner block? */
486 movegotosout(fs, bl); /* update pending gotos to outer block */
487 else if (bl->firstgoto < ls->dyd->gt.n) /* pending gotos in outer block? */
488 undefgoto(ls, &ls->dyd->gt.arr[bl->firstgoto]); /* error */
352}489}
353 490
354 491
@@ -368,10 +505,11 @@ static void codeclosure (LexState *ls, Proto *clp, expdesc *v) { · 13 unmodified lines
368 f->p[fs->np++] = clp;505 f->p[fs->np++] = clp;
369 luaC_objbarrier(ls->L, f, clp);506 luaC_objbarrier(ls->L, f, clp);
370 init_exp(v, VRELOCABLE, luaK_codeABx(fs, OP_CLOSURE, 0, fs->np-1));507 init_exp(v, VRELOCABLE, luaK_codeABx(fs, OP_CLOSURE, 0, fs->np-1));
508 luaK_exp2nextreg(fs, v); /* fix it at stack top (for GC) */
371}509}
372 510
373 511
374static void open_func (LexState *ls, FuncState *fs) {512static void open_func (LexState *ls, FuncState *fs, BlockCnt *bl) {
375 lua_State *L = ls->L;513 lua_State *L = ls->L;
376 Proto *f;514 Proto *f;
377 fs->prev = ls->fs; /* linked list of funcstates */515 fs->prev = ls->fs; /* linked list of funcstates */
@@ -387,7 +525,7 @@ static void open_func (LexState *ls, FuncState *fs) { · 9 unmodified lines
387 fs->nups = 0;525 fs->nups = 0;
388 fs->nlocvars = 0;526 fs->nlocvars = 0;
389 fs->nactvar = 0;527 fs->nactvar = 0;
390 fs->firstlocal = ls->varl->nactvar;528 fs->firstlocal = ls->dyd->actvar.n;
391 fs->bl = NULL;529 fs->bl = NULL;
392 f = luaF_newproto(L);530 f = luaF_newproto(L);
393 fs->f = f;531 fs->f = f;
@@ -400,6 +538,7 @@ static void open_func (LexState *ls, FuncState *fs) { · 6 unmodified lines
400 /* anchor table of constants (to avoid being collected) */538 /* anchor table of constants (to avoid being collected) */
401 sethvalue2s(L, L->top, fs->h);539 sethvalue2s(L, L->top, fs->h);
402 incr_top(L);540 incr_top(L);
541 enterblock(fs, bl, 0);
403}542}
404 543
405 544
@@ -408,7 +547,7 @@ static void close_func (LexState *ls) { · 2 unmodified lines
408 FuncState *fs = ls->fs;547 FuncState *fs = ls->fs;
409 Proto *f = fs->f;548 Proto *f = fs->f;
410 luaK_ret(fs, 0, 0); /* final return */549 luaK_ret(fs, 0, 0); /* final return */
411 removevars(fs, 0);550 leaveblock(fs);
412 luaM_reallocvector(L, f->code, f->sizecode, fs->pc, Instruction);551 luaM_reallocvector(L, f->code, f->sizecode, fs->pc, Instruction);
413 f->sizecode = fs->pc;552 f->sizecode = fs->pc;
414 luaM_reallocvector(L, f->lineinfo, f->sizelineinfo, fs->pc, int);553 luaM_reallocvector(L, f->lineinfo, f->sizelineinfo, fs->pc, int);
@@ -435,42 +574,49 @@ static void close_func (LexState *ls) { · 20 unmodified lines
435** opens the main function, which is a regular vararg function with an574** opens the main function, which is a regular vararg function with an
436** upvalue named LUA_ENV575** upvalue named LUA_ENV
437*/576*/
438static void open_mainfunc (LexState *ls, FuncState *fs) {577static void open_mainfunc (LexState *ls, FuncState *fs, BlockCnt *bl) {
439 expdesc v;578 expdesc v;
440 open_func(ls, fs);579 open_func(ls, fs, bl);
441 fs->f->is_vararg = 1; /* main function is always vararg */580 fs->f->is_vararg = 1; /* main function is always vararg */
442 init_exp(&v, VLOCAL, 0);581 init_exp(&v, VLOCAL, 0);
443 newupvalue(fs, ls->envn, &v); /* create environment upvalue */582 newupvalue(fs, ls->envn, &v); /* create environment upvalue */
444}583}
445 584
446 585
447Proto *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff, Varlist *varl,
448 const char *name) {
449 LexState lexstate;
450 FuncState funcstate;
451 TString *tname = luaS_new(L, name);
452 setsvalue2s(L, L->top, tname); /* push name to protect it */
453 incr_top(L);
454 lexstate.buff = buff;
455 lexstate.varl = varl;
456 luaX_setinput(L, &lexstate, z, tname);
457 open_mainfunc(&lexstate, &funcstate);
458 luaX_next(&lexstate); /* read first token */
459 chunk(&lexstate); /* read main chunk */
460 check(&lexstate, TK_EOS);
461 close_func(&lexstate);
462 L->top--; /* pop name */
463 lua_assert(!funcstate.prev && funcstate.nups == 1 && !lexstate.fs);
464 return funcstate.f;
465}
466
467
468 586
469/*============================================================*/587/*============================================================*/
470/* GRAMMAR RULES */588/* GRAMMAR RULES */
471/*============================================================*/589/*============================================================*/
472 590
473 591
592/*
593** check whether current token is in the follow set of a block.
594** 'until' closes syntactical blocks, but do not close scope,
595** so it handled in separate.
596*/
597static int block_follow (LexState *ls, int withuntil) {
598 switch (ls->t.token) {
599 case TK_ELSE: case TK_ELSEIF:
600 case TK_END: case TK_EOS:
601 return 1;
602 case TK_UNTIL: return withuntil;
603 default: return 0;
604 }
605}
606
607
608static void statlist (LexState *ls) {
609 /* statlist -> { stat [`;'] } */
610 while (!block_follow(ls, 1)) {
611 if (ls->t.token == TK_RETURN) {
612 statement(ls);
613 return; /* 'return' must be last statement */
614 }
615 statement(ls);
616 }
617}
618
619
474static void fieldsel (LexState *ls, expdesc *v) {620static void fieldsel (LexState *ls, expdesc *v) {
475 /* fieldsel -> ['.' | ':'] NAME */621 /* fieldsel -> ['.' | ':'] NAME */
476 FuncState *fs = ls->fs;622 FuncState *fs = ls->fs;
@@ -586,7 +732,7 @@ static void field (LexState *ls, struct ConsControl *cc) { · 109 unmodified lines
586 732
587 733
588static void constructor (LexState *ls, expdesc *t) {734static void constructor (LexState *ls, expdesc *t) {
589 /* constructor -> '{' [ field { sep field } [sep] ] '}' 735 /* constructor -> '{' [ field { sep field } [sep] ] '}'
590 sep -> ',' | ';' */736 sep -> ',' | ';' */
591 FuncState *fs = ls->fs;737 FuncState *fs = ls->fs;
592 int line = ls->linenumber;738 int line = ls->linenumber;
@@ -596,7 +742,7 @@ static void constructor (LexState *ls, expdesc *t) { · 3 unmodified lines
596 cc.t = t;742 cc.t = t;
597 init_exp(t, VRELOCABLE, pc);743 init_exp(t, VRELOCABLE, pc);
598 init_exp(&cc.v, VVOID, 0); /* no value (yet) */744 init_exp(&cc.v, VVOID, 0); /* no value (yet) */
599 luaK_exp2nextreg(ls->fs, t); /* fix it at stack top (for gc) */745 luaK_exp2nextreg(ls->fs, t); /* fix it at stack top */
600 checknext(ls, '{');746 checknext(ls, '{');
601 do {747 do {
602 lua_assert(cc.v.k == VVOID || cc.tostore > 0);748 lua_assert(cc.v.k == VVOID || cc.tostore > 0);
@@ -643,19 +789,20 @@ static void parlist (LexState *ls) { · 40 unmodified lines
643}789}
644 790
645 791
646static void body (LexState *ls, expdesc *e, int needself, int line) {792static void body (LexState *ls, expdesc *e, int ismethod, int line) {
647 /* body -> `(' parlist `)' chunk END */793 /* body -> `(' parlist `)' block END */
648 FuncState new_fs;794 FuncState new_fs;
649 open_func(ls, &new_fs);795 BlockCnt bl;
796 open_func(ls, &new_fs, &bl);
650 new_fs.f->linedefined = line;797 new_fs.f->linedefined = line;
651 checknext(ls, '(');798 checknext(ls, '(');
652 if (needself) {799 if (ismethod) {
653 new_localvarliteral(ls, "self");800 new_localvarliteral(ls, "self"); /* create 'self' parameter */
654 adjustlocalvars(ls, 1);801 adjustlocalvars(ls, 1);
655 }802 }
656 parlist(ls);803 parlist(ls);
657 checknext(ls, ')');804 checknext(ls, ')');
658 chunk(ls);805 statlist(ls);
659 new_fs.f->lastlinedefined = ls->linenumber;806 new_fs.f->lastlinedefined = ls->linenumber;
660 check_match(ls, TK_END, TK_FUNCTION, line);807 check_match(ls, TK_END, TK_FUNCTION, line);
661 codeclosure(ls, new_fs.f, e);808 codeclosure(ls, new_fs.f, e);
@@ -663,8 +810,8 @@ static void body (LexState *ls, expdesc *e, int needself, int line) { · 1 unmodified line
663}810}
664 811
665 812
666static int explist1 (LexState *ls, expdesc *v) {813static int explist (LexState *ls, expdesc *v) {
667 /* explist1 -> expr { `,' expr } */814 /* explist -> expr { `,' expr } */
668 int n = 1; /* at least one expression */815 int n = 1; /* at least one expression */
669 expr(ls, v);816 expr(ls, v);
670 while (testnext(ls, ',')) {817 while (testnext(ls, ',')) {
@@ -681,12 +828,12 @@ static void funcargs (LexState *ls, expdesc *f, int line) { · 10 unmodified lines
681 expdesc args;828 expdesc args;
682 int base, nparams;829 int base, nparams;
683 switch (ls->t.token) {830 switch (ls->t.token) {
684 case '(': { /* funcargs -> `(' [ explist1 ] `)' */831 case '(': { /* funcargs -> `(' [ explist ] `)' */
685 luaX_next(ls);832 luaX_next(ls);
686 if (ls->t.token == ')') /* arg list is empty? */833 if (ls->t.token == ')') /* arg list is empty? */
687 args.k = VVOID;834 args.k = VVOID;
688 else {835 else {
689 explist1(ls, &args);836 explist(ls, &args);
690 luaK_setmultret(fs, &args);837 luaK_setmultret(fs, &args);
691 }838 }
692 check_match(ls, ')', '(', line);839 check_match(ls, ')', '(', line);
@@ -937,23 +1084,12 @@ static void expr (LexState *ls, expdesc *v) { · 244 unmodified lines
937*/1084*/
938 1085
939 1086
940static int block_follow (int token) {
941 switch (token) {
942 case TK_ELSE: case TK_ELSEIF: case TK_END:
943 case TK_UNTIL: case TK_EOS:
944 return 1;
945 default: return 0;
946 }
947}
948
949
950static void block (LexState *ls) {1087static void block (LexState *ls) {
951 /* block -> chunk */1088 /* block -> statlist */
952 FuncState *fs = ls->fs;1089 FuncState *fs = ls->fs;
953 BlockCnt bl;1090 BlockCnt bl;
954 enterblock(fs, &bl, 0);1091 enterblock(fs, &bl, 0);
955 chunk(ls);1092 statlist(ls);
956 lua_assert(bl.breaklist == NO_JUMP);
957 leaveblock(fs);1093 leaveblock(fs);
958}1094}
959 1095
@@ -1012,10 +1148,10 @@ static void assignment (LexState *ls, struct LHS_assign *lh, int nvars) { · 52 unmodified lines
1012 "variable names");1148 "variable names");
1013 assignment(ls, &nv, nvars+1);1149 assignment(ls, &nv, nvars+1);
1014 }1150 }
1015 else { /* assignment -> `=' explist1 */1151 else { /* assignment -> `=' explist */
1016 int nexps;1152 int nexps;
1017 checknext(ls, '=');1153 checknext(ls, '=');
1018 nexps = explist1(ls, &e);1154 nexps = explist(ls, &e);
1019 if (nexps != nvars) {1155 if (nexps != nvars) {
1020 adjust_assign(ls, nvars, nexps, &e);1156 adjust_assign(ls, nvars, nexps, &e);
1021 if (nexps > nvars)1157 if (nexps > nvars)
@@ -1042,19 +1178,38 @@ static int cond (LexState *ls) { · 20 unmodified lines
1042}1178}
1043 1179
1044 1180
1045static void breakstat (LexState *ls) {1181static void gotostat (LexState *ls, TString *label, int line) {
1182 /* create new entry for this goto */
1183 int g = newlabelentry(ls, &ls->dyd->gt, label, line, luaK_jump(ls->fs));
1184 findlabel(ls, g);
1185}
1186
1187
1188static void labelstat (LexState *ls, TString *label, int line) {
1189 /* label -> '@' NAME ':' */
1046 FuncState *fs = ls->fs;1190 FuncState *fs = ls->fs;
1047 BlockCnt *bl = fs->bl;1191 Labellist *ll = &ls->dyd->label;
1048 int upval = 0;1192 int l, i; /* index of new label being created */
1049 while (bl && !bl->isbreakable) {1193 /* check for repeated labels on the same block */
1050 upval |= bl->upval;1194 for (i = ls->fs->bl->firstlabel; i < ll->n; i++) {
1051 bl = bl->previous;1195 if (eqstr(label, ll->arr[i].name)) {
1196 const char *msg = luaO_pushfstring(ls->L,
1197 "label " LUA_QS " already defined on line %d",
1198 getstr(label), ll->arr[i].line);
1199 semerror(ls, msg);
1200 }
1052 }1201 }
1053 if (!bl)1202 checknext(ls, ':'); /* skip colon */
1054 luaX_syntaxerror(ls, "no loop to break");1203 /* create new entry for this label */
1055 if (upval)1204 l = newlabelentry(ls, ll, label, line, fs->pc);
1056 luaK_codeABC(fs, OP_CLOSE, bl->nactvar, 0, 0);1205 /* skip other no-op statements */
1057 luaK_concat(fs, &bl->breaklist, luaK_jump(fs));1206 while (ls->t.token == ';' || ls->t.token == '@')
1207 statement(ls);
1208 if (block_follow(ls, 0)) { /* label is last no-op statement in the block? */
1209 /* assume that locals are already out of scope */
1210 ll->arr[l].nactvar = fs->bl->nactvar;
1211 }
1212 findgotos(ls, &ll->arr[l]);
1058}1213}
1059 1214
1060 1215
@@ -1086,19 +1241,13 @@ static void repeatstat (LexState *ls, int line) { · 25 unmodified lines
1086 enterblock(fs, &bl1, 1); /* loop block */1241 enterblock(fs, &bl1, 1); /* loop block */
1087 enterblock(fs, &bl2, 0); /* scope block */1242 enterblock(fs, &bl2, 0); /* scope block */
1088 luaX_next(ls); /* skip REPEAT */1243 luaX_next(ls); /* skip REPEAT */
1089 chunk(ls);1244 statlist(ls);
1090 check_match(ls, TK_UNTIL, TK_REPEAT, line);1245 check_match(ls, TK_UNTIL, TK_REPEAT, line);
1091 condexit = cond(ls); /* read condition (inside scope block) */1246 condexit = cond(ls); /* read condition (inside scope block) */
1092 if (!bl2.upval) { /* no upvalues? */1247 if (bl2.upval) /* upvalues? */
1093 leaveblock(fs); /* finish scope */1248 luaK_patchclose(fs, condexit, bl2.nactvar);
1094 luaK_patchlist(fs, condexit, repeat_init); /* close the loop */1249 leaveblock(fs); /* finish scope */
1095 }1250 luaK_patchlist(fs, condexit, repeat_init); /* close the loop */
1096 else { /* complete semantics when there are upvalues */
1097 breakstat(ls); /* if condition then break */
1098 luaK_patchtohere(ls->fs, condexit); /* else... */
1099 leaveblock(fs); /* finish scope... */
1100 luaK_jumpto(fs, repeat_init); /* and repeat */
1101 }
1102 leaveblock(fs); /* finish loop */1251 leaveblock(fs); /* finish loop */
1103}1252}
1104 1253
@@ -1163,7 +1312,7 @@ static void fornum (LexState *ls, TString *varname, int line) { · 58 unmodified lines
1163 1312
1164 1313
1165static void forlist (LexState *ls, TString *indexname) {1314static void forlist (LexState *ls, TString *indexname) {
1166 /* forlist -> NAME {,NAME} IN explist1 forbody */1315 /* forlist -> NAME {,NAME} IN explist forbody */
1167 FuncState *fs = ls->fs;1316 FuncState *fs = ls->fs;
1168 expdesc e;1317 expdesc e;
1169 int nvars = 4; /* gen, state, control, plus at least one declared var */1318 int nvars = 4; /* gen, state, control, plus at least one declared var */
@@ -1181,7 +1330,7 @@ static void forlist (LexState *ls, TString *indexname) { · 11 unmodified lines
1181 }1330 }
1182 checknext(ls, TK_IN);1331 checknext(ls, TK_IN);
1183 line = ls->linenumber;1332 line = ls->linenumber;
1184 adjust_assign(ls, 3, explist1(ls, &e), &e);1333 adjust_assign(ls, 3, explist(ls, &e), &e);
1185 luaK_checkstack(fs, 3); /* extra space to call generator */1334 luaK_checkstack(fs, 3); /* extra space to call generator */
1186 forbody(ls, base, line, nvars - 3, 0);1335 forbody(ls, base, line, nvars - 3, 0);
1187}1336}
@@ -1241,19 +1390,20 @@ static void ifstat (LexState *ls, int line) { · 53 unmodified lines
1241 1390
1242 1391
1243static void localfunc (LexState *ls) {1392static void localfunc (LexState *ls) {
1244 expdesc v, b;1393 expdesc b;
1245 FuncState *fs = ls->fs;1394 FuncState *fs = ls->fs;
1246 new_localvar(ls, str_checkname(ls));1395 int varidx = fs->nactvar; /* index of new local variable */
1247 init_exp(&v, VLOCAL, fs->freereg);1396 new_localvar(ls, str_checkname(ls)); /* new local variable */
1248 luaK_reserveregs(fs, 1);1397 adjustlocalvars(ls, 1); /* enter its scope */
1249 adjustlocalvars(ls, 1);1398 body(ls, &b, 0, ls->linenumber); /* function created in next register */
1250 body(ls, &b, 0, ls->linenumber);1399 lua_assert(b.k == VNONRELOC && b.u.ind.idx == varidx);
1251 luaK_storevar(fs, &v, &b);1400 /* debug information will only see the variable after this point! */
1401 getlocvar(fs, varidx)->startpc = fs->pc;
1252}1402}
1253 1403
1254 1404
1255static void localstat (LexState *ls) {1405static void localstat (LexState *ls) {
1256 /* stat -> LOCAL NAME {`,' NAME} [`=' explist1] */1406 /* stat -> LOCAL NAME {`,' NAME} [`=' explist] */
1257 int nvars = 0;1407 int nvars = 0;
1258 int nexps;1408 int nexps;
1259 expdesc e;1409 expdesc e;
@@ -1262,7 +1412,7 @@ static void localstat (LexState *ls) { · 2 unmodified lines
1262 nvars++;1412 nvars++;
1263 } while (testnext(ls, ','));1413 } while (testnext(ls, ','));
1264 if (testnext(ls, '='))1414 if (testnext(ls, '='))
1265 nexps = explist1(ls, &e);1415 nexps = explist(ls, &e);
1266 else {1416 else {
1267 e.k = VVOID;1417 e.k = VVOID;
1268 nexps = 0;1418 nexps = 0;
@@ -1274,25 +1424,25 @@ static void localstat (LexState *ls) { · 5 unmodified lines
1274 1424
1275static int funcname (LexState *ls, expdesc *v) {1425static int funcname (LexState *ls, expdesc *v) {
1276 /* funcname -> NAME {fieldsel} [`:' NAME] */1426 /* funcname -> NAME {fieldsel} [`:' NAME] */
1277 int needself = 0;1427 int ismethod = 0;
1278 singlevar(ls, v);1428 singlevar(ls, v);
1279 while (ls->t.token == '.')1429 while (ls->t.token == '.')
1280 fieldsel(ls, v);1430 fieldsel(ls, v);
1281 if (ls->t.token == ':') {1431 if (ls->t.token == ':') {
1282 needself = 1;1432 ismethod = 1;
1283 fieldsel(ls, v);1433 fieldsel(ls, v);
1284 }1434 }
1285 return needself;1435 return ismethod;
1286}1436}
1287 1437
1288 1438
1289static void funcstat (LexState *ls, int line) {1439static void funcstat (LexState *ls, int line) {
1290 /* funcstat -> FUNCTION funcname body */1440 /* funcstat -> FUNCTION funcname body */
1291 int needself;1441 int ismethod;
1292 expdesc v, b;1442 expdesc v, b;
1293 luaX_next(ls); /* skip FUNCTION */1443 luaX_next(ls); /* skip FUNCTION */
1294 needself = funcname(ls, &v);1444 ismethod = funcname(ls, &v);
1295 body(ls, &b, needself, line);1445 body(ls, &b, ismethod, line);
1296 luaK_storevar(ls->fs, &v, &b);1446 luaK_storevar(ls->fs, &v, &b);
1297 luaK_fixline(ls->fs, line); /* definition `happens' in the first line */1447 luaK_fixline(ls->fs, line); /* definition `happens' in the first line */
1298}1448}
@@ -1313,14 +1463,14 @@ static void exprstat (LexState *ls) { · 14 unmodified lines
1313 1463
1314 1464
1315static void retstat (LexState *ls) {1465static void retstat (LexState *ls) {
1316 /* stat -> RETURN explist */1466 /* stat -> RETURN [explist] [';'] */
1317 FuncState *fs = ls->fs;1467 FuncState *fs = ls->fs;
1318 expdesc e;1468 expdesc e;
1319 int first, nret; /* registers with returned values */1469 int first, nret; /* registers with returned values */
1320 if (block_follow(ls->t.token) || ls->t.token == ';')1470 if (block_follow(ls, 1) || ls->t.token == ';')
1321 first = nret = 0; /* return no values */1471 first = nret = 0; /* return no values */
1322 else {1472 else {
1323 nret = explist1(ls, &e); /* optional return values */1473 nret = explist(ls, &e); /* optional return values */
1324 if (hasmultret(e.k)) {1474 if (hasmultret(e.k)) {
1325 luaK_setmultret(fs, &e);1475 luaK_setmultret(fs, &e);
1326 if (e.k == VCALL && nret == 1) { /* tail call? */1476 if (e.k == VCALL && nret == 1) { /* tail call? */
@@ -1341,41 +1491,43 @@ static void retstat (LexState *ls) { · 14 unmodified lines
1341 }1491 }
1342 }1492 }
1343 luaK_ret(fs, first, nret);1493 luaK_ret(fs, first, nret);
1494 testnext(ls, ';'); /* skip optional semicolon */
1344}1495}
1345 1496
1346 1497
1347static int statement (LexState *ls) {1498static void statement (LexState *ls) {
1348 int line = ls->linenumber; /* may be needed for error messages */1499 int line = ls->linenumber; /* may be needed for error messages */
1500 enterlevel(ls);
1349 switch (ls->t.token) {1501 switch (ls->t.token) {
1350 case ';': { /* stat -> ';' (empty statement) */1502 case ';': { /* stat -> ';' (empty statement) */
1351 luaX_next(ls); /* skip ';' */1503 luaX_next(ls); /* skip ';' */
1352 return 0;1504 break;
1353 }1505 }
1354 case TK_IF: { /* stat -> ifstat */1506 case TK_IF: { /* stat -> ifstat */
1355 ifstat(ls, line);1507 ifstat(ls, line);
1356 return 0;1508 break;
1357 }1509 }
1358 case TK_WHILE: { /* stat -> whilestat */1510 case TK_WHILE: { /* stat -> whilestat */
1359 whilestat(ls, line);1511 whilestat(ls, line);
1360 return 0;1512 break;
1361 }1513 }
1362 case TK_DO: { /* stat -> DO block END */1514 case TK_DO: { /* stat -> DO block END */
1363 luaX_next(ls); /* skip DO */1515 luaX_next(ls); /* skip DO */
1364 block(ls);1516 block(ls);
1365 check_match(ls, TK_END, TK_DO, line);1517 check_match(ls, TK_END, TK_DO, line);
1366 return 0;1518 break;
1367 }1519 }
1368 case TK_FOR: { /* stat -> forstat */1520 case TK_FOR: { /* stat -> forstat */
1369 forstat(ls, line);1521 forstat(ls, line);
1370 return 0;1522 break;
1371 }1523 }
1372 case TK_REPEAT: { /* stat -> repeatstat */1524 case TK_REPEAT: { /* stat -> repeatstat */
1373 repeatstat(ls, line);1525 repeatstat(ls, line);
1374 return 0;1526 break;
1375 }1527 }
1376 case TK_FUNCTION: { /* stat -> funcstat */1528 case TK_FUNCTION: { /* stat -> funcstat */
1377 funcstat(ls, line);1529 funcstat(ls, line);
1378 return 0;1530 break;
1379 }1531 }
1380 case TK_LOCAL: { /* stat -> localstat */1532 case TK_LOCAL: { /* stat -> localstat */
1381 luaX_next(ls); /* skip LOCAL */1533 luaX_next(ls); /* skip LOCAL */
@@ -1383,39 +1535,62 @@ static int statement (LexState *ls) { · 1 unmodified line
1383 localfunc(ls);1535 localfunc(ls);
1384 else1536 else
1385 localstat(ls);1537 localstat(ls);
1386 return 0;1538 break;
1539 }
1540 case '@': { /* stat -> label */
1541 luaX_next(ls); /* skip '@' */
1542 labelstat(ls, str_checkname(ls), line);
1543 break;
1387 }1544 }
1388 case TK_RETURN: { /* stat -> retstat */1545 case TK_RETURN: { /* stat -> retstat */
1389 luaX_next(ls); /* skip RETURN */1546 luaX_next(ls); /* skip RETURN */
1390 retstat(ls);1547 retstat(ls);
1391 return 1; /* must be last statement */1548 break;
1392 }1549 }
1393 case TK_BREAK: { /* stat -> breakstat */1550 case TK_BREAK: { /* stat -> breakstat */
1394 luaX_next(ls); /* skip BREAK */1551 luaX_next(ls); /* skip BREAK */
1395 breakstat(ls);1552 /* code it as "goto 'break'" */
1396 return 1; /* must be last statement */1553 gotostat(ls, luaS_new(ls->L, "break"), line);
1554 break;
1555 }
1556 case TK_GOTO: { /* stat -> 'goto' NAME */
1557 luaX_next(ls); /* skip GOTO */
1558 gotostat(ls, str_checkname(ls), line);
1559 break;
1397 }1560 }
1398 default: { /* stat -> func | assignment */1561 default: { /* stat -> func | assignment */
1399 exprstat(ls);1562 exprstat(ls);
1400 return 0;1563 break;
1401 }1564 }
1402 }1565 }
1566 lua_assert(ls->fs->f->maxstacksize >= ls->fs->freereg &&
1567 ls->fs->freereg >= ls->fs->nactvar);
1568 ls->fs->freereg = ls->fs->nactvar; /* free registers */
1569 leavelevel(ls);
1403}1570}
1404 1571
1572/* }====================================================================== */
1405 1573
1406static void chunk (LexState *ls) {1574
1407 /* chunk -> { stat [`;'] } */1575Proto *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff,
1408 int islast = 0;1576 Dyndata *dyd, const char *name, int firstchar) {
1409 enterlevel(ls);1577 LexState lexstate;
1410 while (!islast && !block_follow(ls->t.token)) {1578 FuncState funcstate;
1411 islast = statement(ls);1579 BlockCnt bl;
1412 if (islast)1580 TString *tname = luaS_new(L, name);
1413 testnext(ls, ';');1581 setsvalue2s(L, L->top, tname); /* push name to protect it */
1414 lua_assert(ls->fs->f->maxstacksize >= ls->fs->freereg &&1582 incr_top(L);
1415 ls->fs->freereg >= ls->fs->nactvar);1583 lexstate.buff = buff;
1416 ls->fs->freereg = ls->fs->nactvar; /* free registers */1584 lexstate.dyd = dyd;
1417 }1585 dyd->actvar.n = dyd->gt.n = dyd->label.n = 0;
1418 leavelevel(ls);1586 luaX_setinput(L, &lexstate, z, tname, firstchar);
1587 open_mainfunc(&lexstate, &funcstate, &bl);
1588 luaX_next(&lexstate); /* read first token */
1589 statlist(&lexstate); /* main body */
1590 check(&lexstate, TK_EOS);
1591 close_func(&lexstate);
1592 L->top--; /* pop name */
1593 lua_assert(!funcstate.prev && funcstate.nups == 1 && !lexstate.fs);
1594 return funcstate.f;
1419}1595}
1420 1596
1421/* }====================================================================== */
src/lparser.h+34−11
@@ -1,5 +1,5 @@
1/*1/*
2** $Id: lparser.h,v 1.65 2010/07/07 16:27:29 roberto Exp $2** $Id: lparser.h,v 1.68 2011/02/23 13:13:10 roberto Exp $
3** Lua Parser3** Lua Parser
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -53,19 +53,42 @@ typedef struct expdesc { · 47 unmodified lines
53} expdesc;53} expdesc;
54 54
55 55
56typedef struct vardesc {56/* description of active local variable */
57 unsigned short idx;57typedef struct Vardesc {
58} vardesc;58 unsigned short idx; /* variable index in stack */
59} Vardesc;
59 60
60 61
61/* list of all active local variables */62/* description of pending goto statements and label statements */
62typedef struct Varlist {63typedef struct Labeldesc {
63 vardesc *actvar;64 TString *name; /* label identifier */
64 int nactvar;65 int pc; /* position in code */
65 int actvarsize;66 int line; /* line where it appeared */
66} Varlist;67 lu_byte nactvar; /* local level where it appears in current block */
68} Labeldesc;
67 69
68 70
71/* list of labels or gotos */
72typedef struct Labellist {
73 Labeldesc *arr; /* array */
74 int n; /* number of entries in use */
75 int size; /* array size */
76} Labellist;
77
78
79/* dynamic structures used by the parser */
80typedef struct Dyndata {
81 struct { /* list of active local variables */
82 Vardesc *arr;
83 int n;
84 int size;
85 } actvar;
86 Labellist gt; /* list of pending gotos */
87 Labellist label; /* list of active labels */
88} Dyndata;
89
90
91/* control of blocks */
69struct BlockCnt; /* defined in lparser.c */92struct BlockCnt; /* defined in lparser.c */
70 93
71 94
@@ -91,7 +114,7 @@ typedef struct FuncState { · 19 unmodified lines
91 114
92 115
93LUAI_FUNC Proto *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff,116LUAI_FUNC Proto *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff,
94 Varlist *varl, const char *name);117 Dyndata *dyd, const char *name, int firstchar);
95 118
96 119
97#endif120#endif
src/lstate.c+12−8
@@ -1,5 +1,5 @@
1/*1/*
2** $Id: lstate.c,v 2.86 2010/09/03 14:14:01 roberto Exp $2** $Id: lstate.c,v 2.89 2010/12/20 19:40:07 roberto Exp $
3** Global State3** Global State
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -65,11 +65,14 @@ typedef struct LG { · 59 unmodified lines
65#define fromstate(L) (cast(LX *, cast(lu_byte *, (L)) - offsetof(LX, l)))65#define fromstate(L) (cast(LX *, cast(lu_byte *, (L)) - offsetof(LX, l)))
66 66
67 67
68
69/*68/*
70** maximum number of nested calls made by error-handling function69** set GCdebt to a new value keeping the value (totalbytes + GCdebt)
70** invariant
71*/71*/
72#define LUAI_EXTRACALLS 1072void luaE_setdebt (global_State *g, l_mem debt) {
73 g->totalbytes -= (debt - g->GCdebt);
74 g->GCdebt = debt;
75}
73 76
74 77
75CallInfo *luaE_extendCI (lua_State *L) {78CallInfo *luaE_extendCI (lua_State *L) {
@@ -154,7 +157,7 @@ static void f_luaopen (lua_State *L, void *ud) { · 78 unmodified lines
154 /* pre-create memory-error message */157 /* pre-create memory-error message */
155 g->memerrmsg = luaS_newliteral(L, MEMERRMSG);158 g->memerrmsg = luaS_newliteral(L, MEMERRMSG);
156 luaS_fix(g->memerrmsg); /* it should never be collected */159 luaS_fix(g->memerrmsg); /* it should never be collected */
157 g->GCdebt = 0;160 g->gcrunning = 1; /* allow gc */
158}161}
159 162
160 163
@@ -187,7 +190,7 @@ static void close_state (lua_State *L) { · 26 unmodified lines
187 luaM_freearray(L, G(L)->strt.hash, G(L)->strt.size);190 luaM_freearray(L, G(L)->strt.hash, G(L)->strt.size);
188 luaZ_freebuffer(L, &g->buff);191 luaZ_freebuffer(L, &g->buff);
189 freestack(L);192 freestack(L);
190 lua_assert(g->totalbytes == sizeof(LG));193 lua_assert(gettotalbytes(g) == sizeof(LG));
191 (*g->frealloc)(g->ud, fromstate(L), sizeof(LG), 0);194 (*g->frealloc)(g->ud, fromstate(L), sizeof(LG), 0);
192}195}
193 196
@@ -241,7 +244,7 @@ LUA_API lua_State *lua_newstate (lua_Alloc f, void *ud) { · 47 unmodified lines
241 g->mainthread = L;244 g->mainthread = L;
242 g->uvhead.u.l.prev = &g->uvhead;245 g->uvhead.u.l.prev = &g->uvhead;
243 g->uvhead.u.l.next = &g->uvhead;246 g->uvhead.u.l.next = &g->uvhead;
244 stopgc(g); /* no GC while building state */247 g->gcrunning = 0; /* no GC while building state */
245 g->lastmajormem = 0;248 g->lastmajormem = 0;
246 g->strt.size = 0;249 g->strt.size = 0;
247 g->strt.nuse = 0;250 g->strt.nuse = 0;
@@ -252,11 +255,12 @@ LUA_API lua_State *lua_newstate (lua_Alloc f, void *ud) { · 4 unmodified lines
252 g->version = lua_version(NULL);255 g->version = lua_version(NULL);
253 g->gcstate = GCSpause;256 g->gcstate = GCSpause;
254 g->allgc = NULL;257 g->allgc = NULL;
255 g->udgc = NULL;258 g->finobj = NULL;
256 g->tobefnz = NULL;259 g->tobefnz = NULL;
257 g->gray = g->grayagain = NULL;260 g->gray = g->grayagain = NULL;
258 g->weak = g->ephemeron = g->allweak = NULL;261 g->weak = g->ephemeron = g->allweak = NULL;
259 g->totalbytes = sizeof(LG);262 g->totalbytes = sizeof(LG);
263 g->GCdebt = 0;
260 g->gcpause = LUAI_GCPAUSE;264 g->gcpause = LUAI_GCPAUSE;
261 g->gcmajorinc = LUAI_GCMAJOR;265 g->gcmajorinc = LUAI_GCMAJOR;
262 g->gcstepmul = LUAI_GCMUL;266 g->gcstepmul = LUAI_GCMUL;
src/lstate.h+11−7
@@ -1,5 +1,5 @@
1/*1/*
2** $Id: lstate.h,v 2.68 2010/10/29 17:52:46 roberto Exp $2** $Id: lstate.h,v 2.72 2011/06/02 19:31:40 roberto Exp $
3** Global State3** Global State
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -32,9 +32,9 @@ · 26 unmodified lines
32** when traversing the respective threads, but the thread may already be32** when traversing the respective threads, but the thread may already be
33** dead, while the upvalue is still accessible through closures.)33** dead, while the upvalue is still accessible through closures.)
34**34**
35** Userdata with finalizers are kept in the list g->udgc.35** Objects with finalizers are kept in the list g->finobj.
36**36**
37** The list g->tobefnz links all userdata being finalized.37** The list g->tobefnz links all objects being finalized.
38 38
39*/39*/
40 40
@@ -104,7 +104,6 @@ typedef struct CallInfo { · 63 unmodified lines
104#define CIST_TAIL (1<<6) /* call was tail called */104#define CIST_TAIL (1<<6) /* call was tail called */
105 105
106 106
107#define ci_func(ci) (clvalue((ci)->func))
108#define isLua(ci) ((ci)->callstatus & CIST_LUA)107#define isLua(ci) ((ci)->callstatus & CIST_LUA)
109 108
110 109
@@ -114,8 +113,8 @@ typedef struct CallInfo { · 3 unmodified lines
114typedef struct global_State {113typedef struct global_State {
115 lua_Alloc frealloc; /* function to reallocate memory */114 lua_Alloc frealloc; /* function to reallocate memory */
116 void *ud; /* auxiliary data to `frealloc' */115 void *ud; /* auxiliary data to `frealloc' */
117 lu_mem totalbytes; /* number of bytes currently allocated */116 lu_mem totalbytes; /* number of bytes currently allocated - GCdebt */
118 l_mem GCdebt; /* when positive, run a GC step */117 l_mem GCdebt; /* bytes allocated not yet compensated by the collector */
119 lu_mem lastmajormem; /* memory in use after last major collection */118 lu_mem lastmajormem; /* memory in use after last major collection */
120 stringtable strt; /* hash table for strings */119 stringtable strt; /* hash table for strings */
121 TValue l_registry;120 TValue l_registry;
@@ -123,9 +122,10 @@ typedef struct global_State { · 1 unmodified line
123 lu_byte currentwhite;122 lu_byte currentwhite;
124 lu_byte gcstate; /* state of garbage collector */123 lu_byte gcstate; /* state of garbage collector */
125 lu_byte gckind; /* kind of GC running */124 lu_byte gckind; /* kind of GC running */
125 lu_byte gcrunning; /* true if GC is running */
126 int sweepstrgc; /* position of sweep in `strt' */126 int sweepstrgc; /* position of sweep in `strt' */
127 GCObject *allgc; /* list of all collectable objects */127 GCObject *allgc; /* list of all collectable objects */
128 GCObject *udgc; /* list of collectable userdata with finalizers */128 GCObject *finobj; /* list of collectable objects with finalizers */
129 GCObject **sweepgc; /* current position of sweep */129 GCObject **sweepgc; /* current position of sweep */
130 GCObject *gray; /* list of gray objects */130 GCObject *gray; /* list of gray objects */
131 GCObject *grayagain; /* list of objects to be traversed atomically */131 GCObject *grayagain; /* list of objects to be traversed atomically */
@@ -209,6 +209,10 @@ union GCObject { · 77 unmodified lines
209#define obj2gco(v) (cast(GCObject *, (v)))209#define obj2gco(v) (cast(GCObject *, (v)))
210 210
211 211
212/* actual number of total bytes allocated */
213#define gettotalbytes(g) ((g)->totalbytes + (g)->GCdebt)
214
215LUAI_FUNC void luaE_setdebt (global_State *g, l_mem debt);
212LUAI_FUNC void luaE_freethread (lua_State *L, lua_State *L1);216LUAI_FUNC void luaE_freethread (lua_State *L, lua_State *L1);
213LUAI_FUNC CallInfo *luaE_extendCI (lua_State *L);217LUAI_FUNC CallInfo *luaE_extendCI (lua_State *L);
214LUAI_FUNC void luaE_freeCI (lua_State *L);218LUAI_FUNC void luaE_freeCI (lua_State *L);
src/lstring.c+4−3
@@ -1,5 +1,5 @@
1/*1/*
2** $Id: lstring.c,v 2.18 2010/05/10 18:23:45 roberto Exp $2** $Id: lstring.c,v 2.19 2011/05/03 16:01:57 roberto Exp $
3** String table (keeps all strings handled by Lua)3** String table (keeps all strings handled by Lua)
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -84,8 +84,9 @@ TString *luaS_newlstr (lua_State *L, const char *str, size_t l) { · 78 unmodified lines
84 o != NULL;84 o != NULL;
85 o = gch(o)->next) {85 o = gch(o)->next) {
86 TString *ts = rawgco2ts(o);86 TString *ts = rawgco2ts(o);
87 if (h == ts->tsv.hash && ts->tsv.len == l &&87 if (h == ts->tsv.hash &&
88 (memcmp(str, getstr(ts), l) == 0)) {88 ts->tsv.len == l &&
89 (memcmp(str, getstr(ts), l * sizeof(char)) == 0)) {
89 if (isdead(G(L), o)) /* string is dead (but was not collected yet)? */90 if (isdead(G(L), o)) /* string is dead (but was not collected yet)? */
90 changewhite(o); /* resurrect it */91 changewhite(o); /* resurrect it */
91 return ts;92 return ts;
src/lstrlib.c+51−22
@@ -1,5 +1,5 @@
1/*1/*
2** $Id: lstrlib.c,v 1.159 2010/11/19 16:25:51 roberto Exp $2** $Id: lstrlib.c,v 1.168 2011/06/09 18:22:47 roberto Exp $
3** Standard library for string operations and pattern-matching3** Standard library for string operations and pattern-matching
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -45,7 +45,7 @@ static int str_len (lua_State *L) { · 39 unmodified lines
45/* translate a relative string position: negative means back from end */45/* translate a relative string position: negative means back from end */
46static size_t posrelat (ptrdiff_t pos, size_t len) {46static size_t posrelat (ptrdiff_t pos, size_t len) {
47 if (pos >= 0) return (size_t)pos;47 if (pos >= 0) return (size_t)pos;
48 else if (pos == -pos || (size_t)-pos > len) return 0;48 else if (-(size_t)pos > len) return 0;
49 else return len - ((size_t)-pos) + 1;49 else return len - ((size_t)-pos) + 1;
50}50}
51 51
@@ -101,15 +101,29 @@ static int str_upper (lua_State *L) { · 49 unmodified lines
101 return 1;101 return 1;
102}102}
103 103
104
105/* reasonable limit to avoid arithmetic overflow */
106#define MAXSIZE ((~(size_t)0) >> 1)
107
104static int str_rep (lua_State *L) {108static int str_rep (lua_State *L) {
105 size_t l;109 size_t l, lsep;
106 luaL_Buffer b;
107 const char *s = luaL_checklstring(L, 1, &l);110 const char *s = luaL_checklstring(L, 1, &l);
108 int n = luaL_checkint(L, 2);111 int n = luaL_checkint(L, 2);
109 luaL_buffinit(L, &b);112 const char *sep = luaL_optlstring(L, 3, "", &lsep);
110 while (n-- > 0)113 if (n <= 0) lua_pushliteral(L, "");
111 luaL_addlstring(&b, s, l);114 else if (l + lsep < l || l + lsep >= MAXSIZE / n) /* may overflow? */
112 luaL_pushresult(&b);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 memcpy(p, sep, lsep * sizeof(char)); p += lsep;
123 }
124 memcpy(p, s, l * sizeof(char)); /* last copy (not followed by separator) */
125 luaL_pushresultsize(&b, totallen);
126 }
113 return 1;127 return 1;
114}128}
115 129
@@ -125,7 +139,7 @@ static int str_byte (lua_State *L) { · 9 unmodified lines
125 if (posi > pose) return 0; /* empty interval; return no values */139 if (posi > pose) return 0; /* empty interval; return no values */
126 n = (int)(pose - posi + 1);140 n = (int)(pose - posi + 1);
127 if (posi + n <= pose) /* overflow? */141 if (posi + n <= pose) /* overflow? */
128 luaL_error(L, "string slice too long");142 return luaL_error(L, "string slice too long");
129 luaL_checkstack(L, n, "string slice too long");143 luaL_checkstack(L, n, "string slice too long");
130 for (i=0; i<n; i++)144 for (i=0; i<n; i++)
131 lua_pushinteger(L, uchar(s[posi+i-1]));145 lua_pushinteger(L, uchar(s[posi+i-1]));
@@ -161,7 +175,7 @@ static int str_dump (lua_State *L) { · 29 unmodified lines
161 lua_settop(L, 1);175 lua_settop(L, 1);
162 luaL_buffinit(L,&b);176 luaL_buffinit(L,&b);
163 if (lua_dump(L, writer, &b) != 0)177 if (lua_dump(L, writer, &b) != 0)
164 luaL_error(L, "unable to dump given function");178 return luaL_error(L, "unable to dump given function");
165 luaL_pushresult(&b);179 luaL_pushresult(&b);
166 return 1;180 return 1;
167}181}
@@ -510,7 +524,7 @@ static int nospecials (const char *p, size_t l) { · 342 unmodified lines
510 size_t upto = 0;524 size_t upto = 0;
511 do {525 do {
512 if (strpbrk(p + upto, SPECIALS))526 if (strpbrk(p + upto, SPECIALS))
513 return 0; /* pattern has a special character */ 527 return 0; /* pattern has a special character */
514 upto += strlen(p + upto) + 1; /* may have more after \0 */528 upto += strlen(p + upto) + 1; /* may have more after \0 */
515 } while (upto <= l);529 } while (upto <= l);
516 return 1; /* no special chars found */530 return 1; /* no special chars found */
@@ -729,7 +743,7 @@ static int str_gsub (lua_State *L) { · 212 unmodified lines
729** the previous length743** the previous length
730*/744*/
731#if !defined(LUA_INTFRMLEN) /* { */745#if !defined(LUA_INTFRMLEN) /* { */
732#if defined(LUA_USELONGLONG)746#if defined(LUA_USE_LONGLONG)
733 747
734#define LUA_INTFRMLEN "ll"748#define LUA_INTFRMLEN "ll"
735#define LUA_INTFRM_T long long749#define LUA_INTFRM_T long long
@@ -794,7 +808,7 @@ static void addquoted (lua_State *L, luaL_Buffer *b, int arg) { · 58 unmodified lines
794static const char *scanformat (lua_State *L, const char *strfrmt, char *form) {808static const char *scanformat (lua_State *L, const char *strfrmt, char *form) {
795 const char *p = strfrmt;809 const char *p = strfrmt;
796 while (*p != '\0' && strchr(FLAGS, *p) != NULL) p++; /* skip flags */810 while (*p != '\0' && strchr(FLAGS, *p) != NULL) p++; /* skip flags */
797 if ((size_t)(p - strfrmt) >= sizeof(FLAGS))811 if ((size_t)(p - strfrmt) >= sizeof(FLAGS)/sizeof(char))
798 luaL_error(L, "invalid format (repeated flags)");812 luaL_error(L, "invalid format (repeated flags)");
799 if (isdigit(uchar(*p))) p++; /* skip width */813 if (isdigit(uchar(*p))) p++; /* skip width */
800 if (isdigit(uchar(*p))) p++; /* (2 digits at most) */814 if (isdigit(uchar(*p))) p++; /* (2 digits at most) */
@@ -806,7 +820,7 @@ static const char *scanformat (lua_State *L, const char *strfrmt, char *form) { · 5 unmodified lines
806 if (isdigit(uchar(*p)))820 if (isdigit(uchar(*p)))
807 luaL_error(L, "invalid format (width or precision too long)");821 luaL_error(L, "invalid format (width or precision too long)");
808 *(form++) = '%';822 *(form++) = '%';
809 memcpy(form, strfrmt, p - strfrmt + 1);823 memcpy(form, strfrmt, (p - strfrmt + 1) * sizeof(char));
810 form += p - strfrmt + 1;824 form += p - strfrmt + 1;
811 *form = '\0';825 *form = '\0';
812 return p;826 return p;
@@ -861,6 +875,9 @@ static int str_format (lua_State *L) { · 48 unmodified lines
861 break;875 break;
862 }876 }
863 case 'e': case 'E': case 'f':877 case 'e': case 'E': case 'f':
878#if defined(LUA_USE_AFORMAT)
879 case 'a': case 'A':
880#endif
864 case 'g': case 'G': {881 case 'g': case 'G': {
865 addlenmod(form, LUA_FLTFRMLEN);882 addlenmod(form, LUA_FLTFRMLEN);
866 nb = sprintf(buff, form, (LUA_FLTFRM_T)luaL_checknumber(L, arg));883 nb = sprintf(buff, form, (LUA_FLTFRM_T)luaL_checknumber(L, arg));
@@ -872,16 +889,16 @@ static int str_format (lua_State *L) { · 5 unmodified lines
872 }889 }
873 case 's': {890 case 's': {
874 size_t l;891 size_t l;
875 const char *s = luaL_checklstring(L, arg, &l);892 const char *s = luaL_tolstring(L, arg, &l);
876 if (!strchr(form, '.') && l >= 100) {893 if (!strchr(form, '.') && l >= 100) {
877 /* no precision and string is too long to be formatted;894 /* no precision and string is too long to be formatted;
878 keep original string */895 keep original string */
879 lua_pushvalue(L, arg);
880 luaL_addvalue(&b);896 luaL_addvalue(&b);
881 break;897 break;
882 }898 }
883 else {899 else {
884 nb = sprintf(buff, form, s);900 nb = sprintf(buff, form, s);
901 lua_pop(L, 1); /* remove result from 'luaL_tolstring' */
885 break;902 break;
886 }903 }
887 }904 }
@@ -900,6 +917,15 @@ static int str_format (lua_State *L) { · 12 unmodified lines
900/* }====================================================== */917/* }====================================================== */
901 918
902 919
920static int noindex (lua_State *L) {
921 const char *f = lua_tostring(L, 2);
922 if (f)
923 return luaL_error(L, "no field '%s' in strings", f);
924 else
925 return luaL_error(L, "no such field in strings");
926}
927
928
903static const luaL_Reg strlib[] = {929static const luaL_Reg strlib[] = {
904 {"byte", str_byte},930 {"byte", str_byte},
905 {"char", str_char},931 {"char", str_char},
@@ -915,19 +941,22 @@ static const luaL_Reg strlib[] = { · 9 unmodified lines
915 {"reverse", str_reverse},941 {"reverse", str_reverse},
916 {"sub", str_sub},942 {"sub", str_sub},
917 {"upper", str_upper},943 {"upper", str_upper},
944 {"__index", noindex},
918 {NULL, NULL}945 {NULL, NULL}
919};946};
920 947
921 948
922static void createmetatable (lua_State *L) {949static void createmetatable (lua_State *L) {
923 lua_createtable(L, 0, 1); /* create metatable for strings */950 /* setmetatable("", {__index = string}) */
924 lua_pushliteral(L, ""); /* dummy string */951 lua_pushliteral(L, ""); /* dummy string */
925 lua_pushvalue(L, -2);952 lua_createtable(L, 0, 1); /* create metatable for strings */
926 lua_setmetatable(L, -2); /* set string metatable */953 lua_pushvalue(L, -3); /* set the string library... */
954 lua_setfield(L, -2, "__index"); /* ...as the __index metamethod */
955 lua_setmetatable(L, -2); /* set metatable for strings */
927 lua_pop(L, 1); /* pop dummy string */956 lua_pop(L, 1); /* pop dummy string */
928 lua_pushvalue(L, -2); /* string library... */957 /* setmetatable(string, string) */
929 lua_setfield(L, -2, "__index"); /* ...is the __index metamethod */958 lua_pushvalue(L, -1); /* push string library */
930 lua_pop(L, 1); /* pop metatable */959 lua_setmetatable(L, -2); /* set it as its own metatable */
931}960}
932 961
933 962
src/ltable.c+10−8
@@ -1,5 +1,5 @@
1/*1/*
2** $Id: ltable.c,v 2.53 2010/11/11 15:38:43 roberto Exp $2** $Id: ltable.c,v 2.59 2011/06/09 18:23:27 roberto Exp $
3** Lua tables (hash)3** Lua tables (hash)
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -33,6 +33,7 @@ · 27 unmodified lines
33#include "lstate.h"33#include "lstate.h"
34#include "lstring.h"34#include "lstring.h"
35#include "ltable.h"35#include "ltable.h"
36#include "lvm.h"
36 37
37 38
38/*39/*
@@ -87,8 +88,9 @@ static Node *hashnum (const Table *t, lua_Number n) { · 48 unmodified lines
87 int i;88 int i;
88 luai_hashnum(i, n);89 luai_hashnum(i, n);
89 if (i < 0) {90 if (i < 0) {
90 i = -i; /* must be a positive value */91 if ((unsigned int)i == -(unsigned int)i)
91 if (i < 0) i = 0; /* handle INT_MIN */92 i = 0; /* handle INT_MIN */
93 i = -i; /* must be a positive value */
92 }94 }
93 return hashmod(t, i);95 return hashmod(t, i);
94}96}
@@ -148,8 +150,8 @@ static int findindex (lua_State *L, Table *t, StkId key) { · 53 unmodified lines
148 Node *n = mainposition(t, key);150 Node *n = mainposition(t, key);
149 do { /* check whether `key' is somewhere in the chain */151 do { /* check whether `key' is somewhere in the chain */
150 /* key may be dead already, but it is ok to use it in `next' */152 /* key may be dead already, but it is ok to use it in `next' */
151 if (luaO_rawequalObj(gkey(n), key) ||153 if (luaV_rawequalobj(gkey(n), key) ||
152 (ttype(gkey(n)) == LUA_TDEADKEY && iscollectable(key) &&154 (ttisdeadkey(gkey(n)) && iscollectable(key) &&
153 gcvalue(gkey(n)) == gcvalue(key))) {155 gcvalue(gkey(n)) == gcvalue(key))) {
154 i = cast_int(n - gnode(t, 0)); /* key index in hash table */156 i = cast_int(n - gnode(t, 0)); /* key index in hash table */
155 /* hash elements are numbered after array ones */157 /* hash elements are numbered after array ones */
@@ -336,7 +338,7 @@ void luaH_resizearray (lua_State *L, Table *t, int nasize) { · 180 unmodified lines
336 338
337static void rehash (lua_State *L, Table *t, const TValue *ek) {339static void rehash (lua_State *L, Table *t, const TValue *ek) {
338 int nasize, na;340 int nasize, na;
339 int nums[MAXBITS+1]; /* nums[i] = number of keys between 2^(i-1) and 2^i */341 int nums[MAXBITS+1]; /* nums[i] = number of keys with 2^(i-1) < k <= 2^i */
340 int i;342 int i;
341 int totaluse;343 int totaluse;
342 for (i=0; i<=MAXBITS; i++) nums[i] = 0; /* reset counts */344 for (i=0; i<=MAXBITS; i++) nums[i] = 0; /* reset counts */
@@ -467,7 +469,7 @@ const TValue *luaH_getstr (Table *t, TString *key) { · 124 unmodified lines
467** main search function469** main search function
468*/470*/
469const TValue *luaH_get (Table *t, const TValue *key) {471const TValue *luaH_get (Table *t, const TValue *key) {
470 switch (ttype(key)) {472 switch (ttypenv(key)) {
471 case LUA_TNIL: return luaO_nilobject;473 case LUA_TNIL: return luaO_nilobject;
472 case LUA_TSTRING: return luaH_getstr(t, rawtsvalue(key));474 case LUA_TSTRING: return luaH_getstr(t, rawtsvalue(key));
473 case LUA_TNUMBER: {475 case LUA_TNUMBER: {
@@ -481,7 +483,7 @@ const TValue *luaH_get (Table *t, const TValue *key) { · 7 unmodified lines
481 default: {483 default: {
482 Node *n = mainposition(t, key);484 Node *n = mainposition(t, key);
483 do { /* check whether `key' is somewhere in the chain */485 do { /* check whether `key' is somewhere in the chain */
484 if (luaO_rawequalObj(gkey(n), key))486 if (luaV_rawequalobj(gkey(n), key))
485 return gval(n); /* that's it */487 return gval(n); /* that's it */
486 else n = gnext(n);488 else n = gnext(n);
487 } while (n);489 } while (n);
src/ltablib.c+4−4
@@ -1,5 +1,5 @@
1/*1/*
2** $Id: ltablib.c,v 1.58 2010/11/23 17:21:14 roberto Exp $2** $Id: ltablib.c,v 1.59 2010/12/17 12:15:34 roberto Exp $
3** Library for Table Manipulation3** Library for Table Manipulation
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -17,7 +17,7 @@ · 11 unmodified lines
17 17
18 18
19#define aux_getn(L,n) \19#define aux_getn(L,n) \
20 (luaL_checktype(L, n, LUA_TTABLE), (int)lua_rawlen(L, n))20 (luaL_checktype(L, n, LUA_TTABLE), luaL_len(L, n))
21 21
22 22
23static int deprecatedfunc (lua_State *L) {23static int deprecatedfunc (lua_State *L) {
@@ -104,7 +104,7 @@ static int tconcat (lua_State *L) { · 80 unmodified lines
104 const char *sep = luaL_optlstring(L, 2, "", &lsep);104 const char *sep = luaL_optlstring(L, 2, "", &lsep);
105 luaL_checktype(L, 1, LUA_TTABLE);105 luaL_checktype(L, 1, LUA_TTABLE);
106 i = luaL_optint(L, 3, 1);106 i = luaL_optint(L, 3, 1);
107 last = luaL_opt(L, luaL_checkint, 4, (int)lua_rawlen(L, 1));107 last = luaL_opt(L, luaL_checkint, 4, luaL_len(L, 1));
108 luaL_buffinit(L, &b);108 luaL_buffinit(L, &b);
109 for (; i < last; i++) {109 for (; i < last; i++) {
110 addfield(L, &b, i);110 addfield(L, &b, i);
@@ -143,7 +143,7 @@ static int unpack (lua_State *L) { · 32 unmodified lines
143 int i, e, n;143 int i, e, n;
144 luaL_checktype(L, 1, LUA_TTABLE);144 luaL_checktype(L, 1, LUA_TTABLE);
145 i = luaL_optint(L, 2, 1);145 i = luaL_optint(L, 2, 1);
146 e = luaL_opt(L, luaL_checkint, 3, (int)lua_rawlen(L, 1));146 e = luaL_opt(L, luaL_checkint, 3, luaL_len(L, 1));
147 if (i > e) return 0; /* empty range */147 if (i > e) return 0; /* empty range */
148 n = e - i + 1; /* number of elements */148 n = e - i + 1; /* number of elements */
149 if (n <= 0 || !lua_checkstack(L, n)) /* n <= 0 means arith. overflow */149 if (n <= 0 || !lua_checkstack(L, n)) /* n <= 0 means arith. overflow */
src/ltm.c+4−4
@@ -1,5 +1,5 @@
1/*1/*
2** $Id: ltm.c,v 2.12 2010/04/13 20:48:12 roberto Exp $2** $Id: ltm.c,v 2.14 2011/06/02 19:31:40 roberto Exp $
3** Tag methods3** Tag methods
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -21,11 +21,11 @@ · 15 unmodified lines
21 21
22static const char udatatypename[] = "userdata";22static const char udatatypename[] = "userdata";
23 23
24LUAI_DDEF const char *const luaT_typenames_[] = {24LUAI_DDEF const char *const luaT_typenames_[LUA_TOTALTAGS] = {
25 "no value",25 "no value",
26 "nil", "boolean", udatatypename, "number",26 "nil", "boolean", udatatypename, "number",
27 "string", "table", "function", udatatypename, "thread",27 "string", "table", "function", udatatypename, "thread",
28 "proto", "upval"28 "proto", "upval" /* these last two cases are used for tests only */
29};29};
30 30
31 31
@@ -62,7 +62,7 @@ const TValue *luaT_gettm (Table *events, TMS event, TString *ename) { · 30 unmodified lines
62 62
63const TValue *luaT_gettmbyobj (lua_State *L, const TValue *o, TMS event) {63const TValue *luaT_gettmbyobj (lua_State *L, const TValue *o, TMS event) {
64 Table *mt;64 Table *mt;
65 switch (ttype(o)) {65 switch (ttypenv(o)) {
66 case LUA_TTABLE:66 case LUA_TTABLE:
67 mt = hvalue(o)->metatable;67 mt = hvalue(o)->metatable;
68 break;68 break;
src/ltm.h+2−2
@@ -1,5 +1,5 @@
1/*1/*
2** $Id: ltm.h,v 2.10 2010/04/13 20:48:12 roberto Exp $2** $Id: ltm.h,v 2.11 2011/02/28 17:32:10 roberto Exp $
3** Tag methods3** Tag methods
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -46,7 +46,7 @@ typedef enum { · 40 unmodified lines
46#define ttypename(x) luaT_typenames_[(x) + 1]46#define ttypename(x) luaT_typenames_[(x) + 1]
47#define objtypename(x) ttypename(ttypenv(x))47#define objtypename(x) ttypename(ttypenv(x))
48 48
49LUAI_DDEC const char *const luaT_typenames_[];49LUAI_DDEC const char *const luaT_typenames_[LUA_TOTALTAGS];
50 50
51 51
52LUAI_FUNC const TValue *luaT_gettm (Table *events, TMS event, TString *ename);52LUAI_FUNC const TValue *luaT_gettm (Table *events, TMS event, TString *ename);
src/lua.c+10−11
@@ -1,5 +1,5 @@
1/*1/*
2** $Id: lua.c,v 1.194 2010/10/25 19:01:37 roberto Exp $2** $Id: lua.c,v 1.199 2011/05/26 16:09:40 roberto Exp $
3** Lua stand-alone interpreter3** Lua stand-alone interpreter
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -106,13 +106,11 @@ static void laction (int i) { · 100 unmodified lines
106 106
107 107
108static void print_usage (const char *badoption) {108static void print_usage (const char *badoption) {
109 if (badoption[1] == 'e' || badoption[1] == 'l') {109 luai_writestringerror("%s: ", progname);
110 luai_writestringerror("%s: ", progname);110 if (badoption[1] == 'e' || badoption[1] == 'l')
111 luai_writestringerror("'%s' needs argument\n", badoption);111 luai_writestringerror("'%s' needs argument\n", badoption);
112 } else {112 else
113 luai_writestringerror("%s: ", progname);
114 luai_writestringerror("unrecognized option '%s'\n", badoption);113 luai_writestringerror("unrecognized option '%s'\n", badoption);
115 }
116 luai_writestringerror(114 luai_writestringerror(
117 "usage: %s [options] [script [args]]\n"115 "usage: %s [options] [script [args]]\n"
118 "Available options are:\n"116 "Available options are:\n"
@@ -185,7 +183,8 @@ static int docall (lua_State *L, int narg, int nres) { · 66 unmodified lines
185 183
186 184
187static void print_version (void) {185static void print_version (void) {
188 printf("%s\n", LUA_COPYRIGHT);186 luai_writestring(LUA_COPYRIGHT, sizeof(LUA_COPYRIGHT));
187 luai_writeline();
189}188}
190 189
191 190
@@ -247,14 +246,14 @@ static const char *get_prompt (lua_State *L, int firstline) { · 55 unmodified lines
247}246}
248 247
249/* mark in error messages for incomplete statements */248/* mark in error messages for incomplete statements */
250#define mark "<eof>"249#define EOFMARK "<eof>"
251#define marklen (sizeof(mark) - 1)250#define marklen (sizeof(EOFMARK)/sizeof(char) - 1)
252 251
253static int incomplete (lua_State *L, int status) {252static int incomplete (lua_State *L, int status) {
254 if (status == LUA_ERRSYNTAX) {253 if (status == LUA_ERRSYNTAX) {
255 size_t lmsg;254 size_t lmsg;
256 const char *msg = lua_tolstring(L, -1, &lmsg);255 const char *msg = lua_tolstring(L, -1, &lmsg);
257 if (lmsg >= marklen && strcmp(msg + lmsg - marklen, mark) == 0) {256 if (lmsg >= marklen && strcmp(msg + lmsg - marklen, EOFMARK) == 0) {
258 lua_pop(L, 1);257 lua_pop(L, 1);
259 return 1;258 return 1;
260 }259 }
@@ -322,7 +321,7 @@ static void dotty (lua_State *L) { · 61 unmodified lines
322 }321 }
323 }322 }
324 lua_settop(L, 0); /* clear stack */323 lua_settop(L, 0); /* clear stack */
325 luai_writestring("\n", 1);324 luai_writeline();
326 progname = oldprogname;325 progname = oldprogname;
327}326}
328 327
src/lua.h+4−4
@@ -1,5 +1,5 @@
1/*1/*
2** $Id: lua.h,v 1.276 2010/10/26 19:32:19 roberto Exp $2** $Id: lua.h,v 1.277 2011/04/18 14:15:48 roberto Exp $
3** Lua - A Scripting Language3** Lua - A Scripting Language
4** Lua.org, PUC-Rio, Brazil (http://www.lua.org)4** Lua.org, PUC-Rio, Brazil (http://www.lua.org)
5** See Copyright Notice at the end of this file5** See Copyright Notice at the end of this file
@@ -18,12 +18,12 @@ · 12 unmodified lines
18 18
19#define LUA_VERSION_MAJOR "5"19#define LUA_VERSION_MAJOR "5"
20#define LUA_VERSION_MINOR "2"20#define LUA_VERSION_MINOR "2"
21#define LUA_VERSION_RELEASE "0" " (alpha)"21#define LUA_VERSION_RELEASE "0" " (beta)"
22 22
23#define LUA_VERSION "Lua " LUA_VERSION_MAJOR "." LUA_VERSION_MINOR23#define LUA_VERSION "Lua " LUA_VERSION_MAJOR "." LUA_VERSION_MINOR
24#define LUA_RELEASE LUA_VERSION "." LUA_VERSION_RELEASE24#define LUA_RELEASE LUA_VERSION "." LUA_VERSION_RELEASE
25#define LUA_VERSION_NUM 50225#define LUA_VERSION_NUM 502
26#define LUA_COPYRIGHT LUA_RELEASE " Copyright (C) 1994-2010 Lua.org, PUC-Rio"26#define LUA_COPYRIGHT LUA_RELEASE " Copyright (C) 1994-2011 Lua.org, PUC-Rio"
27#define LUA_AUTHORS "R. Ierusalimschy, L. H. de Figueiredo, W. Celes"27#define LUA_AUTHORS "R. Ierusalimschy, L. H. de Figueiredo, W. Celes"
28 28
29 29
@@ -415,7 +415,7 @@ struct lua_Debug { · 385 unmodified lines
415 415
416 416
417/******************************************************************************417/******************************************************************************
418* Copyright (C) 1994-2010 Lua.org, PUC-Rio. All rights reserved.418* Copyright (C) 1994-2011 Lua.org, PUC-Rio. All rights reserved.
419*419*
420* Permission is hereby granted, free of charge, to any person obtaining420* Permission is hereby granted, free of charge, to any person obtaining
421* a copy of this software and associated documentation files (the421* a copy of this software and associated documentation files (the
src/luac.c+17−12
@@ -1,5 +1,5 @@
1/*1/*
2** $Id: luac.c,v 1.65 2010/10/26 09:07:52 lhf Exp $2** $Id: luac.c,v 1.66 2011/05/10 01:08:57 lhf Exp $
3** Lua compiler (saves bytecodes to files; also list bytecodes)3** Lua compiler (saves bytecodes to files; also list bytecodes)
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -143,9 +143,12 @@ static const Proto* combine(lua_State* L, int n) · 137 unmodified lines
143 int i=n;143 int i=n;
144 if (lua_load(L,reader,&i,"=(" PROGNAME ")")!=LUA_OK) fatal(lua_tostring(L,-1));144 if (lua_load(L,reader,&i,"=(" PROGNAME ")")!=LUA_OK) fatal(lua_tostring(L,-1));
145 f=toproto(L,-1);145 f=toproto(L,-1);
146 for (i=0; i<n; i++) f->p[i]=toproto(L,i-n-1);146 for (i=0; i<n; i++)
147 {
148 f->p[i]=toproto(L,i-n-1);
149 if (f->p[i]->sizeupvalues>0) f->p[i]->upvalues[0].instack=0;
150 }
147 f->sizelineinfo=0;151 f->sizelineinfo=0;
148 f->sizeupvalues=0;
149 return f;152 return f;
150 }153 }
151}154}
@@ -200,7 +203,7 @@ int main(int argc, char* argv[]) · 48 unmodified lines
200}203}
201 204
202/*205/*
203** $Id: print.c,v 1.66 2010/10/26 09:07:52 lhf Exp $206** $Id: print.c,v 1.67 2011/05/06 13:37:15 lhf Exp $
204** print bytecodes207** print bytecodes
205** See Copyright Notice in lua.h208** See Copyright Notice in lua.h
206*/209*/
@@ -270,6 +273,7 @@ static void PrintConstant(const Proto* f, int i) · 63 unmodified lines
270}273}
271 274
272#define UPVALNAME(x) ((f->upvalues[x].name) ? getstr(f->upvalues[x].name) : "-")275#define UPVALNAME(x) ((f->upvalues[x].name) ? getstr(f->upvalues[x].name) : "-")
276#define MYK(x) (-1-(x))
273 277
274static void PrintCode(const Proto* f)278static void PrintCode(const Proto* f)
275{279{
@@ -293,23 +297,25 @@ static void PrintCode(const Proto* f) · 17 unmodified lines
293 {297 {
294 case iABC:298 case iABC:
295 printf("%d",a);299 printf("%d",a);
296 if (getBMode(o)!=OpArgN) printf(" %d",ISK(b) ? (-1-INDEXK(b)) : b);300 if (getBMode(o)!=OpArgN) printf(" %d",ISK(b) ? (MYK(INDEXK(b))) : b);
297 if (getCMode(o)!=OpArgN) printf(" %d",ISK(c) ? (-1-INDEXK(c)) : c);301 if (getCMode(o)!=OpArgN) printf(" %d",ISK(c) ? (MYK(INDEXK(c))) : c);
298 break;302 break;
299 case iABx:303 case iABx:
300 if (getBMode(o)==OpArgK) printf("%d %d",a,-bx); else printf("%d %d",a,bx);304 printf("%d",a);
305 if (getBMode(o)==OpArgK) printf(" %d",MYK(bx));
306 if (getBMode(o)==OpArgU) printf(" %d",bx);
301 break;307 break;
302 case iAsBx:308 case iAsBx:
303 if (o==OP_JMP) printf("%d",sbx); else printf("%d %d",a,sbx);309 printf("%d %d",a,sbx);
304 break;310 break;
305 case iAx:311 case iAx:
306 printf("%d",-1-ax);312 printf("%d",MYK(ax));
307 break;313 break;
308 }314 }
309 switch (o)315 switch (o)
310 {316 {
311 case OP_LOADK:317 case OP_LOADK:
312 if (bx>0) { printf("\t; "); PrintConstant(f,bx-1); }318 printf("\t; "); PrintConstant(f,bx);
313 break;319 break;
314 case OP_GETUPVAL:320 case OP_GETUPVAL:
315 case OP_SETUPVAL:321 case OP_SETUPVAL:
@@ -355,8 +361,7 @@ static void PrintCode(const Proto* f) · 39 unmodified lines
355 printf("\t; %p",VOID(f->p[bx]));361 printf("\t; %p",VOID(f->p[bx]));
356 break;362 break;
357 case OP_SETLIST:363 case OP_SETLIST:
358 if (c==0) printf("\t; %d",(int)code[++pc]);364 if (c==0) printf("\t; %d",(int)code[++pc]); else printf("\t; %d",c);
359 else printf("\t; %d",c);
360 break;365 break;
361 case OP_EXTRAARG:366 case OP_EXTRAARG:
362 printf("\t; "); PrintConstant(f,ax);367 printf("\t; "); PrintConstant(f,ax);
src/luaconf.h+57−6
@@ -1,5 +1,5 @@
1/*1/*
2** $Id: luaconf.h,v 1.151 2010/11/12 15:48:30 roberto Exp $2** $Id: luaconf.h,v 1.159 2011/06/13 14:13:06 roberto Exp $
3** Configuration file for Lua3** Configuration file for Lua
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -35,6 +35,7 @@ · 29 unmodified lines
35 35
36#if defined(LUA_WIN)36#if defined(LUA_WIN)
37#define LUA_DL_DLL37#define LUA_DL_DLL
38#define LUA_USE_AFORMAT /* assume 'printf' handles 'aA' specifiers */
38#endif39#endif
39 40
40 41
@@ -43,12 +44,18 @@ · 2 unmodified lines
43#define LUA_USE_POSIX44#define LUA_USE_POSIX
44#define LUA_USE_DLOPEN /* needs an extra library: -ldl */45#define LUA_USE_DLOPEN /* needs an extra library: -ldl */
45#define LUA_USE_READLINE /* needs some extra libraries */46#define LUA_USE_READLINE /* needs some extra libraries */
47#define LUA_USE_STRTODHEX /* assume 'strtod' handles hexa formats */
48#define LUA_USE_AFORMAT /* assume 'printf' handles 'aA' specifiers */
49#define LUA_USE_LONGLONG /* assume support for long long */
46#endif50#endif
47 51
48#if defined(LUA_USE_MACOSX)52#if defined(LUA_USE_MACOSX)
49#define LUA_USE_POSIX53#define LUA_USE_POSIX
50#define LUA_USE_DLOPEN /* does not need -ldl */54#define LUA_USE_DLOPEN /* does not need -ldl */
51#define LUA_USE_READLINE /* needs an extra library: -lreadline */55#define LUA_USE_READLINE /* needs an extra library: -lreadline */
56#define LUA_USE_STRTODHEX /* assume 'strtod' handles hexa formats */
57#define LUA_USE_AFORMAT /* assume 'printf' handles 'aA' specifiers */
58#define LUA_USE_LONGLONG /* assume support for long long */
52#endif59#endif
53 60
54 61
@@ -202,10 +209,11 @@ · 147 unmodified lines
202 209
203 210
204/*211/*
205@@ luai_writestring defines how 'print' prints its results.212@@ luai_writestring/luai_writeline define how 'print' prints its results.
206*/213*/
207#include <stdio.h>214#include <stdio.h>
208#define luai_writestring(s,l) fwrite((s), sizeof(char), (l), stdout)215#define luai_writestring(s,l) fwrite((s), sizeof(char), (l), stdout)
216#define luai_writeline() (luai_writestring("\n", 1), fflush(stdout))
209 217
210/*218/*
211@@ luai_writestringerror defines how to print error messages.219@@ luai_writestringerror defines how to print error messages.
@@ -253,6 +261,12 @@ · 41 unmodified lines
253*/261*/
254#define LUA_COMPAT_LOG10262#define LUA_COMPAT_LOG10
255 263
264/*
265@@ LUA_COMPAT_LOADSTRING defines the function 'loadstring' in the base
266** library. You can rewrite 'loadstring(s)' as 'load(s)'.
267*/
268#define LUA_COMPAT_LOADSTRING
269
256/*270/*
257@@ LUA_COMPAT_MAXN defines the function 'maxn' in the table library.271@@ LUA_COMPAT_MAXN defines the function 'maxn' in the table library.
258*/272*/
@@ -371,14 +385,27 @@ · 112 unmodified lines
371@@ LUA_NUMBER_FMT is the format for writing numbers.385@@ LUA_NUMBER_FMT is the format for writing numbers.
372@@ lua_number2str converts a number to a string.386@@ lua_number2str converts a number to a string.
373@@ LUAI_MAXNUMBER2STR is maximum size of previous conversion.387@@ LUAI_MAXNUMBER2STR is maximum size of previous conversion.
374@@ lua_str2number converts a string to a number.
375*/388*/
376#define LUA_NUMBER_SCAN "%lf"389#define LUA_NUMBER_SCAN "%lf"
377#define LUA_NUMBER_FMT "%.14g"390#define LUA_NUMBER_FMT "%.14g"
378#define lua_number2str(s,n) sprintf((s), LUA_NUMBER_FMT, (n))391#define lua_number2str(s,n) sprintf((s), LUA_NUMBER_FMT, (n))
379#define LUAI_MAXNUMBER2STR 32 /* 16 digits, sign, point, and \0 */392#define LUAI_MAXNUMBER2STR 32 /* 16 digits, sign, point, and \0 */
393
394
395/*
396@@ lua_str2number converts a decimal numeric string to a number.
397@@ lua_strx2number converts an hexadecimal numeric string to a number.
398** In C99, 'strtod' do both conversions. C89, however, has no function
399** to convert floating hexadecimal strings to numbers. For these
400** systems, you can leave 'lua_strx2number' undefined and Lua will
401** provide its own implementation.
402*/
380#define lua_str2number(s,p) strtod((s), (p))403#define lua_str2number(s,p) strtod((s), (p))
381 404
405#if defined(LUA_USE_STRTODHEX)
406#define lua_strx2number(s,p) strtod((s), (p))
407#endif
408
382 409
383/*410/*
384@@ The luai_num* macros define the primitive operations over numbers.411@@ The luai_num* macros define the primitive operations over numbers.
@@ -438,11 +465,11 @@ · 53 unmodified lines
438 465
439/*466/*
440@@ LUA_IEEEENDIAN is the endianness of doubles in your machine467@@ LUA_IEEEENDIAN is the endianness of doubles in your machine
441@@ (0 for little endian, 1 for big endian); if not defined, Lua will468** (0 for little endian, 1 for big endian); if not defined, Lua will
442@@ check it dynamically.469** check it dynamically.
443*/470*/
444/* check for known architectures */471/* check for known architectures */
445#if defined(__i386__) || defined(__i386) || defined(i386) || \472#if defined(__i386__) || defined(__i386) || defined(__X86__) || \
446 defined (__x86_64)473 defined (__x86_64)
447#define LUA_IEEEENDIAN 0474#define LUA_IEEEENDIAN 0
448#elif defined(__POWERPC__) || defined(__ppc__)475#elif defined(__POWERPC__) || defined(__ppc__)
@@ -458,6 +485,30 @@ · 9 unmodified lines
458/* }================================================================== */485/* }================================================================== */
459 486
460 487
488/*
489@@ LUA_NANTRICKLE/LUA_NANTRICKBE controls the use of a trick to pack all
490** types into a single double value, using NaN values to represent
491** non-number values. The trick only works on 32-bit machines (ints and
492** pointers are 32-bit values) with numbers represented as IEEE 754-2008
493** doubles with conventional endianess (12345678 or 87654321), in CPUs
494** that do not produce signaling NaN values (all NaNs are quiet).
495*/
496#if defined(LUA_CORE) /* { */
497
498#if defined(LUA_NUMBER_DOUBLE) && !defined(LUA_ANSI) /* { */
499
500/* little-endian architectures that satisfy those conditions */
501#if defined(__i386__) || defined(__i386) || defined(__X86__)
502
503#define LUA_NANTRICKLE
504
505#endif
506
507#endif /* } */
508
509#endif /* } */
510
511
461 512
462 513
463/* =================================================================== */514/* =================================================================== */
src/lualib.h+2−2
@@ -1,5 +1,5 @@
1/*1/*
2** $Id: lualib.h,v 1.41 2010/10/25 14:32:36 roberto Exp $2** $Id: lualib.h,v 1.42 2011/05/25 14:12:28 roberto Exp $
3** Lua standard libraries3** Lua standard libraries
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -50,7 +50,7 @@ LUALIB_API void (luaL_openlibs) (lua_State *L); · 44 unmodified lines
50 50
51 51
52 52
53#ifndef lua_assert53#if !defined(lua_assert)
54#define lua_assert(x) ((void)0)54#define lua_assert(x) ((void)0)
55#endif55#endif
56 56
src/lundump.c+30−23
@@ -1,5 +1,5 @@
1/*1/*
2** $Id: lundump.c,v 1.68 2010/10/26 00:23:46 lhf Exp $2** $Id: lundump.c,v 1.69 2011/05/06 13:35:17 lhf Exp $
3** load precompiled Lua chunks3** load precompiled Lua chunks
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -38,6 +38,10 @@ static void error(LoadState* S, const char* why) · 32 unmodified lines
38#define LoadVar(S,x) LoadMem(S,&x,1,sizeof(x))38#define LoadVar(S,x) LoadMem(S,&x,1,sizeof(x))
39#define LoadVector(S,b,n,size) LoadMem(S,b,n,size)39#define LoadVector(S,b,n,size) LoadMem(S,b,n,size)
40 40
41#if !defined(luai_verifycode)
42#define luai_verifycode(L,b,f) (f)
43#endif
44
41static void LoadBlock(LoadState* S, void* b, size_t size)45static void LoadBlock(LoadState* S, void* b, size_t size)
42{46{
43 if (luaZ_read(S->Z,b,size)!=0) error(S,"corrupted");47 if (luaZ_read(S->Z,b,size)!=0) error(S,"corrupted");
@@ -54,6 +58,7 @@ static int LoadInt(LoadState* S) · 10 unmodified lines
54{58{
55 int x;59 int x;
56 LoadVar(S,x);60 LoadVar(S,x);
61 if (x<0) error(S,"corrupted");
57 return x;62 return x;
58}63}
59 64
@@ -73,7 +78,7 @@ static TString* LoadString(LoadState* S) · 13 unmodified lines
73 else78 else
74 {79 {
75 char* s=luaZ_openspace(S->L,S->b,size);80 char* s=luaZ_openspace(S->L,S->b,size);
76 LoadBlock(S,s,size);81 LoadBlock(S,s,size*sizeof(char));
77 return luaS_newlstr(S->L,s,size-1); /* remove trailing '\0' */82 return luaS_newlstr(S->L,s,size-1); /* remove trailing '\0' */
78 }83 }
79}84}
@@ -177,16 +182,17 @@ static Proto* LoadFunction(LoadState* S) · 97 unmodified lines
177 182
178/* the code below must be consistent with the code in luaU_header */183/* the code below must be consistent with the code in luaU_header */
179#define N0 LUAC_HEADERSIZE184#define N0 LUAC_HEADERSIZE
180#define N1 (sizeof(LUA_SIGNATURE)-1)185#define N1 (sizeof(LUA_SIGNATURE)-sizeof(char))
181#define N2 N1+2186#define N2 N1+2
182#define N3 N2+6187#define N3 N2+6
183 188
184static void LoadHeader(LoadState* S)189static void LoadHeader(LoadState* S)
185{190{
186 char h[LUAC_HEADERSIZE];191 lu_byte h[LUAC_HEADERSIZE];
187 char s[LUAC_HEADERSIZE];192 lu_byte s[LUAC_HEADERSIZE];
188 luaU_header(h);193 luaU_header(h);
189 LoadBlock(S,s,LUAC_HEADERSIZE);194 memcpy(s,h,sizeof(char)); /* first char already read */
195 LoadBlock(S,s+sizeof(char),LUAC_HEADERSIZE-sizeof(char));
190 if (memcmp(h,s,N0)==0) return;196 if (memcmp(h,s,N0)==0) return;
191 if (memcmp(h,s,N1)!=0) error(S,"not a");197 if (memcmp(h,s,N1)!=0) error(S,"not a");
192 if (memcmp(h,s,N2)!=0) error(S,"version mismatch in");198 if (memcmp(h,s,N2)!=0) error(S,"version mismatch in");
@@ -209,29 +215,30 @@ Proto* luaU_undump (lua_State* L, ZIO* Z, Mbuffer* buff, const char* name) · 16 unmodified lines
209 S.Z=Z;215 S.Z=Z;
210 S.b=buff;216 S.b=buff;
211 LoadHeader(&S);217 LoadHeader(&S);
212 return LoadFunction(&S);218 return luai_verifycode(L,buff,LoadFunction(&S));
213}219}
214 220
215/* data to catch conversion errors */221#define MYINT(s) (s[0]-'0')
216#define TAIL "\x19\x93\r\n\x1a\n"222#define VERSION MYINT(LUA_VERSION_MAJOR)*16+MYINT(LUA_VERSION_MINOR)
223#define FORMAT 0 /* this is the official format */
217 224
218/*225/*
219* make header for precompiled chunks226* make header for precompiled chunks
220* if you make any changes in the code below or in LUA_SIGNATURE in lua.h,227* if you change the code below be sure to update LoadHeader and FORMAT above
221* be sure to update LoadHeader above and LUAC_HEADERSIZE in lundump.h228* and LUAC_HEADERSIZE in lundump.h
222*/229*/
223void luaU_header (char* h)230void luaU_header (lu_byte* h)
224{231{
225 int x=1;232 int x=1;
226 memcpy(h,LUA_SIGNATURE,sizeof(LUA_SIGNATURE)-1);233 memcpy(h,LUA_SIGNATURE,sizeof(LUA_SIGNATURE)-sizeof(char));
227 h+=sizeof(LUA_SIGNATURE)-1;234 h+=sizeof(LUA_SIGNATURE)-sizeof(char);
228 *h++=(char)0x52; /* Lua 5.2 */235 *h++=cast_byte(VERSION);
229 *h++=(char)0; /* the official format */236 *h++=cast_byte(FORMAT);
230 *h++=(char)*(char*)&x; /* endianness */237 *h++=cast_byte(*(char*)&x); /* endianness */
231 *h++=(char)sizeof(int);238 *h++=cast_byte(sizeof(int));
232 *h++=(char)sizeof(size_t);239 *h++=cast_byte(sizeof(size_t));
233 *h++=(char)sizeof(Instruction);240 *h++=cast_byte(sizeof(Instruction));
234 *h++=(char)sizeof(lua_Number);241 *h++=cast_byte(sizeof(lua_Number));
235 *h++=(char)(((lua_Number)0.5)==0); /* is lua_Number integral? */242 *h++=cast_byte(((lua_Number)0.5)==0); /* is lua_Number integral? */
236 memcpy(h,TAIL,sizeof(TAIL)-1);243 memcpy(h,LUAC_TAIL,sizeof(LUAC_TAIL)-sizeof(char));
237}244}
src/lundump.h+7−4
@@ -1,5 +1,5 @@
1/*1/*
2** $Id: lundump.h,v 1.43 2010/10/26 00:23:46 lhf Exp $2** $Id: lundump.h,v 1.44 2011/05/06 13:35:17 lhf Exp $
3** load precompiled Lua chunks3** load precompiled Lua chunks
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -14,12 +14,15 @@ · 8 unmodified lines
14LUAI_FUNC Proto* luaU_undump (lua_State* L, ZIO* Z, Mbuffer* buff, const char* name);14LUAI_FUNC Proto* luaU_undump (lua_State* L, ZIO* Z, Mbuffer* buff, const char* name);
15 15
16/* make header; from lundump.c */16/* make header; from lundump.c */
17LUAI_FUNC void luaU_header (char* h);17LUAI_FUNC void luaU_header (lu_byte* h);
18 18
19/* dump one chunk; from ldump.c */19/* dump one chunk; from ldump.c */
20LUAI_FUNC int luaU_dump (lua_State* L, const Proto* f, lua_Writer w, void* data, int strip);20LUAI_FUNC int luaU_dump (lua_State* L, const Proto* f, lua_Writer w, void* data, int strip);
21 21
22/* size of header of binary files */22/* data to catch conversion errors */
23#define LUAC_HEADERSIZE 1823#define LUAC_TAIL "\x19\x93\r\n\x1a\n"
24
25/* size in bytes of header of binary files */
26#define LUAC_HEADERSIZE (sizeof(LUA_SIGNATURE)-sizeof(char)+2+6+sizeof(LUAC_TAIL)-sizeof(char))
24 27
25#endif28#endif
src/lvm.c+97−53
@@ -1,5 +1,5 @@
1/*1/*
2** $Id: lvm.c,v 2.125 2010/10/29 17:52:46 roberto Exp $2** $Id: lvm.c,v 2.141 2011/06/09 18:24:22 roberto Exp $
3** Lua virtual machine3** Lua virtual machine
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -35,7 +35,7 @@ · 29 unmodified lines
35const TValue *luaV_tonumber (const TValue *obj, TValue *n) {35const TValue *luaV_tonumber (const TValue *obj, TValue *n) {
36 lua_Number num;36 lua_Number num;
37 if (ttisnumber(obj)) return obj;37 if (ttisnumber(obj)) return obj;
38 if (ttisstring(obj) && luaO_str2d(svalue(obj), &num)) {38 if (ttisstring(obj) && luaO_str2d(svalue(obj), tsvalue(obj)->len, &num)) {
39 setnvalue(n, num);39 setnvalue(n, num);
40 return n;40 return n;
41 }41 }
@@ -65,7 +65,7 @@ static void traceexec (lua_State *L) { · 23 unmodified lines
65 luaD_hook(L, LUA_HOOKCOUNT, -1);65 luaD_hook(L, LUA_HOOKCOUNT, -1);
66 }66 }
67 if (mask & LUA_MASKLINE) {67 if (mask & LUA_MASKLINE) {
68 Proto *p = ci_func(ci)->l.p;68 Proto *p = ci_func(ci)->p;
69 int npc = pcRel(ci->u.l.savedpc, p);69 int npc = pcRel(ci->u.l.savedpc, p);
70 int newline = getfuncline(p, npc);70 int newline = getfuncline(p, npc);
71 if (npc == 0 || /* call linehook when enter a new function, */71 if (npc == 0 || /* call linehook when enter a new function, */
@@ -161,7 +161,6 @@ static int call_binTM (lua_State *L, const TValue *p1, const TValue *p2, · 89 unmodified lines
161 if (ttisnil(tm))161 if (ttisnil(tm))
162 tm = luaT_gettmbyobj(L, p2, event); /* try second operand */162 tm = luaT_gettmbyobj(L, p2, event); /* try second operand */
163 if (ttisnil(tm)) return 0;163 if (ttisnil(tm)) return 0;
164 if (event == TM_UNM) p2 = luaO_nilobject;
165 callTM(L, tm, p1, p2, res, 1);164 callTM(L, tm, p1, p2, res, 1);
166 return 1;165 return 1;
167}166}
@@ -175,7 +174,7 @@ static const TValue *get_equalTM (lua_State *L, Table *mt1, Table *mt2, · 7 unmodified lines
175 if (mt1 == mt2) return tm1; /* same metatables => same metamethods */174 if (mt1 == mt2) return tm1; /* same metatables => same metamethods */
176 tm2 = fasttm(L, mt2, event);175 tm2 = fasttm(L, mt2, event);
177 if (tm2 == NULL) return NULL; /* no metamethod */176 if (tm2 == NULL) return NULL; /* no metamethod */
178 if (luaO_rawequalObj(tm1, tm2)) /* same metamethods? */177 if (luaV_rawequalobj(tm1, tm2)) /* same metamethods? */
179 return tm1;178 return tm1;
180 return NULL;179 return NULL;
181}180}
@@ -238,9 +237,12 @@ int luaV_lessequal (lua_State *L, const TValue *l, const TValue *r) { · 56 unmodified lines
238}237}
239 238
240 239
241int luaV_equalval_ (lua_State *L, const TValue *t1, const TValue *t2) {240/*
241** equality of Lua values. L == NULL means raw equality (no metamethods)
242*/
243int luaV_equalobj_ (lua_State *L, const TValue *t1, const TValue *t2) {
242 const TValue *tm;244 const TValue *tm;
243 lua_assert(ttype(t1) == ttype(t2));245 lua_assert(ttisequal(t1, t2));
244 switch (ttype(t1)) {246 switch (ttype(t1)) {
245 case LUA_TNIL: return 1;247 case LUA_TNIL: return 1;
246 case LUA_TNUMBER: return luai_numeq(nvalue(t1), nvalue(t2));248 case LUA_TNUMBER: return luai_numeq(nvalue(t1), nvalue(t2));
@@ -250,15 +252,19 @@ int luaV_equalval_ (lua_State *L, const TValue *t1, const TValue *t2) { · 3 unmodified lines
250 case LUA_TSTRING: return eqstr(rawtsvalue(t1), rawtsvalue(t2));252 case LUA_TSTRING: return eqstr(rawtsvalue(t1), rawtsvalue(t2));
251 case LUA_TUSERDATA: {253 case LUA_TUSERDATA: {
252 if (uvalue(t1) == uvalue(t2)) return 1;254 if (uvalue(t1) == uvalue(t2)) return 1;
255 else if (L == NULL) return 0;
253 tm = get_equalTM(L, uvalue(t1)->metatable, uvalue(t2)->metatable, TM_EQ);256 tm = get_equalTM(L, uvalue(t1)->metatable, uvalue(t2)->metatable, TM_EQ);
254 break; /* will try TM */257 break; /* will try TM */
255 }258 }
256 case LUA_TTABLE: {259 case LUA_TTABLE: {
257 if (hvalue(t1) == hvalue(t2)) return 1;260 if (hvalue(t1) == hvalue(t2)) return 1;
261 else if (L == NULL) return 0;
258 tm = get_equalTM(L, hvalue(t1)->metatable, hvalue(t2)->metatable, TM_EQ);262 tm = get_equalTM(L, hvalue(t1)->metatable, hvalue(t2)->metatable, TM_EQ);
259 break; /* will try TM */263 break; /* will try TM */
260 }264 }
261 default: return gcvalue(t1) == gcvalue(t2);265 default:
266 lua_assert(iscollectable(t1));
267 return gcvalue(t1) == gcvalue(t2);
262 }268 }
263 if (tm == NULL) return 0; /* no TM? */269 if (tm == NULL) return 0; /* no TM? */
264 callTM(L, tm, t1, t2, L->top, 1); /* call TM */270 callTM(L, tm, t1, t2, L->top, 1); /* call TM */
@@ -286,18 +292,20 @@ void luaV_concat (lua_State *L, int total) { · 21 unmodified lines
286 char *buffer;292 char *buffer;
287 int i;293 int i;
288 /* collect total length */294 /* collect total length */
289 for (n = 1; n < total && tostring(L, top-n-1); n++) {295 for (i = 1; i < total && tostring(L, top-i-1); i++) {
290 size_t l = tsvalue(top-n-1)->len;296 size_t l = tsvalue(top-i-1)->len;
291 if (l >= MAX_SIZET - tl) luaG_runerror(L, "string length overflow");297 if (l >= (MAX_SIZET/sizeof(char)) - tl)
298 luaG_runerror(L, "string length overflow");
292 tl += l;299 tl += l;
293 }300 }
294 buffer = luaZ_openspace(L, &G(L)->buff, tl);301 buffer = luaZ_openspace(L, &G(L)->buff, tl);
295 tl = 0;302 tl = 0;
296 for (i=n; i>0; i--) { /* concat all strings */303 n = i;
304 do { /* concat all strings */
297 size_t l = tsvalue(top-i)->len;305 size_t l = tsvalue(top-i)->len;
298 memcpy(buffer+tl, svalue(top-i), l);306 memcpy(buffer+tl, svalue(top-i), l * sizeof(char));
299 tl += l;307 tl += l;
300 }308 } while (--i > 0);
301 setsvalue2s(L, top-n, luaS_newlstr(L, buffer, tl));309 setsvalue2s(L, top-n, luaS_newlstr(L, buffer, tl));
302 }310 }
303 total -= n-1; /* got 'n' strings to create 1 new */311 total -= n-1; /* got 'n' strings to create 1 new */
@@ -308,7 +316,7 @@ void luaV_concat (lua_State *L, int total) { · 4 unmodified lines
308 316
309void luaV_objlen (lua_State *L, StkId ra, const TValue *rb) {317void luaV_objlen (lua_State *L, StkId ra, const TValue *rb) {
310 const TValue *tm;318 const TValue *tm;
311 switch (ttype(rb)) {319 switch (ttypenv(rb)) {
312 case LUA_TTABLE: {320 case LUA_TTABLE: {
313 Table *h = hvalue(rb);321 Table *h = hvalue(rb);
314 tm = fasttm(L, h->metatable, TM_LEN);322 tm = fasttm(L, h->metatable, TM_LEN);
@@ -327,7 +335,7 @@ void luaV_objlen (lua_State *L, StkId ra, const TValue *rb) { · 12 unmodified lines
327 break;335 break;
328 }336 }
329 }337 }
330 callTM(L, tm, rb, luaO_nilobject, ra, 1);338 callTM(L, tm, rb, rb, ra, 1);
331}339}
332 340
333 341
@@ -378,7 +386,7 @@ static void pushclosure (lua_State *L, Proto *p, UpVal **encup, StkId base, · 44 unmodified lines
378 Upvaldesc *uv = p->upvalues;386 Upvaldesc *uv = p->upvalues;
379 int i;387 int i;
380 Closure *ncl = luaF_newLclosure(L, p);388 Closure *ncl = luaF_newLclosure(L, p);
381 setclvalue(L, ra, ncl); /* anchor new closure in stack */389 setclLvalue(L, ra, ncl); /* anchor new closure in stack */
382 for (i = 0; i < nup; i++) { /* fill in its upvalues */390 for (i = 0; i < nup; i++) { /* fill in its upvalues */
383 if (uv[i].instack) /* upvalue refers to local variable? */391 if (uv[i].instack) /* upvalue refers to local variable? */
384 ncl->l.upvals[i] = luaF_findupval(L, base + uv[i].idx);392 ncl->l.upvals[i] = luaF_findupval(L, base + uv[i].idx);
@@ -454,6 +462,11 @@ void luaV_finishOp (lua_State *L) { · 69 unmodified lines
454** some macros for common tasks in `luaV_execute'462** some macros for common tasks in `luaV_execute'
455*/463*/
456 464
465#if !defined luai_runtimecheck
466#define luai_runtimecheck(L, c) /* void */
467#endif
468
469
457#define RA(i) (base+GETARG_A(i))470#define RA(i) (base+GETARG_A(i))
458/* to be used after possible stack reallocation */471/* to be used after possible stack reallocation */
459#define RB(i) check_exp(getBMode(GET_OPCODE(i)) == OpArgR, base+GETARG_B(i))472#define RB(i) check_exp(getBMode(GET_OPCODE(i)) == OpArgR, base+GETARG_B(i))
@@ -466,12 +479,19 @@ void luaV_finishOp (lua_State *L) { · 6 unmodified lines
466 (k + (GETARG_Bx(i) != 0 ? GETARG_Bx(i) - 1 : GETARG_Ax(*ci->u.l.savedpc++)))479 (k + (GETARG_Bx(i) != 0 ? GETARG_Bx(i) - 1 : GETARG_Ax(*ci->u.l.savedpc++)))
467 480
468 481
469#define dojump(i) (ci->u.l.savedpc += (i))482/* execute a jump instruction */
483#define dojump(ci,i,e) \
484 { int a = GETARG_A(i); \
485 if (a > 0) luaF_close(L, ci->u.l.base + a - 1); \
486 ci->u.l.savedpc += GETARG_sBx(i) + e; }
487
488/* for test instructions, execute the jump instruction that follows it */
489#define donextjump(ci) { i = *ci->u.l.savedpc; dojump(ci, i, 1); }
470 490
471 491
472#define Protect(x) { {x;}; base = ci->u.l.base; }492#define Protect(x) { {x;}; base = ci->u.l.base; }
473 493
474#define checkGC(L) Protect(luaC_checkGC(L); luai_threadyield(L);)494#define checkGC(L,c) Protect(luaC_condGC(L, c); luai_threadyield(L);)
475 495
476 496
477#define arith_op(op,tm) { \497#define arith_op(op,tm) { \
@@ -493,9 +513,8 @@ void luaV_execute (lua_State *L) { · 15 unmodified lines
493 TValue *k;513 TValue *k;
494 StkId base;514 StkId base;
495 newframe: /* reentry point when frame changes (call/return) */515 newframe: /* reentry point when frame changes (call/return) */
496 lua_assert(isLua(ci));
497 lua_assert(ci == L->ci);516 lua_assert(ci == L->ci);
498 cl = &clvalue(ci->func)->l;517 cl = clLvalue(ci->func);
499 k = cl->p->k;518 k = cl->p->k;
500 base = ci->u.l.base;519 base = ci->u.l.base;
501 /* main loop of interpreter */520 /* main loop of interpreter */
@@ -515,7 +534,13 @@ void luaV_execute (lua_State *L) { · 13 unmodified lines
515 setobjs2s(L, ra, RB(i));534 setobjs2s(L, ra, RB(i));
516 )535 )
517 vmcase(OP_LOADK,536 vmcase(OP_LOADK,
518 TValue *rb = KBx(i);537 TValue *rb = k + GETARG_Bx(i);
538 setobj2s(L, ra, rb);
539 )
540 vmcase(OP_LOADKX,
541 TValue *rb;
542 lua_assert(GET_OPCODE(*ci->u.l.savedpc) == OP_EXTRAARG);
543 rb = k + GETARG_Ax(*ci->u.l.savedpc++);
519 setobj2s(L, ra, rb);544 setobj2s(L, ra, rb);
520 )545 )
521 vmcase(OP_LOADBOOL,546 vmcase(OP_LOADBOOL,
@@ -523,10 +548,10 @@ void luaV_execute (lua_State *L) { · 1 unmodified line
523 if (GETARG_C(i)) ci->u.l.savedpc++; /* skip next instruction (if C) */548 if (GETARG_C(i)) ci->u.l.savedpc++; /* skip next instruction (if C) */
524 )549 )
525 vmcase(OP_LOADNIL,550 vmcase(OP_LOADNIL,
526 TValue *rb = RB(i);551 int b = GETARG_B(i);
527 do {552 do {
528 setnilvalue(rb--);553 setnilvalue(ra++);
529 } while (rb >= ra);554 } while (b--);
530 )555 )
531 vmcase(OP_GETUPVAL,556 vmcase(OP_GETUPVAL,
532 int b = GETARG_B(i);557 int b = GETARG_B(i);
@@ -558,7 +583,11 @@ void luaV_execute (lua_State *L) { · 25 unmodified lines
558 sethvalue(L, ra, t);583 sethvalue(L, ra, t);
559 if (b != 0 || c != 0)584 if (b != 0 || c != 0)
560 luaH_resize(L, t, luaO_fb2int(b), luaO_fb2int(c));585 luaH_resize(L, t, luaO_fb2int(b), luaO_fb2int(c));
561 checkGC(L);586 checkGC(L,
587 L->top = ra + 1; /* limit of live values */
588 luaC_step(L);
589 L->top = ci->top; /* restore top */
590 )
562 )591 )
563 vmcase(OP_SELF,592 vmcase(OP_SELF,
564 StkId rb = RB(i);593 StkId rb = RB(i);
@@ -594,7 +623,8 @@ void luaV_execute (lua_State *L) { · 29 unmodified lines
594 }623 }
595 )624 )
596 vmcase(OP_NOT,625 vmcase(OP_NOT,
597 int res = l_isfalse(RB(i)); /* next assignment may change this value */626 TValue *rb = RB(i);
627 int res = l_isfalse(rb); /* next assignment may change this value */
598 setbvalue(ra, res);628 setbvalue(ra, res);
599 )629 )
600 vmcase(OP_LEN,630 vmcase(OP_LEN,
@@ -603,49 +633,61 @@ void luaV_execute (lua_State *L) { · 2 unmodified lines
603 vmcase(OP_CONCAT,633 vmcase(OP_CONCAT,
604 int b = GETARG_B(i);634 int b = GETARG_B(i);
605 int c = GETARG_C(i);635 int c = GETARG_C(i);
636 StkId rb;
606 L->top = base + c + 1; /* mark the end of concat operands */637 L->top = base + c + 1; /* mark the end of concat operands */
607 Protect(luaV_concat(L, c-b+1); checkGC(L);)638 Protect(luaV_concat(L, c - b + 1));
639 ra = RA(i); /* 'luav_concat' may invoke TMs and move the stack */
640 rb = b + base;
641 setobjs2s(L, ra, rb);
642 checkGC(L,
643 L->top = (ra >= rb ? ra + 1 : rb); /* limit of live values */
644 luaC_step(L);
645 )
608 L->top = ci->top; /* restore top */646 L->top = ci->top; /* restore top */
609 setobjs2s(L, RA(i), base+b);
610 )647 )
611 vmcase(OP_JMP,648 vmcase(OP_JMP,
612 dojump(GETARG_sBx(i));649 dojump(ci, i, 0);
613 )650 )
614 vmcase(OP_EQ,651 vmcase(OP_EQ,
615 TValue *rb = RKB(i);652 TValue *rb = RKB(i);
616 TValue *rc = RKC(i);653 TValue *rc = RKC(i);
617 Protect(654 Protect(
618 if (equalobj(L, rb, rc) == GETARG_A(i))655 if (equalobj(L, rb, rc) != GETARG_A(i))
619 dojump(GETARG_sBx(*ci->u.l.savedpc));656 ci->u.l.savedpc++;
657 else
658 donextjump(ci);
620 )659 )
621 ci->u.l.savedpc++;
622 )660 )
623 vmcase(OP_LT,661 vmcase(OP_LT,
624 Protect(662 Protect(
625 if (luaV_lessthan(L, RKB(i), RKC(i)) == GETARG_A(i))663 if (luaV_lessthan(L, RKB(i), RKC(i)) != GETARG_A(i))
626 dojump(GETARG_sBx(*ci->u.l.savedpc));664 ci->u.l.savedpc++;
665 else
666 donextjump(ci);
627 )667 )
628 ci->u.l.savedpc++;
629 )668 )
630 vmcase(OP_LE,669 vmcase(OP_LE,
631 Protect(670 Protect(
632 if (luaV_lessequal(L, RKB(i), RKC(i)) == GETARG_A(i))671 if (luaV_lessequal(L, RKB(i), RKC(i)) != GETARG_A(i))
633 dojump(GETARG_sBx(*ci->u.l.savedpc));672 ci->u.l.savedpc++;
673 else
674 donextjump(ci);
634 )675 )
635 ci->u.l.savedpc++;
636 )676 )
637 vmcase(OP_TEST,677 vmcase(OP_TEST,
638 if (GETARG_C(i) ? !l_isfalse(ra) : l_isfalse(ra))678 if (GETARG_C(i) ? l_isfalse(ra) : !l_isfalse(ra))
639 dojump(GETARG_sBx(*ci->u.l.savedpc));679 ci->u.l.savedpc++;
640 ci->u.l.savedpc++;680 else
681 donextjump(ci);
641 )682 )
642 vmcase(OP_TESTSET,683 vmcase(OP_TESTSET,
643 TValue *rb = RB(i);684 TValue *rb = RB(i);
644 if (GETARG_C(i) ? !l_isfalse(rb) : l_isfalse(rb)) {685 if (GETARG_C(i) ? l_isfalse(rb) : !l_isfalse(rb))
686 ci->u.l.savedpc++;
687 else {
645 setobjs2s(L, ra, rb);688 setobjs2s(L, ra, rb);
646 dojump(GETARG_sBx(*ci->u.l.savedpc));689 donextjump(ci);
647 }690 }
648 ci->u.l.savedpc++;
649 )691 )
650 vmcase(OP_CALL,692 vmcase(OP_CALL,
651 int b = GETARG_B(i);693 int b = GETARG_B(i);
@@ -711,7 +753,7 @@ void luaV_execute (lua_State *L) { · 59 unmodified lines
711 lua_Number limit = nvalue(ra+1);753 lua_Number limit = nvalue(ra+1);
712 if (luai_numlt(L, 0, step) ? luai_numle(L, idx, limit)754 if (luai_numlt(L, 0, step) ? luai_numle(L, idx, limit)
713 : luai_numle(L, limit, idx)) {755 : luai_numle(L, limit, idx)) {
714 dojump(GETARG_sBx(i)); /* jump back */756 ci->u.l.savedpc += GETARG_sBx(i); /* jump back */
715 setnvalue(ra, idx); /* update internal index... */757 setnvalue(ra, idx); /* update internal index... */
716 setnvalue(ra+3, idx); /* ...and external index */758 setnvalue(ra+3, idx); /* ...and external index */
717 }759 }
@@ -727,7 +769,7 @@ void luaV_execute (lua_State *L) { · 9 unmodified lines
727 else if (!tonumber(pstep, ra+2))769 else if (!tonumber(pstep, ra+2))
728 luaG_runerror(L, LUA_QL("for") " step must be a number");770 luaG_runerror(L, LUA_QL("for") " step must be a number");
729 setnvalue(ra, luai_numsub(L, nvalue(ra), nvalue(pstep)));771 setnvalue(ra, luai_numsub(L, nvalue(ra), nvalue(pstep)));
730 dojump(GETARG_sBx(i));772 ci->u.l.savedpc += GETARG_sBx(i);
731 )773 )
732 vmcase(OP_TFORCALL,774 vmcase(OP_TFORCALL,
733 StkId cb = ra + 3; /* call base */775 StkId cb = ra + 3; /* call base */
@@ -746,7 +788,7 @@ void luaV_execute (lua_State *L) { · 12 unmodified lines
746 l_tforloop:788 l_tforloop:
747 if (!ttisnil(ra + 1)) { /* continue loop? */789 if (!ttisnil(ra + 1)) { /* continue loop? */
748 setobjs2s(L, ra, ra + 1); /* save control variable */790 setobjs2s(L, ra, ra + 1); /* save control variable */
749 dojump(GETARG_sBx(i)); /* jump back */791 ci->u.l.savedpc += GETARG_sBx(i); /* jump back */
750 }792 }
751 )793 )
752 vmcase(OP_SETLIST,794 vmcase(OP_SETLIST,
@@ -759,6 +801,7 @@ void luaV_execute (lua_State *L) { · 6 unmodified lines
759 lua_assert(GET_OPCODE(*ci->u.l.savedpc) == OP_EXTRAARG);801 lua_assert(GET_OPCODE(*ci->u.l.savedpc) == OP_EXTRAARG);
760 c = GETARG_Ax(*ci->u.l.savedpc++);802 c = GETARG_Ax(*ci->u.l.savedpc++);
761 }803 }
804 luai_runtimecheck(L, ttistable(ra));
762 h = hvalue(ra);805 h = hvalue(ra);
763 last = ((c-1)*LFIELDS_PER_FLUSH) + n;806 last = ((c-1)*LFIELDS_PER_FLUSH) + n;
764 if (last > h->sizearray) /* needs more space? */807 if (last > h->sizearray) /* needs more space? */
@@ -770,17 +813,18 @@ void luaV_execute (lua_State *L) { · 5 unmodified lines
770 }813 }
771 L->top = ci->top; /* correct top (in case of previous open call) */814 L->top = ci->top; /* correct top (in case of previous open call) */
772 )815 )
773 vmcase(OP_CLOSE,
774 luaF_close(L, ra);
775 )
776 vmcase(OP_CLOSURE,816 vmcase(OP_CLOSURE,
777 Proto *p = cl->p->p[GETARG_Bx(i)];817 Proto *p = cl->p->p[GETARG_Bx(i)];
778 Closure *ncl = getcached(p, cl->upvals, base); /* cached closure */818 Closure *ncl = getcached(p, cl->upvals, base); /* cached closure */
779 if (ncl == NULL) /* no match? */819 if (ncl == NULL) /* no match? */
780 pushclosure(L, p, cl->upvals, base, ra); /* create a new one */820 pushclosure(L, p, cl->upvals, base, ra); /* create a new one */
781 else821 else
782 setclvalue(L, ra, ncl); /* push cashed closure */822 setclLvalue(L, ra, ncl); /* push cashed closure */
783 checkGC(L);823 checkGC(L,
824 L->top = ra + 1; /* limit of live values */
825 luaC_step(L);
826 L->top = ci->top; /* restore top */
827 )
784 )828 )
785 vmcase(OP_VARARG,829 vmcase(OP_VARARG,
786 int b = GETARG_B(i) - 1;830 int b = GETARG_B(i) - 1;
src/lvm.h+7−4
@@ -1,5 +1,5 @@
1/*1/*
2** $Id: lvm.h,v 2.14 2009/12/17 16:20:01 roberto Exp $2** $Id: lvm.h,v 2.17 2011/05/31 18:27:56 roberto Exp $
3** Lua virtual machine3** Lua virtual machine
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -17,12 +17,15 @@ · 11 unmodified lines
17 17
18#define tonumber(o,n) (ttisnumber(o) || (((o) = luaV_tonumber(o,n)) != NULL))18#define tonumber(o,n) (ttisnumber(o) || (((o) = luaV_tonumber(o,n)) != NULL))
19 19
20#define equalobj(L,o1,o2) \20#define equalobj(L,o1,o2) (ttisequal(o1, o2) && luaV_equalobj_(L, o1, o2))
21 (ttype(o1) == ttype(o2) && luaV_equalval_(L, o1, o2))21
22#define luaV_rawequalobj(t1,t2) \
23 (ttisequal(t1,t2) && luaV_equalobj_(NULL,t1,t2))
22 24
23 25
24/* not to called directly */26/* not to called directly */
25LUAI_FUNC int luaV_equalval_ (lua_State *L, const TValue *t1, const TValue *t2);27LUAI_FUNC int luaV_equalobj_ (lua_State *L, const TValue *t1, const TValue *t2);
28
26 29
27LUAI_FUNC int luaV_lessthan (lua_State *L, const TValue *l, const TValue *r);30LUAI_FUNC int luaV_lessthan (lua_State *L, const TValue *l, const TValue *r);
28LUAI_FUNC int luaV_lessequal (lua_State *L, const TValue *l, const TValue *r);31LUAI_FUNC int luaV_lessequal (lua_State *L, const TValue *l, const TValue *r);
src/lzio.c+12−18
@@ -1,5 +1,5 @@
1/*1/*
2** $Id: lzio.c,v 1.31 2005/06/03 20:15:29 roberto Exp $2** $Id: lzio.c,v 1.33 2011/02/23 13:13:10 roberto Exp $
3** a generic input stream interface3** a generic input stream interface
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -25,26 +25,14 @@ int luaZ_fill (ZIO *z) { · 19 unmodified lines
25 lua_unlock(L);25 lua_unlock(L);
26 buff = z->reader(L, z->data, &size);26 buff = z->reader(L, z->data, &size);
27 lua_lock(L);27 lua_lock(L);
28 if (buff == NULL || size == 0) return EOZ;28 if (buff == NULL || size == 0)
29 z->n = size - 1;29 return EOZ;
30 z->n = size - 1; /* discount char being returned */
30 z->p = buff;31 z->p = buff;
31 return char2int(*(z->p++));32 return char2int(*(z->p++));
32}33}
33 34
34 35
35int luaZ_lookahead (ZIO *z) {
36 if (z->n == 0) {
37 if (luaZ_fill(z) == EOZ)
38 return EOZ;
39 else {
40 z->n++; /* luaZ_fill removed first byte; put back it */
41 z->p--;
42 }
43 }
44 return char2int(*z->p);
45}
46
47
48void luaZ_init (lua_State *L, ZIO *z, lua_Reader reader, void *data) {36void luaZ_init (lua_State *L, ZIO *z, lua_Reader reader, void *data) {
49 z->L = L;37 z->L = L;
50 z->reader = reader;38 z->reader = reader;
@@ -58,8 +46,14 @@ void luaZ_init (lua_State *L, ZIO *z, lua_Reader reader, void *data) { · 7 unmodified lines
58size_t luaZ_read (ZIO *z, void *b, size_t n) {46size_t luaZ_read (ZIO *z, void *b, size_t n) {
59 while (n) {47 while (n) {
60 size_t m;48 size_t m;
61 if (luaZ_lookahead(z) == EOZ)49 if (z->n == 0) { /* no bytes in buffer? */
62 return n; /* return number of missing bytes */50 if (luaZ_fill(z) == EOZ) /* try to read more */
51 return n; /* no more input; return number of missing bytes */
52 else {
53 z->n++; /* luaZ_fill consumed first byte; put it back */
54 z->p--;
55 }
56 }
63 m = (n <= z->n) ? n : z->n; /* min. between n and z->n */57 m = (n <= z->n) ? n : z->n; /* min. between n and z->n */
64 memcpy(b, z->p, m);58 memcpy(b, z->p, m);
65 z->n -= m;59 z->n -= m;
src/lzio.h+2−3
@@ -1,5 +1,5 @@
1/*1/*
2** $Id: lzio.h,v 1.22 2009/05/18 17:26:25 roberto Exp $2** $Id: lzio.h,v 1.24 2011/02/23 13:13:10 roberto Exp $
3** Buffered streams3** Buffered streams
4** See Copyright Notice in lua.h4** See Copyright Notice in lua.h
5*/5*/
@@ -50,7 +50,6 @@ LUAI_FUNC char *luaZ_openspace (lua_State *L, Mbuffer *buff, size_t n); · 44 unmodified lines
50LUAI_FUNC void luaZ_init (lua_State *L, ZIO *z, lua_Reader reader,50LUAI_FUNC void luaZ_init (lua_State *L, ZIO *z, lua_Reader reader,
51 void *data);51 void *data);
52LUAI_FUNC size_t luaZ_read (ZIO* z, void* b, size_t n); /* read next n bytes */52LUAI_FUNC size_t luaZ_read (ZIO* z, void* b, size_t n); /* read next n bytes */
53LUAI_FUNC int luaZ_lookahead (ZIO *z);
54 53
55 54
56 55
@@ -59,7 +58,7 @@ LUAI_FUNC int luaZ_lookahead (ZIO *z); · 2 unmodified lines
59struct Zio {58struct Zio {
60 size_t n; /* bytes still unread */59 size_t n; /* bytes still unread */
61 const char *p; /* current position in buffer */60 const char *p; /* current position in buffer */
62 lua_Reader reader;61 lua_Reader reader; /* reader function */
63 void* data; /* additional data */62 void* data; /* additional data */
64 lua_State *L; /* Lua state (for reader) */63 lua_State *L; /* Lua state (for reader) */
65};64};

Keyboard shortcuts

General

Show keyboard shortcuts
?
Focus the current search
/

Issues and pull requests

Open filters
f

Issues, pull requests and Inbox

Select next item
j↓
Select previous item
k↑
Open selected item
Enter
Dismiss filters or clear selection
Esc

Repository code

Go to file
t