History

Lua 5.3.0-work2

Lua Team committed 12 years ago

Commit ad386d91 parent b83a40a60 files · +3280 −2672Browse files

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

Unified · Split

53 files
  1. src/.fix +1 −1
  2. src/Makefile +5 −4
  3. src/lapi.c +66 −70
  4. src/lauxlib.c +71 −59
  5. src/lauxlib.h +15 −15
  6. src/lbaselib.c +7 −9
  7. src/lbitlib.c +37 −22
  8. src/lcode.c +65 −36
  9. src/lcode.h +7 −3
  10. src/ldblib.c +3 −7
  11. src/ldebug.c +20 −13
  12. src/ldebug.h +2 −2
  13. src/ldo.c +23 −20
  14. src/ldump.c +154 −133
  15. src/lfunc.c +39 −54
  16. src/lfunc.h +24 −3
  17. src/lgc.c +287 −336
  18. src/lgc.h +30 −49
  19. src/linit.c +2 −1
  20. src/liolib.c +61 −58
  21. src/llex.c +80 −42
  22. src/llex.h +3 −1
  23. src/llimits.h +7 −4
  24. src/lmathlib.c +11 −4
  25. src/loadlib.c +15 −19
  26. src/lobject.c +88 −38
  27. src/lobject.h +25 −20
  28. src/lopcodes.c +17 −5
  29. src/lopcodes.h +9 −3
  30. src/loslib.c +42 −18
  31. src/lparser.c +37 −37
  32. src/lparser.h +1 −2
  33. src/lstate.c +53 −32
  34. src/lstate.h +19 −30
  35. src/lstring.c +46 −55
  36. src/lstring.h +3 −5
  37. src/lstrlib.c +222 −5
  38. src/ltable.c +47 −27
  39. src/ltable.h +6 −1
  40. src/ltablib.c +2 −2
  41. src/ltm.c +18 −11
  42. src/ltm.h +10 −4
  43. src/lua.c +69 −31
  44. src/lua.h +25 −21
  45. src/luac.c +1 −1
  46. src/luaconf.h +76 −44
  47. src/lualib.h +4 −1
  48. src/lundump.c +207 −209
  49. src/lundump.h +16 −11
  50. src/lutf8lib.c +240 −0
  51. src/lvm.c +125 −56
  52. src/lvm.h +3 −2
  53. src/lzio.h +2 −1
src/.fix+1−1
@@ -1,2 +1,2 @@
1−#define nvalue(x) 0
1+#define nvalue(x) ((lua_Number)0)
22 #define ttypenv(x) ttnov(x)
src/Makefile+5−4
@@ -33,7 +33,7 @@ CORE_O= lapi.o lcode.o lctype.o ldebug.o ldo.o ldump.o lfunc.o lgc.o llex.o \ · 32 unmodified lines
3333 lmem.o lobject.o lopcodes.o lparser.o lstate.o lstring.o ltable.o \
3434 ltm.o lundump.o lvm.o lzio.o
3535 LIB_O= lauxlib.o lbaselib.o lbitlib.o lcorolib.o ldblib.o liolib.o \
36− lmathlib.o loslib.o lstrlib.o ltablib.o loadlib.o linit.o
36+ lmathlib.o loslib.o lstrlib.o ltablib.o lutf8lib.o loadlib.o linit.o
3737 BASE_O= $(CORE_O) $(LIB_O) $(MYOBJS)
3838
3939 LUA_T= lua
@@ -152,7 +152,7 @@ lgc.o: lgc.c lua.h luaconf.h ldebug.h lstate.h lobject.h llimits.h ltm.h \ · 112 unmodified lines
152152 linit.o: linit.c lua.h luaconf.h lualib.h lauxlib.h
153153 liolib.o: liolib.c lua.h luaconf.h lauxlib.h lualib.h
154154 llex.o: llex.c lua.h luaconf.h lctype.h llimits.h ldo.h lobject.h \
155− lstate.h ltm.h lzio.h lmem.h llex.h lparser.h lstring.h lgc.h ltable.h
155+ lstate.h ltm.h lzio.h lmem.h lgc.h llex.h lparser.h lstring.h ltable.h
156156 lmathlib.o: lmathlib.c lua.h luaconf.h lauxlib.h lualib.h
157157 lmem.o: lmem.c lua.h luaconf.h ldebug.h lstate.h lobject.h llimits.h \
158158 ltm.h lzio.h lmem.h ldo.h lgc.h
@@ -167,8 +167,8 @@ lparser.o: lparser.c lua.h luaconf.h lcode.h llex.h lobject.h llimits.h \ · 8 unmodified lines
167167 lstate.o: lstate.c lua.h luaconf.h lapi.h llimits.h lstate.h lobject.h \
168168 ltm.h lzio.h lmem.h ldebug.h ldo.h lfunc.h lgc.h llex.h lstring.h \
169169 ltable.h
170−lstring.o: lstring.c lua.h luaconf.h lmem.h llimits.h lobject.h lstate.h \
171− ltm.h lzio.h lstring.h lgc.h
170+lstring.o: lstring.c lua.h luaconf.h ldebug.h lstate.h lobject.h \
171+ llimits.h ltm.h lzio.h lmem.h ldo.h lstring.h lgc.h
172172 lstrlib.o: lstrlib.c lua.h luaconf.h lauxlib.h lualib.h
173173 ltable.o: ltable.c lua.h luaconf.h ldebug.h lstate.h lobject.h llimits.h \
174174 ltm.h lzio.h lmem.h ldo.h lgc.h lstring.h ltable.h lvm.h
@@ -180,6 +180,7 @@ luac.o: luac.c lua.h luaconf.h lauxlib.h lobject.h llimits.h lstate.h \ · 5 unmodified lines
180180 ltm.h lzio.h lmem.h lundump.h ldebug.h lopcodes.h
181181 lundump.o: lundump.c lua.h luaconf.h ldebug.h lstate.h lobject.h \
182182 llimits.h ltm.h lzio.h lmem.h ldo.h lfunc.h lstring.h lgc.h lundump.h
183+lutf8lib.o: lutf8lib.c lua.h luaconf.h lauxlib.h lualib.h
183184 lvm.o: lvm.c lua.h luaconf.h ldebug.h lstate.h lobject.h llimits.h ltm.h \
184185 lzio.h lmem.h ldo.h lfunc.h lgc.h lopcodes.h lstring.h ltable.h lvm.h
185186 lzio.o: lzio.c lua.h luaconf.h llimits.h lmem.h lstate.h lobject.h ltm.h \
src/lapi.c+66−70
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lapi.c,v 2.185 2013/07/05 14:29:51 roberto Exp $
2+** $Id: lapi.c,v 2.201 2014/03/12 20:57:40 roberto Exp $
33 ** Lua API
44 ** See Copyright Notice in lua.h
55 */
@@ -286,7 +286,7 @@ LUA_API int lua_isstring (lua_State *L, int idx) { · 280 unmodified lines
286286
287287 LUA_API int lua_isuserdata (lua_State *L, int idx) {
288288 const TValue *o = index2addr(L, idx);
289− return (ttisuserdata(o) || ttislightuserdata(o));
289+ return (ttisfulluserdata(o) || ttislightuserdata(o));
290290 }
291291
292292
@@ -299,9 +299,9 @@ LUA_API int lua_rawequal (lua_State *L, int index1, int index2) { · 6 unmodified lines
299299
300300 LUA_API void lua_arith (lua_State *L, int op) {
301301 lua_lock(L);
302− if (op != LUA_OPUNM) /* all other operations expect two operands */
303− api_checknelems(L, 2);
304− else { /* for unary minus, add fake 2nd operand */
302+ if (op != LUA_OPUNM && op != LUA_OPBNOT)
303+ api_checknelems(L, 2); /* all other operations expect two operands */
304+ else { /* for unary operations, add fake 2nd operand */
305305 api_checknelems(L, 1);
306306 setobjs2s(L, L->top, L->top - 1);
307307 L->top++;
@@ -379,20 +379,20 @@ LUA_API lua_Unsigned lua_tounsignedx (lua_State *L, int idx, int *pisnum) { · 71 unmodified lines
379379 isnum = 1;
380380 break;
381381 }
382− case LUA_TNUMFLT: {
383− const lua_Number twop = (~(lua_Unsigned)0) + cast_num(1);
384− lua_Number n = fltvalue(o);
382+ case LUA_TNUMFLT: { /* compute floor(n) % 2^(numbits in an integer) */
383+ const lua_Number twop = cast_num(MAX_UINTEGER) + cast_num(1); /* 2^n */
384+ lua_Number n = fltvalue(o); /* get value */
385385 int neg = 0;
386− n = l_floor(n);
386+ n = l_floor(n); /* get its floor */
387387 if (n < 0) {
388388 neg = 1;
389− n = -n;
389+ n = -n; /* make 'n' positive, so that 'fmod' is the same as '%' */
390390 }
391− n = l_mathop(fmod)(n, twop);
392− if (luai_numisnan(L,n)) /* not a number? */
391+ n = l_mathop(fmod)(n, twop); /* n = n % 2^(numbits in an integer) */
392+ if (luai_numisnan(n)) /* not a number? */
393393 break; /* not an integer, too */
394− res = cast_unsigned(n);
395− if (neg) res = 0u - res;
394+ res = cast_unsigned(n); /* 'n' now must fit in an unsigned */
395+ if (neg) res = 0u - res; /* back to negative, if needed */
396396 isnum = 1;
397397 break;
398398 }
@@ -586,8 +586,10 @@ LUA_API void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n) { · 187 unmodified lines
586586 cl = luaF_newCclosure(L, n);
587587 cl->c.f = fn;
588588 L->top -= n;
589− while (n--)
589+ while (n--) {
590590 setobj2n(L, &cl->c.upvalue[n], L->top + n);
591+ /* does not need barrier because closure is white */
592+ }
591593 setclCvalue(L, L->top, cl);
592594 }
593595 api_incr_top(L);
@@ -626,7 +628,7 @@ LUA_API int lua_pushthread (lua_State *L) { · 32 unmodified lines
626628 */
627629
628630
629−LUA_API void lua_getglobal (lua_State *L, const char *var) {
631+LUA_API int lua_getglobal (lua_State *L, const char *var) {
630632 Table *reg = hvalue(&G(L)->l_registry);
631633 const TValue *gt; /* global table */
632634 lua_lock(L);
@@ -634,19 +636,21 @@ LUA_API void lua_getglobal (lua_State *L, const char *var) { · 1 unmodified line
634636 setsvalue2s(L, L->top++, luaS_new(L, var));
635637 luaV_gettable(L, gt, L->top - 1, L->top - 1);
636638 lua_unlock(L);
639+ return ttnov(L->top - 1);
637640 }
638641
639642
640−LUA_API void lua_gettable (lua_State *L, int idx) {
643+LUA_API int lua_gettable (lua_State *L, int idx) {
641644 StkId t;
642645 lua_lock(L);
643646 t = index2addr(L, idx);
644647 luaV_gettable(L, t, L->top - 1, L->top - 1);
645648 lua_unlock(L);
649+ return ttnov(L->top - 1);
646650 }
647651
648652
649−LUA_API void lua_getfield (lua_State *L, int idx, const char *k) {
653+LUA_API int lua_getfield (lua_State *L, int idx, const char *k) {
650654 StkId t;
651655 lua_lock(L);
652656 t = index2addr(L, idx);
@@ -654,20 +658,22 @@ LUA_API void lua_getfield (lua_State *L, int idx, const char *k) { · 1 unmodified line
654658 api_incr_top(L);
655659 luaV_gettable(L, t, L->top - 1, L->top - 1);
656660 lua_unlock(L);
661+ return ttnov(L->top - 1);
657662 }
658663
659664
660−LUA_API void lua_rawget (lua_State *L, int idx) {
665+LUA_API int lua_rawget (lua_State *L, int idx) {
661666 StkId t;
662667 lua_lock(L);
663668 t = index2addr(L, idx);
664669 api_check(L, ttistable(t), "table expected");
665670 setobj2s(L, L->top - 1, luaH_get(hvalue(t), L->top - 1));
666671 lua_unlock(L);
672+ return ttnov(L->top - 1);
667673 }
668674
669675
670−LUA_API void lua_rawgeti (lua_State *L, int idx, lua_Integer n) {
676+LUA_API int lua_rawgeti (lua_State *L, int idx, lua_Integer n) {
671677 StkId t;
672678 lua_lock(L);
673679 t = index2addr(L, idx);
@@ -675,10 +681,11 @@ LUA_API void lua_rawgeti (lua_State *L, int idx, lua_Integer n) { · 1 unmodified line
675681 setobj2s(L, L->top, luaH_getint(hvalue(t), n));
676682 api_incr_top(L);
677683 lua_unlock(L);
684+ return ttnov(L->top - 1);
678685 }
679686
680687
681−LUA_API void lua_rawgetp (lua_State *L, int idx, const void *p) {
688+LUA_API int lua_rawgetp (lua_State *L, int idx, const void *p) {
682689 StkId t;
683690 TValue k;
684691 lua_lock(L);
@@ -688,6 +695,7 @@ LUA_API void lua_rawgetp (lua_State *L, int idx, const void *p) { · 3 unmodified lines
688695 setobj2s(L, L->top, luaH_get(hvalue(t), &k));
689696 api_incr_top(L);
690697 lua_unlock(L);
698+ return ttnov(L->top - 1);
691699 }
692700
693701
@@ -737,11 +745,8 @@ LUA_API void lua_getuservalue (lua_State *L, int idx) { · 43 unmodified lines
737745 StkId o;
738746 lua_lock(L);
739747 o = index2addr(L, idx);
740− api_check(L, ttisuserdata(o), "userdata expected");
741− if (uvalue(o)->env) {
742− sethvalue(L, L->top, uvalue(o)->env);
743− } else
744− setnilvalue(L->top);
748+ api_check(L, ttisfulluserdata(o), "full userdata expected");
749+ getuservalue(L, rawuvalue(o), L->top);
745750 api_incr_top(L);
746751 lua_unlock(L);
747752 }
@@ -846,7 +851,7 @@ LUA_API int lua_setmetatable (lua_State *L, int objindex) { · 98 unmodified lines
846851 case LUA_TTABLE: {
847852 hvalue(obj)->metatable = mt;
848853 if (mt) {
849− luaC_objbarrierback(L, gcvalue(obj), mt);
854+ luaC_objbarrier(L, gcvalue(obj), mt);
850855 luaC_checkfinalizer(L, gcvalue(obj), mt);
851856 }
852857 break;
@@ -875,14 +880,9 @@ LUA_API void lua_setuservalue (lua_State *L, int idx) { · 22 unmodified lines
875880 lua_lock(L);
876881 api_checknelems(L, 1);
877882 o = index2addr(L, idx);
878− api_check(L, ttisuserdata(o), "userdata expected");
879− if (ttisnil(L->top - 1))
880− uvalue(o)->env = NULL;
881− else {
882− api_check(L, ttistable(L->top - 1), "table expected");
883− uvalue(o)->env = hvalue(L->top - 1);
884− luaC_objbarrier(L, gcvalue(o), hvalue(L->top - 1));
885− }
883+ api_check(L, ttisfulluserdata(o), "full userdata expected");
884+ setuservalue(L, rawuvalue(o), L->top - 1);
885+ luaC_barrier(L, gcvalue(o), L->top - 1);
886886 L->top--;
887887 lua_unlock(L);
888888 }
@@ -1015,14 +1015,14 @@ LUA_API int lua_load (lua_State *L, lua_Reader reader, void *data, · 126 unmodified lines
10151015 }
10161016
10171017
1018−LUA_API int lua_dump (lua_State *L, lua_Writer writer, void *data) {
1018+LUA_API int lua_dump (lua_State *L, lua_Writer writer, void *data, int strip) {
10191019 int status;
10201020 TValue *o;
10211021 lua_lock(L);
10221022 api_checknelems(L, 1);
10231023 o = L->top - 1;
10241024 if (isLfunction(o))
1025− status = luaU_dump(L, getproto(o), writer, data, 0);
1025+ status = luaU_dump(L, getproto(o), writer, data, strip);
10261026 else
10271027 status = 1;
10281028 lua_unlock(L);
@@ -1068,19 +1068,21 @@ LUA_API int lua_gc (lua_State *L, int what, int data) { · 39 unmodified lines
10681068 break;
10691069 }
10701070 case LUA_GCSTEP: {
1071− if (g->gckind == KGC_GEN) { /* generational mode? */
1072− res = (g->GCestimate == 0); /* true if it will do major collection */
1073− luaC_forcestep(L); /* do a single step */
1071+ l_mem debt = 1; /* =1 to signal that it did an actual step */
1072+ int oldrunning = g->gcrunning;
1073+ g->gcrunning = 1; /* force GC to run */
1074+ if (data == 0) {
1075+ luaE_setdebt(g, -GCSTEPSIZE); /* to do a "small" step */
1076+ luaC_step(L);
10741077 }
1075− else {
1076− lu_mem debt = cast(lu_mem, data) * 1024 - GCSTEPSIZE;
1077− if (g->gcrunning)
1078− debt += g->GCdebt; /* include current debt */
1079− luaE_setdebt(g, debt);
1080− luaC_forcestep(L);
1081− if (g->gcstate == GCSpause) /* end of cycle? */
1082− res = 1; /* signal it */
1078+ else { /* add 'data' to total debt */
1079+ debt = cast(l_mem, data) * 1024 + g->GCdebt;
1080+ luaE_setdebt(g, debt);
1081+ luaC_checkGC(L);
10831082 }
1083+ g->gcrunning = oldrunning; /* restore previous state */
1084+ if (debt > 0 && g->gcstate == GCSpause) /* end of cycle? */
1085+ res = 1; /* signal it */
10841086 break;
10851087 }
10861088 case LUA_GCSETPAUSE: {
@@ -1088,13 +1090,9 @@ LUA_API int lua_gc (lua_State *L, int what, int data) { · 1 unmodified line
10881090 g->gcpause = data;
10891091 break;
10901092 }
1091− case LUA_GCSETMAJORINC: {
1092− res = g->gcmajorinc;
1093− g->gcmajorinc = data;
1094− break;
1095− }
10961093 case LUA_GCSETSTEPMUL: {
10971094 res = g->gcstepmul;
1095+ if (data < 40) data = 40; /* avoid ridiculous low values (and 0) */
10981096 g->gcstepmul = data;
10991097 break;
11001098 }
@@ -1102,14 +1100,6 @@ LUA_API int lua_gc (lua_State *L, int what, int data) { · 1 unmodified line
11021100 res = g->gcrunning;
11031101 break;
11041102 }
1105− case LUA_GCGEN: { /* change collector to generational mode */
1106− luaC_changemode(L, KGC_GEN);
1107− break;
1108− }
1109− case LUA_GCINC: { /* change collector to incremental mode */
1110− luaC_changemode(L, KGC_NORMAL);
1111− break;
1112− }
11131103 default: res = -1; /* invalid option */
11141104 }
11151105 lua_unlock(L);
@@ -1197,7 +1187,7 @@ LUA_API void *lua_newuserdata (lua_State *L, size_t size) { · 81 unmodified lines
11971187 Udata *u;
11981188 lua_lock(L);
11991189 luaC_checkGC(L);
1200− u = luaS_newudata(L, size, NULL);
1190+ u = luaS_newudata(L, size);
12011191 setuvalue(L, L->top, u);
12021192 api_incr_top(L);
12031193 lua_unlock(L);
@@ -1207,7 +1197,7 @@ LUA_API void *lua_newuserdata (lua_State *L, size_t size) { · 3 unmodified lines
12071197
12081198
12091199 static const char *aux_upvalue (StkId fi, int n, TValue **val,
1210− GCObject **owner) {
1200+ GCObject **owner, UpVal **uv) {
12111201 switch (ttype(fi)) {
12121202 case LUA_TCCL: { /* C closure */
12131203 CClosure *f = clCvalue(fi);
@@ -1222,9 +1212,9 @@ static const char *aux_upvalue (StkId fi, int n, TValue **val, · 8 unmodified lines
12221212 Proto *p = f->p;
12231213 if (!(1 <= n && n <= p->sizeupvalues)) return NULL;
12241214 *val = f->upvals[n-1]->v;
1225− if (owner) *owner = obj2gco(f->upvals[n - 1]);
1215+ if (uv) *uv = f->upvals[n - 1];
12261216 name = p->upvalues[n-1].name;
1227− return (name == NULL) ? "" : getstr(name);
1217+ return (name == NULL) ? "(*no name)" : getstr(name);
12281218 }
12291219 default: return NULL; /* not a closure */
12301220 }
@@ -1235,7 +1225,7 @@ LUA_API const char *lua_getupvalue (lua_State *L, int funcindex, int n) { · 4 unmodified lines
12351225 const char *name;
12361226 TValue *val = NULL; /* to avoid warnings */
12371227 lua_lock(L);
1238− name = aux_upvalue(index2addr(L, funcindex), n, &val, NULL);
1228+ name = aux_upvalue(index2addr(L, funcindex), n, &val, NULL, NULL);
12391229 if (name) {
12401230 setobj2s(L, L->top, val);
12411231 api_incr_top(L);
@@ -1248,16 +1238,18 @@ LUA_API const char *lua_getupvalue (lua_State *L, int funcindex, int n) { · 6 unmodified lines
12481238 LUA_API const char *lua_setupvalue (lua_State *L, int funcindex, int n) {
12491239 const char *name;
12501240 TValue *val = NULL; /* to avoid warnings */
1251− GCObject *owner = NULL; /* to avoid warnings */
1241+ GCObject *owner = NULL;
1242+ UpVal *uv = NULL;
12521243 StkId fi;
12531244 lua_lock(L);
12541245 fi = index2addr(L, funcindex);
12551246 api_checknelems(L, 1);
1256− name = aux_upvalue(fi, n, &val, &owner);
1247+ name = aux_upvalue(fi, n, &val, &owner, &uv);
12571248 if (name) {
12581249 L->top--;
12591250 setobj(L, val, L->top);
1260− luaC_barrier(L, owner, L->top);
1251+ if (owner) { luaC_barrier(L, owner, L->top); }
1252+ else if (uv) { luaC_upvalbarrier(L, uv); }
12611253 }
12621254 lua_unlock(L);
12631255 return name;
@@ -1299,7 +1291,11 @@ LUA_API void lua_upvaluejoin (lua_State *L, int fidx1, int n1, · 35 unmodified lines
12991291 LClosure *f1;
13001292 UpVal **up1 = getupvalref(L, fidx1, n1, &f1);
13011293 UpVal **up2 = getupvalref(L, fidx2, n2, NULL);
1294+ luaC_upvdeccount(L, *up1);
13021295 *up1 = *up2;
1303− luaC_objbarrier(L, f1, *up2);
1296+ (*up1)->refcount++;
1297+ if (upisopen(*up1)) (*up1)->u.open.touched = 1;
1298+ luaC_upvalbarrier(L, *up1);
13041299 }
13051300
1301+
src/lauxlib.c+71−59
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lauxlib.c,v 1.255 2013/06/27 18:32:33 roberto Exp $
2+** $Id: lauxlib.c,v 1.260 2014/03/12 20:57:40 roberto Exp $
33 ** Auxiliary functions for building Lua libraries
44 ** See Copyright Notice in lua.h
55 */
@@ -150,33 +150,40 @@ LUALIB_API void luaL_traceback (lua_State *L, lua_State *L1, · 144 unmodified lines
150150 ** =======================================================
151151 */
152152
153−LUALIB_API int luaL_argerror (lua_State *L, int narg, const char *extramsg) {
153+LUALIB_API int luaL_argerror (lua_State *L, int arg, const char *extramsg) {
154154 lua_Debug ar;
155155 if (!lua_getstack(L, 0, &ar)) /* no stack frame? */
156− return luaL_error(L, "bad argument #%d (%s)", narg, extramsg);
156+ return luaL_error(L, "bad argument #%d (%s)", arg, extramsg);
157157 lua_getinfo(L, "n", &ar);
158158 if (strcmp(ar.namewhat, "method") == 0) {
159− narg--; /* do not count `self' */
160− if (narg == 0) /* error is in the self argument itself? */
159+ arg--; /* do not count `self' */
160+ if (arg == 0) /* error is in the self argument itself? */
161161 return luaL_error(L, "calling " LUA_QS " on bad self (%s)",
162162 ar.name, extramsg);
163163 }
164164 if (ar.name == NULL)
165165 ar.name = (pushglobalfuncname(L, &ar)) ? lua_tostring(L, -1) : "?";
166166 return luaL_error(L, "bad argument #%d to " LUA_QS " (%s)",
167− narg, ar.name, extramsg);
167+ arg, ar.name, extramsg);
168168 }
169169
170170
171−static int typeerror (lua_State *L, int narg, const char *tname) {
172− const char *msg = lua_pushfstring(L, "%s expected, got %s",
173− tname, luaL_typename(L, narg));
174− return luaL_argerror(L, narg, msg);
171+static int typeerror (lua_State *L, int arg, const char *tname) {
172+ const char *msg;
173+ const char *typearg = luaL_typename(L, arg);
174+ if (lua_getmetatable(L, arg)) {
175+ if (lua_getfield(L, -1, "__name") == LUA_TSTRING)
176+ typearg = lua_tostring(L, -1);
177+ }
178+ else if (lua_type(L, arg) == LUA_TLIGHTUSERDATA)
179+ typearg = "light userdata";
180+ msg = lua_pushfstring(L, "%s expected, got %s", tname, typearg);
181+ return luaL_argerror(L, arg, msg);
175182 }
176183
177184
178−static void tag_error (lua_State *L, int narg, int tag) {
179− typeerror(L, narg, lua_typename(L, tag));
185+static void tag_error (lua_State *L, int arg, int tag) {
186+ typeerror(L, arg, lua_typename(L, tag));
180187 }
181188
182189
@@ -275,6 +282,8 @@ LUALIB_API int luaL_newmetatable (lua_State *L, const char *tname) { · 92 unmodified lines
275282 return 0; /* leave previous value on top, but return 0 */
276283 lua_pop(L, 1);
277284 lua_newtable(L); /* create metatable */
285+ lua_pushstring(L, tname);
286+ lua_setfield(L, -2, "__name"); /* metatable.__name = tname */
278287 lua_pushvalue(L, -1);
279288 lua_setfield(L, LUA_REGISTRYINDEX, tname); /* registry.name = metatable */
280289 return 1;
@@ -317,15 +326,15 @@ LUALIB_API void *luaL_checkudata (lua_State *L, int ud, const char *tname) { · 36 unmodified lines
317326 ** =======================================================
318327 */
319328
320−LUALIB_API int luaL_checkoption (lua_State *L, int narg, const char *def,
329+LUALIB_API int luaL_checkoption (lua_State *L, int arg, const char *def,
321330 const char *const lst[]) {
322− const char *name = (def) ? luaL_optstring(L, narg, def) :
323− luaL_checkstring(L, narg);
331+ const char *name = (def) ? luaL_optstring(L, arg, def) :
332+ luaL_checkstring(L, arg);
324333 int i;
325334 for (i=0; lst[i]; i++)
326335 if (strcmp(lst[i], name) == 0)
327336 return i;
328− return luaL_argerror(L, narg,
337+ return luaL_argerror(L, arg,
329338 lua_pushfstring(L, "invalid option " LUA_QS, name));
330339 }
331340
@@ -342,86 +351,86 @@ LUALIB_API void luaL_checkstack (lua_State *L, int space, const char *msg) { · 10 unmodified lines
342351 }
343352
344353
345−LUALIB_API void luaL_checktype (lua_State *L, int narg, int t) {
346− if (lua_type(L, narg) != t)
347− tag_error(L, narg, t);
354+LUALIB_API void luaL_checktype (lua_State *L, int arg, int t) {
355+ if (lua_type(L, arg) != t)
356+ tag_error(L, arg, t);
348357 }
349358
350359
351−LUALIB_API void luaL_checkany (lua_State *L, int narg) {
352− if (lua_type(L, narg) == LUA_TNONE)
353− luaL_argerror(L, narg, "value expected");
360+LUALIB_API void luaL_checkany (lua_State *L, int arg) {
361+ if (lua_type(L, arg) == LUA_TNONE)
362+ luaL_argerror(L, arg, "value expected");
354363 }
355364
356365
357−LUALIB_API const char *luaL_checklstring (lua_State *L, int narg, size_t *len) {
358− const char *s = lua_tolstring(L, narg, len);
359− if (!s) tag_error(L, narg, LUA_TSTRING);
366+LUALIB_API const char *luaL_checklstring (lua_State *L, int arg, size_t *len) {
367+ const char *s = lua_tolstring(L, arg, len);
368+ if (!s) tag_error(L, arg, LUA_TSTRING);
360369 return s;
361370 }
362371
363372
364−LUALIB_API const char *luaL_optlstring (lua_State *L, int narg,
373+LUALIB_API const char *luaL_optlstring (lua_State *L, int arg,
365374 const char *def, size_t *len) {
366− if (lua_isnoneornil(L, narg)) {
375+ if (lua_isnoneornil(L, arg)) {
367376 if (len)
368377 *len = (def ? strlen(def) : 0);
369378 return def;
370379 }
371− else return luaL_checklstring(L, narg, len);
380+ else return luaL_checklstring(L, arg, len);
372381 }
373382
374383
375−LUALIB_API lua_Number luaL_checknumber (lua_State *L, int narg) {
384+LUALIB_API lua_Number luaL_checknumber (lua_State *L, int arg) {
376385 int isnum;
377− lua_Number d = lua_tonumberx(L, narg, &isnum);
386+ lua_Number d = lua_tonumberx(L, arg, &isnum);
378387 if (!isnum)
379− tag_error(L, narg, LUA_TNUMBER);
388+ tag_error(L, arg, LUA_TNUMBER);
380389 return d;
381390 }
382391
383392
384−LUALIB_API lua_Number luaL_optnumber (lua_State *L, int narg, lua_Number def) {
385− return luaL_opt(L, luaL_checknumber, narg, def);
393+LUALIB_API lua_Number luaL_optnumber (lua_State *L, int arg, lua_Number def) {
394+ return luaL_opt(L, luaL_checknumber, arg, def);
386395 }
387396
388397
389−static void interror (lua_State *L, int narg) {
390− if (lua_type(L, narg) == LUA_TNUMBER)
391− luaL_argerror(L, narg, "float value out of range");
398+static void interror (lua_State *L, int arg) {
399+ if (lua_type(L, arg) == LUA_TNUMBER)
400+ luaL_argerror(L, arg, "float value out of range");
392401 else
393− tag_error(L, narg, LUA_TNUMBER);
402+ tag_error(L, arg, LUA_TNUMBER);
394403 }
395404
396405
397−LUALIB_API lua_Integer luaL_checkinteger (lua_State *L, int narg) {
406+LUALIB_API lua_Integer luaL_checkinteger (lua_State *L, int arg) {
398407 int isnum;
399− lua_Integer d = lua_tointegerx(L, narg, &isnum);
408+ lua_Integer d = lua_tointegerx(L, arg, &isnum);
400409 if (!isnum) {
401− interror(L, narg);
410+ interror(L, arg);
402411 }
403412 return d;
404413 }
405414
406415
407−LUALIB_API lua_Unsigned luaL_checkunsigned (lua_State *L, int narg) {
416+LUALIB_API lua_Unsigned luaL_checkunsigned (lua_State *L, int arg) {
408417 int isnum;
409− lua_Unsigned d = lua_tounsignedx(L, narg, &isnum);
418+ lua_Unsigned d = lua_tounsignedx(L, arg, &isnum);
410419 if (!isnum)
411− interror(L, narg);
420+ interror(L, arg);
412421 return d;
413422 }
414423
415424
416−LUALIB_API lua_Integer luaL_optinteger (lua_State *L, int narg,
425+LUALIB_API lua_Integer luaL_optinteger (lua_State *L, int arg,
417426 lua_Integer def) {
418− return luaL_opt(L, luaL_checkinteger, narg, def);
427+ return luaL_opt(L, luaL_checkinteger, arg, def);
419428 }
420429
421430
422−LUALIB_API lua_Unsigned luaL_optunsigned (lua_State *L, int narg,
431+LUALIB_API lua_Unsigned luaL_optunsigned (lua_State *L, int arg,
423432 lua_Unsigned def) {
424− return luaL_opt(L, luaL_checkunsigned, narg, def);
433+ return luaL_opt(L, luaL_checkunsigned, arg, def);
425434 }
426435
427436 /* }====================================================== */
@@ -709,8 +718,7 @@ LUALIB_API int luaL_getmetafield (lua_State *L, int obj, const char *event) { · 281 unmodified lines
709718 if (!lua_getmetatable(L, obj)) /* no metatable? */
710719 return 0;
711720 lua_pushstring(L, event);
712− lua_rawget(L, -2);
713− if (lua_isnil(L, -1)) {
721+ if (lua_rawget(L, -2) == LUA_TNIL) { /* is metafield nil? */
714722 lua_pop(L, 2); /* remove metatable and metafield */
715723 return 0;
716724 }
@@ -746,10 +754,16 @@ LUALIB_API lua_Integer luaL_len (lua_State *L, int idx) { · 29 unmodified lines
746754 LUALIB_API const char *luaL_tolstring (lua_State *L, int idx, size_t *len) {
747755 if (!luaL_callmeta(L, idx, "__tostring")) { /* no metafield? */
748756 switch (lua_type(L, idx)) {
749− case LUA_TNUMBER: { /* concatenate with empty string to convert */
750− lua_pushvalue(L, idx);
751− lua_pushliteral(L, "");
752− lua_concat(L, 2);
757+ case LUA_TNUMBER: {
758+ if (lua_isinteger(L, idx))
759+ lua_pushfstring(L, "%I", lua_tointeger(L, idx));
760+ else {
761+ const char *s = lua_pushfstring(L, "%f", lua_tonumber(L, idx));
762+ if (s[strspn(s, "-0123456789")] == '\0') { /* looks like an int? */
763+ lua_pushliteral(L, ".0"); /* add a '.0' to result */
764+ lua_concat(L, 2);
765+ }
766+ }
753767 break;
754768 }
755769 case LUA_TSTRING:
@@ -786,8 +800,7 @@ static const char *luaL_findtable (lua_State *L, int idx, · 30 unmodified lines
786800 e = strchr(fname, '.');
787801 if (e == NULL) e = fname + strlen(fname);
788802 lua_pushlstring(L, fname, e - fname);
789− lua_rawget(L, -2);
790− if (lua_isnil(L, -1)) { /* no such field? */
803+ if (lua_rawget(L, -2) == LUA_TNIL) { /* no such field? */
791804 lua_pop(L, 1); /* remove this nil */
792805 lua_createtable(L, 0, (*e == '.' ? 1 : szhint)); /* new table for field */
793806 lua_pushlstring(L, fname, e - fname);
@@ -824,8 +837,7 @@ static int libsize (const luaL_Reg *l) { · 30 unmodified lines
824837 LUALIB_API void luaL_pushmodule (lua_State *L, const char *modname,
825838 int sizehint) {
826839 luaL_findtable(L, LUA_REGISTRYINDEX, "_LOADED", 1); /* get _LOADED table */
827− lua_getfield(L, -1, modname); /* get _LOADED[modname] */
828− if (!lua_istable(L, -1)) { /* not found? */
840+ if (lua_getfield(L, -1, modname) != LUA_TTABLE) { /* no _LOADED[modname]? */
829841 lua_pop(L, 1); /* remove previous result */
830842 /* try global variable (and create one if it does not exist) */
831843 lua_pushglobaltable(L);
@@ -877,8 +889,8 @@ LUALIB_API void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup) { · 45 unmodified lines
877889 ** into the stack
878890 */
879891 LUALIB_API int luaL_getsubtable (lua_State *L, int idx, const char *fname) {
880− lua_getfield(L, idx, fname);
881− if (lua_istable(L, -1)) return 1; /* table already there */
892+ if (lua_getfield(L, idx, fname) == LUA_TTABLE)
893+ return 1; /* table already there */
882894 else {
883895 lua_pop(L, 1); /* remove previous result */
884896 idx = lua_absindex(L, idx);
src/lauxlib.h+15−15
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lauxlib.h,v 1.122 2013/06/27 18:32:33 roberto Exp $
2+** $Id: lauxlib.h,v 1.123 2014/01/05 14:04:46 roberto Exp $
33 ** Auxiliary functions for building Lua libraries
44 ** See Copyright Notice in lua.h
55 */
@@ -35,24 +35,24 @@ LUALIB_API void (luaL_checkversion_) (lua_State *L, int ver, size_t sz); · 29 unmodified lines
3535 LUALIB_API int (luaL_getmetafield) (lua_State *L, int obj, const char *e);
3636 LUALIB_API int (luaL_callmeta) (lua_State *L, int obj, const char *e);
3737 LUALIB_API const char *(luaL_tolstring) (lua_State *L, int idx, size_t *len);
38−LUALIB_API int (luaL_argerror) (lua_State *L, int numarg, const char *extramsg);
39−LUALIB_API const char *(luaL_checklstring) (lua_State *L, int numArg,
38+LUALIB_API int (luaL_argerror) (lua_State *L, int arg, const char *extramsg);
39+LUALIB_API const char *(luaL_checklstring) (lua_State *L, int arg,
4040 size_t *l);
41−LUALIB_API const char *(luaL_optlstring) (lua_State *L, int numArg,
41+LUALIB_API const char *(luaL_optlstring) (lua_State *L, int arg,
4242 const char *def, size_t *l);
43−LUALIB_API lua_Number (luaL_checknumber) (lua_State *L, int numArg);
44−LUALIB_API lua_Number (luaL_optnumber) (lua_State *L, int nArg, lua_Number def);
43+LUALIB_API lua_Number (luaL_checknumber) (lua_State *L, int arg);
44+LUALIB_API lua_Number (luaL_optnumber) (lua_State *L, int arg, lua_Number def);
4545
46−LUALIB_API lua_Integer (luaL_checkinteger) (lua_State *L, int numArg);
47−LUALIB_API lua_Integer (luaL_optinteger) (lua_State *L, int nArg,
46+LUALIB_API lua_Integer (luaL_checkinteger) (lua_State *L, int arg);
47+LUALIB_API lua_Integer (luaL_optinteger) (lua_State *L, int arg,
4848 lua_Integer def);
49−LUALIB_API lua_Unsigned (luaL_checkunsigned) (lua_State *L, int numArg);
50−LUALIB_API lua_Unsigned (luaL_optunsigned) (lua_State *L, int numArg,
49+LUALIB_API lua_Unsigned (luaL_checkunsigned) (lua_State *L, int arg);
50+LUALIB_API lua_Unsigned (luaL_optunsigned) (lua_State *L, int arg,
5151 lua_Unsigned def);
5252
5353 LUALIB_API void (luaL_checkstack) (lua_State *L, int sz, const char *msg);
54−LUALIB_API void (luaL_checktype) (lua_State *L, int narg, int t);
55−LUALIB_API void (luaL_checkany) (lua_State *L, int narg);
54+LUALIB_API void (luaL_checktype) (lua_State *L, int arg, int t);
55+LUALIB_API void (luaL_checkany) (lua_State *L, int arg);
5656
5757 LUALIB_API int (luaL_newmetatable) (lua_State *L, const char *tname);
5858 LUALIB_API void (luaL_setmetatable) (lua_State *L, const char *tname);
@@ -62,7 +62,7 @@ LUALIB_API void *(luaL_checkudata) (lua_State *L, int ud, const char *tname); · 3 unmodified lines
6262 LUALIB_API void (luaL_where) (lua_State *L, int lvl);
6363 LUALIB_API int (luaL_error) (lua_State *L, const char *fmt, ...);
6464
65−LUALIB_API int (luaL_checkoption) (lua_State *L, int narg, const char *def,
65+LUALIB_API int (luaL_checkoption) (lua_State *L, int arg, const char *def,
6666 const char *const lst[]);
6767
6868 LUALIB_API int (luaL_fileresult) (lua_State *L, int stat, const char *fname);
@@ -114,8 +114,8 @@ LUALIB_API void (luaL_requiref) (lua_State *L, const char *modname, · 45 unmodified lines
114114 #define luaL_newlib(L,l) \
115115 (luaL_checkversion(L), luaL_newlibtable(L,l), luaL_setfuncs(L,l,0))
116116
117−#define luaL_argcheck(L, cond,numarg,extramsg) \
118− ((void)((cond) || luaL_argerror(L, (numarg), (extramsg))))
117+#define luaL_argcheck(L, cond,arg,extramsg) \
118+ ((void)((cond) || luaL_argerror(L, (arg), (extramsg))))
119119 #define luaL_checkstring(L,n) (luaL_checklstring(L, (n), NULL))
120120 #define luaL_optstring(L,n,d) (luaL_optlstring(L, (n), (d), NULL))
121121 #define luaL_checkint(L,n) ((int)luaL_checkinteger(L, (n)))
src/lbaselib.c+7−9
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lbaselib.c,v 1.279 2013/07/05 14:39:15 roberto Exp $
2+** $Id: lbaselib.c,v 1.285 2014/03/12 20:57:40 roberto Exp $
33 ** Basic library
44 ** See Copyright Notice in lua.h
55 */
@@ -63,7 +63,7 @@ static int b_str2int (const char *s, const char *e, int base, lua_Integer *pn) { · 57 unmodified lines
6363 s += strspn(s, SPACECHARS); /* skip trailing spaces */
6464 if (s != e) /* invalid trailing characters? */
6565 return 0;
66− *pn = (neg) ? -(lua_Integer)n : (lua_Integer)n;
66+ *pn = (lua_Integer)((neg) ? (0u - n) : n);
6767 return 1;
6868 }
6969
@@ -175,19 +175,18 @@ static int luaB_rawset (lua_State *L) { · 105 unmodified lines
175175 static int luaB_collectgarbage (lua_State *L) {
176176 static const char *const opts[] = {"stop", "restart", "collect",
177177 "count", "step", "setpause", "setstepmul",
178− "setmajorinc", "isrunning", "generational", "incremental", NULL};
178+ "isrunning", NULL};
179179 static const int optsnum[] = {LUA_GCSTOP, LUA_GCRESTART, LUA_GCCOLLECT,
180180 LUA_GCCOUNT, LUA_GCSTEP, LUA_GCSETPAUSE, LUA_GCSETSTEPMUL,
181− LUA_GCSETMAJORINC, LUA_GCISRUNNING, LUA_GCGEN, LUA_GCINC};
181+ LUA_GCISRUNNING};
182182 int o = optsnum[luaL_checkoption(L, 1, "collect", opts)];
183183 int ex = luaL_optint(L, 2, 0);
184184 int res = lua_gc(L, o, ex);
185185 switch (o) {
186186 case LUA_GCCOUNT: {
187187 int b = lua_gc(L, LUA_GCCOUNTB, 0);
188− lua_pushnumber(L, res + ((lua_Number)b/1024));
189− lua_pushinteger(L, b);
190− return 2;
188+ lua_pushnumber(L, (lua_Number)res + ((lua_Number)b/1024));
189+ return 1;
191190 }
192191 case LUA_GCSTEP: case LUA_GCISRUNNING: {
193192 lua_pushboolean(L, res);
@@ -247,8 +246,7 @@ static int ipairsaux (lua_State *L) { · 53 unmodified lines
247246 luaL_checktype(L, 1, LUA_TTABLE);
248247 i++; /* next value */
249248 lua_pushinteger(L, i);
250− lua_rawgeti(L, 1, i);
251− return (lua_isnil(L, -1)) ? 1 : 2;
249+ return (lua_rawgeti(L, 1, i) == LUA_TNIL) ? 1 : 2;
252250 }
253251
254252
src/lbitlib.c+37−22
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lbitlib.c,v 1.20 2013/06/21 17:27:24 roberto Exp $
2+** $Id: lbitlib.c,v 1.25 2014/03/20 19:22:16 roberto Exp $
33 ** Standard library for bitwise operations
44 ** See Copyright Notice in lua.h
55 */
@@ -13,17 +13,21 @@ · 7 unmodified lines
1313 #include "lualib.h"
1414
1515
16+#if defined(LUA_COMPAT_BITLIB) /* { */
17+
18+
1619 /* number of bits to consider in a number */
1720 #if !defined(LUA_NBITS)
1821 #define LUA_NBITS 32
1922 #endif
2023
2124
22−/* type with (at least) LUA_NBITS bits */
23−typedef unsigned long b_uint;
24−
25−
26−#define ALLONES (~(((~(b_uint)0) << (LUA_NBITS - 1)) << 1))
25+/*
26+** a lua_Unsigned with its first LUA_NBITS bits equal to 1. (Shift must
27+** be made in two parts to avoid problems when LUA_NBITS is equal to the
28+** number of bits in a lua_Unsigned.)
29+*/
30+#define ALLONES (~(((~(lua_Unsigned)0) << (LUA_NBITS - 1)) << 1))
2731
2832
2933 /* macro to trim extra bits */
@@ -35,9 +39,9 @@ typedef unsigned long b_uint; · 5 unmodified lines
3539
3640
3741
38−static b_uint andaux (lua_State *L) {
42+static lua_Unsigned andaux (lua_State *L) {
3943 int i, n = lua_gettop(L);
40− b_uint r = ~(b_uint)0;
44+ lua_Unsigned r = ~(lua_Unsigned)0;
4145 for (i = 1; i <= n; i++)
4246 r &= luaL_checkunsigned(L, i);
4347 return trim(r);
@@ -45,14 +49,14 @@ static b_uint andaux (lua_State *L) { · 1 unmodified line
4549
4650
4751 static int b_and (lua_State *L) {
48− b_uint r = andaux(L);
52+ lua_Unsigned r = andaux(L);
4953 lua_pushunsigned(L, r);
5054 return 1;
5155 }
5256
5357
5458 static int b_test (lua_State *L) {
55− b_uint r = andaux(L);
59+ lua_Unsigned r = andaux(L);
5660 lua_pushboolean(L, r != 0);
5761 return 1;
5862 }
@@ -60,7 +64,7 @@ static int b_test (lua_State *L) { · 1 unmodified line
6064
6165 static int b_or (lua_State *L) {
6266 int i, n = lua_gettop(L);
63− b_uint r = 0;
67+ lua_Unsigned r = 0;
6468 for (i = 1; i <= n; i++)
6569 r |= luaL_checkunsigned(L, i);
6670 lua_pushunsigned(L, trim(r));
@@ -70,7 +74,7 @@ static int b_or (lua_State *L) { · 3 unmodified lines
7074
7175 static int b_xor (lua_State *L) {
7276 int i, n = lua_gettop(L);
73− b_uint r = 0;
77+ lua_Unsigned r = 0;
7478 for (i = 1; i <= n; i++)
7579 r ^= luaL_checkunsigned(L, i);
7680 lua_pushunsigned(L, trim(r));
@@ -79,13 +83,13 @@ static int b_xor (lua_State *L) { · 2 unmodified lines
7983
8084
8185 static int b_not (lua_State *L) {
82− b_uint r = ~luaL_checkunsigned(L, 1);
86+ lua_Unsigned r = ~luaL_checkunsigned(L, 1);
8387 lua_pushunsigned(L, trim(r));
8488 return 1;
8589 }
8690
8791
88−static int b_shift (lua_State *L, b_uint r, int i) {
92+static int b_shift (lua_State *L, lua_Unsigned r, int i) {
8993 if (i < 0) { /* shift right? */
9094 i = -i;
9195 r = trim(r);
@@ -113,14 +117,14 @@ static int b_rshift (lua_State *L) { · 21 unmodified lines
113117
114118
115119 static int b_arshift (lua_State *L) {
116− b_uint r = luaL_checkunsigned(L, 1);
120+ lua_Unsigned r = luaL_checkunsigned(L, 1);
117121 int i = luaL_checkint(L, 2);
118− if (i < 0 || !(r & ((b_uint)1 << (LUA_NBITS - 1))))
122+ if (i < 0 || !(r & ((lua_Unsigned)1 << (LUA_NBITS - 1))))
119123 return b_shift(L, r, -i);
120124 else { /* arithmetic shift for 'negative' number */
121125 if (i >= LUA_NBITS) r = ALLONES;
122126 else
123− r = trim((r >> i) | ~(trim(~(b_uint)0) >> i)); /* add signal bit */
127+ r = trim((r >> i) | ~(trim(~(lua_Unsigned)0) >> i)); /* add signal bit */
124128 lua_pushunsigned(L, r);
125129 return 1;
126130 }
@@ -128,10 +132,11 @@ static int b_arshift (lua_State *L) { · 1 unmodified line
128132
129133
130134 static int b_rot (lua_State *L, int i) {
131− b_uint r = luaL_checkunsigned(L, 1);
135+ lua_Unsigned r = luaL_checkunsigned(L, 1);
132136 i &= (LUA_NBITS - 1); /* i = i % NBITS */
133137 r = trim(r);
134− r = (r << i) | (r >> (LUA_NBITS - i));
138+ if (i != 0) /* avoid undefined shift of LUA_NBITS when i == 0 */
139+ r = (r << i) | (r >> (LUA_NBITS - i));
135140 lua_pushunsigned(L, trim(r));
136141 return 1;
137142 }
@@ -167,7 +172,7 @@ static int fieldargs (lua_State *L, int farg, int *width) { · 29 unmodified lines
167172
168173 static int b_extract (lua_State *L) {
169174 int w;
170− b_uint r = trim(luaL_checkunsigned(L, 1));
175+ lua_Unsigned r = trim(luaL_checkunsigned(L, 1));
171176 int f = fieldargs(L, 2, &w);
172177 r = (r >> f) & mask(w);
173178 lua_pushunsigned(L, r);
@@ -177,8 +182,8 @@ static int b_extract (lua_State *L) { · 3 unmodified lines
177182
178183 static int b_replace (lua_State *L) {
179184 int w;
180− b_uint r = trim(luaL_checkunsigned(L, 1));
181− b_uint v = luaL_checkunsigned(L, 2);
185+ lua_Unsigned r = trim(luaL_checkunsigned(L, 1));
186+ lua_Unsigned v = luaL_checkunsigned(L, 2);
182187 int f = fieldargs(L, 3, &w);
183188 int m = mask(w);
184189 v &= m; /* erase bits outside given width */
@@ -211,3 +216,13 @@ LUAMOD_API int luaopen_bit32 (lua_State *L) { · 26 unmodified lines
211216 return 1;
212217 }
213218
219+
220+#else /* }{ */
221+
222+
223+LUAMOD_API int luaopen_bit32 (lua_State *L) {
224+ lua_pushnil(L);
225+ return 1;
226+}
227+
228+#endif /* } */
src/lcode.c+65−36
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lcode.c,v 2.71 2013/06/25 18:57:18 roberto Exp $
2+** $Id: lcode.c,v 2.85 2014/03/21 13:52:33 roberto Exp $
33 ** Code generator for Lua
44 ** See Copyright Notice in lua.h
55 */
@@ -307,17 +307,21 @@ static void freeexp (FuncState *fs, expdesc *e) { · 301 unmodified lines
307307 }
308308
309309
310+/*
311+** Use scanner's table to cache position of constants in constant list
312+** and try to reuse constants
313+*/
310314 static int addk (FuncState *fs, TValue *key, TValue *v) {
311315 lua_State *L = fs->ls->L;
312− TValue *idx = luaH_set(L, fs->h, key);
313316 Proto *f = fs->f;
317+ TValue *idx = luaH_set(L, fs->ls->h, key); /* index scanner table */
314318 int k, oldsize;
315− if (ttisinteger(idx)) {
319+ if (ttisinteger(idx)) { /* is there an index there? */
316320 k = ivalue(idx);
317− if (luaV_rawequalobj(&f->k[k], v))
318− return k;
319− /* else may be a collision (e.g., between 0.0 and "\0\0\0\0\0\0\0\0");
320− go through and create a new entry for this value */
321+ /* correct value? (warning: must distinguish floats from integers!) */
322+ if (k < fs->nk && ttype(&f->k[k]) == ttype(v) &&
323+ luaV_rawequalobj(&f->k[k], v))
324+ return k; /* reuse index */
321325 }
322326 /* constant not found; create a new entry */
323327 oldsize = f->sizek;
@@ -360,7 +364,7 @@ int luaK_intK (FuncState *fs, lua_Integer n) { · 36 unmodified lines
360364 */
361365 static int luaK_numberK (FuncState *fs, lua_Number r) {
362366 TValue o;
363− lua_assert(!luai_numisnan(NULL, r) && !isminuszero(r));
367+ lua_assert(!luai_numisnan(r) && !isminuszero(r));
364368 setnvalue(&o, r);
365369 return addk(fs, &o, &o);
366370 }
@@ -377,7 +381,7 @@ static int nilK (FuncState *fs) { · 10 unmodified lines
377381 TValue k, v;
378382 setnilvalue(&v);
379383 /* cannot use nil as key; instead use table itself to represent nil */
380− sethvalue(fs->ls->L, &k, fs->h);
384+ sethvalue(fs->ls->L, &k, fs->ls->h);
381385 return addk(fs, &k, &v);
382386 }
383387
@@ -746,24 +750,46 @@ void luaK_indexed (FuncState *fs, expdesc *t, expdesc *k) { · 362 unmodified lines
746750 }
747751
748752
749−static int constfolding (OpCode op, expdesc *e1, expdesc *e2) {
750− TValue v1, v2, res;
753+/*
754+** return false if folding can raise an error
755+*/
756+static int validop (int op, TValue *v1, TValue *v2) {
757+ lua_Number a, b;
751758 lua_Integer i;
752− if (!tonumeral(e1, &v1) || !tonumeral(e2, &v2))
759+ cast_void(a); cast_void(b); /* macro may not use its arguments */
760+ if (luai_numinvalidop(op, (cast_void(tonumber(v1, &a)), a),
761+ (cast_void(tonumber(v2, &b)), b)))
753762 return 0;
754− if (op == OP_IDIV &&
755− (!tointeger(&v1, &i) || !tointeger(&v2, &i) || i == 0))
756− return 0; /* avoid division by 0 and conversion errors */
757− if (op == OP_MOD && ttisinteger(&v1) && ttisinteger(&v2) && ivalue(&v2) == 0)
758− return 0; /* avoid module by 0 at compile time */
759− luaO_arith(NULL, op - OP_ADD + LUA_OPADD, &v1, &v2, &res);
763+ switch (op) {
764+ case LUA_OPIDIV: /* division by 0 and conversion errors */
765+ return (tointeger(v1, &i) && tointeger(v2, &i) && i != 0);
766+ case LUA_OPBAND: case LUA_OPBOR: case LUA_OPBXOR:
767+ case LUA_OPSHL: case LUA_OPSHR: case LUA_OPBNOT: /* conversion errors */
768+ return (tointeger(v1, &i) && tointeger(v2, &i));
769+ case LUA_OPMOD: /* integer module by 0 */
770+ return !(ttisinteger(v1) && ttisinteger(v2) && ivalue(v2) == 0);
771+ case LUA_OPPOW: /* negative integer exponentiation */
772+ return !(ttisinteger(v1) && ttisinteger(v2) && ivalue(v2) < 0);
773+ default: return 1; /* everything else is valid */
774+ }
775+}
776+
777+
778+/*
779+** Try to "constant-fold" an operation; return 1 iff successful
780+*/
781+static int constfolding (FuncState *fs, int op, expdesc *e1, expdesc *e2) {
782+ TValue v1, v2, res;
783+ if (!tonumeral(e1, &v1) || !tonumeral(e2, &v2) || !validop(op, &v1, &v2))
784+ return 0; /* non-numeric operands or not safe to fold */
785+ luaO_arith(fs->ls->L, op, &v1, &v2, &res);
760786 if (ttisinteger(&res)) {
761787 e1->k = VKINT;
762788 e1->u.ival = ivalue(&res);
763789 }
764790 else {
765791 lua_Number n = fltvalue(&res);
766− if (luai_numisnan(NULL, n) || isminuszero(n))
792+ if (luai_numisnan(n) || isminuszero(n))
767793 return 0; /* folds neither NaN nor -0 */
768794 e1->k = VKFLT;
769795 e1->u.nval = n;
@@ -774,9 +800,16 @@ static int constfolding (OpCode op, expdesc *e1, expdesc *e2) { · 4 unmodified lines
774800
775801 static void codearith (FuncState *fs, OpCode op,
776802 expdesc *e1, expdesc *e2, int line) {
777− if (!constfolding(op, e1, e2)) { /* could not fold operation? */
778− int o2 = (op != OP_UNM && op != OP_LEN) ? luaK_exp2RK(fs, e2) : 0;
779− int o1 = luaK_exp2RK(fs, e1);
803+ if (!constfolding(fs, op - OP_ADD + LUA_OPADD, e1, e2)) {
804+ int o1, o2;
805+ if (op == OP_UNM || op == OP_BNOT || op == OP_LEN) {
806+ o2 = 0;
807+ o1 = luaK_exp2anyreg(fs, e1); /* cannot operate on constants */
808+ }
809+ else { /* regular case (binary operators) */
810+ o2 = luaK_exp2RK(fs, e2);
811+ o1 = luaK_exp2RK(fs, e1);
812+ }
780813 if (o1 > o2) {
781814 freeexp(fs, e1);
782815 freeexp(fs, e2);
@@ -810,21 +843,13 @@ static void codecomp (FuncState *fs, OpCode op, int cond, expdesc *e1, · 27 unmodified lines
810843
811844 void luaK_prefix (FuncState *fs, UnOpr op, expdesc *e, int line) {
812845 expdesc e2;
813− e2.t = e2.f = NO_JUMP; e2.k = VKFLT; e2.u.nval = 0;
846+ e2.t = e2.f = NO_JUMP; e2.k = VKINT; e2.u.ival = 0;
814847 switch (op) {
815− case OPR_MINUS: {
816− if (!constfolding(OP_UNM, e, e)) { /* cannot fold it? */
817− luaK_exp2anyreg(fs, e);
818− codearith(fs, OP_UNM, e, &e2, line);
819− }
848+ case OPR_MINUS: case OPR_BNOT: case OPR_LEN: {
849+ codearith(fs, cast(OpCode, (op - OPR_MINUS) + OP_UNM), e, &e2, line);
820850 break;
821851 }
822852 case OPR_NOT: codenot(fs, e); break;
823− case OPR_LEN: {
824− luaK_exp2anyreg(fs, e); /* cannot operate on constants */
825− codearith(fs, OP_LEN, e, &e2, line);
826− break;
827− }
828853 default: lua_assert(0);
829854 }
830855 }
@@ -846,7 +871,9 @@ void luaK_infix (FuncState *fs, BinOpr op, expdesc *v) { · 15 unmodified lines
846871 }
847872 case OPR_ADD: case OPR_SUB:
848873 case OPR_MUL: case OPR_DIV: case OPR_IDIV:
849− case OPR_MOD: case OPR_POW: {
874+ case OPR_MOD: case OPR_POW:
875+ case OPR_BAND: case OPR_BOR: case OPR_BXOR:
876+ case OPR_SHL: case OPR_SHR: {
850877 if (!tonumeral(v, NULL)) luaK_exp2RK(fs, v);
851878 break;
852879 }
@@ -890,8 +917,10 @@ void luaK_posfix (FuncState *fs, BinOpr op, · 37 unmodified lines
890917 break;
891918 }
892919 case OPR_ADD: case OPR_SUB: case OPR_MUL: case OPR_DIV:
893− case OPR_IDIV: case OPR_MOD: case OPR_POW: {
894− codearith(fs, cast(OpCode, op - OPR_ADD + OP_ADD), e1, e2, line);
920+ case OPR_IDIV: case OPR_MOD: case OPR_POW:
921+ case OPR_BAND: case OPR_BOR: case OPR_BXOR:
922+ case OPR_SHL: case OPR_SHR: {
923+ codearith(fs, cast(OpCode, (op - OPR_ADD) + OP_ADD), e1, e2, line);
895924 break;
896925 }
897926 case OPR_EQ: case OPR_LT: case OPR_LE: {
src/lcode.h+7−3
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lcode.h,v 1.60 2013/04/26 13:07:53 roberto Exp $
2+** $Id: lcode.h,v 1.63 2013/12/30 20:47:58 roberto Exp $
33 ** Code generator for Lua
44 ** See Copyright Notice in lua.h
55 */
@@ -24,7 +24,11 @@ · 18 unmodified lines
2424 ** grep "ORDER OPR" if you change these enums (ORDER OP)
2525 */
2626 typedef enum BinOpr {
27− OPR_ADD, OPR_SUB, OPR_MUL, OPR_DIV, OPR_IDIV, OPR_MOD, OPR_POW,
27+ OPR_ADD, OPR_SUB, OPR_MUL, OPR_MOD, OPR_POW,
28+ OPR_DIV,
29+ OPR_IDIV,
30+ OPR_BAND, OPR_BOR, OPR_BXOR,
31+ OPR_SHL, OPR_SHR,
2832 OPR_CONCAT,
2933 OPR_EQ, OPR_LT, OPR_LE,
3034 OPR_NE, OPR_GT, OPR_GE,
@@ -33,7 +37,7 @@ typedef enum BinOpr { · 2 unmodified lines
3337 } BinOpr;
3438
3539
36−typedef enum UnOpr { OPR_MINUS, OPR_NOT, OPR_LEN, OPR_NOUNOPR } UnOpr;
40+typedef enum UnOpr { OPR_MINUS, OPR_BNOT, OPR_NOT, OPR_LEN, OPR_NOUNOPR } UnOpr;
3741
3842
3943 #define getcode(fs,e) ((fs)->f->code[(e)->u.info])
src/ldblib.c+3−7
@@ -1,5 +1,5 @@
11 /*
2−** $Id: ldblib.c,v 1.133 2013/06/25 19:37:00 roberto Exp $
2+** $Id: ldblib.c,v 1.137 2014/03/12 20:57:40 roberto Exp $
33 ** Interface from Lua to its debug API
44 ** See Copyright Notice in lua.h
55 */
@@ -69,11 +69,8 @@ static int db_getuservalue (lua_State *L) { · 63 unmodified lines
6969
7070
7171 static int db_setuservalue (lua_State *L) {
72− if (lua_type(L, 1) == LUA_TLIGHTUSERDATA)
73− luaL_argerror(L, 1, "full userdata expected, got light userdata");
7472 luaL_checktype(L, 1, LUA_TUSERDATA);
75− if (!lua_isnoneornil(L, 2))
76− luaL_checktype(L, 2, LUA_TTABLE);
73+ luaL_checkany(L, 2);
7774 lua_settop(L, 2);
7875 lua_setuservalue(L, 1);
7976 return 1;
@@ -273,8 +270,7 @@ static void hookf (lua_State *L, lua_Debug *ar) { · 193 unmodified lines
273270 {"call", "return", "line", "count", "tail call"};
274271 gethooktable(L);
275272 lua_pushthread(L);
276− lua_rawget(L, -2);
277− if (lua_isfunction(L, -1)) {
273+ if (lua_rawget(L, -2) == LUA_TFUNCTION) {
278274 lua_pushstring(L, hooknames[(int)ar->event]);
279275 if (ar->currentline >= 0)
280276 lua_pushinteger(L, ar->currentline);
src/ldebug.c+20−13
@@ -1,5 +1,5 @@
11 /*
2−** $Id: ldebug.c,v 2.95 2013/05/06 17:21:59 roberto Exp $
2+** $Id: ldebug.c,v 2.97 2013/12/09 14:21:10 roberto Exp $
33 ** Debug Interface
44 ** See Copyright Notice in lua.h
55 */
@@ -50,7 +50,7 @@ static int currentline (CallInfo *ci) { · 44 unmodified lines
5050 /*
5151 ** this function can be called asynchronous (e.g. during a signal)
5252 */
53−LUA_API int lua_sethook (lua_State *L, lua_Hook func, int mask, int count) {
53+LUA_API void lua_sethook (lua_State *L, lua_Hook func, int mask, int count) {
5454 if (func == NULL || mask == 0) { /* turn off hooks? */
5555 mask = 0;
5656 func = NULL;
@@ -61,7 +61,6 @@ LUA_API int lua_sethook (lua_State *L, lua_Hook func, int mask, int count) { · 4 unmodified lines
6161 L->basehookcount = count;
6262 resethookcount(L);
6363 L->hookmask = cast_byte(mask);
64− return 1;
6564 }
6665
6766
@@ -327,12 +326,20 @@ static void kname (Proto *p, int pc, int c, const char **name) { · 259 unmodified lines
327326 }
328327
329328
329+static int filterpc (int pc, int jmptarget) {
330+ if (pc < jmptarget) /* is code conditional (inside a jump)? */
331+ return -1; /* cannot know who sets that register */
332+ else return pc; /* current position sets that register */
333+}
334+
335+
330336 /*
331337 ** try to find last instruction before 'lastpc' that modified register 'reg'
332338 */
333339 static int findsetreg (Proto *p, int lastpc, int reg) {
334340 int pc;
335341 int setreg = -1; /* keep last instruction that changed 'reg' */
342+ int jmptarget = 0; /* any code before this address is conditional */
336343 for (pc = 0; pc < lastpc; pc++) {
337344 Instruction i = p->code[pc];
338345 OpCode op = GET_OPCODE(i);
@@ -341,33 +348,33 @@ static int findsetreg (Proto *p, int lastpc, int reg) { · 2 unmodified lines
341348 case OP_LOADNIL: {
342349 int b = GETARG_B(i);
343350 if (a <= reg && reg <= a + b) /* set registers from 'a' to 'a+b' */
344− setreg = pc;
351+ setreg = filterpc(pc, jmptarget);
345352 break;
346353 }
347354 case OP_TFORCALL: {
348− if (reg >= a + 2) setreg = pc; /* affect all regs above its base */
355+ if (reg >= a + 2) /* affect all regs above its base */
356+ setreg = filterpc(pc, jmptarget);
349357 break;
350358 }
351359 case OP_CALL:
352360 case OP_TAILCALL: {
353− if (reg >= a) setreg = pc; /* affect all registers above base */
361+ if (reg >= a) /* affect all registers above base */
362+ setreg = filterpc(pc, jmptarget);
354363 break;
355364 }
356365 case OP_JMP: {
357366 int b = GETARG_sBx(i);
358367 int dest = pc + 1 + b;
359368 /* jump is forward and do not skip `lastpc'? */
360− if (pc < dest && dest <= lastpc)
361− pc += b; /* do the jump */
362− break;
363− }
364− case OP_TEST: {
365− if (reg == a) setreg = pc; /* jumped code can change 'a' */
369+ if (pc < dest && dest <= lastpc) {
370+ if (dest > jmptarget)
371+ jmptarget = dest; /* update 'jmptarget' */
372+ }
366373 break;
367374 }
368375 default:
369376 if (testAMode(op) && reg == a) /* any instruction that set A */
370− setreg = pc;
377+ setreg = filterpc(pc, jmptarget);
371378 break;
372379 }
373380 }
src/ldebug.h+2−2
@@ -1,5 +1,5 @@
11 /*
2−** $Id: ldebug.h,v 2.10 2013/05/06 17:19:11 roberto Exp $
2+** $Id: ldebug.h,v 2.11 2014/02/25 14:31:16 roberto Exp $
33 ** Auxiliary functions from Debug Interface module
44 ** See Copyright Notice in lua.h
55 */
@@ -13,7 +13,7 @@ · 7 unmodified lines
1313
1414 #define pcRel(pc, p) (cast(int, (pc) - (p)->code) - 1)
1515
16−#define getfuncline(f,pc) (((f)->lineinfo) ? (f)->lineinfo[pc] : 0)
16+#define getfuncline(f,pc) (((f)->lineinfo) ? (f)->lineinfo[pc] : -1)
1717
1818 #define resethookcount(L) (L->hookcount = L->basehookcount)
1919
src/ldo.c+23−20
@@ -1,5 +1,5 @@
11 /*
2−** $Id: ldo.c,v 2.109 2013/04/19 21:05:04 roberto Exp $
2+** $Id: ldo.c,v 2.115 2014/03/21 13:52:33 roberto Exp $
33 ** Stack and Call structure of Lua
44 ** See Copyright Notice in lua.h
55 */
@@ -46,30 +46,33 @@ · 40 unmodified lines
4646 ** C++ code, with _longjmp/_setjmp when asked to use them, and with
4747 ** longjmp/setjmp otherwise.
4848 */
49−#if !defined(LUAI_THROW)
49+#if !defined(LUAI_THROW) /* { */
50+
51+#if defined(__cplusplus) && !defined(LUA_USE_LONGJMP) /* { */
5052
51−#if defined(__cplusplus) && !defined(LUA_USE_LONGJMP)
5253 /* C++ exceptions */
5354 #define LUAI_THROW(L,c) throw(c)
5455 #define LUAI_TRY(L,c,a) \
5556 try { a } catch(...) { if ((c)->status == 0) (c)->status = -1; }
5657 #define luai_jmpbuf int /* dummy variable */
5758
58−#elif defined(LUA_USE_ULONGJMP)
59−/* in Unix, try _longjmp/_setjmp (more efficient) */
59+#elif defined(LUA_USE_POSIX) /* }{ */
60+
61+/* in POSIX, try _longjmp/_setjmp (more efficient) */
6062 #define LUAI_THROW(L,c) _longjmp((c)->b, 1)
6163 #define LUAI_TRY(L,c,a) if (_setjmp((c)->b) == 0) { a }
6264 #define luai_jmpbuf jmp_buf
6365
64−#else
65−/* default handling with long jumps */
66+#else /* }{ */
67+
68+/* ANSI handling with long jumps */
6669 #define LUAI_THROW(L,c) longjmp((c)->b, 1)
6770 #define LUAI_TRY(L,c,a) if (setjmp((c)->b) == 0) { a }
6871 #define luai_jmpbuf jmp_buf
6972
70−#endif
73+#endif /* } */
7174
72−#endif
75+#endif /* } */
7376
7477
7578
@@ -141,10 +144,10 @@ int luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud) { · 65 unmodified lines
141144
142145 static void correctstack (lua_State *L, TValue *oldstack) {
143146 CallInfo *ci;
144− GCObject *up;
147+ UpVal *up;
145148 L->top = (L->top - oldstack) + L->stack;
146− for (up = L->openupval; up != NULL; up = up->gch.next)
147− gco2uv(up)->v = (gco2uv(up)->v - oldstack) + L->stack;
149+ for (up = L->openupval; up != NULL; up = up->u.open.next)
150+ up->v = (up->v - oldstack) + L->stack;
148151 for (ci = L->ci; ci != NULL; ci = ci->previous) {
149152 ci->top = (ci->top - oldstack) + L->stack;
150153 ci->func = (ci->func - oldstack) + L->stack;
@@ -206,7 +209,11 @@ void luaD_shrinkstack (lua_State *L) { · 55 unmodified lines
206209 int inuse = stackinuse(L);
207210 int goodsize = inuse + (inuse / 8) + 2*EXTRA_STACK;
208211 if (goodsize > LUAI_MAXSTACK) goodsize = LUAI_MAXSTACK;
209− if (inuse > LUAI_MAXSTACK || /* handling stack overflow? */
212+ if (L->stacksize > LUAI_MAXSTACK) /* was handling stack overflow? */
213+ luaE_freeCI(L); /* free all CIs (list grew because of an error) */
214+ else
215+ luaE_shrinkCI(L); /* shrink list */
216+ if (inuse > LUAI_MAXSTACK || /* still handling stack overflow? */
210217 goodsize >= L->stacksize) /* would grow instead of shrink? */
211218 condmovestack(L); /* don't change stack (change only for debugging) */
212219 else
@@ -534,6 +541,7 @@ static void resume (lua_State *L, void *ud) { · 321 unmodified lines
534541
535542 LUA_API int lua_resume (lua_State *L, lua_State *from, int nargs) {
536543 int status;
544+ int oldnny = L->nny; /* save 'nny' */
537545 lua_lock(L);
538546 luai_userstateresume(L, nargs);
539547 L->nCcalls = (from) ? from->nCcalls + 1 : 1;
@@ -555,7 +563,7 @@ LUA_API int lua_resume (lua_State *L, lua_State *from, int nargs) { · 15 unmodified lines
555563 }
556564 lua_assert(status == L->status);
557565 }
558− L->nny = 1; /* do not allow yields */
566+ L->nny = oldnny; /* restore 'nny' */
559567 L->nCcalls--;
560568 lua_assert(L->nCcalls == ((from) ? from->nCcalls : 0));
561569 lua_unlock(L);
@@ -637,7 +645,6 @@ static void checkmode (lua_State *L, const char *mode, const char *x) { · 75 unmodified lines
637645
638646
639647 static void f_parser (lua_State *L, void *ud) {
640− int i;
641648 Closure *cl;
642649 struct SParser *p = cast(struct SParser *, ud);
643650 int c = zgetc(p->z); /* read first character */
@@ -650,11 +657,7 @@ static void f_parser (lua_State *L, void *ud) { · 6 unmodified lines
650657 cl = luaY_parser(L, p->z, &p->buff, &p->dyd, p->name, c);
651658 }
652659 lua_assert(cl->l.nupvalues == cl->l.p->sizeupvalues);
653− for (i = 0; i < cl->l.nupvalues; i++) { /* initialize upvalues */
654− UpVal *up = luaF_newupval(L);
655− cl->l.upvals[i] = up;
656− luaC_objbarrier(L, cl, up);
657− }
660+ luaF_initupvals(L, &cl->l);
658661 }
659662
660663
src/ldump.c+154−133
@@ -1,5 +1,5 @@
11 /*
2−** $Id: ldump.c,v 2.19 2013/04/26 18:48:35 roberto Exp $
2+** $Id: ldump.c,v 2.27 2014/03/11 18:56:27 roberto Exp $
33 ** save precompiled Lua chunks
44 ** See Copyright Notice in lua.h
55 */
@@ -15,167 +15,188 @@ · 9 unmodified lines
1515 #include "lstate.h"
1616 #include "lundump.h"
1717
18+
1819 typedef struct {
19− lua_State* L;
20− lua_Writer writer;
21− void* data;
22− int strip;
23− int status;
20+ lua_State *L;
21+ lua_Writer writer;
22+ void *data;
23+ int strip;
24+ int status;
2425 } DumpState;
2526
26−#define DumpMem(b,n,size,D) DumpBlock(b,(n)*(size),D)
27−#define DumpVar(x,D) DumpMem(&x,1,sizeof(x),D)
28−
29−static void DumpBlock(const void* b, size_t size, DumpState* D)
30−{
31− if (D->status==0)
32− {
33− lua_unlock(D->L);
34− D->status=(*D->writer)(D->L,b,size,D->data);
35− lua_lock(D->L);
36− }
27+
28+/*
29+** All high-level dumps go through DumpVector; you can change it to
30+** change the endianess of the result
31+*/
32+#define DumpVector(v,n,D) DumpBlock(v,(n)*sizeof((v)[0]),D)
33+
34+#define DumpLiteral(s,D) DumpBlock(s, sizeof(s) - sizeof(char), D)
35+
36+
37+static void DumpBlock (const void *b, size_t size, DumpState *D) {
38+ if (D->status == 0) {
39+ lua_unlock(D->L);
40+ D->status = (*D->writer)(D->L, b, size, D->data);
41+ lua_lock(D->L);
42+ }
3743 }
3844
39−static void DumpChar(int y, DumpState* D)
40−{
41− char x=(char)y;
42− DumpVar(x,D);
45+
46+#define DumpVar(x,D) DumpVector(&x,1,D)
47+
48+
49+static void DumpByte (int y, DumpState *D) {
50+ lu_byte x = (lu_byte)y;
51+ DumpVar(x, D);
4352 }
4453
45−static void DumpInt(int x, DumpState* D)
46−{
47− DumpVar(x,D);
54+
55+static void DumpInt (int x, DumpState *D) {
56+ DumpVar(x, D);
4857 }
4958
50−static void DumpNumber(lua_Number x, DumpState* D)
51−{
52− DumpVar(x,D);
59+
60+static void DumpNumber (lua_Number x, DumpState *D) {
61+ DumpVar(x, D);
5362 }
5463
55−static void DumpInteger(lua_Integer x, DumpState* D)
56−{
57− DumpVar(x,D);
64+
65+static void DumpInteger (lua_Integer x, DumpState *D) {
66+ DumpVar(x, D);
5867 }
5968
60−static void DumpVector(const void* b, int n, size_t size, DumpState* D)
61−{
62− DumpInt(n,D);
63− DumpMem(b,n,size,D);
69+
70+static void DumpString (const TString *s, DumpState *D) {
71+ if (s == NULL)
72+ DumpByte(0, D);
73+ else {
74+ size_t size = s->tsv.len + 1; /* include trailing '\0' */
75+ if (size < 0xFF)
76+ DumpByte(size, D);
77+ else {
78+ DumpByte(0xFF, D);
79+ DumpVar(size, D);
80+ }
81+ DumpVector(getstr(s), size - 1, D); /* no need to save '\0' */
82+ }
6483 }
6584
66−static void DumpString(const TString* s, DumpState* D)
67−{
68− if (s==NULL)
69− {
70− size_t size=0;
71− DumpVar(size,D);
72− }
73− else
74− {
75− size_t size=s->tsv.len+1; /* include trailing '\0' */
76− DumpVar(size,D);
77− DumpBlock(getstr(s),size*sizeof(char),D);
78− }
85+
86+static void DumpCode (const Proto *f, DumpState *D) {
87+ DumpInt(f->sizecode, D);
88+ DumpVector(f->code, f->sizecode, D);
7989 }
8090
81−#define DumpCode(f,D) DumpVector(f->code,f->sizecode,sizeof(Instruction),D)
82−
83−static void DumpFunction(const Proto* f, DumpState* D);
84−
85−static void DumpConstants(const Proto* f, DumpState* D)
86−{
87− int i,n=f->sizek;
88− DumpInt(n,D);
89− for (i=0; i<n; i++)
90− {
91− const TValue* o=&f->k[i];
92− DumpChar(ttype(o),D);
93− switch (ttype(o))
94− {
95− case LUA_TNIL:
96− break;
97− case LUA_TBOOLEAN:
98− DumpChar(bvalue(o),D);
99− break;
100− case LUA_TNUMFLT:
101− DumpNumber(fltvalue(o),D);
102− break;
103− case LUA_TNUMINT:
104− DumpInteger(ivalue(o),D);
105− break;
106− case LUA_TSHRSTR: case LUA_TLNGSTR:
107− DumpString(rawtsvalue(o),D);
108− break;
109− default: lua_assert(0);
91+
92+static void DumpFunction(const Proto *f, DumpState *D);
93+
94+static void DumpConstants (const Proto *f, DumpState *D) {
95+ int i;
96+ int n = f->sizek;
97+ DumpInt(n, D);
98+ for (i = 0; i < n; i++) {
99+ const TValue *o = &f->k[i];
100+ DumpByte(ttype(o), D);
101+ switch (ttype(o)) {
102+ case LUA_TNIL:
103+ break;
104+ case LUA_TBOOLEAN:
105+ DumpByte(bvalue(o), D);
106+ break;
107+ case LUA_TNUMFLT:
108+ DumpNumber(fltvalue(o), D);
109+ break;
110+ case LUA_TNUMINT:
111+ DumpInteger(ivalue(o), D);
112+ break;
113+ case LUA_TSHRSTR:
114+ case LUA_TLNGSTR:
115+ DumpString(rawtsvalue(o), D);
116+ break;
117+ default:
118+ lua_assert(0);
119+ }
110120 }
111− }
112− n=f->sizep;
113− DumpInt(n,D);
114− for (i=0; i<n; i++) DumpFunction(f->p[i],D);
121+ n = f->sizep;
122+ DumpInt(n, D);
123+ for (i = 0; i < n; i++)
124+ DumpFunction(f->p[i], D);
115125 }
116126
117−static void DumpUpvalues(const Proto* f, DumpState* D)
118−{
119− int i,n=f->sizeupvalues;
120− DumpInt(n,D);
121− for (i=0; i<n; i++)
122− {
123− DumpChar(f->upvalues[i].instack,D);
124− DumpChar(f->upvalues[i].idx,D);
125− }
127+
128+static void DumpUpvalues (const Proto *f, DumpState *D) {
129+ int i, n = f->sizeupvalues;
130+ DumpInt(n, D);
131+ for (i = 0; i < n; i++) {
132+ DumpByte(f->upvalues[i].instack, D);
133+ DumpByte(f->upvalues[i].idx, D);
134+ }
126135 }
127136
128−static void DumpDebug(const Proto* f, DumpState* D)
129−{
130− int i,n;
131− DumpString((D->strip) ? NULL : f->source,D);
132− n= (D->strip) ? 0 : f->sizelineinfo;
133− DumpVector(f->lineinfo,n,sizeof(int),D);
134− n= (D->strip) ? 0 : f->sizelocvars;
135− DumpInt(n,D);
136− for (i=0; i<n; i++)
137− {
138− DumpString(f->locvars[i].varname,D);
139− DumpInt(f->locvars[i].startpc,D);
140− DumpInt(f->locvars[i].endpc,D);
141− }
142− n= (D->strip) ? 0 : f->sizeupvalues;
143− DumpInt(n,D);
144− for (i=0; i<n; i++) DumpString(f->upvalues[i].name,D);
137+
138+static void DumpDebug (const Proto *f, DumpState *D) {
139+ int i, n;
140+ DumpString((D->strip) ? NULL : f->source, D);
141+ n = (D->strip) ? 0 : f->sizelineinfo;
142+ DumpInt(n, D);
143+ DumpVector(f->lineinfo, n, D);
144+ n = (D->strip) ? 0 : f->sizelocvars;
145+ DumpInt(n, D);
146+ for (i = 0; i < n; i++) {
147+ DumpString(f->locvars[i].varname, D);
148+ DumpInt(f->locvars[i].startpc, D);
149+ DumpInt(f->locvars[i].endpc, D);
150+ }
151+ n = (D->strip) ? 0 : f->sizeupvalues;
152+ DumpInt(n, D);
153+ for (i = 0; i < n; i++)
154+ DumpString(f->upvalues[i].name, D);
145155 }
146156
147−static void DumpFunction(const Proto* f, DumpState* D)
148−{
149− DumpInt(f->linedefined,D);
150− DumpInt(f->lastlinedefined,D);
151− DumpChar(f->numparams,D);
152− DumpChar(f->is_vararg,D);
153− DumpChar(f->maxstacksize,D);
154− DumpCode(f,D);
155− DumpConstants(f,D);
156− DumpUpvalues(f,D);
157− DumpDebug(f,D);
157+
158+static void DumpFunction (const Proto *f, DumpState *D) {
159+ DumpInt(f->linedefined, D);
160+ DumpInt(f->lastlinedefined, D);
161+ DumpByte(f->numparams, D);
162+ DumpByte(f->is_vararg, D);
163+ DumpByte(f->maxstacksize, D);
164+ DumpCode(f, D);
165+ DumpConstants(f, D);
166+ DumpUpvalues(f, D);
167+ DumpDebug(f, D);
158168 }
159169
160−static void DumpHeader(DumpState* D)
161−{
162− lu_byte h[LUAC_HEADERSIZE];
163− luaU_header(h);
164− DumpBlock(h,LUAC_HEADERSIZE,D);
170+
171+static void DumpHeader (DumpState *D) {
172+ DumpLiteral(LUA_SIGNATURE, D);
173+ DumpByte(LUAC_VERSION, D);
174+ DumpByte(LUAC_FORMAT, D);
175+ DumpLiteral(LUAC_DATA, D);
176+ DumpByte(sizeof(int), D);
177+ DumpByte(sizeof(size_t), D);
178+ DumpByte(sizeof(Instruction), D);
179+ DumpByte(sizeof(lua_Integer), D);
180+ DumpByte(sizeof(lua_Number), D);
181+ DumpInteger(LUAC_INT, D);
182+ DumpNumber(LUAC_NUM, D);
165183 }
166184
185+
167186 /*
168187 ** dump Lua function as precompiled chunk
169188 */
170−int luaU_dump (lua_State* L, const Proto* f, lua_Writer w, void* data, int strip)
171−{
172− DumpState D;
173− D.L=L;
174− D.writer=w;
175− D.data=data;
176− D.strip=strip;
177− D.status=0;
178− DumpHeader(&D);
179− DumpFunction(f,&D);
180− return D.status;
189+int luaU_dump(lua_State *L, const Proto *f, lua_Writer w, void *data,
190+ int strip) {
191+ DumpState D;
192+ D.L = L;
193+ D.writer = w;
194+ D.data = data;
195+ D.strip = strip;
196+ D.status = 0;
197+ DumpHeader(&D);
198+ DumpByte(f->sizeupvalues, &D);
199+ DumpFunction(f, &D);
200+ return D.status;
181201 }
202+
src/lfunc.c+39−54
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lfunc.c,v 2.30 2012/10/03 12:36:46 roberto Exp $
2+** $Id: lfunc.c,v 2.41 2014/02/18 13:39:37 roberto Exp $
33 ** Auxiliary functions to manipulate prototypes and closures
44 ** See Copyright Notice in lua.h
55 */
@@ -21,94 +21,79 @@ · 15 unmodified lines
2121
2222
2323 Closure *luaF_newCclosure (lua_State *L, int n) {
24− Closure *c = &luaC_newobj(L, LUA_TCCL, sizeCclosure(n), NULL, 0)->cl;
24+ Closure *c = &luaC_newobj(L, LUA_TCCL, sizeCclosure(n))->cl;
2525 c->c.nupvalues = cast_byte(n);
2626 return c;
2727 }
2828
2929
3030 Closure *luaF_newLclosure (lua_State *L, int n) {
31− Closure *c = &luaC_newobj(L, LUA_TLCL, sizeLclosure(n), NULL, 0)->cl;
31+ Closure *c = &luaC_newobj(L, LUA_TLCL, sizeLclosure(n))->cl;
3232 c->l.p = NULL;
3333 c->l.nupvalues = cast_byte(n);
3434 while (n--) c->l.upvals[n] = NULL;
3535 return c;
3636 }
3737
38−
39−UpVal *luaF_newupval (lua_State *L) {
40− UpVal *uv = &luaC_newobj(L, LUA_TUPVAL, sizeof(UpVal), NULL, 0)->uv;
41− uv->v = &uv->u.value;
42− setnilvalue(uv->v);
43− return uv;
38+/*
39+** fill a closure with new closed upvalues
40+*/
41+void luaF_initupvals (lua_State *L, LClosure *cl) {
42+ int i;
43+ for (i = 0; i < cl->nupvalues; i++) {
44+ UpVal *uv = luaM_new(L, UpVal);
45+ uv->refcount = 1;
46+ uv->v = &uv->u.value; /* make it closed */
47+ setnilvalue(uv->v);
48+ cl->upvals[i] = uv;
49+ }
4450 }
4551
4652
4753 UpVal *luaF_findupval (lua_State *L, StkId level) {
48− global_State *g = G(L);
49− GCObject **pp = &L->openupval;
54+ UpVal **pp = &L->openupval;
5055 UpVal *p;
5156 UpVal *uv;
52− while (*pp != NULL && (p = gco2uv(*pp))->v >= level) {
53− GCObject *o = obj2gco(p);
54− lua_assert(p->v != &p->u.value);
55− lua_assert(!isold(o) || isold(obj2gco(L)));
56− if (p->v == level) { /* found a corresponding upvalue? */
57− if (isdead(g, o)) /* is it dead? */
58− changewhite(o); /* resurrect it */
59− return p;
60− }
61− pp = &p->next;
57+ lua_assert(isintwups(L) || L->openupval == NULL);
58+ while (*pp != NULL && (p = *pp)->v >= level) {
59+ lua_assert(upisopen(p));
60+ if (p->v == level) /* found a corresponding upvalue? */
61+ return p; /* return it */
62+ pp = &p->u.open.next;
6263 }
63− /* not found: create a new one */
64− uv = &luaC_newobj(L, LUA_TUPVAL, sizeof(UpVal), pp, 0)->uv;
64+ /* not found: create a new upvalue */
65+ uv = luaM_new(L, UpVal);
66+ uv->refcount = 0;
67+ uv->u.open.next = *pp; /* link it to list of open upvalues */
68+ uv->u.open.touched = 1;
69+ *pp = uv;
6570 uv->v = level; /* current value lives in the stack */
66− uv->u.l.prev = &g->uvhead; /* double link it in `uvhead' list */
67− uv->u.l.next = g->uvhead.u.l.next;
68− uv->u.l.next->u.l.prev = uv;
69− g->uvhead.u.l.next = uv;
70− lua_assert(uv->u.l.next->u.l.prev == uv && uv->u.l.prev->u.l.next == uv);
71+ if (!isintwups(L)) { /* thread not in list of threads with upvalues? */
72+ L->twups = G(L)->twups; /* link it to the list */
73+ G(L)->twups = L;
74+ }
7175 return uv;
7276 }
7377
7478
75−static void unlinkupval (UpVal *uv) {
76− lua_assert(uv->u.l.next->u.l.prev == uv && uv->u.l.prev->u.l.next == uv);
77− uv->u.l.next->u.l.prev = uv->u.l.prev; /* remove from `uvhead' list */
78− uv->u.l.prev->u.l.next = uv->u.l.next;
79−}
80−
81−
82−void luaF_freeupval (lua_State *L, UpVal *uv) {
83− if (uv->v != &uv->u.value) /* is it open? */
84− unlinkupval(uv); /* remove from open list */
85− luaM_free(L, uv); /* free upvalue */
86−}
87−
88−
8979 void luaF_close (lua_State *L, StkId level) {
9080 UpVal *uv;
91− global_State *g = G(L);
92− while (L->openupval != NULL && (uv = gco2uv(L->openupval))->v >= level) {
93− GCObject *o = obj2gco(uv);
94− lua_assert(!isblack(o) && uv->v != &uv->u.value);
95− L->openupval = uv->next; /* remove from `open' list */
96− if (isdead(g, o))
97− luaF_freeupval(L, uv); /* free upvalue */
81+ while (L->openupval != NULL && (uv = L->openupval)->v >= level) {
82+ lua_assert(upisopen(uv));
83+ L->openupval = uv->u.open.next; /* remove from `open' list */
84+ if (uv->refcount == 0) /* no references? */
85+ luaM_free(L, uv); /* free upvalue */
9886 else {
99− unlinkupval(uv); /* remove upvalue from 'uvhead' list */
10087 setobj(L, &uv->u.value, uv->v); /* move value to upvalue slot */
10188 uv->v = &uv->u.value; /* now current value lives here */
102− gch(o)->next = g->allgc; /* link upvalue into 'allgc' list */
103− g->allgc = o;
104− luaC_checkupvalcolor(g, uv);
89+ luaC_upvalbarrier(L, uv);
10590 }
10691 }
10792 }
10893
10994
11095 Proto *luaF_newproto (lua_State *L) {
111− Proto *f = &luaC_newobj(L, LUA_TPROTO, sizeof(Proto), NULL, 0)->p;
96+ Proto *f = &luaC_newobj(L, LUA_TPROTO, sizeof(Proto))->p;
11297 f->k = NULL;
11398 f->sizek = 0;
11499 f->p = NULL;
src/lfunc.h+24−3
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lfunc.h,v 2.8 2012/05/08 13:53:33 roberto Exp $
2+** $Id: lfunc.h,v 2.13 2014/02/18 13:39:37 roberto Exp $
33 ** Auxiliary functions to manipulate prototypes and closures
44 ** See Copyright Notice in lua.h
55 */
@@ -18,14 +18,35 @@ · 12 unmodified lines
1818 cast(int, sizeof(TValue *)*((n)-1)))
1919
2020
21+/* test whether thread is in 'twups' list */
22+#define isintwups(L) (L->twups != L)
23+
24+
25+/*
26+** Upvalues for Lua closures
27+*/
28+struct UpVal {
29+ TValue *v; /* points to stack or to its own value */
30+ lu_mem refcount; /* reference counter */
31+ union {
32+ struct { /* (when open) */
33+ UpVal *next; /* linked list */
34+ int touched; /* mark to avoid cycles with dead threads */
35+ } open;
36+ TValue value; /* the value (when closed) */
37+ } u;
38+};
39+
40+#define upisopen(up) ((up)->v != &(up)->u.value)
41+
42+
2143 LUAI_FUNC Proto *luaF_newproto (lua_State *L);
2244 LUAI_FUNC Closure *luaF_newCclosure (lua_State *L, int nelems);
2345 LUAI_FUNC Closure *luaF_newLclosure (lua_State *L, int nelems);
24−LUAI_FUNC UpVal *luaF_newupval (lua_State *L);
46+LUAI_FUNC void luaF_initupvals (lua_State *L, LClosure *cl);
2547 LUAI_FUNC UpVal *luaF_findupval (lua_State *L, StkId level);
2648 LUAI_FUNC void luaF_close (lua_State *L, StkId level);
2749 LUAI_FUNC void luaF_freeproto (lua_State *L, Proto *f);
28−LUAI_FUNC void luaF_freeupval (lua_State *L, UpVal *uv);
2950 LUAI_FUNC const char *luaF_getlocalname (const Proto *func, int local_number,
3051 int pc);
3152
src/lgc.c+287−336
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lgc.c,v 2.141 2013/04/26 18:26:49 roberto Exp $
2+** $Id: lgc.c,v 2.179 2014/03/21 13:52:33 roberto Exp $
33 ** Garbage Collector
44 ** See Copyright Notice in lua.h
55 */
@@ -23,6 +23,11 @@ · 17 unmodified lines
2323 #include "ltm.h"
2424
2525
26+/*
27+** internal state for collector while inside the atomic phase. The
28+** collector should never be in this state while running regular code.
29+*/
30+#define GCSinsideatomic (GCSpause + 1)
2631
2732 /*
2833 ** cost of sweeping one element (the size of a small object divided
@@ -33,8 +38,8 @@ · 4 unmodified lines
3338 /* maximum number of elements to sweep in each single step */
3439 #define GCSWEEPMAX (cast_int((GCSTEPSIZE / GCSWEEPCOST) / 4))
3540
36−/* maximum number of finalizers to call in each GC step */
37−#define GCFINALIZENUM 4
41+/* cost of calling one finalizer */
42+#define GCFINALIZECOST GCSWEEPCOST
3843
3944
4045 /*
@@ -52,10 +57,10 @@ · 11 unmodified lines
5257
5358
5459 /*
55−** 'makewhite' erases all color bits plus the old bit and then
56−** sets only the current white bit
60+** 'makewhite' erases all color bits then sets only the current white
61+** bit
5762 */
58−#define maskcolors (~(bit2mask(BLACKBIT, OLDBIT) | WHITEBITS))
63+#define maskcolors (~(bitmask(BLACKBIT) | WHITEBITS))
5964 #define makewhite(g,x) \
6065 (gch(x)->marked = cast_byte((gch(x)->marked & maskcolors) | luaC_white(g)))
6166
@@ -63,7 +68,7 @@ · 1 unmodified line
6368 #define black2gray(x) resetbit(gch(x)->marked, BLACKBIT)
6469
6570
66−#define isfinalized(x) testbit(gch(x)->marked, FINALIZEDBIT)
71+#define valiswhite(x) (iscollectable(x) && iswhite(gcvalue(x)))
6772
6873 #define checkdeadkey(n) lua_assert(!ttisdeadkey(gkey(n)) || ttisnil(gval(n)))
6974
@@ -75,8 +80,8 @@ · 5 unmodified lines
7580 #define markvalue(g,o) { checkconsistency(o); \
7681 if (valiswhite(o)) reallymarkobject(g,gcvalue(o)); }
7782
78−#define markobject(g,t) { if ((t) && iswhite(obj2gco(t))) \
79− reallymarkobject(g, obj2gco(t)); }
83+#define markobject(g,t) \
84+ { if ((t) && iswhite(obj2gco(t))) reallymarkobject(g, obj2gco(t)); }
8085
8186 static void reallymarkobject (global_State *g, GCObject *o);
8287
@@ -136,8 +141,8 @@ void luaC_barrier_ (lua_State *L, GCObject *o, GCObject *v) { · 53 unmodified lines
136141 global_State *g = G(L);
137142 lua_assert(isblack(o) && iswhite(v) && !isdead(g, v) && !isdead(g, o));
138143 lua_assert(g->gcstate != GCSpause);
139− lua_assert(gch(o)->tt != LUA_TTABLE);
140− if (keepinvariantout(g)) /* must keep invariant? */
144+ lua_assert(gch(o)->tt != LUA_TTABLE); /* tables use a back barrier */
145+ if (keepinvariant(g)) /* must keep invariant? */
141146 reallymarkobject(g, v); /* restore invariant */
142147 else { /* sweep phase */
143148 lua_assert(issweepphase(g));
@@ -162,64 +167,41 @@ void luaC_barrierback_ (lua_State *L, GCObject *o) { · 18 unmodified lines
162167
163168
164169 /*
165−** barrier for prototypes. When creating first closure (cache is
166−** NULL), use a forward barrier; this may be the only closure of the
167−** prototype (if it is a "regular" function, with a single instance)
168−** and the prototype may be big, so it is better to avoid traversing
169−** it again. Otherwise, use a backward barrier, to avoid marking all
170−** possible instances.
170+** barrier for assignments to closed upvalues. Because upvalues are
171+** shared among closures, it is impossible to know the color of all
172+** closures pointing to it. So, we assume that the object being assigned
173+** must be marked.
171174 */
172−LUAI_FUNC void luaC_barrierproto_ (lua_State *L, Proto *p, Closure *c) {
175+LUAI_FUNC void luaC_upvalbarrier_ (lua_State *L, UpVal *uv) {
173176 global_State *g = G(L);
174− lua_assert(isblack(obj2gco(p)));
175− if (p->cache == NULL) { /* first time? */
176− luaC_objbarrier(L, p, c);
177− }
178− else { /* use a backward barrier */
179− black2gray(obj2gco(p)); /* make prototype gray (again) */
180− p->gclist = g->grayagain;
181− g->grayagain = obj2gco(p);
182− }
177+ GCObject *o = gcvalue(uv->v);
178+ lua_assert(!upisopen(uv)); /* ensured by macro luaC_upvalbarrier */
179+ if (keepinvariant(g))
180+ markobject(g, o);
183181 }
184182
185183
186−/*
187−** check color (and invariants) for an upvalue that was closed,
188−** i.e., moved into the 'allgc' list
189−*/
190−void luaC_checkupvalcolor (global_State *g, UpVal *uv) {
191− GCObject *o = obj2gco(uv);
192− lua_assert(!isblack(o)); /* open upvalues are never black */
193− if (isgray(o)) {
194− if (keepinvariant(g)) {
195− resetoldbit(o); /* see MOVE OLD rule */
196− gray2black(o); /* it is being visited now */
197− markvalue(g, uv->v);
198− }
199− else {
200− lua_assert(issweepphase(g));
201− makewhite(g, o);
202− }
203− }
184+void luaC_fix (lua_State *L, GCObject *o) {
185+ global_State *g = G(L);
186+ lua_assert(g->allgc == o); /* object must be 1st in 'allgc' list! */
187+ white2gray(o); /* they will be gray forever */
188+ g->allgc = o->gch.next; /* remove object from 'allgc' list */
189+ o->gch.next = g->fixedgc; /* link it to 'fixedgc' list */
190+ g->fixedgc = o;
204191 }
205192
206193
207194 /*
208195 ** create a new collectable object (with given type and size) and link
209−** it to '*list'. 'offset' tells how many bytes to allocate before the
210−** object itself (used only by states).
196+** it to 'allgc' list.
211197 */
212−GCObject *luaC_newobj (lua_State *L, int tt, size_t sz, GCObject **list,
213− int offset) {
198+GCObject *luaC_newobj (lua_State *L, int tt, size_t sz) {
214199 global_State *g = G(L);
215− char *raw = cast(char *, luaM_newobject(L, novariant(tt), sz));
216− GCObject *o = obj2gco(raw + offset);
217− if (list == NULL)
218− list = &g->allgc; /* standard list for collectable objects */
200+ GCObject *o = cast(GCObject *, luaM_newobject(L, novariant(tt), sz));
219201 gch(o)->marked = luaC_white(g);
220202 gch(o)->tt = tt;
221− gch(o)->next = *list;
222− *list = o;
203+ gch(o)->next = g->allgc;
204+ g->allgc = o;
223205 return o;
224206 }
225207
@@ -241,57 +223,53 @@ GCObject *luaC_newobj (lua_State *L, int tt, size_t sz, GCObject **list, · 15 unmodified lines
241223 ** upvalues are already linked in 'headuv' list.)
242224 */
243225 static void reallymarkobject (global_State *g, GCObject *o) {
244− lu_mem size;
226+ reentry:
245227 white2gray(o);
246228 switch (gch(o)->tt) {
247229 case LUA_TSHRSTR:
248230 case LUA_TLNGSTR: {
249− size = sizestring(gco2ts(o));
250− break; /* nothing else to mark; make it black */
251− }
252− case LUA_TUSERDATA: {
253− Table *mt = gco2u(o)->metatable;
254− markobject(g, mt);
255− markobject(g, gco2u(o)->env);
256− size = sizeudata(gco2u(o));
231+ gray2black(o);
232+ g->GCmemtrav += sizestring(gco2ts(o));
257233 break;
258234 }
259− case LUA_TUPVAL: {
260− UpVal *uv = gco2uv(o);
261− markvalue(g, uv->v);
262− if (uv->v != &uv->u.value) /* open? */
263− return; /* open upvalues remain gray */
264− size = sizeof(UpVal);
235+ case LUA_TUSERDATA: {
236+ TValue uvalue;
237+ markobject(g, gco2u(o)->metatable); /* mark its metatable */
238+ gray2black(o);
239+ g->GCmemtrav += sizeudata(gco2u(o));
240+ getuservalue(g->mainthread, rawgco2u(o), &uvalue);
241+ if (valiswhite(&uvalue)) { /* markvalue(g, &uvalue); */
242+ o = gcvalue(&uvalue);
243+ goto reentry;
244+ }
265245 break;
266246 }
267247 case LUA_TLCL: {
268248 gco2lcl(o)->gclist = g->gray;
269249 g->gray = o;
270− return;
250+ break;
271251 }
272252 case LUA_TCCL: {
273253 gco2ccl(o)->gclist = g->gray;
274254 g->gray = o;
275− return;
255+ break;
276256 }
277257 case LUA_TTABLE: {
278258 linktable(gco2t(o), &g->gray);
279− return;
259+ break;
280260 }
281261 case LUA_TTHREAD: {
282262 gco2th(o)->gclist = g->gray;
283263 g->gray = o;
284− return;
264+ break;
285265 }
286266 case LUA_TPROTO: {
287267 gco2p(o)->gclist = g->gray;
288268 g->gray = o;
289− return;
269+ break;
290270 }
291− default: lua_assert(0); return;
271+ default: lua_assert(0); break;
292272 }
293− gray2black(o);
294− g->GCmemtrav += size;
295273 }
296274
297275
@@ -310,29 +288,41 @@ static void markmt (global_State *g) { · 12 unmodified lines
310288 */
311289 static void markbeingfnz (global_State *g) {
312290 GCObject *o;
313− for (o = g->tobefnz; o != NULL; o = gch(o)->next) {
314− makewhite(g, o);
315− reallymarkobject(g, o);
316− }
291+ for (o = g->tobefnz; o != NULL; o = gch(o)->next)
292+ markobject(g, o);
317293 }
318294
319295
320296 /*
321−** mark all values stored in marked open upvalues. (See comment in
322−** 'lstate.h'.)
297+** Mark all values stored in marked open upvalues from non-marked threads.
298+** (Values from marked threads were already marked when traversing the
299+** thread.) Remove from the list threads that no longer have upvalues and
300+** not-marked threads.
323301 */
324302 static void remarkupvals (global_State *g) {
325− UpVal *uv;
326− for (uv = g->uvhead.u.l.next; uv != &g->uvhead; uv = uv->u.l.next) {
327− if (isgray(obj2gco(uv)))
328− markvalue(g, uv->v);
303+ lua_State *thread;
304+ lua_State **p = &g->twups;
305+ while ((thread = *p) != NULL) {
306+ lua_assert(!isblack(obj2gco(thread))); /* threads are never black */
307+ if (isgray(obj2gco(thread)) && thread->openupval != NULL)
308+ p = &thread->twups; /* keep marked thread with upvalues in the list */
309+ else { /* thread is not marked or without upvalues */
310+ UpVal *uv;
311+ *p = thread->twups; /* remove thread from the list */
312+ thread->twups = thread; /* mark that it is out of list */
313+ for (uv = thread->openupval; uv != NULL; uv = uv->u.open.next) {
314+ if (uv->u.open.touched) {
315+ markvalue(g, uv->v); /* remark upvalue's value */
316+ uv->u.open.touched = 0;
317+ }
318+ }
319+ }
329320 }
330321 }
331322
332323
333324 /*
334−** mark root set and reset all gray lists, to start a new
335−** incremental (or full) collection
325+** mark root set and reset all gray lists, to start a new collection
336326 */
337327 static void restartcollection (global_State *g) {
338328 g->gray = g->grayagain = NULL;
@@ -483,11 +473,24 @@ static lu_mem traverseCclosure (global_State *g, CClosure *cl) { · 144 unmodified lines
483473 return sizeCclosure(cl->nupvalues);
484474 }
485475
476+/*
477+** open upvalues point to values in a thread, so those values should
478+** be marked when the thread is traversed except in the atomic phase
479+** (because then the value cannot be changed by the thread and the
480+** thread may not be traversed again)
481+*/
486482 static lu_mem traverseLclosure (global_State *g, LClosure *cl) {
487483 int i;
488484 markobject(g, cl->p); /* mark its prototype */
489− for (i = 0; i < cl->nupvalues; i++) /* mark its upvalues */
490− markobject(g, cl->upvals[i]);
485+ for (i = 0; i < cl->nupvalues; i++) { /* mark its upvalues */
486+ UpVal *uv = cl->upvals[i];
487+ if (uv != NULL) {
488+ if (upisopen(uv) && g->gcstate != GCSinsideatomic)
489+ uv->u.open.touched = 1; /* can be marked in 'remarkupvals' */
490+ else
491+ markvalue(g, uv->v);
492+ }
493+ }
491494 return sizeLclosure(cl->nupvalues);
492495 }
493496
@@ -497,17 +500,27 @@ static lu_mem traversestack (global_State *g, lua_State *th) { · 3 unmodified lines
497500 StkId o = th->stack;
498501 if (o == NULL)
499502 return 1; /* stack not completely built yet */
503+ lua_assert(g->gcstate == GCSinsideatomic ||
504+ th->openupval == NULL || isintwups(th));
500505 for (; o < th->top; o++) /* mark live elements in the stack */
501506 markvalue(g, o);
502− if (g->gcstate == GCSatomic) { /* final traversal? */
507+ if (g->gcstate == GCSinsideatomic) { /* final traversal? */
503508 StkId lim = th->stack + th->stacksize; /* real end of stack */
504509 for (; o < lim; o++) /* clear not-marked stack slice */
505510 setnilvalue(o);
511+ /* 'remarkupvals' may have removed thread from 'twups' list */
512+ if (!isintwups(th) && th->openupval != NULL) {
513+ th->twups = g->twups; /* link it back to the list */
514+ g->twups = th;
515+ }
506516 }
507− else { /* count call infos to compute size */
517+ else {
508518 CallInfo *ci;
509519 for (ci = &th->base_ci; ci != th->ci; ci = ci->next)
510− n++;
520+ n++; /* count call infos to compute size */
521+ /* should not change the stack during an emergency gc cycle */
522+ if (g->gckind != KGC_EMERGENCY)
523+ luaD_shrinkstack(th);
511524 }
512525 return sizeof(lua_State) + sizeof(TValue) * th->stacksize +
513526 sizeof(CallInfo) * n;
@@ -660,23 +673,41 @@ static void clearvalues (global_State *g, GCObject *l, GCObject *f) { · 146 unmodified lines
660673 }
661674
662675
676+void luaC_upvdeccount (lua_State *L, UpVal *uv) {
677+ lua_assert(uv->refcount > 0);
678+ uv->refcount--;
679+ if (uv->refcount == 0 && !upisopen(uv))
680+ luaM_free(L, uv);
681+}
682+
683+
684+static void freeLclosure (lua_State *L, LClosure *cl) {
685+ int i;
686+ for (i = 0; i < cl->nupvalues; i++) {
687+ UpVal *uv = cl->upvals[i];
688+ if (uv)
689+ luaC_upvdeccount(L, uv);
690+ }
691+ luaM_freemem(L, cl, sizeLclosure(cl->nupvalues));
692+}
693+
694+
663695 static void freeobj (lua_State *L, GCObject *o) {
664696 switch (gch(o)->tt) {
665697 case LUA_TPROTO: luaF_freeproto(L, gco2p(o)); break;
666698 case LUA_TLCL: {
667− luaM_freemem(L, o, sizeLclosure(gco2lcl(o)->nupvalues));
699+ freeLclosure(L, gco2lcl(o));
668700 break;
669701 }
670702 case LUA_TCCL: {
671703 luaM_freemem(L, o, sizeCclosure(gco2ccl(o)->nupvalues));
672704 break;
673705 }
674− case LUA_TUPVAL: luaF_freeupval(L, gco2uv(o)); break;
675706 case LUA_TTABLE: luaH_free(L, gco2t(o)); break;
676707 case LUA_TTHREAD: luaE_freethread(L, gco2th(o)); break;
677708 case LUA_TUSERDATA: luaM_freemem(L, o, sizeudata(gco2u(o))); break;
678709 case LUA_TSHRSTR:
679− G(L)->strt.nuse--;
710+ luaS_remove(L, rawgco2ts(o)); /* remove it from hash table */
680711 /* go through */
681712 case LUA_TLNGSTR: {
682713 luaM_freemem(L, o, sizestring(gco2ts(o)));
@@ -691,46 +722,17 @@ static void freeobj (lua_State *L, GCObject *o) { · 8 unmodified lines
691722 static GCObject **sweeplist (lua_State *L, GCObject **p, lu_mem count);
692723
693724
694−/*
695−** sweep the (open) upvalues of a thread and resize its stack and
696−** list of call-info structures.
697−*/
698−static void sweepthread (lua_State *L, lua_State *L1) {
699− if (L1->stack == NULL) return; /* stack not completely built yet */
700− sweepwholelist(L, &L1->openupval); /* sweep open upvalues */
701− luaE_freeCI(L1); /* free extra CallInfo slots */
702− /* should not change the stack during an emergency gc cycle */
703− if (G(L)->gckind != KGC_EMERGENCY)
704− luaD_shrinkstack(L1);
705−}
706−
707−
708725 /*
709726 ** sweep at most 'count' elements from a list of GCObjects erasing dead
710727 ** objects, where a dead (not alive) object is one marked with the "old"
711−** (non current) white and not fixed.
712−** In non-generational mode, change all non-dead objects back to white,
713−** preparing for next collection cycle.
714−** In generational mode, keep black objects black, and also mark them as
715−** old; stop when hitting an old object, as all objects after that
716−** one will be old too.
728+** (non current) white and not fixed; change all non-dead objects back
729+** to white, preparing for next collection cycle.
717730 ** When object is a thread, sweep its list of open upvalues too.
718731 */
719732 static GCObject **sweeplist (lua_State *L, GCObject **p, lu_mem count) {
720733 global_State *g = G(L);
721734 int ow = otherwhite(g);
722− int toclear, toset; /* bits to clear and to set in all live objects */
723− int tostop; /* stop sweep when this is true */
724− if (isgenerational(g)) { /* generational mode? */
725− toclear = ~0; /* clear nothing */
726− toset = bitmask(OLDBIT); /* set the old bit of all surviving objects */
727− tostop = bitmask(OLDBIT); /* do not sweep old generation */
728− }
729− else { /* normal mode */
730− toclear = maskcolors; /* clear all color bits + old bit */
731− toset = luaC_white(g); /* make object white */
732− tostop = 0; /* do not stop */
733− }
735+ int white = luaC_white(g); /* current white */
734736 while (*p != NULL && count-- > 0) {
735737 GCObject *curr = *p;
736738 int marked = gch(curr)->marked;
@@ -738,13 +740,8 @@ static GCObject **sweeplist (lua_State *L, GCObject **p, lu_mem count) { · 1 unmodified line
738740 *p = gch(curr)->next; /* remove 'curr' from list */
739741 freeobj(L, curr); /* erase 'curr' */
740742 }
741− else {
742− if (testbits(marked, tostop))
743− return NULL; /* stop sweeping this list */
744− if (gch(curr)->tt == LUA_TTHREAD)
745− sweepthread(L, gco2th(curr)); /* sweep thread's upvalues */
746− /* update marks */
747− gch(curr)->marked = cast_byte((marked & toclear) | toset);
743+ else { /* update marks */
744+ gch(curr)->marked = cast_byte((marked & maskcolors) | white);
748745 p = &gch(curr)->next; /* go to next element */
749746 }
750747 }
@@ -756,7 +753,7 @@ static GCObject **sweeplist (lua_State *L, GCObject **p, lu_mem count) { · 5 unmodified lines
756753 ** sweep a list until a live object (or end of list)
757754 */
758755 static GCObject **sweeptolive (lua_State *L, GCObject **p, int *n) {
759− GCObject ** old = p;
756+ GCObject **old = p;
760757 int i = 0;
761758 do {
762759 i++;
@@ -775,26 +772,26 @@ static GCObject **sweeptolive (lua_State *L, GCObject **p, int *n) { · 12 unmodified lines
775772 ** =======================================================
776773 */
777774
778−static void checkSizes (lua_State *L) {
779− global_State *g = G(L);
780− if (g->gckind != KGC_EMERGENCY) { /* do not change sizes in emergency */
781− int hs = g->strt.size / 2; /* half the size of the string table */
782− if (g->strt.nuse < cast(lu_int32, hs)) /* using less than that half? */
783− luaS_resize(L, hs); /* halve its size */
775+/*
776+** If possible, free concatenation buffer and shrink string table
777+*/
778+static void checkSizes (lua_State *L, global_State *g) {
779+ if (g->gckind != KGC_EMERGENCY) {
784780 luaZ_freebuffer(L, &g->buff); /* free concatenation buffer */
781+ if (g->strt.nuse < g->strt.size / 4) /* string table too big? */
782+ luaS_resize(L, g->strt.size / 2); /* shrink it a little */
785783 }
786784 }
787785
788786
789787 static GCObject *udata2finalize (global_State *g) {
790788 GCObject *o = g->tobefnz; /* get first element */
791− lua_assert(isfinalized(o));
789+ lua_assert(tofinalize(o));
792790 g->tobefnz = gch(o)->next; /* remove it from 'tobefnz' list */
793791 gch(o)->next = g->allgc; /* return it to 'allgc' list */
794792 g->allgc = o;
795− resetbit(gch(o)->marked, SEPARATED); /* mark that it is not in 'tobefnz' */
796− lua_assert(!isold(o)); /* see MOVE OLD rule */
797− if (!keepinvariantout(g)) /* not keeping invariant? */
793+ resetbit(gch(o)->marked, FINALIZEDBIT); /* object is "normal" again */
794+ if (issweepphase(g))
798795 makewhite(g, o); /* "sweep" object */
799796 return o;
800797 }
@@ -839,25 +836,39 @@ static void GCTM (lua_State *L, int propagateerrors) { · 38 unmodified lines
839836
840837
841838 /*
842−** move all unreachable objects (or 'all' objects) that need
843−** finalization from list 'finobj' to list 'tobefnz' (to be finalized)
839+** call all pending finalizers
844840 */
845−static void separatetobefnz (lua_State *L, int all) {
841+static void callallpendingfinalizers (lua_State *L, int propagateerrors) {
846842 global_State *g = G(L);
847− GCObject **p = &g->finobj;
843+ while (g->tobefnz)
844+ GCTM(L, propagateerrors);
845+}
846+
847+
848+/*
849+** find last 'next' field in list 'p' list (to add elements in its end)
850+*/
851+static GCObject **findlast (GCObject **p) {
852+ while (*p != NULL)
853+ p = &gch(*p)->next;
854+ return p;
855+}
856+
857+
858+/*
859+** move all unreachable objects (or 'all' objects) that need
860+** finalization from list 'p' to list 'tobefnz' (to be finalized)
861+*/
862+static void separatetobefnz (global_State *g, int all) {
848863 GCObject *curr;
849− GCObject **lastnext = &g->tobefnz;
850− /* find last 'next' field in 'tobefnz' list (to add elements in its end) */
851− while (*lastnext != NULL)
852− lastnext = &gch(*lastnext)->next;
864+ GCObject **p = &g->finobj;
865+ GCObject **lastnext = findlast(&g->tobefnz);
853866 while ((curr = *p) != NULL) { /* traverse all finalizable objects */
854− lua_assert(!isfinalized(curr));
855− lua_assert(testbit(gch(curr)->marked, SEPARATED));
867+ lua_assert(tofinalize(curr));
856868 if (!(iswhite(curr) || all)) /* not being collected? */
857869 p = &gch(curr)->next; /* don't bother with it */
858870 else {
859− l_setbit(gch(curr)->marked, FINALIZEDBIT); /* won't be finalized again */
860− *p = gch(curr)->next; /* remove 'curr' from 'finobj' list */
871+ *p = gch(curr)->next; /* remove 'curr' from "fin" list */
861872 gch(curr)->next = *lastnext; /* link at the end of 'tobefnz' list */
862873 *lastnext = curr;
863874 lastnext = &gch(curr)->next;
@@ -872,33 +883,30 @@ static void separatetobefnz (lua_State *L, int all) { · 8 unmodified lines
872883 */
873884 void luaC_checkfinalizer (lua_State *L, GCObject *o, Table *mt) {
874885 global_State *g = G(L);
875− if (testbit(gch(o)->marked, SEPARATED) || /* obj. is already separated... */
876− isfinalized(o) || /* ... or is finalized... */
877− gfasttm(g, mt, TM_GC) == NULL) /* or has no finalizer? */
886+ if (tofinalize(o) || /* obj. is already marked... */
887+ gfasttm(g, mt, TM_GC) == NULL) /* or has no finalizer? */
878888 return; /* nothing to be done */
879889 else { /* move 'o' to 'finobj' list */
880890 GCObject **p;
881− GCheader *ho = gch(o);
882− if (g->sweepgc == &ho->next) { /* avoid removing current sweep object */
891+ if (g->sweepgc == &o->gch.next) { /* avoid removing current sweep object */
883892 lua_assert(issweepphase(g));
884893 g->sweepgc = sweeptolive(L, g->sweepgc, NULL);
885894 }
886895 /* search for pointer pointing to 'o' */
887896 for (p = &g->allgc; *p != o; p = &gch(*p)->next) { /* empty */ }
888− *p = ho->next; /* remove 'o' from root list */
889− ho->next = g->finobj; /* link it in list 'finobj' */
897+ *p = o->gch.next; /* remove 'o' from its list */
898+ o->gch.next = g->finobj; /* link it in "fin" list */
890899 g->finobj = o;
891− l_setbit(ho->marked, SEPARATED); /* mark it as such */
892− if (!keepinvariantout(g)) /* not keeping invariant? */
900+ l_setbit(o->gch.marked, FINALIZEDBIT); /* mark it as such */
901+ if (issweepphase(g))
893902 makewhite(g, o); /* "sweep" object */
894− else
895− resetoldbit(o); /* see MOVE OLD rule */
896903 }
897904 }
898905
899906 /* }====================================================== */
900907
901908
909+
902910 /*
903911 ** {======================================================
904912 ** GC control
@@ -911,87 +919,45 @@ void luaC_checkfinalizer (lua_State *L, GCObject *o, Table *mt) { · 6 unmodified lines
911919 ** cycle will start when memory use hits threshold
912920 */
913921 static void setpause (global_State *g, l_mem estimate) {
914− l_mem debt, threshold;
922+ l_mem threshold, debt;
915923 estimate = estimate / PAUSEADJ; /* adjust 'estimate' */
916924 threshold = (g->gcpause < MAX_LMEM / estimate) /* overflow? */
917925 ? estimate * g->gcpause /* no overflow */
918926 : MAX_LMEM; /* overflow; truncate to maximum */
919− debt = -cast(l_mem, threshold - gettotalbytes(g));
927+ debt = gettotalbytes(g) - threshold;
920928 luaE_setdebt(g, debt);
921929 }
922930
923931
924−#define sweepphases \
925− (bitmask(GCSsweepstring) | bitmask(GCSsweepudata) | bitmask(GCSsweep))
926−
927−
928932 /*
929−** enter first sweep phase (strings) and prepare pointers for other
930−** sweep phases. The calls to 'sweeptolive' make pointers point to an
931−** object inside the list (instead of to the header), so that the real
932−** sweep do not need to skip objects created between "now" and the start
933−** of the real sweep.
933+** Enter first sweep phase.
934+** The call to 'sweeptolive' makes pointer point to an object inside
935+** the list (instead of to the header), so that the real sweep do not
936+** need to skip objects created between "now" and the start of the real
937+** sweep.
934938 ** Returns how many objects it swept.
935939 */
936940 static int entersweep (lua_State *L) {
937941 global_State *g = G(L);
938942 int n = 0;
939− g->gcstate = GCSsweepstring;
940− lua_assert(g->sweepgc == NULL && g->sweepfin == NULL);
941− /* prepare to sweep strings, finalizable objects, and regular objects */
942− g->sweepstrgc = 0;
943− g->sweepfin = sweeptolive(L, &g->finobj, &n);
943+ g->gcstate = GCSswpallgc;
944+ lua_assert(g->sweepgc == NULL);
944945 g->sweepgc = sweeptolive(L, &g->allgc, &n);
945946 return n;
946947 }
947948
948949
949−/*
950−** change GC mode
951−*/
952−void luaC_changemode (lua_State *L, int mode) {
953− global_State *g = G(L);
954− if (mode == g->gckind) return; /* nothing to change */
955− if (mode == KGC_GEN) { /* change to generational mode */
956− /* make sure gray lists are consistent */
957− luaC_runtilstate(L, bitmask(GCSpropagate));
958− g->GCestimate = gettotalbytes(g);
959− g->gckind = KGC_GEN;
960− }
961− else { /* change to incremental mode */
962− /* sweep all objects to turn them back to white
963− (as white has not changed, nothing extra will be collected) */
964− g->gckind = KGC_NORMAL;
965− entersweep(L);
966− luaC_runtilstate(L, ~sweepphases);
967− }
968−}
969−
970−
971−/*
972−** call all pending finalizers
973−*/
974−static void callallpendingfinalizers (lua_State *L, int propagateerrors) {
975− global_State *g = G(L);
976− while (g->tobefnz) {
977− resetoldbit(g->tobefnz);
978− GCTM(L, propagateerrors);
979− }
980−}
981−
982−
983950 void luaC_freeallobjects (lua_State *L) {
984951 global_State *g = G(L);
985− int i;
986− separatetobefnz(L, 1); /* separate all objects with finalizers */
952+ separatetobefnz(g, 1); /* separate all objects with finalizers */
987953 lua_assert(g->finobj == NULL);
988954 callallpendingfinalizers(L, 0);
955+ lua_assert(g->tobefnz == NULL);
989956 g->currentwhite = WHITEBITS; /* this "white" makes all objects look dead */
990957 g->gckind = KGC_NORMAL;
991− sweepwholelist(L, &g->finobj); /* finalizers can create objs. in 'finobj' */
958+ sweepwholelist(L, &g->finobj);
992959 sweepwholelist(L, &g->allgc);
993− for (i = 0; i < g->strt.size; i++) /* free all string lists */
994− sweepwholelist(L, &g->strt.hash[i]);
960+ sweepwholelist(L, &g->fixedgc); /* collect fixed objects */
995961 lua_assert(g->strt.nuse == 0);
996962 }
997963
@@ -1001,6 +967,7 @@ static l_mem atomic (lua_State *L) { · 3 unmodified lines
1001967 l_mem work = -cast(l_mem, g->GCmemtrav); /* start counting work */
1002968 GCObject *origweak, *origall;
1003969 lua_assert(!iswhite(obj2gco(g->mainthread)));
970+ g->gcstate = GCSinsideatomic;
1004971 markobject(g, L); /* mark running thread */
1005972 /* registry and global metatables may be changed by API */
1006973 markvalue(g, &g->l_registry);
@@ -1014,14 +981,15 @@ static l_mem atomic (lua_State *L) { · 7 unmodified lines
1014981 work -= g->GCmemtrav; /* restart counting */
1015982 convergeephemerons(g);
1016983 /* at this point, all strongly accessible objects are marked. */
1017− /* clear values from weak tables, before checking finalizers */
984+ /* Clear values from weak tables, before checking finalizers */
1018985 clearvalues(g, g->weak, NULL);
1019986 clearvalues(g, g->allweak, NULL);
1020987 origweak = g->weak; origall = g->allweak;
1021988 work += g->GCmemtrav; /* stop counting (objects being finalized) */
1022− separatetobefnz(L, 0); /* separate objects to be finalized */
989+ separatetobefnz(g, 0); /* separate objects to be finalized */
990+ g->gcfinnum = 1; /* there may be objects to be finalized */
1023991 markbeingfnz(g); /* mark objects that will be finalized */
1024− propagateall(g); /* remark, to propagate `preserveness' */
992+ propagateall(g); /* remark, to propagate 'resurrection' */
1025993 work -= g->GCmemtrav; /* restart counting */
1026994 convergeephemerons(g);
1027995 /* at this point, all resurrected objects are marked. */
@@ -1037,66 +1005,67 @@ static l_mem atomic (lua_State *L) { · 9 unmodified lines
10371005 }
10381006
10391007
1008+static lu_mem sweepstep (lua_State *L, global_State *g,
1009+ int nextstate, GCObject **nextlist) {
1010+ if (g->sweepgc) {
1011+ g->sweepgc = sweeplist(L, g->sweepgc, GCSWEEPMAX);
1012+ if (g->sweepgc) /* is there still something to sweep? */
1013+ return (GCSWEEPMAX * GCSWEEPCOST);
1014+ }
1015+ /* else enter next state */
1016+ g->gcstate = nextstate;
1017+ g->sweepgc = nextlist;
1018+ return 0;
1019+}
1020+
1021+
10401022 static lu_mem singlestep (lua_State *L) {
10411023 global_State *g = G(L);
10421024 switch (g->gcstate) {
10431025 case GCSpause: {
10441026 /* start to count memory traversed */
10451027 g->GCmemtrav = g->strt.size * sizeof(GCObject*);
1046− lua_assert(!isgenerational(g));
10471028 restartcollection(g);
10481029 g->gcstate = GCSpropagate;
10491030 return g->GCmemtrav;
10501031 }
10511032 case GCSpropagate: {
1052− if (g->gray) {
1053− lu_mem oldtrav = g->GCmemtrav;
1054− propagatemark(g);
1055− return g->GCmemtrav - oldtrav; /* memory traversed in this step */
1056− }
1057− else { /* no more `gray' objects */
1058− lu_mem work;
1059− int sw;
1060− g->gcstate = GCSatomic; /* finish mark phase */
1061− g->GCestimate = g->GCmemtrav; /* save what was counted */;
1062− work = atomic(L); /* add what was traversed by 'atomic' */
1063− g->GCestimate += work; /* estimate of total memory traversed */
1064− sw = entersweep(L);
1065− return work + sw * GCSWEEPCOST;
1066− }
1033+ lu_mem oldtrav = g->GCmemtrav;
1034+ lua_assert(g->gray);
1035+ propagatemark(g);
1036+ if (g->gray == NULL) /* no more `gray' objects? */
1037+ g->gcstate = GCSatomic; /* finish propagate phase */
1038+ return g->GCmemtrav - oldtrav; /* memory traversed in this step */
10671039 }
1068− case GCSsweepstring: {
1069− int i;
1070− for (i = 0; i < GCSWEEPMAX && g->sweepstrgc + i < g->strt.size; i++)
1071− sweepwholelist(L, &g->strt.hash[g->sweepstrgc + i]);
1072− g->sweepstrgc += i;
1073− if (g->sweepstrgc >= g->strt.size) /* no more strings to sweep? */
1074− g->gcstate = GCSsweepudata;
1075− return i * GCSWEEPCOST;
1040+ case GCSatomic: {
1041+ lu_mem work;
1042+ int sw;
1043+ propagateall(g); /* make sure gray list is empty */
1044+ g->GCestimate = g->GCmemtrav; /* save what was counted */;
1045+ work = atomic(L); /* work is what was traversed by 'atomic' */
1046+ g->GCestimate += work; /* estimate of total memory traversed */
1047+ sw = entersweep(L);
1048+ return work + sw * GCSWEEPCOST;
10761049 }
1077− case GCSsweepudata: {
1078− if (g->sweepfin) {
1079− g->sweepfin = sweeplist(L, g->sweepfin, GCSWEEPMAX);
1080− return GCSWEEPMAX*GCSWEEPCOST;
1081− }
1082− else {
1083− g->gcstate = GCSsweep;
1084− return 0;
1085− }
1050+ case GCSswpallgc: { /* sweep "regular" objects */
1051+ return sweepstep(L, g, GCSswpfinobj, &g->finobj);
10861052 }
1087− case GCSsweep: {
1088− if (g->sweepgc) {
1089− g->sweepgc = sweeplist(L, g->sweepgc, GCSWEEPMAX);
1090− return GCSWEEPMAX*GCSWEEPCOST;
1091− }
1092− else {
1093− /* sweep main thread */
1094− GCObject *mt = obj2gco(g->mainthread);
1095− sweeplist(L, &mt, 1);
1096− checkSizes(L);
1097− g->gcstate = GCSpause; /* finish collection */
1098− return GCSWEEPCOST;
1099− }
1053+ case GCSswpfinobj: { /* sweep objects with finalizers */
1054+ return sweepstep(L, g, GCSswptobefnz, &g->tobefnz);
1055+ }
1056+ case GCSswptobefnz: { /* sweep objects to be finalized */
1057+ return sweepstep(L, g, GCSswpend, NULL);
1058+ }
1059+ case GCSswpend: { /* finish sweeps */
1060+ makewhite(g, obj2gco(g->mainthread)); /* sweep main thread */
1061+ checkSizes(L, g);
1062+ g->gcstate = GCScallfin;
1063+ return 0;
1064+ }
1065+ case GCScallfin: { /* state to finish calling finalizers */
1066+ /* do nothing here; should be handled by 'luaC_forcestep' */
1067+ g->gcstate = GCSpause; /* finish collection */
1068+ return 0;
11001069 }
11011070 default: lua_assert(0); return 0;
11021071 }
@@ -1114,88 +1083,74 @@ void luaC_runtilstate (lua_State *L, int statesmask) { · 11 unmodified lines
11141083 }
11151084
11161085
1117−static void generationalcollection (lua_State *L) {
1086+/*
1087+** run a few (up to 'g->gcfinnum') finalizers
1088+*/
1089+static int runafewfinalizers (lua_State *L) {
11181090 global_State *g = G(L);
1119− lua_assert(g->gcstate == GCSpropagate);
1120− if (g->GCestimate == 0) { /* signal for another major collection? */
1121− luaC_fullgc(L, 0); /* perform a full regular collection */
1122− g->GCestimate = gettotalbytes(g); /* update control */
1123− }
1124− else {
1125− lu_mem estimate = g->GCestimate;
1126− luaC_runtilstate(L, bitmask(GCSpause)); /* run complete (minor) cycle */
1127− g->gcstate = GCSpropagate; /* skip restart */
1128− if (gettotalbytes(g) > (estimate / 100) * g->gcmajorinc)
1129− g->GCestimate = 0; /* signal for a major collection */
1130− else
1131− g->GCestimate = estimate; /* keep estimate from last major coll. */
1132−
1133− }
1134− setpause(g, gettotalbytes(g));
1135− lua_assert(g->gcstate == GCSpropagate);
1091+ unsigned int i;
1092+ lua_assert(!g->tobefnz || g->gcfinnum > 0);
1093+ for (i = 0; g->tobefnz && i < g->gcfinnum; i++)
1094+ GCTM(L, 1); /* call one finalizer */
1095+ g->gcfinnum = (!g->tobefnz) ? 0 /* nothing more to finalize? */
1096+ : g->gcfinnum * 2; /* else call a few more next time */
1097+ return i;
11361098 }
11371099
11381100
1139−static void incstep (lua_State *L) {
1140− global_State *g = G(L);
1101+/*
1102+** get GC debt and convert it from Kb to 'work units' (avoid zero debt
1103+** and overflows)
1104+*/
1105+static l_mem getdebt (global_State *g) {
11411106 l_mem debt = g->GCdebt;
11421107 int stepmul = g->gcstepmul;
1143− if (stepmul < 40) stepmul = 40; /* avoid ridiculous low values (and 0) */
1144− /* convert debt from Kb to 'work units' (avoid zero debt and overflows) */
11451108 debt = (debt / STEPMULADJ) + 1;
11461109 debt = (debt < MAX_LMEM / stepmul) ? debt * stepmul : MAX_LMEM;
1147− do { /* always perform at least one single step */
1148− lu_mem work = singlestep(L); /* do some work */
1149− debt -= work;
1150− } while (debt > -GCSTEPSIZE && g->gcstate != GCSpause);
1151− if (g->gcstate == GCSpause)
1152− setpause(g, g->GCestimate); /* pause until next cycle */
1153− else {
1154− debt = (debt / stepmul) * STEPMULADJ; /* convert 'work units' to Kb */
1155− luaE_setdebt(g, debt);
1156− }
1110+ return debt;
11571111 }
11581112
1159−
11601113 /*
1161−** performs a basic GC step
1162−*/
1163−void luaC_forcestep (lua_State *L) {
1164− global_State *g = G(L);
1165− int i;
1166− if (isgenerational(g)) generationalcollection(L);
1167− else incstep(L);
1168− /* run a few finalizers (or all of them at the end of a collect cycle) */
1169− for (i = 0; g->tobefnz && (i < GCFINALIZENUM || g->gcstate == GCSpause); i++)
1170− GCTM(L, 1); /* call one finalizer */
1171−}
1172−
1173−
1174−/*
1175−** performs a basic GC step only if collector is running
1114+** performs a basic GC step when collector is running
11761115 */
11771116 void luaC_step (lua_State *L) {
11781117 global_State *g = G(L);
1179− if (g->gcrunning) luaC_forcestep(L);
1180− else luaE_setdebt(g, -GCSTEPSIZE); /* avoid being called too often */
1118+ l_mem debt = getdebt(g);
1119+ if (!g->gcrunning) { /* not running? */
1120+ luaE_setdebt(g, -GCSTEPSIZE * 10); /* avoid being called too often */
1121+ return;
1122+ }
1123+ do {
1124+ if (g->gcstate == GCScallfin && g->tobefnz) {
1125+ unsigned int n = runafewfinalizers(L);
1126+ debt -= (n * GCFINALIZECOST);
1127+ }
1128+ else { /* perform one single step */
1129+ lu_mem work = singlestep(L);
1130+ debt -= work;
1131+ }
1132+ } while (debt > -GCSTEPSIZE && g->gcstate != GCSpause);
1133+ if (g->gcstate == GCSpause)
1134+ setpause(g, g->GCestimate); /* pause until next cycle */
1135+ else {
1136+ debt = (debt / g->gcstepmul) * STEPMULADJ; /* convert 'work units' to Kb */
1137+ luaE_setdebt(g, debt);
1138+ runafewfinalizers(L);
1139+ }
11811140 }
11821141
11831142
1184−
11851143 /*
11861144 ** performs a full GC cycle; if "isemergency", does not call
11871145 ** finalizers (which could change stack positions)
11881146 */
11891147 void luaC_fullgc (lua_State *L, int isemergency) {
11901148 global_State *g = G(L);
1191− int origkind = g->gckind;
1192− lua_assert(origkind != KGC_EMERGENCY);
1149+ lua_assert(g->gckind == KGC_NORMAL);
11931150 if (isemergency) /* do not run finalizers during emergency GC */
11941151 g->gckind = KGC_EMERGENCY;
1195− else {
1196− g->gckind = KGC_NORMAL;
1152+ else
11971153 callallpendingfinalizers(L, 1);
1198− }
11991154 if (keepinvariant(g)) { /* may there be some black objects? */
12001155 /* must sweep all objects to turn them back to white
12011156 (as white has not changed, nothing will be collected) */
@@ -1205,11 +1160,7 @@ void luaC_fullgc (lua_State *L, int isemergency) { · 3 unmodified lines
12051160 luaC_runtilstate(L, bitmask(GCSpause));
12061161 luaC_runtilstate(L, ~bitmask(GCSpause)); /* start new collection */
12071162 luaC_runtilstate(L, bitmask(GCSpause)); /* run entire collection */
1208− if (origkind == KGC_GEN) { /* generational mode? */
1209− /* generational mode must be kept in propagate phase */
1210− luaC_runtilstate(L, bitmask(GCSpropagate));
1211− }
1212− g->gckind = origkind;
1163+ g->gckind = KGC_NORMAL;
12131164 setpause(g, gettotalbytes(g));
12141165 if (!isemergency) /* do not run finalizers during emergency GC */
12151166 callallpendingfinalizers(L, 1);
src/lgc.h+30−49
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lgc.h,v 2.58 2012/09/11 12:53:08 roberto Exp $
2+** $Id: lgc.h,v 2.82 2014/03/19 18:51:16 roberto Exp $
33 ** Garbage Collector
44 ** See Copyright Notice in lua.h
55 */
@@ -38,36 +38,27 @@ · 32 unmodified lines
3838 */
3939 #define GCSpropagate 0
4040 #define GCSatomic 1
41−#define GCSsweepstring 2
42−#define GCSsweepudata 3
43−#define GCSsweep 4
44−#define GCSpause 5
41+#define GCSswpallgc 2
42+#define GCSswpfinobj 3
43+#define GCSswptobefnz 4
44+#define GCSswpend 5
45+#define GCScallfin 6
46+#define GCSpause 7
4547
4648
4749 #define issweepphase(g) \
48− (GCSsweepstring <= (g)->gcstate && (g)->gcstate <= GCSsweep)
50+ (GCSswpallgc <= (g)->gcstate && (g)->gcstate <= GCSswpend)
4951
50−#define isgenerational(g) ((g)->gckind == KGC_GEN)
5152
5253 /*
53−** macros to tell when main invariant (white objects cannot point to black
54−** ones) must be kept. During a non-generational collection, the sweep
54+** macro to tell when main invariant (white objects cannot point to black
55+** ones) must be kept. During a collection, the sweep
5556 ** phase may break the invariant, as objects turned white may point to
5657 ** still-black objects. The invariant is restored when sweep ends and
57−** all objects are white again. During a generational collection, the
58−** invariant must be kept all times.
58+** all objects are white again.
5959 */
6060
61−#define keepinvariant(g) (isgenerational(g) || g->gcstate <= GCSatomic)
62−
63−
64−/*
65−** Outside the collector, the state in generational mode is kept in
66−** 'propagate', so 'keepinvariant' is always true.
67−*/
68−#define keepinvariantout(g) \
69− check_exp(g->gcstate == GCSpropagate || !isgenerational(g), \
70− g->gcstate <= GCSatomic)
61+#define keepinvariant(g) ((g)->gcstate <= GCSatomic)
7162
7263
7364 /*
@@ -87,10 +78,7 @@ · 13 unmodified lines
8778 #define WHITE0BIT 0 /* object is white (type 0) */
8879 #define WHITE1BIT 1 /* object is white (type 1) */
8980 #define BLACKBIT 2 /* object is black */
90−#define FINALIZEDBIT 3 /* object has been separated for finalization */
91−#define SEPARATED 4 /* object is in 'finobj' list or in 'tobefnz' */
92−#define FIXEDBIT 5 /* object is fixed (should not be collected) */
93−#define OLDBIT 6 /* object is old (only in generational mode) */
81+#define FINALIZEDBIT 3 /* object has been marked for finalization */
9482 /* bit 7 is currently used by tests (luaL_checkmemory) */
9583
9684 #define WHITEBITS bit2mask(WHITE0BIT, WHITE1BIT)
@@ -101,21 +89,15 @@ · 4 unmodified lines
10189 #define isgray(x) /* neither white nor black */ \
10290 (!testbits((x)->gch.marked, WHITEBITS | bitmask(BLACKBIT)))
10391
104−#define isold(x) testbit((x)->gch.marked, OLDBIT)
92+#define tofinalize(x) testbit((x)->gch.marked, FINALIZEDBIT)
10593
106−/* MOVE OLD rule: whenever an object is moved to the beginning of
107− a GC list, its old bit must be cleared */
108−#define resetoldbit(o) resetbit((o)->gch.marked, OLDBIT)
109−
110−#define otherwhite(g) (g->currentwhite ^ WHITEBITS)
94+#define otherwhite(g) ((g)->currentwhite ^ WHITEBITS)
11195 #define isdeadm(ow,m) (!(((m) ^ WHITEBITS) & (ow)))
11296 #define isdead(g,v) isdeadm(otherwhite(g), (v)->gch.marked)
11397
11498 #define changewhite(x) ((x)->gch.marked ^= WHITEBITS)
11599 #define gray2black(x) l_setbit((x)->gch.marked, BLACKBIT)
116100
117−#define valiswhite(x) (iscollectable(x) && iswhite(gcvalue(x)))
118−
119101 #define luaC_white(g) cast(lu_byte, (g)->currentwhite & WHITEBITS)
120102
121103
@@ -124,34 +106,33 @@ · 2 unmodified lines
124106 #define luaC_checkGC(L) luaC_condGC(L, luaC_step(L);)
125107
126108
127−#define luaC_barrier(L,p,v) { if (valiswhite(v) && isblack(obj2gco(p))) \
109+#define luaC_barrier(L,p,v) { \
110+ if (iscollectable(v) && isblack(obj2gco(p)) && iswhite(gcvalue(v))) \
128111 luaC_barrier_(L,obj2gco(p),gcvalue(v)); }
129112
130−#define luaC_barrierback(L,p,v) { if (valiswhite(v) && isblack(obj2gco(p))) \
131− luaC_barrierback_(L,p); }
113+#define luaC_barrierback(L,p,v) { \
114+ if (iscollectable(v) && isblack(obj2gco(p)) && iswhite(gcvalue(v))) \
115+ luaC_barrierback_(L,obj2gco(p)); }
132116
133−#define luaC_objbarrier(L,p,o) \
134− { if (iswhite(obj2gco(o)) && isblack(obj2gco(p))) \
117+#define luaC_objbarrier(L,p,o) { \
118+ if (isblack(obj2gco(p)) && iswhite(obj2gco(o))) \
135119 luaC_barrier_(L,obj2gco(p),obj2gco(o)); }
136120
137−#define luaC_objbarrierback(L,p,o) \
138− { if (iswhite(obj2gco(o)) && isblack(obj2gco(p))) luaC_barrierback_(L,p); }
139−
140−#define luaC_barrierproto(L,p,c) \
141− { if (isblack(obj2gco(p))) luaC_barrierproto_(L,p,c); }
121+#define luaC_upvalbarrier(L,uv) \
122+ { if (iscollectable((uv)->v) && !upisopen(uv)) \
123+ luaC_upvalbarrier_(L,uv); }
142124
125+LUAI_FUNC void luaC_fix (lua_State *L, GCObject *o);
143126 LUAI_FUNC void luaC_freeallobjects (lua_State *L);
144127 LUAI_FUNC void luaC_step (lua_State *L);
145−LUAI_FUNC void luaC_forcestep (lua_State *L);
146128 LUAI_FUNC void luaC_runtilstate (lua_State *L, int statesmask);
147129 LUAI_FUNC void luaC_fullgc (lua_State *L, int isemergency);
148−LUAI_FUNC GCObject *luaC_newobj (lua_State *L, int tt, size_t sz,
149− GCObject **list, int offset);
130+LUAI_FUNC GCObject *luaC_newobj (lua_State *L, int tt, size_t sz);
150131 LUAI_FUNC void luaC_barrier_ (lua_State *L, GCObject *o, GCObject *v);
151132 LUAI_FUNC void luaC_barrierback_ (lua_State *L, GCObject *o);
152−LUAI_FUNC void luaC_barrierproto_ (lua_State *L, Proto *p, Closure *c);
133+LUAI_FUNC void luaC_upvalbarrier_ (lua_State *L, UpVal *uv);
153134 LUAI_FUNC void luaC_checkfinalizer (lua_State *L, GCObject *o, Table *mt);
154−LUAI_FUNC void luaC_checkupvalcolor (global_State *g, UpVal *uv);
155−LUAI_FUNC void luaC_changemode (lua_State *L, int mode);
135+LUAI_FUNC void luaC_upvdeccount (lua_State *L, UpVal *uv);
136+
156137
157138 #endif
src/linit.c+2−1
@@ -1,5 +1,5 @@
11 /*
2−** $Id: linit.c,v 1.32 2011/04/08 19:17:36 roberto Exp $
2+** $Id: linit.c,v 1.33 2014/02/06 17:32:33 roberto Exp $
33 ** Initialization of libraries for lua.c and other clients
44 ** See Copyright Notice in lua.h
55 */
@@ -34,6 +34,7 @@ static const luaL_Reg loadedlibs[] = { · 28 unmodified lines
3434 {LUA_IOLIBNAME, luaopen_io},
3535 {LUA_OSLIBNAME, luaopen_os},
3636 {LUA_STRLIBNAME, luaopen_string},
37+ {LUA_UTF8LIBNAME, luaopen_utf8},
3738 {LUA_BITLIBNAME, luaopen_bit32},
3839 {LUA_MATHLIBNAME, luaopen_math},
3940 {LUA_DBLIBNAME, luaopen_debug},
src/liolib.c+61−58
@@ -1,5 +1,5 @@
11 /*
2−** $Id: liolib.c,v 2.114 2013/06/07 19:01:35 roberto Exp $
2+** $Id: liolib.c,v 2.120 2014/03/19 18:57:42 roberto Exp $
33 ** Standard I/O (and system) library
44 ** See Copyright Notice in lua.h
55 */
@@ -29,14 +29,14 @@ · 23 unmodified lines
2929 #include "lualib.h"
3030
3131
32−#if !defined(lua_checkmode)
32+#if !defined(l_checkmode)
3333
3434 /*
3535 ** Check whether 'mode' matches '[rwa]%+?b?'.
3636 ** Change this macro to accept other modes for 'fopen' besides
3737 ** the standard ones.
3838 */
39−#define lua_checkmode(mode) \
39+#define l_checkmode(mode) \
4040 (*mode != '\0' && strchr("rwa", *(mode++)) != NULL && \
4141 (*mode != '+' || ++mode) && /* skip if char is '+' */ \
4242 (*mode != 'b' || ++mode) && /* skip if char is 'b' */ \
@@ -46,45 +46,61 @@ · 3 unmodified lines
4646
4747 /*
4848 ** {======================================================
49−** lua_popen spawns a new process connected to the current
49+** l_popen spawns a new process connected to the current
5050 ** one through the file streams.
5151 ** =======================================================
5252 */
5353
54−#if !defined(lua_popen) /* { */
54+#if !defined(l_popen) /* { */
5555
56−#if defined(LUA_USE_POPEN) /* { */
56+#if defined(LUA_USE_POSIX) /* { */
5757
58−#define lua_popen(L,c,m) ((void)L, fflush(NULL), popen(c,m))
59−#define lua_pclose(L,file) ((void)L, pclose(file))
58+#define l_popen(L,c,m) (fflush(NULL), popen(c,m))
59+#define l_pclose(L,file) (pclose(file))
6060
6161 #elif defined(LUA_WIN) /* }{ */
6262
63−#define lua_popen(L,c,m) ((void)L, _popen(c,m))
64−#define lua_pclose(L,file) ((void)L, _pclose(file))
65−
63+#define l_popen(L,c,m) (_popen(c,m))
64+#define l_pclose(L,file) (_pclose(file))
6665
6766 #else /* }{ */
6867
69−#define lua_popen(L,c,m) ((void)((void)c, m), \
70− luaL_error(L, LUA_QL("popen") " not supported"), (FILE*)0)
71−#define lua_pclose(L,file) ((void)((void)L, file), -1)
72−
68+/* ANSI definitions */
69+#define l_popen(L,c,m) \
70+ ((void)((void)c, m), \
71+ luaL_error(L, LUA_QL("popen") " not supported"), \
72+ (FILE*)0)
73+#define l_pclose(L,file) ((void)L, (void)file, -1)
7374
7475 #endif /* } */
7576
76−#endif /* } */
77+#endif /* } */
7778
7879 /* }====================================================== */
7980
8081
82+#if !defined(l_getc) /* { */
83+
84+#if defined(LUA_USE_POSIX)
85+#define l_getc(f) getc_unlocked(f)
86+#define l_lockfile(f) flockfile(f)
87+#define l_unlockfile(f) funlockfile(f)
88+#else
89+#define l_getc(f) getc(f)
90+#define l_lockfile(f) ((void)0)
91+#define l_unlockfile(f) ((void)0)
92+#endif
93+
94+#endif /* } */
95+
96+
8197 /*
8298 ** {======================================================
83−** lua_fseek: configuration for longer offsets
99+** l_fseek: configuration for longer offsets
84100 ** =======================================================
85101 */
86102
87−#if !defined(lua_fseek) && !defined(LUA_ANSI) /* { */
103+#if !defined(l_fseek) /* { */
88104
89105 #if defined(LUA_USE_POSIX) /* { */
90106
@@ -94,22 +110,22 @@ · 3 unmodified lines
94110
95111 #elif defined(LUA_WIN) && !defined(_CRTIMP_TYPEINFO) \
96112 && defined(_MSC_VER) && (_MSC_VER >= 1400) /* }{ */
97−/* Windows (but not DDK) and Visual C++ 2005 or higher */
98113
114+/* Windows (but not DDK) and Visual C++ 2005 or higher */
99115 #define l_fseek(f,o,w) _fseeki64(f,o,w)
100116 #define l_ftell(f) _ftelli64(f)
101117 #define l_seeknum __int64
102118
103−#endif /* } */
104−
105−#endif /* } */
106−
119+#else /* }{ */
107120
108−#if !defined(l_fseek) /* default definitions */
121+/* ANSI definitions */
109122 #define l_fseek(f,o,w) fseek(f,o,w)
110123 #define l_ftell(f) ftell(f)
111124 #define l_seeknum long
112−#endif
125+
126+#endif /* } */
127+
128+#endif /* } */
113129
114130 /* }====================================================== */
115131
@@ -228,7 +244,7 @@ static int io_open (lua_State *L) { · 112 unmodified lines
228244 const char *mode = luaL_optstring(L, 2, "r");
229245 LStream *p = newfile(L);
230246 const char *md = mode; /* to traverse/check mode */
231− luaL_argcheck(L, lua_checkmode(md), 2, "invalid mode");
247+ luaL_argcheck(L, l_checkmode(md), 2, "invalid mode");
232248 p->f = fopen(filename, mode);
233249 return (p->f == NULL) ? luaL_fileresult(L, 0, filename) : 1;
234250 }
@@ -239,7 +255,7 @@ static int io_open (lua_State *L) { · 4 unmodified lines
239255 */
240256 static int io_pclose (lua_State *L) {
241257 LStream *p = tolstream(L);
242− return luaL_execresult(L, lua_pclose(L, p->f));
258+ return luaL_execresult(L, l_pclose(L, p->f));
243259 }
244260
245261
@@ -247,7 +263,7 @@ static int io_popen (lua_State *L) { · 1 unmodified line
247263 const char *filename = luaL_checkstring(L, 1);
248264 const char *mode = luaL_optstring(L, 2, "r");
249265 LStream *p = newprefile(L);
250− p->f = lua_popen(L, filename, mode);
266+ p->f = l_popen(L, filename, mode);
251267 p->closef = &io_pclose;
252268 return (p->f == NULL) ? luaL_fileresult(L, 0, filename) : 1;
253269 }
@@ -375,7 +391,7 @@ static int read_number (lua_State *L, FILE *f) { · 121 unmodified lines
375391
376392 static int test_eof (lua_State *L, FILE *f) {
377393 int c = getc(f);
378− ungetc(c, f);
394+ ungetc(c, f); /* no-op when c == EOF */
379395 lua_pushlstring(L, NULL, 0);
380396 return (c != EOF);
381397 }
@@ -383,40 +399,27 @@ static int test_eof (lua_State *L, FILE *f) { · 1 unmodified line
383399
384400 static int read_line (lua_State *L, FILE *f, int chop) {
385401 luaL_Buffer b;
402+ int c;
386403 luaL_buffinit(L, &b);
387− for (;;) {
388− size_t l;
389− char *p = luaL_prepbuffer(&b);
390− if (fgets(p, LUAL_BUFFERSIZE, f) == NULL) { /* eof? */
391− luaL_pushresult(&b); /* close buffer */
392− return (lua_rawlen(L, -1) > 0); /* check whether read something */
393− }
394− l = strlen(p);
395− if (l == 0 || p[l-1] != '\n')
396− luaL_addsize(&b, l);
397− else {
398− luaL_addsize(&b, l - chop); /* chop 'eol' if needed */
399− luaL_pushresult(&b); /* close buffer */
400− return 1; /* read at least an `eol' */
401− }
402− }
404+ l_lockfile(f);
405+ while ((c = l_getc(f)) != EOF && c != '\n')
406+ luaL_addchar(&b, c);
407+ l_unlockfile(f);
408+ if (!chop && c == '\n') luaL_addchar(&b, c);
409+ luaL_pushresult(&b); /* close buffer */
410+ return (c == '\n' || lua_rawlen(L, -1) > 0);
403411 }
404412
405413
406−#define MAX_SIZE_T (~(size_t)0)
407−
408414 static void read_all (lua_State *L, FILE *f) {
409− size_t rlen = LUAL_BUFFERSIZE; /* how much to read in each cycle */
415+ size_t nr;
410416 luaL_Buffer b;
411417 luaL_buffinit(L, &b);
412− for (;;) {
413− char *p = luaL_prepbuffsize(&b, rlen);
414− size_t nr = fread(p, sizeof(char), rlen, f);
418+ do { /* read file in chunks of LUAL_BUFFERSIZE bytes */
419+ char *p = luaL_prepbuffsize(&b, LUAL_BUFFERSIZE);
420+ nr = fread(p, sizeof(char), LUAL_BUFFERSIZE, f);
415421 luaL_addsize(&b, nr);
416− if (nr < rlen) break; /* eof? */
417− else if (rlen <= (MAX_SIZE_T / 4)) /* avoid buffers too large */
418− rlen *= 2; /* double buffer size at each iteration */
419− }
422+ } while (nr == LUAL_BUFFERSIZE);
420423 luaL_pushresult(&b); /* close buffer */
421424 }
422425
@@ -566,15 +569,15 @@ static int f_seek (lua_State *L) { · 143 unmodified lines
566569 static const char *const modenames[] = {"set", "cur", "end", NULL};
567570 FILE *f = tofile(L);
568571 int op = luaL_checkoption(L, 2, "cur", modenames);
569− lua_Number p3 = luaL_optnumber(L, 3, 0);
572+ lua_Integer p3 = luaL_optinteger(L, 3, 0);
570573 l_seeknum offset = (l_seeknum)p3;
571− luaL_argcheck(L, (lua_Number)offset == p3, 3,
574+ luaL_argcheck(L, (lua_Integer)offset == p3, 3,
572575 "not an integer in proper range");
573576 op = l_fseek(f, offset, mode[op]);
574577 if (op)
575578 return luaL_fileresult(L, 0, NULL); /* error */
576579 else {
577− lua_pushnumber(L, (lua_Number)l_ftell(f));
580+ lua_pushinteger(L, (lua_Integer)l_ftell(f));
578581 return 1;
579582 }
580583 }
src/llex.c+80−42
@@ -1,5 +1,5 @@
11 /*
2−** $Id: llex.c,v 2.67 2013/06/19 14:27:00 roberto Exp $
2+** $Id: llex.c,v 2.74 2014/02/14 15:23:51 roberto Exp $
33 ** Lexical Analyzer
44 ** See Copyright Notice in lua.h
55 */
@@ -15,6 +15,7 @@ · 9 unmodified lines
1515
1616 #include "lctype.h"
1717 #include "ldo.h"
18+#include "lgc.h"
1819 #include "llex.h"
1920 #include "lobject.h"
2021 #include "lparser.h"
@@ -38,7 +39,8 @@ static const char *const luaX_tokens [] = { · 17 unmodified lines
3839 "end", "false", "for", "function", "goto", "if",
3940 "in", "local", "nil", "not", "or", "repeat",
4041 "return", "then", "true", "until", "while",
41− "//", "..", "...", "==", ">=", "<=", "~=", "::", "<eof>",
42+ "//", "..", "...", "==", ">=", "<=", "~=",
43+ "<<", ">>", "::", "<eof>",
4244 "<number>", "<number>", "<name>", "<string>"
4345 };
4446
@@ -64,9 +66,11 @@ static void save (LexState *ls, int c) { · 19 unmodified lines
6466
6567 void luaX_init (lua_State *L) {
6668 int i;
69+ TString *e = luaS_new(L, LUA_ENV); /* create env name */
70+ luaC_fix(L, obj2gco(e)); /* never collect this name */
6771 for (i=0; i<NUM_RESERVED; i++) {
6872 TString *ts = luaS_new(L, luaX_tokens[i]);
69− luaS_fix(ts); /* reserved words are never collected */
73+ luaC_fix(L, obj2gco(ts)); /* reserved words are never collected */
7074 ts->tsv.extra = cast_byte(i+1); /* reserved word */
7175 }
7276 }
@@ -116,22 +120,25 @@ l_noret luaX_syntaxerror (LexState *ls, const char *msg) { · 43 unmodified lines
116120
117121
118122 /*
119−** creates a new string and anchors it in function's table so that
120−** it will not be collected until the end of the function's compilation
121−** (by that time it should be anchored in function's prototype)
123+** creates a new string and anchors it in scanner's table so that
124+** it will not be collected until the end of the compilation
125+** (by that time it should be anchored somewhere)
122126 */
123127 TString *luaX_newstring (LexState *ls, const char *str, size_t l) {
124128 lua_State *L = ls->L;
125129 TValue *o; /* entry for `str' */
126130 TString *ts = luaS_newlstr(L, str, l); /* create new string */
127131 setsvalue2s(L, L->top++, ts); /* temporarily anchor it in stack */
128− o = luaH_set(L, ls->fs->h, L->top - 1);
129− if (ttisnil(o)) { /* not in use yet? (see 'addK') */
132+ o = luaH_set(L, ls->h, L->top - 1);
133+ if (ttisnil(o)) { /* not in use yet? */
130134 /* boolean value does not need GC barrier;
131135 table has no metatable, so it does not need to invalidate cache */
132136 setbvalue(o, 1); /* t[string] = true */
133137 luaC_checkGC(L);
134138 }
139+ else { /* string already present */
140+ ts = rawtsvalue(keyfromval(o)); /* re-use value previously stored */
141+ }
135142 L->top--; /* remove string from stack */
136143 return ts;
137144 }
@@ -163,8 +170,7 @@ void luaX_setinput (lua_State *L, LexState *ls, ZIO *z, TString *source, · 25 unmodified lines
163170 ls->linenumber = 1;
164171 ls->lastline = 1;
165172 ls->source = source;
166− ls->envn = luaS_new(L, LUA_ENV); /* create env name */
167− luaS_fix(ls->envn); /* never collect this name */
173+ ls->envn = luaS_new(L, LUA_ENV); /* get env name */
168174 luaZ_resizebuffer(ls->L, ls->buff, LUA_MINBUFFER); /* initialize buffer */
169175 }
170176
@@ -314,40 +320,65 @@ static void read_long_string (LexState *ls, SemInfo *seminfo, int sep) { · 143 unmodified lines
314320 }
315321
316322
317−static void escerror (LexState *ls, int *c, int n, const char *msg) {
318− int i;
319− luaZ_resetbuffer(ls->buff); /* prepare error message */
320− save(ls, '\\');
321− for (i = 0; i < n && c[i] != EOZ; i++)
322− save(ls, c[i]);
323− lexerror(ls, msg, TK_STRING);
323+static void esccheck (LexState *ls, int c, const char *msg) {
324+ if (!c) {
325+ if (ls->current != EOZ)
326+ save_and_next(ls); /* add current to buffer for error message */
327+ lexerror(ls, msg, TK_STRING);
328+ }
329+}
330+
331+
332+static int gethexa (LexState *ls) {
333+ save_and_next(ls);
334+ esccheck (ls, lisxdigit(ls->current), "hexadecimal digit expected");
335+ return luaO_hexavalue(ls->current);
324336 }
325337
326338
327339 static int readhexaesc (LexState *ls) {
328− int c[3], i; /* keep input for error message */
329− int r = 0; /* result accumulator */
330− c[0] = 'x'; /* for error message */
331− for (i = 1; i < 3; i++) { /* read two hexadecimal digits */
332− c[i] = next(ls);
333− if (!lisxdigit(c[i]))
334− escerror(ls, c, i + 1, "hexadecimal digit expected");
335− r = (r << 4) + luaO_hexavalue(c[i]);
340+ int r = gethexa(ls);
341+ r = (r << 4) + gethexa(ls);
342+ luaZ_buffremove(ls->buff, 2); /* remove saved chars from buffer */
343+ return r;
344+}
345+
346+
347+static unsigned int readutf8esc (LexState *ls) {
348+ unsigned int r;
349+ int i = 4; /* chars to be removed: '\', 'u', '{', and first digit */
350+ save_and_next(ls); /* skip 'u' */
351+ esccheck(ls, ls->current == '{', "missing '{'");
352+ r = gethexa(ls); /* must have at least one digit */
353+ while ((save_and_next(ls), lisxdigit(ls->current))) {
354+ i++;
355+ r = (r << 4) + luaO_hexavalue(ls->current);
356+ esccheck(ls, r <= 0x10FFFF, "UTF-8 value too large");
336357 }
358+ esccheck(ls, ls->current == '}', "missing '}'");
359+ next(ls); /* skip '}' */
360+ luaZ_buffremove(ls->buff, i); /* remove saved chars from buffer */
337361 return r;
338362 }
339363
340364
365+static void utf8esc (LexState *ls) {
366+ char buff[UTF8BUFFSZ];
367+ int n = luaO_utf8esc(buff, readutf8esc(ls));
368+ for (; n > 0; n--) /* add 'buff' to string */
369+ save(ls, buff[UTF8BUFFSZ - n]);
370+}
371+
372+
341373 static int readdecesc (LexState *ls) {
342− int c[3], i;
374+ int i;
343375 int r = 0; /* result accumulator */
344376 for (i = 0; i < 3 && lisdigit(ls->current); i++) { /* read up to 3 digits */
345− c[i] = ls->current;
346− r = 10*r + c[i] - '0';
347− next(ls);
377+ r = 10*r + ls->current - '0';
378+ save_and_next(ls);
348379 }
349− if (r > UCHAR_MAX)
350− escerror(ls, c, i, "decimal escape too large");
380+ esccheck(ls, r <= UCHAR_MAX, "decimal escape too large");
381+ luaZ_buffremove(ls->buff, i); /* remove read digits from buffer */
351382 return r;
352383 }
353384
@@ -365,7 +396,7 @@ static void read_string (LexState *ls, int del, SemInfo *seminfo) { · 11 unmodified lines
365396 break; /* to avoid warnings */
366397 case '\\': { /* escape sequences */
367398 int c; /* final character to be saved */
368− next(ls); /* do not save the `\' */
399+ save_and_next(ls); /* keep '\\' for error messages */
369400 switch (ls->current) {
370401 case 'a': c = '\a'; goto read_save;
371402 case 'b': c = '\b'; goto read_save;
@@ -375,12 +406,14 @@ static void read_string (LexState *ls, int del, SemInfo *seminfo) { · 3 unmodified lines
375406 case 't': c = '\t'; goto read_save;
376407 case 'v': c = '\v'; goto read_save;
377408 case 'x': c = readhexaesc(ls); goto read_save;
409+ case 'u': utf8esc(ls); goto no_save;
378410 case '\n': case '\r':
379411 inclinenumber(ls); c = '\n'; goto only_save;
380412 case '\\': case '\"': case '\'':
381413 c = ls->current; goto read_save;
382414 case EOZ: goto no_save; /* will raise an error next loop */
383415 case 'z': { /* zap following span of spaces */
416+ luaZ_buffremove(ls->buff, 1); /* remove '\\' */
384417 next(ls); /* skip the 'z' */
385418 while (lisspace(ls->current)) {
386419 if (currIsNewline(ls)) inclinenumber(ls);
@@ -389,15 +422,18 @@ static void read_string (LexState *ls, int del, SemInfo *seminfo) { · 2 unmodified lines
389422 goto no_save;
390423 }
391424 default: {
392− if (!lisdigit(ls->current))
393− escerror(ls, &ls->current, 1, "invalid escape sequence");
394− /* digital escape \ddd */
395− c = readdecesc(ls);
425+ esccheck(ls, lisdigit(ls->current), "invalid escape sequence");
426+ c = readdecesc(ls); /* digital escape \ddd */
396427 goto only_save;
397428 }
398429 }
399− read_save: next(ls); /* read next character */
400− only_save: save(ls, c); /* save 'c' */
430+ read_save:
431+ next(ls);
432+ /* go through */
433+ only_save:
434+ luaZ_buffremove(ls->buff, 1); /* remove '\\' */
435+ save(ls, c);
436+ /* go through */
401437 no_save: break;
402438 }
403439 default:
@@ -457,13 +493,15 @@ static int llex (LexState *ls, SemInfo *seminfo) { · 53 unmodified lines
457493 }
458494 case '<': {
459495 next(ls);
460− if (ls->current != '=') return '<';
461− else { next(ls); return TK_LE; }
496+ if (ls->current == '=') { next(ls); return TK_LE; }
497+ if (ls->current == '<') { next(ls); return TK_SHL; }
498+ return '<';
462499 }
463500 case '>': {
464501 next(ls);
465− if (ls->current != '=') return '>';
466− else { next(ls); return TK_GE; }
502+ if (ls->current == '=') { next(ls); return TK_GE; }
503+ if (ls->current == '>') { next(ls); return TK_SHR; }
504+ return '>';
467505 }
468506 case '/': {
469507 next(ls);
src/llex.h+3−1
@@ -1,5 +1,5 @@
11 /*
2−** $Id: llex.h,v 1.74 2013/04/26 13:07:53 roberto Exp $
2+** $Id: llex.h,v 1.76 2013/12/30 20:47:58 roberto Exp $
33 ** Lexical Analyzer
44 ** See Copyright Notice in lua.h
55 */
@@ -27,6 +27,7 @@ enum RESERVED { · 21 unmodified lines
2727 TK_RETURN, TK_THEN, TK_TRUE, TK_UNTIL, TK_WHILE,
2828 /* other terminal symbols */
2929 TK_IDIV, TK_CONCAT, TK_DOTS, TK_EQ, TK_GE, TK_LE, TK_NE,
30+ TK_SHL, TK_SHR,
3031 TK_DBCOLON, TK_EOS,
3132 TK_FLT, TK_INT, TK_NAME, TK_STRING
3233 };
@@ -60,6 +61,7 @@ typedef struct LexState { · 27 unmodified lines
6061 struct lua_State *L;
6162 ZIO *z; /* input stream */
6263 Mbuffer *buff; /* buffer for tokens */
64+ Table *h; /* to avoid collection/reuse strings */
6365 struct Dyndata *dyd; /* dynamic structures used by the parser */
6466 TString *source; /* current source name */
6567 TString *envn; /* environment variable name */
src/llimits.h+7−4
@@ -1,5 +1,5 @@
11 /*
2−** $Id: llimits.h,v 1.108 2013/06/19 14:27:00 roberto Exp $
2+** $Id: llimits.h,v 1.111 2014/03/07 16:19:00 roberto Exp $
33 ** Limits, basic types, and some other `installation-dependent' definitions
44 ** See Copyright Notice in lua.h
55 */
@@ -43,11 +43,13 @@ typedef unsigned char lu_byte; · 37 unmodified lines
4343 #define MAX_INT (INT_MAX-2) /* maximum value of an int (-2 for safety) */
4444
4545
46+/* maximum value for a lua_Unsigned */
47+#define MAX_UINTEGER (~(lua_Unsigned)0)
48+
4649 /* minimum and maximum values for lua_Integer */
47−#define MAX_INTEGER ((lua_Integer)(~(lua_Unsigned)0 >> 1))
50+#define MAX_INTEGER ((lua_Integer)(MAX_UINTEGER >> 1))
4851 #define MIN_INTEGER (~MAX_INTEGER)
4952
50−
5153 /*
5254 ** conversion of pointer to integer
5355 ** this is for hashing only; there is no problem if the integer
@@ -104,6 +106,7 @@ typedef LUAI_UACNUMBER l_uacNumber; · 50 unmodified lines
104106
105107 #define cast(t, exp) ((t)(exp))
106108
109+#define cast_void(i) cast(void, (i))
107110 #define cast_byte(i) cast(lu_byte, (i))
108111 #define cast_num(i) cast(lua_Number, (i))
109112 #define cast_int(i) cast(int, (i))
@@ -155,7 +158,7 @@ typedef lu_int32 Instruction; · 45 unmodified lines
155158
156159 /* minimum size for the string table (must be power of 2) */
157160 #if !defined(MINSTRTABSIZE)
158−#define MINSTRTABSIZE 32
161+#define MINSTRTABSIZE 64 /* minimum size for "predefined" strings */
159162 #endif
160163
161164
src/lmathlib.c+11−4
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lmathlib.c,v 1.90 2013/07/03 17:23:19 roberto Exp $
2+** $Id: lmathlib.c,v 1.92 2013/07/22 16:05:53 roberto Exp $
33 ** Standard mathematical library
44 ** See Copyright Notice in lua.h
55 */
@@ -251,9 +251,16 @@ static int math_randomseed (lua_State *L) { · 245 unmodified lines
251251 }
252252
253253
254−static int math_isfloat (lua_State *L) {
254+static int math_type (lua_State *L) {
255255 luaL_checkany(L, 1);
256− lua_pushboolean(L, (lua_type(L, 1) == LUA_TNUMBER && !lua_isinteger(L, 1)));
256+ if (lua_type(L, 1) == LUA_TNUMBER) {
257+ if (lua_isinteger(L, 1))
258+ lua_pushliteral(L, "integer");
259+ else
260+ lua_pushliteral(L, "float");
261+ }
262+ else
263+ lua_pushnil(L);
257264 return 1;
258265 }
259266
@@ -273,7 +280,6 @@ static const luaL_Reg mathlib[] = { · 13 unmodified lines
273280 {"ifloor", math_ifloor},
274281 {"fmod", math_fmod},
275282 {"frexp", math_frexp},
276− {"isfloat", math_isfloat},
277283 {"ldexp", math_ldexp},
278284 #if defined(LUA_COMPAT_LOG10)
279285 {"log10", math_log10},
@@ -291,6 +297,7 @@ static const luaL_Reg mathlib[] = { · 11 unmodified lines
291297 {"sqrt", math_sqrt},
292298 {"tanh", math_tanh},
293299 {"tan", math_tan},
300+ {"type", math_type},
294301 {NULL, NULL}
295302 };
296303
src/loadlib.c+15−19
@@ -1,5 +1,5 @@
11 /*
2−** $Id: loadlib.c,v 1.111 2012/05/30 12:33:44 roberto Exp $
2+** $Id: loadlib.c,v 1.113 2014/03/12 20:57:40 roberto Exp $
33 ** Dynamic library loader for Lua
44 ** See Copyright Notice in lua.h
55 **
@@ -31,21 +31,21 @@ · 25 unmodified lines
3131
3232
3333 /*
34−** LUA_PATH and LUA_CPATH are the names of the environment
34+** LUA_PATH_VAR and LUA_CPATH_VAR are the names of the environment
3535 ** variables that Lua check to set its paths.
3636 */
37−#if !defined(LUA_PATH)
38−#define LUA_PATH "LUA_PATH"
37+#if !defined(LUA_PATH_VAR)
38+#define LUA_PATH_VAR "LUA_PATH"
3939 #endif
4040
41−#if !defined(LUA_CPATH)
42−#define LUA_CPATH "LUA_CPATH"
41+#if !defined(LUA_CPATH_VAR)
42+#define LUA_CPATH_VAR "LUA_CPATH"
4343 #endif
4444
4545 #define LUA_PATHSUFFIX "_" LUA_VERSION_MAJOR "_" LUA_VERSION_MINOR
4646
47−#define LUA_PATHVERSION LUA_PATH LUA_PATHSUFFIX
48−#define LUA_CPATHVERSION LUA_CPATH LUA_PATHSUFFIX
47+#define LUA_PATHVARVERSION LUA_PATH_VAR LUA_PATHSUFFIX
48+#define LUA_CPATHVARVERSION LUA_CPATH_VAR LUA_PATHSUFFIX
4949
5050 /*
5151 ** LUA_PATH_SEP is the character that separates templates in a path.
@@ -468,8 +468,7 @@ static int searcher_Croot (lua_State *L) { · 416 unmodified lines
468468 static int searcher_preload (lua_State *L) {
469469 const char *name = luaL_checkstring(L, 1);
470470 lua_getfield(L, LUA_REGISTRYINDEX, "_PRELOAD");
471− lua_getfield(L, -1, name);
472− if (lua_isnil(L, -1)) /* not found? */
471+ if (lua_getfield(L, -1, name) == LUA_TNIL) /* not found? */
473472 lua_pushfstring(L, "\n\tno field package.preload['%s']", name);
474473 return 1;
475474 }
@@ -484,8 +483,7 @@ static void findloader (lua_State *L, const char *name) { · 8 unmodified lines
484483 luaL_error(L, LUA_QL("package.searchers") " must be a table");
485484 /* iterate over available searchers to find a loader */
486485 for (i = 1; ; i++) {
487− lua_rawgeti(L, 3, i); /* get a searcher */
488− if (lua_isnil(L, -1)) { /* no more searchers? */
486+ if (lua_rawgeti(L, 3, i) == LUA_TNIL) { /* no more searchers? */
489487 lua_pop(L, 1); /* remove nil */
490488 luaL_pushresult(&msg); /* create error message */
491489 luaL_error(L, "module " LUA_QS " not found:%s",
@@ -520,8 +518,7 @@ static int ll_require (lua_State *L) { · 28 unmodified lines
520518 lua_call(L, 2, 1); /* run loader to load module */
521519 if (!lua_isnil(L, -1)) /* non-nil return? */
522520 lua_setfield(L, 2, name); /* _LOADED[name] = returned value */
523− lua_getfield(L, 2, name);
524− if (lua_isnil(L, -1)) { /* module did not set a value? */
521+ if (lua_getfield(L, 2, name) == LUA_TNIL) { /* module set no value? */
525522 lua_pushboolean(L, 1); /* use true as result */
526523 lua_pushvalue(L, -1); /* extra copy to be returned */
527524 lua_setfield(L, 2, name); /* _LOADED[name] = true */
@@ -587,9 +584,8 @@ static int ll_module (lua_State *L) { · 59 unmodified lines
587584 int lastarg = lua_gettop(L); /* last parameter */
588585 luaL_pushmodule(L, modname, 1); /* get/create module table */
589586 /* check whether table already has a _NAME field */
590− lua_getfield(L, -1, "_NAME");
591− if (!lua_isnil(L, -1)) /* is table an initialized module? */
592− lua_pop(L, 1);
587+ if (lua_getfield(L, -1, "_NAME") != LUA_TNIL)
588+ lua_pop(L, 1); /* table is an initialized module */
593589 else { /* no; initialize it */
594590 lua_pop(L, 1);
595591 modinit(L, modname);
@@ -703,9 +699,9 @@ LUAMOD_API int luaopen_package (lua_State *L) { · 107 unmodified lines
703699 #endif
704700 lua_setfield(L, -2, "searchers"); /* put it in field 'searchers' */
705701 /* set field 'path' */
706− setpath(L, "path", LUA_PATHVERSION, LUA_PATH, LUA_PATH_DEFAULT);
702+ setpath(L, "path", LUA_PATHVARVERSION, LUA_PATH_VAR, LUA_PATH_DEFAULT);
707703 /* set field 'cpath' */
708− setpath(L, "cpath", LUA_CPATHVERSION, LUA_CPATH, LUA_CPATH_DEFAULT);
704+ setpath(L, "cpath", LUA_CPATHVARVERSION, LUA_CPATH_VAR, LUA_CPATH_DEFAULT);
709705 /* store config information */
710706 lua_pushliteral(L, LUA_DIRSEP "\n" LUA_PATH_SEP "\n" LUA_PATH_MARK "\n"
711707 LUA_EXEC_DIR "\n" LUA_IGMARK "\n");
src/lobject.c+88−38
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lobject.c,v 2.67 2013/06/25 18:58:32 roberto Exp $
2+** $Id: lobject.c,v 2.76 2014/03/21 13:52:33 roberto Exp $
33 ** Some generic functions over Lua objects
44 ** See Copyright Notice in lua.h
55 */
@@ -77,22 +77,30 @@ static lua_Integer intarith (lua_State *L, int op, lua_Integer v1, · 71 unmodified lines
7777 case LUA_OPSUB:return intop(-, v1, v2);
7878 case LUA_OPMUL:return intop(*, v1, v2);
7979 case LUA_OPMOD: return luaV_mod(L, v1, v2);
80− case LUA_OPPOW: return luaV_pow(v1, v2);
81− case LUA_OPUNM: return -v1;
80+ case LUA_OPPOW: return luaV_pow(L, v1, v2);
81+ case LUA_OPIDIV: return luaV_div(L, v1, v2);
82+ case LUA_OPBAND: return intop(&, v1, v2);
83+ case LUA_OPBOR: return intop(|, v1, v2);
84+ case LUA_OPBXOR: return intop(^, v1, v2);
85+ case LUA_OPSHL: return luaV_shiftl(v1, v2);
86+ case LUA_OPSHR: return luaV_shiftl(v1, -v2);
87+ case LUA_OPUNM: return intop(-, 0, v1);
88+ case LUA_OPBNOT: return intop(^, cast_integer(-1), v1);
8289 default: lua_assert(0); return 0;
8390 }
8491 }
8592
8693
87−static lua_Number numarith (int op, lua_Number v1, lua_Number v2) {
94+static lua_Number numarith (lua_State *L, int op, lua_Number v1,
95+ lua_Number v2) {
8896 switch (op) {
89− case LUA_OPADD: return luai_numadd(NULL, v1, v2);
90− case LUA_OPSUB: return luai_numsub(NULL, v1, v2);
91− case LUA_OPMUL: return luai_nummul(NULL, v1, v2);
92− case LUA_OPDIV: return luai_numdiv(NULL, v1, v2);
93− case LUA_OPMOD: return luai_nummod(NULL, v1, v2);
94− case LUA_OPPOW: return luai_numpow(NULL, v1, v2);
95− case LUA_OPUNM: return luai_numunm(NULL, v1);
97+ case LUA_OPADD: return luai_numadd(L, v1, v2);
98+ case LUA_OPSUB: return luai_numsub(L, v1, v2);
99+ case LUA_OPMUL: return luai_nummul(L, v1, v2);
100+ case LUA_OPDIV: return luai_numdiv(L, v1, v2);
101+ case LUA_OPMOD: return luai_nummod(L, v1, v2);
102+ case LUA_OPPOW: return luai_numpow(L, v1, v2);
103+ case LUA_OPUNM: return luai_numunm(L, v1);
96104 default: lua_assert(0); return 0;
97105 }
98106 }
@@ -100,29 +108,40 @@ static lua_Number numarith (int op, lua_Number v1, lua_Number v2) { · 1 unmodified line
100108
101109 void luaO_arith (lua_State *L, int op, const TValue *p1, const TValue *p2,
102110 TValue *res) {
103− if (op == LUA_OPIDIV) { /* operates only on integers */
104− lua_Integer i1; lua_Integer i2;
105− if (tointeger(p1, &i1) && tointeger(p2, &i2)) {
106− setivalue(res, luaV_div(L, i1, i2));
107− return;
111+ switch (op) {
112+ case LUA_OPIDIV: case LUA_OPBAND: case LUA_OPBOR:
113+ case LUA_OPBXOR: case LUA_OPSHL: case LUA_OPSHR:
114+ case LUA_OPBNOT: { /* operates only on integers */
115+ lua_Integer i1; lua_Integer i2;
116+ if (tointeger(p1, &i1) && tointeger(p2, &i2)) {
117+ setivalue(res, intarith(L, op, i1, i2));
118+ return;
119+ }
120+ else break; /* go to the end */
108121 }
109− /* else go to the end */
110− }
111− else { /* other operations */
112− lua_Number n1; lua_Number n2;
113− if (ttisinteger(p1) && ttisinteger(p2) && op != LUA_OPDIV &&
114− (op != LUA_OPPOW || ivalue(p2) >= 0)) {
115− setivalue(res, intarith(L, op, ivalue(p1), ivalue(p2)));
116− return;
122+ case LUA_OPDIV: { /* operates only on floats */
123+ lua_Number n1; lua_Number n2;
124+ if (tonumber(p1, &n1) && tonumber(p2, &n2)) {
125+ setnvalue(res, numarith(L, op, n1, n2));
126+ return;
127+ }
128+ else break; /* go to the end */
117129 }
118− else if (tonumber(p1, &n1) && tonumber(p2, &n2)) {
119− setnvalue(res, numarith(op, n1, n2));
120− return;
130+ default: { /* other operations */
131+ lua_Number n1; lua_Number n2;
132+ if (ttisinteger(p1) && ttisinteger(p2)) {
133+ setivalue(res, intarith(L, op, ivalue(p1), ivalue(p2)));
134+ return;
135+ }
136+ else if (tonumber(p1, &n1) && tonumber(p2, &n2)) {
137+ setnvalue(res, numarith(L, op, n1, n2));
138+ return;
139+ }
140+ else break; /* go to the end */
121141 }
122− /* else go to the end */
123142 }
124− /* could not perform raw operation; try metmethod */
125− lua_assert(L != NULL); /* cannot fail when folding (compile time) */
143+ /* could not perform raw operation; try metamethod */
144+ lua_assert(L != NULL); /* should not fail when folding (compile time) */
126145 luaT_trybinTM(L, p1, p2, res, cast(TMS, op - LUA_OPADD + TM_ADD));
127146 }
128147
@@ -141,22 +160,26 @@ static int isneg (const char **s) { · 12 unmodified lines
141160
142161
143162 /*
163+** {======================================================
144164 ** lua_strx2number converts an hexadecimal numeric string to a number.
145165 ** In C99, 'strtod' does both conversions. C89, however, has no function
146166 ** to convert floating hexadecimal strings to numbers. For these
147167 ** systems, you can leave 'lua_strx2number' undefined and Lua will
148168 ** provide its own implementation.
169+** =======================================================
149170 */
150−#if defined(LUA_USE_STRTODHEX)
171+#if !defined(lua_strx2number) /* { */
172+
173+#if defined(LUA_USE_C99) /* { */
174+
151175 #define lua_strx2number(s,p) lua_str2number(s,p)
152−#endif
153176
177+#else /* }{ */
154178
155−#if !defined(lua_strx2number)
179+/* Lua's implementation for 'lua_strx2number' */
156180
157181 #include <math.h>
158182
159−
160183 /* maximum number of significant digits to read (to avoid overflows
161184 even with single floats) */
162185 #define MAXSIGDIG 30
@@ -219,7 +242,11 @@ static lua_Number lua_strx2number (const char *s, char **endptr) { · 56 unmodified lines
219242 return l_mathop(ldexp)(r, e);
220243 }
221244
222−#endif
245+#endif /* } */
246+
247+#endif /* } */
248+
249+/* }====================================================== */
223250
224251
225252 int luaO_str2d (const char *s, size_t len, lua_Number *result) {
@@ -260,19 +287,36 @@ int luaO_str2int (const char *s, size_t len, lua_Integer *result) { · 34 unmodified lines
260287 while (lisspace(cast_uchar(*s))) s++; /* skip trailing spaces */
261288 if (empty || s != ends) return 0; /* something wrong in the numeral */
262289 else {
263− if (neg) *result = -cast(lua_Integer, a);
264− else *result = cast(lua_Integer, a);
290+ *result = cast_integer((neg) ? 0u - a : a);
265291 return 1;
266292 }
267293 }
268294
269295
296+int luaO_utf8esc (char *buff, unsigned int x) {
297+ int n = 1; /* number of bytes put in buffer (backwards) */
298+ if (x < 0x80) /* ascii? */
299+ buff[UTF8BUFFSZ - 1] = x;
300+ else { /* need continuation bytes */
301+ unsigned int mfb = 0x3f; /* maximum that fits in first byte */
302+ do {
303+ buff[UTF8BUFFSZ - (n++)] = 0x80 | (x & 0x3f); /* add continuation byte */
304+ x >>= 6; /* remove added bits */
305+ mfb >>= 1; /* now there is one less bit available in first byte */
306+ } while (x > mfb); /* still needs continuation byte? */
307+ buff[UTF8BUFFSZ - n] = (~mfb << 1) | x; /* add first byte */
308+ }
309+ return n;
310+}
311+
312+
270313 static void pushstr (lua_State *L, const char *str, size_t l) {
271314 setsvalue2s(L, L->top++, luaS_newlstr(L, str, l));
272315 }
273316
274317
275−/* this function handles only `%d', `%c', %f, %p, and `%s' formats */
318+/* this function handles only '%d', '%c', '%f', '%p', and '%s'
319+ conventional formats, plus Lua-specific '%L' and '%U' */
276320 const char *luaO_pushvfstring (lua_State *L, const char *fmt, va_list argp) {
277321 int n = 0;
278322 for (;;) {
@@ -311,6 +355,12 @@ const char *luaO_pushvfstring (lua_State *L, const char *fmt, va_list argp) { · 32 unmodified lines
311355 pushstr(L, buff, l);
312356 break;
313357 }
358+ case 'U': {
359+ char buff[UTF8BUFFSZ];
360+ int l = luaO_utf8esc(buff, va_arg(argp, int));
361+ pushstr(L, buff + UTF8BUFFSZ - l, l);
362+ break;
363+ }
314364 case '%': {
315365 pushstr(L, "%", 1);
316366 break;
src/lobject.h+25−20
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lobject.h,v 2.78 2013/05/14 15:59:04 roberto Exp $
2+** $Id: lobject.h,v 2.86 2014/02/19 13:52:42 roberto Exp $
33 ** Type definitions for Lua objects
44 ** See Copyright Notice in lua.h
55 */
@@ -20,13 +20,12 @@ · 14 unmodified lines
2020 ** Extra tags for non-values
2121 */
2222 #define LUA_TPROTO LUA_NUMTAGS
23−#define LUA_TUPVAL (LUA_NUMTAGS+1)
24−#define LUA_TDEADKEY (LUA_NUMTAGS+2)
23+#define LUA_TDEADKEY (LUA_NUMTAGS+1)
2524
2625 /*
2726 ** number of all possible tags (including LUA_TNONE but excluding DEADKEY)
2827 */
29−#define LUA_TOTALTAGS (LUA_TUPVAL+2)
28+#define LUA_TOTALTAGS (LUA_TPROTO + 2)
3029
3130
3231 /*
@@ -147,7 +146,7 @@ typedef struct lua_TValue TValue; · 114 unmodified lines
147146 #define ttisCclosure(o) checktag((o), ctb(LUA_TCCL))
148147 #define ttisLclosure(o) checktag((o), ctb(LUA_TLCL))
149148 #define ttislcf(o) checktag((o), LUA_TLCF)
150−#define ttisuserdata(o) checktag((o), ctb(LUA_TUSERDATA))
149+#define ttisfulluserdata(o) checktag((o), ctb(LUA_TUSERDATA))
151150 #define ttisthread(o) checktag((o), ctb(LUA_TTHREAD))
152151 #define ttisdeadkey(o) checktag((o), LUA_TDEADKEY)
153152
@@ -159,7 +158,7 @@ typedef struct lua_TValue TValue; · 5 unmodified lines
159158 #define pvalue(o) check_exp(ttislightuserdata(o), val_(o).p)
160159 #define rawtsvalue(o) check_exp(ttisstring(o), &val_(o).gc->ts)
161160 #define tsvalue(o) (&rawtsvalue(o)->tsv)
162−#define rawuvalue(o) check_exp(ttisuserdata(o), &val_(o).gc->u)
161+#define rawuvalue(o) check_exp(ttisfulluserdata(o), &val_(o).gc->u)
163162 #define uvalue(o) (&rawuvalue(o)->uv)
164163 #define clvalue(o) check_exp(ttisclosure(o), &val_(o).gc->cl)
165164 #define clLvalue(o) check_exp(ttisLclosure(o), &val_(o).gc->cl.l)
@@ -311,8 +310,9 @@ typedef union TString { · 145 unmodified lines
311310 struct {
312311 CommonHeader;
313312 lu_byte extra; /* reserved words for short strings; "has hash" for longs */
314− unsigned int hash;
315313 size_t len; /* number of characters in string */
314+ union TString *hnext; /* linked list for hash table */
315+ unsigned int hash;
316316 } tsv;
317317 } TString;
318318
@@ -331,13 +331,25 @@ typedef union Udata { · 12 unmodified lines
331331 L_Umaxalign dummy; /* ensures maximum alignment for `local' udata */
332332 struct {
333333 CommonHeader;
334+ lu_byte ttuv_; /* user value's tag */
334335 struct Table *metatable;
335− struct Table *env;
336336 size_t len; /* number of bytes */
337+ union Value user_; /* user value */
337338 } uv;
338339 } Udata;
339340
340341
342+#define setuservalue(L,u,o) \
343+ { const TValue *io=(o); Udata *iu = (u); \
344+ iu->uv.user_ = io->value_; iu->uv.ttuv_ = io->tt_; \
345+ checkliveness(G(L),io); }
346+
347+
348+#define getuservalue(L,u,o) \
349+ { TValue *io=(o); const Udata *iu = (u); \
350+ io->value_ = iu->uv.user_; io->tt_ = iu->uv.ttuv_; \
351+ checkliveness(G(L),io); }
352+
341353
342354 /*
343355 ** Description of an upvalue for function prototypes
@@ -392,17 +404,7 @@ typedef struct Proto { · 48 unmodified lines
392404 /*
393405 ** Lua Upvalues
394406 */
395−typedef struct UpVal {
396− CommonHeader;
397− TValue *v; /* points to stack or to its own value */
398− union {
399− TValue value; /* the value (when closed) */
400− struct { /* double linked list (when open) */
401− struct UpVal *prev;
402− struct UpVal *next;
403− } l;
404− } u;
405−} UpVal;
407+typedef struct UpVal UpVal;
406408
407409
408410 /*
@@ -444,7 +446,7 @@ typedef union Closure { · 35 unmodified lines
444446 typedef union TKey {
445447 struct {
446448 TValuefields;
447− struct Node *next; /* for chaining */
449+ int next; /* for chaining (offset for next node) */
448450 } nk;
449451 TValue tvk;
450452 } TKey;
@@ -489,9 +491,12 @@ typedef struct Table { · 38 unmodified lines
489491
490492 LUAI_DDEC const TValue luaO_nilobject_;
491493
494+/* size of buffer for 'luaO_utf8esc' function */
495+#define UTF8BUFFSZ 8
492496
493497 LUAI_FUNC int luaO_int2fb (unsigned int x);
494498 LUAI_FUNC int luaO_fb2int (int x);
499+LUAI_FUNC int luaO_utf8esc (char *buff, unsigned int x);
495500 LUAI_FUNC int luaO_ceillog2 (unsigned int x);
496501 LUAI_FUNC void luaO_arith (lua_State *L, int op, const TValue *p1,
497502 const TValue *p2, TValue *res);
src/lopcodes.c+17−5
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lopcodes.c,v 1.50 2013/04/26 13:07:53 roberto Exp $
2+** $Id: lopcodes.c,v 1.53 2013/12/30 20:47:58 roberto Exp $
33 ** Opcodes for Lua virtual machine
44 ** See Copyright Notice in lua.h
55 */
@@ -31,11 +31,17 @@ LUAI_DDEF const char *const luaP_opnames[NUM_OPCODES+1] = { · 25 unmodified lines
3131 "ADD",
3232 "SUB",
3333 "MUL",
34− "DIV",
35− "IDIV",
3634 "MOD",
3735 "POW",
36+ "DIV",
37+ "IDIV",
38+ "BAND",
39+ "BOR",
40+ "BXOR",
41+ "SHL",
42+ "SHR",
3843 "UNM",
44+ "BNOT",
3945 "NOT",
4046 "LEN",
4147 "CONCAT",
@@ -80,11 +86,17 @@ LUAI_DDEF const lu_byte luaP_opmodes[NUM_OPCODES] = { · 38 unmodified lines
8086 ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_ADD */
8187 ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_SUB */
8288 ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_MUL */
83− ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_DIV */
84− ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_IDIV */
8589 ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_MOD */
8690 ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_POW */
91+ ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_DIV */
92+ ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_IDIV */
93+ ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_BAND */
94+ ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_BOR */
95+ ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_BXOR */
96+ ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_SHL */
97+ ,opmode(0, 1, OpArgK, OpArgK, iABC) /* OP_SHR */
8798 ,opmode(0, 1, OpArgR, OpArgN, iABC) /* OP_UNM */
99+ ,opmode(0, 1, OpArgR, OpArgN, iABC) /* OP_BNOT */
88100 ,opmode(0, 1, OpArgR, OpArgN, iABC) /* OP_NOT */
89101 ,opmode(0, 1, OpArgR, OpArgN, iABC) /* OP_LEN */
90102 ,opmode(0, 1, OpArgR, OpArgR, iABC) /* OP_CONCAT */
src/lopcodes.h+9−3
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lopcodes.h,v 1.143 2013/04/26 13:07:53 roberto Exp $
2+** $Id: lopcodes.h,v 1.146 2013/12/30 20:47:58 roberto Exp $
33 ** Opcodes for Lua virtual machine
44 ** See Copyright Notice in lua.h
55 */
@@ -187,11 +187,17 @@ OP_SELF,/* A B C R(A+1) := R(B); R(A) := R(B)[RK(C)] */ · 181 unmodified lines
187187 OP_ADD,/* A B C R(A) := RK(B) + RK(C) */
188188 OP_SUB,/* A B C R(A) := RK(B) - RK(C) */
189189 OP_MUL,/* A B C R(A) := RK(B) * RK(C) */
190−OP_DIV,/* A B C R(A) := RK(B) / RK(C) */
191−OP_IDIV,/* A B C R(A) := RK(B) // RK(C) */
192190 OP_MOD,/* A B C R(A) := RK(B) % RK(C) */
193191 OP_POW,/* A B C R(A) := RK(B) ^ RK(C) */
192+OP_DIV,/* A B C R(A) := RK(B) / RK(C) */
193+OP_IDIV,/* A B C R(A) := RK(B) // RK(C) */
194+OP_BAND,/* A B C R(A) := RK(B) & RK(C) */
195+OP_BOR,/* A B C R(A) := RK(B) | RK(C) */
196+OP_BXOR,/* A B C R(A) := RK(B) ~ RK(C) */
197+OP_SHL,/* A B C R(A) := RK(B) << RK(C) */
198+OP_SHR,/* A B C R(A) := RK(B) >> RK(C) */
194199 OP_UNM,/* A B R(A) := -R(B) */
200+OP_BNOT,/* A B R(A) := ~R(B) */
195201 OP_NOT,/* A B R(A) := not R(B) */
196202 OP_LEN,/* A B R(A) := length of R(B) */
197203
src/loslib.c+42−18
@@ -1,5 +1,5 @@
11 /*
2−** $Id: loslib.c,v 1.41 2013/05/14 15:57:11 roberto Exp $
2+** $Id: loslib.c,v 1.45 2014/03/20 19:18:54 roberto Exp $
33 ** Standard Operating System library
44 ** See Copyright Notice in lua.h
55 */
@@ -20,29 +20,44 @@ · 14 unmodified lines
2020 #include "lualib.h"
2121
2222
23+#if !defined(LUA_STRFTIMEOPTIONS) /* { */
2324 /*
2425 ** list of valid conversion specifiers for the 'strftime' function
2526 */
26−#if !defined(LUA_STRFTIMEOPTIONS)
2727
2828 #if !defined(LUA_USE_POSIX)
2929 #define LUA_STRFTIMEOPTIONS { "aAbBcdHIjmMpSUwWxXyYz%", "" }
3030 #else
3131 #define LUA_STRFTIMEOPTIONS \
32− { "aAbBcCdDeFgGhHIjmMnprRStTuUVwWxXyYzZ%", "" \
33− "", "E", "cCxXyY", \
32+ { "aAbBcCdDeFgGhHIjmMnprRStTuUVwWxXyYzZ%", "", \
33+ "E", "cCxXyY", \
3434 "O", "deHImMSuUVwWy" }
3535 #endif
3636
37−#endif
37+#endif /* } */
38+
39+
40+
41+#if !defined(l_time_t) /* { */
42+/*
43+** type to represent time_t in Lua
44+*/
45+#define l_timet lua_Integer
46+#define l_pushtime(L,t) lua_pushinteger(L,(lua_Integer)(t))
47+#define l_checktime(L,a) ((time_t)luaL_checkinteger(L,a))
3848
49+#endif /* } */
3950
4051
52+
53+#if !defined(lua_tmpnam) /* { */
4154 /*
4255 ** By default, Lua uses tmpnam except when POSIX is available, where it
4356 ** uses mkstemp.
4457 */
45−#if defined(LUA_USE_MKSTEMP)
58+
59+#if defined(LUA_USE_POSIX) /* { */
60+
4661 #include <unistd.h>
4762 #define LUA_TMPNAMBUFSIZE 32
4863 #define lua_tmpnam(b,e) { \
@@ -51,29 +66,38 @@ · 2 unmodified lines
5166 if (e != -1) close(e); \
5267 e = (e == -1); }
5368
54−#elif !defined(lua_tmpnam)
69+#else /* }{ */
5570
71+/* ANSI definitions */
5672 #define LUA_TMPNAMBUFSIZE L_tmpnam
5773 #define lua_tmpnam(b,e) { e = (tmpnam(b) == NULL); }
5874
59−#endif
75+#endif /* } */
76+
77+#endif /* } */
78+
6079
6180
81+#if !defined(l_gmtime) /* { */
6282 /*
6383 ** By default, Lua uses gmtime/localtime, except when POSIX is available,
6484 ** where it uses gmtime_r/localtime_r
6585 */
66−#if defined(LUA_USE_GMTIME_R)
86+
87+#if defined(LUA_USE_POSIX) /* { */
6788
6889 #define l_gmtime(t,r) gmtime_r(t,r)
6990 #define l_localtime(t,r) localtime_r(t,r)
7091
71−#elif !defined(l_gmtime)
92+#else /* }{ */
7293
94+/* ANSI definitions */
7395 #define l_gmtime(t,r) ((void)r, gmtime(t))
7496 #define l_localtime(t,r) ((void)r, localtime(t))
7597
76−#endif
98+#endif /* } */
99+
100+#endif /* } */
77101
78102
79103
@@ -147,8 +171,7 @@ static void setboolfield (lua_State *L, const char *key, int value) { · 67 unmodified lines
147171
148172 static int getboolfield (lua_State *L, const char *key) {
149173 int res;
150− lua_getfield(L, -1, key);
151− res = lua_isnil(L, -1) ? -1 : lua_toboolean(L, -1);
174+ res = (lua_getfield(L, -1, key) == LUA_TNIL) ? -1 : lua_toboolean(L, -1);
152175 lua_pop(L, 1);
153176 return res;
154177 }
@@ -194,7 +217,7 @@ static const char *checkoption (lua_State *L, const char *conv, char *buff) { · 39 unmodified lines
194217
195218 static int os_date (lua_State *L) {
196219 const char *s = luaL_optstring(L, 1, "%c");
197− time_t t = luaL_opt(L, (time_t)luaL_checkinteger, 2, time(NULL));
220+ time_t t = luaL_opt(L, l_checktime, 2, time(NULL));
198221 struct tm tmr, *stm;
199222 if (*s == '!') { /* UTC? */
200223 stm = l_gmtime(&t, &tmr);
@@ -255,17 +278,18 @@ static int os_time (lua_State *L) { · 54 unmodified lines
255278 ts.tm_isdst = getboolfield(L, "isdst");
256279 t = mktime(&ts);
257280 }
258− if (t == (time_t)(-1))
281+ if (t != (time_t)(l_timet)t)
282+ luaL_error(L, "time result cannot be represented in this Lua instalation");
283+ else if (t == (time_t)(-1))
259284 lua_pushnil(L);
260285 else
261− lua_pushinteger(L, t);
286+ l_pushtime(L, t);
262287 return 1;
263288 }
264289
265290
266291 static int os_difftime (lua_State *L) {
267− lua_pushnumber(L, difftime((time_t)(luaL_checkinteger(L, 1)),
268− (time_t)(luaL_optinteger(L, 2, 0))));
292+ lua_pushnumber(L, difftime((l_checktime(L, 1)), (l_checktime(L, 2))));
269293 return 1;
270294 }
271295
src/lparser.c+37−37
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lparser.c,v 2.133 2013/04/26 13:07:53 roberto Exp $
2+** $Id: lparser.c,v 2.138 2013/12/30 20:47:58 roberto Exp $
33 ** Lua Parser
44 ** See Copyright Notice in lua.h
55 */
@@ -35,6 +35,10 @@ · 29 unmodified lines
3535 #define hasmultret(k) ((k) == VCALL || (k) == VVARARG)
3636
3737
38+/* because all strings are unified by the scanner, the parser
39+ can use pointer equality for string equality */
40+#define eqstr(a,b) ((a) == (b))
41+
3842
3943 /*
4044 ** nodes for block list (list of active blocks)
@@ -57,16 +61,6 @@ static void statement (LexState *ls); · 16 unmodified lines
5761 static void expr (LexState *ls, expdesc *v);
5862
5963
60−static void anchor_token (LexState *ls) {
61− /* last token from outer function must be EOS */
62− lua_assert(ls->fs != NULL || ls->t.token == TK_EOS);
63− if (ls->t.token == TK_NAME || ls->t.token == TK_STRING) {
64− TString *ts = ls->t.seminfo.ts;
65− luaX_newstring(ls, getstr(ts), ts->tsv.len);
66− }
67−}
68−
69−
7064 /* semantic error */
7165 static l_noret semerror (LexState *ls, const char *msg) {
7266 ls->t.token = 0; /* remove 'near to' from final message */
@@ -222,7 +216,7 @@ static int searchupvalue (FuncState *fs, TString *name) { · 149 unmodified lines
222216 int i;
223217 Upvaldesc *up = fs->f->upvalues;
224218 for (i = 0; i < fs->nups; i++) {
225− if (luaS_eqstr(up[i].name, name)) return i;
219+ if (eqstr(up[i].name, name)) return i;
226220 }
227221 return -1; /* not found */
228222 }
@@ -246,7 +240,7 @@ static int newupvalue (FuncState *fs, TString *name, expdesc *v) { · 17 unmodified lines
246240 static int searchvar (FuncState *fs, TString *n) {
247241 int i;
248242 for (i = cast_int(fs->nactvar) - 1; i >= 0; i--) {
249− if (luaS_eqstr(n, getlocvar(fs, i)->varname))
243+ if (eqstr(n, getlocvar(fs, i)->varname))
250244 return i;
251245 }
252246 return -1; /* not found */
@@ -342,7 +336,7 @@ static void closegoto (LexState *ls, int g, Labeldesc *label) { · 89 unmodified lines
342336 FuncState *fs = ls->fs;
343337 Labellist *gl = &ls->dyd->gt;
344338 Labeldesc *gt = &gl->arr[g];
345− lua_assert(luaS_eqstr(gt->name, label->name));
339+ lua_assert(eqstr(gt->name, label->name));
346340 if (gt->nactvar < label->nactvar) {
347341 TString *vname = getlocvar(fs, gt->nactvar)->varname;
348342 const char *msg = luaO_pushfstring(ls->L,
@@ -369,7 +363,7 @@ static int findlabel (LexState *ls, int g) { · 20 unmodified lines
369363 /* check labels in current block for a match */
370364 for (i = bl->firstlabel; i < dyd->label.n; i++) {
371365 Labeldesc *lb = &dyd->label.arr[i];
372− if (luaS_eqstr(lb->name, gt->name)) { /* correct label? */
366+ if (eqstr(lb->name, gt->name)) { /* correct label? */
373367 if (gt->nactvar > lb->nactvar &&
374368 (bl->upval || dyd->label.n > bl->firstlabel))
375369 luaK_patchclose(ls->fs, gt->pc, lb->nactvar);
@@ -403,7 +397,7 @@ static void findgotos (LexState *ls, Labeldesc *lb) { · 27 unmodified lines
403397 Labellist *gl = &ls->dyd->gt;
404398 int i = ls->fs->bl->firstgoto;
405399 while (i < gl->n) {
406− if (luaS_eqstr(gl->arr[i].name, lb->name))
400+ if (eqstr(gl->arr[i].name, lb->name))
407401 closegoto(ls, i, lb);
408402 else
409403 i++;
@@ -525,7 +519,6 @@ static void codeclosure (LexState *ls, expdesc *v) { · 115 unmodified lines
525519
526520
527521 static void open_func (LexState *ls, FuncState *fs, BlockCnt *bl) {
528− lua_State *L = ls->L;
529522 Proto *f;
530523 fs->prev = ls->fs; /* linked list of funcstates */
531524 fs->ls = ls;
@@ -544,10 +537,6 @@ static void open_func (LexState *ls, FuncState *fs, BlockCnt *bl) { · 12 unmodified lines
544537 f = fs->f;
545538 f->source = ls->source;
546539 f->maxstacksize = 2; /* registers 0/1 are always valid */
547− fs->h = luaH_new(L);
548− /* anchor table of constants (to avoid being collected) */
549− sethvalue2s(L, L->top, fs->h);
550− incr_top(L);
551540 enterblock(fs, bl, 0);
552541 }
553542
@@ -572,9 +561,6 @@ static void close_func (LexState *ls) { · 18 unmodified lines
572561 f->sizeupvalues = fs->nups;
573562 lua_assert(fs->bl == NULL);
574563 ls->fs = fs->prev;
575− /* last token read was anchored in defunct function; must re-anchor it */
576− anchor_token(ls);
577− L->top--; /* pop table of constants */
578564 luaC_checkGC(L);
579565 }
580566
@@ -993,6 +979,7 @@ static UnOpr getunopr (int op) { · 412 unmodified lines
993979 switch (op) {
994980 case TK_NOT: return OPR_NOT;
995981 case '-': return OPR_MINUS;
982+ case '~': return OPR_BNOT;
996983 case '#': return OPR_LEN;
997984 default: return OPR_NOUNOPR;
998985 }
@@ -1004,10 +991,15 @@ static BinOpr getbinopr (int op) { · 5 unmodified lines
1004991 case '+': return OPR_ADD;
1005992 case '-': return OPR_SUB;
1006993 case '*': return OPR_MUL;
1007− case '/': return OPR_DIV;
1008− case TK_IDIV: return OPR_IDIV;
1009994 case '%': return OPR_MOD;
1010995 case '^': return OPR_POW;
996+ case '/': return OPR_DIV;
997+ case TK_IDIV: return OPR_IDIV;
998+ case '&': return OPR_BAND;
999+ case '|': return OPR_BOR;
1000+ case '~': return OPR_BXOR;
1001+ case TK_SHL: return OPR_SHL;
1002+ case TK_SHR: return OPR_SHR;
10111003 case TK_CONCAT: return OPR_CONCAT;
10121004 case TK_NE: return OPR_NE;
10131005 case TK_EQ: return OPR_EQ;
@@ -1026,15 +1018,19 @@ static const struct { · 12 unmodified lines
10261018 lu_byte left; /* left priority for each binary operator */
10271019 lu_byte right; /* right priority */
10281020 } priority[] = { /* ORDER OPR */
1029− {6, 6}, {6, 6}, /* '+' '-' */
1030− {7, 7}, {7, 7}, {7, 7}, {7, 7}, /* '*' '/' '//' '%' */
1031− {10, 9}, {5, 4}, /* ^, .. (right associative) */
1032− {3, 3}, {3, 3}, {3, 3}, /* ==, <, <= */
1033− {3, 3}, {3, 3}, {3, 3}, /* ~=, >, >= */
1034− {2, 2}, {1, 1} /* and, or */
1021+ {10, 10}, {10, 10}, /* '+' '-' */
1022+ {11, 11}, {11, 11}, /* '*' '%' */
1023+ {14, 13}, /* '^' (right associative) */
1024+ {11, 11}, {11, 11}, /* '/' '//' */
1025+ {6, 6}, {4, 4}, {5, 5}, /* '&' '|' '~' */
1026+ {7, 7}, {7, 7}, /* '<<' '>>' */
1027+ {9, 8}, /* '..' (right associative) */
1028+ {3, 3}, {3, 3}, {3, 3}, /* ==, <, <= */
1029+ {3, 3}, {3, 3}, {3, 3}, /* ~=, >, >= */
1030+ {2, 2}, {1, 1} /* and, or */
10351031 };
10361032
1037−#define UNARY_PRIORITY 8 /* priority for unary operators */
1033+#define UNARY_PRIORITY 12 /* priority for unary operators */
10381034
10391035
10401036 /*
@@ -1202,7 +1198,7 @@ static void gotostat (LexState *ls, int pc) { · 161 unmodified lines
12021198 static void checkrepeated (FuncState *fs, Labellist *ll, TString *label) {
12031199 int i;
12041200 for (i = fs->bl->firstlabel; i < ll->n; i++) {
1205− if (luaS_eqstr(label, ll->arr[i].name)) {
1201+ if (eqstr(label, ll->arr[i].name)) {
12061202 const char *msg = luaO_pushfstring(fs->ls->L,
12071203 "label " LUA_QS " already defined on line %d",
12081204 getstr(label), ll->arr[i].line);
@@ -1627,11 +1623,14 @@ Closure *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff, · 418 unmodified lines
16271623 LexState lexstate;
16281624 FuncState funcstate;
16291625 Closure *cl = luaF_newLclosure(L, 1); /* create main closure */
1630− /* anchor closure (to avoid being collected) */
1631− setclLvalue(L, L->top, cl);
1626+ setclLvalue(L, L->top, cl); /* anchor it (to avoid being collected) */
1627+ incr_top(L);
1628+ lexstate.h = luaH_new(L); /* create table for scanner */
1629+ sethvalue(L, L->top, lexstate.h); /* anchor it */
16321630 incr_top(L);
16331631 funcstate.f = cl->l.p = luaF_newproto(L);
16341632 funcstate.f->source = luaS_new(L, name); /* create and anchor TString */
1633+ luaC_objbarrier(L, funcstate.f, funcstate.f->source);
16351634 lexstate.buff = buff;
16361635 lexstate.dyd = dyd;
16371636 dyd->actvar.n = dyd->gt.n = dyd->label.n = 0;
@@ -1640,6 +1639,7 @@ Closure *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff, · 2 unmodified lines
16401639 lua_assert(!funcstate.prev && funcstate.nups == 1 && !lexstate.fs);
16411640 /* all scopes should be correctly finished */
16421641 lua_assert(dyd->actvar.n == 0 && dyd->gt.n == 0 && dyd->label.n == 0);
1643− return cl; /* it's on the stack too */
1642+ L->top--; /* remove scanner's table */
1643+ return cl; /* closure is on the stack, too */
16441644 }
16451645
src/lparser.h+1−2
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lparser.h,v 1.71 2013/04/16 18:46:28 roberto Exp $
2+** $Id: lparser.h,v 1.72 2013/08/30 16:01:37 roberto Exp $
33 ** Lua Parser
44 ** See Copyright Notice in lua.h
55 */
@@ -97,7 +97,6 @@ struct BlockCnt; /* defined in lparser.c */ · 91 unmodified lines
9797 /* state needed to generate code for a given function */
9898 typedef struct FuncState {
9999 Proto *f; /* current function header */
100− Table *h; /* table to find (and reuse) elements in `k' */
101100 struct FuncState *prev; /* enclosing function */
102101 struct LexState *ls; /* lexical state */
103102 struct BlockCnt *bl; /* chain of current blocks */
src/lstate.c+53−32
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lstate.c,v 2.99 2012/10/02 17:40:53 roberto Exp $
2+** $Id: lstate.c,v 2.121 2014/02/18 13:46:26 roberto Exp $
33 ** Global State
44 ** See Copyright Notice in lua.h
55 */
@@ -30,10 +30,6 @@ · 24 unmodified lines
3030 #define LUAI_GCPAUSE 200 /* 200% */
3131 #endif
3232
33−#if !defined(LUAI_GCMAJOR)
34−#define LUAI_GCMAJOR 200 /* 200% */
35−#endif
36−
3733 #if !defined(LUAI_GCMUL)
3834 #define LUAI_GCMUL 200 /* GC runs 'twice the speed' of memory allocation */
3935 #endif
@@ -119,6 +115,9 @@ CallInfo *luaE_extendCI (lua_State *L) { · 79 unmodified lines
119115 }
120116
121117
118+/*
119+** free all CallInfo structures not in use by a thread
120+*/
122121 void luaE_freeCI (lua_State *L) {
123122 CallInfo *ci = L->ci;
124123 CallInfo *next = ci->next;
@@ -130,6 +129,22 @@ void luaE_freeCI (lua_State *L) { · 5 unmodified lines
130129 }
131130
132131
132+/*
133+** free half of the CallInfo structures not in use by a thread
134+*/
135+void luaE_shrinkCI (lua_State *L) {
136+ CallInfo *ci = L->ci;
137+ while (ci->next != NULL) { /* while there is 'next' */
138+ CallInfo *next2 = ci->next->next; /* next's next */
139+ if (next2 == NULL) break;
140+ luaM_free(L, ci->next); /* remove next */
141+ ci->next = next2; /* remove 'next' from the list */
142+ next2->previous = ci;
143+ ci = next2;
144+ }
145+}
146+
147+
133148 static void stack_init (lua_State *L1, lua_State *L) {
134149 int i; CallInfo *ci;
135150 /* initialize stack array */
@@ -163,22 +178,23 @@ static void freestack (lua_State *L) { · 27 unmodified lines
163178 ** Create registry table and its predefined values
164179 */
165180 static void init_registry (lua_State *L, global_State *g) {
166− TValue mt;
181+ TValue temp;
167182 /* create registry */
168183 Table *registry = luaH_new(L);
169184 sethvalue(L, &g->l_registry, registry);
170185 luaH_resize(L, registry, LUA_RIDX_LAST, 0);
171186 /* registry[LUA_RIDX_MAINTHREAD] = L */
172− setthvalue(L, &mt, L);
173− luaH_setint(L, registry, LUA_RIDX_MAINTHREAD, &mt);
187+ setthvalue(L, &temp, L); /* temp = L */
188+ luaH_setint(L, registry, LUA_RIDX_MAINTHREAD, &temp);
174189 /* registry[LUA_RIDX_GLOBALS] = table of globals */
175− sethvalue(L, &mt, luaH_new(L));
176− luaH_setint(L, registry, LUA_RIDX_GLOBALS, &mt);
190+ sethvalue(L, &temp, luaH_new(L)); /* temp = new table (global table) */
191+ luaH_setint(L, registry, LUA_RIDX_GLOBALS, &temp);
177192 }
178193
179194
180195 /*
181−** open parts of the state that may cause memory-allocation errors
196+** open parts of the state that may cause memory-allocation errors.
197+** ('g->version' != NULL flags that the state was completely build)
182198 */
183199 static void f_luaopen (lua_State *L, void *ud) {
184200 global_State *g = G(L);
@@ -190,20 +206,23 @@ static void f_luaopen (lua_State *L, void *ud) { · 5 unmodified lines
190206 luaX_init(L);
191207 /* pre-create memory-error message */
192208 g->memerrmsg = luaS_newliteral(L, MEMERRMSG);
193− luaS_fix(g->memerrmsg); /* it should never be collected */
209+ luaC_fix(L, obj2gco(g->memerrmsg)); /* it should never be collected */
194210 g->gcrunning = 1; /* allow gc */
211+ g->version = lua_version(NULL);
212+ luai_userstateopen(L);
195213 }
196214
197215
198216 /*
199−** preinitialize a state with consistent values without allocating
217+** preinitialize a thread with consistent values without allocating
200218 ** any memory (to avoid errors)
201219 */
202−static void preinit_state (lua_State *L, global_State *g) {
220+static void preinit_thread (lua_State *L, global_State *g) {
203221 G(L) = g;
204222 L->stack = NULL;
205223 L->ci = NULL;
206224 L->stacksize = 0;
225+ L->twups = L; /* thread has no upvalues */
207226 L->errorJmp = NULL;
208227 L->nCcalls = 0;
209228 L->hook = NULL;
@@ -222,6 +241,8 @@ static void close_state (lua_State *L) { · 12 unmodified lines
222241 global_State *g = G(L);
223242 luaF_close(L, L->stack); /* close all upvalues for this thread */
224243 luaC_freeallobjects(L); /* collect all objects */
244+ if (g->version) /* closing a fully built state? */
245+ luai_userstateclose(L);
225246 luaM_freearray(L, G(L)->strt.hash, G(L)->strt.size);
226247 luaZ_freebuffer(L, &g->buff);
227248 freestack(L);
@@ -231,13 +252,20 @@ static void close_state (lua_State *L) { · 3 unmodified lines
231252
232253
233254 LUA_API lua_State *lua_newthread (lua_State *L) {
255+ global_State *g = G(L);
234256 lua_State *L1;
235257 lua_lock(L);
236258 luaC_checkGC(L);
237− L1 = &luaC_newobj(L, LUA_TTHREAD, sizeof(LX), NULL, offsetof(LX, l))->th;
259+ /* create new thread */
260+ L1 = &cast(LX *, luaM_newobject(L, LUA_TTHREAD, sizeof(LX)))->l;
261+ L1->marked = luaC_white(g);
262+ L1->tt = LUA_TTHREAD;
263+ /* link it on list 'allgc' */
264+ L1->next = g->allgc;
265+ g->allgc = obj2gco(L1);
238266 setthvalue(L, L->top, L1);
239267 api_incr_top(L);
240− preinit_state(L1, G(L));
268+ preinit_thread(L1, g);
241269 L1->hookmask = L->hookmask;
242270 L1->basehookcount = L->basehookcount;
243271 L1->hook = L->hook;
@@ -269,36 +297,32 @@ LUA_API lua_State *lua_newstate (lua_Alloc f, void *ud) { · 25 unmodified lines
269297 g = &l->g;
270298 L->next = NULL;
271299 L->tt = LUA_TTHREAD;
272− g->currentwhite = bit2mask(WHITE0BIT, FIXEDBIT);
300+ g->currentwhite = bitmask(WHITE0BIT);
273301 L->marked = luaC_white(g);
274− g->gckind = KGC_NORMAL;
275− preinit_state(L, g);
302+ preinit_thread(L, g);
276303 g->frealloc = f;
277304 g->ud = ud;
278305 g->mainthread = L;
279306 g->seed = makeseed(L);
280− g->uvhead.u.l.prev = &g->uvhead;
281− g->uvhead.u.l.next = &g->uvhead;
282307 g->gcrunning = 0; /* no GC while building state */
283308 g->GCestimate = 0;
284− g->strt.size = 0;
285− g->strt.nuse = 0;
309+ g->strt.size = g->strt.nuse = 0;
286310 g->strt.hash = NULL;
287311 setnilvalue(&g->l_registry);
288312 luaZ_initbuffer(L, &g->buff);
289313 g->panic = NULL;
290− g->version = lua_version(NULL);
314+ g->version = NULL;
291315 g->gcstate = GCSpause;
292− g->allgc = NULL;
293− g->finobj = NULL;
294− g->tobefnz = NULL;
295− g->sweepgc = g->sweepfin = NULL;
316+ g->gckind = KGC_NORMAL;
317+ g->allgc = g->finobj = g->tobefnz = g->fixedgc = NULL;
318+ g->sweepgc = NULL;
296319 g->gray = g->grayagain = NULL;
297320 g->weak = g->ephemeron = g->allweak = NULL;
321+ g->twups = NULL;
298322 g->totalbytes = sizeof(LG);
299323 g->GCdebt = 0;
324+ g->gcfinnum = 0;
300325 g->gcpause = LUAI_GCPAUSE;
301− g->gcmajorinc = LUAI_GCMAJOR;
302326 g->gcstepmul = LUAI_GCMUL;
303327 for (i=0; i < LUA_NUMTAGS; i++) g->mt[i] = NULL;
304328 if (luaD_rawrunprotected(L, f_luaopen, NULL) != LUA_OK) {
@@ -306,8 +330,6 @@ LUA_API lua_State *lua_newstate (lua_Alloc f, void *ud) { · 1 unmodified line
306330 close_state(L);
307331 L = NULL;
308332 }
309− else
310− luai_userstateopen(L);
311333 return L;
312334 }
313335
@@ -315,7 +337,6 @@ LUA_API lua_State *lua_newstate (lua_Alloc f, void *ud) { · 1 unmodified line
315337 LUA_API void lua_close (lua_State *L) {
316338 L = G(L)->mainthread; /* only the main thread can be closed */
317339 lua_lock(L);
318− luai_userstateclose(L);
319340 close_state(L);
320341 }
321342
src/lstate.h+19−30
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lstate.h,v 2.82 2012/07/02 13:37:04 roberto Exp $
2+** $Id: lstate.h,v 2.102 2014/02/18 13:46:26 roberto Exp $
33 ** Global State
44 ** See Copyright Notice in lua.h
55 */
@@ -16,25 +16,16 @@ · 10 unmodified lines
1616
1717 /*
1818
19−** Some notes about garbage-collected objects: All objects in Lua must
20−** be kept somehow accessible until being freed.
19+** Some notes about garbage-collected objects: All objects in Lua must
20+** be kept somehow accessible until being freed, so all objects always
21+** belong to one (and only one) of these lists, using field 'next' of
22+** the 'CommonHeader' for the link:
2123 **
22−** Lua keeps most objects linked in list g->allgc. The link uses field
23−** 'next' of the CommonHeader.
24−**
25−** Strings are kept in several lists headed by the array g->strt.hash.
26−**
27−** Open upvalues are not subject to independent garbage collection. They
28−** are collected together with their respective threads. Lua keeps a
29−** double-linked list with all open upvalues (g->uvhead) so that it can
30−** mark objects referred by them. (They are always gray, so they must
31−** be remarked in the atomic step. Usually their contents would be marked
32−** when traversing the respective threads, but the thread may already be
33−** dead, while the upvalue is still accessible through closures.)
34−**
35−** Objects with finalizers are kept in the list g->finobj.
36−**
37−** The list g->tobefnz links all objects being finalized.
24+** allgc: all objects not marked for finalization;
25+** finobj: all objects marked for finalization;
26+** tobefnz: all objects ready to be finalized;
27+** fixedgc: all objects that are not to be collected (currently
28+** only small strings, such as reserved words).
3829
3930 */
4031
@@ -53,12 +44,11 @@ struct lua_longjmp; /* defined in ldo.c */ · 12 unmodified lines
5344 /* kinds of Garbage Collection */
5445 #define KGC_NORMAL 0
5546 #define KGC_EMERGENCY 1 /* gc was forced by an allocation failure */
56−#define KGC_GEN 2 /* generational collection */
5747
5848
5949 typedef struct stringtable {
60− GCObject **hash;
61− lu_int32 nuse; /* number of elements */
50+ TString **hash;
51+ int nuse; /* number of elements */
6252 int size;
6353 } stringtable;
6454
@@ -123,21 +113,20 @@ typedef struct global_State { · 58 unmodified lines
123113 lu_byte gcstate; /* state of garbage collector */
124114 lu_byte gckind; /* kind of GC running */
125115 lu_byte gcrunning; /* true if GC is running */
126− int sweepstrgc; /* position of sweep in `strt' */
127116 GCObject *allgc; /* list of all collectable objects */
117+ GCObject **sweepgc; /* current position of sweep in list */
128118 GCObject *finobj; /* list of collectable objects with finalizers */
129− GCObject **sweepgc; /* current position of sweep in list 'allgc' */
130− GCObject **sweepfin; /* current position of sweep in list 'finobj' */
131119 GCObject *gray; /* list of gray objects */
132120 GCObject *grayagain; /* list of objects to be traversed atomically */
133121 GCObject *weak; /* list of tables with weak values */
134122 GCObject *ephemeron; /* list of ephemeron tables (weak keys) */
135123 GCObject *allweak; /* list of all-weak tables */
136124 GCObject *tobefnz; /* list of userdata to be GC */
137− UpVal uvhead; /* head of double-linked list of all open upvalues */
125+ GCObject *fixedgc; /* list of objects not to be collected */
126+ struct lua_State *twups; /* list of threads with open upvalues */
138127 Mbuffer buff; /* temporary buffer for string concatenation */
128+ unsigned int gcfinnum; /* number of finalizers to call in each GC step */
139129 int gcpause; /* size of pause between successive GCs */
140− int gcmajorinc; /* pause between major collections (only in gen. mode) */
141130 int gcstepmul; /* GC `granularity' */
142131 lua_CFunction panic; /* to be called in unprotected errors */
143132 struct lua_State *mainthread;
@@ -168,8 +157,9 @@ struct lua_State { · 24 unmodified lines
168157 int basehookcount;
169158 int hookcount;
170159 lua_Hook hook;
171− GCObject *openupval; /* list of open upvalues in this stack */
160+ UpVal *openupval; /* list of open upvalues in this stack */
172161 GCObject *gclist;
162+ struct lua_State *twups; /* list of threads with open upvalues */
173163 struct lua_longjmp *errorJmp; /* current error recover point */
174164 ptrdiff_t errfunc; /* current error handling function (stack index) */
175165 CallInfo base_ci; /* CallInfo for first level (C calling Lua) */
@@ -189,7 +179,6 @@ union GCObject { · 13 unmodified lines
189179 union Closure cl;
190180 struct Table h;
191181 struct Proto p;
192− struct UpVal uv;
193182 struct lua_State th; /* thread */
194183 };
195184
@@ -208,7 +197,6 @@ union GCObject { · 12 unmodified lines
208197 check_exp(novariant((o)->gch.tt) == LUA_TFUNCTION, &((o)->cl))
209198 #define gco2t(o) check_exp((o)->gch.tt == LUA_TTABLE, &((o)->h))
210199 #define gco2p(o) check_exp((o)->gch.tt == LUA_TPROTO, &((o)->p))
211−#define gco2uv(o) check_exp((o)->gch.tt == LUA_TUPVAL, &((o)->uv))
212200 #define gco2th(o) check_exp((o)->gch.tt == LUA_TTHREAD, &((o)->th))
213201
214202 /* macro to convert any Lua object into a GCObject */
@@ -222,6 +210,7 @@ LUAI_FUNC void luaE_setdebt (global_State *g, l_mem debt); · 7 unmodified lines
222210 LUAI_FUNC void luaE_freethread (lua_State *L, lua_State *L1);
223211 LUAI_FUNC CallInfo *luaE_extendCI (lua_State *L);
224212 LUAI_FUNC void luaE_freeCI (lua_State *L);
213+LUAI_FUNC void luaE_shrinkCI (lua_State *L);
225214
226215
227216 #endif
src/lstring.c+46−55
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lstring.c,v 2.27 2013/06/19 14:27:00 roberto Exp $
2+** $Id: lstring.c,v 2.38 2014/03/19 18:51:42 roberto Exp $
33 ** String table (keeps all strings handled by Lua)
44 ** See Copyright Notice in lua.h
55 */
@@ -12,12 +12,15 @@ · 6 unmodified lines
1212
1313 #include "lua.h"
1414
15+#include "ldebug.h"
16+#include "ldo.h"
1517 #include "lmem.h"
1618 #include "lobject.h"
1719 #include "lstate.h"
1820 #include "lstring.h"
1921
2022
23+
2124 /*
2225 ** Lua will use at most ~(2^LUAI_HASHLIMIT) bytes from a string to
2326 ** compute its hash
@@ -39,15 +42,6 @@ int luaS_eqlngstr (TString *a, TString *b) { · 15 unmodified lines
3942 }
4043
4144
42−/*
43−** equality for strings
44−*/
45−int luaS_eqstr (TString *a, TString *b) {
46− return (a->tsv.tt == b->tsv.tt) &&
47− (a->tsv.tt == LUA_TSHRSTR ? eqshrstr(a, b) : luaS_eqlngstr(a, b));
48−}
49−
50−
5145 unsigned int luaS_hash (const char *str, size_t l, unsigned int seed) {
5246 unsigned int h = seed ^ cast(unsigned int, l);
5347 size_t l1;
@@ -64,43 +58,41 @@ unsigned int luaS_hash (const char *str, size_t l, unsigned int seed) { · 10 unmodified lines
6458 void luaS_resize (lua_State *L, int newsize) {
6559 int i;
6660 stringtable *tb = &G(L)->strt;
67− /* cannot resize while GC is traversing strings */
68− luaC_runtilstate(L, ~bitmask(GCSsweepstring));
69− if (newsize > tb->size) {
70− luaM_reallocvector(L, tb->hash, tb->size, newsize, GCObject *);
71− for (i = tb->size; i < newsize; i++) tb->hash[i] = NULL;
61+ if (newsize > tb->size) { /* grow table if needed */
62+ luaM_reallocvector(L, tb->hash, tb->size, newsize, TString *);
63+ for (i = tb->size; i < newsize; i++)
64+ tb->hash[i] = NULL;
7265 }
73− /* rehash */
74− for (i=0; i<tb->size; i++) {
75− GCObject *p = tb->hash[i];
66+ for (i = 0; i < tb->size; i++) { /* rehash */
67+ TString *p = tb->hash[i];
7668 tb->hash[i] = NULL;
7769 while (p) { /* for each node in the list */
78− GCObject *next = gch(p)->next; /* save next */
79− unsigned int h = lmod(gco2ts(p)->hash, newsize); /* new position */
80− gch(p)->next = tb->hash[h]; /* chain it */
70+ TString *hnext = p->tsv.hnext; /* save next */
71+ unsigned int h = lmod(p->tsv.hash, newsize); /* new position */
72+ p->tsv.hnext = tb->hash[h]; /* chain it */
8173 tb->hash[h] = p;
82− resetoldbit(p); /* see MOVE OLD rule */
83− p = next;
74+ p = hnext;
8475 }
8576 }
86− if (newsize < tb->size) {
87− /* shrinking slice must be empty */
77+ if (newsize < tb->size) { /* shrink table if needed */
78+ /* vanishing slice should be empty */
8879 lua_assert(tb->hash[newsize] == NULL && tb->hash[tb->size - 1] == NULL);
89− luaM_reallocvector(L, tb->hash, tb->size, newsize, GCObject *);
80+ luaM_reallocvector(L, tb->hash, tb->size, newsize, TString *);
9081 }
9182 tb->size = newsize;
9283 }
9384
9485
86+
9587 /*
9688 ** creates a new string object
9789 */
9890 static TString *createstrobj (lua_State *L, const char *str, size_t l,
99− int tag, unsigned int h, GCObject **list) {
91+ int tag, unsigned int h) {
10092 TString *ts;
10193 size_t totalsize; /* total size of TString object */
10294 totalsize = sizeof(TString) + ((l + 1) * sizeof(char));
103− ts = &luaC_newobj(L, tag, totalsize, list, 0)->ts;
95+ ts = &luaC_newobj(L, tag, totalsize)->ts;
10496 ts->tsv.len = l;
10597 ts->tsv.hash = h;
10698 ts->tsv.extra = 0;
@@ -110,20 +102,13 @@ static TString *createstrobj (lua_State *L, const char *str, size_t l, · 3 unmodified lines
110102 }
111103
112104
113−/*
114−** creates a new short string, inserting it into string table
115−*/
116−static TString *newshrstr (lua_State *L, const char *str, size_t l,
117− unsigned int h) {
118− GCObject **list; /* (pointer to) list where it will be inserted */
105+LUAI_FUNC void luaS_remove (lua_State *L, TString *ts) {
119106 stringtable *tb = &G(L)->strt;
120− TString *s;
121− if (tb->nuse >= cast(lu_int32, tb->size) && tb->size <= MAX_INT/2)
122− luaS_resize(L, tb->size*2); /* too crowded */
123− list = &tb->hash[lmod(h, tb->size)];
124− s = createstrobj(L, str, l, LUA_TSHRSTR, h, list);
125− tb->nuse++;
126− return s;
107+ TString **p = &tb->hash[lmod(ts->tsv.hash, tb->size)];
108+ while (*p != ts) /* find previous element */
109+ p = &(*p)->tsv.hnext;
110+ *p = (*p)->tsv.hnext; /* remove element from its list */
111+ tb->nuse--;
127112 }
128113
129114
@@ -131,22 +116,28 @@ static TString *newshrstr (lua_State *L, const char *str, size_t l, · 1 unmodified line
131116 ** checks whether short string exists and reuses it or creates a new one
132117 */
133118 static TString *internshrstr (lua_State *L, const char *str, size_t l) {
134− GCObject *o;
119+ TString *ts;
135120 global_State *g = G(L);
136121 unsigned int h = luaS_hash(str, l, g->seed);
137− for (o = g->strt.hash[lmod(h, g->strt.size)];
138− o != NULL;
139− o = gch(o)->next) {
140− TString *ts = rawgco2ts(o);
141− if (h == ts->tsv.hash &&
142− l == ts->tsv.len &&
122+ TString **list = &g->strt.hash[lmod(h, g->strt.size)];
123+ for (ts = *list; ts != NULL; ts = ts->tsv.hnext) {
124+ if (l == ts->tsv.len &&
143125 (memcmp(str, getstr(ts), l * sizeof(char)) == 0)) {
144− if (isdead(G(L), o)) /* string is dead (but was not collected yet)? */
145− changewhite(o); /* resurrect it */
126+ /* found! */
127+ if (isdead(g, obj2gco(ts))) /* dead (but not collected yet)? */
128+ changewhite(obj2gco(ts)); /* resurrect it */
146129 return ts;
147130 }
148131 }
149− return newshrstr(L, str, l, h); /* not found; create a new string */
132+ if (g->strt.nuse >= g->strt.size && g->strt.size <= MAX_INT/2) {
133+ luaS_resize(L, g->strt.size * 2);
134+ list = &g->strt.hash[lmod(h, g->strt.size)]; /* recompute with new size */
135+ }
136+ ts = createstrobj(L, str, l, LUA_TSHRSTR, h);
137+ ts->tsv.hnext = *list;
138+ *list = ts;
139+ g->strt.nuse++;
140+ return ts;
150141 }
151142
152143
@@ -159,7 +150,7 @@ TString *luaS_newlstr (lua_State *L, const char *str, size_t l) { · 6 unmodified lines
159150 else {
160151 if (l + 1 > (MAX_SIZE - sizeof(TString))/sizeof(char))
161152 luaM_toobig(L);
162− return createstrobj(L, str, l, LUA_TLNGSTR, G(L)->seed, NULL);
153+ return createstrobj(L, str, l, LUA_TLNGSTR, G(L)->seed);
163154 }
164155 }
165156
@@ -172,14 +163,14 @@ TString *luaS_new (lua_State *L, const char *str) { · 6 unmodified lines
172163 }
173164
174165
175−Udata *luaS_newudata (lua_State *L, size_t s, Table *e) {
166+Udata *luaS_newudata (lua_State *L, size_t s) {
176167 Udata *u;
177168 if (s > MAX_SIZE - sizeof(Udata))
178169 luaM_toobig(L);
179− u = &luaC_newobj(L, LUA_TUSERDATA, sizeof(Udata) + s, NULL, 0)->u;
170+ u = &luaC_newobj(L, LUA_TUSERDATA, sizeof(Udata) + s)->u;
180171 u->uv.len = s;
181172 u->uv.metatable = NULL;
182− u->uv.env = e;
173+ setuservalue(L, u, luaO_nilobject);
183174 return u;
184175 }
185176
src/lstring.h+3−5
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lstring.h,v 1.49 2012/02/01 21:57:15 roberto Exp $
2+** $Id: lstring.h,v 1.54 2014/03/19 18:51:42 roberto Exp $
33 ** String table (keep all strings handled by Lua)
44 ** See Copyright Notice in lua.h
55 */
@@ -19,8 +19,6 @@ · 13 unmodified lines
1919 #define luaS_newliteral(L, s) (luaS_newlstr(L, "" s, \
2020 (sizeof(s)/sizeof(char))-1))
2121
22−#define luaS_fix(s) l_setbit((s)->tsv.marked, FIXEDBIT)
23−
2422
2523 /*
2624 ** test whether a string is a reserved word
@@ -36,9 +34,9 @@ · 9 unmodified lines
3634
3735 LUAI_FUNC unsigned int luaS_hash (const char *str, size_t l, unsigned int seed);
3836 LUAI_FUNC int luaS_eqlngstr (TString *a, TString *b);
39−LUAI_FUNC int luaS_eqstr (TString *a, TString *b);
4037 LUAI_FUNC void luaS_resize (lua_State *L, int newsize);
41−LUAI_FUNC Udata *luaS_newudata (lua_State *L, size_t s, Table *e);
38+LUAI_FUNC void luaS_remove (lua_State *L, TString *ts);
39+LUAI_FUNC Udata *luaS_newudata (lua_State *L, size_t s);
4240 LUAI_FUNC TString *luaS_newlstr (lua_State *L, const char *str, size_t l);
4341 LUAI_FUNC TString *luaS_new (lua_State *L, const char *str);
4442
src/lstrlib.c+222−5
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lstrlib.c,v 1.182 2013/06/20 15:06:51 roberto Exp $
2+** $Id: lstrlib.c,v 1.189 2014/03/21 14:26:44 roberto Exp $
33 ** Standard library for string operations and pattern-matching
44 ** See Copyright Notice in lua.h
55 */
@@ -116,7 +116,7 @@ static int str_rep (lua_State *L) { · 110 unmodified lines
116116 lua_Integer n = luaL_checkinteger(L, 2);
117117 const char *sep = luaL_optlstring(L, 3, "", &lsep);
118118 if (n <= 0) lua_pushliteral(L, "");
119− else if (l + lsep < l || l + lsep >= MAXSIZE / n) /* may overflow? */
119+ else if (l + lsep < l || l + lsep > MAXSIZE / n) /* may overflow? */
120120 return luaL_error(L, "resulting string too large");
121121 else {
122122 size_t totallen = n * l + (n - 1) * lsep;
@@ -124,8 +124,9 @@ static int str_rep (lua_State *L) { · 1 unmodified line
124124 char *p = luaL_buffinitsize(L, &b, totallen);
125125 while (n-- > 1) { /* first n-1 copies (followed by separator) */
126126 memcpy(p, s, l * sizeof(char)); p += l;
127− if (lsep > 0) { /* avoid empty 'memcpy' (may be expensive) */
128− memcpy(p, sep, lsep * sizeof(char)); p += lsep;
127+ if (lsep > 0) { /* empty 'memcpy' is not that cheap */
128+ memcpy(p, sep, lsep * sizeof(char));
129+ p += lsep;
129130 }
130131 }
131132 memcpy(p, s, l * sizeof(char)); /* last copy (not followed by separator) */
@@ -178,10 +179,11 @@ static int writer (lua_State *L, const void *b, size_t size, void *B) { · 46 unmodified lines
178179
179180 static int str_dump (lua_State *L) {
180181 luaL_Buffer b;
182+ int strip = lua_toboolean(L, 2);
181183 luaL_checktype(L, 1, LUA_TFUNCTION);
182184 lua_settop(L, 1);
183185 luaL_buffinit(L,&b);
184− if (lua_dump(L, writer, &b) != 0)
186+ if (lua_dump(L, writer, &b, strip) != 0)
185187 return luaL_error(L, "unable to dump given function");
186188 luaL_pushresult(&b);
187189 return 1;
@@ -938,6 +940,217 @@ static int str_format (lua_State *L) { · 750 unmodified lines
938940 /* }====================================================== */
939941
940942
943+/*
944+** {======================================================
945+** PACK/UNPACK
946+** =======================================================
947+*/
948+
949+/* maximum size for the binary representation of an integer */
950+#define MAXINTSIZE 8
951+
952+
953+/* number of bits in a character */
954+#define NB CHAR_BIT
955+
956+/* mask for one character (NB ones) */
957+#define MC (((lua_Integer)1 << NB) - 1)
958+
959+/* mask for one character without sign ((NB - 1) ones) */
960+#define SM (((lua_Integer)1 << (NB - 1)) - 1)
961+
962+
963+#define SZINT ((int)sizeof(lua_Integer))
964+
965+
966+static union {
967+ int dummy;
968+ char little; /* true iff machine is little endian */
969+} const nativeendian = {1};
970+
971+
972+static int getendian (lua_State *L, int arg) {
973+ const char *endian = luaL_optstring(L, arg,
974+ (nativeendian.little ? "l" : "b"));
975+ if (*endian == 'n') /* native? */
976+ return nativeendian.little;
977+ luaL_argcheck(L, *endian == 'l' || *endian == 'b', arg,
978+ "endianess must be 'l'/'b'/'n'");
979+ return (*endian == 'l');
980+}
981+
982+
983+static int getintsize (lua_State *L, int arg) {
984+ int size = luaL_optint(L, arg, 0);
985+ if (size == 0) size = SZINT;
986+ luaL_argcheck(L, 1 <= size && size <= MAXINTSIZE, arg,
987+ "integer size out of valid range");
988+ return size;
989+}
990+
991+
992+static int packint (char *buff, lua_Integer n, int littleendian, int size) {
993+ int i;
994+ if (littleendian) {
995+ for (i = 0; i < size - 1; i++) {
996+ buff[i] = (n & MC);
997+ n >>= NB;
998+ }
999+ }
1000+ else {
1001+ for (i = size - 1; i > 0; i--) {
1002+ buff[i] = (n & MC);
1003+ n >>= NB;
1004+ }
1005+ }
1006+ buff[i] = (n & MC); /* last byte */
1007+ /* test for overflow: OK if there are only zeros left in higher bytes,
1008+ or if there are only ones left and packed number is negative (signal
1009+ bit, the higher bit in last byte, is one) */
1010+ return ((n & ~MC) == 0 || (n | SM) == ~(lua_Integer)0);
1011+}
1012+
1013+
1014+static int packint_l (lua_State *L) {
1015+ char buff[MAXINTSIZE];
1016+ lua_Integer n = luaL_checkinteger(L, 1);
1017+ int size = getintsize(L, 2);
1018+ int endian = getendian(L, 3);
1019+ if (packint(buff, n, endian, size))
1020+ lua_pushlstring(L, buff, size);
1021+ else
1022+ luaL_error(L, "integer does not fit into given size (%d)", size);
1023+ return 1;
1024+}
1025+
1026+
1027+/* mask to check higher-order byte in a Lua integer */
1028+#define HIGHERBYTE (MC << (NB * (SZINT - 1)))
1029+
1030+/* mask to check higher-order byte + signal bit of next (lower) byte */
1031+#define HIGHERBYTE1 (HIGHERBYTE | (HIGHERBYTE >> 1))
1032+
1033+static int unpackint (const char *buff, lua_Integer *res,
1034+ int littleendian, int size) {
1035+ lua_Integer n = 0;
1036+ int i;
1037+ for (i = 0; i < size; i++) {
1038+ if (i >= SZINT) { /* will throw away a byte? */
1039+ /* check for overflow: it is OK to throw away leading zeros for a
1040+ positive number, leading ones for a negative number, and a
1041+ leading zero byte to allow unsigned integers with a 1 in
1042+ its "signal bit" */
1043+ if (!((n & HIGHERBYTE1) == 0 || /* zeros for positive number */
1044+ (n & HIGHERBYTE1) == HIGHERBYTE1 || /* ones for negative number */
1045+ ((n & HIGHERBYTE) == 0 && i == size - 1))) /* leading zero */
1046+ return 0; /* overflow */
1047+ }
1048+ n <<= NB;
1049+ n |= (lua_Integer)(unsigned char)buff[littleendian ? size - 1 - i : i];
1050+ }
1051+ if (size < SZINT) { /* need sign extension? */
1052+ lua_Integer mask = (~(lua_Integer)0) << (size*NB - 1);
1053+ if (n & mask) /* negative value? */
1054+ n |= mask; /* signal extension */
1055+ }
1056+ *res = n;
1057+ return 1;
1058+}
1059+
1060+
1061+static int unpackint_l (lua_State *L) {
1062+ lua_Integer res;
1063+ size_t len;
1064+ const char *s = luaL_checklstring(L, 1, &len);
1065+ lua_Integer pos = posrelat(luaL_optinteger(L, 2, 1), len);
1066+ int size = getintsize(L, 3);
1067+ int endian = getendian(L, 4);
1068+ luaL_argcheck(L, 1 <= pos && (size_t)pos + size - 1 <= len, 1,
1069+ "string too short");
1070+ if(unpackint(s + pos - 1, &res, endian, size))
1071+ lua_pushinteger(L, res);
1072+ else
1073+ luaL_error(L, "result does not fit into a Lua integer");
1074+ return 1;
1075+}
1076+
1077+
1078+static void correctendianess (lua_State *L, char *b, int size, int endianarg) {
1079+ int endian = getendian(L, endianarg);
1080+ if (endian != nativeendian.little) { /* not native endianess? */
1081+ int i = 0;
1082+ while (i < --size) {
1083+ char temp = b[i];
1084+ b[i++] = b[size];
1085+ b[size] = temp;
1086+ }
1087+ }
1088+}
1089+
1090+
1091+static int getfloatsize (lua_State *L, int arg) {
1092+ const char *size = luaL_optstring(L, arg, "n");
1093+ if (*size == 'n') return sizeof(lua_Number);
1094+ luaL_argcheck(L, *size == 'd' || *size == 'f', arg,
1095+ "size must be 'f'/'d'/'n'");
1096+ return (*size == 'd' ? sizeof(double) : sizeof(float));
1097+}
1098+
1099+
1100+static int packfloat_l (lua_State *L) {
1101+ float f; double d;
1102+ char *pn; /* pointer to number */
1103+ lua_Number n = luaL_checknumber(L, 1);
1104+ int size = getfloatsize(L, 2);
1105+ if (size == sizeof(lua_Number))
1106+ pn = (char*)&n;
1107+ else if (size == sizeof(float)) {
1108+ f = (float)n;
1109+ pn = (char*)&f;
1110+ }
1111+ else { /* native lua_Number may be neither float nor double */
1112+ lua_assert(size == sizeof(double));
1113+ d = (double)n;
1114+ pn = (char*)&d;
1115+ }
1116+ correctendianess(L, pn, size, 3);
1117+ lua_pushlstring(L, pn, size);
1118+ return 1;
1119+}
1120+
1121+
1122+static int unpackfloat_l (lua_State *L) {
1123+ lua_Number res;
1124+ size_t len;
1125+ const char *s = luaL_checklstring(L, 1, &len);
1126+ lua_Integer pos = posrelat(luaL_optinteger(L, 2, 1), len);
1127+ int size = getfloatsize(L, 3);
1128+ luaL_argcheck(L, 1 <= pos && (size_t)pos + size - 1 <= len, 1,
1129+ "string too short");
1130+ if (size == sizeof(lua_Number)) {
1131+ memcpy(&res, s + pos - 1, size);
1132+ correctendianess(L, (char*)&res, size, 4);
1133+ }
1134+ else if (size == sizeof(float)) {
1135+ float f;
1136+ memcpy(&f, s + pos - 1, size);
1137+ correctendianess(L, (char*)&f, size, 4);
1138+ res = (lua_Number)f;
1139+ }
1140+ else { /* native lua_Number may be neither float nor double */
1141+ double d;
1142+ lua_assert(size == sizeof(double));
1143+ memcpy(&d, s + pos - 1, size);
1144+ correctendianess(L, (char*)&d, size, 4);
1145+ res = (lua_Number)d;
1146+ }
1147+ lua_pushnumber(L, res);
1148+ return 1;
1149+}
1150+
1151+/* }====================================================== */
1152+
1153+
9411154 static const luaL_Reg strlib[] = {
9421155 {"byte", str_byte},
9431156 {"char", str_char},
@@ -953,6 +1166,10 @@ static const luaL_Reg strlib[] = { · 9 unmodified lines
9531166 {"reverse", str_reverse},
9541167 {"sub", str_sub},
9551168 {"upper", str_upper},
1169+ {"packfloat", packfloat_l},
1170+ {"packint", packint_l},
1171+ {"unpackfloat", unpackfloat_l},
1172+ {"unpackint", unpackint_l},
9561173 {NULL, NULL}
9571174 };
9581175
src/ltable.c+47−27
@@ -1,5 +1,5 @@
11 /*
2−** $Id: ltable.c,v 2.78 2013/06/20 15:02:49 roberto Exp $
2+** $Id: ltable.c,v 2.84 2014/01/27 13:34:32 roberto Exp $
33 ** Lua tables (hash)
44 ** See Copyright Notice in lua.h
55 */
@@ -79,7 +79,7 @@ · 73 unmodified lines
7979
8080 static const Node dummynode_ = {
8181 {NILCONSTANT}, /* value */
82− {{NILCONSTANT, NULL}} /* key */
82+ {{NILCONSTANT, 0}} /* key */
8383 };
8484
8585
@@ -158,6 +158,7 @@ static int findindex (lua_State *L, Table *t, StkId key) { · 72 unmodified lines
158158 if (0 < i && i <= t->sizearray) /* is `key' inside array part? */
159159 return i-1; /* yes; that's the index (corrected to C) */
160160 else {
161+ int nx;
161162 Node *n = mainposition(t, key);
162163 for (;;) { /* check whether `key' is somewhere in the chain */
163164 /* key may be dead already, but it is ok to use it in `next' */
@@ -168,9 +169,10 @@ static int findindex (lua_State *L, Table *t, StkId key) { · 4 unmodified lines
168169 /* hash elements are numbered after array ones */
169170 return i + t->sizearray;
170171 }
171− else n = gnext(n);
172− if (n == NULL)
172+ nx = gnext(n);
173+ if (nx == 0)
173174 luaG_runerror(L, "invalid key to " LUA_QL("next")); /* key not found */
175+ else n += nx;
174176 }
175177 }
176178 }
@@ -301,7 +303,7 @@ static void setnodevector (lua_State *L, Table *t, int size) { · 124 unmodified lines
301303 t->node = luaM_newvector(L, size, Node);
302304 for (i=0; i<size; i++) {
303305 Node *n = gnode(t, i);
304− gnext(n) = NULL;
306+ gnext(n) = 0;
305307 setnilvalue(gkey(n));
306308 setnilvalue(gval(n));
307309 }
@@ -376,7 +378,7 @@ static void rehash (lua_State *L, Table *t, const TValue *ek) { · 68 unmodified lines
376378
377379
378380 Table *luaH_new (lua_State *L) {
379− Table *t = &luaC_newobj(L, LUA_TTABLE, sizeof(Table), NULL, 0)->h;
381+ Table *t = &luaC_newobj(L, LUA_TTABLE, sizeof(Table))->h;
380382 t->metatable = NULL;
381383 t->flags = cast_byte(~0);
382384 t->array = NULL;
@@ -419,7 +421,7 @@ TValue *luaH_newkey (lua_State *L, Table *t, const TValue *key) { · 36 unmodified lines
419421 else if (ttisfloat(key)) {
420422 lua_Number n = fltvalue(key);
421423 lua_Integer k;
422− if (luai_numisnan(L, n))
424+ if (luai_numisnan(n))
423425 luaG_runerror(L, "table index is NaN");
424426 if (numisinteger(n, &k)) { /* index is int? */
425427 setivalue(&aux, k);
@@ -429,31 +431,37 @@ TValue *luaH_newkey (lua_State *L, Table *t, const TValue *key) { · 3 unmodified lines
429431 mp = mainposition(t, key);
430432 if (!ttisnil(gval(mp)) || isdummy(mp)) { /* main position is taken? */
431433 Node *othern;
432− Node *n = getfreepos(t); /* get a free place */
433− if (n == NULL) { /* cannot find a free place? */
434+ Node *f = getfreepos(t); /* get a free place */
435+ if (f == NULL) { /* cannot find a free place? */
434436 rehash(L, t, key); /* grow table */
435437 /* whatever called 'newkey' take care of TM cache and GC barrier */
436438 return luaH_set(L, t, key); /* insert key into grown table */
437439 }
438− lua_assert(!isdummy(n));
440+ lua_assert(!isdummy(f));
439441 othern = mainposition(t, gkey(mp));
440442 if (othern != mp) { /* is colliding node out of its main position? */
441443 /* yes; move colliding node into free position */
442− while (gnext(othern) != mp) othern = gnext(othern); /* find previous */
443− gnext(othern) = n; /* redo the chain with `n' in place of `mp' */
444− *n = *mp; /* copy colliding node into free pos. (mp->next also goes) */
445− gnext(mp) = NULL; /* now `mp' is free */
444+ while (othern + gnext(othern) != mp) /* find previous */
445+ othern += gnext(othern);
446+ gnext(othern) = f - othern; /* re-chain with 'f' in place of 'mp' */
447+ *f = *mp; /* copy colliding node into free pos. (mp->next also goes) */
448+ if (gnext(mp) != 0) {
449+ gnext(f) += mp - f; /* correct 'next' */
450+ gnext(mp) = 0; /* now 'mp' is free */
451+ }
446452 setnilvalue(gval(mp));
447453 }
448454 else { /* colliding node is in its own main position */
449455 /* new node will go into free position */
450− gnext(n) = gnext(mp); /* chain new position */
451− gnext(mp) = n;
452− mp = n;
456+ if (gnext(mp) != 0)
457+ gnext(f) = (mp + gnext(mp)) - f; /* chain new position */
458+ else lua_assert(gnext(f) == 0);
459+ gnext(mp) = f - mp;
460+ mp = f;
453461 }
454462 }
455463 setobj2t(L, gkey(mp), key);
456− luaC_barrierback(L, obj2gco(t), key);
464+ luaC_barrierback(L, t, key);
457465 lua_assert(ttisnil(gval(mp)));
458466 return gval(mp);
459467 }
@@ -468,11 +476,15 @@ const TValue *luaH_getint (Table *t, lua_Integer key) { · 8 unmodified lines
468476 return &t->array[key - 1];
469477 else {
470478 Node *n = hashint(t, key);
471− do { /* check whether `key' is somewhere in the chain */
479+ for (;;) { /* check whether `key' is somewhere in the chain */
472480 if (ttisinteger(gkey(n)) && ivalue(gkey(n)) == key)
473481 return gval(n); /* that's it */
474− else n = gnext(n);
475− } while (n);
482+ else {
483+ int nx = gnext(n);
484+ if (nx == 0) break;
485+ n += nx;
486+ }
487+ };
476488 return luaO_nilobject;
477489 }
478490 }
@@ -484,11 +496,15 @@ const TValue *luaH_getint (Table *t, lua_Integer key) { · 5 unmodified lines
484496 const TValue *luaH_getstr (Table *t, TString *key) {
485497 Node *n = hashstr(t, key);
486498 lua_assert(key->tsv.tt == LUA_TSHRSTR);
487− do { /* check whether `key' is somewhere in the chain */
499+ for (;;) { /* check whether `key' is somewhere in the chain */
488500 if (ttisshrstring(gkey(n)) && eqshrstr(rawtsvalue(gkey(n)), key))
489501 return gval(n); /* that's it */
490− else n = gnext(n);
491− } while (n);
502+ else {
503+ int nx = gnext(n);
504+ if (nx == 0) break;
505+ n += nx;
506+ }
507+ };
492508 return luaO_nilobject;
493509 }
494510
@@ -509,11 +525,15 @@ const TValue *luaH_get (Table *t, const TValue *key) { · 14 unmodified lines
509525 }
510526 default: {
511527 Node *n = mainposition(t, key);
512− do { /* check whether `key' is somewhere in the chain */
528+ for (;;) { /* check whether `key' is somewhere in the chain */
513529 if (luaV_rawequalobj(gkey(n), key))
514530 return gval(n); /* that's it */
515− else n = gnext(n);
516− } while (n);
531+ else {
532+ int nx = gnext(n);
533+ if (nx == 0) break;
534+ n += nx;
535+ }
536+ };
517537 return luaO_nilobject;
518538 }
519539 }
src/ltable.h+6−1
@@ -1,5 +1,5 @@
11 /*
2−** $Id: ltable.h,v 2.17 2013/04/26 15:39:25 roberto Exp $
2+** $Id: ltable.h,v 2.18 2013/08/30 16:01:37 roberto Exp $
33 ** Lua tables (hash)
44 ** See Copyright Notice in lua.h
55 */
@@ -18,6 +18,11 @@ · 12 unmodified lines
1818 #define invalidateTMcache(t) ((t)->flags = 0)
1919
2020
21+/* returns the key, given the value of a table entry */
22+#define keyfromval(v) \
23+ (gkey(cast(Node *, cast(char *, (v)) - offsetof(Node, i_val))))
24+
25+
2126 LUAI_FUNC const TValue *luaH_getint (Table *t, lua_Integer key);
2227 LUAI_FUNC void luaH_setint (lua_State *L, Table *t, lua_Integer key,
2328 TValue *value);
src/ltablib.c+2−2
@@ -1,5 +1,5 @@
11 /*
2−** $Id: ltablib.c,v 1.65 2013/03/07 18:17:24 roberto Exp $
2+** $Id: ltablib.c,v 1.66 2014/03/21 13:52:33 roberto Exp $
33 ** Library for Table Manipulation
44 ** See Copyright Notice in lua.h
55 */
@@ -140,7 +140,7 @@ static int unpack (lua_State *L) { · 134 unmodified lines
140140 e = luaL_opt(L, luaL_checkint, 3, luaL_len(L, 1));
141141 if (i > e) return 0; /* empty range */
142142 n = e - i + 1; /* number of elements */
143− if (n <= 0 || !lua_checkstack(L, n)) /* n <= 0 means arith. overflow */
143+ if (n <= 0 || !lua_checkstack(L, n)) /* n <= 0 means arithmetic overflow */
144144 return luaL_error(L, "too many results to unpack");
145145 lua_rawgeti(L, 1, i); /* push arg[i] (avoiding overflow problems) */
146146 while (i++ < e) /* push arg[i + 1...e] */
src/ltm.c+18−11
@@ -1,5 +1,5 @@
11 /*
2−** $Id: ltm.c,v 2.20 2013/05/06 17:19:11 roberto Exp $
2+** $Id: ltm.c,v 2.25 2013/12/30 20:47:58 roberto Exp $
33 ** Tag methods
44 ** See Copyright Notice in lua.h
55 */
@@ -28,7 +28,7 @@ LUAI_DDEF const char *const luaT_typenames_[LUA_TOTALTAGS] = { · 22 unmodified lines
2828 "no value",
2929 "nil", "boolean", udatatypename, "number",
3030 "string", "table", "function", udatatypename, "thread",
31− "proto", "upval" /* these last two cases are used for tests only */
31+ "proto" /* this last case is used for tests only */
3232 };
3333
3434
@@ -36,14 +36,16 @@ void luaT_init (lua_State *L) { · 1 unmodified line
3636 static const char *const luaT_eventname[] = { /* ORDER TM */
3737 "__index", "__newindex",
3838 "__gc", "__mode", "__len", "__eq",
39− "__add", "__sub", "__mul", "__div", "__idiv", "__mod",
40− "__pow", "__unm", "__lt", "__le",
39+ "__add", "__sub", "__mul", "__mod", "__pow",
40+ "__div", "__idiv",
41+ "__band", "__bor", "__bxor", "__shl", "__shr",
42+ "__unm", "__bnot", "__lt", "__le",
4143 "__concat", "__call"
4244 };
4345 int i;
4446 for (i=0; i<TM_N; i++) {
4547 G(L)->tmname[i] = luaS_new(L, luaT_eventname[i]);
46− luaS_fix(G(L)->tmname[i]); /* never collect these names */
48+ luaC_fix(L, obj2gco(G(L)->tmname[i])); /* never collect these names */
4749 }
4850 }
4951
@@ -110,12 +112,17 @@ int luaT_callbinTM (lua_State *L, const TValue *p1, const TValue *p2, · 60 unmodified lines
110112 void luaT_trybinTM (lua_State *L, const TValue *p1, const TValue *p2,
111113 StkId res, TMS event) {
112114 if (!luaT_callbinTM(L, p1, p2, res, event)) {
113− if (event == TM_CONCAT)
114− luaG_concaterror(L, p1, p2);
115− else if (event == TM_IDIV && ttisnumber(p1) && ttisnumber(p2))
116− luaG_tointerror(L, p1, p2);
117− else
118− luaG_aritherror(L, p1, p2);
115+ switch (event) {
116+ case TM_CONCAT:
117+ luaG_concaterror(L, p1, p2);
118+ case TM_IDIV: case TM_BAND: case TM_BOR: case TM_BXOR:
119+ case TM_SHL: case TM_SHR: case TM_BNOT:
120+ if (ttisnumber(p1) && ttisnumber(p2))
121+ luaG_tointerror(L, p1, p2);
122+ /* else go through */
123+ default:
124+ luaG_aritherror(L, p1, p2);
125+ }
119126 }
120127 }
121128
src/ltm.h+10−4
@@ -1,5 +1,5 @@
11 /*
2−** $Id: ltm.h,v 2.16 2013/04/29 16:56:50 roberto Exp $
2+** $Id: ltm.h,v 2.19 2013/12/30 20:47:58 roberto Exp $
33 ** Tag methods
44 ** See Copyright Notice in lua.h
55 */
@@ -13,7 +13,7 @@ · 7 unmodified lines
1313
1414 /*
1515 * WARNING: if you change the order of this enumeration,
16−* grep "ORDER TM"
16+* grep "ORDER TM" and "ORDER OP"
1717 */
1818 typedef enum {
1919 TM_INDEX,
@@ -25,11 +25,17 @@ typedef enum { · 5 unmodified lines
2525 TM_ADD,
2626 TM_SUB,
2727 TM_MUL,
28− TM_DIV,
29− TM_IDIV,
3028 TM_MOD,
3129 TM_POW,
30+ TM_DIV,
31+ TM_IDIV,
32+ TM_BAND,
33+ TM_BOR,
34+ TM_BXOR,
35+ TM_SHL,
36+ TM_SHR,
3237 TM_UNM,
38+ TM_BNOT,
3339 TM_LT,
3440 TM_LE,
3541 TM_CONCAT,
src/lua.c+69−31
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lua.c,v 1.206 2012/09/29 20:07:06 roberto Exp $
2+** $Id: lua.c,v 1.210 2014/02/26 15:27:56 roberto Exp $
33 ** Lua stand-alone interpreter
44 ** See Copyright Notice in lua.h
55 */
@@ -31,28 +31,38 @@ · 25 unmodified lines
3131 #define LUA_MAXINPUT 512
3232 #endif
3333
34−#if !defined(LUA_INIT)
35−#define LUA_INIT "LUA_INIT"
34+#if !defined(LUA_INIT_VAR)
35+#define LUA_INIT_VAR "LUA_INIT"
3636 #endif
3737
38−#define LUA_INITVERSION \
39− LUA_INIT "_" LUA_VERSION_MAJOR "_" LUA_VERSION_MINOR
38+#define LUA_INITVARVERSION \
39+ LUA_INIT_VAR "_" LUA_VERSION_MAJOR "_" LUA_VERSION_MINOR
4040
4141
4242 /*
4343 ** lua_stdin_is_tty detects whether the standard input is a 'tty' (that
4444 ** is, whether we're running lua interactively).
4545 */
46−#if defined(LUA_USE_ISATTY)
46+#if !defined(lua_stdin_is_tty) /* { */
47+
48+#if defined(LUA_USE_POSIX) /* { */
49+
4750 #include <unistd.h>
4851 #define lua_stdin_is_tty() isatty(0)
49−#elif defined(LUA_WIN)
52+
53+#elif defined(LUA_WIN) /* }{ */
54+
5055 #include <io.h>
51−#include <stdio.h>
5256 #define lua_stdin_is_tty() _isatty(_fileno(stdin))
53−#else
57+
58+#else /* }{ */
59+
60+/* ANSI definition */
5461 #define lua_stdin_is_tty() 1 /* assume stdin is a tty */
55−#endif
62+
63+#endif /* } */
64+
65+#endif /* } */
5666
5767
5868 /*
@@ -61,9 +71,10 @@ · 2 unmodified lines
6171 ** lua_saveline defines how to "save" a read line in a "history".
6272 ** lua_freeline defines how to free a line read by lua_readline.
6373 */
64−#if defined(LUA_USE_READLINE)
74+#if !defined(lua_readline) /* { */
75+
76+#if defined(LUA_USE_READLINE) /* { */
6577
66−#include <stdio.h>
6778 #include <readline/readline.h>
6879 #include <readline/history.h>
6980 #define lua_readline(L,b,p) ((void)L, ((b)=readline(p)) != NULL)
@@ -72,7 +83,7 @@ · 2 unmodified lines
7283 add_history(lua_tostring(L, idx)); /* add it to history */
7384 #define lua_freeline(L,b) ((void)L, free(b))
7485
75−#elif !defined(lua_readline)
86+#else /* }{ */
7687
7788 #define lua_readline(L,b,p) \
7889 ((void)L, fputs(p, stdout), fflush(stdout), /* show prompt */ \
@@ -80,7 +91,9 @@ · 1 unmodified line
8091 #define lua_saveline(L,idx) { (void)L; (void)idx; }
8192 #define lua_freeline(L,b) { (void)L; (void)b; }
8293
83−#endif
94+#endif /* } */
95+
96+#endif /* } */
8497
8598
8699
@@ -257,20 +270,21 @@ static int incomplete (lua_State *L, int status) { · 170 unmodified lines
257270 }
258271
259272
273+/* prompt the user, read a line, and push it into the Lua stack */
260274 static int pushline (lua_State *L, int firstline) {
261275 char buffer[LUA_MAXINPUT];
262276 char *b = buffer;
263277 size_t l;
264278 const char *prmt = get_prompt(L, firstline);
265279 int readstatus = lua_readline(L, b, prmt);
266− lua_pop(L, 1); /* remove result from 'get_prompt' */
267280 if (readstatus == 0)
268− return 0; /* no input */
281+ return 0; /* no input (prompt will be popped by caller) */
282+ lua_pop(L, 1); /* remove prompt */
269283 l = strlen(b);
270284 if (l > 0 && b[l-1] == '\n') /* line ends with newline? */
271285 b[l-1] = '\0'; /* remove it */
272− if (firstline && b[0] == '=') /* first line starts with `=' ? */
273− lua_pushfstring(L, "return %s", b+1); /* change it to `return' */
286+ if (firstline && b[0] == '=') /* for compatibility with 5.2, ... */
287+ lua_pushfstring(L, "return %s", b + 1); /* change '=' to 'return' */
274288 else
275289 lua_pushstring(L, b);
276290 lua_freeline(L, b);
@@ -278,24 +292,48 @@ static int pushline (lua_State *L, int firstline) { · 1 unmodified line
278292 }
279293
280294
281−static int loadline (lua_State *L) {
295+/* try to compile line on the stack as 'return <line>'; on return, stack
296+ has either compiled chunk or original line (if compilation failed) */
297+static int addreturn (lua_State *L) {
282298 int status;
283− lua_settop(L, 0);
284− if (!pushline(L, 1))
285− return -1; /* no input */
299+ size_t len; const char *line;
300+ lua_pushliteral(L, "return ");
301+ lua_pushvalue(L, -2); /* duplicate line */
302+ lua_concat(L, 2); /* new line is "return ..." */
303+ line = lua_tolstring(L, -1, &len);
304+ if ((status = luaL_loadbuffer(L, line, len, "=stdin")) == LUA_OK)
305+ lua_remove(L, -3); /* remove original line */
306+ else
307+ lua_pop(L, 2); /* remove result from 'luaL_loadbuffer' and new line */
308+ return status;
309+}
310+
311+
312+/* read multiple lines until a complete line */
313+static int multiline (lua_State *L) {
286314 for (;;) { /* repeat until gets a complete line */
287− size_t l;
288− const char *line = lua_tolstring(L, 1, &l);
289− status = luaL_loadbuffer(L, line, l, "=stdin");
290− if (!incomplete(L, status)) break; /* cannot try to add lines? */
291− if (!pushline(L, 0)) /* no more input? */
292− return -1;
293− lua_pushliteral(L, "\n"); /* add a new line... */
315+ size_t len;
316+ const char *line = lua_tolstring(L, 1, &len); /* get what it has */
317+ int status = luaL_loadbuffer(L, line, len, "=stdin"); /* try it */
318+ if (!incomplete(L, status) || !pushline(L, 0))
319+ return status; /* cannot/should not try to add continuation line */
320+ lua_pushliteral(L, "\n"); /* add newline... */
294321 lua_insert(L, -2); /* ...between the two lines */
295322 lua_concat(L, 3); /* join them */
296323 }
324+}
325+
326+
327+static int loadline (lua_State *L) {
328+ int status;
329+ lua_settop(L, 0);
330+ if (!pushline(L, 1))
331+ return -1; /* no input */
332+ if ((status = addreturn(L)) != LUA_OK) /* 'return ...' did not work? */
333+ status = multiline(L); /* try as command, maybe with continuation lines */
297334 lua_saveline(L, 1);
298335 lua_remove(L, 1); /* remove line */
336+ lua_assert(lua_gettop(L) == 1);
299337 return status;
300338 }
301339
@@ -421,10 +459,10 @@ static int runargs (lua_State *L, char **argv, int n) { · 119 unmodified lines
421459
422460
423461 static int handle_luainit (lua_State *L) {
424− const char *name = "=" LUA_INITVERSION;
462+ const char *name = "=" LUA_INITVARVERSION;
425463 const char *init = getenv(name + 1);
426464 if (init == NULL) {
427− name = "=" LUA_INIT;
465+ name = "=" LUA_INIT_VAR;
428466 init = getenv(name + 1); /* try alternative name */
429467 }
430468 if (init == NULL) return LUA_OK;
src/lua.h+25−21
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lua.h,v 1.292 2013/07/05 14:29:51 roberto Exp $
2+** $Id: lua.h,v 1.302 2014/03/20 19:42:35 roberto Exp $
33 ** Lua - A Scripting Language
44 ** Lua.org, PUC-Rio, Brazil (http://www.lua.org)
55 ** See Copyright Notice at the end of this file
@@ -19,11 +19,11 @@ · 13 unmodified lines
1919 #define LUA_VERSION_MAJOR "5"
2020 #define LUA_VERSION_MINOR "3"
2121 #define LUA_VERSION_NUM 503
22−#define LUA_VERSION_RELEASE "0 (work1)"
22+#define LUA_VERSION_RELEASE "0 (work2)"
2323
2424 #define LUA_VERSION "Lua " LUA_VERSION_MAJOR "." LUA_VERSION_MINOR
2525 #define LUA_RELEASE LUA_VERSION "." LUA_VERSION_RELEASE
26−#define LUA_COPYRIGHT LUA_RELEASE " Copyright (C) 1994-2013 Lua.org, PUC-Rio"
26+#define LUA_COPYRIGHT LUA_RELEASE " Copyright (C) 1994-2014 Lua.org, PUC-Rio"
2727 #define LUA_AUTHORS "R. Ierusalimschy, L. H. de Figueiredo, W. Celes"
2828
2929
@@ -182,14 +182,20 @@ LUA_API const void *(lua_topointer) (lua_State *L, int idx); · 152 unmodified lines
182182 ** Comparison and arithmetic functions
183183 */
184184
185−#define LUA_OPADD 0 /* ORDER TM */
185+#define LUA_OPADD 0 /* ORDER TM, ORDER OP */
186186 #define LUA_OPSUB 1
187187 #define LUA_OPMUL 2
188−#define LUA_OPDIV 3
189−#define LUA_OPIDIV 4
190−#define LUA_OPMOD 5
191−#define LUA_OPPOW 6
192−#define LUA_OPUNM 7
188+#define LUA_OPMOD 3
189+#define LUA_OPPOW 4
190+#define LUA_OPDIV 5
191+#define LUA_OPIDIV 6
192+#define LUA_OPBAND 7
193+#define LUA_OPBOR 8
194+#define LUA_OPBXOR 9
195+#define LUA_OPSHL 10
196+#define LUA_OPSHR 11
197+#define LUA_OPUNM 12
198+#define LUA_OPBNOT 13
193199
194200 LUA_API void (lua_arith) (lua_State *L, int op);
195201
@@ -222,12 +228,13 @@ LUA_API int (lua_pushthread) (lua_State *L); · 26 unmodified lines
222228 /*
223229 ** get functions (Lua -> stack)
224230 */
225−LUA_API void (lua_getglobal) (lua_State *L, const char *var);
226−LUA_API void (lua_gettable) (lua_State *L, int idx);
227−LUA_API void (lua_getfield) (lua_State *L, int idx, const char *k);
228−LUA_API void (lua_rawget) (lua_State *L, int idx);
229−LUA_API void (lua_rawgeti) (lua_State *L, int idx, lua_Integer n);
230−LUA_API void (lua_rawgetp) (lua_State *L, int idx, const void *p);
231+LUA_API int (lua_getglobal) (lua_State *L, const char *var);
232+LUA_API int (lua_gettable) (lua_State *L, int idx);
233+LUA_API int (lua_getfield) (lua_State *L, int idx, const char *k);
234+LUA_API int (lua_rawget) (lua_State *L, int idx);
235+LUA_API int (lua_rawgeti) (lua_State *L, int idx, lua_Integer n);
236+LUA_API int (lua_rawgetp) (lua_State *L, int idx, const void *p);
237+
231238 LUA_API void (lua_createtable) (lua_State *L, int narr, int nrec);
232239 LUA_API void *(lua_newuserdata) (lua_State *L, size_t sz);
233240 LUA_API int (lua_getmetatable) (lua_State *L, int objindex);
@@ -264,7 +271,7 @@ LUA_API int (lua_load) (lua_State *L, lua_Reader reader, void *dt, · 30 unmodified lines
264271 const char *chunkname,
265272 const char *mode);
266273
267−LUA_API int (lua_dump) (lua_State *L, lua_Writer writer, void *data);
274+LUA_API int (lua_dump) (lua_State *L, lua_Writer writer, void *data, int strip);
268275
269276
270277 /*
@@ -288,10 +295,7 @@ LUA_API int (lua_status) (lua_State *L); · 17 unmodified lines
288295 #define LUA_GCSTEP 5
289296 #define LUA_GCSETPAUSE 6
290297 #define LUA_GCSETSTEPMUL 7
291−#define LUA_GCSETMAJORINC 8
292298 #define LUA_GCISRUNNING 9
293−#define LUA_GCGEN 10
294−#define LUA_GCINC 11
295299
296300 LUA_API int (lua_gc) (lua_State *L, int what, int data);
297301
@@ -394,7 +398,7 @@ LUA_API void *(lua_upvalueid) (lua_State *L, int fidx, int n); · 96 unmodified lines
394398 LUA_API void (lua_upvaluejoin) (lua_State *L, int fidx1, int n1,
395399 int fidx2, int n2);
396400
397−LUA_API int (lua_sethook) (lua_State *L, lua_Hook func, int mask, int count);
401+LUA_API void (lua_sethook) (lua_State *L, lua_Hook func, int mask, int count);
398402 LUA_API lua_Hook (lua_gethook) (lua_State *L);
399403 LUA_API int (lua_gethookmask) (lua_State *L);
400404 LUA_API int (lua_gethookcount) (lua_State *L);
@@ -422,7 +426,7 @@ struct lua_Debug { · 21 unmodified lines
422426
423427
424428 /******************************************************************************
425−* Copyright (C) 1994-2013 Lua.org, PUC-Rio.
429+* Copyright (C) 1994-2014 Lua.org, PUC-Rio.
426430 *
427431 * Permission is hereby granted, free of charge, to any person obtaining
428432 * a copy of this software and associated documentation files (the
src/luac.c+1−1
@@ -202,7 +202,7 @@ int main(int argc, char* argv[]) · 201 unmodified lines
202202 return EXIT_SUCCESS;
203203 }
204204
205−#define nvalue(x) 0
205+#define nvalue(x) ((lua_Number)0)
206206 #define ttypenv(x) ttnov(x)
207207 /*
208208 ** $Id: print.c,v 1.69 2013/07/04 01:03:46 lhf Exp $
src/luaconf.h+76−44
@@ -1,5 +1,5 @@
11 /*
2−** $Id: luaconf.h,v 1.185 2013/06/25 19:04:40 roberto Exp $
2+** $Id: luaconf.h,v 1.193 2014/03/21 14:27:16 roberto Exp $
33 ** Configuration file for Lua
44 ** See Copyright Notice in lua.h
55 */
@@ -19,6 +19,24 @@ · 13 unmodified lines
1919 */
2020
2121
22+/*
23+** ===================================================================
24+@@ LUA_INT_INT / LUA_INT_LONG / LUA_INT_LONGLONG defines size for
25+@* Lua integers;
26+@@ LUA_REAL_FLOAT / LUA_REAL_DOUBLE / LUA_REAL_LONGDOUBLE defines size for
27+@* Lua floats.
28+**
29+** These definitions set the numeric types for Lua. Lua should work
30+** fine with 32-bit or 64-bit integers mixed with 32-bit or 64-bit
31+** floats. The usual configurations are 64-bit integers and floats (the
32+** default) and 32-bit integers and floats (Small Lua, for restricted
33+** hardware).
34+** =====================================================================
35+*/
36+#define LUA_INT_LONGLONG
37+#define LUA_REAL_DOUBLE
38+
39+
2240 /*
2341 @@ LUA_ANSI controls the use of non-ansi features.
2442 ** CHANGE it (define it) if you want Lua to avoid the use of any
@@ -41,24 +59,28 @@ · 16 unmodified lines
4159
4260
4361 #if defined(LUA_USE_LINUX)
62+#define LUA_USE_C99
4463 #define LUA_USE_POSIX
4564 #define LUA_USE_DLOPEN /* needs an extra library: -ldl */
4665 #define LUA_USE_READLINE /* needs some extra libraries */
47−#define LUA_USE_STRTODHEX /* assume 'strtod' handles hex formats */
48−#define LUA_USE_AFORMAT /* assume 'printf' handles 'aA' specifiers */
49−#define LUA_USE_LONGLONG /* assume support for long long */
5066 #endif
5167
5268 #if defined(LUA_USE_MACOSX)
69+#define LUA_USE_C99
5370 #define LUA_USE_POSIX
5471 #define LUA_USE_DLOPEN /* does not need -ldl */
5572 #define LUA_USE_READLINE /* needs an extra library: -lreadline */
56−#define LUA_USE_STRTODHEX /* assume 'strtod' handles hex formats */
57−#define LUA_USE_AFORMAT /* assume 'printf' handles 'aA' specifiers */
58−#define LUA_USE_LONGLONG /* assume support for long long */
5973 #endif
6074
6175
76+/*
77+@@ LUA_USE_C99 includes all functionality from C 99.
78+** CHANGE it (define it) if your system is compatible.
79+*/
80+#if defined(LUA_USE_C99)
81+#define LUA_USE_AFORMAT /* assume 'printf' handles 'aA' specifiers */
82+#endif
83+
6284
6385 /*
6486 @@ LUA_USE_POSIX includes all functionality listed as X/Open System
@@ -66,11 +88,6 @@ · 1 unmodified line
6688 ** CHANGE it (define it) if your system is XSI compatible.
6789 */
6890 #if defined(LUA_USE_POSIX)
69−#define LUA_USE_MKSTEMP
70−#define LUA_USE_ISATTY
71−#define LUA_USE_POPEN
72−#define LUA_USE_ULONGJMP
73−#define LUA_USE_GMTIME_R
7491 #endif
7592
7693
@@ -93,7 +110,8 @@ · 16 unmodified lines
93110 #define LUA_CDIR "!\\"
94111 #define LUA_PATH_DEFAULT \
95112 LUA_LDIR"?.lua;" LUA_LDIR"?\\init.lua;" \
96− LUA_CDIR"?.lua;" LUA_CDIR"?\\init.lua;" ".\\?.lua"
113+ LUA_CDIR"?.lua;" LUA_CDIR"?\\init.lua;" \
114+ ".\\?.lua;" ".\\?\\init.lua"
97115 #define LUA_CPATH_DEFAULT \
98116 LUA_CDIR"?.dll;" LUA_CDIR"loadall.dll;" ".\\?.dll"
99117
@@ -105,7 +123,8 @@ · 5 unmodified lines
105123 #define LUA_CDIR LUA_ROOT "lib/lua/" LUA_VDIR
106124 #define LUA_PATH_DEFAULT \
107125 LUA_LDIR"?.lua;" LUA_LDIR"?/init.lua;" \
108− LUA_CDIR"?.lua;" LUA_CDIR"?/init.lua;" "./?.lua"
126+ LUA_CDIR"?.lua;" LUA_CDIR"?/init.lua;" \
127+ "./?.lua;" "./?/init.lua"
109128 #define LUA_CPATH_DEFAULT \
110129 LUA_CDIR"?.so;" LUA_CDIR"loadall.so;" "./?.so"
111130 #endif /* } */
@@ -246,6 +265,11 @@ · 134 unmodified lines
246265 */
247266 #if defined(LUA_COMPAT_ALL) /* { */
248267
268+/*
269+@@ LUA_COMPAT_BITLIB controls the presence of library 'bit32'.
270+*/
271+#define LUA_COMPAT_BITLIB
272+
249273 /*
250274 @@ LUA_COMPAT_UNPACK controls the presence of global 'unpack'.
251275 ** You can replace it with 'table.unpack'.
@@ -350,7 +374,7 @@ · 98 unmodified lines
350374 /*
351375 @@ LUAI_MAXSTACK limits the size of the Lua stack.
352376 ** CHANGE it if you need a different limit. This limit is arbitrary;
353−** its only purpose is to stop Lua to consume unlimited stack
377+** its only purpose is to stop Lua from consuming unlimited stack
354378 ** space (and to reserve some numbers for pseudo-indices).
355379 */
356380 #if LUAI_BITSINT >= 32
@@ -372,26 +396,14 @@ · 15 unmodified lines
372396 #define LUAL_BUFFERSIZE BUFSIZ
373397
374398
375−
376−
377399 /*
378400 ** {==================================================================
379−** The following definitions set the numeric types for Lua.
380−** Lua should work fine with 32-bit or 64-bit integers mixed with
381−** 32-bit or 64-bit floats. The usual configurations are 64-bit
382−** integers and floats (the default) and 32-bit integers and floats.
401+** Configuration for Numbers.
402+** Change these definitions if no predefined LUA_REAL_* / LUA_INT_*
403+** satisfy your needs.
383404 ** ===================================================================
384405 */
385406
386−/*
387−@@ LUA_INTSIZE defines size for Lua integer: 1=int, 2=long, 3=long long
388−@@ LUA_FLOATSIZE defines size for Lua float: 1=float, 2=double, 3=long double
389−** Default is long long + double
390−*/
391−#define LUA_INTSIZE 3
392−#define LUA_FLOATSIZE 2
393−
394−
395407 /*
396408 @@ LUA_NUMBER is the floating-point type used by Lua.
397409 **
@@ -401,14 +413,14 @@ · 3 unmodified lines
401413 @@ LUA_NUMBER_FRMLEN is the length modifier for writing floats.
402414 @@ LUA_NUMBER_SCAN is the format for reading floats.
403415 @@ LUA_NUMBER_FMT is the format for writing floats.
404−@@ lua_number2str converts a floats to a string.
416+@@ lua_number2str converts a float to a string.
405417 **
406418 @@ l_mathop allows the addition of an 'l' or 'f' to all math operations
407419 **
408420 @@ lua_str2number converts a decimal numeric string to a number.
409421 */
410422
411−#if LUA_FLOATSIZE == 1 /* { single float */
423+#if defined(LUA_REAL_FLOAT) /* { single float */
412424
413425 #define LUA_NUMBER float
414426
@@ -423,7 +435,7 @@ · 8 unmodified lines
423435 #define lua_str2number(s,p) strtof((s), (p))
424436
425437
426−#elif LUA_FLOATSIZE == 3 /* }{ long double */
438+#elif defined(LUA_REAL_LONGDOUBLE) /* }{ long double */
427439
428440 #define LUA_NUMBER long double
429441
@@ -437,7 +449,7 @@ · 7 unmodified lines
437449
438450 #define lua_str2number(s,p) strtold((s), (p))
439451
440−#else /* }{ default: double */
452+#elif defined(LUA_REAL_DOUBLE) /* }{ double */
441453
442454 #define LUA_NUMBER double
443455
@@ -451,7 +463,11 @@ · 7 unmodified lines
451463
452464 #define lua_str2number(s,p) strtod((s), (p))
453465
454−#endif /* } */
466+#else /* }{ */
467+
468+#error "numeric real type not defined"
469+
470+#endif /* } */
455471
456472
457473 #if defined(LUA_ANSI)
@@ -481,8 +497,8 @@ · 23 unmodified lines
481497 /* the following operations need the math library */
482498 #if defined(lobject_c) || defined(lvm_c)
483499 #include <math.h>
484−#define luai_nummod(L,a,b) ((a) - l_floor((a)/(b))*(b))
485−#define luai_numpow(L,a,b) (l_mathop(pow)(a,b))
500+#define luai_nummod(L,a,b) ((void)L, (a) - l_floor((a)/(b))*(b))
501+#define luai_numpow(L,a,b) ((void)L, l_mathop(pow)(a,b))
486502 #endif
487503
488504 /* these are quite standard operations */
@@ -493,12 +509,19 @@ · 4 unmodified lines
493509 #define luai_numdiv(L,a,b) ((a)/(b))
494510 #define luai_numunm(L,a) (-(a))
495511 #define luai_numeq(a,b) ((a)==(b))
496−#define luai_numlt(L,a,b) ((a)<(b))
497−#define luai_numle(L,a,b) ((a)<=(b))
498−#define luai_numisnan(L,a) (!luai_numeq((a), (a)))
512+#define luai_numlt(a,b) ((a)<(b))
513+#define luai_numle(a,b) ((a)<=(b))
514+#define luai_numisnan(a) (!luai_numeq((a), (a)))
499515 #endif
500516
501517
518+/*
519+** The following macro checks whether an operation is not safe to be
520+** performed by the constant folder. It should result in zero only if
521+** the operation is safe.
522+*/
523+#define luai_numinvalidop(op,a,b) 0
524+
502525
503526 /*
504527 @@ LUA_INTEGER is the integer type used by Lua.
@@ -511,22 +534,31 @@ · 6 unmodified lines
511534 @@ lua_integer2str converts an integer to a string.
512535 */
513536
514−#if LUA_INTSIZE == 1 /* { int */
537+#if defined(LUA_INT_INT) /* { int */
515538
516539 #define LUA_INTEGER int
517540 #define LUA_INTEGER_FRMLEN ""
518541
519−#elif LUA_INTSIZE == 2 /* }{ long */
542+#elif defined(LUA_INT_LONG) /* }{ long */
520543
521544 #define LUA_INTEGER long
522545 #define LUA_INTEGER_FRMLEN "l"
523546
524−#else /* }{ default: long long */
547+#elif defined(LUA_INT_LONGLONG) /* }{ long long */
525548
549+#if defined(_WIN32)
550+#define LUA_INTEGER __int64
551+#define LUA_INTEGER_FRMLEN "I64"
552+#else
526553 #define LUA_INTEGER long long
527554 #define LUA_INTEGER_FRMLEN "ll"
555+#endif
528556
529−#endif /* } */
557+#else /* }{ */
558+
559+#error "numeric integer type not defined"
560+
561+#endif /* } */
530562
531563
532564 #define LUA_INTEGER_SCAN "%" LUA_INTEGER_FRMLEN "d"
src/lualib.h+4−1
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lualib.h,v 1.43 2011/12/08 12:11:37 roberto Exp $
2+** $Id: lualib.h,v 1.44 2014/02/06 17:32:33 roberto Exp $
33 ** Lua standard libraries
44 ** See Copyright Notice in lua.h
55 */
@@ -29,6 +29,9 @@ LUAMOD_API int (luaopen_os) (lua_State *L); · 23 unmodified lines
2929 #define LUA_STRLIBNAME "string"
3030 LUAMOD_API int (luaopen_string) (lua_State *L);
3131
32+#define LUA_UTF8LIBNAME "utf8"
33+LUAMOD_API int (luaopen_utf8) (lua_State *L);
34+
3235 #define LUA_BITLIBNAME "bit32"
3336 LUAMOD_API int (luaopen_bit32) (lua_State *L);
3437
src/lundump.c+207−209
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lundump.c,v 2.23 2013/04/26 18:48:35 roberto Exp $
2+** $Id: lundump.c,v 2.34 2014/03/11 18:56:27 roberto Exp $
33 ** load precompiled Lua chunks
44 ** See Copyright Notice in lua.h
55 */
@@ -20,249 +20,247 @@ · 14 unmodified lines
2020 #include "lundump.h"
2121 #include "lzio.h"
2222
23+
24+#if !defined(luai_verifycode)
25+#define luai_verifycode(L,b,f) /* empty */
26+#endif
27+
28+
2329 typedef struct {
24− lua_State* L;
25− ZIO* Z;
26− Mbuffer* b;
27− const char* name;
30+ lua_State *L;
31+ ZIO *Z;
32+ Mbuffer *b;
33+ const char *name;
2834 } LoadState;
2935
30−static l_noret error(LoadState* S, const char* why)
31−{
32− luaO_pushfstring(S->L,"%s: %s precompiled chunk",S->name,why);
33− luaD_throw(S->L,LUA_ERRSYNTAX);
36+
37+static l_noret error(LoadState *S, const char *why) {
38+ luaO_pushfstring(S->L, "%s: %s precompiled chunk", S->name, why);
39+ luaD_throw(S->L, LUA_ERRSYNTAX);
3440 }
3541
36−#define LoadMem(S,b,n,size) LoadBlock(S,b,(n)*(size))
37−#define LoadByte(S) (lu_byte)LoadChar(S)
38−#define LoadVar(S,x) LoadMem(S,&x,1,sizeof(x))
39−#define LoadVector(S,b,n,size) LoadMem(S,b,n,size)
4042
41−#if !defined(luai_verifycode)
42−#define luai_verifycode(L,b,f) /* empty */
43−#endif
43+/*
44+** All high-level loads go through LoadVector; you can change it to
45+** adapt to the endianess of the input
46+*/
47+#define LoadVector(S,b,n) LoadBlock(S,b,(n)*sizeof((b)[0]))
4448
45−static void LoadBlock(LoadState* S, void* b, size_t size)
46−{
47− if (luaZ_read(S->Z,b,size)!=0) error(S,"truncated");
49+static void LoadBlock (LoadState *S, void *b, size_t size) {
50+ if (luaZ_read(S->Z, b, size) != 0)
51+ error(S, "truncated");
4852 }
4953
50−static int LoadChar(LoadState* S)
51−{
52− char x;
53− LoadVar(S,x);
54− return x;
54+
55+#define LoadVar(S,x) LoadVector(S,&x,1)
56+
57+
58+static lu_byte LoadByte (LoadState *S) {
59+ lu_byte x;
60+ LoadVar(S, x);
61+ return x;
5562 }
5663
57−static int LoadInt(LoadState* S)
58−{
59− int x;
60− LoadVar(S,x);
61− if (x<0) error(S,"corrupted");
62− return x;
64+
65+static int LoadInt (LoadState *S) {
66+ int x;
67+ LoadVar(S, x);
68+ return x;
6369 }
6470
65−static lua_Number LoadNumber(LoadState* S)
66−{
67− lua_Number x;
68− LoadVar(S,x);
69− return x;
71+
72+static lua_Number LoadNumber (LoadState *S) {
73+ lua_Number x;
74+ LoadVar(S, x);
75+ return x;
7076 }
7177
72−static lua_Integer LoadInteger(LoadState* S)
73−{
74− lua_Integer x;
75− LoadVar(S,x);
76− return x;
78+
79+static lua_Integer LoadInteger (LoadState *S) {
80+ lua_Integer x;
81+ LoadVar(S, x);
82+ return x;
7783 }
7884
79−static TString* LoadString(LoadState* S)
80−{
81− size_t size;
82− LoadVar(S,size);
83− if (size==0)
84− return NULL;
85− else
86− {
87− char* s=luaZ_openspace(S->L,S->b,size);
88− LoadBlock(S,s,size*sizeof(char));
89− return luaS_newlstr(S->L,s,size-1); /* remove trailing '\0' */
90− }
85+
86+static TString *LoadString (LoadState *S) {
87+ size_t size = LoadByte(S);
88+ if (size == 0xFF)
89+ LoadVar(S, size);
90+ if (size == 0)
91+ return NULL;
92+ else {
93+ char *s = luaZ_openspace(S->L, S->b, --size);
94+ LoadVector(S, s, size);
95+ return luaS_newlstr(S->L, s, size);
96+ }
9197 }
9298
93−static void LoadCode(LoadState* S, Proto* f)
94−{
95− int n=LoadInt(S);
96− f->code=luaM_newvector(S->L,n,Instruction);
97− f->sizecode=n;
98− LoadVector(S,f->code,n,sizeof(Instruction));
99+
100+static void LoadCode (LoadState *S, Proto *f) {
101+ int n = LoadInt(S);
102+ f->code = luaM_newvector(S->L, n, Instruction);
103+ f->sizecode = n;
104+ LoadVector(S, f->code, n);
99105 }
100106
101−static void LoadFunction(LoadState* S, Proto* f);
102−
103−static void LoadConstants(LoadState* S, Proto* f)
104−{
105− int i,n;
106− n=LoadInt(S);
107− f->k=luaM_newvector(S->L,n,TValue);
108− f->sizek=n;
109− for (i=0; i<n; i++) setnilvalue(&f->k[i]);
110− for (i=0; i<n; i++)
111− {
112− TValue* o=&f->k[i];
113− int t=LoadChar(S);
114− switch (t)
115− {
116− case LUA_TNIL:
117− setnilvalue(o);
118− break;
119− case LUA_TBOOLEAN:
120− setbvalue(o,LoadChar(S));
121− break;
122− case LUA_TNUMFLT:
123− setnvalue(o,LoadNumber(S));
124− break;
125− case LUA_TNUMINT:
126− setivalue(o,LoadInteger(S));
127− break;
128− case LUA_TSHRSTR: case LUA_TLNGSTR:
129− setsvalue2n(S->L,o,LoadString(S));
130− break;
131− default: lua_assert(0);
107+
108+static void LoadFunction(LoadState *S, Proto *f);
109+
110+
111+static void LoadConstants (LoadState *S, Proto *f) {
112+ int i, n;
113+ n = LoadInt(S);
114+ f->k = luaM_newvector(S->L, n, TValue);
115+ f->sizek = n;
116+ for (i = 0; i < n; i++)
117+ setnilvalue(&f->k[i]);
118+ for (i = 0; i < n; i++) {
119+ TValue *o = &f->k[i];
120+ int t = LoadByte(S);
121+ switch (t) {
122+ case LUA_TNIL:
123+ setnilvalue(o);
124+ break;
125+ case LUA_TBOOLEAN:
126+ setbvalue(o, LoadByte(S));
127+ break;
128+ case LUA_TNUMFLT:
129+ setnvalue(o, LoadNumber(S));
130+ break;
131+ case LUA_TNUMINT:
132+ setivalue(o, LoadInteger(S));
133+ break;
134+ case LUA_TSHRSTR:
135+ case LUA_TLNGSTR:
136+ setsvalue2n(S->L, o, LoadString(S));
137+ break;
138+ default:
139+ lua_assert(0);
140+ }
141+ }
142+ n = LoadInt(S);
143+ f->p = luaM_newvector(S->L, n, Proto *);
144+ f->sizep = n;
145+ for (i = 0; i < n; i++)
146+ f->p[i] = NULL;
147+ for (i = 0; i < n; i++) {
148+ f->p[i] = luaF_newproto(S->L);
149+ LoadFunction(S, f->p[i]);
132150 }
133− }
134− n=LoadInt(S);
135− f->p=luaM_newvector(S->L,n,Proto*);
136− f->sizep=n;
137− for (i=0; i<n; i++) f->p[i]=NULL;
138− for (i=0; i<n; i++)
139− {
140− f->p[i]=luaF_newproto(S->L);
141− LoadFunction(S,f->p[i]);
142− }
143151 }
144152
145−static void LoadUpvalues(LoadState* S, Proto* f)
146−{
147− int i,n;
148− n=LoadInt(S);
149− f->upvalues=luaM_newvector(S->L,n,Upvaldesc);
150− f->sizeupvalues=n;
151− for (i=0; i<n; i++) f->upvalues[i].name=NULL;
152− for (i=0; i<n; i++)
153− {
154− f->upvalues[i].instack=LoadByte(S);
155− f->upvalues[i].idx=LoadByte(S);
156− }
153+
154+static void LoadUpvalues (LoadState *S, Proto *f) {
155+ int i, n;
156+ n = LoadInt(S);
157+ f->upvalues = luaM_newvector(S->L, n, Upvaldesc);
158+ f->sizeupvalues = n;
159+ for (i = 0; i < n; i++)
160+ f->upvalues[i].name = NULL;
161+ for (i = 0; i < n; i++) {
162+ f->upvalues[i].instack = LoadByte(S);
163+ f->upvalues[i].idx = LoadByte(S);
164+ }
157165 }
158166
159−static void LoadDebug(LoadState* S, Proto* f)
160−{
161− int i,n;
162− f->source=LoadString(S);
163− n=LoadInt(S);
164− f->lineinfo=luaM_newvector(S->L,n,int);
165− f->sizelineinfo=n;
166− LoadVector(S,f->lineinfo,n,sizeof(int));
167− n=LoadInt(S);
168− f->locvars=luaM_newvector(S->L,n,LocVar);
169− f->sizelocvars=n;
170− for (i=0; i<n; i++) f->locvars[i].varname=NULL;
171− for (i=0; i<n; i++)
172− {
173− f->locvars[i].varname=LoadString(S);
174− f->locvars[i].startpc=LoadInt(S);
175− f->locvars[i].endpc=LoadInt(S);
176− }
177− n=LoadInt(S);
178− for (i=0; i<n; i++) f->upvalues[i].name=LoadString(S);
167+
168+static void LoadDebug (LoadState *S, Proto *f) {
169+ int i, n;
170+ f->source = LoadString(S);
171+ n = LoadInt(S);
172+ f->lineinfo = luaM_newvector(S->L, n, int);
173+ f->sizelineinfo = n;
174+ LoadVector(S, f->lineinfo, n);
175+ n = LoadInt(S);
176+ f->locvars = luaM_newvector(S->L, n, LocVar);
177+ f->sizelocvars = n;
178+ for (i = 0; i < n; i++)
179+ f->locvars[i].varname = NULL;
180+ for (i = 0; i < n; i++) {
181+ f->locvars[i].varname = LoadString(S);
182+ f->locvars[i].startpc = LoadInt(S);
183+ f->locvars[i].endpc = LoadInt(S);
184+ }
185+ n = LoadInt(S);
186+ for (i = 0; i < n; i++)
187+ f->upvalues[i].name = LoadString(S);
179188 }
180189
181−static void LoadFunction(LoadState* S, Proto* f)
182−{
183− f->linedefined=LoadInt(S);
184− f->lastlinedefined=LoadInt(S);
185− f->numparams=LoadByte(S);
186− f->is_vararg=LoadByte(S);
187− f->maxstacksize=LoadByte(S);
188− LoadCode(S,f);
189− LoadConstants(S,f);
190− LoadUpvalues(S,f);
191− LoadDebug(S,f);
190+
191+static void LoadFunction (LoadState *S, Proto *f) {
192+ f->linedefined = LoadInt(S);
193+ f->lastlinedefined = LoadInt(S);
194+ f->numparams = LoadByte(S);
195+ f->is_vararg = LoadByte(S);
196+ f->maxstacksize = LoadByte(S);
197+ LoadCode(S, f);
198+ LoadConstants(S, f);
199+ LoadUpvalues(S, f);
200+ LoadDebug(S, f);
192201 }
193202
194−/* the code below must be consistent with the code in luaU_header */
195−#define N0 LUAC_HEADERSIZE
196−#define N1 (sizeof(LUA_SIGNATURE)-sizeof(char))
197−#define N2 N1+2
198−#define N3 N2+6
199−
200−static void LoadHeader(LoadState* S)
201−{
202− lu_byte h[LUAC_HEADERSIZE];
203− lu_byte s[LUAC_HEADERSIZE];
204− luaU_header(h);
205− memcpy(s,h,sizeof(char)); /* first char already read */
206− LoadBlock(S,s+sizeof(char),LUAC_HEADERSIZE-sizeof(char));
207− if (memcmp(h,s,N0)==0) return;
208− if (memcmp(h,s,N1)!=0) error(S,"not a");
209− if (memcmp(h,s,N2)!=0) error(S,"version mismatch in");
210− if (memcmp(h,s,N3)!=0) error(S,"incompatible"); else error(S,"corrupted");
203+
204+static void checkliteral (LoadState *S, const char *s, const char *msg) {
205+ char buff[sizeof(LUA_SIGNATURE) + sizeof(LUAC_DATA)]; /* larger than both */
206+ int len = strlen(s);
207+ LoadVector(S, buff, len);
208+ if (memcmp(s, buff, len) != 0)
209+ error(S, msg);
211210 }
212211
213−/*
214−** load precompiled chunk
215−*/
216−Closure* luaU_undump (lua_State* L, ZIO* Z, Mbuffer* buff, const char* name)
217−{
218− LoadState S;
219− Closure* cl;
220− if (*name=='@' || *name=='=')
221− S.name=name+1;
222− else if (*name==LUA_SIGNATURE[0])
223− S.name="binary string";
224− else
225− S.name=name;
226− S.L=L;
227− S.Z=Z;
228− S.b=buff;
229− LoadHeader(&S);
230− cl=luaF_newLclosure(L,1);
231− setclLvalue(L,L->top,cl); incr_top(L);
232− cl->l.p=luaF_newproto(L);
233− LoadFunction(&S,cl->l.p);
234− if (cl->l.p->sizeupvalues != 1)
235− {
236− Proto* p=cl->l.p;
237− cl=luaF_newLclosure(L,cl->l.p->sizeupvalues);
238− cl->l.p=p;
239− setclLvalue(L,L->top-1,cl);
240− }
241− luai_verifycode(L,buff,cl->l.p);
242− return cl;
212+
213+static void fchecksize (LoadState *S, size_t size, const char *tname) {
214+ if (LoadByte(S) != size)
215+ error(S, luaO_pushfstring(S->L, "%s size mismatch in", tname));
216+}
217+
218+
219+#define checksize(S,t) fchecksize(S,sizeof(t),#t)
220+
221+static void checkHeader (LoadState *S) {
222+ checkliteral(S, LUA_SIGNATURE + 1, "not a"); /* 1st char already checked */
223+ if (LoadByte(S) != LUAC_VERSION)
224+ error(S, "version mismatch in");
225+ if (LoadByte(S) != LUAC_FORMAT)
226+ error(S, "format mismatch in");
227+ checkliteral(S, LUAC_DATA, "corrupted");
228+ checksize(S, int);
229+ checksize(S, size_t);
230+ checksize(S, Instruction);
231+ checksize(S, lua_Integer);
232+ checksize(S, lua_Number);
233+ if (LoadInteger(S) != LUAC_INT)
234+ error(S, "endianess mismatch in");
235+ if (LoadNumber(S) != LUAC_NUM)
236+ error(S, "float format mismatch in");
243237 }
244238
245−#define MYINT(s) (s[0]-'0')
246−#define VERSION MYINT(LUA_VERSION_MAJOR)*16+MYINT(LUA_VERSION_MINOR)
247−#define FORMAT 0 /* this is the official format */
248239
249240 /*
250−* make header for precompiled chunks
251−* if you change the code below be sure to update LoadHeader and FORMAT above
252−* and LUAC_HEADERSIZE in lundump.h
241+** load precompiled chunk
253242 */
254−void luaU_header (lu_byte* h)
255−{
256− int x=1;
257− memcpy(h,LUA_SIGNATURE,sizeof(LUA_SIGNATURE)-sizeof(char));
258− h+=sizeof(LUA_SIGNATURE)-sizeof(char);
259− *h++=cast_byte(VERSION);
260− *h++=cast_byte(FORMAT);
261− *h++=cast_byte(*(char*)&x); /* endianness */
262− *h++=cast_byte(sizeof(int));
263− *h++=cast_byte(sizeof(size_t));
264− *h++=cast_byte(sizeof(Instruction));
265− *h++=cast_byte(sizeof(lua_Number));
266− *h++=cast_byte(((lua_Number)0.5)==0); /* is lua_Number integral? */
267− memcpy(h,LUAC_TAIL,sizeof(LUAC_TAIL)-sizeof(char));
243+Closure *luaU_undump(lua_State *L, ZIO *Z, Mbuffer *buff,
244+ const char *name) {
245+ LoadState S;
246+ Closure *cl;
247+ if (*name == '@' || *name == '=')
248+ S.name = name + 1;
249+ else if (*name == LUA_SIGNATURE[0])
250+ S.name = "binary string";
251+ else
252+ S.name = name;
253+ S.L = L;
254+ S.Z = Z;
255+ S.b = buff;
256+ checkHeader(&S);
257+ cl = luaF_newLclosure(L, LoadByte(&S));
258+ setclLvalue(L, L->top, cl);
259+ incr_top(L);
260+ cl->l.p = luaF_newproto(L);
261+ LoadFunction(&S, cl->l.p);
262+ lua_assert(cl->l.nupvalues == cl->l.p->sizeupvalues);
263+ luai_verifycode(L, buff, cl->l.p);
264+ return cl;
268265 }
266+
src/lundump.h+16−11
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lundump.h,v 1.39 2012/05/08 13:53:33 roberto Exp $
2+** $Id: lundump.h,v 1.42 2014/03/11 14:22:54 roberto Exp $
33 ** load precompiled Lua chunks
44 ** See Copyright Notice in lua.h
55 */
@@ -7,22 +7,27 @@ · 1 unmodified line
77 #ifndef lundump_h
88 #define lundump_h
99
10+#include "llimits.h"
1011 #include "lobject.h"
1112 #include "lzio.h"
1213
13−/* load one chunk; from lundump.c */
14−LUAI_FUNC Closure* luaU_undump (lua_State* L, ZIO* Z, Mbuffer* buff, const char* name);
1514
16−/* make header; from lundump.c */
17−LUAI_FUNC void luaU_header (lu_byte* h);
15+/* data to catch conversion errors */
16+#define LUAC_DATA "\x19\x93\r\n\x1a\n"
1817
19−/* dump one chunk; from ldump.c */
20−LUAI_FUNC int luaU_dump (lua_State* L, const Proto* f, lua_Writer w, void* data, int strip);
18+#define LUAC_INT cast_integer(0xABCD)
19+#define LUAC_NUM cast_num(370.5)
2120
22−/* data to catch conversion errors */
23−#define LUAC_TAIL "\x19\x93\r\n\x1a\n"
21+#define MYINT(s) (s[0]-'0')
22+#define LUAC_VERSION (MYINT(LUA_VERSION_MAJOR)*16+MYINT(LUA_VERSION_MINOR))
23+#define LUAC_FORMAT 0 /* this is the official format */
2424
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))
25+/* load one chunk; from lundump.c */
26+LUAI_FUNC Closure* luaU_undump (lua_State* L, ZIO* Z, Mbuffer* buff,
27+ const char* name);
28+
29+/* dump one chunk; from ldump.c */
30+LUAI_FUNC int luaU_dump (lua_State* L, const Proto* f, lua_Writer w,
31+ void* data, int strip);
2732
2833 #endif
src/lutf8lib.c+240−0
@@ -0,0 +1,240 @@
1+/*
2+** $Id: lutf8lib.c,v 1.4 2014/03/20 19:36:02 roberto Exp $
3+** Standard library for UTF-8 manipulation
4+** See Copyright Notice in lua.h
5+*/
6+
7+
8+#include <assert.h>
9+#include <stdlib.h>
10+#include <string.h>
11+
12+#define lutf8lib_c
13+#define LUA_LIB
14+
15+#include "lua.h"
16+
17+#include "lauxlib.h"
18+#include "lualib.h"
19+
20+#define MAXUNICODE 0x10FFFF
21+
22+#define iscont(p) ((*(p) & 0xC0) == 0x80)
23+
24+
25+/* from strlib */
26+/* translate a relative string position: negative means back from end */
27+static lua_Integer u_posrelat (lua_Integer pos, size_t len) {
28+ if (pos >= 0) return pos;
29+ else if (0u - (size_t)pos > len) return 0;
30+ else return (lua_Integer)len + pos + 1;
31+}
32+
33+
34+/*
35+** Decode an UTF-8 sequence, returning NULL if byte sequence is invalid.
36+*/
37+static const char *utf8_decode (const char *o, int *val) {
38+ static unsigned int limits[] = {0xFF, 0x7F, 0x7FF, 0xFFFF};
39+ const unsigned char *s = (const unsigned char *)o;
40+ unsigned int c = s[0];
41+ unsigned int res = 0; /* final result */
42+ if (c < 0x80) /* ascii? */
43+ res = c;
44+ else {
45+ int count = 0; /* to count number of continuation bytes */
46+ while (c & 0x40) { /* still have continuation bytes? */
47+ int cc = s[++count]; /* read next byte */
48+ if ((cc & 0xC0) != 0x80) /* not a continuation byte? */
49+ return NULL; /* invalid byte sequence */
50+ res = (res << 6) | (cc & 0x3F); /* add lower 6 bits from cont. byte */
51+ c <<= 1; /* to test next bit */
52+ }
53+ res |= ((c & 0x7F) << (count * 5)); /* add first byte */
54+ if (count > 3 || res > MAXUNICODE || res <= limits[count])
55+ return NULL; /* invalid byte sequence */
56+ s += count; /* skip continuation bytes read */
57+ }
58+ if (val) *val = res;
59+ return (const char *)s + 1; /* +1 to include first byte */
60+}
61+
62+
63+/*
64+** utf8len(s, [i]) --> number of codepoints in 's' after 'i';
65+** nil if 's' not well formed
66+*/
67+static int utflen (lua_State *L) {
68+ int n = 0;
69+ const char *ends;
70+ size_t len;
71+ const char *s = luaL_checklstring(L, 1, &len);
72+ lua_Integer posi = u_posrelat(luaL_optinteger(L, 2, 1), 1);
73+ luaL_argcheck(L, 1 <= posi && posi <= (lua_Integer)len, 1,
74+ "initial position out of string");
75+ ends = s + len;
76+ s += posi - 1;
77+ while (s < ends && (s = utf8_decode(s, NULL)) != NULL)
78+ n++;
79+ if (s == ends)
80+ lua_pushinteger(L, n);
81+ else
82+ lua_pushnil(L);
83+ return 1;
84+}
85+
86+
87+/*
88+** codepoint(s, [i, [j]]) -> returns codepoints for all characters
89+** between i and j
90+*/
91+static int codepoint (lua_State *L) {
92+ size_t len;
93+ const char *s = luaL_checklstring(L, 1, &len);
94+ lua_Integer posi = u_posrelat(luaL_optinteger(L, 2, 1), len);
95+ lua_Integer pose = u_posrelat(luaL_optinteger(L, 3, posi), len);
96+ int n;
97+ const char *se;
98+ luaL_argcheck(L, posi >= 1, 2, "out of range");
99+ luaL_argcheck(L, pose <= (lua_Integer)len, 3, "out of range");
100+ if (posi > pose) return 0; /* empty interval; return no values */
101+ n = (int)(pose - posi + 1);
102+ if (posi + n <= pose) /* (lua_Integer -> int) overflow? */
103+ return luaL_error(L, "string slice too long");
104+ luaL_checkstack(L, n, "string slice too long");
105+ n = 0;
106+ se = s + pose;
107+ for (s += posi - 1; s < se;) {
108+ int code;
109+ s = utf8_decode(s, &code);
110+ if (s == NULL)
111+ return luaL_error(L, "invalid UTF-8 code");
112+ lua_pushinteger(L, code);
113+ n++;
114+ }
115+ return n;
116+}
117+
118+
119+static void pushutfchar (lua_State *L, int arg) {
120+ int code = luaL_checkint(L, arg);
121+ luaL_argcheck(L, 0 <= code && code <= MAXUNICODE, arg, "value out of range");
122+ lua_pushfstring(L, "%U", code);
123+}
124+
125+
126+/*
127+** utfchar(n1, n2, ...) -> char(n1)..char(n2)...
128+*/
129+static int utfchar (lua_State *L) {
130+ int n = lua_gettop(L); /* number of arguments */
131+ if (n == 1) /* optimize common case of single char */
132+ pushutfchar(L, 1);
133+ else {
134+ int i;
135+ luaL_Buffer b;
136+ luaL_buffinit(L, &b);
137+ for (i = 1; i <= n; i++) {
138+ pushutfchar(L, i);
139+ luaL_addvalue(&b);
140+ }
141+ luaL_pushresult(&b);
142+ }
143+ return 1;
144+}
145+
146+
147+/*
148+** offset(s, n, [i]) -> index where n-th character *after*
149+** position 'i' starts; 0 means character at 'i'.
150+*/
151+static int byteoffset (lua_State *L) {
152+ size_t len;
153+ const char *s = luaL_checklstring(L, 1, &len);
154+ int n = luaL_checkint(L, 2);
155+ lua_Integer posi = u_posrelat(luaL_optinteger(L, 3, 1), len) - 1;
156+ luaL_argcheck(L, 0 <= posi && posi <= (lua_Integer)len, 3,
157+ "position out of range");
158+ if (n == 0) {
159+ /* find beginning of current byte sequence */
160+ while (posi > 0 && iscont(s + posi)) posi--;
161+ }
162+ else if (n < 0) {
163+ while (n < 0 && posi > 0) { /* move back */
164+ do { /* find beginning of previous character */
165+ posi--;
166+ } while (posi > 0 && iscont(s + posi));
167+ n++;
168+ }
169+ }
170+ else {
171+ n--; /* do not move for 1st character */
172+ while (n > 0 && posi < (lua_Integer)len) {
173+ do { /* find beginning of next character */
174+ posi++;
175+ } while (iscont(s + posi)); /* ('\0' is not continuation) */
176+ n--;
177+ }
178+ }
179+ if (n == 0)
180+ lua_pushinteger(L, posi + 1);
181+ else
182+ lua_pushnil(L); /* no such position */
183+ return 1;
184+}
185+
186+
187+static int iter_aux (lua_State *L) {
188+ size_t len;
189+ const char *s = luaL_checklstring(L, 1, &len);
190+ int n = lua_tointeger(L, 2) - 1;
191+ if (n < 0) /* first iteration? */
192+ n = 0; /* start from here */
193+ else if (n < (lua_Integer)len) {
194+ n++; /* skip current byte */
195+ while (iscont(s + n)) n++; /* and its continuations */
196+ }
197+ if (n >= (lua_Integer)len)
198+ return 0; /* no more codepoints */
199+ else {
200+ int code;
201+ const char *next = utf8_decode(s + n, &code);
202+ if (next == NULL || iscont(next))
203+ return luaL_error(L, "invalid UTF-8 code");
204+ lua_pushinteger(L, n + 1);
205+ lua_pushinteger(L, code);
206+ return 2;
207+ }
208+}
209+
210+
211+static int iter_codes (lua_State *L) {
212+ luaL_checkstring(L, 1);
213+ lua_pushcfunction(L, iter_aux);
214+ lua_pushvalue(L, 1);
215+ lua_pushinteger(L, 0);
216+ return 3;
217+}
218+
219+
220+/* pattern to match a single UTF-8 character */
221+#define UTF8PATT "[\0-\x7F\xC2-\xF4][\x80-\xBF]*"
222+
223+
224+static struct luaL_Reg funcs[] = {
225+ {"offset", byteoffset},
226+ {"codepoint", codepoint},
227+ {"char", utfchar},
228+ {"len", utflen},
229+ {"codes", iter_codes},
230+ {NULL, NULL}
231+};
232+
233+
234+int luaopen_utf8 (lua_State *L) {
235+ luaL_newlib(L, funcs);
236+ lua_pushliteral(L, UTF8PATT);
237+ lua_setfield(L, -2, "charpatt");
238+ return 1;
239+}
240+
src/lvm.c+125−56
@@ -1,10 +1,11 @@
11 /*
2−** $Id: lvm.c,v 2.175 2013/06/20 15:02:49 roberto Exp $
2+** $Id: lvm.c,v 2.190 2014/03/15 12:29:48 roberto Exp $
33 ** Lua virtual machine
44 ** See Copyright Notice in lua.h
55 */
66
77
8+#include <limits.h>
89 #include <stdio.h>
910 #include <stdlib.h>
1011 #include <string.h>
@@ -29,7 +30,7 @@ · 18 unmodified lines
2930
3031
3132 /* limit for table tag-method chains (to avoid loops) */
32−#define MAXTAGLOOP 100
33+#define MAXTAGLOOP 2000
3334
3435
3536 /* maximum length of the conversion of a number to a string */
@@ -52,17 +53,9 @@ int luaV_tostring (lua_State *L, StkId obj) { · 16 unmodified lines
5253 return 0;
5354 else {
5455 char buff[MAXNUMBER2STR];
55− size_t len;
56− if (ttisinteger(obj))
57− len = lua_integer2str(buff, ivalue(obj));
58− else {
59− len = lua_number2str(buff, fltvalue(obj));
60− if (strspn(buff, "-0123456789") == len) { /* look like an integer? */
61− buff[len++] = '.'; /* add a '.0' */
62− buff[len++] = '0';
63− buff[len] = '\0';
64− }
65− }
56+ size_t len = (ttisinteger(obj))
57+ ? lua_integer2str(buff, ivalue(obj))
58+ : lua_number2str(buff, fltvalue(obj));
6659 setsvalue2s(L, obj, luaS_newlstr(L, buff, len));
6760 return 1;
6861 }
@@ -73,7 +66,7 @@ int luaV_tostring (lua_State *L, StkId obj) { · 4 unmodified lines
7366 ** Check whether a float number is within the range of a lua_Integer.
7467 ** (The comparisons are tricky because of rounding, which can or
7568 ** not occur depending on the relative sizes of floats and integers.)
76−** This function is called only when 'n' has an integer value.
69+** This function should be called only when 'n' has an integral value.
7770 */
7871 int luaV_numtointeger (lua_Number n, lua_Integer *p) {
7972 if (cast_num(MIN_INTEGER) <= n && n < (MAX_INTEGER + cast_num(1))) {
@@ -121,7 +114,7 @@ void luaV_gettable (lua_State *L, const TValue *t, TValue *key, StkId val) { · 41 unmodified lines
121114 }
122115 t = tm; /* else repeat with 'tm' */
123116 }
124− luaG_runerror(L, "loop in gettable");
117+ luaG_runerror(L, "gettable chain too long; possible loop");
125118 }
126119
127120
@@ -145,7 +138,7 @@ void luaV_settable (lua_State *L, const TValue *t, TValue *key, StkId val) { · 17 unmodified lines
145138 /* no metamethod and (now) there is an entry with given key */
146139 setobj2t(L, oldval, val); /* assign new value to that entry */
147140 invalidateTMcache(h);
148− luaC_barrierback(L, obj2gco(h), val);
141+ luaC_barrierback(L, h, val);
149142 return;
150143 }
151144 /* else will try the metamethod */
@@ -160,7 +153,7 @@ void luaV_settable (lua_State *L, const TValue *t, TValue *key, StkId val) { · 8 unmodified lines
160153 }
161154 t = tm; /* else repeat with 'tm' */
162155 }
163− luaG_runerror(L, "loop in settable");
156+ luaG_runerror(L, "settable chain too long; possible loop");
164157 }
165158
166159
@@ -192,7 +185,7 @@ int luaV_lessthan (lua_State *L, const TValue *l, const TValue *r) { · 25 unmodified lines
192185 if (ttisinteger(l) && ttisinteger(r))
193186 return (ivalue(l) < ivalue(r));
194187 else if (tonumber(l, &nl) && tonumber(r, &nr))
195− return luai_numlt(L, nl, nr);
188+ return luai_numlt(nl, nr);
196189 else if (ttisstring(l) && ttisstring(r))
197190 return l_strcmp(rawtsvalue(l), rawtsvalue(r)) < 0;
198191 else if ((res = luaT_callorderTM(L, l, r, TM_LT)) < 0)
@@ -207,7 +200,7 @@ int luaV_lessequal (lua_State *L, const TValue *l, const TValue *r) { · 8 unmodified lines
207200 if (ttisinteger(l) && ttisinteger(r))
208201 return (ivalue(l) <= ivalue(r));
209202 else if (tonumber(l, &nl) && tonumber(r, &nr))
210− return luai_numle(L, nl, nr);
203+ return luai_numle(nl, nr);
211204 else if (ttisstring(l) && ttisstring(r))
212205 return l_strcmp(rawtsvalue(l), rawtsvalue(r)) <= 0;
213206 else if ((res = luaT_callorderTM(L, l, r, TM_LE)) >= 0) /* first try `le' */
@@ -229,7 +222,7 @@ int luaV_equalobj (lua_State *L, const TValue *t1, const TValue *t2) { · 15 unmodified lines
229222 else { /* two numbers with different variants */
230223 lua_Number n1, n2;
231224 lua_assert(ttisnumber(t1) && ttisnumber(t2));
232− (void)tonumber(t1, &n1); (void)tonumber(t2, &n2);
225+ cast_void(tonumber(t1, &n1)); cast_void(tonumber(t2, &n2));
233226 return luai_numeq(n1, n2);
234227 }
235228 }
@@ -272,7 +265,7 @@ void luaV_concat (lua_State *L, int total) { · 36 unmodified lines
272265 if (!(ttisstring(top-2) || ttisnumber(top-2)) || !tostring(L, top-1))
273266 luaT_trybinTM(L, top-2, top-1, top-2, TM_CONCAT);
274267 else if (tsvalue(top-1)->len == 0) /* second operand is empty? */
275− (void)tostring(L, top - 2); /* result is first operand */
268+ cast_void(tostring(L, top - 2)); /* result is first operand */
276269 else if (ttisstring(top-2) && tsvalue(top-2)->len == 0) {
277270 setobjs2s(L, top - 2, top - 1); /* result is second op. */
278271 }
@@ -333,8 +326,7 @@ lua_Integer luaV_div (lua_State *L, lua_Integer x, lua_Integer y) { · 54 unmodified lines
333326 if (cast_unsigned(y) + 1 <= 1U) { /* special cases: -1 or 0 */
334327 if (y == 0)
335328 luaG_runerror(L, "attempt to divide by zero");
336− else /* -1 */
337− return -x; /* avoid overflow with 0x80000... */
329+ return intop(-, 0, x); /* y==-1; avoid overflow with 0x80000...//-1 */
338330 }
339331 else {
340332 lua_Integer d = x / y; /* perform division */
@@ -350,8 +342,7 @@ lua_Integer luaV_mod (lua_State *L, lua_Integer x, lua_Integer y) { · 9 unmodified lines
350342 if (cast_unsigned(y) + 1 <= 1U) { /* special cases: -1 or 0 */
351343 if (y == 0)
352344 luaG_runerror(L, "attempt to perform 'n%%0'");
353− else /* -1 */
354− return 0; /* avoid overflow with 0x80000... */
345+ return 0; /* y==-1; avoid overflow with 0x80000...%-1 */
355346 }
356347 else {
357348 lua_Integer r = x % y;
@@ -363,16 +354,36 @@ lua_Integer luaV_mod (lua_State *L, lua_Integer x, lua_Integer y) { · 5 unmodified lines
363354 }
364355
365356
366−lua_Integer luaV_pow (lua_Integer x, lua_Integer y) {
367− lua_Integer r = 1;
368− lua_assert(y >= 0);
369− if (y == 0) return r;
370− for (; y > 1; y >>= 1) {
371− if (y & 1) r = intop(*, r, x);
372− x = intop(*, x, x);
357+lua_Integer luaV_pow (lua_State *L, lua_Integer x, lua_Integer y) {
358+ if (y <= 0) { /* special cases: 0 or negative exponent */
359+ if (y < 0)
360+ luaG_runerror(L, "integer exponentiation with negative exponent");
361+ return 1; /* x^0 == 1 */
362+ }
363+ else {
364+ lua_Integer r = 1;
365+ for (; y > 1; y >>= 1) {
366+ if (y & 1) r = intop(*, r, x);
367+ x = intop(*, x, x);
368+ }
369+ r = intop(*, r, x);
370+ return r;
371+ }
372+}
373+
374+
375+/* number of bits in an integer */
376+#define NBITS cast_int(sizeof(lua_Integer) * CHAR_BIT)
377+
378+LUAI_FUNC lua_Integer luaV_shiftl (lua_Integer x, lua_Integer y) {
379+ if (y < 0) { /* shift right? */
380+ if (y <= -NBITS) return 0;
381+ else return cast_integer(cast_unsigned(x) >> (-y));
382+ }
383+ else { /* shift left */
384+ if (y >= NBITS) return 0;
385+ else return x << y;
373386 }
374− r = intop(*, r, x);
375− return r;
376387 }
377388
378389
@@ -399,9 +410,9 @@ static Closure *getcached (Proto *p, UpVal **encup, StkId base) { · 20 unmodified lines
399410
400411 /*
401412 ** create a new Lua closure, push it in the stack, and initialize
402−** its upvalues. Note that the call to 'luaC_barrierproto' must come
403−** before the assignment to 'p->cache', as the function needs the
404−** original value of that field.
413+** its upvalues. Note that the closure is not cached if prototype is
414+** already black (which means that 'cache' was already cleared by the
415+** GC).
405416 */
406417 static void pushclosure (lua_State *L, Proto *p, UpVal **encup, StkId base,
407418 StkId ra) {
@@ -416,9 +427,11 @@ static void pushclosure (lua_State *L, Proto *p, UpVal **encup, StkId base, · 8 unmodified lines
416427 ncl->l.upvals[i] = luaF_findupval(L, base + uv[i].idx);
417428 else /* get upvalue from enclosing function */
418429 ncl->l.upvals[i] = encup[uv[i].idx];
430+ ncl->l.upvals[i]->refcount++;
431+ /* new closure is white, so we do not need a barrier here */
419432 }
420− luaC_barrierproto(L, p, ncl);
421− p->cache = ncl; /* save it on cache for reuse */
433+ if (!isblack(obj2gco(p))) /* cache will not break GC invariant? */
434+ p->cache = ncl; /* save it on cache for reuse */
422435 }
423436
424437
@@ -432,7 +445,9 @@ void luaV_finishOp (lua_State *L) { · 7 unmodified lines
432445 OpCode op = GET_OPCODE(inst);
433446 switch (op) { /* finish its execution */
434447 case OP_ADD: case OP_SUB: case OP_MUL: case OP_DIV: case OP_IDIV:
435− case OP_MOD: case OP_POW: case OP_UNM: case OP_LEN:
448+ case OP_BAND: case OP_BOR: case OP_BXOR: case OP_SHL: case OP_SHR:
449+ case OP_MOD: case OP_POW:
450+ case OP_UNM: case OP_BNOT: case OP_LEN:
436451 case OP_GETTABUP: case OP_GETTABLE: case OP_SELF: {
437452 setobjs2s(L, base + GETARG_A(inst), --L->top);
438453 break;
@@ -590,7 +605,7 @@ void luaV_execute (lua_State *L) { · 151 unmodified lines
590605 vmcase(OP_SETUPVAL,
591606 UpVal *uv = cl->upvals[GETARG_B(i)];
592607 setobj(L, uv->v, ra);
593− luaC_barrier(L, uv, ra);
608+ luaC_upvalbarrier(L, uv);
594609 )
595610 vmcase(OP_SETTABLE,
596611 Protect(luaV_settable(L, ra, RKB(i), RKC(i)));
@@ -666,6 +681,51 @@ void luaV_execute (lua_State *L) { · 69 unmodified lines
666681 }
667682 else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_IDIV)); }
668683 )
684+ vmcase(OP_BAND,
685+ TValue *rb = RKB(i);
686+ TValue *rc = RKC(i);
687+ lua_Integer ib; lua_Integer ic;
688+ if (tointeger(rb, &ib) && tointeger(rc, &ic)) {
689+ setivalue(ra, intop(&, ib, ic));
690+ }
691+ else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_BAND)); }
692+ )
693+ vmcase(OP_BOR,
694+ TValue *rb = RKB(i);
695+ TValue *rc = RKC(i);
696+ lua_Integer ib; lua_Integer ic;
697+ if (tointeger(rb, &ib) && tointeger(rc, &ic)) {
698+ setivalue(ra, intop(|, ib, ic));
699+ }
700+ else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_BOR)); }
701+ )
702+ vmcase(OP_BXOR,
703+ TValue *rb = RKB(i);
704+ TValue *rc = RKC(i);
705+ lua_Integer ib; lua_Integer ic;
706+ if (tointeger(rb, &ib) && tointeger(rc, &ic)) {
707+ setivalue(ra, intop(^, ib, ic));
708+ }
709+ else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_BXOR)); }
710+ )
711+ vmcase(OP_SHL,
712+ TValue *rb = RKB(i);
713+ TValue *rc = RKC(i);
714+ lua_Integer ib; lua_Integer ic;
715+ if (tointeger(rb, &ib) && tointeger(rc, &ic)) {
716+ setivalue(ra, luaV_shiftl(ib, ic));
717+ }
718+ else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_SHL)); }
719+ )
720+ vmcase(OP_SHR,
721+ TValue *rb = RKB(i);
722+ TValue *rc = RKC(i);
723+ lua_Integer ib; lua_Integer ic;
724+ if (tointeger(rb, &ib) && tointeger(rc, &ic)) {
725+ setivalue(ra, luaV_shiftl(ib, -ic));
726+ }
727+ else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_SHR)); }
728+ )
669729 vmcase(OP_MOD,
670730 TValue *rb = RKB(i);
671731 TValue *rc = RKC(i);
@@ -683,11 +743,9 @@ void luaV_execute (lua_State *L) { · 11 unmodified lines
683743 TValue *rb = RKB(i);
684744 TValue *rc = RKC(i);
685745 lua_Number nb; lua_Number nc;
686− lua_Integer ic;
687− if (ttisinteger(rb) && ttisinteger(rc) &&
688− (ic = ivalue(rc)) >= 0) {
689− lua_Integer ib = ivalue(rb);
690− setivalue(ra, luaV_pow(ib, ic));
746+ if (ttisinteger(rb) && ttisinteger(rc)) {
747+ lua_Integer ib = ivalue(rb); lua_Integer ic = ivalue(rc);
748+ setivalue(ra, luaV_pow(L, ib, ic));
691749 }
692750 else if (tonumber(rb, &nb) && tonumber(rc, &nc)) {
693751 setnvalue(ra, luai_numpow(L, nb, nc));
@@ -699,7 +757,7 @@ void luaV_execute (lua_State *L) { · 5 unmodified lines
699757 lua_Number nb;
700758 if (ttisinteger(rb)) {
701759 lua_Integer ib = ivalue(rb);
702− setivalue(ra, -ib);
760+ setivalue(ra, intop(-, 0, ib));
703761 }
704762 else if (tonumber(rb, &nb)) {
705763 setnvalue(ra, luai_numunm(L, nb));
@@ -708,6 +766,16 @@ void luaV_execute (lua_State *L) { · 2 unmodified lines
708766 Protect(luaT_trybinTM(L, rb, rb, ra, TM_UNM));
709767 }
710768 )
769+ vmcase(OP_BNOT,
770+ TValue *rb = RB(i);
771+ lua_Integer ib;
772+ if (tointeger(rb, &ib)) {
773+ setivalue(ra, intop(^, cast_integer(-1), ib));
774+ }
775+ else {
776+ Protect(luaT_trybinTM(L, rb, rb, ra, TM_BNOT));
777+ }
778+ )
711779 vmcase(OP_NOT,
712780 TValue *rb = RB(i);
713781 int res = l_isfalse(rb); /* next assignment may change this value */
@@ -831,7 +899,7 @@ void luaV_execute (lua_State *L) { · 117 unmodified lines
831899 }
832900 )
833901 vmcase(OP_FORLOOP,
834− if (ttisinteger(ra)) { /* integer count? */
902+ if (ttisinteger(ra)) { /* integer loop? */
835903 lua_Integer step = ivalue(ra + 2);
836904 lua_Integer idx = ivalue(ra) + step; /* increment index */
837905 lua_Integer limit = ivalue(ra + 1);
@@ -841,12 +909,12 @@ void luaV_execute (lua_State *L) { · 3 unmodified lines
841909 setivalue(ra + 3, idx); /* ...and external index */
842910 }
843911 }
844− else { /* floating count */
912+ else { /* floating loop */
845913 lua_Number step = fltvalue(ra + 2);
846914 lua_Number idx = luai_numadd(L, fltvalue(ra), step); /* inc. index */
847915 lua_Number limit = fltvalue(ra + 1);
848− if (luai_numlt(L, 0, step) ? luai_numle(L, idx, limit)
849− : luai_numle(L, limit, idx)) {
916+ if (luai_numlt(0, step) ? luai_numle(idx, limit)
917+ : luai_numle(limit, idx)) {
850918 ci->u.l.savedpc += GETARG_sBx(i); /* jump back */
851919 setnvalue(ra, idx); /* update internal index... */
852920 setnvalue(ra + 3, idx); /* ...and external index */
@@ -857,10 +925,11 @@ void luaV_execute (lua_State *L) { · 4 unmodified lines
857925 TValue *init = ra;
858926 TValue *plimit = ra + 1;
859927 TValue *pstep = ra + 2;
860− if (ttisinteger(ra) && ttisinteger(ra + 1) && ttisinteger(ra + 2)) {
861− setivalue(ra, ivalue(ra) - ivalue(pstep));
928+ if (ttisinteger(init) && ttisinteger(plimit) && ttisinteger(pstep)) {
929+ /* all values are integer */
930+ setivalue(init, ivalue(init) - ivalue(pstep));
862931 }
863− else { /* try with floats */
932+ else { /* try making all values floats */
864933 lua_Number ninit; lua_Number nlimit; lua_Number nstep;
865934 if (!tonumber(plimit, &nlimit))
866935 luaG_runerror(L, LUA_QL("for") " limit must be a number");
@@ -870,7 +939,7 @@ void luaV_execute (lua_State *L) { · 3 unmodified lines
870939 setnvalue(pstep, nstep);
871940 if (!tonumber(init, &ninit))
872941 luaG_runerror(L, LUA_QL("for") " initial value must be a number");
873− setnvalue(ra, luai_numsub(L, ninit, nstep));
942+ setnvalue(init, luai_numsub(L, ninit, nstep));
874943 }
875944 ci->u.l.savedpc += GETARG_sBx(i);
876945 )
@@ -912,7 +981,7 @@ void luaV_execute (lua_State *L) { · 35 unmodified lines
912981 for (; n > 0; n--) {
913982 TValue *val = ra+n;
914983 luaH_setint(L, h, last--, val);
915− luaC_barrierback(L, obj2gco(h), val);
984+ luaC_barrierback(L, h, val);
916985 }
917986 L->top = ci->top; /* correct top (in case of previous open call) */
918987 )
src/lvm.h+3−2
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lvm.h,v 2.23 2013/05/02 12:31:26 roberto Exp $
2+** $Id: lvm.h,v 2.25 2013/12/30 20:47:58 roberto Exp $
33 ** Lua virtual machine
44 ** See Copyright Notice in lua.h
55 */
@@ -43,7 +43,8 @@ LUAI_FUNC void luaV_execute (lua_State *L); · 37 unmodified lines
4343 LUAI_FUNC void luaV_concat (lua_State *L, int total);
4444 LUAI_FUNC lua_Integer luaV_div (lua_State *L, lua_Integer x, lua_Integer y);
4545 LUAI_FUNC lua_Integer luaV_mod (lua_State *L, lua_Integer x, lua_Integer y);
46−LUAI_FUNC lua_Integer luaV_pow (lua_Integer x, lua_Integer y);
46+LUAI_FUNC lua_Integer luaV_pow (lua_State *L, lua_Integer x, lua_Integer y);
47+LUAI_FUNC lua_Integer luaV_shiftl (lua_Integer x, lua_Integer y);
4748 LUAI_FUNC void luaV_objlen (lua_State *L, StkId ra, const TValue *rb);
4849
4950 #endif
src/lzio.h+2−1
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lzio.h,v 1.27 2013/06/07 14:51:10 roberto Exp $
2+** $Id: lzio.h,v 1.28 2014/01/31 15:14:22 roberto Exp $
33 ** Buffered streams
44 ** See Copyright Notice in lua.h
55 */
@@ -32,6 +32,7 @@ typedef struct Mbuffer { · 26 unmodified lines
3232 #define luaZ_sizebuffer(buff) ((buff)->buffsize)
3333 #define luaZ_bufflen(buff) ((buff)->n)
3434
35+#define luaZ_buffremove(buff,i) ((buff)->n -= (i))
3536 #define luaZ_resetbuffer(buff) ((buff)->n = 0)
3637
3738