History

Lua 5.2.0-work3

Lua Team committed 16 years ago

Commit d618ddd1 parent be77f2777 files · +3825 −3949Browse files

Showing the changes to src (46 of 77 files). Show all

Unified · Split

46 files
  1. src/Makefile +5 −5
  2. src/lapi.c +126 −114
  3. src/lauxlib.c +92 −109
  4. src/lauxlib.h +22 −17
  5. src/lbaselib.c +27 −68
  6. src/lbitlib.c +27 −7
  7. src/lcode.c +31 −20
  8. src/lcode.h +5 −3
  9. src/ldblib.c +14 −16
  10. src/ldebug.c +72 −44
  11. src/ldo.c +41 −34
  12. src/ldump.c +1 −2
  13. src/lfunc.c +12 −11
  14. src/lfunc.h +3 −3
  15. src/lgc.c +429 −263
  16. src/lgc.h +61 −30
  17. src/linit.c +4 −5
  18. src/liolib.c +82 −47
  19. src/llex.c +69 −47
  20. src/llex.h +2 −1
  21. src/llimits.h +7 −6
  22. src/lmem.c +25 −4
  23. src/lmem.h +1 −3
  24. src/loadlib.c +17 −14
  25. src/lobject.c +19 −19
  26. src/lobject.h +35 −23
  27. src/lopcodes.c +5 −5
  28. src/lopcodes.h +4 −5
  29. src/lparser.c +95 −89
  30. src/lparser.h +5 −6
  31. src/lstate.c +34 −46
  32. src/lstate.h +16 −18
  33. src/lstring.c +7 −1
  34. src/lstring.h +9 −3
  35. src/lstrlib.c +79 −53
  36. src/ltable.c +5 −2
  37. src/ltablib.c +10 −10
  38. src/ltm.c +2 −2
  39. src/ltm.h +3 −2
  40. src/lua.c +27 −25
  41. src/lua.h +18 −12
  42. src/luac.c +9 −22
  43. src/luaconf.h +37 −34
  44. src/lundump.c +1 −2
  45. src/lvm.c +137 −197
  46. src/print.c +15 −6
src/Makefile+5−5
@@ -27,7 +27,7 @@ CORE_O= lapi.o lcode.o lctype.o ldebug.o ldo.o ldump.o lfunc.o lgc.o llex.o \ · 26 unmodified lines
2727 lmem.o lobject.o lopcodes.o lparser.o lstate.o lstring.o ltable.o \
2828 ltm.o lundump.o lvm.o lzio.o
2929 LIB_O= lauxlib.o lbaselib.o lbitlib.o ldblib.o liolib.o lmathlib.o loslib.o \
30− ltablib.o lstrlib.o loadlib.o linit.o
30+ lstrlib.o ltablib.o loadlib.o linit.o
3131
3232 LUA_T= lua
3333 LUA_O= lua.o
@@ -103,7 +103,7 @@ macosx: · 69 unmodified lines
103103 $(MAKE) $(ALL) MYCFLAGS="-DLUA_USE_MACOSX" MYLIBS="-lreadline"
104104
105105 mingw:
106− $(MAKE) "LUA_A=lua51.dll" "LUA_T=lua.exe" \
106+ $(MAKE) "LUA_A=lua52.dll" "LUA_T=lua.exe" \
107107 "AR=$(CC) -shared -o" "RANLIB=strip --strip-unneeded" \
108108 "MYCFLAGS=-DLUA_BUILD_AS_DLL" "MYLIBS=" "MYLDFLAGS=-s" lua.exe
109109
@@ -137,8 +137,8 @@ ldo.o: ldo.c lua.h luaconf.h lapi.h llimits.h lstate.h lobject.h ltm.h \ · 27 unmodified lines
137137 lstring.h ltable.h lundump.h lvm.h
138138 ldump.o: ldump.c lua.h luaconf.h lobject.h llimits.h lstate.h ltm.h \
139139 lzio.h lmem.h lundump.h
140−lfunc.o: lfunc.c lua.h luaconf.h lfunc.h lobject.h llimits.h lgc.h lmem.h \
141− lopcodes.h lstate.h ltm.h lzio.h
140+lfunc.o: lfunc.c lua.h luaconf.h lfunc.h lobject.h llimits.h lgc.h \
141+ lstate.h ltm.h lzio.h lmem.h lopcodes.h
142142 lgc.o: lgc.c lua.h luaconf.h ldebug.h lstate.h lobject.h llimits.h ltm.h \
143143 lzio.h lmem.h ldo.h lfunc.h lgc.h lstring.h ltable.h
144144 linit.o: linit.c lua.h luaconf.h lualib.h lauxlib.h
@@ -163,7 +163,7 @@ lstring.o: lstring.c lua.h luaconf.h lmem.h llimits.h lobject.h lstate.h \ · 18 unmodified lines
163163 ltm.h lzio.h lstring.h lgc.h
164164 lstrlib.o: lstrlib.c lua.h luaconf.h lauxlib.h lualib.h
165165 ltable.o: ltable.c lua.h luaconf.h ldebug.h lstate.h lobject.h llimits.h \
166− ltm.h lzio.h lmem.h ldo.h lgc.h ltable.h
166+ ltm.h lzio.h lmem.h ldo.h lgc.h lstring.h ltable.h
167167 ltablib.o: ltablib.c lua.h luaconf.h lauxlib.h lualib.h
168168 ltm.o: ltm.c lua.h luaconf.h lobject.h llimits.h lstate.h ltm.h lzio.h \
169169 lmem.h lstring.h lgc.h ltable.h
src/lapi.c+126−114
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lapi.c,v 2.111 2010/01/13 16:18:25 roberto Exp $
2+** $Id: lapi.c,v 2.129 2010/05/14 13:15:26 roberto Exp $
33 ** Lua API
44 ** See Copyright Notice in lua.h
55 */
@@ -39,16 +39,6 @@ const char lua_ident[] = · 33 unmodified lines
3939 "invalid index")
4040
4141
42−static Table *getcurrenv (lua_State *L) {
43− if (L->ci->previous == NULL) /* no enclosing function? */
44− return G(L)->l_gt; /* use global table as environment */
45− else {
46− Closure *func = curr_func(L);
47− return func->c.env;
48− }
49−}
50−
51−
5242 static TValue *index2addr (lua_State *L, int idx) {
5343 CallInfo *ci = L->ci;
5444 if (idx > 0) {
@@ -61,26 +51,25 @@ static TValue *index2addr (lua_State *L, int idx) { · 6 unmodified lines
6151 api_check(L, idx != 0 && -idx <= L->top - (ci->func + 1), "invalid index");
6252 return L->top + idx;
6353 }
64− else switch (idx) { /* pseudo-indices */
65− case LUA_REGISTRYINDEX: return &G(L)->l_registry;
66− case LUA_ENVIRONINDEX: {
67− sethvalue(L, &L->env, getcurrenv(L));
68− return &L->env;
69− }
70− default: {
71− Closure *func = curr_func(L);
72− idx = LUA_ENVIRONINDEX - idx;
73− api_check(L, idx <= UCHAR_MAX + 1, "upvalue index too large");
54+ else if (idx == LUA_REGISTRYINDEX)
55+ return &G(L)->l_registry;
56+ else { /* upvalues */
57+ idx = LUA_REGISTRYINDEX - idx;
58+ api_check(L, idx <= UCHAR_MAX + 1, "upvalue index too large");
59+ if (ttislcf(ci->func)) /* light C function? */
60+ return cast(TValue *, luaO_nilobject); /* it has no upvalues */
61+ else {
62+ Closure *func = clvalue(ci->func);
7463 return (idx <= func->c.nupvalues)
75− ? &func->c.upvalue[idx-1]
76− : cast(TValue *, luaO_nilobject);
64+ ? &func->c.upvalue[idx-1]
65+ : cast(TValue *, luaO_nilobject);
7766 }
7867 }
7968 }
8069
8170
8271 /*
83−** to be caled by 'lua_checkstack' in protected mode, to grow stack
72+** to be called by 'lua_checkstack' in protected mode, to grow stack
8473 ** capturing memory errors
8574 */
8675 static void growstack (lua_State *L, void *ud) {
@@ -147,6 +136,16 @@ LUA_API const lua_Number *lua_version (lua_State *L) { · 60 unmodified lines
147136 */
148137
149138
139+/*
140+** convert an acceptable stack index into an absolute index
141+*/
142+LUA_API int lua_absindex (lua_State *L, int idx) {
143+ return (idx > 0 || idx <= LUA_REGISTRYINDEX)
144+ ? idx
145+ : cast_int(L->top - L->ci->func + idx);
146+}
147+
148+
150149 LUA_API int lua_gettop (lua_State *L) {
151150 return cast_int(L->top - (L->ci->func + 1));
152151 }
@@ -195,16 +194,10 @@ LUA_API void lua_insert (lua_State *L, int idx) { · 42 unmodified lines
195194 static void moveto (lua_State *L, TValue *fr, int idx) {
196195 TValue *to = index2addr(L, idx);
197196 api_checkvalidindex(L, to);
198− if (idx == LUA_ENVIRONINDEX) {
199− Closure *func = curr_func(L);
200− api_check(L, ttistable(fr), "table expected");
201− func->c.env = hvalue(fr);
202− luaC_barrier(L, func, fr);
203− }
204− else {
205− setobj(L, to, fr);
206− if (idx < LUA_ENVIRONINDEX) /* function upvalue? */
207− luaC_barrier(L, curr_func(L), fr);
197+ setobj(L, to, fr);
198+ if (idx < LUA_REGISTRYINDEX) { /* function upvalue? */
199+ lua_assert(ttisclosure(L->ci->func));
200+ luaC_barrier(L, clvalue(L->ci->func), fr);
208201 }
209202 /* LUA_REGISTRYINDEX does not need gc barrier
210203 (collector revisits it before finishing collection) */
@@ -213,9 +206,6 @@ static void moveto (lua_State *L, TValue *fr, int idx) { · 2 unmodified lines
213206
214207 LUA_API void lua_replace (lua_State *L, int idx) {
215208 lua_lock(L);
216− /* explicit test for incompatible code */
217− if (idx == LUA_ENVIRONINDEX && L->ci->previous == NULL)
218− luaG_runerror(L, "no calling environment");
219209 api_checknelems(L, 1);
220210 moveto(L, L->top - 1, idx);
221211 L->top--;
@@ -249,19 +239,19 @@ LUA_API void lua_pushvalue (lua_State *L, int idx) { · 27 unmodified lines
249239
250240 LUA_API int lua_type (lua_State *L, int idx) {
251241 StkId o = index2addr(L, idx);
252− return (o == luaO_nilobject) ? LUA_TNONE : ttype(o);
242+ return (o == luaO_nilobject) ? LUA_TNONE : ttypenv(o);
253243 }
254244
255245
256246 LUA_API const char *lua_typename (lua_State *L, int t) {
257247 UNUSED(L);
258− return typename(t);
248+ return ttypename(t);
259249 }
260250
261251
262252 LUA_API int lua_iscfunction (lua_State *L, int idx) {
263253 StkId o = index2addr(L, idx);
264− return iscfunction(o);
254+ return (ttislcf(o) || (ttisclosure(o) && clvalue(o)->c.isC));
265255 }
266256
267257
@@ -387,7 +377,10 @@ LUA_API size_t lua_rawlen (lua_State *L, int idx) { · 119 unmodified lines
387377
388378 LUA_API lua_CFunction lua_tocfunction (lua_State *L, int idx) {
389379 StkId o = index2addr(L, idx);
390− return (!iscfunction(o)) ? NULL : clvalue(o)->c.f;
380+ if (ttislcf(o)) return fvalue(o);
381+ else if (ttisclosure(o) && clvalue(o)->c.isC)
382+ return clvalue(o)->c.f;
383+ else return NULL; /* not a C function */
391384 }
392385
393386
@@ -412,6 +405,7 @@ LUA_API const void *lua_topointer (lua_State *L, int idx) { · 18 unmodified lines
412405 switch (ttype(o)) {
413406 case LUA_TTABLE: return hvalue(o);
414407 case LUA_TFUNCTION: return clvalue(o);
408+ case LUA_TLCF: return cast(void *, cast(size_t, fvalue(o)));
415409 case LUA_TTHREAD: return thvalue(o);
416410 case LUA_TUSERDATA:
417411 case LUA_TLIGHTUSERDATA:
@@ -468,8 +462,16 @@ LUA_API const char *lua_pushstring (lua_State *L, const char *s) { · 50 unmodified lines
468462 lua_pushnil(L);
469463 return NULL;
470464 }
471− else
472− return lua_pushlstring(L, s, strlen(s));
465+ else {
466+ TString *ts;
467+ lua_lock(L);
468+ luaC_checkGC(L);
469+ ts = luaS_new(L, s);
470+ setsvalue2s(L, L->top, ts);
471+ api_incr_top(L);
472+ lua_unlock(L);
473+ return getstr(ts);
474+ }
473475 }
474476
475477
@@ -498,18 +500,22 @@ LUA_API const char *lua_pushfstring (lua_State *L, const char *fmt, ...) { · 22 unmodified lines
498500
499501
500502 LUA_API void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n) {
501− Closure *cl;
502503 lua_lock(L);
503− api_checknelems(L, n);
504− api_check(L, n <= UCHAR_MAX, "upvalue index too large");
505− luaC_checkGC(L);
506− cl = luaF_newCclosure(L, n, getcurrenv(L));
507− cl->c.f = fn;
508− L->top -= n;
509− while (n--)
510− setobj2n(L, &cl->c.upvalue[n], L->top+n);
511− setclvalue(L, L->top, cl);
512− lua_assert(iswhite(obj2gco(cl)));
504+ if (n == 0) {
505+ setfvalue(L->top, fn);
506+ }
507+ else {
508+ Closure *cl;
509+ api_checknelems(L, n);
510+ api_check(L, n <= UCHAR_MAX, "upvalue index too large");
511+ luaC_checkGC(L);
512+ cl = luaF_newCclosure(L, n);
513+ cl->c.f = fn;
514+ L->top -= n;
515+ while (n--)
516+ setobj2n(L, &cl->c.upvalue[n], L->top + n);
517+ setclvalue(L, L->top, cl);
518+ }
513519 api_incr_top(L);
514520 lua_unlock(L);
515521 }
@@ -616,7 +622,7 @@ LUA_API int lua_getmetatable (lua_State *L, int objindex) { · 100 unmodified lines
616622 mt = uvalue(obj)->metatable;
617623 break;
618624 default:
619− mt = G(L)->mt[ttype(obj)];
625+ mt = G(L)->mt[ttypenv(obj)];
620626 break;
621627 }
622628 if (mt == NULL)
@@ -631,22 +637,16 @@ LUA_API int lua_getmetatable (lua_State *L, int objindex) { · 8 unmodified lines
631637 }
632638
633639
634−LUA_API void lua_getfenv (lua_State *L, int idx) {
640+LUA_API void lua_getenv (lua_State *L, int idx) {
635641 StkId o;
636642 lua_lock(L);
637643 o = index2addr(L, idx);
638644 api_checkvalidindex(L, o);
639− switch (ttype(o)) {
640− case LUA_TFUNCTION:
641− sethvalue(L, L->top, clvalue(o)->c.env);
642− break;
643− case LUA_TUSERDATA:
644− sethvalue(L, L->top, uvalue(o)->env);
645− break;
646− default:
647− setnilvalue(L->top);
648− break;
649− }
645+ api_check(L, ttisuserdata(o), "userdata expected");
646+ if (uvalue(o)->env) {
647+ sethvalue(L, L->top, uvalue(o)->env);
648+ } else
649+ setnilvalue(L->top);
650650 api_incr_top(L);
651651 lua_unlock(L);
652652 }
@@ -737,7 +737,7 @@ LUA_API int lua_setmetatable (lua_State *L, int objindex) { · 84 unmodified lines
737737 break;
738738 }
739739 default: {
740− G(L)->mt[ttype(obj)] = mt;
740+ G(L)->mt[ttypenv(obj)] = mt;
741741 break;
742742 }
743743 }
@@ -747,29 +747,22 @@ LUA_API int lua_setmetatable (lua_State *L, int objindex) { · 3 unmodified lines
747747 }
748748
749749
750−LUA_API int lua_setfenv (lua_State *L, int idx) {
750+LUA_API void lua_setenv (lua_State *L, int idx) {
751751 StkId o;
752− int res = 1;
753752 lua_lock(L);
754753 api_checknelems(L, 1);
755754 o = index2addr(L, idx);
756755 api_checkvalidindex(L, o);
757− api_check(L, ttistable(L->top - 1), "table expected");
758− switch (ttype(o)) {
759− case LUA_TFUNCTION:
760− clvalue(o)->c.env = hvalue(L->top - 1);
761− break;
762− case LUA_TUSERDATA:
763− uvalue(o)->env = hvalue(L->top - 1);
764− break;
765− default:
766− res = 0;
767− break;
756+ api_check(L, ttisuserdata(o), "userdata expected");
757+ if (ttisnil(L->top - 1))
758+ uvalue(o)->env = NULL;
759+ else {
760+ api_check(L, ttistable(L->top - 1), "table expected");
761+ uvalue(o)->env = hvalue(L->top - 1);
762+ luaC_objbarrier(L, gcvalue(o), hvalue(L->top - 1));
768763 }
769− if (res) luaC_objbarrier(L, gcvalue(o), hvalue(L->top - 1));
770764 L->top--;
771765 lua_unlock(L);
772− return res;
773766 }
774767
775768
@@ -857,7 +850,7 @@ LUA_API int lua_pcallk (lua_State *L, int nargs, int nresults, int errfunc, · 81 unmodified lines
857850 ci->u.c.k = k; /* save continuation */
858851 ci->u.c.ctx = ctx; /* save context */
859852 /* save information for error recovery */
860− ci->u.c.oldtop = savestack(L, c.func);
853+ ci->u.c.extra = savestack(L, c.func);
861854 ci->u.c.old_allowhook = L->allowhook;
862855 ci->u.c.old_errfunc = L->errfunc;
863856 L->errfunc = func;
@@ -882,6 +875,18 @@ LUA_API int lua_load (lua_State *L, lua_Reader reader, void *data, · 18 unmodified lines
882875 if (!chunkname) chunkname = "?";
883876 luaZ_init(L, &z, reader, data);
884877 status = luaD_protectedparser(L, &z, chunkname);
878+ if (status == LUA_OK) { /* no errors? */
879+ Closure *f = clvalue(L->top - 1); /* get newly created function */
880+ lua_assert(!f->c.isC);
881+ if (f->l.nupvalues == 1) { /* does it have one upvalue? */
882+ /* get global table from registry */
883+ Table *reg = hvalue(&G(L)->l_registry);
884+ const TValue *gt = luaH_getint(reg, LUA_RIDX_GLOBALS);
885+ /* set global table as 1st upvalue of 'f' (may be _ENV) */
886+ setobj(L, f->l.upvals[0]->v, gt);
887+ luaC_barrier(L, f->l.upvals[0], gt);
888+ }
889+ }
885890 lua_unlock(L);
886891 return status;
887892 }
@@ -918,11 +923,11 @@ LUA_API int lua_gc (lua_State *L, int what, int data) { · 30 unmodified lines
918923 g = G(L);
919924 switch (what) {
920925 case LUA_GCSTOP: {
921− g->GCthreshold = MAX_LUMEM;
926+ stopgc(g);
922927 break;
923928 }
924929 case LUA_GCRESTART: {
925− g->GCthreshold = g->totalbytes;
930+ g->GCdebt = 0;
926931 break;
927932 }
928933 case LUA_GCCOLLECT: {
@@ -939,18 +944,22 @@ LUA_API int lua_gc (lua_State *L, int what, int data) { · 10 unmodified lines
939944 break;
940945 }
941946 case LUA_GCSTEP: {
942− lu_mem oldts = g->GCthreshold;
943− lu_mem a = (cast(lu_mem, data) << 10);
944− g->GCthreshold = (a <= g->totalbytes) ? g->totalbytes - a : 0;
945− while (g->GCthreshold <= g->totalbytes) {
946− luaC_step(L);
947− if (g->gcstate == GCSpause) { /* end of cycle? */
948− res = 1; /* signal it */
949− break;
947+ int stopped = gcstopped(g);
948+ if (g->gckind == KGC_GEN) { /* generational mode? */
949+ res = (g->lastmajormem == 0); /* 1 if will do major collection */
950+ luaC_step(L); /* do a single step */
951+ }
952+ else {
953+ while (data-- >= 0) {
954+ luaC_step(L);
955+ if (g->gcstate == GCSpause) { /* end of cycle? */
956+ res = 1; /* signal it */
957+ break;
958+ }
950959 }
951960 }
952− if (oldts == MAX_LUMEM) /* collector was stopped? */
953− g->GCthreshold = oldts; /* keep it that way */
961+ if (stopped) /* collector was stopped? */
962+ stopgc(g); /* keep it that way */
954963 break;
955964 }
956965 case LUA_GCSETPAUSE: {
@@ -964,7 +973,15 @@ LUA_API int lua_gc (lua_State *L, int what, int data) { · 7 unmodified lines
964973 break;
965974 }
966975 case LUA_GCISRUNNING: {
967− res = (g->GCthreshold != MAX_LUMEM);
976+ res = !gcstopped(g);
977+ break;
978+ }
979+ case LUA_GCGEN: { /* change collector to generational mode */
980+ luaC_changemode(L, KGC_GEN);
981+ break;
982+ }
983+ case LUA_GCINC: { /* change collector to incremental mode */
984+ luaC_changemode(L, KGC_NORMAL);
968985 break;
969986 }
970987 default: res = -1; /* invalid option */
@@ -1054,7 +1071,7 @@ LUA_API void *lua_newuserdata (lua_State *L, size_t size) { · 83 unmodified lines
10541071 Udata *u;
10551072 lua_lock(L);
10561073 luaC_checkGC(L);
1057− u = luaS_newudata(L, size, getcurrenv(L));
1074+ u = luaS_newudata(L, size, NULL);
10581075 setuvalue(L, L->top, u);
10591076 api_incr_top(L);
10601077 lua_unlock(L);
@@ -1064,19 +1081,22 @@ LUA_API void *lua_newuserdata (lua_State *L, size_t size) { · 3 unmodified lines
10641081
10651082
10661083
1067−static const char *aux_upvalue (StkId fi, int n, TValue **val) {
1084+static const char *aux_upvalue (StkId fi, int n, TValue **val,
1085+ GCObject **owner) {
10681086 Closure *f;
1069− if (!ttisfunction(fi)) return NULL;
1087+ if (!ttisclosure(fi)) return NULL;
10701088 f = clvalue(fi);
10711089 if (f->c.isC) {
10721090 if (!(1 <= n && n <= f->c.nupvalues)) return NULL;
10731091 *val = &f->c.upvalue[n-1];
1092+ if (owner) *owner = obj2gco(f);
10741093 return "";
10751094 }
10761095 else {
10771096 Proto *p = f->l.p;
10781097 if (!(1 <= n && n <= p->sizeupvalues)) return NULL;
10791098 *val = f->l.upvals[n-1]->v;
1099+ if (owner) *owner = obj2gco(f->l.upvals[n - 1]);
10801100 return getstr(p->upvalues[n-1].name);
10811101 }
10821102 }
@@ -1086,7 +1106,7 @@ LUA_API const char *lua_getupvalue (lua_State *L, int funcindex, int n) { · 3 unmodified lines
10861106 const char *name;
10871107 TValue *val;
10881108 lua_lock(L);
1089− name = aux_upvalue(index2addr(L, funcindex), n, &val);
1109+ name = aux_upvalue(index2addr(L, funcindex), n, &val, NULL);
10901110 if (name) {
10911111 setobj2s(L, L->top, val);
10921112 api_incr_top(L);
@@ -1099,15 +1119,16 @@ LUA_API const char *lua_getupvalue (lua_State *L, int funcindex, int n) { · 6 unmodified lines
10991119 LUA_API const char *lua_setupvalue (lua_State *L, int funcindex, int n) {
11001120 const char *name;
11011121 TValue *val;
1122+ GCObject *owner;
11021123 StkId fi;
11031124 lua_lock(L);
11041125 fi = index2addr(L, funcindex);
11051126 api_checknelems(L, 1);
1106− name = aux_upvalue(fi, n, &val);
1127+ name = aux_upvalue(fi, n, &val, &owner);
11071128 if (name) {
11081129 L->top--;
11091130 setobj(L, val, L->top);
1110− luaC_barrier(L, clvalue(fi), L->top);
1131+ luaC_barrier(L, owner, L->top);
11111132 }
11121133 lua_unlock(L);
11131134 return name;
@@ -1118,7 +1139,7 @@ static UpVal **getupvalref (lua_State *L, int fidx, int n, Closure **pf) { · 4 unmodified lines
11181139 Closure *f;
11191140 Proto *p;
11201141 StkId fi = index2addr(L, fidx);
1121− api_check(L, ttisfunction(fi), "function expected");
1142+ api_check(L, ttisclosure(fi), "Lua function expected");
11221143 f = clvalue(fi);
11231144 api_check(L, !f->c.isC, "Lua function expected");
11241145 p = f->l.p;
@@ -1131,7 +1152,7 @@ static UpVal **getupvalref (lua_State *L, int fidx, int n, Closure **pf) { · 6 unmodified lines
11311152 LUA_API void *lua_upvalueid (lua_State *L, int fidx, int n) {
11321153 Closure *f;
11331154 StkId fi = index2addr(L, fidx);
1134− api_check(L, ttisfunction(fi), "function expected");
1155+ api_check(L, ttisclosure(fi), "function expected");
11351156 f = clvalue(fi);
11361157 if (f->c.isC) {
11371158 api_check(L, 1 <= n && n <= f->c.nupvalues, "invalid upvalue index");
@@ -1150,12 +1171,3 @@ LUA_API void lua_upvaluejoin (lua_State *L, int fidx1, int n1, · 12 unmodified lines
11501171 luaC_objbarrier(L, f1, *up2);
11511172 }
11521173
1153−
1154−#if defined(LUA_COMPAT_CPCALL)
1155−LUA_API int lua_cpcall (lua_State *L, lua_CFunction func, void *ud) {
1156− lua_rawgeti(L, LUA_REGISTRYINDEX, LUA_RIDX_CPCALL);
1157− lua_pushlightuserdata(L, &func);
1158− lua_pushlightuserdata(L, ud);
1159− return lua_pcall(L, 2, 0, 0);
1160−}
1161−#endif
src/lauxlib.c+92−109
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lauxlib.c,v 1.196 2009/12/22 15:32:50 roberto Exp $
2+** $Id: lauxlib.c,v 1.212 2010/05/18 17:21:24 roberto Exp $
33 ** Auxiliary functions for building Lua libraries
44 ** See Copyright Notice in lua.h
55 */
@@ -24,11 +24,6 @@ · 18 unmodified lines
2424 #include "lauxlib.h"
2525
2626
27−/* convert a stack index to positive */
28−#define abs_index(L, i) ((i) > 0 || (i) <= LUA_REGISTRYINDEX ? (i) : \
29− lua_gettop(L) + (i) + 1)
30−
31−
3227 /*
3328 ** {======================================================
3429 ** Traceback
@@ -347,54 +342,40 @@ LUALIB_API lua_Integer luaL_optinteger (lua_State *L, int narg, · 312 unmodified lines
347342 ** =======================================================
348343 */
349344
350−
351−#define bufflen(B) ((B)->p - (B)->buffer)
352−#define bufffree(B) ((size_t)(LUAL_BUFFERSIZE - bufflen(B)))
353−
354−#define LIMIT (LUA_MINSTACK/2)
355−
356−
357−static int emptybuffer (luaL_Buffer *B) {
358− size_t l = bufflen(B);
359− if (l == 0) return 0; /* put nothing on stack */
360− else {
361− lua_pushlstring(B->L, B->buffer, l);
362− B->p = B->buffer;
363− B->lvl++;
364− return 1;
365− }
366−}
345+/*
346+** check whether buffer is using a userdata on the stack as a temporary
347+** buffer
348+*/
349+#define buffonstack(B) ((B)->b != (B)->initb)
367350
368351
369−static void adjuststack (luaL_Buffer *B) {
370− if (B->lvl > 1) {
371− lua_State *L = B->L;
372− int toget = 1; /* number of levels to concat */
373− size_t toplen = lua_rawlen(L, -1);
374− do {
375− size_t l = lua_rawlen(L, -(toget+1));
376− if (B->lvl - toget + 1 >= LIMIT || toplen > l) {
377− toplen += l;
378− toget++;
379− }
380− else break;
381− } while (toget < B->lvl);
382− lua_concat(L, toget);
383− B->lvl = B->lvl - toget + 1;
352+/*
353+** returns a pointer to a free area with at least 'sz' bytes
354+*/
355+LUALIB_API char *luaL_prepbuffsize (luaL_Buffer *B, size_t sz) {
356+ lua_State *L = B->L;
357+ if (B->size - B->n < sz) { /* not enough space? */
358+ char *newbuff;
359+ size_t newsize = B->size * 2; /* double buffer size */
360+ if (newsize - B->n < sz) /* not bit enough? */
361+ newsize = B->n + sz;
362+ if (newsize < B->n || newsize - B->n < sz)
363+ luaL_error(L, "string too large");
364+ newbuff = (char *)lua_newuserdata(L, newsize); /* create larger buffer */
365+ memcpy(newbuff, B->b, B->n); /* move content to new buffer */
366+ if (buffonstack(B))
367+ lua_remove(L, -2); /* remove old buffer */
368+ B->b = newbuff;
369+ B->size = newsize;
384370 }
385−}
386−
387−
388−LUALIB_API char *luaL_prepbuffer (luaL_Buffer *B) {
389− if (emptybuffer(B))
390− adjuststack(B);
391− return B->buffer;
371+ return &B->b[B->n];
392372 }
393373
394374
395375 LUALIB_API void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l) {
396− while (l--)
397− luaL_addchar(B, *s++);
376+ char *b = luaL_prepbuffsize(B, l);
377+ memcpy(b, s, l);
378+ luaL_addsize(B, l);
398379 }
399380
400381
@@ -404,35 +385,41 @@ LUALIB_API void luaL_addstring (luaL_Buffer *B, const char *s) { · 3 unmodified lines
404385
405386
406387 LUALIB_API void luaL_pushresult (luaL_Buffer *B) {
407− emptybuffer(B);
408− lua_concat(B->L, B->lvl);
409− B->lvl = 1;
388+ lua_State *L = B->L;
389+ lua_pushlstring(L, B->b, B->n);
390+ if (buffonstack(B))
391+ lua_remove(L, -2); /* remove old buffer */
392+}
393+
394+
395+LUALIB_API void luaL_pushresultsize (luaL_Buffer *B, size_t sz) {
396+ luaL_addsize(B, sz);
397+ luaL_pushresult(B);
410398 }
411399
412400
413401 LUALIB_API void luaL_addvalue (luaL_Buffer *B) {
414402 lua_State *L = B->L;
415− size_t vl;
416− const char *s = lua_tolstring(L, -1, &vl);
417− if (vl <= bufffree(B)) { /* fit into buffer? */
418− memcpy(B->p, s, vl); /* put it there */
419− B->p += vl;
420− lua_pop(L, 1); /* remove from stack */
421− }
422− else {
423− if (emptybuffer(B))
424− lua_insert(L, -2); /* put buffer before new value */
425− B->lvl++; /* add new value into B stack */
426− adjuststack(B);
427− }
403+ size_t l;
404+ const char *s = lua_tolstring(L, -1, &l);
405+ if (buffonstack(B))
406+ lua_insert(L, -2); /* put value below buffer */
407+ luaL_addlstring(B, s, l);
408+ lua_remove(L, (buffonstack(B)) ? -2 : -1); /* remove value */
428409 }
429410
430411
431412 LUALIB_API void luaL_buffinit (lua_State *L, luaL_Buffer *B) {
432− luaL_checkstack(L, LIMIT + LUA_MINSTACK, "no space for new buffer");
433413 B->L = L;
434− B->p = B->buffer;
435− B->lvl = 0;
414+ B->b = B->initb;
415+ B->n = 0;
416+ B->size = LUAL_BUFFERSIZE;
417+}
418+
419+
420+LUALIB_API char *luaL_buffinitsize (lua_State *L, luaL_Buffer *B, size_t sz) {
421+ luaL_buffinit(L, B);
422+ return luaL_prepbuffsize(B, sz);
436423 }
437424
438425 /* }====================================================== */
@@ -444,32 +431,26 @@ LUALIB_API void luaL_buffinit (lua_State *L, luaL_Buffer *B) { · 5 unmodified lines
444431 ** =======================================================
445432 */
446433
447−/* number of prereserved references (for internal use) */
448−#define FREELIST_REF (LUA_RIDX_LAST + 1) /* free list of references */
434+/* index of free-list header */
435+#define freelist "lua-freelist"
449436
450437
451438 LUALIB_API int luaL_ref (lua_State *L, int t) {
452439 int ref;
453− t = abs_index(L, t);
440+ t = lua_absindex(L, t);
454441 if (lua_isnil(L, -1)) {
455442 lua_pop(L, 1); /* remove from stack */
456443 return LUA_REFNIL; /* `nil' has a unique fixed reference */
457444 }
458− lua_rawgeti(L, t, FREELIST_REF); /* get first free element */
445+ lua_getfield(L, t, freelist); /* get first free element */
459446 ref = (int)lua_tointeger(L, -1); /* ref = t[FREELIST_REF] */
460447 lua_pop(L, 1); /* remove it from stack */
461448 if (ref != 0) { /* any free element? */
462449 lua_rawgeti(L, t, ref); /* remove it from list */
463− lua_rawseti(L, t, FREELIST_REF); /* (t[FREELIST_REF] = t[ref]) */
450+ lua_setfield(L, t, freelist); /* (t[freelist] = t[ref]) */
464451 }
465− else { /* no free elements */
452+ else /* no free elements */
466453 ref = (int)lua_rawlen(L, t) + 1; /* get a new reference */
467− if (ref == FREELIST_REF) { /* FREELIST_REF not initialized? */
468− lua_pushinteger(L, 0);
469− lua_rawseti(L, t, FREELIST_REF);
470− ref = FREELIST_REF + 1;
471− }
472− }
473454 lua_rawseti(L, t, ref);
474455 return ref;
475456 }
@@ -477,11 +458,11 @@ LUALIB_API int luaL_ref (lua_State *L, int t) { · 1 unmodified line
477458
478459 LUALIB_API void luaL_unref (lua_State *L, int t, int ref) {
479460 if (ref >= 0) {
480− t = abs_index(L, t);
481− lua_rawgeti(L, t, FREELIST_REF);
482− lua_rawseti(L, t, ref); /* t[ref] = t[FREELIST_REF] */
461+ t = lua_absindex(L, t);
462+ lua_getfield(L, t, freelist);
463+ lua_rawseti(L, t, ref); /* t[ref] = t[freelist] */
483464 lua_pushinteger(L, ref);
484− lua_rawseti(L, t, FREELIST_REF); /* t[FREELIST_REF] = ref */
465+ lua_setfield(L, t, freelist); /* t[freelist] = ref */
485466 }
486467 }
487468
@@ -495,7 +476,7 @@ LUALIB_API void luaL_unref (lua_State *L, int t, int ref) { · 7 unmodified lines
495476 */
496477
497478 typedef struct LoadF {
498− int extraline;
479+ int first;
499480 FILE *f;
500481 char buff[LUAL_BUFFERSIZE];
501482 } LoadF;
@@ -504,17 +485,19 @@ typedef struct LoadF { · 2 unmodified lines
504485 static const char *getF (lua_State *L, void *ud, size_t *size) {
505486 LoadF *lf = (LoadF *)ud;
506487 (void)L;
507− if (lf->extraline) {
508− lf->extraline = 0;
488+ if (lf->first != EOF) {
509489 *size = 1;
510− return "\n";
490+ lf->buff[0] = (char)lf->first;
491+ lf->first = EOF;
492+ }
493+ else {
494+ /* 'fread' can return > 0 *and* set the EOF flag. If next call to
495+ 'getF' called 'fread', it might still wait for user input.
496+ The next check avoids this problem. */
497+ if (feof(lf->f)) return NULL;
498+ *size = fread(lf->buff, 1, sizeof(lf->buff), lf->f);
511499 }
512− /* 'fread' can return > 0 *and* set the EOF flag. If next call to
513− 'getF' calls 'fread', terminal may still wait for user input.
514− The next check avoids this problem. */
515− if (feof(lf->f)) return NULL;
516− *size = fread(lf->buff, 1, sizeof(lf->buff), lf->f);
517− return (*size > 0) ? lf->buff : NULL;
500+ return lf->buff;
518501 }
519502
520503
@@ -532,7 +515,6 @@ LUALIB_API int luaL_loadfile (lua_State *L, const char *filename) { · 11 unmodified lines
532515 int status, readstatus;
533516 int c;
534517 int fnameindex = lua_gettop(L) + 1; /* index of filename on the stack */
535− lf.extraline = 0;
536518 if (filename == NULL) {
537519 lua_pushliteral(L, "=stdin");
538520 lf.f = stdin;
@@ -544,18 +526,14 @@ LUALIB_API int luaL_loadfile (lua_State *L, const char *filename) { · 5 unmodified lines
544526 }
545527 c = getc(lf.f);
546528 if (c == '#') { /* Unix exec. file? */
547− lf.extraline = 1;
548529 while ((c = getc(lf.f)) != EOF && c != '\n') ; /* skip first line */
549− if (c == '\n') c = getc(lf.f);
550530 }
551− if (c == LUA_SIGNATURE[0] && filename) { /* binary file? */
531+ else if (c == LUA_SIGNATURE[0] && filename) { /* binary file? */
552532 lf.f = freopen(filename, "rb", lf.f); /* reopen in binary mode */
553533 if (lf.f == NULL) return errfile(L, "reopen", fnameindex);
554− /* skip eventual `#!...' */
555− while ((c = getc(lf.f)) != EOF && c != LUA_SIGNATURE[0]) ;
556− lf.extraline = 0;
534+ c = getc(lf.f); /* re-read first character */
557535 }
558− ungetc(c, lf.f);
536+ lf.first = c; /* 'c' is the first character of the stream */
559537 status = lua_load(L, getF, &lf, lua_tostring(L, -1));
560538 readstatus = ferror(lf.f);
561539 if (filename) fclose(lf.f); /* close file (even in case of errors) */
@@ -618,7 +596,7 @@ LUALIB_API int luaL_getmetafield (lua_State *L, int obj, const char *event) { · 56 unmodified lines
618596
619597
620598 LUALIB_API int luaL_callmeta (lua_State *L, int obj, const char *event) {
621− obj = abs_index(L, obj);
599+ obj = lua_absindex(L, obj);
622600 if (!luaL_getmetafield(L, obj, event)) /* no metafield? */
623601 return 0;
624602 lua_pushvalue(L, obj);
@@ -663,13 +641,13 @@ LUALIB_API const char *luaL_tolstring (lua_State *L, int idx, size_t *len) { · 38 unmodified lines
663641
664642 static int libsize (const luaL_Reg *l) {
665643 int size = 0;
666− for (; l->name; l++) size++;
644+ for (; l && l->name; l++) size++;
667645 return size;
668646 }
669647
670648
671−LUALIB_API void luaL_register (lua_State *L, const char *libname,
672− const luaL_Reg *l) {
649+LUALIB_API void luaL_openlib (lua_State *L, const char *libname,
650+ const luaL_Reg *l, int nup) {
673651 luaL_checkversion(L);
674652 if (libname) {
675653 /* check whether lib already exists */
@@ -685,12 +663,17 @@ LUALIB_API void luaL_register (lua_State *L, const char *libname, · 9 unmodified lines
685663 lua_setfield(L, -3, libname); /* _LOADED[libname] = new table */
686664 }
687665 lua_remove(L, -2); /* remove _LOADED table */
666+ lua_insert(L, -(nup + 1)); /* move library table to below upvalues */
688667 }
689− if (l == NULL) return; /* nothing to register? */
690− for (; l->name; l++) { /* else fill the table with given functions */
691− lua_pushcfunction(L, l->func);
692− lua_setfield(L, -2, l->name);
668+ luaL_checkstack(L, nup, "too many upvalues");
669+ for (; l && l->name; l++) { /* fill the table with given functions */
670+ int i;
671+ for (i = 0; i < nup; i++) /* copy upvalues to the top */
672+ lua_pushvalue(L, -nup);
673+ lua_pushcclosure(L, l->func, nup);
674+ lua_setfield(L, -(nup + 2), l->name);
693675 }
676+ lua_pop(L, nup); /* remove upvalues */
694677 }
695678
696679
@@ -751,7 +734,7 @@ static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) { · 54 unmodified lines
751734
752735
753736 static int panic (lua_State *L) {
754− fprintf(stderr, "PANIC: unprotected error in call to Lua API (%s)\n",
737+ luai_writestringerror("PANIC: unprotected error in call to Lua API (%s)\n",
755738 lua_tostring(L, -1));
756739 return 0; /* return to Lua to abort */
757740 }
src/lauxlib.h+22−17
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lauxlib.h,v 1.99 2010/01/11 16:00:45 roberto Exp $
2+** $Id: lauxlib.h,v 1.105 2010/05/04 17:21:08 roberto Exp $
33 ** Auxiliary functions for building Lua libraries
44 ** See Copyright Notice in lua.h
55 */
@@ -29,11 +29,11 @@ typedef struct luaL_Reg { · 23 unmodified lines
2929 LUALIB_API void (luaL_checkversion_) (lua_State *L, lua_Number ver);
3030 #define luaL_checkversion(L) luaL_checkversion_(L, LUA_VERSION_NUM)
3131
32−LUALIB_API void (luaL_register) (lua_State *L, const char *libname,
33− const luaL_Reg *l);
32+LUALIB_API void (luaL_openlib) (lua_State *L, const char *libname,
33+ const luaL_Reg *l, int nup);
3434 LUALIB_API int (luaL_getmetafield) (lua_State *L, int obj, const char *e);
3535 LUALIB_API int (luaL_callmeta) (lua_State *L, int obj, const char *e);
36−LUALIB_API const char *luaL_tolstring (lua_State *L, int idx, size_t *len);
36+LUALIB_API const char *(luaL_tolstring) (lua_State *L, int idx, size_t *len);
3737 LUALIB_API int (luaL_typeerror) (lua_State *L, int narg, const char *tname);
3838 LUALIB_API int (luaL_argerror) (lua_State *L, int numarg, const char *extramsg);
3939 LUALIB_API const char *(luaL_checklstring) (lua_State *L, int numArg,
@@ -71,7 +71,7 @@ LUALIB_API int (luaL_loadstring) (lua_State *L, const char *s); · 31 unmodified lines
7171
7272 LUALIB_API lua_State *(luaL_newstate) (void);
7373
74−LUALIB_API int luaL_len (lua_State *L, int idx);
74+LUALIB_API int (luaL_len) (lua_State *L, int idx);
7575
7676 LUALIB_API const char *(luaL_gsub) (lua_State *L, const char *s, const char *p,
7777 const char *r);
@@ -79,9 +79,8 @@ LUALIB_API const char *(luaL_gsub) (lua_State *L, const char *s, const char *p, · 1 unmodified line
7979 LUALIB_API const char *(luaL_findtable) (lua_State *L, int idx,
8080 const char *fname, int szhint);
8181
82−LUALIB_API void luaL_traceback (lua_State *L, lua_State *L1,
83− const char *msg, int level);
84−
82+LUALIB_API void (luaL_traceback) (lua_State *L, lua_State *L1,
83+ const char *msg, int level);
8584
8685
8786 /*
@@ -111,34 +110,40 @@ LUALIB_API void luaL_traceback (lua_State *L, lua_State *L1, · 23 unmodified lines
111110
112111 #define luaL_opt(L,f,n,d) (lua_isnoneornil(L,(n)) ? (d) : f(L,(n)))
113112
113+#define luaL_register(L,n,l) (luaL_openlib(L,(n),(l),0))
114+
115+
114116 /*
115117 ** {======================================================
116118 ** Generic Buffer manipulation
117119 ** =======================================================
118120 */
119121
120−
121−
122122 typedef struct luaL_Buffer {
123− char *p; /* current position in buffer */
124− int lvl; /* number of strings in the stack (level) */
123+ char *b; /* buffer address */
124+ size_t size; /* buffer size */
125+ size_t n; /* number of characters in buffer */
125126 lua_State *L;
126− char buffer[LUAL_BUFFERSIZE];
127+ char initb[LUAL_BUFFERSIZE]; /* initial buffer */
127128 } luaL_Buffer;
128129
130+
129131 #define luaL_addchar(B,c) \
130− ((void)((B)->p < ((B)->buffer+LUAL_BUFFERSIZE) || luaL_prepbuffer(B)), \
131− (*(B)->p++ = (char)(c)))
132+ ((void)((B)->n < (B)->size || luaL_prepbuffsize((B), 1)), \
133+ ((B)->b[(B)->n++] = (c)))
132134
133−#define luaL_addsize(B,n) ((B)->p += (n))
135+#define luaL_addsize(B,s) ((B)->n += (s))
134136
135137 LUALIB_API void (luaL_buffinit) (lua_State *L, luaL_Buffer *B);
136−LUALIB_API char *(luaL_prepbuffer) (luaL_Buffer *B);
138+LUALIB_API char *(luaL_prepbuffsize) (luaL_Buffer *B, size_t sz);
137139 LUALIB_API void (luaL_addlstring) (luaL_Buffer *B, const char *s, size_t l);
138140 LUALIB_API void (luaL_addstring) (luaL_Buffer *B, const char *s);
139141 LUALIB_API void (luaL_addvalue) (luaL_Buffer *B);
140142 LUALIB_API void (luaL_pushresult) (luaL_Buffer *B);
143+LUALIB_API void (luaL_pushresultsize) (luaL_Buffer *B, size_t sz);
144+LUALIB_API char *(luaL_buffinitsize) (lua_State *L, luaL_Buffer *B, size_t sz);
141145
146+#define luaL_prepbuffer(B) luaL_prepbuffsize(B, LUAL_BUFFERSIZE)
142147
143148 /* }====================================================== */
144149
src/lbaselib.c+27−68
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lbaselib.c,v 1.235 2009/12/28 16:30:31 roberto Exp $
2+** $Id: lbaselib.c,v 1.243 2010/04/19 17:02:02 roberto Exp $
33 ** Basic library
44 ** See Copyright Notice in lua.h
55 */
@@ -23,7 +23,7 @@ · 17 unmodified lines
2323 static int luaB_print (lua_State *L) {
2424 int n = lua_gettop(L); /* number of arguments */
2525 int i;
26− lua_getfield(L, LUA_ENVIRONINDEX, "tostring");
26+ lua_getglobal(L, "tostring");
2727 for (i=1; i<=n; i++) {
2828 const char *s;
2929 size_t l;
@@ -107,50 +107,12 @@ static int luaB_setmetatable (lua_State *L) { · 77 unmodified lines
107107 }
108108
109109
110−
111−#if defined(LUA_COMPAT_FENV)
112−
113−static void getfunc (lua_State *L, int opt) {
114− if (lua_isfunction(L, 1)) lua_pushvalue(L, 1);
115− else {
116− lua_Debug ar;
117− int level = opt ? luaL_optint(L, 1, 1) : luaL_checkint(L, 1);
118− luaL_argcheck(L, level >= 0, 1, "level must be non-negative");
119− if (lua_getstack(L, level, &ar) == 0)
120− luaL_argerror(L, 1, "invalid level");
121− lua_getinfo(L, "f", &ar);
122− }
123−}
124−
125−static int luaB_getfenv (lua_State *L) {
126− getfunc(L, 1);
127− if (lua_iscfunction(L, -1)) /* is a C function? */
128− lua_pushglobaltable(L); /* return the global env. */
129− else
130− lua_getfenv(L, -1);
131− return 1;
132−}
133−
134−static int luaB_setfenv (lua_State *L) {
135− luaL_checktype(L, 2, LUA_TTABLE);
136− getfunc(L, 0);
137− lua_pushvalue(L, 2);
138− if (lua_iscfunction(L, -2) || lua_setfenv(L, -2) == 0)
139− return luaL_error(L,
140− LUA_QL("setfenv") " cannot change environment of given object");
141− return 1;
142−}
143−
144−#else
145−
146110 static int luaB_getfenv (lua_State *L) {
147111 return luaL_error(L, "getfenv/setfenv deprecated");
148112 }
149113
150114 #define luaB_setfenv luaB_getfenv
151115
152−#endif
153−
154116
155117 static int luaB_rawequal (lua_State *L) {
156118 luaL_checkany(L, 1);
@@ -178,18 +140,13 @@ static int luaB_rawset (lua_State *L) { · 21 unmodified lines
178140 }
179141
180142
181−static int luaB_gcinfo (lua_State *L) {
182− lua_pushinteger(L, lua_gc(L, LUA_GCCOUNT, 0));
183− return 1;
184−}
185−
186−
187143 static int luaB_collectgarbage (lua_State *L) {
188144 static const char *const opts[] = {"stop", "restart", "collect",
189− "count", "step", "setpause", "setstepmul", "isrunning", NULL};
145+ "count", "step", "setpause", "setstepmul", "isrunning",
146+ "gen", "inc", NULL};
190147 static const int optsnum[] = {LUA_GCSTOP, LUA_GCRESTART, LUA_GCCOLLECT,
191148 LUA_GCCOUNT, LUA_GCSTEP, LUA_GCSETPAUSE, LUA_GCSETSTEPMUL,
192− LUA_GCISRUNNING};
149+ LUA_GCISRUNNING, LUA_GCGEN, LUA_GCINC};
193150 int o = optsnum[luaL_checkoption(L, 1, "collect", opts)];
194151 int ex = luaL_optint(L, 2, 0);
195152 int res = lua_gc(L, o, ex);
@@ -219,10 +176,11 @@ static int luaB_type (lua_State *L) { · 23 unmodified lines
219176 }
220177
221178
222−static int pairsmeta (lua_State *L, const char *method, int iszero) {
179+static int pairsmeta (lua_State *L, const char *method, int iszero,
180+ lua_CFunction iter) {
223181 if (!luaL_getmetafield(L, 1, method)) { /* no metamethod? */
224182 luaL_checktype(L, 1, LUA_TTABLE); /* argument must be a table */
225− lua_pushvalue(L, lua_upvalueindex(1)); /* will return generator, */
183+ lua_pushcfunction(L, iter); /* will return generator, */
226184 lua_pushvalue(L, 1); /* state, */
227185 if (iszero) lua_pushinteger(L, 0); /* and initial value */
228186 else lua_pushnil(L);
@@ -248,10 +206,12 @@ static int luaB_next (lua_State *L) { · 19 unmodified lines
248206
249207
250208 static int luaB_pairs (lua_State *L) {
251− return pairsmeta(L, "__pairs", 0);
209+ return pairsmeta(L, "__pairs", 0, luaB_next);
252210 }
253211
254212
213+#if defined(LUA_COMPAT_IPAIRS)
214+
255215 static int ipairsaux (lua_State *L) {
256216 int i = luaL_checkint(L, 2);
257217 luaL_checktype(L, 1, LUA_TTABLE);
@@ -263,9 +223,17 @@ static int ipairsaux (lua_State *L) { · 5 unmodified lines
263223
264224
265225 static int luaB_ipairs (lua_State *L) {
266− return pairsmeta(L, "__ipairs", 1);
226+ return pairsmeta(L, "__ipairs", 1, ipairsaux);
227+}
228+
229+#else
230+
231+static int luaB_ipairs (lua_State *L) {
232+ return luaL_error(L, "'ipairs' deprecated");
267233 }
268234
235+#endif
236+
269237
270238 static int load_aux (lua_State *L, int status) {
271239 if (status == LUA_OK)
@@ -376,7 +344,7 @@ static int luaB_loadin (lua_State *L) { · 104 unmodified lines
376344 n = luaB_load_aux(L, 2);
377345 if (n == 1) { /* success? */
378346 lua_pushvalue(L, 1); /* environment for loaded function */
379− lua_setfenv(L, -2);
347+ lua_setupvalue(L, -2, 1);
380348 }
381349 return n;
382350 }
@@ -507,14 +475,15 @@ static const luaL_Reg base_funcs[] = { · 124 unmodified lines
507475 {"collectgarbage", luaB_collectgarbage},
508476 {"dofile", luaB_dofile},
509477 {"error", luaB_error},
510− {"gcinfo", luaB_gcinfo},
511478 {"getfenv", luaB_getfenv},
512479 {"getmetatable", luaB_getmetatable},
480+ {"ipairs", luaB_ipairs},
513481 {"loadfile", luaB_loadfile},
514482 {"load", luaB_load},
515483 {"loadin", luaB_loadin},
516484 {"loadstring", luaB_loadstring},
517485 {"next", luaB_next},
486+ {"pairs", luaB_pairs},
518487 {"pcall", luaB_pcall},
519488 {"print", luaB_print},
520489 {"rawequal", luaB_rawequal},
@@ -668,25 +637,15 @@ static const luaL_Reg co_funcs[] = { · 147 unmodified lines
668637 /* }====================================================== */
669638
670639
671−static void auxopen (lua_State *L, const char *name,
672− lua_CFunction f, lua_CFunction u) {
673− lua_pushcfunction(L, u);
674− lua_pushcclosure(L, f, 1);
675− lua_setfield(L, -2, name);
676−}
677−
678−
679640 static void base_open (lua_State *L) {
680641 /* set global _G */
681642 lua_pushglobaltable(L);
682− lua_setfield(L, LUA_ENVIRONINDEX, "_G");
643+ lua_pushglobaltable(L);
644+ lua_setfield(L, -2, "_G");
683645 /* open lib into global table */
684646 luaL_register(L, "_G", base_funcs);
685647 lua_pushliteral(L, LUA_VERSION);
686− lua_setfield(L, LUA_ENVIRONINDEX, "_VERSION"); /* set global _VERSION */
687− /* `ipairs' and `pairs' need auxiliary functions as upvalues */
688− auxopen(L, "ipairs", luaB_ipairs, ipairsaux);
689− auxopen(L, "pairs", luaB_pairs, luaB_next);
648+ lua_setfield(L, -2, "_VERSION"); /* set global _VERSION */
690649 /* `newproxy' needs a weaktable as upvalue */
691650 lua_createtable(L, 0, 1); /* new table `w' */
692651 lua_pushvalue(L, -1); /* `w' will be its own metatable */
@@ -694,7 +653,7 @@ static void base_open (lua_State *L) { · 1 unmodified line
694653 lua_pushliteral(L, "kv");
695654 lua_setfield(L, -2, "__mode"); /* metatable(w).__mode = "kv" */
696655 lua_pushcclosure(L, luaB_newproxy, 1);
697− lua_setfield(L, LUA_ENVIRONINDEX, "newproxy"); /* set global `newproxy' */
656+ lua_setfield(L, -2, "newproxy"); /* set global `newproxy' */
698657 }
699658
700659
src/lbitlib.c+27−7
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lbitlib.c,v 1.3 2010/01/12 19:40:02 roberto Exp $
2+** $Id: lbitlib.c,v 1.4 2010/02/11 15:55:29 roberto Exp $
33 ** Standard library for bitwise operations
44 ** See Copyright Notice in lua.h
55 */
@@ -80,9 +80,8 @@ static int b_not (lua_State *L) { · 74 unmodified lines
8080 }
8181
8282
83−static int b_shift (lua_State *L) {
83+static int b_shift (lua_State *L, int i) {
8484 b_uint r = getuintarg(L, 1);
85− lua_Integer i = luaL_checkinteger(L, 2);
8685 if (i < 0) { /* shift right? */
8786 i = -i;
8887 if (i >= NBITS) r = 0;
@@ -97,9 +96,18 @@ static int b_shift (lua_State *L) { · 8 unmodified lines
9796 }
9897
9998
100−static int b_rotate (lua_State *L) {
99+static int b_lshift (lua_State *L) {
100+ return b_shift(L, luaL_checkint(L, 2));
101+}
102+
103+
104+static int b_rshift (lua_State *L) {
105+ return b_shift(L, -luaL_checkint(L, 2));
106+}
107+
108+
109+static int b_rot (lua_State *L, int i) {
101110 b_uint r = getuintarg(L, 1);
102− lua_Integer i = luaL_checkinteger(L, 2);
103111 i &= (NBITS - 1); /* i = i % NBITS */
104112 r = (r << i) | (r >> (NBITS - i));
105113 lua_pushnumber(L, lua_uint2number(r));
@@ -107,14 +115,26 @@ static int b_rotate (lua_State *L) { · 1 unmodified line
107115 }
108116
109117
118+static int b_rol (lua_State *L) {
119+ return b_rot(L, luaL_checkint(L, 2));
120+}
121+
122+
123+static int b_ror (lua_State *L) {
124+ return b_rot(L, -luaL_checkint(L, 2));
125+}
126+
127+
110128 static const luaL_Reg bitlib[] = {
111129 {"band", b_and},
112130 {"btest", b_test},
113131 {"bor", b_or},
114132 {"bxor", b_xor},
115133 {"bnot", b_not},
116− {"bshift", b_shift},
117− {"brotate", b_rotate},
134+ {"lshift", b_lshift},
135+ {"rshift", b_rshift},
136+ {"rol", b_rol},
137+ {"ror", b_ror},
118138 {NULL, NULL}
119139 };
120140
src/lcode.c+31−20
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lcode.c,v 2.43 2010/01/11 17:38:30 roberto Exp $
2+** $Id: lcode.c,v 2.46 2010/04/17 12:46:32 roberto Exp $
33 ** Code generator for Lua
44 ** See Copyright Notice in lua.h
55 */
@@ -372,11 +372,6 @@ void luaK_dischargevars (FuncState *fs, expdesc *e) { · 366 unmodified lines
372372 e->k = VRELOCABLE;
373373 break;
374374 }
375− case VGLOBAL: {
376− e->u.s.info = luaK_codeABxX(fs, OP_GETGLOBAL, 0, e->u.s.info);
377− e->k = VRELOCABLE;
378− break;
379− }
380375 case VINDEXED: {
381376 freereg(fs, e->u.s.aux);
382377 freereg(fs, e->u.s.info);
@@ -384,6 +379,12 @@ void luaK_dischargevars (FuncState *fs, expdesc *e) { · 1 unmodified line
384379 e->k = VRELOCABLE;
385380 break;
386381 }
382+ case VINDEXEDUP: {
383+ freereg(fs, e->u.s.aux);
384+ e->u.s.info = luaK_codeABC(fs, OP_GETTABUP, 0, e->u.s.info, e->u.s.aux);
385+ e->k = VRELOCABLE;
386+ break;
387+ }
387388 case VVARARG:
388389 case VCALL: {
389390 luaK_setoneret(fs, e);
@@ -493,6 +494,12 @@ int luaK_exp2anyreg (FuncState *fs, expdesc *e) { · 103 unmodified lines
493494 }
494495
495496
497+void luaK_exp2anyregup (FuncState *fs, expdesc *e) {
498+ if (e->k != VUPVAL || hasjumps(e))
499+ luaK_exp2anyreg(fs, e);
500+}
501+
502+
496503 void luaK_exp2val (FuncState *fs, expdesc *e) {
497504 if (hasjumps(e))
498505 luaK_exp2anyreg(fs, e);
@@ -543,16 +550,16 @@ void luaK_storevar (FuncState *fs, expdesc *var, expdesc *ex) { · 44 unmodified lines
543550 luaK_codeABC(fs, OP_SETUPVAL, e, var->u.s.info, 0);
544551 break;
545552 }
546− case VGLOBAL: {
547− int e = luaK_exp2anyreg(fs, ex);
548− luaK_codeABxX(fs, OP_SETGLOBAL, e, var->u.s.info);
549− break;
550− }
551553 case VINDEXED: {
552554 int e = luaK_exp2RK(fs, ex);
553555 luaK_codeABC(fs, OP_SETTABLE, var->u.s.info, var->u.s.aux, e);
554556 break;
555557 }
558+ case VINDEXEDUP: {
559+ int e = luaK_exp2RK(fs, ex);
560+ luaK_codeABC(fs, OP_SETTABUP, var->u.s.info, var->u.s.aux, e);
561+ break;
562+ }
556563 default: {
557564 lua_assert(0); /* invalid var kind to store */
558565 break;
@@ -567,9 +574,9 @@ void luaK_self (FuncState *fs, expdesc *e, expdesc *key) { · 8 unmodified lines
567574 luaK_exp2anyreg(fs, e);
568575 freeexp(fs, e);
569576 func = fs->freereg;
570− luaK_reserveregs(fs, 2);
571577 luaK_codeABC(fs, OP_SELF, func, e->u.s.info, luaK_exp2RK(fs, key));
572578 freeexp(fs, key);
579+ luaK_reserveregs(fs, 2);
573580 e->u.s.info = func;
574581 e->k = VNONRELOC;
575582 }
@@ -695,8 +702,9 @@ static void codenot (FuncState *fs, expdesc *e) { · 119 unmodified lines
695702
696703
697704 void luaK_indexed (FuncState *fs, expdesc *t, expdesc *k) {
705+ lua_assert(!hasjumps(t));
698706 t->u.s.aux = luaK_exp2RK(fs, k);
699− t->k = VINDEXED;
707+ t->k = (t->k == VUPVAL) ? VINDEXEDUP : VINDEXED;
700708 }
701709
702710
@@ -711,7 +719,8 @@ static int constfolding (OpCode op, expdesc *e1, expdesc *e2) { · 8 unmodified lines
711719 }
712720
713721
714−static void codearith (FuncState *fs, OpCode op, expdesc *e1, expdesc *e2) {
722+static void codearith (FuncState *fs, OpCode op,
723+ expdesc *e1, expdesc *e2, int line) {
715724 if (constfolding(op, e1, e2))
716725 return;
717726 else {
@@ -727,6 +736,7 @@ static void codearith (FuncState *fs, OpCode op, expdesc *e1, expdesc *e2) { · 9 unmodified lines
727736 }
728737 e1->u.s.info = luaK_codeABC(fs, op, 0, o1, o2);
729738 e1->k = VRELOCABLE;
739+ luaK_fixline(fs, line);
730740 }
731741 }
732742
@@ -747,7 +757,7 @@ static void codecomp (FuncState *fs, OpCode op, int cond, expdesc *e1, · 14 unmodified lines
747757 }
748758
749759
750−void luaK_prefix (FuncState *fs, UnOpr op, expdesc *e) {
760+void luaK_prefix (FuncState *fs, UnOpr op, expdesc *e, int line) {
751761 expdesc e2;
752762 e2.t = e2.f = NO_JUMP; e2.k = VKNUM; e2.u.nval = 0;
753763 switch (op) {
@@ -756,14 +766,14 @@ void luaK_prefix (FuncState *fs, UnOpr op, expdesc *e) { · 2 unmodified lines
756766 e->u.nval = luai_numunm(NULL, e->u.nval); /* fold it */
757767 else {
758768 luaK_exp2anyreg(fs, e);
759− codearith(fs, OP_UNM, e, &e2);
769+ codearith(fs, OP_UNM, e, &e2, line);
760770 }
761771 break;
762772 }
763773 case OPR_NOT: codenot(fs, e); break;
764774 case OPR_LEN: {
765775 luaK_exp2anyreg(fs, e); /* cannot operate on constants */
766− codearith(fs, OP_LEN, e, &e2);
776+ codearith(fs, OP_LEN, e, &e2, line);
767777 break;
768778 }
769779 default: lua_assert(0);
@@ -798,7 +808,8 @@ void luaK_infix (FuncState *fs, BinOpr op, expdesc *v) { · 28 unmodified lines
798808 }
799809
800810
801−void luaK_posfix (FuncState *fs, BinOpr op, expdesc *e1, expdesc *e2) {
811+void luaK_posfix (FuncState *fs, BinOpr op,
812+ expdesc *e1, expdesc *e2, int line) {
802813 switch (op) {
803814 case OPR_AND: {
804815 lua_assert(e1->t == NO_JUMP); /* list must be closed */
@@ -824,13 +835,13 @@ void luaK_posfix (FuncState *fs, BinOpr op, expdesc *e1, expdesc *e2) { · 19 unmodified lines
824835 }
825836 else {
826837 luaK_exp2nextreg(fs, e2); /* operand must be on the 'stack' */
827− codearith(fs, OP_CONCAT, e1, e2);
838+ codearith(fs, OP_CONCAT, e1, e2, line);
828839 }
829840 break;
830841 }
831842 case OPR_ADD: case OPR_SUB: case OPR_MUL: case OPR_DIV:
832843 case OPR_MOD: case OPR_POW: {
833− codearith(fs, cast(OpCode, op - OPR_ADD + OP_ADD), e1, e2);
844+ codearith(fs, cast(OpCode, op - OPR_ADD + OP_ADD), e1, e2, line);
834845 break;
835846 }
836847 case OPR_EQ: case OPR_LT: case OPR_LE: {
src/lcode.h+5−3
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lcode.h,v 1.52 2009/09/23 20:33:05 roberto Exp $
2+** $Id: lcode.h,v 1.54 2010/04/17 12:46:32 roberto Exp $
33 ** Code generator for Lua
44 ** See Copyright Notice in lua.h
55 */
@@ -57,6 +57,7 @@ LUAI_FUNC int luaK_stringK (FuncState *fs, TString *s); · 51 unmodified lines
5757 LUAI_FUNC int luaK_numberK (FuncState *fs, lua_Number r);
5858 LUAI_FUNC void luaK_dischargevars (FuncState *fs, expdesc *e);
5959 LUAI_FUNC int luaK_exp2anyreg (FuncState *fs, expdesc *e);
60+LUAI_FUNC void luaK_exp2anyregup (FuncState *fs, expdesc *e);
6061 LUAI_FUNC void luaK_exp2nextreg (FuncState *fs, expdesc *e);
6162 LUAI_FUNC void luaK_exp2val (FuncState *fs, expdesc *e);
6263 LUAI_FUNC int luaK_exp2RK (FuncState *fs, expdesc *e);
@@ -72,9 +73,10 @@ LUAI_FUNC void luaK_patchlist (FuncState *fs, int list, int target); · 9 unmodified lines
7273 LUAI_FUNC void luaK_patchtohere (FuncState *fs, int list);
7374 LUAI_FUNC void luaK_concat (FuncState *fs, int *l1, int l2);
7475 LUAI_FUNC int luaK_getlabel (FuncState *fs);
75−LUAI_FUNC void luaK_prefix (FuncState *fs, UnOpr op, expdesc *v);
76+LUAI_FUNC void luaK_prefix (FuncState *fs, UnOpr op, expdesc *v, int line);
7677 LUAI_FUNC void luaK_infix (FuncState *fs, BinOpr op, expdesc *v);
77−LUAI_FUNC void luaK_posfix (FuncState *fs, BinOpr op, expdesc *v1, expdesc *v2);
78+LUAI_FUNC void luaK_posfix (FuncState *fs, BinOpr op, expdesc *v1,
79+ expdesc *v2, int line);
7880 LUAI_FUNC void luaK_setlist (FuncState *fs, int base, int nelems, int tostore);
7981
8082
src/ldblib.c+14−16
@@ -1,5 +1,5 @@
11 /*
2−** $Id: ldblib.c,v 1.119 2010/01/06 14:42:35 roberto Exp $
2+** $Id: ldblib.c,v 1.121 2010/03/26 20:58:11 roberto Exp $
33 ** Interface from Lua to its debug API
44 ** See Copyright Notice in lua.h
55 */
@@ -44,19 +44,19 @@ static int db_setmetatable (lua_State *L) { · 38 unmodified lines
4444 }
4545
4646
47−static int db_getfenv (lua_State *L) {
48− luaL_checkany(L, 1);
49− lua_getfenv(L, 1);
47+static int db_getenv (lua_State *L) {
48+ luaL_checktype(L, 1, LUA_TUSERDATA);
49+ lua_getenv(L, 1);
5050 return 1;
5151 }
5252
5353
54−static int db_setfenv (lua_State *L) {
55− luaL_checktype(L, 2, LUA_TTABLE);
54+static int db_setenv (lua_State *L) {
55+ luaL_checktype(L, 1, LUA_TUSERDATA);
56+ if (!lua_isnoneornil(L, 2))
57+ luaL_checktype(L, 2, LUA_TTABLE);
5658 lua_settop(L, 2);
57− if (lua_setfenv(L, 1) == 0)
58− luaL_error(L, LUA_QL("setfenv")
59− " cannot change environment of given object");
59+ lua_setenv(L, 1);
6060 return 1;
6161 }
6262
@@ -339,15 +339,13 @@ static int db_gethook (lua_State *L) { · 276 unmodified lines
339339 static int db_debug (lua_State *L) {
340340 for (;;) {
341341 char buffer[250];
342− fputs("lua_debug> ", stderr);
342+ luai_writestringerror("%s", "lua_debug> ");
343343 if (fgets(buffer, sizeof(buffer), stdin) == 0 ||
344344 strcmp(buffer, "cont\n") == 0)
345345 return 0;
346346 if (luaL_loadbuffer(L, buffer, strlen(buffer), "=(debug command)") ||
347− lua_pcall(L, 0, 0, 0)) {
348− fputs(lua_tostring(L, -1), stderr);
349− fputs("\n", stderr);
350− }
347+ lua_pcall(L, 0, 0, 0))
348+ luai_writestringerror("%s\n", lua_tostring(L, -1));
351349 lua_settop(L, 0); /* remove eventual returns */
352350 }
353351 }
@@ -369,7 +367,7 @@ static int db_traceback (lua_State *L) { · 15 unmodified lines
369367
370368 static const luaL_Reg dblib[] = {
371369 {"debug", db_debug},
372− {"getfenv", db_getfenv},
370+ {"getenv", db_getenv},
373371 {"gethook", db_gethook},
374372 {"getinfo", db_getinfo},
375373 {"getlocal", db_getlocal},
@@ -378,7 +376,7 @@ static const luaL_Reg dblib[] = { · 2 unmodified lines
378376 {"getupvalue", db_getupvalue},
379377 {"upvaluejoin", db_upvaluejoin},
380378 {"upvalueid", db_upvalueid},
381− {"setfenv", db_setfenv},
379+ {"setenv", db_setenv},
382380 {"sethook", db_sethook},
383381 {"setlocal", db_setlocal},
384382 {"setmetatable", db_setmetatable},
src/ldebug.c+72−44
@@ -1,5 +1,5 @@
11 /*
2−** $Id: ldebug.c,v 2.63 2010/01/13 16:18:25 roberto Exp $
2+** $Id: ldebug.c,v 2.70 2010/04/13 20:48:12 roberto Exp $
33 ** Debug Interface
44 ** See Copyright Notice in lua.h
55 */
@@ -144,7 +144,7 @@ LUA_API const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n) { · 138 unmodified lines
144144
145145
146146 static void funcinfo (lua_Debug *ar, Closure *cl) {
147− if (cl->c.isC) {
147+ if (cl == NULL || cl->c.isC) {
148148 ar->source = "=[C]";
149149 ar->linedefined = -1;
150150 ar->lastlinedefined = -1;
@@ -191,8 +191,8 @@ static int auxgetinfo (lua_State *L, const char *what, lua_Debug *ar, · 40 unmodified lines
191191 break;
192192 }
193193 case 'u': {
194− ar->nups = f->c.nupvalues;
195− if (f->c.isC) {
194+ ar->nups = (f == NULL) ? 0 : f->c.nupvalues;
195+ if (f == NULL || f->c.isC) {
196196 ar->isvararg = 1;
197197 ar->nparams = 0;
198198 }
@@ -226,28 +226,30 @@ static int auxgetinfo (lua_State *L, const char *what, lua_Debug *ar, · 27 unmodified lines
226226
227227 LUA_API int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar) {
228228 int status;
229− Closure *f = NULL;
230− CallInfo *ci = NULL;
229+ Closure *cl;
230+ CallInfo *ci;
231+ StkId func;
231232 lua_lock(L);
232233 if (*what == '>') {
233− StkId func = L->top - 1;
234+ ci = NULL;
235+ func = L->top - 1;
234236 luai_apicheck(L, ttisfunction(func));
235237 what++; /* skip the '>' */
236− f = clvalue(func);
237238 L->top--; /* pop function */
238239 }
239240 else {
240241 ci = ar->i_ci;
242+ func = ci->func;
241243 lua_assert(ttisfunction(ci->func));
242− f = clvalue(ci->func);
243244 }
244− status = auxgetinfo(L, what, ar, f, ci);
245+ cl = ttisclosure(func) ? clvalue(func) : NULL;
246+ status = auxgetinfo(L, what, ar, cl, ci);
245247 if (strchr(what, 'f')) {
246− setclvalue(L, L->top, f);
248+ setobjs2s(L, L->top, func);
247249 incr_top(L);
248250 }
249251 if (strchr(what, 'L'))
250− collectvalidlines(L, f);
252+ collectvalidlines(L, cl);
251253 lua_unlock(L);
252254 return status;
253255 }
@@ -260,22 +262,23 @@ LUA_API int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar) { · 6 unmodified lines
260262 */
261263
262264
263−static const char *kname (Proto *p, int c) {
264− if (ISK(c) && ttisstring(&p->k[INDEXK(c)]))
265− return svalue(&p->k[INDEXK(c)]);
265+static void kname (Proto *p, int c, int reg, const char *what,
266+ const char **name) {
267+ if (c == reg && *what == 'c')
268+ return; /* index is a constant; name already correct */
269+ else if (ISK(c) && ttisstring(&p->k[INDEXK(c)]))
270+ *name = svalue(&p->k[INDEXK(c)]);
266271 else
267− return "?";
272+ *name = "?";
268273 }
269274
270275
271276 static const char *getobjname (lua_State *L, CallInfo *ci, int reg,
272277 const char **name) {
273− Proto *p;
274− int lastpc, pc;
278+ Proto *p = ci_func(ci)->l.p;
275279 const char *what = NULL;
276− lua_assert(isLua(ci));
277− p = ci_func(ci)->l.p;
278− lastpc = currentpc(ci);
280+ int lastpc = currentpc(ci);
281+ int pc;
279282 *name = luaF_getlocalname(p, reg + 1, lastpc);
280283 if (*name) /* is a local? */
281284 return "local";
@@ -285,17 +288,6 @@ static const char *getobjname (lua_State *L, CallInfo *ci, int reg, · 3 unmodified lines
285288 OpCode op = GET_OPCODE(i);
286289 int a = GETARG_A(i);
287290 switch (op) {
288− case OP_GETGLOBAL: {
289− if (reg == a) {
290− int g = GETARG_Bx(i);
291− if (g != 0) g--;
292− else g = GETARG_Ax(p->code[++pc]);
293− lua_assert(ttisstring(&p->k[g]));
294− *name = svalue(&p->k[g]);
295− what = "global";
296− }
297− break;
298− }
299291 case OP_MOVE: {
300292 if (reg == a) {
301293 int b = GETARG_B(i); /* move from 'b' to 'a' */
@@ -305,11 +297,16 @@ static const char *getobjname (lua_State *L, CallInfo *ci, int reg, · 3 unmodified lines
305297 }
306298 break;
307299 }
300+ case OP_GETTABUP:
308301 case OP_GETTABLE: {
309302 if (reg == a) {
310303 int k = GETARG_C(i); /* key index */
311− *name = kname(p, k);
312− what = "field";
304+ int t = GETARG_B(i);
305+ const char *vn = (op == OP_GETTABLE) /* name of indexed variable */
306+ ? luaF_getlocalname(p, t + 1, pc)
307+ : getstr(p->upvalues[t].name);
308+ kname(p, k, a, what, name);
309+ what = (vn && strcmp(vn, "_ENV") == 0) ? "global" : "field";
313310 }
314311 break;
315312 }
@@ -322,6 +319,17 @@ static const char *getobjname (lua_State *L, CallInfo *ci, int reg, · 6 unmodified lines
322319 }
323320 break;
324321 }
322+ case OP_LOADK: {
323+ if (reg == a) {
324+ int b = GETARG_Bx(i);
325+ b = (b > 0) ? b - 1 : GETARG_Ax(p->code[pc + 1]);
326+ if (ttisstring(&p->k[b])) {
327+ what = "constant";
328+ *name = svalue(&p->k[b]);
329+ }
330+ }
331+ break;
332+ }
325333 case OP_LOADNIL: {
326334 int b = GETARG_B(i); /* move from 'b' to 'a' */
327335 if (a <= reg && reg <= b) /* set registers from 'a' to 'b' */
@@ -331,7 +339,7 @@ static const char *getobjname (lua_State *L, CallInfo *ci, int reg, · 3 unmodified lines
331339 case OP_SELF: {
332340 if (reg == a) {
333341 int k = GETARG_C(i); /* key index */
334− *name = kname(p, k);
342+ kname(p, k, a, what, name);
335343 what = "method";
336344 }
337345 break;
@@ -374,12 +382,15 @@ static const char *getfuncname (lua_State *L, CallInfo *ci, const char **name) { · 36 unmodified lines
374382 switch (GET_OPCODE(i)) {
375383 case OP_CALL:
376384 case OP_TAILCALL:
377− case OP_TFORLOOP:
378385 return getobjname(L, ci, GETARG_A(i), name);
379− case OP_GETGLOBAL:
386+ case OP_TFORCALL: {
387+ *name = "for iterator";
388+ return "for iterator";
389+ }
380390 case OP_SELF:
391+ case OP_GETTABUP:
381392 case OP_GETTABLE: tm = TM_INDEX; break;
382− case OP_SETGLOBAL:
393+ case OP_SETTABUP:
383394 case OP_SETTABLE: tm = TM_NEWINDEX; break;
384395 case OP_EQ: tm = TM_EQ; break;
385396 case OP_ADD: tm = TM_ADD; break;
@@ -413,13 +424,30 @@ static int isinstack (CallInfo *ci, const TValue *o) { · 27 unmodified lines
413424 }
414425
415426
427+static const char *getupvalname (CallInfo *ci, const TValue *o,
428+ const char **name) {
429+ LClosure *c = &ci_func(ci)->l;
430+ int i;
431+ for (i = 0; i < c->nupvalues; i++) {
432+ if (c->upvals[i]->v == o) {
433+ *name = getstr(c->p->upvalues[i].name);
434+ return "upvalue";
435+ }
436+ }
437+ return NULL;
438+}
439+
440+
416441 void luaG_typeerror (lua_State *L, const TValue *o, const char *op) {
417442 CallInfo *ci = L->ci;
418443 const char *name = NULL;
419− const char *t = typename(ttype(o));
420− const char *kind = (isLua(ci) && isinstack(ci, o)) ?
421− getobjname(L, ci, cast_int(o - ci->u.l.base), &name) :
422− NULL;
444+ const char *t = objtypename(o);
445+ const char *kind = NULL;
446+ if (isLua(ci)) {
447+ kind = getupvalname(ci, o, &name); /* check whether 'o' is an upvalue */
448+ if (!kind && isinstack(ci, o)) /* no? try a register */
449+ kind = getobjname(L, ci, cast_int(o - ci->u.l.base), &name);
450+ }
423451 if (kind)
424452 luaG_runerror(L, "attempt to %s %s " LUA_QS " (a %s value)",
425453 op, kind, name, t);
@@ -444,8 +472,8 @@ void luaG_aritherror (lua_State *L, const TValue *p1, const TValue *p2) { · 18 unmodified lines
444472
445473
446474 int luaG_ordererror (lua_State *L, const TValue *p1, const TValue *p2) {
447− const char *t1 = typename(ttype(p1));
448− const char *t2 = typename(ttype(p2));
475+ const char *t1 = objtypename(p1);
476+ const char *t2 = objtypename(p2);
449477 if (t1 == t2)
450478 luaG_runerror(L, "attempt to compare two %s values", t1);
451479 else
src/ldo.c+41−34
@@ -1,5 +1,5 @@
11 /*
2−** $Id: ldo.c,v 2.80 2010/01/13 16:17:32 roberto Exp $
2+** $Id: ldo.c,v 2.87 2010/05/05 18:49:56 roberto Exp $
33 ** Stack and Call structure of Lua
44 ** See Copyright Notice in lua.h
55 */
@@ -48,7 +48,7 @@ · 42 unmodified lines
4848 */
4949 #if !defined(LUAI_THROW)
5050
51−#if defined(__cplusplus)
51+#if defined(__cplusplus) && !defined(LUA_USE_LONGJMP)
5252 /* C++ exceptions */
5353 #define LUAI_THROW(L,c) throw(c)
5454 #define LUAI_TRY(L,c,a) \
@@ -83,8 +83,8 @@ struct lua_longjmp { · 28 unmodified lines
8383
8484 static void seterrorobj (lua_State *L, int errcode, StkId oldtop) {
8585 switch (errcode) {
86− case LUA_ERRMEM: {
87− setsvalue2s(L, oldtop, luaS_newliteral(L, MEMERRMSG));
86+ case LUA_ERRMEM: { /* memory error? */
87+ setsvalue2s(L, oldtop, G(L)->memerrmsg); /* reuse preregistered msg. */
8888 break;
8989 }
9090 case LUA_ERRERR: {
@@ -293,18 +293,43 @@ static StkId tryfuncTM (lua_State *L, StkId func) { · 202 unmodified lines
293293 ** returns true if function has been executed (C function)
294294 */
295295 int luaD_precall (lua_State *L, StkId func, int nresults) {
296− LClosure *cl;
296+ Closure *cl;
297+ lua_CFunction f;
297298 ptrdiff_t funcr;
298299 if (!ttisfunction(func)) /* `func' is not a function? */
299300 func = tryfuncTM(L, func); /* check the `function' tag method */
300301 funcr = savestack(L, func);
301− cl = &clvalue(func)->l;
302302 L->ci->nresults = nresults;
303− if (!cl->isC) { /* Lua function? prepare its call */
303+ if (ttislcf(func)) { /* light C function? */
304+ f = fvalue(func); /* get it */
305+ goto isCfunc; /* go to call it */
306+ }
307+ cl = clvalue(func);
308+ if (cl->c.isC) { /* C closure? */
309+ CallInfo *ci;
310+ int n;
311+ f = cl->c.f;
312+ isCfunc: /* call C function 'f' */
313+ luaD_checkstack(L, LUA_MINSTACK); /* ensure minimum stack size */
314+ ci = next_ci(L); /* now 'enter' new function */
315+ ci->func = restorestack(L, funcr);
316+ ci->top = L->top + LUA_MINSTACK;
317+ lua_assert(ci->top <= L->stack_last);
318+ ci->callstatus = 0;
319+ if (L->hookmask & LUA_MASKCALL)
320+ luaD_hook(L, LUA_HOOKCALL, -1);
321+ lua_unlock(L);
322+ n = (*f)(L); /* do the actual call */
323+ lua_lock(L);
324+ api_checknelems(L, n);
325+ luaD_poscall(L, L->top - n);
326+ return 1;
327+ }
328+ else { /* Lua function: prepare its call */
304329 CallInfo *ci;
305330 int nparams, nargs;
306331 StkId base;
307− Proto *p = cl->p;
332+ Proto *p = cl->l.p;
308333 luaD_checkstack(L, p->maxstacksize);
309334 func = restorestack(L, funcr);
310335 nargs = cast_int(L->top - func) - 1; /* number of real arguments */
@@ -327,24 +352,6 @@ int luaD_precall (lua_State *L, StkId func, int nresults) { · 16 unmodified lines
327352 callhook(L, ci);
328353 return 0;
329354 }
330− else { /* if is a C function, call it */
331− CallInfo *ci;
332− int n;
333− luaD_checkstack(L, LUA_MINSTACK); /* ensure minimum stack size */
334− ci = next_ci(L); /* now 'enter' new function */
335− ci->func = restorestack(L, funcr);
336− ci->top = L->top + LUA_MINSTACK;
337− lua_assert(ci->top <= L->stack_last);
338− ci->callstatus = 0;
339− if (L->hookmask & LUA_MASKCALL)
340− luaD_hook(L, LUA_HOOKCALL, -1);
341− lua_unlock(L);
342− n = (*curr_func(L)->c.f)(L); /* do the actual call */
343− lua_lock(L);
344− api_checknelems(L, n);
345− luaD_poscall(L, L->top - n);
346− return 1;
347− }
348355 }
349356
350357
@@ -452,7 +459,7 @@ static int recover (lua_State *L, int status) { · 101 unmodified lines
452459 CallInfo *ci = findpcall(L);
453460 if (ci == NULL) return 0; /* no recovery point */
454461 /* "finish" luaD_pcall */
455− oldtop = restorestack(L, ci->u.c.oldtop);
462+ oldtop = restorestack(L, ci->u.c.extra);
456463 luaF_close(L, oldtop);
457464 seterrorobj(L, status, oldtop);
458465 L->ci = ci;
@@ -469,7 +476,7 @@ static int recover (lua_State *L, int status) { · 10 unmodified lines
469476 /*
470477 ** signal an error in the call to 'resume', not in the execution of the
471478 ** coroutine itself. (Such errors should not be handled by any coroutine
472−** error hanlder and should not kill the coroutine.)
479+** error handler and should not kill the coroutine.)
473480 */
474481 static void resume_error (lua_State *L, const char *msg, StkId firstArg) {
475482 L->top = firstArg; /* remove args from the stack */
@@ -501,11 +508,11 @@ static void resume (lua_State *L, void *ud) { · 25 unmodified lines
501508 if (isLua(ci)) /* yielded inside a hook? */
502509 luaV_execute(L); /* just continue running Lua code */
503510 else { /* 'common' yield */
511+ ci->func = restorestack(L, ci->u.c.extra);
504512 if (ci->u.c.k != NULL) { /* does it have a continuation? */
505513 int n;
506514 ci->u.c.status = LUA_YIELD; /* 'default' status */
507515 ci->callstatus |= CIST_YIELDED;
508− ci->func = restorestack(L, ci->u.c.oldtop);
509516 lua_unlock(L);
510517 n = (*ci->u.c.k)(L); /* call continuation */
511518 lua_lock(L);
@@ -526,6 +533,7 @@ LUA_API int lua_resume (lua_State *L, int nargs) { · 14 unmodified lines
526533 luai_userstateresume(L, nargs);
527534 ++G(L)->nCcalls; /* count resume */
528535 L->nny = 0; /* allow yields */
536+ api_checknelems(L, (L->status == LUA_OK) ? nargs + 1 : nargs);
529537 status = luaD_rawrunprotected(L, resume, L->top - nargs);
530538 if (status == -1) /* error calling 'lua_resume'? */
531539 status = LUA_ERRRUN;
@@ -565,11 +573,10 @@ LUA_API int lua_yieldk (lua_State *L, int nresults, int ctx, lua_CFunction k) { · 33 unmodified lines
565573 api_check(L, k == NULL, "hooks cannot continue after yielding");
566574 }
567575 else {
568− if ((ci->u.c.k = k) != NULL) { /* is there a continuation? */
576+ if ((ci->u.c.k = k) != NULL) /* is there a continuation? */
569577 ci->u.c.ctx = ctx; /* save context */
570− ci->u.c.oldtop = savestack(L, ci->func); /* save current 'func' */
571− }
572− ci->func = L->top - nresults - 1; /* protect stack slots below */
578+ ci->u.c.extra = savestack(L, ci->func); /* save current 'func' */
579+ ci->func = L->top - nresults - 1; /* protect stack below results */
573580 luaD_throw(L, LUA_YIELD);
574581 }
575582 lua_assert(ci->callstatus & CIST_HOOKED); /* must be inside a hook */
@@ -623,7 +630,7 @@ static void f_parser (lua_State *L, void *ud) { · 47 unmodified lines
623630 : luaY_parser(L, p->z, &p->buff, &p->varl, p->name);
624631 setptvalue2s(L, L->top, tf);
625632 incr_top(L);
626− cl = luaF_newLclosure(L, tf->sizeupvalues, G(L)->l_gt);
633+ cl = luaF_newLclosure(L, tf->sizeupvalues);
627634 cl->l.p = tf;
628635 setclvalue(L, L->top - 1, cl);
629636 for (i = 0; i < tf->sizeupvalues; i++) /* initialize upvalues */
src/ldump.c+1−2
@@ -1,5 +1,5 @@
11 /*
2−** $Id: ldump.c,v 2.12 2009/09/30 15:38:37 roberto Exp $
2+** $Id: ldump.c,v 2.13 2010/03/12 19:14:06 roberto Exp $
33 ** save precompiled Lua chunks
44 ** See Copyright Notice in lua.h
55 */
@@ -145,7 +145,6 @@ static void DumpFunction(const Proto* f, const TString* p, DumpState* D) · 139 unmodified lines
145145 DumpChar(f->numparams,D);
146146 DumpChar(f->is_vararg,D);
147147 DumpChar(f->maxstacksize,D);
148− DumpChar(f->envreg,D);
149148 DumpCode(f,D);
150149 DumpConstants(f,D);
151150 DumpUpvalues(f,D);
src/lfunc.c+12−11
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lfunc.c,v 2.19 2009/12/16 16:42:58 roberto Exp $
2+** $Id: lfunc.c,v 2.24 2010/05/10 18:23:45 roberto Exp $
33 ** Auxiliary functions to manipulate prototypes and closures
44 ** See Copyright Notice in lua.h
55 */
@@ -21,19 +21,17 @@ · 15 unmodified lines
2121
2222
2323
24−Closure *luaF_newCclosure (lua_State *L, int n, Table *e) {
24+Closure *luaF_newCclosure (lua_State *L, int n) {
2525 Closure *c = &luaC_newobj(L, LUA_TFUNCTION, sizeCclosure(n), NULL, 0)->cl;
2626 c->c.isC = 1;
27− c->c.env = e;
2827 c->c.nupvalues = cast_byte(n);
2928 return c;
3029 }
3130
3231
33−Closure *luaF_newLclosure (lua_State *L, int n, Table *e) {
32+Closure *luaF_newLclosure (lua_State *L, int n) {
3433 Closure *c = &luaC_newobj(L, LUA_TFUNCTION, sizeLclosure(n), NULL, 0)->cl;
3534 c->l.isC = 0;
36− c->l.env = e;
3735 c->l.nupvalues = cast_byte(n);
3836 while (n--) c->l.upvals[n] = NULL;
3937 return c;
@@ -54,12 +52,14 @@ UpVal *luaF_findupval (lua_State *L, StkId level) { · 14 unmodified lines
5452 UpVal *p;
5553 UpVal *uv;
5654 while (*pp != NULL && (p = gco2uv(*pp))->v >= level) {
55+ GCObject *o = obj2gco(p);
5756 lua_assert(p->v != &p->u.value);
5857 if (p->v == level) { /* found a corresponding upvalue? */
59− if (isdead(g, obj2gco(p))) /* is it dead? */
60− changewhite(obj2gco(p)); /* ressurrect it */
58+ if (isdead(g, o)) /* is it dead? */
59+ changewhite(o); /* ressurrect it */
6160 return p;
6261 }
62+ resetoldbit(o); /* may create a newer upval after this one */
6363 pp = &p->next;
6464 }
6565 /* not found: create a new one */
@@ -98,10 +98,12 @@ void luaF_close (lua_State *L, StkId level) { · 32 unmodified lines
9898 if (isdead(g, o))
9999 luaF_freeupval(L, uv); /* free upvalue */
100100 else {
101− unlinkupval(uv);
102− setobj(L, &uv->u.value, uv->v);
101+ unlinkupval(uv); /* remove upvalue from 'uvhead' list */
102+ setobj(L, &uv->u.value, uv->v); /* move value to upvalue slot */
103103 uv->v = &uv->u.value; /* now current value lives here */
104− luaC_linkupval(L, uv); /* link upvalue into `gcroot' list */
104+ gch(o)->next = g->allgc; /* link upvalue into 'allgc' list */
105+ g->allgc = o;
106+ luaC_checkupvalcolor(g, uv);
105107 }
106108 }
107109 }
@@ -127,7 +129,6 @@ Proto *luaF_newproto (lua_State *L) { · 19 unmodified lines
127129 f->linedefined = 0;
128130 f->lastlinedefined = 0;
129131 f->source = NULL;
130− f->envreg = NO_REG;
131132 return f;
132133 }
133134
src/lfunc.h+3−3
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lfunc.h,v 2.4 2005/04/25 19:24:10 roberto Exp $
2+** $Id: lfunc.h,v 2.5 2010/03/26 20:58:11 roberto Exp $
33 ** Auxiliary functions to manipulate prototypes and closures
44 ** See Copyright Notice in lua.h
55 */
@@ -19,8 +19,8 @@ · 13 unmodified lines
1919
2020
2121 LUAI_FUNC Proto *luaF_newproto (lua_State *L);
22−LUAI_FUNC Closure *luaF_newCclosure (lua_State *L, int nelems, Table *e);
23−LUAI_FUNC Closure *luaF_newLclosure (lua_State *L, int nelems, Table *e);
22+LUAI_FUNC Closure *luaF_newCclosure (lua_State *L, int nelems);
23+LUAI_FUNC Closure *luaF_newLclosure (lua_State *L, int nelems);
2424 LUAI_FUNC UpVal *luaF_newupval (lua_State *L);
2525 LUAI_FUNC UpVal *luaF_findupval (lua_State *L, StkId level);
2626 LUAI_FUNC void luaF_close (lua_State *L, StkId level);
src/lgc.c+429−263
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lgc.c,v 2.67 2009/12/22 15:32:50 roberto Exp $
2+** $Id: lgc.c,v 2.96 2010/05/17 20:39:31 roberto Exp $
33 ** Garbage Collector
44 ** See Copyright Notice in lua.h
55 */
@@ -23,21 +23,49 @@ · 17 unmodified lines
2323 #include "ltm.h"
2424
2525
26−#define GCSTEPSIZE 1024u
26+
27+/* how much to allocate before next GC step */
28+#define GCSTEPSIZE 1024
29+
30+/* maximum numer of elements to sweep in each single step */
2731 #define GCSWEEPMAX 40
28−#define GCSWEEPCOST 10
29−#define GCFINALIZECOST 100
3032
33+/* cost of sweeping one element */
34+#define GCSWEEPCOST 1
35+
36+/* maximum number of finalizers to call in each GC step */
37+#define GCFINALIZENUM 4
38+
39+/* cost of marking the root set */
40+#define GCROOTCOST 10
41+
42+/* cost of atomic step */
43+#define GCATOMICCOST 1000
44+
45+/* basic cost to traverse one object (to be added to the links the
46+ object may have) */
47+#define TRAVCOST 5
3148
32−#define maskcolors cast_byte(~(bitmask(BLACKBIT)|WHITEBITS))
3349
50+/*
51+** standard negative debt for GC; a reasonable "time" to wait before
52+** starting a new cycle
53+*/
54+#define stddebt(g) (-cast(l_mem, g->totalbytes/100) * g->gcpause)
55+
56+
57+/*
58+** 'makewhite' erases all color bits plus the old bit and then
59+** sets only the current white bit
60+*/
61+#define maskcolors (~(bit2mask(BLACKBIT, OLDBIT) | WHITEBITS))
3462 #define makewhite(g,x) \
3563 (gch(x)->marked = cast_byte((gch(x)->marked & maskcolors) | luaC_white(g)))
3664
3765 #define white2gray(x) resetbits(gch(x)->marked, WHITEBITS)
3866 #define black2gray(x) resetbit(gch(x)->marked, BLACKBIT)
3967
40−#define stringmark(s) resetbits((s)->tsv.marked, WHITEBITS)
68+#define stringmark(s) ((void)((s) && resetbits((s)->tsv.marked, WHITEBITS)))
4169
4270
4371 #define isfinalized(u) testbit((u)->marked, FINALIZEDBIT)
@@ -51,7 +79,6 @@ · 7 unmodified lines
5179 #define markobject(g,t) { if ((t) && iswhite(obj2gco(t))) \
5280 reallymarkobject(g, obj2gco(t)); }
5381
54−
5582 static void reallymarkobject (global_State *g, GCObject *o);
5683
5784
@@ -61,12 +88,16 @@ static void reallymarkobject (global_State *g, GCObject *o); · 3 unmodified lines
6188 ** =======================================================
6289 */
6390
64−static void linktable (Table *h, GCObject **p) {
65− h->gclist = *p;
66− *p = obj2gco(h);
67−}
91+
92+/*
93+** link table 'h' into list pointed by 'p'
94+*/
95+#define linktable(h,p) ((h)->gclist = *(p), *(p) = obj2gco(h))
6896
6997
98+/*
99+** mark a table entry as dead (therefore removing it from the table)
100+*/
70101 static void removeentry (Node *n) {
71102 lua_assert(ttisnil(gval(n)));
72103 if (iscollectable(gkey(n)))
@@ -75,8 +106,8 @@ static void removeentry (Node *n) { · 2 unmodified lines
75106
76107
77108 /*
78−** The next function tells whether a key or value can be cleared from
79−** a weak table. Non-collectable objects are never removed from weak
109+** tells whether a key or value can be cleared from a weak
110+** table. Non-collectable objects are never removed from weak
80111 ** tables. Strings behave as `values', so are never removed too. for
81112 ** other objects: if really collected, cannot keep them; for objects
82113 ** being finalized, keep them in keys, but not in values
@@ -92,24 +123,32 @@ static int iscleared (const TValue *o, int iskey) { · 9 unmodified lines
92123 }
93124
94125
126+/*
127+** barrier that moves collector forward, that is, mark the white object
128+** being pointed by a black object.
129+*/
95130 void luaC_barrierf (lua_State *L, GCObject *o, GCObject *v) {
96131 global_State *g = G(L);
97132 lua_assert(isblack(o) && iswhite(v) && !isdead(g, v) && !isdead(g, o));
98− lua_assert(g->gcstate != GCSfinalize && g->gcstate != GCSpause);
133+ lua_assert(isgenerational(g) || g->gcstate != GCSpause);
99134 lua_assert(gch(o)->tt != LUA_TTABLE);
100− /* must keep invariant? */
101− if (g->gcstate == GCSpropagate)
135+ if (keepinvariant(g)) /* must keep invariant? */
102136 reallymarkobject(g, v); /* restore invariant */
103− else /* don't mind */
104− makewhite(g, o); /* mark as white just to avoid other barriers */
137+ else { /* sweep phase */
138+ lua_assert(issweepphase(g));
139+ makewhite(g, o); /* mark main obj. as white to avoid other barriers */
140+ }
105141 }
106142
107143
144+/*
145+** barrier that moves collector backward, that is, mark the black object
146+** pointing to a white object as gray again.
147+*/
108148 void luaC_barrierback (lua_State *L, Table *t) {
109149 global_State *g = G(L);
110150 GCObject *o = obj2gco(t);
111151 lua_assert(isblack(o) && !isdead(g, o));
112− lua_assert(g->gcstate != GCSfinalize && g->gcstate != GCSpause);
113152 black2gray(o); /* make table gray (again) */
114153 t->gclist = g->grayagain;
115154 g->grayagain = o;
@@ -117,14 +156,37 @@ void luaC_barrierback (lua_State *L, Table *t) { · 1 unmodified line
117156
118157
119158 /*
120−** create a new collectable object and link it to '*list'
159+** check color (and invariants) for an upvalue that was closed,
160+** i.e., moved into the 'allgc' list
161+*/
162+void luaC_checkupvalcolor (global_State *g, UpVal *uv) {
163+ GCObject *o = obj2gco(uv);
164+ lua_assert(!isblack(o)); /* open upvalues are never black */
165+ if (isgray(o)) {
166+ if (keepinvariant(g)) {
167+ resetoldbit(o); /* see MOVE OLD rule */
168+ gray2black(o); /* it is being visited now */
169+ markvalue(g, uv->v);
170+ }
171+ else {
172+ lua_assert(issweepphase(g));
173+ makewhite(g, o);
174+ }
175+ }
176+}
177+
178+
179+/*
180+** create a new collectable object (with given type and size) and link
181+** it to '*list'. 'offset' tells how many bytes to allocate before the
182+** object itself (used only by states).
121183 */
122184 GCObject *luaC_newobj (lua_State *L, int tt, size_t sz, GCObject **list,
123185 int offset) {
124186 global_State *g = G(L);
125187 GCObject *o = obj2gco(cast(char *, luaM_newobject(L, tt, sz)) + offset);
126188 if (list == NULL)
127− list = &g->rootgc; /* standard list for collectable objects */
189+ list = &g->allgc; /* standard list for collectable objects */
128190 gch(o)->marked = luaC_white(g);
129191 gch(o)->tt = tt;
130192 gch(o)->next = *list;
@@ -132,24 +194,6 @@ GCObject *luaC_newobj (lua_State *L, int tt, size_t sz, GCObject **list, · 1 unmodified line
132194 return o;
133195 }
134196
135−
136−void luaC_linkupval (lua_State *L, UpVal *uv) {
137− global_State *g = G(L);
138− GCObject *o = obj2gco(uv);
139− gch(o)->next = g->rootgc; /* link upvalue into `rootgc' list */
140− g->rootgc = o;
141− if (isgray(o)) {
142− if (g->gcstate == GCSpropagate) {
143− gray2black(o); /* closed upvalues need barrier */
144− luaC_barrier(L, uv, uv->v);
145− }
146− else { /* sweep phase: sweep it (turning it into white) */
147− makewhite(g, o);
148− lua_assert(g->gcstate != GCSfinalize && g->gcstate != GCSpause);
149− }
150− }
151−}
152−
153197 /* }====================================================== */
154198
155199
@@ -160,25 +204,33 @@ void luaC_linkupval (lua_State *L, UpVal *uv) { · 4 unmodified lines
160204 ** =======================================================
161205 */
162206
207+
208+/*
209+** mark an object. Userdata and closed upvalues are visited and turned
210+** black here. Strings remain gray (it is the same as making them
211+** black). Other objects are marked gray and added to appropriate list
212+** to be visited (and turned black) later. (Open upvalues are already
213+** linked in 'headuv' list.)
214+*/
163215 static void reallymarkobject (global_State *g, GCObject *o) {
164216 lua_assert(iswhite(o) && !isdead(g, o));
165217 white2gray(o);
166218 switch (gch(o)->tt) {
167219 case LUA_TSTRING: {
168− return;
220+ return; /* for strings, gray is as good as black */
169221 }
170222 case LUA_TUSERDATA: {
171223 Table *mt = gco2u(o)->metatable;
172− gray2black(o); /* udata are never gray */
173224 markobject(g, mt);
174225 markobject(g, gco2u(o)->env);
226+ gray2black(o); /* all pointers marked */
175227 return;
176228 }
177229 case LUA_TUPVAL: {
178230 UpVal *uv = gco2uv(o);
179231 markvalue(g, uv->v);
180− if (uv->v == &uv->u.value) /* closed? */
181− gray2black(o); /* open upvalues are never black */
232+ if (uv->v == &uv->u.value) /* closed? (open upvalues remain gray) */
233+ gray2black(o); /* make it black */
182234 return;
183235 }
184236 case LUA_TFUNCTION: {
@@ -205,48 +257,55 @@ static void reallymarkobject (global_State *g, GCObject *o) { · 20 unmodified lines
205257 }
206258
207259
260+/*
261+** mark tag methods for basic types
262+*/
208263 static void markmt (global_State *g) {
209264 int i;
210− for (i=0; i<NUM_TAGS; i++)
265+ for (i=0; i < LUA_NUMTAGS; i++)
211266 markobject(g, g->mt[i]);
212267 }
213268
214269
270+/*
271+** mark all objects in list of being-finalized
272+*/
215273 static void markbeingfnz (global_State *g) {
216274 GCObject *o;
217275 for (o = g->tobefnz; o != NULL; o = gch(o)->next) {
218− lua_assert(testbit(gch(o)->marked, SEPARATED));
219276 makewhite(g, o);
220277 reallymarkobject(g, o);
221278 }
222279 }
223280
224281
225−/* mark root set */
226−static void markroot (lua_State *L) {
227− global_State *g = G(L);
228− g->gray = NULL;
229− g->grayagain = NULL;
230− g->weak = g->ephemeron = g->allweak = NULL;
231− markobject(g, g->mainthread);
232− /* make global table and registry to be traversed before main stack */
233− markobject(g, g->l_gt);
234− markvalue(g, &g->l_registry);
235− markmt(g);
236− markbeingfnz(g); /* mark any finalizing object left from previous cycle */
237− g->gcstate = GCSpropagate;
238−}
239−
240−
282+/*
283+** mark all values stored in marked open upvalues. (See comment in
284+** 'lstate.h'.)
285+*/
241286 static void remarkupvals (global_State *g) {
242287 UpVal *uv;
243288 for (uv = g->uvhead.u.l.next; uv != &g->uvhead; uv = uv->u.l.next) {
244− lua_assert(uv->u.l.next->u.l.prev == uv && uv->u.l.prev->u.l.next == uv);
245289 if (isgray(obj2gco(uv)))
246290 markvalue(g, uv->v);
247291 }
248292 }
249293
294+
295+/*
296+** mark root set and reset all gray lists, to start a new
297+** incremental (or full) collection
298+*/
299+static void markroot (lua_State *L) {
300+ global_State *g = G(L);
301+ g->gray = g->grayagain = NULL;
302+ g->weak = g->allweak = g->ephemeron = NULL;
303+ markobject(g, g->mainthread);
304+ markvalue(g, &g->l_registry);
305+ markmt(g);
306+ markbeingfnz(g); /* mark any finalizing object left from previous cycle */
307+}
308+
250309 /* }====================================================== */
251310
252311
@@ -257,49 +316,48 @@ static void remarkupvals (global_State *g) { · 4 unmodified lines
257316 */
258317
259318 static void traverseweakvalue (global_State *g, Table *h) {
260− int i = sizenode(h);
261− while (i--) {
262− Node *n = gnode(h, i);
319+ Node *n, *limit = gnode(h, sizenode(h));
320+ for (n = gnode(h, 0); n < limit; n++) {
263321 checkdeadkey(n);
264− if (ttisnil(gval(n)))
265− removeentry(n); /* remove empty entries */
322+ if (ttisnil(gval(n))) /* entry is empty? */
323+ removeentry(n); /* remove it */
266324 else {
267325 lua_assert(!ttisnil(gkey(n)));
268− markvalue(g, gkey(n));
326+ markvalue(g, gkey(n)); /* mark key */
269327 }
270328 }
271− linktable(h, &g->weak);
329+ linktable(h, &g->weak); /* link into appropriate list */
272330 }
273331
274332
275333 static int traverseephemeron (global_State *g, Table *h) {
276− int marked = 0;
277− int hasclears = 0;
278− int i = h->sizearray;
279− while (i--) { /* mark array part (numeric keys are 'strong') */
334+ int marked = 0; /* true if an object is marked in this traversal */
335+ int hasclears = 0; /* true if table has unmarked pairs */
336+ Node *n, *limit = gnode(h, sizenode(h));
337+ int i;
338+ /* traverse array part (numeric keys are 'strong') */
339+ for (i = 0; i < h->sizearray; i++) {
280340 if (valiswhite(&h->array[i])) {
281341 marked = 1;
282342 reallymarkobject(g, gcvalue(&h->array[i]));
283343 }
284344 }
285− i = sizenode(h);
286− while (i--) {
287− Node *n = gnode(h, i);
345+ /* traverse hash part */
346+ for (n = gnode(h, 0); n < limit; n++) {
288347 checkdeadkey(n);
289348 if (ttisnil(gval(n))) /* entry is empty? */
290349 removeentry(n); /* remove it */
291− else if (valiswhite(gval(n))) {
292− /* value is not marked yet */
350+ else if (valiswhite(gval(n))) { /* value not marked yet? */
293351 if (iscleared(key2tval(n), 1)) /* key is not marked (yet)? */
294352 hasclears = 1; /* may have to propagate mark from key to value */
295− else { /* mark value only if key is marked */
296− marked = 1; /* some mark changed status */
353+ else { /* key is marked, so mark value */
354+ marked = 1; /* value was not marked */
297355 reallymarkobject(g, gcvalue(gval(n)));
298356 }
299357 }
300358 }
301− if (hasclears)
302− linktable(h, &g->ephemeron);
359+ if (hasclears) /* does table have unmarked pairs? */
360+ linktable(h, &g->ephemeron); /* will have to propagate again */
303361 else /* nothing to propagate */
304362 linktable(h, &g->weak); /* avoid convergence phase */
305363 return marked;
@@ -307,26 +365,24 @@ static int traverseephemeron (global_State *g, Table *h) { · 1 unmodified line
307365
308366
309367 static void traversestrongtable (global_State *g, Table *h) {
368+ Node *n, *limit = gnode(h, sizenode(h));
310369 int i;
311− i = h->sizearray;
312− while (i--)
370+ for (i = 0; i < h->sizearray; i++) /* traverse array part */
313371 markvalue(g, &h->array[i]);
314− i = sizenode(h);
315− while (i--) {
316− Node *n = gnode(h, i);
372+ for (n = gnode(h, 0); n < limit; n++) { /* traverse hash part */
317373 checkdeadkey(n);
318− if (ttisnil(gval(n)))
319− removeentry(n); /* remove empty entries */
374+ if (ttisnil(gval(n))) /* entry is empty? */
375+ removeentry(n); /* remove it */
320376 else {
321377 lua_assert(!ttisnil(gkey(n)));
322− markvalue(g, gkey(n));
323− markvalue(g, gval(n));
378+ markvalue(g, gkey(n)); /* mark key */
379+ markvalue(g, gval(n)); /* mark value */
324380 }
325381 }
326382 }
327383
328384
329−static void traversetable (global_State *g, Table *h) {
385+static int traversetable (global_State *g, Table *h) {
330386 const TValue *mode = gfasttm(g, h->metatable, TM_MODE);
331387 markobject(g, h->metatable);
332388 if (mode && ttisstring(mode)) { /* is there a weak mode? */
@@ -334,43 +390,41 @@ static void traversetable (global_State *g, Table *h) { · 1 unmodified line
334390 int weakvalue = (strchr(svalue(mode), 'v') != NULL);
335391 if (weakkey || weakvalue) { /* is really weak? */
336392 black2gray(obj2gco(h)); /* keep table gray */
337− if (!weakkey) /* strong keys? */
393+ if (!weakkey) { /* strong keys? */
338394 traverseweakvalue(g, h);
339− else if (!weakvalue) /* strong values? */
395+ return TRAVCOST + sizenode(h);
396+ }
397+ else if (!weakvalue) { /* strong values? */
340398 traverseephemeron(g, h);
341− else
399+ return TRAVCOST + h->sizearray + sizenode(h);
400+ }
401+ else {
342402 linktable(h, &g->allweak); /* nothing to traverse now */
343− return;
403+ return TRAVCOST;
404+ }
344405 } /* else go through */
345406 }
346407 traversestrongtable(g, h);
408+ return TRAVCOST + h->sizearray + (2 * sizenode(h));
347409 }
348410
349411
350−/*
351−** All marks are conditional because a GC may happen while the
352−** prototype is still being created
353−*/
354−static void traverseproto (global_State *g, Proto *f) {
412+static int traverseproto (global_State *g, Proto *f) {
355413 int i;
356− if (f->source) stringmark(f->source);
357− for (i=0; i<f->sizek; i++) /* mark literals */
414+ stringmark(f->source);
415+ for (i = 0; i < f->sizek; i++) /* mark literals */
358416 markvalue(g, &f->k[i]);
359− for (i=0; i<f->sizeupvalues; i++) { /* mark upvalue names */
360− if (f->upvalues[i].name)
361− stringmark(f->upvalues[i].name);
362− }
363− for (i=0; i<f->sizep; i++) /* mark nested protos */
417+ for (i = 0; i < f->sizeupvalues; i++) /* mark upvalue names */
418+ stringmark(f->upvalues[i].name);
419+ for (i = 0; i < f->sizep; i++) /* mark nested protos */
364420 markobject(g, f->p[i]);
365− for (i=0; i<f->sizelocvars; i++) { /* mark local-variable names */
366− if (f->locvars[i].varname)
367− stringmark(f->locvars[i].varname);
368− }
421+ for (i = 0; i < f->sizelocvars; i++) /* mark local-variable names */
422+ stringmark(f->locvars[i].varname);
423+ return TRAVCOST + f->sizek + f->sizeupvalues + f->sizep + f->sizelocvars;
369424 }
370425
371426
372−static void traverseclosure (global_State *g, Closure *cl) {
373− markobject(g, cl->c.env);
427+static l_mem traverseclosure (global_State *g, Closure *cl) {
374428 if (cl->c.isC) {
375429 int i;
376430 for (i=0; i<cl->c.nupvalues; i++) /* mark its upvalues */
@@ -379,32 +433,35 @@ static void traverseclosure (global_State *g, Closure *cl) { · 2 unmodified lines
379433 else {
380434 int i;
381435 lua_assert(cl->l.nupvalues == cl->l.p->sizeupvalues);
382− markobject(g, cl->l.p);
436+ markobject(g, cl->l.p); /* mark its prototype */
383437 for (i=0; i<cl->l.nupvalues; i++) /* mark its upvalues */
384438 markobject(g, cl->l.upvals[i]);
385439 }
440+ return TRAVCOST + cl->c.nupvalues;
386441 }
387442
388443
389−static void traversestack (global_State *g, lua_State *L) {
390− StkId o;
391− if (L->stack == NULL)
392− return; /* stack not completely built yet */
393− for (o = L->stack; o < L->top; o++)
444+static int traversestack (global_State *g, lua_State *L) {
445+ StkId o = L->stack;
446+ if (o == NULL)
447+ return 1; /* stack not completely built yet */
448+ for (; o < L->top; o++)
394449 markvalue(g, o);
395450 if (g->gcstate == GCSatomic) { /* final traversal? */
396451 StkId lim = L->stack + L->stacksize; /* real end of stack */
397452 for (; o < lim; o++) /* clear not-marked stack slice */
398453 setnilvalue(o);
399454 }
455+ return TRAVCOST + cast_int(o - L->stack);
400456 }
401457
402458
403459 /*
404−** traverse one gray object, turning it to black.
405−** Returns `quantity' traversed.
460+** traverse one gray object, turning it to black (except for threads,
461+** which are always gray).
462+** Returns number of values traversed.
406463 */
407−static l_mem propagatemark (global_State *g) {
464+static int propagatemark (global_State *g) {
408465 GCObject *o = g->gray;
409466 lua_assert(isgray(o));
410467 gray2black(o);
@@ -412,16 +469,12 @@ static l_mem propagatemark (global_State *g) { · 1 unmodified line
412469 case LUA_TTABLE: {
413470 Table *h = gco2t(o);
414471 g->gray = h->gclist;
415− traversetable(g, h);
416− return sizeof(Table) + sizeof(TValue) * h->sizearray +
417− sizeof(Node) * sizenode(h);
472+ return traversetable(g, h);
418473 }
419474 case LUA_TFUNCTION: {
420475 Closure *cl = gco2cl(o);
421476 g->gray = cl->c.gclist;
422− traverseclosure(g, cl);
423− return (cl->c.isC) ? sizeCclosure(cl->c.nupvalues) :
424− sizeLclosure(cl->l.nupvalues);
477+ return traverseclosure(g, cl);
425478 }
426479 case LUA_TTHREAD: {
427480 lua_State *th = gco2th(o);
@@ -429,19 +482,12 @@ static l_mem propagatemark (global_State *g) { · 1 unmodified line
429482 th->gclist = g->grayagain;
430483 g->grayagain = o;
431484 black2gray(o);
432− traversestack(g, th);
433− return sizeof(lua_State) + sizeof(TValue) * th->stacksize;
485+ return traversestack(g, th);
434486 }
435487 case LUA_TPROTO: {
436488 Proto *p = gco2p(o);
437489 g->gray = p->gclist;
438− traverseproto(g, p);
439− return sizeof(Proto) + sizeof(Instruction) * p->sizecode +
440− sizeof(Proto *) * p->sizep +
441− sizeof(TValue) * p->sizek +
442− sizeof(int) * p->sizelineinfo +
443− sizeof(LocVar) * p->sizelocvars +
444− sizeof(TString *) * p->sizeupvalues;
490+ return traverseproto(g, p);
445491 }
446492 default: lua_assert(0); return 0;
447493 }
@@ -465,14 +511,14 @@ static void convergeephemerons (global_State *g) { · 17 unmodified lines
465511 int changed;
466512 do {
467513 GCObject *w;
468− GCObject *next = g->ephemeron;
469− g->ephemeron = NULL;
514+ GCObject *next = g->ephemeron; /* get ephemeron list */
515+ g->ephemeron = NULL; /* tables will return to this list when traversed */
470516 changed = 0;
471517 while ((w = next) != NULL) {
472518 next = gco2t(w)->gclist;
473− if (traverseephemeron(g, gco2t(w))) {
474− changed = 1;
475− propagateall(g);
519+ if (traverseephemeron(g, gco2t(w))) { /* traverse marked some value? */
520+ propagateall(g); /* propagate changes */
521+ changed = 1; /* will have to revisit all ephemeron tables */
476522 }
477523 }
478524 } while (changed);
@@ -487,26 +533,26 @@ static void convergeephemerons (global_State *g) { · 8 unmodified lines
487533 ** =======================================================
488534 */
489535
490−/* clear collected entries from weaktables */
536+/*
537+** clear collected entries from all weaktables in list 'l'
538+*/
491539 static void cleartable (GCObject *l) {
492− while (l) {
540+ for (; l != NULL; l = gco2t(l)->gclist) {
493541 Table *h = gco2t(l);
494− int i = h->sizearray;
495− while (i--) {
542+ Node *n, *limit = gnode(h, sizenode(h));
543+ int i;
544+ for (i = 0; i < h->sizearray; i++) {
496545 TValue *o = &h->array[i];
497546 if (iscleared(o, 0)) /* value was collected? */
498547 setnilvalue(o); /* remove value */
499548 }
500− i = sizenode(h);
501− while (i--) {
502− Node *n = gnode(h, i);
549+ for (n = gnode(h, 0); n < limit; n++) {
503550 if (!ttisnil(gval(n)) && /* non-empty entry? */
504551 (iscleared(key2tval(n), 1) || iscleared(gval(n), 0))) {
505552 setnilvalue(gval(n)); /* remove value ... */
506− removeentry(n); /* remove entry from table */
553+ removeentry(n); /* and remove entry from table */
507554 }
508555 }
509− l = h->gclist;
510556 }
511557 }
512558
@@ -533,33 +579,63 @@ static void freeobj (lua_State *L, GCObject *o) { · 20 unmodified lines
533579 static GCObject **sweeplist (lua_State *L, GCObject **p, lu_mem count);
534580
535581
536−static void sweepthread (lua_State *L, lua_State *L1, int alive) {
582+/*
583+** sweep the (open) upvalues of a thread and resize its stack and
584+** list of call-info structures.
585+*/
586+static void sweepthread (lua_State *L, lua_State *L1) {
537587 if (L1->stack == NULL) return; /* stack not completely built yet */
538588 sweepwholelist(L, &L1->openupval); /* sweep open upvalues */
539589 luaE_freeCI(L1); /* free extra CallInfo slots */
540590 /* should not change the stack during an emergency gc cycle */
541− if (alive && G(L)->gckind != KGC_EMERGENCY)
591+ if (G(L)->gckind != KGC_EMERGENCY)
542592 luaD_shrinkstack(L1);
543593 }
544594
545595
596+/*
597+** sweep at most 'count' elements from a list of GCObjects erasing dead
598+** objects, where a dead (not alive) object is one marked with the "old"
599+** (non current) white and not fixed.
600+** In non-generational mode, change all non-dead objects back to white,
601+** preparing for next collection cycle.
602+** In generational mode, keep black objects black, and also mark them as
603+** old; stop when hitting an old object, as all objects after that
604+** one will be old too.
605+** When object is a thread, sweep its list of open upvalues too.
606+*/
546607 static GCObject **sweeplist (lua_State *L, GCObject **p, lu_mem count) {
547− GCObject *curr;
548608 global_State *g = G(L);
549− int deadmask = otherwhite(g);
550− while ((curr = *p) != NULL && count-- > 0) {
551− int alive = (gch(curr)->marked ^ WHITEBITS) & deadmask;
552− if (gch(curr)->tt == LUA_TTHREAD)
553− sweepthread(L, gco2th(curr), alive);
554− if (alive) {
555− lua_assert(!isdead(g, curr) || testbit(gch(curr)->marked, FIXEDBIT));
556− makewhite(g, curr); /* make it white (for next cycle) */
557− p = &gch(curr)->next;
558− }
559− else { /* must erase `curr' */
560− lua_assert(isdead(g, curr) || deadmask == bitmask(SFIXEDBIT));
609+ int ow = otherwhite(g);
610+ int toclear, toset; /* bits to clear and to set in all live objects */
611+ int tostop; /* stop sweep when this is true */
612+ if (isgenerational(g)) { /* generational mode? */
613+ toclear = ~0; /* clear nothing */
614+ toset = bitmask(OLDBIT); /* set the old bit of all surviving objects */
615+ tostop = bitmask(OLDBIT); /* do not sweep old generation */
616+ }
617+ else { /* normal mode */
618+ toclear = maskcolors; /* clear all color bits + old bit */
619+ toset = luaC_white(g); /* make object white */
620+ tostop = 0; /* do not stop */
621+ }
622+ while (*p != NULL && count-- > 0) {
623+ GCObject *curr = *p;
624+ int marked = gch(curr)->marked;
625+ if (isdeadm(ow, marked)) { /* is 'curr' dead? */
561626 *p = gch(curr)->next; /* remove 'curr' from list */
562− freeobj(L, curr);
627+ freeobj(L, curr); /* erase 'curr' */
628+ }
629+ else {
630+ if (gch(curr)->tt == LUA_TTHREAD)
631+ sweepthread(L, gco2th(curr)); /* sweep thread's upvalues */
632+ if (testbits(marked, tostop)) {
633+ static GCObject *nullp = NULL;
634+ return &nullp; /* stop sweeping this list */
635+ }
636+ /* update marks */
637+ gch(curr)->marked = cast_byte((marked & toclear) | toset);
638+ p = &gch(curr)->next; /* go to next element */
563639 }
564640 }
565641 return p;
@@ -576,25 +652,28 @@ static GCObject **sweeplist (lua_State *L, GCObject **p, lu_mem count) { · 10 unmodified lines
576652
577653 static void checkSizes (lua_State *L) {
578654 global_State *g = G(L);
579− if (g->strt.nuse < cast(lu_int32, g->strt.size)) {
580− /* string-table size could be the smaller power of 2 larger than 'nuse' */
581− int size = 1 << luaO_ceillog2(g->strt.nuse);
582− if (size < g->strt.size) /* current table too large? */
583− luaS_resize(L, size); /* shrink it */
655+ if (g->gckind != KGC_EMERGENCY) { /* do not change sizes in emergency */
656+ int hs = g->strt.size / 2; /* half the size of the string table */
657+ if (g->strt.nuse < cast(lu_int32, hs)) /* using less than that half? */
658+ luaS_resize(L, hs); /* halve its size */
659+ luaZ_freebuffer(L, &g->buff); /* free concatenation buffer */
584660 }
585− luaZ_freebuffer(L, &g->buff);
586661 }
587662
588663
589664 static Udata *udata2finalize (global_State *g) {
590665 GCObject *o = g->tobefnz; /* get first element */
591− g->tobefnz = gch(o)->next; /* remove it from 'tobefnz' list */
592− gch(o)->next = g->rootgc; /* return it to `root' list */
593− g->rootgc = o;
594− lua_assert(isfinalized(gch(o)));
595− resetbit(gch(o)->marked, SEPARATED); /* mark it as such */
596− makewhite(g, o);
597− return rawgco2u(o);
666+ Udata *u = rawgco2u(o);
667+ lua_assert(isfinalized(&u->uv));
668+ lua_assert(!isold(o));
669+ g->tobefnz = u->uv.next; /* remove it from 'tobefnz' list */
670+ u->uv.next = g->allgc; /* return it to 'allgc' list */
671+ g->allgc = o;
672+ resetbit(u->uv.marked, SEPARATED); /* mark that it is not in 'tobefnz' */
673+ resetoldbit(o); /* see MOVE OLD rule */
674+ if (!keepinvariant(g)) /* not keeping invariant? */
675+ makewhite(g, o); /* "sweep" object */
676+ return u;
598677 }
599678
600679
@@ -608,18 +687,18 @@ static void GCTM (lua_State *L, int propagateerrors) { · 7 unmodified lines
608687 global_State *g = G(L);
609688 Udata *udata = udata2finalize(g);
610689 const TValue *tm = gfasttm(g, udata->uv.metatable, TM_GC);
611− if (tm != NULL && ttisfunction(tm)) {
690+ if (tm != NULL && ttisfunction(tm)) { /* is there a finalizer? */
612691 int status;
613692 lu_byte oldah = L->allowhook;
614− lu_mem oldt = g->GCthreshold;
693+ lu_mem oldd = g->GCdebt;
615694 L->allowhook = 0; /* stop debug hooks during GC tag method */
616− g->GCthreshold = 2*g->totalbytes; /* avoid GC steps */
617− setobj2s(L, L->top, tm);
618− setuvalue(L, L->top+1, udata);
619− L->top += 2;
695+ stopgc(g); /* avoid GC steps */
696+ setobj2s(L, L->top, tm); /* push finalizer... */
697+ setuvalue(L, L->top+1, udata); /* ... and its argument */
698+ L->top += 2; /* and (next line) call the finalizer */
620699 status = luaD_pcall(L, dothecall, NULL, savestack(L, L->top - 2), 0);
621700 L->allowhook = oldah; /* restore hooks */
622− g->GCthreshold = oldt; /* restore threshold */
701+ g->GCdebt = oldd; /* restore threshold */
623702 if (status != LUA_OK && propagateerrors) { /* error while running __gc? */
624703 if (status == LUA_ERRRUN) { /* is there an error msg.? */
625704 luaO_pushfstring(L, "error in __gc tag method (%s)",
@@ -632,14 +711,18 @@ static void GCTM (lua_State *L, int propagateerrors) { · 6 unmodified lines
632711 }
633712
634713
635−/* move 'dead' udata that need finalization to list 'tobefnz' */
714+/*
715+** move all unreachable udata that need finalization from list 'udgc' to
716+** list 'tobefnz'
717+*/
636718 void luaC_separateudata (lua_State *L, int all) {
637719 global_State *g = G(L);
638− GCObject **p = &g->mainthread->next;
720+ GCObject **p = &g->udgc;
639721 GCObject *curr;
640722 GCObject **lastnext = &g->tobefnz;
641− /* find last 'next' field in 'tobefnz' list (to insert elements in its end) */
642− while (*lastnext != NULL) lastnext = &gch(*lastnext)->next;
723+ /* find last 'next' field in 'tobefnz' list (to add elements in its end) */
724+ while (*lastnext != NULL)
725+ lastnext = &gch(*lastnext)->next;
643726 while ((curr = *p) != NULL) { /* traverse all finalizable objects */
644727 lua_assert(gch(curr)->tt == LUA_TUSERDATA && !isfinalized(gco2u(curr)));
645728 lua_assert(testbit(gch(curr)->marked, SEPARATED));
@@ -647,9 +730,8 @@ void luaC_separateudata (lua_State *L, int all) { · 1 unmodified line
647730 p = &gch(curr)->next; /* don't bother with it */
648731 else {
649732 l_setbit(gch(curr)->marked, FINALIZEDBIT); /* won't be finalized again */
650− *p = gch(curr)->next; /* remove 'curr' from 'rootgc' list */
651− /* link 'curr' at the end of 'tobefnz' list */
652− gch(curr)->next = *lastnext;
733+ *p = gch(curr)->next; /* remove 'curr' from 'udgc' list */
734+ gch(curr)->next = *lastnext; /* link at the end of 'tobefnz' list */
653735 *lastnext = curr;
654736 lastnext = &gch(curr)->next;
655737 }
@@ -657,20 +739,24 @@ void luaC_separateudata (lua_State *L, int all) { · 1 unmodified line
657739 }
658740
659741
742+/*
743+** if userdata 'u' has a finalizer, remove it from 'allgc' list (must
744+** search the list to find it) and link it in 'udgc' list.
745+*/
660746 void luaC_checkfinalizer (lua_State *L, Udata *u) {
661747 global_State *g = G(L);
662− if (testbit(u->uv.marked, SEPARATED) || /* userdata is already separated... */
663− isfinalized(&u->uv) || /* ... or is finalized... */
664− gfasttm(g, u->uv.metatable, TM_GC) == NULL) /* or has no finalization? */
748+ if (testbit(u->uv.marked, SEPARATED) || /* udata is already separated... */
749+ isfinalized(&u->uv) || /* ... or is finalized... */
750+ gfasttm(g, u->uv.metatable, TM_GC) == NULL) /* or has no finalizer? */
665751 return; /* nothing to be done */
666− else { /* move 'u' to 2nd part of root list */
752+ else { /* move 'u' to 'udgc' list */
667753 GCObject **p;
668− for (p = &g->rootgc; *p != obj2gco(u); p = &gch(*p)->next)
669− lua_assert(*p != obj2gco(g->mainthread)); /* 'u' must be in this list */
754+ for (p = &g->allgc; *p != obj2gco(u); p = &gch(*p)->next) ;
670755 *p = u->uv.next; /* remove 'u' from root list */
671− u->uv.next = g->mainthread->next; /* re-link it in list */
672− g->mainthread->next = obj2gco(u);
756+ u->uv.next = g->udgc; /* link it in list 'udgc' */
757+ g->udgc = obj2gco(u);
673758 l_setbit(u->uv.marked, SEPARATED); /* mark it as such */
759+ resetoldbit(obj2gco(u)); /* see MOVE OLD rule */
674760 }
675761 }
676762
@@ -683,15 +769,52 @@ void luaC_checkfinalizer (lua_State *L, Udata *u) { · 6 unmodified lines
683769 ** =======================================================
684770 */
685771
772+
773+#define sweepphases \
774+ (bitmask(GCSsweepstring) | bitmask(GCSsweepudata) | bitmask(GCSsweep))
775+
776+/*
777+** change GC mode
778+*/
779+void luaC_changemode (lua_State *L, int mode) {
780+ global_State *g = G(L);
781+ if (mode == g->gckind) return; /* nothing to change */
782+ if (mode == KGC_GEN) { /* change to generational mode */
783+ /* make sure gray lists are consistent */
784+ luaC_runtilstate(L, bitmask(GCSpropagate));
785+ g->lastmajormem = g->totalbytes;
786+ g->gckind = KGC_GEN;
787+ }
788+ else { /* change to incremental mode */
789+ /* sweep all objects to turn them back to white
790+ (as white has not changed, nothing extra will be collected) */
791+ g->sweepstrgc = 0;
792+ g->gcstate = GCSsweepstring;
793+ g->gckind = KGC_NORMAL;
794+ luaC_runtilstate(L, ~sweepphases);
795+ }
796+}
797+
798+
799+/*
800+** call all pending finalizers */
801+static void callallpendingfinalizers (lua_State *L, int propagateerrors) {
802+ global_State *g = G(L);
803+ while (g->tobefnz) GCTM(L, propagateerrors);
804+}
805+
806+
686807 void luaC_freeallobjects (lua_State *L) {
687808 global_State *g = G(L);
688809 int i;
689− while (g->tobefnz) GCTM(L, 0); /* Call all pending finalizers */
810+ callallpendingfinalizers(L, 0);
690811 /* following "white" makes all objects look dead */
691− g->currentwhite = WHITEBITS | bitmask(SFIXEDBIT);
692− sweepwholelist(L, &g->rootgc);
693− lua_assert(g->rootgc == obj2gco(g->mainthread) &&
694− g->mainthread->next == NULL);
812+ g->currentwhite = WHITEBITS;
813+ g->gckind = KGC_NORMAL;
814+ sweepwholelist(L, &g->udgc);
815+ lua_assert(g->udgc == NULL);
816+ sweepwholelist(L, &g->allgc);
817+ lua_assert(g->allgc == NULL);
695818 for (i = 0; i < g->strt.size; i++) /* free all string lists */
696819 sweepwholelist(L, &g->strt.hash[i]);
697820 lua_assert(g->strt.nuse == 0);
@@ -700,7 +823,6 @@ void luaC_freeallobjects (lua_State *L) { · 2 unmodified lines
700823
701824 static void atomic (lua_State *L) {
702825 global_State *g = G(L);
703− g->gcstate = GCSatomic;
704826 lua_assert(!iswhite(obj2gco(g->mainthread)));
705827 markobject(g, L); /* mark running thread */
706828 /* registry and global metatables may be changed by API */
@@ -710,12 +832,11 @@ static void atomic (lua_State *L) { · 3 unmodified lines
710832 remarkupvals(g);
711833 /* traverse objects caught by write barrier and by 'remarkupvals' */
712834 propagateall(g);
713− /* at this point, all strongly accessible objects are marked.
714− Start marking weakly accessible objects. */
715835 traverselistofgrays(g, &g->weak); /* remark weak tables */
716836 traverselistofgrays(g, &g->ephemeron); /* remark ephemeron tables */
717837 traverselistofgrays(g, &g->grayagain); /* remark gray again */
718838 convergeephemerons(g);
839+ /* at this point, all strongly accessible objects are marked. */
719840 luaC_separateudata(L, 0); /* separate userdata to be finalized */
720841 markbeingfnz(g); /* mark userdata that will be finalized */
721842 propagateall(g); /* remark, to propagate `preserveness' */
@@ -724,51 +845,68 @@ static void atomic (lua_State *L) { · 2 unmodified lines
724845 cleartable(g->weak);
725846 cleartable(g->ephemeron);
726847 cleartable(g->allweak);
727− g->currentwhite = cast_byte(otherwhite(g)); /* flip current white */
728− g->sweepstrgc = 0; /* go to sweep phase */
848+ g->sweepstrgc = 0; /* prepare to sweep strings */
729849 g->gcstate = GCSsweepstring;
850+ g->currentwhite = cast_byte(otherwhite(g)); /* flip current white */
851+ /*lua_checkmemory(L);*/
730852 }
731853
732854
733855 static l_mem singlestep (lua_State *L) {
734856 global_State *g = G(L);
735− /*lua_checkmemory(L);*/
736857 switch (g->gcstate) {
737858 case GCSpause: {
738− markroot(L); /* start a new collection */
739− return 0;
859+ if (!isgenerational(g))
860+ markroot(L); /* start a new collection */
861+ /* in any case, root must be marked */
862+ lua_assert(!iswhite(obj2gco(g->mainthread))
863+ && !iswhite(gcvalue(&g->l_registry)));
864+ g->gcstate = GCSpropagate;
865+ return GCROOTCOST;
740866 }
741867 case GCSpropagate: {
742868 if (g->gray)
743869 return propagatemark(g);
744870 else { /* no more `gray' objects */
745− atomic(L); /* finish mark phase */
746− return 0;
871+ g->gcstate = GCSatomic; /* finish mark phase */
872+ atomic(L);
873+ return GCATOMICCOST;
747874 }
748875 }
749876 case GCSsweepstring: {
750− sweepwholelist(L, &g->strt.hash[g->sweepstrgc++]);
751− if (g->sweepstrgc >= g->strt.size) { /* nothing more to sweep? */
752− g->sweepgc = &g->rootgc;
753− g->gcstate = GCSsweep; /* sweep all other objects */
877+ if (g->sweepstrgc < g->strt.size) {
878+ sweepwholelist(L, &g->strt.hash[g->sweepstrgc++]);
879+ return GCSWEEPCOST;
880+ }
881+ else { /* no more strings to sweep */
882+ g->sweepgc = &g->udgc; /* prepare to sweep userdata */
883+ g->gcstate = GCSsweepudata;
884+ return 0;
754885 }
755− return GCSWEEPCOST;
756886 }
757− case GCSsweep: {
758− g->sweepgc = sweeplist(L, g->sweepgc, GCSWEEPMAX);
759− if (*g->sweepgc == NULL) /* nothing more to sweep? */
760− g->gcstate = GCSfinalize; /* end sweep phase */
761− return GCSWEEPMAX*GCSWEEPCOST;
887+ case GCSsweepudata: {
888+ if (*g->sweepgc) {
889+ g->sweepgc = sweeplist(L, g->sweepgc, GCSWEEPMAX);
890+ return GCSWEEPMAX*GCSWEEPCOST;
891+ }
892+ else {
893+ g->sweepgc = &g->allgc; /* go to next phase */
894+ g->gcstate = GCSsweep;
895+ return GCSWEEPCOST;
896+ }
762897 }
763− case GCSfinalize: {
764− if (g->tobefnz) {
765− GCTM(L, 1);
766− return GCFINALIZECOST;
898+ case GCSsweep: {
899+ if (*g->sweepgc) {
900+ g->sweepgc = sweeplist(L, g->sweepgc, GCSWEEPMAX);
901+ return GCSWEEPMAX*GCSWEEPCOST;
767902 }
768903 else {
904+ /* sweep main thread */
905+ GCObject *mt = obj2gco(g->mainthread);
906+ sweeplist(L, &mt, 1);
769907 checkSizes(L);
770− g->gcstate = GCSpause; /* end collection */
771− return 0;
908+ g->gcstate = GCSpause; /* finish collection */
909+ return GCSWEEPCOST;
772910 }
773911 }
774912 default: lua_assert(0); return 0;
@@ -776,22 +914,6 @@ static l_mem singlestep (lua_State *L) { · 1 unmodified line
776914 }
777915
778916
779−void luaC_step (lua_State *L) {
780− global_State *g = G(L);
781− l_mem lim = (GCSTEPSIZE/100) * g->gcstepmul; /* how much to work */
782− lu_mem debt = g->totalbytes - g->GCthreshold;
783− lua_assert(g->gckind == KGC_NORMAL);
784− do { /* always perform at least one single step */
785− lim -= singlestep(L);
786− } while (lim > 0 && g->gcstate != GCSpause);
787− g->GCthreshold = (g->gcstate != GCSpause)
788− ? g->totalbytes + GCSTEPSIZE
789− : (g->totalbytes/100) * g->gcpause;
790− /* compensate if GC is "behind schedule" (has some debt to pay) */
791− if (g->GCthreshold > debt) g->GCthreshold -= debt;
792−}
793−
794−
795917 /*
796918 ** advances the garbage collector until it reaches a state allowed
797919 ** by 'statemask'
@@ -803,29 +925,73 @@ void luaC_runtilstate (lua_State *L, int statesmask) { · 5 unmodified lines
803925 }
804926
805927
928+static void generationalcollection (lua_State *L) {
929+ global_State *g = G(L);
930+ if (g->lastmajormem == 0) { /* signal for another major collection? */
931+ luaC_fullgc(L, 0); /* perform a full regular collection */
932+ g->lastmajormem = g->totalbytes; /* update control */
933+ }
934+ else {
935+ luaC_runtilstate(L, bitmask(GCSpause)); /* run collection */
936+ if (g->totalbytes > g->lastmajormem/100 * g->gcpause)
937+ g->lastmajormem = 0; /* signal for a major collection */
938+ }
939+ g->GCdebt = stddebt(g);
940+}
941+
942+
943+static void step (lua_State *L) {
944+ global_State *g = G(L);
945+ l_mem lim = g->gcstepmul; /* how much to work */
946+ do { /* always perform at least one single step */
947+ lim -= singlestep(L);
948+ } while (lim > 0 && g->gcstate != GCSpause);
949+ if (g->gcstate != GCSpause)
950+ g->GCdebt -= GCSTEPSIZE;
951+ else
952+ g->GCdebt = stddebt(g);
953+}
954+
955+
956+void luaC_step (lua_State *L) {
957+ int i;
958+ if (isgenerational(G(L))) generationalcollection(L);
959+ else step(L);
960+ for (i = 0; i < GCFINALIZENUM && G(L)->tobefnz; i++)
961+ GCTM(L, 1); /* Call a few pending finalizers */
962+}
963+
964+
806965 /*
807−** performs a full GC cycle; if "isememrgency", does not call
966+** performs a full GC cycle; if "isemergency", does not call
808967 ** finalizers (which could change stack positions)
809968 */
810969 void luaC_fullgc (lua_State *L, int isemergency) {
811970 global_State *g = G(L);
812− lua_assert(g->gckind == KGC_NORMAL);
813− g->gckind = isemergency ? KGC_EMERGENCY : KGC_FORCED;
814− if (g->gcstate == GCSpropagate) { /* marking phase? */
971+ int origkind = g->gckind;
972+ lua_assert(origkind != KGC_EMERGENCY);
973+ if (!isemergency) /* do not run finalizers during emergency GC */
974+ callallpendingfinalizers(L, 1);
975+ if (keepinvariant(g)) { /* marking phase? */
815976 /* must sweep all objects to turn them back to white
816− (as white does not change, nothing will be collected) */
977+ (as white has not changed, nothing will be collected) */
817978 g->sweepstrgc = 0;
818979 g->gcstate = GCSsweepstring;
819980 }
820− /* finish any pending sweep phase */
821− luaC_runtilstate(L, ~bit2mask(GCSsweepstring, GCSsweep));
822− markroot(L); /* start a new collection */
823− /* run collector up to finalizers */
824− luaC_runtilstate(L, bitmask(GCSfinalize));
825− g->gckind = KGC_NORMAL;
981+ g->gckind = isemergency ? KGC_EMERGENCY : KGC_NORMAL;
982+ /* finish any pending sweep phase to start a new cycle */
983+ luaC_runtilstate(L, bitmask(GCSpause));
984+ /* run entire collector */
985+ luaC_runtilstate(L, ~bitmask(GCSpause));
986+ luaC_runtilstate(L, bitmask(GCSpause));
987+ if (origkind == KGC_GEN) { /* generational mode? */
988+ /* generational mode must always start in propagate phase */
989+ luaC_runtilstate(L, bitmask(GCSpropagate));
990+ }
991+ g->gckind = origkind;
992+ g->GCdebt = stddebt(g);
826993 if (!isemergency) /* do not run finalizers during emergency GC */
827− luaC_runtilstate(L, ~bitmask(GCSfinalize));
828− g->GCthreshold = (g->totalbytes/100) * g->gcpause;
994+ callallpendingfinalizers(L, 1);
829995 }
830996
831997 /* }====================================================== */
src/lgc.h+61−30
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lgc.h,v 2.27 2009/12/16 16:42:58 roberto Exp $
2+** $Id: lgc.h,v 2.41 2010/05/10 18:23:45 roberto Exp $
33 ** Garbage Collector
44 ** See Copyright Notice in lua.h
55 */
@@ -9,18 +9,51 @@ · 3 unmodified lines
99
1010
1111 #include "lobject.h"
12+#include "lstate.h"
13+
14+/*
15+** Collectable objects may have one of three colors: white, which
16+** means the object is not marked; gray, which means the
17+** object is marked, but its references may be not marked; and
18+** black, which means that the object and all its references are marked.
19+** The main invariant of the garbage collector, while marking objects,
20+** is that a black object can never point to a white one. Moreover,
21+** any gray object must be in a "gray list" (gray, grayagain, weak,
22+** allweak, ephemeron) so that it can be visited again before finishing
23+** the collection cycle. These lists have no meaning when the invariant
24+** is not being enforced (e.g., sweep phase).
25+*/
1226
1327
1428 /*
1529 ** Possible states of the Garbage Collector
1630 */
17−#define GCSpause 0
18−#define GCSpropagate 1
19−#define GCSatomic 2
20−#define GCSsweepstring 3
31+#define GCSpropagate 0
32+#define GCSatomic 1
33+#define GCSsweepstring 2
34+#define GCSsweepudata 3
2135 #define GCSsweep 4
22−#define GCSfinalize 5
36+#define GCSpause 5
37+
38+
39+#define issweepphase(g) \
40+ (GCSsweepstring <= (g)->gcstate && (g)->gcstate <= GCSsweep)
41+
42+#define isgenerational(g) ((g)->gckind == KGC_GEN)
43+
44+/*
45+** macro to tell when main invariant (white objects cannot point to black
46+** ones) must be kept. During a non-generational collection, the sweep
47+** phase may brak the invariant, as objects turned white may point to
48+** still-black objects. The invariant is restored when sweep ends and
49+** all objects are white again. During a generational collection, the
50+** invariant must be kept all times.
51+*/
52+#define keepinvariant(g) (isgenerational(g) || g->gcstate <= GCSatomic)
53+
2354
55+#define gcstopped(g) ((g)->GCdebt == MIN_LMEM)
56+#define stopgc(g) ((g)->GCdebt = MIN_LMEM)
2457
2558
2659 /*
@@ -39,34 +72,33 @@ · 12 unmodified lines
3972
4073
4174
42−/*
43−** Layout for bit use in `marked' field:
44−** bit 0 - object is white (type 0)
45−** bit 1 - object is white (type 1)
46−** bit 2 - object is black
47−** bit 3 - for userdata: has been finalized
48−** bit 4 - for userdata: it's in 2nd part of rootgc list or in tobefnz
49−** bit 5 - object is fixed (should not be collected)
50−** bit 6 - object is "super" fixed (only the main thread)
51−*/
52−
75+/* Layout for bit use in `marked' field: */
76+#define WHITE0BIT 0 /* object is white (type 0) */
77+#define WHITE1BIT 1 /* object is white (type 1) */
78+#define BLACKBIT 2 /* object is black */
79+#define FINALIZEDBIT 3 /* for userdata: has been finalized */
80+#define SEPARATED 4 /* " ": it's in 'udgc' list or in 'tobefnz' */
81+#define FIXEDBIT 5 /* object is fixed (should not be collected) */
82+#define OLDBIT 6 /* object is old (only in generational mode) */
83+/* bit 7 is currently used by tests (luaL_checkmemory) */
5384
54−#define WHITE0BIT 0
55−#define WHITE1BIT 1
56−#define BLACKBIT 2
57−#define FINALIZEDBIT 3
58−#define SEPARATED 4
59−#define FIXEDBIT 5
60−#define SFIXEDBIT 6
6185 #define WHITEBITS bit2mask(WHITE0BIT, WHITE1BIT)
6286
6387
6488 #define iswhite(x) testbits((x)->gch.marked, WHITEBITS)
6589 #define isblack(x) testbit((x)->gch.marked, BLACKBIT)
66−#define isgray(x) (!isblack(x) && !iswhite(x))
90+#define isgray(x) /* neither white nor black */ \
91+ (!testbits((x)->gch.marked, WHITEBITS | bitmask(BLACKBIT)))
92+
93+#define isold(x) testbit((x)->gch.marked, OLDBIT)
94+
95+/* MOVE OLD rule: whenever an object is moved to the beginning of
96+ a GC list, its old bit must be cleared */
97+#define resetoldbit(o) resetbit((o)->gch.marked, OLDBIT)
6798
6899 #define otherwhite(g) (g->currentwhite ^ WHITEBITS)
69−#define isdead(g,v) ((v)->gch.marked & otherwhite(g) & WHITEBITS)
100+#define isdeadm(ow,m) (!(((m) ^ WHITEBITS) & (ow)))
101+#define isdead(g,v) isdeadm(otherwhite(g), (v)->gch.marked)
70102
71103 #define changewhite(x) ((x)->gch.marked ^= WHITEBITS)
72104 #define gray2black(x) l_setbit((x)->gch.marked, BLACKBIT)
@@ -76,8 +108,7 @@ · 3 unmodified lines
76108 #define luaC_white(g) cast(lu_byte, (g)->currentwhite & WHITEBITS)
77109
78110
79−#define luaC_checkGC(L) \
80− {condchangemem(L); if (G(L)->totalbytes >= G(L)->GCthreshold) luaC_step(L);}
111+#define luaC_checkGC(L) {condchangemem(L); if (G(L)->GCdebt > 0) luaC_step(L);}
81112
82113
83114 #define luaC_barrier(L,p,v) { if (valiswhite(v) && isblack(obj2gco(p))) \
@@ -100,10 +131,10 @@ LUAI_FUNC void luaC_runtilstate (lua_State *L, int statesmask); · 16 unmodified lines
100131 LUAI_FUNC void luaC_fullgc (lua_State *L, int isemergency);
101132 LUAI_FUNC GCObject *luaC_newobj (lua_State *L, int tt, size_t sz,
102133 GCObject **list, int offset);
103−LUAI_FUNC void luaC_linkupval (lua_State *L, UpVal *uv);
104134 LUAI_FUNC void luaC_barrierf (lua_State *L, GCObject *o, GCObject *v);
105135 LUAI_FUNC void luaC_barrierback (lua_State *L, Table *t);
106136 LUAI_FUNC void luaC_checkfinalizer (lua_State *L, Udata *u);
107−
137+LUAI_FUNC void luaC_checkupvalcolor (global_State *g, UpVal *uv);
138+LUAI_FUNC void luaC_changemode (lua_State *L, int mode);
108139
109140 #endif
src/linit.c+4−5
@@ -1,5 +1,5 @@
11 /*
2−** $Id: linit.c,v 1.23 2009/12/22 15:32:50 roberto Exp $
2+** $Id: linit.c,v 1.24 2010/03/26 20:58:11 roberto Exp $
33 ** Initialization of libraries for lua.c and other clients
44 ** See Copyright Notice in lua.h
55 */
@@ -52,9 +52,9 @@ LUALIB_API void luaL_openlibs (lua_State *L) { · 46 unmodified lines
5252 const luaL_Reg *lib;
5353 /* call open functions from 'loadedlibs' */
5454 for (lib = loadedlibs; lib->func; lib++) {
55− lua_pushcfunction(L, lib->func);
55+ lua_settop(L, 0);
5656 lua_pushstring(L, lib->name);
57− lua_call(L, 1, 0);
57+ (lib->func)(L);
5858 }
5959 /* add open functions from 'preloadedlibs' into 'package.preload' table */
6060 lua_pushglobaltable(L);
@@ -65,8 +65,7 @@ LUALIB_API void luaL_openlibs (lua_State *L) { · 4 unmodified lines
6565 }
6666 lua_pop(L, 1); /* remove package.preload table */
6767 #if defined(LUA_COMPAT_DEBUGLIB)
68− lua_pushglobaltable(L);
69− lua_getfield(L, -1, "require");
68+ lua_getglobal(L, "require");
7069 lua_pushliteral(L, LUA_DBLIBNAME);
7170 lua_call(L, 1, 0); /* call 'require"debug"' */
7271 lua_pop(L, 1); /* remove global table */
src/liolib.c+82−47
@@ -1,5 +1,5 @@
11 /*
2−** $Id: liolib.c,v 2.85 2009/12/17 16:20:01 roberto Exp $
2+** $Id: liolib.c,v 2.88 2010/03/26 20:58:11 roberto Exp $
33 ** Standard I/O (and system) library
44 ** See Copyright Notice in lua.h
55 */
@@ -103,13 +103,12 @@ static FILE *tofile (lua_State *L) { · 97 unmodified lines
103103 }
104104
105105
106−
107106 /*
108107 ** When creating file handles, always creates a `closed' file handle
109108 ** before opening the actual file; so, if there is a memory error, the
110109 ** file is not left opened.
111110 */
112−static FILE **newfile (lua_State *L) {
111+static FILE **newprefile (lua_State *L) {
113112 FILE **pf = (FILE **)lua_newuserdata(L, sizeof(FILE *));
114113 *pf = NULL; /* file handle is currently `closed' */
115114 luaL_getmetatable(L, LUA_FILEHANDLE);
@@ -118,6 +117,14 @@ static FILE **newfile (lua_State *L) { · 2 unmodified lines
118117 }
119118
120119
120+static FILE **newfile (lua_State *L) {
121+ FILE **pf = newprefile(L);
122+ lua_pushvalue(L, lua_upvalueindex(1)); /* set upvalue... */
123+ lua_setenv(L, -2); /* ... as environment for new file */
124+ return pf;
125+}
126+
127+
121128 /*
122129 ** function to (not) close the standard files stdin, stdout, and stderr
123130 */
@@ -156,7 +163,7 @@ static int io_fclose (lua_State *L) { · 32 unmodified lines
156163
157164
158165 static int aux_close (lua_State *L) {
159− lua_getfenv(L, 1);
166+ lua_getenv(L, 1);
160167 lua_getfield(L, -1, "__close");
161168 return (lua_tocfunction(L, -1))(L);
162169 }
@@ -164,7 +171,7 @@ static int aux_close (lua_State *L) { · 1 unmodified line
164171
165172 static int io_close (lua_State *L) {
166173 if (lua_isnone(L, 1))
167− lua_rawgeti(L, LUA_ENVIRONINDEX, IO_OUTPUT);
174+ lua_rawgeti(L, lua_upvalueindex(1), IO_OUTPUT);
168175 tofile(L); /* make sure argument is a file */
169176 return aux_close(L);
170177 }
@@ -229,7 +236,7 @@ static int io_tmpfile (lua_State *L) { · 58 unmodified lines
229236
230237 static FILE *getiofile (lua_State *L, int findex) {
231238 FILE *f;
232− lua_rawgeti(L, LUA_ENVIRONINDEX, findex);
239+ lua_rawgeti(L, lua_upvalueindex(1), findex);
233240 f = *(FILE **)lua_touserdata(L, -1);
234241 if (f == NULL)
235242 luaL_error(L, "standard %s file is closed", fnames[findex - 1]);
@@ -250,10 +257,10 @@ static int g_iofile (lua_State *L, int f, const char *mode) { · 14 unmodified lines
250257 tofile(L); /* check that it's a valid file handle */
251258 lua_pushvalue(L, 1);
252259 }
253− lua_rawseti(L, LUA_ENVIRONINDEX, f);
260+ lua_rawseti(L, lua_upvalueindex(1), f);
254261 }
255262 /* return current value */
256− lua_rawgeti(L, LUA_ENVIRONINDEX, f);
263+ lua_rawgeti(L, lua_upvalueindex(1), f);
257264 return 1;
258265 }
259266
@@ -271,35 +278,46 @@ static int io_output (lua_State *L) { · 11 unmodified lines
271278 static int io_readline (lua_State *L);
272279
273280
274−static void aux_lines (lua_State *L, int idx, int toclose) {
275− lua_pushvalue(L, idx);
281+static void aux_lines (lua_State *L, int toclose) {
282+ int i;
283+ int n = lua_gettop(L) - 1; /* number of arguments to read */
284+ /* ensure that arguments will fit here and into 'io_readline' stack */
285+ luaL_argcheck(L, n <= LUA_MINSTACK - 3, LUA_MINSTACK - 3, "too many options");
286+ lua_pushvalue(L, 1); /* file handle */
287+ lua_pushinteger(L, n); /* number of arguments to read */
276288 lua_pushboolean(L, toclose); /* close/not close file when finished */
277− lua_pushcclosure(L, io_readline, 2);
289+ for (i = 1; i <= n; i++) lua_pushvalue(L, i + 1); /* copy arguments */
290+ lua_pushcclosure(L, io_readline, 3 + n);
278291 }
279292
280293
281294 static int f_lines (lua_State *L) {
282295 tofile(L); /* check that it's a valid file handle */
283− aux_lines(L, 1, 0);
296+ aux_lines(L, 0);
284297 return 1;
285298 }
286299
287300
288301 static int io_lines (lua_State *L) {
289− if (lua_isnoneornil(L, 1)) { /* no arguments? */
290− /* will iterate over default input */
291− lua_rawgeti(L, LUA_ENVIRONINDEX, IO_INPUT);
292− return f_lines(L);
302+ int toclose;
303+ if (lua_isnone(L, 1)) lua_pushnil(L); /* at least one argument */
304+ if (lua_isnil(L, 1)) { /* no file name? */
305+ lua_rawgeti(L, lua_upvalueindex(1), IO_INPUT); /* get default input */
306+ lua_replace(L, 1); /* put it at index 1 */
307+ tofile(L); /* check that it's a valid file handle */
308+ toclose = 0; /* do not close it after iteration */
293309 }
294− else {
310+ else { /* open a new file */
295311 const char *filename = luaL_checkstring(L, 1);
296312 FILE **pf = newfile(L);
297313 *pf = fopen(filename, "r");
298314 if (*pf == NULL)
299315 fileerror(L, 1, filename);
300− aux_lines(L, lua_gettop(L), 1);
301− return 1;
316+ lua_replace(L, 1); /* put file at index 1 */
317+ toclose = 1; /* close it after iteration */
302318 }
319+ aux_lines(L, toclose);
320+ return 1;
303321 }
304322
305323
@@ -316,7 +334,10 @@ static int read_number (lua_State *L, FILE *f) { · 10 unmodified lines
316334 lua_pushnumber(L, d);
317335 return 1;
318336 }
319− else return 0; /* read fails */
337+ else {
338+ lua_pushnil(L); /* "result" to be removed */
339+ return 0; /* read fails */
340+ }
320341 }
321342
322343
@@ -328,7 +349,7 @@ static int test_eof (lua_State *L, FILE *f) { · 5 unmodified lines
328349 }
329350
330351
331−static int read_line (lua_State *L, FILE *f) {
352+static int read_line (lua_State *L, FILE *f, int chop) {
332353 luaL_Buffer b;
333354 luaL_buffinit(L, &b);
334355 for (;;) {
@@ -342,7 +363,7 @@ static int read_line (lua_State *L, FILE *f) { · 7 unmodified lines
342363 if (l == 0 || p[l-1] != '\n')
343364 luaL_addsize(&b, l);
344365 else {
345− luaL_addsize(&b, l - 1); /* do not include `eol' */
366+ luaL_addsize(&b, l - chop); /* chop 'eol' if needed */
346367 luaL_pushresult(&b); /* close buffer */
347368 return 1; /* read at least an `eol' */
348369 }
@@ -375,7 +396,7 @@ static int g_read (lua_State *L, FILE *f, int first) { · 26 unmodified lines
375396 int n;
376397 clearerr(f);
377398 if (nargs == 0) { /* no arguments? */
378− success = read_line(L, f);
399+ success = read_line(L, f, 1);
379400 n = first+1; /* to return 1 result */
380401 }
381402 else { /* ensure stack space for all results and for auxlib's buffer */
@@ -394,7 +415,10 @@ static int g_read (lua_State *L, FILE *f, int first) { · 12 unmodified lines
394415 success = read_number(L, f);
395416 break;
396417 case 'l': /* line */
397− success = read_line(L, f);
418+ success = read_line(L, f, 1);
419+ break;
420+ case 'L': /* line with end-of-line */
421+ success = read_line(L, f, 0);
398422 break;
399423 case 'a': /* file */
400424 read_chars(L, f, ~((size_t)0)); /* read MAX_SIZE_T chars */
@@ -428,15 +452,22 @@ static int f_read (lua_State *L) { · 27 unmodified lines
428452
429453 static int io_readline (lua_State *L) {
430454 FILE *f = *(FILE **)lua_touserdata(L, lua_upvalueindex(1));
431− int success;
455+ int i;
456+ int n = lua_tointeger(L, lua_upvalueindex(2));
432457 if (f == NULL) /* file is already closed? */
433458 luaL_error(L, "file is already closed");
434− success = read_line(L, f);
435− if (ferror(f))
436− return luaL_error(L, "%s", strerror(errno));
437− if (success) return 1;
438− else { /* EOF */
439− if (lua_toboolean(L, lua_upvalueindex(2))) { /* generator created file? */
459+ lua_settop(L , 1);
460+ for (i = 1; i <= n; i++) /* push arguments to 'g_read' */
461+ lua_pushvalue(L, lua_upvalueindex(3 + i));
462+ n = g_read(L, f, 2); /* 'n' is number of results */
463+ lua_assert(n > 0); /* should return at least a nil */
464+ if (!lua_isnil(L, -n)) /* read at least one value? */
465+ return n; /* return them */
466+ else { /* first result is nil: EOF or error */
467+ if (!lua_isnil(L, -1)) /* is there error information? */
468+ return luaL_error(L, "%s", lua_tostring(L, -1)); /* error */
469+ /* else EOF */
470+ if (lua_toboolean(L, lua_upvalueindex(3))) { /* generator created file? */
440471 lua_settop(L, 0);
441472 lua_pushvalue(L, lua_upvalueindex(1));
442473 aux_close(L); /* close it */
@@ -552,23 +583,27 @@ static void createmeta (lua_State *L) { · 109 unmodified lines
552583 luaL_newmetatable(L, LUA_FILEHANDLE); /* create metatable for file handles */
553584 lua_pushvalue(L, -1); /* push metatable */
554585 lua_setfield(L, -2, "__index"); /* metatable.__index = metatable */
555− luaL_register(L, NULL, flib); /* file methods */
586+ luaL_register(L, NULL, flib); /* add file methods to new metatable */
587+ lua_pop(L, 1); /* pop new metatable */
556588 }
557589
558590
559591 static void createstdfile (lua_State *L, FILE *f, int k, const char *fname) {
560− *newfile(L) = f;
592+ *newprefile(L) = f;
561593 if (k > 0) {
562− lua_pushvalue(L, -1);
563− lua_rawseti(L, LUA_ENVIRONINDEX, k);
594+ lua_pushvalue(L, -1); /* copy new file */
595+ lua_rawseti(L, 1, k); /* add it to common upvalue */
564596 }
565− lua_pushvalue(L, -2); /* copy environment */
566− lua_setfenv(L, -2); /* set it */
567− lua_setfield(L, -3, fname);
597+ lua_pushvalue(L, 3); /* get environment for default files */
598+ lua_setenv(L, -2); /* set it as environment for file */
599+ lua_setfield(L, 2, fname); /* add file to module */
568600 }
569601
570602
571−static void newfenv (lua_State *L, lua_CFunction cls) {
603+/*
604+** pushes a new table with {__close = cls}
605+*/
606+static void newenv (lua_State *L, lua_CFunction cls) {
572607 lua_createtable(L, 0, 1);
573608 lua_pushcfunction(L, cls);
574609 lua_setfield(L, -2, "__close");
@@ -576,21 +611,21 @@ static void newfenv (lua_State *L, lua_CFunction cls) { · 1 unmodified line
576611
577612
578613 LUAMOD_API int luaopen_io (lua_State *L) {
614+ lua_settop(L, 0);
579615 createmeta(L);
580616 /* create (private) environment (with fields IO_INPUT, IO_OUTPUT, __close) */
581− newfenv(L, io_fclose);
582− lua_replace(L, LUA_ENVIRONINDEX);
583− /* open library */
584− luaL_register(L, LUA_IOLIBNAME, iolib);
617+ newenv(L, io_fclose); /* upvalue for all io functions at index 1 */
618+ lua_pushvalue(L, -1); /* copy to be consumed by 'openlib' */
619+ luaL_openlib(L, LUA_IOLIBNAME, iolib, 1); /* new module at index 2 */
585620 /* create (and set) default files */
586− newfenv(L, io_noclose); /* close function for default files */
621+ newenv(L, io_noclose); /* environment for default files at index 3 */
587622 createstdfile(L, stdin, IO_INPUT, "stdin");
588623 createstdfile(L, stdout, IO_OUTPUT, "stdout");
589624 createstdfile(L, stderr, 0, "stderr");
590625 lua_pop(L, 1); /* pop environment for default files */
591− lua_getfield(L, -1, "popen");
592− newfenv(L, io_pclose); /* create environment for 'popen' */
593− lua_setfenv(L, -2); /* set fenv for 'popen' */
626+ lua_getfield(L, 2, "popen");
627+ newenv(L, io_pclose); /* create environment for 'popen' streams */
628+ lua_setupvalue(L, -2, 1); /* set it as upvalue for 'popen' */
594629 lua_pop(L, 1); /* pop 'popen' */
595630 return 1;
596631 }
src/llex.c+69−47
@@ -1,5 +1,5 @@
11 /*
2−** $Id: llex.c,v 2.34 2009/11/17 16:33:38 roberto Exp $
2+** $Id: llex.c,v 2.37 2010/04/16 12:31:07 roberto Exp $
33 ** Lexical Analyzer
44 ** See Copyright Notice in lua.h
55 */
@@ -117,21 +117,30 @@ void luaX_syntaxerror (LexState *ls, const char *msg) { · 111 unmodified lines
117117 }
118118
119119
120+/*
121+** creates a new string and anchors it in function's table so that
122+** it will not be collected until the end of the function's compilation
123+** (by that time it should be anchored in function's prototype)
124+*/
120125 TString *luaX_newstring (LexState *ls, const char *str, size_t l) {
121126 lua_State *L = ls->L;
122127 TValue *o; /* entry for `str' */
123− TString *ts = luaS_newlstr(L, str, l);
124− setsvalue2s(L, L->top++, ts); /* anchor string */
125− o = luaH_setstr(L, ls->fs->h, ts);
128+ TString *ts = luaS_newlstr(L, str, l); /* create new string */
129+ setsvalue2s(L, L->top++, ts); /* temporarily anchor it in stack */
130+ o = luaH_setstr(L, ls->fs->h, ts);
126131 if (ttisnil(o)) {
127− setbvalue(o, 1); /* make sure `str' will not be collected */
132+ setbvalue(o, 1); /* t[string] = true */
128133 luaC_checkGC(L);
129134 }
130− L->top--;
135+ L->top--; /* remove string from stack */
131136 return ts;
132137 }
133138
134139
140+/*
141+** increment line number and skips newline sequence (any of
142+** \n, \r, \n\r, or \r\n)
143+*/
135144 static void inclinenumber (LexState *ls) {
136145 int old = ls->current;
137146 lua_assert(currIsNewline(ls));
@@ -152,6 +161,8 @@ void luaX_setinput (lua_State *L, LexState *ls, ZIO *z, TString *source) { · 14 unmodified lines
152161 ls->linenumber = 1;
153162 ls->lastline = 1;
154163 ls->source = source;
164+ ls->envn = luaS_new(L, "_ENV"); /* create env name */
165+ luaS_fix(ls->envn); /* never collect this name */
155166 luaZ_resizebuffer(ls->L, ls->buff, LUA_MINBUFFER); /* initialize buffer */
156167 next(ls); /* read first char */
157168 }
@@ -174,6 +185,9 @@ static int check_next (LexState *ls, const char *set) { · 16 unmodified lines
174185 }
175186
176187
188+/*
189+** change all characters 'from' in buffer to 'to'
190+*/
177191 static void buffreplace (LexState *ls, char from, char to) {
178192 size_t n = luaZ_bufflen(ls->buff);
179193 char *p = luaZ_buffer(ls->buff);
@@ -186,11 +200,14 @@ static void buffreplace (LexState *ls, char from, char to) { · 6 unmodified lines
186200 #define getlocaledecpoint() (localeconv()->decimal_point[0])
187201 #endif
188202
203+/*
204+** in case of format error, try to change decimal point separator to
205+** the one defined in the current locale and check again
206+*/
189207 static void trydecpoint (LexState *ls, SemInfo *seminfo) {
190− /* format error: try to update decimal point separator */
191208 char old = ls->decpoint;
192209 ls->decpoint = getlocaledecpoint();
193− buffreplace(ls, old, ls->decpoint); /* try updated decimal separator */
210+ buffreplace(ls, old, ls->decpoint); /* try new decimal separator */
194211 if (!luaO_str2d(luaZ_buffer(ls->buff), &seminfo->r)) {
195212 /* format error with correct decimal point: no more options */
196213 buffreplace(ls, ls->decpoint, '.'); /* undo change (for error message) */
@@ -216,6 +233,10 @@ static void read_numeral (LexState *ls, SemInfo *seminfo) { · 19 unmodified lines
216233 }
217234
218235
236+/*
237+** skip a sequence '[=*=[' or ']=*]' and return its number of '='s or
238+** -1 if sequence is malformed
239+*/
219240 static int skip_sep (LexState *ls) {
220241 int count = 0;
221242 int s = ls->current;
@@ -246,8 +267,7 @@ static void read_long_string (LexState *ls, SemInfo *seminfo, int sep) { · 24 unmodified lines
246267 }
247268 break;
248269 }
249− case '\n':
250− case '\r': {
270+ case '\n': case '\r': {
251271 save(ls, '\n');
252272 inclinenumber(ls);
253273 if (!seminfo) luaZ_resetbuffer(ls->buff); /* avoid wasting space */
@@ -308,16 +328,16 @@ static int readdecesc (LexState *ls) { · 54 unmodified lines
308328
309329
310330 static void read_string (LexState *ls, int del, SemInfo *seminfo) {
311− save_and_next(ls);
331+ save_and_next(ls); /* keep delimiter (for error messages) */
312332 while (ls->current != del) {
313333 switch (ls->current) {
314334 case EOZ:
315335 lexerror(ls, "unfinished string", TK_EOS);
316− continue; /* to avoid warnings */
336+ break; /* to avoid warnings */
317337 case '\n':
318338 case '\r':
319339 lexerror(ls, "unfinished string", TK_STRING);
320− continue; /* to avoid warnings */
340+ break; /* to avoid warnings */
321341 case '\\': { /* escape sequences */
322342 int c; /* final character to be saved */
323343 next(ls); /* do not save the `\' */
@@ -333,6 +353,14 @@ static void read_string (LexState *ls, int del, SemInfo *seminfo) { · 9 unmodified lines
333353 case '\n':
334354 case '\r': save(ls, '\n'); inclinenumber(ls); continue;
335355 case EOZ: continue; /* will raise an error next loop */
356+ case '*': { /* skip following span of spaces */
357+ next(ls); /* skip the '*' */
358+ while (lisspace(ls->current)) {
359+ if (currIsNewline(ls)) inclinenumber(ls);
360+ else next(ls);
361+ }
362+ continue; /* do not save 'c' */
363+ }
336364 default: {
337365 if (!lisdigit(ls->current))
338366 c = ls->current; /* handles \\, \", \', and \? */
@@ -343,7 +371,7 @@ static void read_string (LexState *ls, int del, SemInfo *seminfo) { · 4 unmodified lines
343371 }
344372 next(ls);
345373 save(ls, c);
346− continue;
374+ break;
347375 }
348376 default:
349377 save_and_next(ls);
@@ -359,31 +387,34 @@ static int llex (LexState *ls, SemInfo *seminfo) { · 9 unmodified lines
359387 luaZ_resetbuffer(ls->buff);
360388 for (;;) {
361389 switch (ls->current) {
362− case '\n':
363− case '\r': {
390+ case '\n': case '\r': { /* line breaks */
364391 inclinenumber(ls);
365− continue;
392+ break;
366393 }
367− case '-': {
394+ case ' ': case '\f': case '\t': case '\v': { /* spaces */
395+ next(ls);
396+ break;
397+ }
398+ case '-': { /* '-' or '--' (comment) */
368399 next(ls);
369400 if (ls->current != '-') return '-';
370401 /* else is a comment */
371402 next(ls);
372− if (ls->current == '[') {
403+ if (ls->current == '[') { /* long comment? */
373404 int sep = skip_sep(ls);
374405 luaZ_resetbuffer(ls->buff); /* `skip_sep' may dirty the buffer */
375406 if (sep >= 0) {
376− read_long_string(ls, NULL, sep); /* long comment */
377− luaZ_resetbuffer(ls->buff);
378− continue;
407+ read_long_string(ls, NULL, sep); /* skip long comment */
408+ luaZ_resetbuffer(ls->buff); /* previous call may dirty the buff. */
409+ break;
379410 }
380411 }
381412 /* else short comment */
382413 while (!currIsNewline(ls) && ls->current != EOZ)
383− next(ls);
384− continue;
414+ next(ls); /* skip until end of line (or end of file) */
415+ break;
385416 }
386− case '[': {
417+ case '[': { /* long string or simply '[' */
387418 int sep = skip_sep(ls);
388419 if (sep >= 0) {
389420 read_long_string(ls, seminfo, sep);
@@ -412,39 +443,30 @@ static int llex (LexState *ls, SemInfo *seminfo) { · 22 unmodified lines
412443 if (ls->current != '=') return '~';
413444 else { next(ls); return TK_NE; }
414445 }
415− case '"':
416− case '\'': {
446+ case '"': case '\'': { /* short literal strings */
417447 read_string(ls, ls->current, seminfo);
418448 return TK_STRING;
419449 }
420− case '.': {
450+ case '.': { /* '.', '..', '...', or number */
421451 save_and_next(ls);
422452 if (check_next(ls, ".")) {
423453 if (check_next(ls, "."))
424− return TK_DOTS; /* ... */
425− else return TK_CONCAT; /* .. */
454+ return TK_DOTS; /* '...' */
455+ else return TK_CONCAT; /* '..' */
426456 }
427457 else if (!lisdigit(ls->current)) return '.';
428− else {
429− read_numeral(ls, seminfo);
430− return TK_NUMBER;
431− }
458+ /* else go through */
459+ }
460+ case '0': case '1': case '2': case '3': case '4':
461+ case '5': case '6': case '7': case '8': case '9': {
462+ read_numeral(ls, seminfo);
463+ return TK_NUMBER;
432464 }
433465 case EOZ: {
434466 return TK_EOS;
435467 }
436468 default: {
437− if (lisspace(ls->current)) {
438− lua_assert(!currIsNewline(ls));
439− next(ls);
440− continue;
441− }
442− else if (lisdigit(ls->current)) {
443− read_numeral(ls, seminfo);
444− return TK_NUMBER;
445− }
446− else if (lislalpha(ls->current)) {
447− /* identifier or reserved word */
469+ if (lislalpha(ls->current)) { /* identifier or reserved word? */
448470 TString *ts;
449471 do {
450472 save_and_next(ls);
@@ -458,10 +480,10 @@ static int llex (LexState *ls, SemInfo *seminfo) { · 7 unmodified lines
458480 return TK_NAME;
459481 }
460482 }
461− else {
483+ else { /* single-char tokens (+ - / ...) */
462484 int c = ls->current;
463485 next(ls);
464− return c; /* single-char tokens (+ - / ...) */
486+ return c;
465487 }
466488 }
467489 }
src/llex.h+2−1
@@ -1,5 +1,5 @@
11 /*
2−** $Id: llex.h,v 1.62 2009/10/11 20:02:19 roberto Exp $
2+** $Id: llex.h,v 1.65 2010/04/05 16:35:37 roberto Exp $
33 ** Lexical Analyzer
44 ** See Copyright Notice in lua.h
55 */
@@ -60,6 +60,7 @@ typedef struct LexState { · 54 unmodified lines
6060 Mbuffer *buff; /* buffer for tokens */
6161 struct Varlist *varl; /* list of all active local variables */
6262 TString *source; /* current source name */
63+ TString *envn; /* environment variable name */
6364 char decpoint; /* locale decimal point */
6465 } LexState;
6566
src/llimits.h+7−6
@@ -1,5 +1,5 @@
11 /*
2−** $Id: llimits.h,v 1.77 2009/12/17 12:50:20 roberto Exp $
2+** $Id: llimits.h,v 1.80 2010/05/07 18:44:12 roberto Exp $
33 ** Limits, basic types, and some other `installation-dependent' definitions
44 ** See Copyright Notice in lua.h
55 */
@@ -30,6 +30,7 @@ typedef unsigned char lu_byte; · 24 unmodified lines
3030 #define MAX_SIZET ((size_t)(~(size_t)0)-2)
3131
3232 #define MAX_LUMEM ((lu_mem)(~(lu_mem)0)-2)
33+#define MIN_LMEM ((l_mem)~((~(lu_mem)0)>>1))
3334
3435
3536 #define MAX_INT (INT_MAX-2) /* maximum value of an int (-2 for safety) */
@@ -59,7 +60,7 @@ typedef LUAI_UACNUMBER l_uacNumber; · 23 unmodified lines
5960 #if defined(lua_assert)
6061 #define check_exp(c,e) (lua_assert(c), (e))
6162 #else
62−#define lua_assert(c) ((void)0)
63+#define lua_assert(c) /* empty */
6364 #define check_exp(c,e) (e)
6465 #endif
6566
@@ -139,19 +140,19 @@ typedef lu_int32 Instruction; · 73 unmodified lines
139140 ** created/deleted/resumed/yielded.
140141 */
141142 #if !defined(luai_userstateopen)
142−#define luai_userstateopen(L) ((void)L)
143+#define luai_userstateopen(L) ((void)L)
143144 #endif
144145
145146 #if !defined(luai_userstateclose)
146−#define luai_userstateclose(L) ((void)L)
147+#define luai_userstateclose(L) ((void)L)
147148 #endif
148149
149150 #if !defined(luai_userstatethread)
150−#define luai_userstatethread(L,L1) ((void)L)
151+#define luai_userstatethread(L,L1) ((void)L)
151152 #endif
152153
153154 #if !defined(luai_userstatefree)
154−#define luai_userstatefree(L) ((void)L)
155+#define luai_userstatefree(L,L1) ((void)L)
155156 #endif
156157
157158 #if !defined(luai_userstateresume)
src/lmem.c+25−4
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lmem.c,v 1.74 2009/12/16 16:42:58 roberto Exp $
2+** $Id: lmem.c,v 1.79 2010/05/05 18:49:56 roberto Exp $
33 ** Interface to Memory Manager
44 ** See Copyright Notice in lua.h
55 */
@@ -79,13 +79,14 @@ void *luaM_realloc_ (lua_State *L, void *block, size_t osize, size_t nsize) { · 73 unmodified lines
7979 size_t realosize = (block) ? osize : 0;
8080 lua_assert((realosize == 0) == (block == NULL));
8181 #if defined(HARDMEMTESTS)
82− if (nsize > realosize && g->GCthreshold != MAX_LUMEM)
82+ if (nsize > realosize && !gcstopped(g))
8383 luaC_fullgc(L, 1); /* force a GC whenever possible */
8484 #endif
8585 newblock = (*g->frealloc)(g->ud, block, osize, nsize);
8686 if (newblock == NULL && nsize > 0) {
87− lua_assert(nsize > realosize); /* cannot fail when shrinking a block */
88− if (g->GCthreshold != MAX_LUMEM) {
87+ api_check(L, nsize > realosize,
88+ "realloc cannot fail when shrinking a block");
89+ if (!gcstopped(g)) {
8990 luaC_fullgc(L, 1); /* try to free some memory... */
9091 newblock = (*g->frealloc)(g->ud, block, osize, nsize); /* try again */
9192 }
@@ -94,6 +95,26 @@ void *luaM_realloc_ (lua_State *L, void *block, size_t osize, size_t nsize) { · 2 unmodified lines
9495 }
9596 lua_assert((nsize == 0) == (newblock == NULL));
9697 g->totalbytes = (g->totalbytes - realosize) + nsize;
98+ if (!gcstopped(g))
99+ g->GCdebt += nsize; /* give some credit to garbage collector */
100+#if defined(TRACEMEM)
101+ { /* auxiliary patch to monitor garbage collection.
102+ ** To plot, gnuplot with following command:
103+ ** plot TRACEMEM using 1:2 with lines, TRACEMEM using 1:3 with lines
104+ */
105+ static unsigned long total = 0; /* our "time" */
106+ static FILE *f = NULL; /* output file */
107+ total++; /* "time" always grows */
108+ if ((total % 200) == 0) {
109+ if (f == NULL) f = fopen(TRACEMEM, "w");
110+ fprintf(f, "%lu %u %d %d\n", total,
111+ g->totalbytes,
112+ gcstopped(g) ? 0 : g->GCdebt,
113+ g->gcstate * 1000);
114+ }
115+ }
116+#endif
117+
97118 return newblock;
98119 }
99120
src/lmem.h+1−3
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lmem.h,v 1.35 2009/12/16 16:42:58 roberto Exp $
2+** $Id: lmem.h,v 1.36 2010/04/08 17:16:46 roberto Exp $
33 ** Interface to Memory Manager
44 ** See Copyright Notice in lua.h
55 */
@@ -13,8 +13,6 @@ · 7 unmodified lines
1313 #include "llimits.h"
1414 #include "lua.h"
1515
16−#define MEMERRMSG "not enough memory"
17−
1816
1917 #define luaM_reallocv(L,b,on,n,e) \
2018 ((cast(size_t, (n)+1) <= MAX_SIZET/(e)) ? /* +1 to avoid warnings */ \
src/loadlib.c+17−14
@@ -1,5 +1,5 @@
11 /*
2−** $Id: loadlib.c,v 1.80 2010/01/13 16:30:27 roberto Exp $
2+** $Id: loadlib.c,v 1.82 2010/03/19 15:02:34 roberto Exp $
33 ** Dynamic library loader for Lua
44 ** See Copyright Notice in lua.h
55 **
@@ -353,9 +353,7 @@ static int ll_loadfunc (lua_State *L, const char *path, const char *sym) { · 347 unmodified lines
353353 lua_CFunction f = ll_sym(L, *reg, sym);
354354 if (f == NULL)
355355 return ERRFUNC; /* unable to find function */
356− lua_pushcfunction(L, f); /* else create new function... */
357− lua_pushglobaltable(L); /* ... and set the standard global table... */
358− lua_setfenv(L, -2); /* ... as its environment */
356+ lua_pushcfunction(L, f); /* else create new function */
359357 return 0; /* no errors */
360358 }
361359 }
@@ -435,7 +433,7 @@ static int ll_searchpath (lua_State *L) { · 73 unmodified lines
435433 static const char *findfile (lua_State *L, const char *name,
436434 const char *pname) {
437435 const char *path;
438− lua_getfield(L, LUA_ENVIRONINDEX, pname);
436+ lua_getfield(L, lua_upvalueindex(1), pname);
439437 path = lua_tostring(L, -1);
440438 if (path == NULL)
441439 luaL_error(L, LUA_QL("package.%s") " must be a string", pname);
@@ -509,7 +507,7 @@ static int loader_Croot (lua_State *L) { · 67 unmodified lines
509507
510508 static int loader_preload (lua_State *L) {
511509 const char *name = luaL_checkstring(L, 1);
512− lua_getfield(L, LUA_ENVIRONINDEX, "preload");
510+ lua_getfield(L, lua_upvalueindex(1), "preload");
513511 if (!lua_istable(L, -1))
514512 luaL_error(L, LUA_QL("package.preload") " must be a table");
515513 lua_getfield(L, -1, name);
@@ -535,7 +533,7 @@ static int ll_require (lua_State *L) { · 19 unmodified lines
535533 return 1; /* package is already loaded */
536534 }
537535 /* else must load it; iterate over available loaders */
538− lua_getfield(L, LUA_ENVIRONINDEX, "loaders");
536+ lua_getfield(L, lua_upvalueindex(1), "loaders");
539537 if (!lua_istable(L, -1))
540538 luaL_error(L, LUA_QL("package.loaders") " must be a table");
541539 lua_pushliteral(L, ""); /* error message accumulator */
@@ -579,14 +577,18 @@ static int ll_require (lua_State *L) { · 37 unmodified lines
579577 */
580578
581579
582−static void setfenv (lua_State *L) {
580+/*
581+** FOR COMPATIBILITY ONLY: changes the _ENV variable of
582+** calling function
583+*/
584+static void set_env (lua_State *L) {
583585 lua_Debug ar;
584586 if (lua_getstack(L, 1, &ar) == 0 ||
585587 lua_getinfo(L, "f", &ar) == 0 || /* get calling function */
586588 lua_iscfunction(L, -1))
587589 luaL_error(L, LUA_QL("module") " not called from a Lua function");
588590 lua_pushvalue(L, -2); /* copy new environment table to top */
589− lua_setfenv(L, -2);
591+ lua_setupvalue(L, -2, 1);
590592 lua_pop(L, 1); /* remove function */
591593 }
592594
@@ -639,7 +641,7 @@ static int ll_module (lua_State *L) { · 46 unmodified lines
639641 modinit(L, modname);
640642 }
641643 lua_pushvalue(L, -1);
642− setfenv(L);
644+ set_env(L);
643645 dooptions(L, loaded - 1);
644646 return 1;
645647 }
@@ -709,12 +711,12 @@ LUAMOD_API int luaopen_package (lua_State *L) { · 63 unmodified lines
709711 lua_setfield(L, -2, "__gc");
710712 /* create `package' table */
711713 luaL_register(L, LUA_LOADLIBNAME, pk_funcs);
712− lua_copy(L, -1, LUA_ENVIRONINDEX);
713714 /* create `loaders' table */
714715 lua_createtable(L, sizeof(loaders)/sizeof(loaders[0]) - 1, 0);
715716 /* fill it with pre-defined loaders */
716717 for (i=0; loaders[i] != NULL; i++) {
717− lua_pushcfunction(L, loaders[i]);
718+ lua_pushvalue(L, -2); /* set 'package' as upvalue for all loaders */
719+ lua_pushcclosure(L, loaders[i], 1);
718720 lua_rawseti(L, -2, i+1);
719721 }
720722 lua_setfield(L, -2, "loaders"); /* put it in field `loaders' */
@@ -731,8 +733,9 @@ LUAMOD_API int luaopen_package (lua_State *L) { · 10 unmodified lines
731733 lua_newtable(L);
732734 lua_setfield(L, -2, "preload");
733735 lua_pushglobaltable(L);
734− luaL_register(L, NULL, ll_funcs); /* open lib into global table */
735− lua_pop(L, 1);
736+ lua_pushvalue(L, -2); /* set 'package' as upvalue for next lib */
737+ luaL_openlib(L, NULL, ll_funcs, 1); /* open lib into global table */
738+ lua_pop(L, 1); /* pop global table */
736739 return 1; /* return 'package' table */
737740 }
738741
src/lobject.c+19−19
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lobject.c,v 2.34 2009/11/26 11:39:20 roberto Exp $
2+** $Id: lobject.c,v 2.40 2010/04/18 13:22:48 roberto Exp $
33 ** Some generic functions over Lua objects
44 ** See Copyright Notice in lua.h
55 */
@@ -81,6 +81,10 @@ int luaO_rawequalObj (const TValue *t1, const TValue *t2) { · 75 unmodified lines
8181 return bvalue(t1) == bvalue(t2); /* boolean true must be 1 !! */
8282 case LUA_TLIGHTUSERDATA:
8383 return pvalue(t1) == pvalue(t2);
84+ case LUA_TSTRING:
85+ return rawtsvalue(t1) == rawtsvalue(t2);
86+ case LUA_TLCF:
87+ return fvalue(t1) == fvalue(t2);
8488 default:
8589 lua_assert(iscollectable(t1));
8690 return gcvalue(t1) == gcvalue(t2);
@@ -96,7 +100,7 @@ lua_Number luaO_arith (int op, lua_Number v1, lua_Number v2) { · 9 unmodified lines
96100 case LUA_OPDIV: return luai_numdiv(NULL, v1, v2);
97101 case LUA_OPMOD: return luai_nummod(NULL, v1, v2);
98102 case LUA_OPPOW: return luai_numpow(NULL, v1, v2);
99− case LUA_OPUNM: return luai_numunm(N, v1);
103+ case LUA_OPUNM: return luai_numunm(NULL, v1);
100104 default: lua_assert(0); return 0;
101105 }
102106 }
@@ -108,24 +112,21 @@ int luaO_str2d (const char *s, lua_Number *result) { · 5 unmodified lines
108112 if (endptr == s) return 0; /* conversion failed */
109113 if (*endptr == 'x' || *endptr == 'X') /* maybe an hexadecimal constant? */
110114 *result = cast_num(strtoul(s, &endptr, 16));
111− if (*endptr == '\0') return 1; /* most common case */
112115 while (lisspace(cast(unsigned char, *endptr))) endptr++;
113− if (*endptr != '\0') return 0; /* invalid trailing characters? */
114− return 1;
116+ return (*endptr == '\0'); /* OK if no trailing characters */
115117 }
116118
117119
118120
119−static void pushstr (lua_State *L, const char *str) {
120− setsvalue2s(L, L->top, luaS_new(L, str));
121+static void pushstr (lua_State *L, const char *str, size_t l) {
122+ setsvalue2s(L, L->top, luaS_newlstr(L, str, l));
121123 incr_top(L);
122124 }
123125
124126
125127 /* this function handles only `%d', `%c', %f, %p, and `%s' formats */
126128 const char *luaO_pushvfstring (lua_State *L, const char *fmt, va_list argp) {
127− int n = 1;
128− pushstr(L, "");
129+ int n = 0;
129130 for (;;) {
130131 const char *e = strchr(fmt, '%');
131132 if (e == NULL) break;
@@ -135,14 +136,13 @@ const char *luaO_pushvfstring (lua_State *L, const char *fmt, va_list argp) { · 3 unmodified lines
135136 case 's': {
136137 const char *s = va_arg(argp, char *);
137138 if (s == NULL) s = "(null)";
138− pushstr(L, s);
139+ pushstr(L, s, strlen(s));
139140 break;
140141 }
141142 case 'c': {
142− char buff[2];
143− buff[0] = cast(char, va_arg(argp, int));
144− buff[1] = '\0';
145− pushstr(L, buff);
143+ char buff;
144+ buff = cast(char, va_arg(argp, int));
145+ pushstr(L, &buff, 1);
146146 break;
147147 }
148148 case 'd': {
@@ -157,12 +157,12 @@ const char *luaO_pushvfstring (lua_State *L, const char *fmt, va_list argp) { · 8 unmodified lines
157157 }
158158 case 'p': {
159159 char buff[4*sizeof(void *) + 8]; /* should be enough space for a `%p' */
160− sprintf(buff, "%p", va_arg(argp, void *));
161− pushstr(L, buff);
160+ int l = sprintf(buff, "%p", va_arg(argp, void *));
161+ pushstr(L, buff, l);
162162 break;
163163 }
164164 case '%': {
165− pushstr(L, "%");
165+ pushstr(L, "%", 1);
166166 break;
167167 }
168168 default: {
@@ -175,8 +175,8 @@ const char *luaO_pushvfstring (lua_State *L, const char *fmt, va_list argp) { · 6 unmodified lines
175175 n += 2;
176176 fmt = e+2;
177177 }
178− pushstr(L, fmt);
179− luaV_concat(L, n+1);
178+ pushstr(L, fmt, strlen(fmt));
179+ if (n > 0) luaV_concat(L, n + 1);
180180 return svalue(L->top - 1);
181181 }
182182
src/lobject.h+35−23
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lobject.h,v 2.34 2010/01/08 20:00:20 roberto Exp $
2+** $Id: lobject.h,v 2.40 2010/05/07 18:44:46 roberto Exp $
33 ** Type definitions for Lua objects
44 ** See Copyright Notice in lua.h
55 */
@@ -16,20 +16,20 @@ · 10 unmodified lines
1616 #include "lua.h"
1717
1818
19−/* tags for values visible from Lua */
20−#define LAST_TAG LUA_TTHREAD
21−
22−#define NUM_TAGS (LAST_TAG+1)
23−
24−
2519 /*
2620 ** Extra tags for non-values
2721 */
28−#define LUA_TPROTO (LAST_TAG+1)
29−#define LUA_TUPVAL (LAST_TAG+2)
30−#define LUA_TDEADKEY (LAST_TAG+3)
22+#define LUA_TPROTO LUA_NUMTAGS
23+#define LUA_TUPVAL (LUA_NUMTAGS+1)
24+#define LUA_TDEADKEY (LUA_NUMTAGS+2)
3125
3226
27+/*
28+** Variant tag for light C functions (negative to be considered
29+** non collectable by 'iscollectable')
30+*/
31+#define LUA_TLCF (~0x0F | LUA_TFUNCTION)
32+
3333 /*
3434 ** Union of all collectable objects
3535 */
@@ -60,6 +60,7 @@ typedef union { · 24 unmodified lines
6060 void *p;
6161 lua_Number n;
6262 int b;
63+ lua_CFunction f;
6364 } Value;
6465
6566
@@ -79,12 +80,26 @@ typedef struct lua_TValue { · 13 unmodified lines
7980 #define NILCONSTANT {NULL}, LUA_TNIL
8081
8182
83+/*
84+** type tag of a TValue
85+*/
86+#define ttype(o) ((o)->tt_)
87+
88+
89+/*
90+** type tag of a TValue with no variants
91+*/
92+#define ttypenv(o) (ttype(o) & 0x0F)
93+
94+
8295 /* Macros to test type */
8396 #define ttisnil(o) (ttype(o) == LUA_TNIL)
8497 #define ttisnumber(o) (ttype(o) == LUA_TNUMBER)
8598 #define ttisstring(o) (ttype(o) == LUA_TSTRING)
8699 #define ttistable(o) (ttype(o) == LUA_TTABLE)
87−#define ttisfunction(o) (ttype(o) == LUA_TFUNCTION)
100+#define ttisfunction(o) (ttypenv(o) == LUA_TFUNCTION)
101+#define ttisclosure(o) (ttype(o) == LUA_TFUNCTION)
102+#define ttislcf(o) (ttype(o) == LUA_TLCF)
88103 #define ttisboolean(o) (ttype(o) == LUA_TBOOLEAN)
89104 #define ttisuserdata(o) (ttype(o) == LUA_TUSERDATA)
90105 #define ttisthread(o) (ttype(o) == LUA_TTHREAD)
@@ -92,7 +107,6 @@ typedef struct lua_TValue { · 1 unmodified line
92107 #define ttisdeadkey(o) (ttype(o) == LUA_TDEADKEY)
93108
94109 /* Macros to access values */
95−#define ttype(o) ((o)->tt_)
96110 #define gcvalue(o) check_exp(iscollectable(o), (o)->value_.gc)
97111 #define pvalue(o) check_exp(ttislightuserdata(o), (o)->value_.p)
98112 #define nvalue(o) check_exp(ttisnumber(o), (o)->value_.n)
@@ -100,16 +114,15 @@ typedef struct lua_TValue { · 1 unmodified line
100114 #define tsvalue(o) (&rawtsvalue(o)->tsv)
101115 #define rawuvalue(o) check_exp(ttisuserdata(o), &(o)->value_.gc->u)
102116 #define uvalue(o) (&rawuvalue(o)->uv)
103−#define clvalue(o) check_exp(ttisfunction(o), &(o)->value_.gc->cl)
117+#define clvalue(o) check_exp(ttisclosure(o), &(o)->value_.gc->cl)
118+#define fvalue(o) check_exp(ttislcf(o), (o)->value_.f)
104119 #define hvalue(o) check_exp(ttistable(o), &(o)->value_.gc->h)
105120 #define bvalue(o) check_exp(ttisboolean(o), (o)->value_.b)
106121 #define thvalue(o) check_exp(ttisthread(o), &(o)->value_.gc->th)
107122
108123 #define l_isfalse(o) (ttisnil(o) || (ttisboolean(o) && bvalue(o) == 0))
109124
110−/*
111−** for internal debug only
112−*/
125+
113126 #define iscollectable(o) (ttype(o) >= LUA_TSTRING)
114127
115128 #define righttt(obj) (ttype(obj) == gcvalue(obj)->gch.tt)
@@ -126,8 +139,10 @@ typedef struct lua_TValue { · 10 unmodified lines
126139 #define setnvalue(obj,x) \
127140 { TValue *i_o=(obj); i_o->value_.n=(x); i_o->tt_=LUA_TNUMBER; }
128141
129−#define changenvalue(obj,x) \
130− ( lua_assert((obj)->tt_==LUA_TNUMBER), (obj)->value_.n=(x) )
142+#define setfvalue(obj,x) \
143+ { TValue *i_o=(obj); i_o->value_.f=(x); i_o->tt_=LUA_TLCF; }
144+
145+#define changenvalue(o,x) check_exp((o)->tt_==LUA_TNUMBER, (o)->value_.n=(x))
131146
132147 #define setpvalue(obj,x) \
133148 { TValue *i_o=(obj); i_o->value_.p=(x); i_o->tt_=LUA_TLIGHTUSERDATA; }
@@ -264,7 +279,6 @@ typedef struct Proto { · 130 unmodified lines
264279 lu_byte numparams;
265280 lu_byte is_vararg;
266281 lu_byte maxstacksize;
267− lu_byte envreg; /* register in outer function with initial environment */
268282 } Proto;
269283
270284
@@ -298,8 +312,7 @@ typedef struct UpVal { · 27 unmodified lines
298312 */
299313
300314 #define ClosureHeader \
301− CommonHeader; lu_byte isC; lu_byte nupvalues; GCObject *gclist; \
302− struct Table *env
315+ CommonHeader; lu_byte isC; lu_byte nupvalues; GCObject *gclist
303316
304317 typedef struct CClosure {
305318 ClosureHeader;
@@ -321,8 +334,7 @@ typedef union Closure { · 15 unmodified lines
321334 } Closure;
322335
323336
324−#define iscfunction(o) (ttisfunction(o) && clvalue(o)->c.isC)
325−#define isLfunction(o) (ttisfunction(o) && !clvalue(o)->c.isC)
337+#define isLfunction(o) (ttisclosure(o) && !clvalue(o)->c.isC)
326338
327339 #define getproto(o) (clvalue(o)->l.p)
328340
src/lopcodes.c+5−5
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lopcodes.c,v 1.41 2009/11/19 19:06:52 roberto Exp $
2+** $Id: lopcodes.c,v 1.43 2010/03/12 19:14:06 roberto Exp $
33 ** See Copyright Notice in lua.h
44 */
55
@@ -19,9 +19,9 @@ LUAI_DDEF const char *const luaP_opnames[NUM_OPCODES+1] = { · 13 unmodified lines
1919 "LOADBOOL",
2020 "LOADNIL",
2121 "GETUPVAL",
22− "GETGLOBAL",
22+ "GETTABUP",
2323 "GETTABLE",
24− "SETGLOBAL",
24+ "SETTABUP",
2525 "SETUPVAL",
2626 "SETTABLE",
2727 "NEWTABLE",
@@ -67,9 +67,9 @@ LUAI_DDEF const lu_byte luaP_opmodes[NUM_OPCODES] = { · 39 unmodified lines
6767 ,opmode(0, 1, OpArgU, OpArgU, iABC) /* OP_LOADBOOL */
6868 ,opmode(0, 1, OpArgR, OpArgN, iABC) /* OP_LOADNIL */
6969 ,opmode(0, 1, OpArgU, OpArgN, iABC) /* OP_GETUPVAL */
70− ,opmode(0, 1, OpArgK, OpArgN, iABx) /* OP_GETGLOBAL */
70+ ,opmode(0, 1, OpArgU, OpArgK, iABC) /* OP_GETTABUP */
7171 ,opmode(0, 1, OpArgR, OpArgK, iABC) /* OP_GETTABLE */
72− ,opmode(0, 0, OpArgK, OpArgN, iABx) /* OP_SETGLOBAL */
72+ ,opmode(0, 0, OpArgK, OpArgK, iABC) /* OP_SETTABUP */
7373 ,opmode(0, 0, OpArgU, OpArgN, iABC) /* OP_SETUPVAL */
7474 ,opmode(0, 0, OpArgK, OpArgK, iABC) /* OP_SETTABLE */
7575 ,opmode(0, 1, OpArgU, OpArgU, iABC) /* OP_NEWTABLE */
src/lopcodes.h+4−5
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lopcodes.h,v 1.133 2009/11/19 19:06:52 roberto Exp $
2+** $Id: lopcodes.h,v 1.135 2010/03/12 19:14:06 roberto Exp $
33 ** Opcodes for Lua virtual machine
44 ** See Copyright Notice in lua.h
55 */
@@ -171,10 +171,10 @@ OP_LOADBOOL,/* A B C R(A) := (Bool)B; if (C) pc++ */ · 165 unmodified lines
171171 OP_LOADNIL,/* A B R(A) := ... := R(B) := nil */
172172 OP_GETUPVAL,/* A B R(A) := UpValue[B] */
173173
174−OP_GETGLOBAL,/* A Bx R(A) := Gbl[Kst(Bx - 1)] */
174+OP_GETTABUP,/* A B C R(A) := UpValue[B][RK(C)] */
175175 OP_GETTABLE,/* A B C R(A) := R(B)[RK(C)] */
176176
177−OP_SETGLOBAL,/* A Bx Gbl[Kst(Bx - 1)] := R(A) */
177+OP_SETTABUP,/* A B C UpValue[A][RK(B)] := RK(C) */
178178 OP_SETUPVAL,/* A B UpValue[B] := R(A) */
179179 OP_SETTABLE,/* A B C R(A)[RK(B)] := RK(C) */
180180
@@ -243,8 +243,7 @@ OP_EXTRAARG/* Ax extra (larger) argument for previous opcode */ · 62 unmodified lines
243243 (*) In OP_SETLIST, if (B == 0) then B = `top'; if (C == 0) then next
244244 'instruction' is EXTRAARG(real C).
245245
246− (*) In OP_LOADK, OP_GETGLOBAL, and OP_SETGLOBAL, if (Bx == 0) then next
247− 'instruction' is EXTRAARG(real Bx).
246+ (*) In OP_LOADK, if (Bx == 0) then next 'instruction' is EXTRAARG(real Bx).
248247
249248 (*) For comparisons, A specifies what condition the test should accept
250249 (true or false).
src/lparser.c+95−89
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lparser.c,v 2.75 2010/01/06 11:48:02 roberto Exp $
2+** $Id: lparser.c,v 2.86 2010/05/15 13:32:02 roberto Exp $
33 ** Lua Parser
44 ** See Copyright Notice in lua.h
55 */
@@ -74,9 +74,10 @@ static void error_expected (LexState *ls, int token) { · 68 unmodified lines
7474
7575 static void errorlimit (FuncState *fs, int limit, const char *what) {
7676 const char *msg;
77− const char *where = (fs->f->linedefined == 0) ?
78− "main function" :
79− luaO_pushfstring(fs->L, "function at line %d", fs->f->linedefined);
77+ int line = fs->f->linedefined;
78+ const char *where = (line == 0)
79+ ? "main function"
80+ : luaO_pushfstring(fs->L, "function at line %d", line);
8081 msg = luaO_pushfstring(fs->L, "too many %s (limit is %d) in %s",
8182 what, limit, where);
8283 luaX_syntaxerror(fs->ls, msg);
@@ -207,27 +208,27 @@ static void removevars (FuncState *fs, int tolevel) { · 124 unmodified lines
207208 }
208209
209210
210−static int indexupvalue (FuncState *fs, TString *name, expdesc *v) {
211+static int searchupvalue (FuncState *fs, TString *name) {
211212 int i;
213+ Upvaldesc *up = fs->f->upvalues;
214+ for (i = 0; i < fs->nups; i++) {
215+ if (eqstr(up[i].name, name)) return i;
216+ }
217+ return -1; /* not found */
218+}
219+
220+
221+static int newupvalue (FuncState *fs, TString *name, expdesc *v) {
212222 Proto *f = fs->f;
213223 int oldsize = f->sizeupvalues;
214− int instk = (v->k == VLOCAL);
215− lua_assert(instk || v->k == VUPVAL);
216− for (i=0; i<fs->nups; i++) {
217− if (f->upvalues[i].instack == instk && f->upvalues[i].idx == v->u.s.info) {
218− lua_assert(f->upvalues[i].name == name);
219− return i;
220− }
221− }
222− /* new one */
223224 checklimit(fs, fs->nups + 1, UCHAR_MAX, "upvalues");
224225 luaM_growvector(fs->L, f->upvalues, fs->nups, f->sizeupvalues,
225226 Upvaldesc, UCHAR_MAX, "upvalues");
226227 while (oldsize < f->sizeupvalues) f->upvalues[oldsize++].name = NULL;
228+ f->upvalues[fs->nups].instack = (v->k == VLOCAL);
229+ f->upvalues[fs->nups].idx = cast_byte(v->u.s.info);
227230 f->upvalues[fs->nups].name = name;
228231 luaC_objbarrier(fs->L, f, name);
229− f->upvalues[fs->nups].instack = cast_byte(instk);
230− f->upvalues[fs->nups].idx = cast_byte(v->u.s.info);
231232 return fs->nups++;
232233 }
233234
@@ -235,13 +236,17 @@ static int indexupvalue (FuncState *fs, TString *name, expdesc *v) { · 1 unmodified line
235236 static int searchvar (FuncState *fs, TString *n) {
236237 int i;
237238 for (i=fs->nactvar-1; i >= 0; i--) {
238− if (n == getlocvar(fs, i)->varname)
239+ if (eqstr(n, getlocvar(fs, i)->varname))
239240 return i;
240241 }
241242 return -1; /* not found */
242243 }
243244
244245
246+/*
247+ Mark block where variable at given level was defined
248+ (to emit OP_CLOSE later).
249+*/
245250 static void markupval (FuncState *fs, int level) {
246251 BlockCnt *bl = fs->bl;
247252 while (bl && bl->nactvar > level) bl = bl->previous;
@@ -249,22 +254,30 @@ static void markupval (FuncState *fs, int level) { · 1 unmodified line
249254 }
250255
251256
257+/*
258+ Find variable with given name 'n'. If it is an upvalue, add this
259+ upvalue into all intermediate functions.
260+*/
252261 static int singlevaraux (FuncState *fs, TString *n, expdesc *var, int base) {
253262 if (fs == NULL) /* no more levels? */
254− return VGLOBAL; /* default is global variable */
263+ return VVOID; /* default is global */
255264 else {
256− int v = searchvar(fs, n); /* look up at current level */
257− if (v >= 0) {
258− init_exp(var, VLOCAL, v);
265+ int v = searchvar(fs, n); /* look up locals at current level */
266+ if (v >= 0) { /* found? */
267+ init_exp(var, VLOCAL, v); /* variable is local */
259268 if (!base)
260269 markupval(fs, v); /* local will be used as an upval */
261270 return VLOCAL;
262271 }
263− else { /* not found at current level; try upper one */
264− if (singlevaraux(fs->prev, n, var, 0) == VGLOBAL)
265− return VGLOBAL;
266− var->u.s.info = indexupvalue(fs, n, var); /* else was LOCAL or UPVAL */
267− var->k = VUPVAL; /* upvalue in this level */
272+ else { /* not found as local at current level; try upvalues */
273+ int idx = searchupvalue(fs, n); /* try existing upvalues */
274+ if (idx < 0) { /* not found? */
275+ if (singlevaraux(fs->prev, n, var, 0) == VVOID) /* try upper levels */
276+ return VVOID; /* not found; is a global */
277+ /* else was LOCAL or UPVAL */
278+ idx = newupvalue(fs, n, var); /* will be a new upvalue */
279+ }
280+ init_exp(var, VUPVAL, idx);
268281 return VUPVAL;
269282 }
270283 }
@@ -274,15 +287,12 @@ static int singlevaraux (FuncState *fs, TString *n, expdesc *var, int base) { · 3 unmodified lines
274287 static void singlevar (LexState *ls, expdesc *var) {
275288 TString *varname = str_checkname(ls);
276289 FuncState *fs = ls->fs;
277− if (singlevaraux(fs, varname, var, 1) == VGLOBAL) {
278− if (fs->envreg == NO_REG) /* regular global? */
279− init_exp(var, VGLOBAL, luaK_stringK(fs, varname));
280− else { /* "globals" are in current lexical environment */
281− expdesc key;
282− init_exp(var, VLOCAL, fs->envreg); /* current environment */
283− codestring(ls, &key, varname); /* key is variable name */
284− luaK_indexed(fs, var, &key); /* env[varname] */
285− }
290+ if (singlevaraux(fs, varname, var, 1) == VVOID) { /* global name? */
291+ expdesc key;
292+ singlevaraux(fs, ls->envn, var, 1); /* get _ENV variable */
293+ lua_assert(var->k == VLOCAL || var->k == VUPVAL);
294+ codestring(ls, &key, varname); /* key is variable name */
295+ luaK_indexed(fs, var, &key); /* env[varname] */
286296 }
287297 }
288298
@@ -351,7 +361,6 @@ static void pushclosure (LexState *ls, Proto *clp, expdesc *v) { · 62 unmodified lines
351361 while (oldsize < f->sizep) f->p[oldsize++] = NULL;
352362 f->p[fs->np++] = clp;
353363 /* initial environment for new function is current lexical environment */
354− clp->envreg = fs->envreg;
355364 luaC_objbarrier(ls->L, f, clp);
356365 init_exp(v, VRELOCABLE, luaK_codeABx(fs, OP_CLOSURE, 0, fs->np-1));
357366 }
@@ -374,7 +383,6 @@ static void open_func (LexState *ls, FuncState *fs) { · 16 unmodified lines
374383 fs->nlocvars = 0;
375384 fs->nactvar = 0;
376385 fs->firstlocal = ls->varl->nactvar;
377− fs->envreg = NO_REG;
378386 fs->bl = NULL;
379387 f = luaF_newproto(L);
380388 fs->f = f;
@@ -418,26 +426,36 @@ static void close_func (LexState *ls) { · 37 unmodified lines
418426 }
419427
420428
429+/*
430+** opens the main function, which is a regular vararg function with an
431+** upvalue named '_ENV'
432+*/
433+static void open_mainfunc (LexState *ls, FuncState *fs) {
434+ expdesc v;
435+ open_func(ls, fs);
436+ fs->f->is_vararg = 1; /* main function is always vararg */
437+ init_exp(&v, VLOCAL, 0);
438+ newupvalue(fs, ls->envn, &v); /* create '_ENV' upvalue */
439+}
440+
441+
421442 Proto *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff, Varlist *varl,
422443 const char *name) {
423− struct LexState lexstate;
424− struct FuncState funcstate;
444+ LexState lexstate;
445+ FuncState funcstate;
425446 TString *tname = luaS_new(L, name);
426447 setsvalue2s(L, L->top, tname); /* push name to protect it */
427448 incr_top(L);
428449 lexstate.buff = buff;
429450 lexstate.varl = varl;
430451 luaX_setinput(L, &lexstate, z, tname);
431− open_func(&lexstate, &funcstate);
432− funcstate.f->is_vararg = 1; /* main function is always vararg */
452+ open_mainfunc(&lexstate, &funcstate);
433453 luaX_next(&lexstate); /* read first token */
434− chunk(&lexstate);
454+ chunk(&lexstate); /* read main chunk */
435455 check(&lexstate, TK_EOS);
436456 close_func(&lexstate);
437457 L->top--; /* pop name */
438− lua_assert(funcstate.prev == NULL);
439− lua_assert(funcstate.nups == 0);
440− lua_assert(lexstate.fs == NULL);
458+ lua_assert(!funcstate.prev && funcstate.nups == 1 && !lexstate.fs);
441459 return funcstate.f;
442460 }
443461
@@ -452,7 +470,7 @@ static void fieldsel (LexState *ls, expdesc *v) { · 8 unmodified lines
452470 /* fieldsel -> ['.' | ':'] NAME */
453471 FuncState *fs = ls->fs;
454472 expdesc key;
455− luaK_exp2anyreg(fs, v);
473+ luaK_exp2anyregup(fs, v);
456474 luaX_next(ls); /* skip the dot or colon */
457475 checkname(ls, &key);
458476 luaK_indexed(fs, v, &key);
@@ -653,15 +671,12 @@ static int explist1 (LexState *ls, expdesc *v) { · 194 unmodified lines
653671 }
654672
655673
656−static void funcargs (LexState *ls, expdesc *f) {
674+static void funcargs (LexState *ls, expdesc *f, int line) {
657675 FuncState *fs = ls->fs;
658676 expdesc args;
659677 int base, nparams;
660− int line = ls->linenumber;
661678 switch (ls->t.token) {
662679 case '(': { /* funcargs -> `(' [ explist1 ] `)' */
663− if (line != ls->lastline)
664− luaX_syntaxerror(ls,"ambiguous syntax (function call x new statement)");
665680 luaX_next(ls);
666681 if (ls->t.token == ')') /* arg list is empty? */
667682 args.k = VVOID;
@@ -738,6 +753,7 @@ static void primaryexp (LexState *ls, expdesc *v) { · 70 unmodified lines
738753 /* primaryexp ->
739754 prefixexp { `.' NAME | `[' exp `]' | `:' NAME funcargs | funcargs } */
740755 FuncState *fs = ls->fs;
756+ int line = ls->linenumber;
741757 prefixexp(ls, v);
742758 for (;;) {
743759 switch (ls->t.token) {
@@ -747,7 +763,7 @@ static void primaryexp (LexState *ls, expdesc *v) { · 3 unmodified lines
747763 }
748764 case '[': { /* `[' exp1 `]' */
749765 expdesc key;
750− luaK_exp2anyreg(fs, v);
766+ luaK_exp2anyregup(fs, v);
751767 yindex(ls, &key);
752768 luaK_indexed(fs, v, &key);
753769 break;
@@ -757,12 +773,12 @@ static void primaryexp (LexState *ls, expdesc *v) { · 3 unmodified lines
757773 luaX_next(ls);
758774 checkname(ls, &key);
759775 luaK_self(fs, v, &key);
760− funcargs(ls, v);
776+ funcargs(ls, v, line);
761777 break;
762778 }
763779 case '(': case TK_STRING: case '{': { /* funcargs */
764780 luaK_exp2nextreg(fs, v);
765− funcargs(ls, v);
781+ funcargs(ls, v, line);
766782 break;
767783 }
768784 default: return;
@@ -877,9 +893,10 @@ static BinOpr subexpr (LexState *ls, expdesc *v, unsigned int limit) { · 108 unmodified lines
877893 enterlevel(ls);
878894 uop = getunopr(ls->t.token);
879895 if (uop != OPR_NOUNOPR) {
896+ int line = ls->linenumber;
880897 luaX_next(ls);
881898 subexpr(ls, v, UNARY_PRIORITY);
882− luaK_prefix(ls->fs, uop, v);
899+ luaK_prefix(ls->fs, uop, v, line);
883900 }
884901 else simpleexp(ls, v);
885902 /* expand while operators have priorities higher than `limit' */
@@ -887,11 +904,12 @@ static BinOpr subexpr (LexState *ls, expdesc *v, unsigned int limit) { · 1 unmodified line
887904 while (op != OPR_NOBINOPR && priority[op].left > limit) {
888905 expdesc v2;
889906 BinOpr nextop;
907+ int line = ls->linenumber;
890908 luaX_next(ls);
891909 luaK_infix(ls->fs, op, v);
892910 /* read sub-expression with higher priority */
893911 nextop = subexpr(ls, &v2, priority[op].right);
894− luaK_posfix(ls->fs, op, v, &v2);
912+ luaK_posfix(ls->fs, op, v, &v2, line);
895913 op = nextop;
896914 }
897915 leavelevel(ls);
@@ -951,24 +969,27 @@ struct LHS_assign { · 53 unmodified lines
951969 ** local value in a safe place and use this safe copy in the previous
952970 ** assignment.
953971 */
954−static void check_conflict (LexState *ls, struct LHS_assign *lh, expdesc *v) {
972+static void check_conflict (LexState *ls, struct LHS_assign *lh, expdesc *v,
973+ expkind ix, OpCode op) {
955974 FuncState *fs = ls->fs;
956975 int extra = fs->freereg; /* eventual position to save local variable */
957976 int conflict = 0;
958977 for (; lh; lh = lh->prev) {
959− if (lh->v.k == VINDEXED) {
978+ if (lh->v.k == ix) {
960979 if (lh->v.u.s.info == v->u.s.info) { /* conflict? */
961980 conflict = 1;
981+ lh->v.k = VINDEXED;
962982 lh->v.u.s.info = extra; /* previous assignment will use safe copy */
963983 }
964− if (lh->v.u.s.aux == v->u.s.info) { /* conflict? */
984+ if (v->k == VLOCAL && lh->v.u.s.aux == v->u.s.info) { /* conflict? */
965985 conflict = 1;
986+ lua_assert(lh->v.k == VINDEXED);
966987 lh->v.u.s.aux = extra; /* previous assignment will use safe copy */
967988 }
968989 }
969990 }
970991 if (conflict) {
971− luaK_codeABC(fs, OP_MOVE, fs->freereg, v->u.s.info, 0); /* make copy */
992+ luaK_codeABC(fs, op, fs->freereg, v->u.s.info, 0); /* make copy */
972993 luaK_reserveregs(fs, 1);
973994 }
974995 }
@@ -976,14 +997,16 @@ static void check_conflict (LexState *ls, struct LHS_assign *lh, expdesc *v) { · 1 unmodified line
976997
977998 static void assignment (LexState *ls, struct LHS_assign *lh, int nvars) {
978999 expdesc e;
979− check_condition(ls, VLOCAL <= lh->v.k && lh->v.k <= VINDEXED,
1000+ check_condition(ls, VLOCAL <= lh->v.k && lh->v.k <= VINDEXEDUP,
9801001 "syntax error");
9811002 if (testnext(ls, ',')) { /* assignment -> `,' primaryexp assignment */
9821003 struct LHS_assign nv;
9831004 nv.prev = lh;
9841005 primaryexp(ls, &nv.v);
9851006 if (nv.v.k == VLOCAL)
986− check_conflict(ls, lh, &nv.v);
1007+ check_conflict(ls, lh, &nv.v, VINDEXED, OP_MOVE);
1008+ else if (nv.v.k == VUPVAL)
1009+ check_conflict(ls, lh, &nv.v, VINDEXEDUP, OP_GETUPVAL);
9871010 checklimit(ls->fs, nvars, LUAI_MAXCCALLS - G(ls->L)->nCcalls,
9881011 "variable names");
9891012 assignment(ls, &nv, nvars+1);
@@ -1274,24 +1297,6 @@ static void funcstat (LexState *ls, int line) { · 284 unmodified lines
12741297 }
12751298
12761299
1277−static void instat (LexState *ls, int line) {
1278− /* instat -> IN exp DO block END */
1279− FuncState *fs = ls->fs;
1280− int oldenv = fs->envreg; /* save current environment */
1281− BlockCnt bl;
1282− luaX_next(ls); /* skip IN */
1283− enterblock(fs, &bl, 0); /* scope for environment variable */
1284− new_localvarliteral(ls, "(environment)");
1285− fs->envreg = exp1(ls); /* new environment */
1286− adjustlocalvars(ls, 1);
1287− checknext(ls, TK_DO);
1288− block(ls);
1289− leaveblock(fs);
1290− check_match(ls, TK_END, TK_IN, line);
1291− fs->envreg = oldenv; /* restore outer environment */
1292−}
1293−
1294−
12951300 static void exprstat (LexState *ls) {
12961301 /* stat -> func | assignment */
12971302 FuncState *fs = ls->fs;
@@ -1311,7 +1316,6 @@ static void retstat (LexState *ls) { · 13 unmodified lines
13111316 FuncState *fs = ls->fs;
13121317 expdesc e;
13131318 int first, nret; /* registers with returned values */
1314− luaX_next(ls); /* skip RETURN */
13151319 if (block_follow(ls->t.token) || ls->t.token == ';')
13161320 first = nret = 0; /* return no values */
13171321 else {
@@ -1342,6 +1346,10 @@ static void retstat (LexState *ls) { · 24 unmodified lines
13421346 static int statement (LexState *ls) {
13431347 int line = ls->linenumber; /* may be needed for error messages */
13441348 switch (ls->t.token) {
1349+ case ';': { /* stat -> ';' (empty statement) */
1350+ luaX_next(ls); /* skip ';' */
1351+ return 0;
1352+ }
13451353 case TK_IF: { /* stat -> ifstat */
13461354 ifstat(ls, line);
13471355 return 0;
@@ -1356,10 +1364,6 @@ static int statement (LexState *ls) { · 8 unmodified lines
13561364 check_match(ls, TK_END, TK_DO, line);
13571365 return 0;
13581366 }
1359− case TK_IN: {
1360− instat(ls, line);
1361− return 0;
1362− }
13631367 case TK_FOR: { /* stat -> forstat */
13641368 forstat(ls, line);
13651369 return 0;
@@ -1368,8 +1372,8 @@ static int statement (LexState *ls) { · 2 unmodified lines
13681372 repeatstat(ls, line);
13691373 return 0;
13701374 }
1371− case TK_FUNCTION: {
1372− funcstat(ls, line); /* stat -> funcstat */
1375+ case TK_FUNCTION: { /* stat -> funcstat */
1376+ funcstat(ls, line);
13731377 return 0;
13741378 }
13751379 case TK_LOCAL: { /* stat -> localstat */
@@ -1381,6 +1385,7 @@ static int statement (LexState *ls) { · 5 unmodified lines
13811385 return 0;
13821386 }
13831387 case TK_RETURN: { /* stat -> retstat */
1388+ luaX_next(ls); /* skip RETURN */
13841389 retstat(ls);
13851390 return 1; /* must be last statement */
13861391 }
@@ -1389,9 +1394,9 @@ static int statement (LexState *ls) { · 2 unmodified lines
13891394 breakstat(ls);
13901395 return 1; /* must be last statement */
13911396 }
1392− default: {
1397+ default: { /* stat -> func | assignment */
13931398 exprstat(ls);
1394− return 0; /* to avoid warnings */
1399+ return 0;
13951400 }
13961401 }
13971402 }
@@ -1403,7 +1408,8 @@ static void chunk (LexState *ls) { · 5 unmodified lines
14031408 enterlevel(ls);
14041409 while (!islast && !block_follow(ls->t.token)) {
14051410 islast = statement(ls);
1406− testnext(ls, ';');
1411+ if (islast)
1412+ testnext(ls, ';');
14071413 lua_assert(ls->fs->f->maxstacksize >= ls->fs->freereg &&
14081414 ls->fs->freereg >= ls->fs->nactvar);
14091415 ls->fs->freereg = ls->fs->nactvar; /* free registers */
src/lparser.h+5−6
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lparser.h,v 1.61 2009/10/11 20:02:19 roberto Exp $
2+** $Id: lparser.h,v 1.63 2010/03/12 19:14:06 roberto Exp $
33 ** Lua Parser
44 ** See Copyright Notice in lua.h
55 */
@@ -23,10 +23,10 @@ typedef enum { · 17 unmodified lines
2323 VFALSE,
2424 VK, /* info = index of constant in `k' */
2525 VKNUM, /* nval = numerical value */
26− VLOCAL, /* info = local register; aux = read only */
27− VUPVAL, /* info = index of upvalue in 'upvalues'; aux = read only */
28− VGLOBAL, /* info = index of table; aux = index of global name in `k' */
29− VINDEXED, /* info = table register; aux = index register (or `k') */
26+ VLOCAL, /* info = local register */
27+ VUPVAL, /* info = index of upvalue in 'upvalues' */
28+ VINDEXED, /* info = table R/K; aux = index R/K */
29+ VINDEXEDUP, /* info = table upvalue; aux = R/K */
3030 VJMP, /* info = instruction pc */
3131 VRELOCABLE, /* info = instruction pc */
3232 VNONRELOC, /* info = result register */
@@ -80,7 +80,6 @@ typedef struct FuncState { · 47 unmodified lines
8080 short nlocvars; /* number of elements in `locvars' */
8181 lu_byte nactvar; /* number of active local variables */
8282 lu_byte nups; /* number of upvalues */
83− lu_byte envreg; /* register holding current lexical environment */
8483 } FuncState;
8584
8685
src/lstate.c+34−46
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lstate.c,v 2.68 2009/12/22 15:32:50 roberto Exp $
2+** $Id: lstate.c,v 2.85 2010/04/30 18:36:22 roberto Exp $
33 ** Global State
44 ** See Copyright Notice in lua.h
55 */
@@ -26,7 +26,7 @@ · 20 unmodified lines
2626
2727
2828 #if !defined(LUAI_GCPAUSE)
29−#define LUAI_GCPAUSE 162 /* 162% (wait memory to double before next GC) */
29+#define LUAI_GCPAUSE 200 /* 200% */
3030 #endif
3131
3232 #if !defined(LUAI_GCMUL)
@@ -34,6 +34,9 @@ · 1 unmodified line
3434 #endif
3535
3636
37+#define MEMERRMSG "not enough memory"
38+
39+
3740 /*
3841 ** thread state + extra space
3942 */
@@ -87,7 +90,7 @@ void luaE_freeCI (lua_State *L) { · 47 unmodified lines
8790
8891
8992 static void stack_init (lua_State *L1, lua_State *L) {
90− int i;
93+ int i; CallInfo *ci;
9194 /* initialize stack array */
9295 L1->stack = luaM_newvector(L, BASIC_STACK_SIZE, TValue);
9396 L1->stacksize = BASIC_STACK_SIZE;
@@ -96,32 +99,22 @@ static void stack_init (lua_State *L1, lua_State *L) { · 2 unmodified lines
9699 L1->top = L1->stack;
97100 L1->stack_last = L1->stack + L1->stacksize - EXTRA_STACK;
98101 /* initialize first ci */
99− L1->ci->func = L1->top;
102+ ci = &L1->base_ci;
103+ ci->next = ci->previous = NULL;
104+ ci->callstatus = 0;
105+ ci->func = L1->top;
100106 setnilvalue(L1->top++); /* 'function' entry for this 'ci' */
101− L1->ci->top = L1->top + LUA_MINSTACK;
102− L1->ci->callstatus = 0;
107+ ci->top = L1->top + LUA_MINSTACK;
108+ L1->ci = ci;
103109 }
104110
105111
106112 static void freestack (lua_State *L) {
107− L->ci = &L->base_ci; /* reset 'ci' list */
113+ if (L->stack == NULL)
114+ return; /* stack not completely built yet */
115+ L->ci = &L->base_ci; /* free the entire 'ci' list */
108116 luaE_freeCI(L);
109− luaM_freearray(L, L->stack, L->stacksize);
110−}
111−
112−
113−/*
114−** Calls the function in variable pointed to by userdata in first argument
115−** (Userdata cannot point directly to the function because pointer to
116−** function is not compatible with void*.)
117−*/
118−static int cpcall (lua_State *L) {
119− lua_CFunction f = *(lua_CFunction *)lua_touserdata(L, 1);
120− lua_remove(L, 1); /* remove f from stack */
121− /* restore original environment for 'cpcall' */
122− lua_pushglobaltable(L);
123− lua_replace(L, LUA_ENVIRONINDEX);
124− return f(L);
117+ luaM_freearray(L, L->stack, L->stacksize); /* free stack array */
125118 }
126119
127120
@@ -129,7 +122,6 @@ static int cpcall (lua_State *L) { · 1 unmodified line
129122 ** Create registry table and its predefined values
130123 */
131124 static void init_registry (lua_State *L, global_State *g) {
132− Closure *cp;
133125 TValue mt;
134126 /* create registry */
135127 Table *registry = luaH_new(L);
@@ -138,13 +130,8 @@ static void init_registry (lua_State *L, global_State *g) { · 2 unmodified lines
138130 /* registry[LUA_RIDX_MAINTHREAD] = L */
139131 setthvalue(L, &mt, L);
140132 setobj2t(L, luaH_setint(L, registry, LUA_RIDX_MAINTHREAD), &mt);
141− /* registry[LUA_RIDX_CPCALL] = cpcall */
142− cp = luaF_newCclosure(L, 0, g->l_gt);
143− cp->c.f = cpcall;
144− setclvalue(L, &mt, cp);
145− setobj2t(L, luaH_setint(L, registry, LUA_RIDX_CPCALL), &mt);
146− /* registry[LUA_RIDX_GLOBALS] = l_gt */
147− sethvalue(L, &mt, g->l_gt);
133+ /* registry[LUA_RIDX_GLOBALS] = table of globals */
134+ sethvalue(L, &mt, luaH_new(L));
148135 setobj2t(L, luaH_setint(L, registry, LUA_RIDX_GLOBALS), &mt);
149136 }
150137
@@ -156,13 +143,14 @@ static void f_luaopen (lua_State *L, void *ud) { · 5 unmodified lines
156143 global_State *g = G(L);
157144 UNUSED(ud);
158145 stack_init(L, L); /* init stack */
159− g->l_gt = luaH_new(L); /* table of globals */
160146 init_registry(L, g);
161147 luaS_resize(L, MINSTRTABSIZE); /* initial size of string table */
162148 luaT_init(L);
163149 luaX_init(L);
164− luaS_fix(luaS_newliteral(L, MEMERRMSG));
165− g->GCthreshold = 4*g->totalbytes;
150+ /* pre-create memory-error message */
151+ g->memerrmsg = luaS_newliteral(L, MEMERRMSG);
152+ luaS_fix(g->memerrmsg); /* it should never be collected */
153+ g->GCdebt = 0;
166154 }
167155
168156
@@ -173,6 +161,7 @@ static void f_luaopen (lua_State *L, void *ud) { · 4 unmodified lines
173161 static void preinit_state (lua_State *L, global_State *g) {
174162 G(L) = g;
175163 L->stack = NULL;
164+ L->ci = NULL;
176165 L->stacksize = 0;
177166 L->errorJmp = NULL;
178167 L->hook = NULL;
@@ -183,8 +172,6 @@ static void preinit_state (lua_State *L, global_State *g) { · 4 unmodified lines
183172 L->openupval = NULL;
184173 L->nny = 1;
185174 L->status = LUA_OK;
186− L->base_ci.next = L->base_ci.previous = NULL;
187− L->ci = &L->base_ci;
188175 L->errfunc = 0;
189176 }
190177
@@ -209,14 +196,13 @@ LUA_API lua_State *lua_newthread (lua_State *L) { · 18 unmodified lines
209196 setthvalue(L, L->top, L1);
210197 api_incr_top(L);
211198 preinit_state(L1, G(L));
212− stack_init(L1, L); /* init stack */
213199 L1->hookmask = L->hookmask;
214200 L1->basehookcount = L->basehookcount;
215201 L1->hook = L->hook;
216202 resethookcount(L1);
217− lua_assert(iswhite(obj2gco(L1)));
218− lua_unlock(L);
219203 luai_userstatethread(L, L1);
204+ stack_init(L1, L); /* init stack */
205+ lua_unlock(L);
220206 return L1;
221207 }
222208
@@ -225,7 +211,7 @@ void luaE_freethread (lua_State *L, lua_State *L1) { · 2 unmodified lines
225211 LX *l = fromstate(L1);
226212 luaF_close(L1, L1->stack); /* close all upvalues for this thread */
227213 lua_assert(L1->openupval == NULL);
228− luai_userstatefree(L1);
214+ luai_userstatefree(L, L1);
229215 freestack(L1);
230216 luaM_free(L, l);
231217 }
@@ -235,7 +221,7 @@ LUA_API lua_State *lua_newstate (lua_Alloc f, void *ud) { · 3 unmodified lines
235221 int i;
236222 lua_State *L;
237223 global_State *g;
238− LG *l = cast(LG *, (*f)(ud, NULL, 0, sizeof(LG)));
224+ LG *l = cast(LG *, (*f)(ud, NULL, LUA_TTHREAD, sizeof(LG)));
239225 if (l == NULL) return NULL;
240226 L = &l->l.l;
241227 g = &l->g;
@@ -245,29 +231,31 @@ LUA_API lua_State *lua_newstate (lua_Alloc f, void *ud) { · 3 unmodified lines
245231 L->marked = luaC_white(g);
246232 g->gckind = KGC_NORMAL;
247233 g->nCcalls = 0;
248− set2bits(L->marked, FIXEDBIT, SFIXEDBIT);
249234 preinit_state(L, g);
250235 g->frealloc = f;
251236 g->ud = ud;
252237 g->mainthread = L;
253238 g->uvhead.u.l.prev = &g->uvhead;
254239 g->uvhead.u.l.next = &g->uvhead;
255− g->GCthreshold = MAX_LUMEM; /* no GC while building state */
240+ stopgc(g); /* no GC while building state */
241+ g->lastmajormem = 0;
256242 g->strt.size = 0;
257243 g->strt.nuse = 0;
258244 g->strt.hash = NULL;
259245 setnilvalue(&g->l_registry);
260− g->l_gt = NULL;
261246 luaZ_initbuffer(L, &g->buff);
262247 g->panic = NULL;
263248 g->version = lua_version(NULL);
264249 g->gcstate = GCSpause;
265− g->rootgc = obj2gco(L);
250+ g->allgc = NULL;
251+ g->udgc = NULL;
266252 g->tobefnz = NULL;
253+ g->gray = g->grayagain = NULL;
254+ g->weak = g->ephemeron = g->allweak = NULL;
267255 g->totalbytes = sizeof(LG);
268256 g->gcpause = LUAI_GCPAUSE;
269257 g->gcstepmul = LUAI_GCMUL;
270− for (i=0; i<NUM_TAGS; i++) g->mt[i] = NULL;
258+ for (i=0; i < LUA_NUMTAGS; i++) g->mt[i] = NULL;
271259 if (luaD_rawrunprotected(L, f_luaopen, NULL) != LUA_OK) {
272260 /* memory allocation error: free partial state */
273261 close_state(L);
src/lstate.h+16−18
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lstate.h,v 2.52 2009/12/22 15:32:50 roberto Exp $
2+** $Id: lstate.h,v 2.65 2010/05/03 17:39:48 roberto Exp $
33 ** Global State
44 ** See Copyright Notice in lua.h
55 */
@@ -19,7 +19,7 @@ · 13 unmodified lines
1919 ** Some notes about garbage-collected objects: All objects in Lua must
2020 ** be kept somehow accessible until being freed.
2121 **
22−** Lua keeps most objects linked in list g->rootgc. The link uses field
22+** Lua keeps most objects linked in list g->allgc. The link uses field
2323 ** 'next' of the CommonHeader.
2424 **
2525 ** Strings are kept in several lists headed by the array g->strt.hash.
@@ -32,9 +32,7 @@ · 6 unmodified lines
3232 ** when traversing the respective threads, but the thread may already be
3333 ** dead, while the upvalue is still accessible through closures.)
3434 **
35−** Userdata with finalizers are kept in the list g->rootgc, but after
36−** the mainthread, which should be otherwise the last element in the
37−** list, as it was the first one inserted there.
35+** Userdata with finalizers are kept in the list g->udgc.
3836 **
3937 ** The list g->tobefnz links all userdata being finalized.
4038
@@ -56,8 +54,8 @@ struct lua_longjmp; /* defined in ldo.c */ · 15 unmodified lines
5654
5755 /* kinds of Garbage Collection */
5856 #define KGC_NORMAL 0
59−#define KGC_FORCED 1 /* gc was forced by the program */
60−#define KGC_EMERGENCY 2 /* gc was forced by an allocation failure */
57+#define KGC_EMERGENCY 1 /* gc was forced by an allocation failure */
58+#define KGC_GEN 2 /* generational collection */
6159
6260
6361 typedef struct stringtable {
@@ -85,7 +83,7 @@ typedef struct CallInfo { · 21 unmodified lines
8583 int ctx; /* context info. in case of yields */
8684 lua_CFunction k; /* continuation in case of yields */
8785 ptrdiff_t old_errfunc;
88− ptrdiff_t oldtop;
86+ ptrdiff_t extra;
8987 lu_byte old_allowhook;
9088 lu_byte status;
9189 } c;
@@ -106,7 +104,6 @@ typedef struct CallInfo { · 14 unmodified lines
106104 #define CIST_TAIL (1<<6) /* call was tail called */
107105
108106
109−#define curr_func(L) (clvalue(L->ci->func))
110107 #define ci_func(ci) (clvalue((ci)->func))
111108 #define isLua(ci) ((ci)->callstatus & CIST_LUA)
112109
@@ -115,15 +112,20 @@ typedef struct CallInfo { · 2 unmodified lines
115112 ** `global state', shared by all threads of this state
116113 */
117114 typedef struct global_State {
118− stringtable strt; /* hash table for strings */
119115 lua_Alloc frealloc; /* function to reallocate memory */
120116 void *ud; /* auxiliary data to `frealloc' */
117+ lu_mem totalbytes; /* number of bytes currently allocated */
118+ l_mem GCdebt; /* when positive, run a GC step */
119+ lu_mem lastmajormem; /* memory in use after last major collection */
120+ stringtable strt; /* hash table for strings */
121+ TValue l_registry;
121122 unsigned short nCcalls; /* number of nested C calls */
122123 lu_byte currentwhite;
123124 lu_byte gcstate; /* state of garbage collector */
124125 lu_byte gckind; /* kind of GC running */
125126 int sweepstrgc; /* position of sweep in `strt' */
126− GCObject *rootgc; /* list of all collectable objects */
127+ GCObject *allgc; /* list of all collectable objects */
128+ GCObject *udgc; /* list of collectable userdata with finalizers */
127129 GCObject **sweepgc; /* current position of sweep */
128130 GCObject *gray; /* list of gray objects */
129131 GCObject *grayagain; /* list of objects to be traversed atomically */
@@ -131,19 +133,16 @@ typedef struct global_State { · 1 unmodified line
131133 GCObject *ephemeron; /* list of ephemeron tables (weak keys) */
132134 GCObject *allweak; /* list of all-weak tables */
133135 GCObject *tobefnz; /* list of userdata to be GC */
136+ UpVal uvhead; /* head of double-linked list of all open upvalues */
134137 Mbuffer buff; /* temporary buffer for string concatenation */
135− lu_mem GCthreshold; /* when totalbytes > GCthreshold, run GC step */
136− lu_mem totalbytes; /* number of bytes currently allocated */
137138 int gcpause; /* size of pause between successive GCs */
138139 int gcstepmul; /* GC `granularity' */
139140 lua_CFunction panic; /* to be called in unprotected errors */
140− TValue l_registry;
141− struct Table *l_gt; /* table of globals */
142141 struct lua_State *mainthread;
143− UpVal uvhead; /* head of double-linked list of all open upvalues */
144142 const lua_Number *version; /* pointer to version number */
145− struct Table *mt[NUM_TAGS]; /* metatables for basic types */
143+ TString *memerrmsg; /* memory-error message */
146144 TString *tmname[TM_N]; /* array with tag-method names */
145+ struct Table *mt[LUA_NUMTAGS]; /* metatables for basic types */
147146 } global_State;
148147
149148
@@ -166,7 +165,6 @@ struct lua_State { · 16 unmodified lines
166165 int basehookcount;
167166 int hookcount;
168167 lua_Hook hook;
169− TValue env; /* temporary place for environments */
170168 GCObject *openupval; /* list of open upvalues in this stack */
171169 GCObject *gclist;
172170 struct lua_longjmp *errorJmp; /* current error recover point */
src/lstring.c+7−1
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lstring.c,v 2.16 2009/12/16 16:42:58 roberto Exp $
2+** $Id: lstring.c,v 2.18 2010/05/10 18:23:45 roberto Exp $
33 ** String table (keeps all strings handled by Lua)
44 ** See Copyright Notice in lua.h
55 */
@@ -37,6 +37,7 @@ void luaS_resize (lua_State *L, int newsize) { · 31 unmodified lines
3737 unsigned int h = lmod(gco2ts(p)->hash, newsize); /* new position */
3838 gch(p)->next = tb->hash[h]; /* chain it */
3939 tb->hash[h] = p;
40+ resetoldbit(p); /* see MOVE OLD rule */
4041 p = next;
4142 }
4243 }
@@ -94,6 +95,11 @@ TString *luaS_newlstr (lua_State *L, const char *str, size_t l) { · 51 unmodified lines
9495 }
9596
9697
98+TString *luaS_new (lua_State *L, const char *str) {
99+ return luaS_newlstr(L, str, strlen(str));
100+}
101+
102+
97103 Udata *luaS_newudata (lua_State *L, size_t s, Table *e) {
98104 Udata *u;
99105 if (s > MAX_SIZET - sizeof(Udata))
src/lstring.h+9−3
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lstring.h,v 1.43 2005/04/25 19:24:10 roberto Exp $
2+** $Id: lstring.h,v 1.46 2010/04/05 16:26:37 roberto Exp $
33 ** String table (keep all strings handled by Lua)
44 ** See Copyright Notice in lua.h
55 */
@@ -7,7 +7,6 @@ · 1 unmodified line
77 #ifndef lstring_h
88 #define lstring_h
99
10−
1110 #include "lgc.h"
1211 #include "lobject.h"
1312 #include "lstate.h"
@@ -17,15 +16,22 @@ · 3 unmodified lines
1716
1817 #define sizeudata(u) (sizeof(union Udata)+(u)->len)
1918
20−#define luaS_new(L, s) (luaS_newlstr(L, s, strlen(s)))
2119 #define luaS_newliteral(L, s) (luaS_newlstr(L, "" s, \
2220 (sizeof(s)/sizeof(char))-1))
2321
2422 #define luaS_fix(s) l_setbit((s)->tsv.marked, FIXEDBIT)
2523
24+
25+/*
26+** as all string are internalized, string equality becomes
27+** pointer equality
28+*/
29+#define eqstr(a,b) ((a) == (b))
30+
2631 LUAI_FUNC void luaS_resize (lua_State *L, int newsize);
2732 LUAI_FUNC Udata *luaS_newudata (lua_State *L, size_t s, Table *e);
2833 LUAI_FUNC TString *luaS_newlstr (lua_State *L, const char *str, size_t l);
34+LUAI_FUNC TString *luaS_new (lua_State *L, const char *str);
2935
3036
3137 #endif
src/lstrlib.c+79−53
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lstrlib.c,v 1.148 2010/01/04 16:37:19 roberto Exp $
2+** $Id: lstrlib.c,v 1.152 2010/05/04 17:20:33 roberto Exp $
33 ** Standard library for string operations and pattern-matching
44 ** See Copyright Notice in lua.h
55 */
@@ -65,12 +65,13 @@ static int str_sub (lua_State *L) { · 59 unmodified lines
6565
6666
6767 static int str_reverse (lua_State *L) {
68− size_t l;
68+ size_t l, i;
6969 luaL_Buffer b;
7070 const char *s = luaL_checklstring(L, 1, &l);
71− luaL_buffinit(L, &b);
72− while (l--) luaL_addchar(&b, s[l]);
73− luaL_pushresult(&b);
71+ char *p = luaL_buffinitsize(L, &b, l);
72+ for (i = 0; i < l; i++)
73+ p[i] = s[l - i - 1];
74+ luaL_pushresultsize(&b, l);
7475 return 1;
7576 }
7677
@@ -80,10 +81,10 @@ static int str_lower (lua_State *L) { · 3 unmodified lines
8081 size_t i;
8182 luaL_Buffer b;
8283 const char *s = luaL_checklstring(L, 1, &l);
83− luaL_buffinit(L, &b);
84+ char *p = luaL_buffinitsize(L, &b, l);
8485 for (i=0; i<l; i++)
85− luaL_addchar(&b, tolower(uchar(s[i])));
86− luaL_pushresult(&b);
86+ p[i] = tolower(uchar(s[i]));
87+ luaL_pushresultsize(&b, l);
8788 return 1;
8889 }
8990
@@ -93,10 +94,10 @@ static int str_upper (lua_State *L) { · 3 unmodified lines
9394 size_t i;
9495 luaL_Buffer b;
9596 const char *s = luaL_checklstring(L, 1, &l);
96− luaL_buffinit(L, &b);
97+ char *p = luaL_buffinitsize(L, &b, l);
9798 for (i=0; i<l; i++)
98− luaL_addchar(&b, toupper(uchar(s[i])));
99− luaL_pushresult(&b);
99+ p[i] = toupper(uchar(s[i]));
100+ luaL_pushresultsize(&b, l);
100101 return 1;
101102 }
102103
@@ -136,13 +137,13 @@ static int str_char (lua_State *L) { · 33 unmodified lines
136137 int n = lua_gettop(L); /* number of arguments */
137138 int i;
138139 luaL_Buffer b;
139− luaL_buffinit(L, &b);
140+ char *p = luaL_buffinitsize(L, &b, n);
140141 for (i=1; i<=n; i++) {
141142 int c = luaL_checkint(L, i);
142143 luaL_argcheck(L, uchar(c) == c, i, "invalid value");
143− luaL_addchar(&b, uchar(c));
144+ p[i - 1] = uchar(c);
144145 }
145− luaL_pushresult(&b);
146+ luaL_pushresultsize(&b, n);
146147 return 1;
147148 }
148149
@@ -179,7 +180,8 @@ static int str_dump (lua_State *L) { · 30 unmodified lines
179180
180181 typedef struct MatchState {
181182 const char *src_init; /* init of source string */
182− const char *src_end; /* end (`\0') of source string */
183+ const char *src_end; /* end ('\0') of source string */
184+ const char *p_end; /* end ('\0') of pattern */
183185 lua_State *L;
184186 int level; /* total number of captures (finished or unfinished) */
185187 struct {
@@ -212,16 +214,16 @@ static int capture_to_close (MatchState *ms) { · 26 unmodified lines
212214 static const char *classend (MatchState *ms, const char *p) {
213215 switch (*p++) {
214216 case L_ESC: {
215− if (*p == '\0')
217+ if (p == ms->p_end)
216218 luaL_error(ms->L, "malformed pattern (ends with " LUA_QL("%%") ")");
217219 return p+1;
218220 }
219221 case '[': {
220222 if (*p == '^') p++;
221223 do { /* look for a `]' */
222− if (*p == '\0')
224+ if (p == ms->p_end)
223225 luaL_error(ms->L, "malformed pattern (missing " LUA_QL("]") ")");
224− if (*(p++) == L_ESC && *p != '\0')
226+ if (*(p++) == L_ESC && p < ms->p_end)
225227 p++; /* skip escapes (e.g. `%]') */
226228 } while (*p != ']');
227229 return p+1;
@@ -245,7 +247,7 @@ static int match_class (int c, int cl) { · 17 unmodified lines
245247 case 'u' : res = isupper(c); break;
246248 case 'w' : res = isalnum(c); break;
247249 case 'x' : res = isxdigit(c); break;
248− case 'z' : res = (c == 0); break;
250+ case 'z' : res = (c == 0); break; /* deprecated option */
249251 default: return (cl == c);
250252 }
251253 return (islower(cl) ? res : !res);
@@ -290,8 +292,9 @@ static const char *match (MatchState *ms, const char *s, const char *p); · 38 unmodified lines
290292
291293 static const char *matchbalance (MatchState *ms, const char *s,
292294 const char *p) {
293− if (*p == 0 || *(p+1) == 0)
294− luaL_error(ms->L, "unbalanced pattern");
295+ if (p >= ms->p_end - 1)
296+ luaL_error(ms->L, "malformed pattern "
297+ "(missing arguments to " LUA_QL("%%b") ")");
295298 if (*s != *p) return NULL;
296299 else {
297300 int b = *p;
@@ -374,6 +377,8 @@ static const char *match_capture (MatchState *ms, const char *s, int l) { · 76 unmodified lines
374377
375378 static const char *match (MatchState *ms, const char *s, const char *p) {
376379 init: /* using goto's to optimize tail recursion */
380+ if (p == ms->p_end) /* end of pattern? */
381+ return s; /* match succeeded */
377382 switch (*p) {
378383 case '(': { /* start capture */
379384 if (*(p+1) == ')') /* position capture? */
@@ -384,11 +389,8 @@ static const char *match (MatchState *ms, const char *s, const char *p) { · 4 unmodified lines
384389 case ')': { /* end capture */
385390 return end_capture(ms, s, p+1);
386391 }
387− case '\0': { /* end of pattern */
388− return s; /* match succeeded */
389− }
390392 case '$': {
391− if (*(p+1) == '\0') /* is the `$' the last char in pattern? */
393+ if ((p+1) == ms->p_end) /* is the `$' the last char in pattern? */
392394 return (s == ms->src_end) ? s : NULL; /* check end of string */
393395 else goto dflt;
394396 }
@@ -418,12 +420,12 @@ static const char *match (MatchState *ms, const char *s, const char *p) { · 23 unmodified lines
418420 if (s == NULL) return NULL;
419421 p+=2; goto init; /* else return match(ms, s, p+2) */
420422 }
421− default: break; /* go through to 'dflt' */
423+ default: goto dflt;
422424 }
423425 }
424426 default: dflt: { /* pattern class plus optional sufix */
425427 const char *ep = classend(ms, p); /* points to what is next */
426− int m = s<ms->src_end && singlematch(uchar(*s), p, ep);
428+ int m = s < ms->src_end && singlematch(uchar(*s), p, ep);
427429 switch (*ep) {
428430 case '?': { /* optional */
429431 const char *res;
@@ -503,32 +505,36 @@ static int push_captures (MatchState *ms, const char *s, const char *e) { · 73 unmodified lines
503505
504506
505507 static int str_find_aux (lua_State *L, int find) {
506− size_t l1, l2;
507− const char *s = luaL_checklstring(L, 1, &l1);
508− const char *p = luaL_checklstring(L, 2, &l2);
509− size_t init = posrelat(luaL_optinteger(L, 3, 1), l1);
508+ size_t ls, lp;
509+ const char *s = luaL_checklstring(L, 1, &ls);
510+ const char *p = luaL_checklstring(L, 2, &lp);
511+ size_t init = posrelat(luaL_optinteger(L, 3, 1), ls);
510512 if (init < 1) init = 1;
511− else if (init > l1 + 1) { /* start after string's end? */
513+ else if (init > ls + 1) { /* start after string's end? */
512514 lua_pushnil(L); /* cannot find anything */
513515 return 1;
514516 }
515517 if (find && (lua_toboolean(L, 4) || /* explicit request? */
516518 strpbrk(p, SPECIALS) == NULL)) { /* or no special characters? */
517519 /* do a plain search */
518− const char *s2 = lmemfind(s + init - 1, l1 - init + 1, p, l2);
520+ const char *s2 = lmemfind(s + init - 1, ls - init + 1, p, lp);
519521 if (s2) {
520522 lua_pushinteger(L, s2 - s + 1);
521− lua_pushinteger(L, s2 - s + l2);
523+ lua_pushinteger(L, s2 - s + lp);
522524 return 2;
523525 }
524526 }
525527 else {
526528 MatchState ms;
527− int anchor = (*p == '^') ? (p++, 1) : 0;
528529 const char *s1 = s + init - 1;
530+ int anchor = (*p == '^');
531+ if (anchor) {
532+ p++; lp--; /* skip anchor character */
533+ }
529534 ms.L = L;
530535 ms.src_init = s;
531− ms.src_end = s + l1;
536+ ms.src_end = s + ls;
537+ ms.p_end = p + lp;
532538 do {
533539 const char *res;
534540 ms.level = 0;
@@ -560,13 +566,14 @@ static int str_match (lua_State *L) { · 25 unmodified lines
560566
561567 static int gmatch_aux (lua_State *L) {
562568 MatchState ms;
563− size_t ls;
569+ size_t ls, lp;
564570 const char *s = lua_tolstring(L, lua_upvalueindex(1), &ls);
565− const char *p = lua_tostring(L, lua_upvalueindex(2));
571+ const char *p = lua_tolstring(L, lua_upvalueindex(2), &lp);
566572 const char *src;
567573 ms.L = L;
568574 ms.src_init = s;
569575 ms.src_end = s+ls;
576+ ms.p_end = p + lp;
570577 for (src = s + (size_t)lua_tointeger(L, lua_upvalueindex(3));
571578 src <= ms.src_end;
572579 src++) {
@@ -658,12 +665,12 @@ static void add_value (MatchState *ms, luaL_Buffer *b, const char *s, · 85 unmodified lines
658665
659666
660667 static int str_gsub (lua_State *L) {
661− size_t srcl;
668+ size_t srcl, lp;
662669 const char *src = luaL_checklstring(L, 1, &srcl);
663− const char *p = luaL_checkstring(L, 2);
670+ const char *p = luaL_checklstring(L, 2, &lp);
664671 int tr = lua_type(L, 3);
665672 size_t max_s = luaL_optinteger(L, 4, srcl+1);
666− int anchor = (*p == '^') ? (p++, 1) : 0;
673+ int anchor = (*p == '^');
667674 size_t n = 0;
668675 MatchState ms;
669676 luaL_Buffer b;
@@ -671,9 +678,13 @@ static int str_gsub (lua_State *L) { · 1 unmodified line
671678 tr == LUA_TFUNCTION || tr == LUA_TTABLE, 3,
672679 "string/function/table expected");
673680 luaL_buffinit(L, &b);
681+ if (anchor) {
682+ p++; lp--; /* skip anchor character */
683+ }
674684 ms.L = L;
675685 ms.src_init = src;
676686 ms.src_end = src+srcl;
687+ ms.p_end = p + lp;
677688 while (n < max_s) {
678689 const char *e;
679690 ms.level = 0;
@@ -698,11 +709,18 @@ static int str_gsub (lua_State *L) { · 18 unmodified lines
698709 /* }====================================================== */
699710
700711
712+
701713 /*
702−** length modifier for integer conversions ** in 'string.format' and
703−** integer type corresponding to the previous length
714+** {======================================================
715+** STRING FORMAT
716+** =======================================================
704717 */
705718
719+/*
720+** LUA_INTFRMLEN is the length modifier for integer conversions in
721+** 'string.format'; LUA_INTFRM_T is the integer type corresponding to
722+** the previous length
723+*/
706724 #if defined(LUA_USELONGLONG)
707725
708726 #define LUA_INTFRMLEN "ll"
@@ -738,7 +756,7 @@ static void addquoted (lua_State *L, luaL_Buffer *b, int arg) { · 29 unmodified lines
738756 }
739757 else if (*s == '\0' || iscntrl(uchar(*s))) {
740758 char buff[10];
741− if (*s != '\0' && !isdigit(uchar(*(s+1))))
759+ if (!isdigit(uchar(*(s+1))))
742760 sprintf(buff, "\\%d", uchar(*s));
743761 else
744762 sprintf(buff, "\\%03d", uchar(*s));
@@ -773,6 +791,9 @@ static const char *scanformat (lua_State *L, const char *strfrmt, char *form) { · 28 unmodified lines
773791 }
774792
775793
794+/*
795+** add length modifier into integer formats
796+*/
776797 static void addintlen (char *form) {
777798 size_t l = strlen(form);
778799 char spec = form[l - 1];
@@ -783,6 +804,7 @@ static void addintlen (char *form) { · 4 unmodified lines
783804
784805
785806 static int str_format (lua_State *L) {
807+ int top = lua_gettop(L);
786808 int arg = 1;
787809 size_t sfl;
788810 const char *strfrmt = luaL_checklstring(L, arg, &sfl);
@@ -796,12 +818,14 @@ static int str_format (lua_State *L) { · 7 unmodified lines
796818 luaL_addchar(&b, *strfrmt++); /* %% */
797819 else { /* format item */
798820 char form[MAX_FORMAT]; /* to store the format (`%...') */
799− char buff[MAX_ITEM]; /* to store the formatted item */
800− arg++;
821+ char *buff = luaL_prepbuffsize(&b, MAX_ITEM); /* to put formatted item */
822+ int nb = 0; /* number of bytes in added item */
823+ if (++arg > top)
824+ luaL_argerror(L, arg, "no value");
801825 strfrmt = scanformat(L, strfrmt, form);
802826 switch (*strfrmt++) {
803827 case 'c': {
804− sprintf(buff, form, luaL_checkint(L, arg));
828+ nb = sprintf(buff, form, luaL_checkint(L, arg));
805829 break;
806830 }
807831 case 'd': case 'i':
@@ -810,17 +834,17 @@ static int str_format (lua_State *L) { · 2 unmodified lines
810834 LUA_INTFRM_T r = (n < 0) ? (LUA_INTFRM_T)n :
811835 (LUA_INTFRM_T)(unsigned LUA_INTFRM_T)n;
812836 addintlen(form);
813− sprintf(buff, form, r);
837+ nb = sprintf(buff, form, r);
814838 break;
815839 }
816840 case 'e': case 'E': case 'f':
817841 case 'g': case 'G': {
818− sprintf(buff, form, (double)luaL_checknumber(L, arg));
842+ nb = sprintf(buff, form, (double)luaL_checknumber(L, arg));
819843 break;
820844 }
821845 case 'q': {
822846 addquoted(L, &b, arg);
823− continue; /* skip the 'addsize' at the end */
847+ break;
824848 }
825849 case 's': {
826850 size_t l;
@@ -830,10 +854,10 @@ static int str_format (lua_State *L) { · 3 unmodified lines
830854 keep original string */
831855 lua_pushvalue(L, arg);
832856 luaL_addvalue(&b);
833− continue; /* skip the `addsize' at the end */
857+ break;
834858 }
835859 else {
836− sprintf(buff, form, s);
860+ nb = sprintf(buff, form, s);
837861 break;
838862 }
839863 }
@@ -842,13 +866,15 @@ static int str_format (lua_State *L) { · 2 unmodified lines
842866 LUA_QL("format"), *(strfrmt - 1));
843867 }
844868 }
845− luaL_addlstring(&b, buff, strlen(buff));
869+ luaL_addsize(&b, nb);
846870 }
847871 }
848872 luaL_pushresult(&b);
849873 return 1;
850874 }
851875
876+/* }====================================================== */
877+
852878
853879 static const luaL_Reg strlib[] = {
854880 {"byte", str_byte},
src/ltable.c+5−2
@@ -1,5 +1,5 @@
11 /*
2−** $Id: ltable.c,v 2.47 2009/12/17 15:46:44 roberto Exp $
2+** $Id: ltable.c,v 2.50 2010/04/18 13:22:48 roberto Exp $
33 ** Lua tables (hash)
44 ** See Copyright Notice in lua.h
55 */
@@ -31,6 +31,7 @@ · 25 unmodified lines
3131 #include "lmem.h"
3232 #include "lobject.h"
3333 #include "lstate.h"
34+#include "lstring.h"
3435 #include "ltable.h"
3536
3637
@@ -108,6 +109,8 @@ static Node *mainposition (const Table *t, const TValue *key) { · 71 unmodified lines
108109 return hashboolean(t, bvalue(key));
109110 case LUA_TLIGHTUSERDATA:
110111 return hashpointer(t, pvalue(key));
112+ case LUA_TLCF:
113+ return hashpointer(t, fvalue(key));
111114 default:
112115 return hashpointer(t, gcvalue(key));
113116 }
@@ -452,7 +455,7 @@ const TValue *luaH_getint (Table *t, int key) { · 338 unmodified lines
452455 const TValue *luaH_getstr (Table *t, TString *key) {
453456 Node *n = hashstr(t, key);
454457 do { /* check whether `key' is somewhere in the chain */
455− if (ttisstring(gkey(n)) && rawtsvalue(gkey(n)) == key)
458+ if (ttisstring(gkey(n)) && eqstr(rawtsvalue(gkey(n)), key))
456459 return gval(n); /* that's it */
457460 else n = gnext(n);
458461 } while (n);
src/ltablib.c+10−10
@@ -1,5 +1,5 @@
11 /*
2−** $Id: ltablib.c,v 1.54 2010/01/13 19:59:10 roberto Exp $
2+** $Id: ltablib.c,v 1.55 2010/03/13 03:57:46 roberto Exp $
33 ** Library for Table Manipulation
44 ** See Copyright Notice in lua.h
55 */
@@ -171,15 +171,15 @@ static int tconcat (lua_State *L) { · 165 unmodified lines
171171 static int pack (lua_State *L) {
172172 int top = lua_gettop(L);
173173 lua_createtable(L, top, 1); /* create result table */
174− /* use function environment as a temporary place to keep new table */
175− lua_replace(L, LUA_ENVIRONINDEX);
176174 lua_pushinteger(L, top); /* number of elements */
177− lua_setfield(L, LUA_ENVIRONINDEX, "n"); /* t.n = number of elements */
178− for (; top >= 1; top--) /* assign elements */
179− lua_rawseti(L, LUA_ENVIRONINDEX, top);
180− lua_pushvalue(L, LUA_ENVIRONINDEX); /* return new table */
181− /* remove new table from environment to allow its later collection */
182− lua_copy(L, LUA_REGISTRYINDEX, LUA_ENVIRONINDEX);
175+ lua_setfield(L, -2, "n"); /* t.n = number of elements */
176+ if (top > 0) { /* at least one element? */
177+ lua_pushvalue(L, 1);
178+ lua_rawseti(L, -2, 1); /* insert first element */
179+ lua_replace(L, 1); /* move table into its position (index 1) */
180+ for (; top >= 2; top--) /* assign other elements */
181+ lua_rawseti(L, 1, top);
182+ }
183183 return 1;
184184 }
185185
@@ -328,7 +328,7 @@ LUAMOD_API int luaopen_table (lua_State *L) { · 142 unmodified lines
328328 #if defined(LUA_COMPAT_UNPACK)
329329 /* _G.unpack = table.unpack */
330330 lua_getfield(L, -1, "unpack");
331− lua_setfield(L, LUA_ENVIRONINDEX, "unpack");
331+ lua_setglobal(L, "unpack");
332332 #endif
333333 return 1;
334334 }
src/ltm.c+2−2
@@ -1,5 +1,5 @@
11 /*
2−** $Id: ltm.c,v 2.11 2010/01/13 16:18:25 roberto Exp $
2+** $Id: ltm.c,v 2.12 2010/04/13 20:48:12 roberto Exp $
33 ** Tag methods
44 ** See Copyright Notice in lua.h
55 */
@@ -70,7 +70,7 @@ const TValue *luaT_gettmbyobj (lua_State *L, const TValue *o, TMS event) { · 64 unmodified lines
7070 mt = uvalue(o)->metatable;
7171 break;
7272 default:
73− mt = G(L)->mt[ttype(o)];
73+ mt = G(L)->mt[ttypenv(o)];
7474 }
7575 return (mt ? luaH_getstr(mt, G(L)->tmname[event]) : luaO_nilobject);
7676 }
src/ltm.h+3−2
@@ -1,5 +1,5 @@
11 /*
2−** $Id: ltm.h,v 2.9 2010/01/13 16:18:25 roberto Exp $
2+** $Id: ltm.h,v 2.10 2010/04/13 20:48:12 roberto Exp $
33 ** Tag methods
44 ** See Copyright Notice in lua.h
55 */
@@ -43,7 +43,8 @@ typedef enum { · 37 unmodified lines
4343
4444 #define fasttm(l,et,e) gfasttm(G(l), et, e)
4545
46−#define typename(x) luaT_typenames_[(x) + 1]
46+#define ttypename(x) luaT_typenames_[(x) + 1]
47+#define objtypename(x) ttypename(ttypenv(x))
4748
4849 LUAI_DDEC const char *const luaT_typenames_[];
4950
src/lua.c+27−25
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lua.c,v 1.182 2009/12/22 16:47:12 roberto Exp $
2+** $Id: lua.c,v 1.190 2010/04/14 15:14:21 roberto Exp $
33 ** Lua stand-alone interpreter
44 ** See Copyright Notice in lua.h
55 */
@@ -102,26 +102,31 @@ static void laction (int i) { · 96 unmodified lines
102102 }
103103
104104
105−static void print_usage (void) {
106− fprintf(stderr,
105+static void print_usage (const char *badoption) {
106+ if (badoption[1] == 'e' || badoption[1] == 'l') {
107+ luai_writestringerror("%s: ", progname);
108+ luai_writestringerror("'%s' needs argument\n", badoption);
109+ } else {
110+ luai_writestringerror("%s: ", progname);
111+ luai_writestringerror("unrecognized option '%s'\n", badoption);
112+ }
113+ luai_writestringerror(
107114 "usage: %s [options] [script [args]]\n"
108115 "Available options are:\n"
109116 " -e stat execute string " LUA_QL("stat") "\n"
110− " -l name require library " LUA_QL("name") "\n"
111117 " -i enter interactive mode after executing " LUA_QL("script") "\n"
118+ " -l name require library " LUA_QL("name") "\n"
112119 " -v show version information\n"
113120 " -- stop handling options\n"
114− " - execute stdin and stop handling options\n"
121+ " - stop handling options and execute stdin\n"
115122 ,
116123 progname);
117− fflush(stderr);
118124 }
119125
120126
121127 static void l_message (const char *pname, const char *msg) {
122− if (pname) fprintf(stderr, "%s: ", pname);
123− fprintf(stderr, "%s\n", msg);
124− fflush(stderr);
128+ if (pname) luai_writestringerror("%s: ", pname);
129+ luai_writestringerror("%s\n", msg);
125130 }
126131
127132
@@ -214,7 +219,7 @@ static int dostring (lua_State *L, const char *s, const char *name) { · 86 unmodified lines
214219
215220
216221 static int dolibrary (lua_State *L, const char *name) {
217− lua_getfield(L, LUA_ENVIRONINDEX, "require");
222+ lua_getglobal(L, "require");
218223 lua_pushstring(L, name);
219224 return report(L, docall(L, 1, 1));
220225 }
@@ -222,7 +227,7 @@ static int dolibrary (lua_State *L, const char *name) { · 1 unmodified line
222227
223228 static const char *get_prompt (lua_State *L, int firstline) {
224229 const char *p;
225− lua_getfield(L, LUA_ENVIRONINDEX, firstline ? "_PROMPT" : "_PROMPT2");
230+ lua_getglobal(L, firstline ? "_PROMPT" : "_PROMPT2");
226231 p = lua_tostring(L, -1);
227232 if (p == NULL) p = (firstline ? LUA_PROMPT : LUA_PROMPT2);
228233 lua_pop(L, 1); /* remove global */
@@ -296,7 +301,7 @@ static void dotty (lua_State *L) { · 67 unmodified lines
296301 report(L, status);
297302 if (status == LUA_OK && lua_gettop(L) > 0) { /* any result to print? */
298303 luaL_checkstack(L, LUA_MINSTACK, "too many results to print");
299− lua_getfield(L, LUA_ENVIRONINDEX, "print");
304+ lua_getglobal(L, "print");
300305 lua_insert(L, 1);
301306 if (lua_pcall(L, lua_gettop(L)-1, 0, 0) != LUA_OK)
302307 l_message(progname, lua_pushfstring(L,
@@ -306,7 +311,6 @@ static void dotty (lua_State *L) { · 3 unmodified lines
306311 }
307312 lua_settop(L, 0); /* clear stack */
308313 luai_writestring("\n", 1);
309− fflush(stdout);
310314 progname = oldprogname;
311315 }
312316
@@ -315,7 +319,7 @@ static int handle_script (lua_State *L, char **argv, int n) { · 2 unmodified lines
315319 int status;
316320 const char *fname;
317321 int narg = getargs(L, argv, n); /* collect arguments */
318− lua_setfield(L, LUA_ENVIRONINDEX, "arg");
322+ lua_setglobal(L, "arg");
319323 fname = argv[n];
320324 if (strcmp(fname, "-") == 0 && strcmp(argv[n-1], "--") != 0)
321325 fname = NULL; /* stdin */
@@ -356,10 +360,11 @@ static int collectargs (char **argv, int *pi, int *pv, int *pe) { · 34 unmodified lines
356360 case 'l':
357361 if (argv[i][2] == '\0') {
358362 i++;
359− if (argv[i] == NULL) return -1;
363+ if (argv[i] == NULL) return -(i - 1);
360364 }
361365 break;
362− default: return -1; /* invalid option */
366+ default: /* invalid option; return its index... */
367+ return -i; /* ...as a negative value */
363368 }
364369 }
365370 return 0;
@@ -369,7 +374,6 @@ static int collectargs (char **argv, int *pi, int *pv, int *pe) { · 3 unmodified lines
369374 static int runargs (lua_State *L, char **argv, int n) {
370375 int i;
371376 for (i = 1; i < n; i++) {
372− if (argv[i] == NULL) continue;
373377 lua_assert(argv[i][0] == '-');
374378 switch (argv[i][1]) { /* option */
375379 case 'e': {
@@ -412,8 +416,8 @@ static int pmain (lua_State *L) { · 36 unmodified lines
412416 int has_i = 0, has_v = 0, has_e = 0;
413417 if (argv[0] && argv[0][0]) progname = argv[0];
414418 script = collectargs(argv, &has_i, &has_v, &has_e);
415− if (script < 0) { /* invalid args? */
416− print_usage();
419+ if (script < 0) { /* invalid arg? */
420+ print_usage(argv[-script]);
417421 return 0;
418422 }
419423 if (has_v) print_version();
@@ -443,7 +447,6 @@ static int pmain (lua_State *L) { · 23 unmodified lines
443447
444448
445449 int main (int argc, char **argv) {
446− static lua_CFunction ppmain = &pmain;
447450 int status, result;
448451 lua_State *L = luaL_newstate(); /* create state */
449452 if (L == NULL) {
@@ -451,11 +454,10 @@ int main (int argc, char **argv) { · 1 unmodified line
451454 return EXIT_FAILURE;
452455 }
453456 /* call 'pmain' in protected mode */
454− lua_rawgeti(L, LUA_REGISTRYINDEX, LUA_RIDX_CPCALL); /* calling function */
455− lua_pushlightuserdata(L, &ppmain);
456− lua_pushinteger(L, argc);
457− lua_pushlightuserdata(L, argv);
458− status = lua_pcall(L, 3, 1, 0);
457+ lua_pushcfunction(L, &pmain);
458+ lua_pushinteger(L, argc); /* 1st argument */
459+ lua_pushlightuserdata(L, argv); /* 2nd argument */
460+ status = lua_pcall(L, 2, 1, 0);
459461 result = lua_toboolean(L, -1); /* get result */
460462 finalreport(L, status);
461463 lua_close(L);
src/lua.h+18−12
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lua.h,v 1.261 2010/01/11 17:15:11 roberto Exp $
2+** $Id: lua.h,v 1.270 2010/05/12 14:09:20 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
@@ -17,7 +17,7 @@ · 11 unmodified lines
1717
1818
1919 #define LUA_VERSION "Lua 5.2"
20−#define LUA_RELEASE "Lua 5.2.0 (work2)"
20+#define LUA_RELEASE "Lua 5.2.0 (work3)"
2121 #define LUA_VERSION_NUM 502
2222 #define LUA_COPYRIGHT LUA_RELEASE " Copyright (C) 1994-2010 Lua.org, PUC-Rio"
2323 #define LUA_AUTHORS "R. Ierusalimschy, L. H. de Figueiredo, W. Celes"
@@ -34,8 +34,7 @@ · 10 unmodified lines
3434 ** pseudo-indices
3535 */
3636 #define LUA_REGISTRYINDEX LUAI_FIRSTPSEUDOIDX
37−#define LUA_ENVIRONINDEX (LUA_REGISTRYINDEX - 1)
38−#define lua_upvalueindex(i) (LUA_ENVIRONINDEX - (i))
37+#define lua_upvalueindex(i) (LUA_REGISTRYINDEX - (i))
3938
4039
4140 /* thread status */
@@ -82,6 +81,8 @@ typedef void * (*lua_Alloc) (void *ud, void *ptr, size_t osize, size_t nsize); · 40 unmodified lines
8281 #define LUA_TUSERDATA 7
8382 #define LUA_TTHREAD 8
8483
84+#define LUA_NUMTAGS 9
85+
8586
8687
8788 /* minimum Lua stack available to a C function */
@@ -90,8 +91,7 @@ typedef void * (*lua_Alloc) (void *ud, void *ptr, size_t osize, size_t nsize); · 2 unmodified lines
9091
9192 /* predefined values in the registry */
9293 #define LUA_RIDX_MAINTHREAD 1
93−#define LUA_RIDX_CPCALL 2
94−#define LUA_RIDX_GLOBALS 3
94+#define LUA_RIDX_GLOBALS 2
9595 #define LUA_RIDX_LAST LUA_RIDX_GLOBALS
9696
9797
@@ -129,6 +129,7 @@ LUA_API const lua_Number *(lua_version) (lua_State *L); · 31 unmodified lines
129129 /*
130130 ** basic stack manipulation
131131 */
132+LUA_API int (lua_absindex) (lua_State *L, int idx);
132133 LUA_API int (lua_gettop) (lua_State *L);
133134 LUA_API void (lua_settop) (lua_State *L, int idx);
134135 LUA_API void (lua_pushvalue) (lua_State *L, int idx);
@@ -212,7 +213,7 @@ LUA_API void (lua_rawgeti) (lua_State *L, int idx, int n); · 77 unmodified lines
212213 LUA_API void (lua_createtable) (lua_State *L, int narr, int nrec);
213214 LUA_API void *(lua_newuserdata) (lua_State *L, size_t sz);
214215 LUA_API int (lua_getmetatable) (lua_State *L, int objindex);
215−LUA_API void (lua_getfenv) (lua_State *L, int idx);
216+LUA_API void (lua_getenv) (lua_State *L, int idx);
216217
217218
218219 /*
@@ -223,7 +224,7 @@ LUA_API void (lua_setfield) (lua_State *L, int idx, const char *k); · 4 unmodified lines
223224 LUA_API void (lua_rawset) (lua_State *L, int idx);
224225 LUA_API void (lua_rawseti) (lua_State *L, int idx, int n);
225226 LUA_API int (lua_setmetatable) (lua_State *L, int objindex);
226−LUA_API int (lua_setfenv) (lua_State *L, int idx);
227+LUA_API void (lua_setenv) (lua_State *L, int idx);
227228
228229
229230 /*
@@ -267,6 +268,8 @@ LUA_API int (lua_status) (lua_State *L); · 37 unmodified lines
267268 #define LUA_GCSETPAUSE 6
268269 #define LUA_GCSETSTEPMUL 7
269270 #define LUA_GCISRUNNING 8
271+#define LUA_GCGEN 9
272+#define LUA_GCINC 10
270273
271274 LUA_API int (lua_gc) (lua_State *L, int what, int data);
272275
@@ -297,11 +300,14 @@ LUA_API void (lua_setallocf) (lua_State *L, lua_Alloc f, void *ud); · 24 unmodified lines
297300
298301 #define lua_newtable(L) lua_createtable(L, 0, 0)
299302
300−#define lua_setglobal(L,s) lua_setfield(L, LUA_ENVIRONINDEX, (s))
301−#define lua_getglobal(L,s) lua_getfield(L, LUA_ENVIRONINDEX, (s))
303+#define lua_setglobal(L,s) \
304+ (lua_pushglobaltable(L), lua_pushvalue(L, -2), \
305+ lua_setfield(L, -2, (s)), lua_pop(L, 2))
306+
307+#define lua_getglobal(L,s) \
308+ (lua_pushglobaltable(L), lua_getfield(L, -1, (s)), lua_remove(L, -2))
302309
303−#define lua_register(L,n,f) \
304− (lua_pushcfunction(L, (f)), lua_setfield(L, LUA_ENVIRONINDEX, (n)))
310+#define lua_register(L,n,f) (lua_pushcfunction(L, (f)), lua_setglobal(L, (n)))
305311
306312 #define lua_pushcfunction(L,f) lua_pushcclosure(L, (f), 0)
307313
src/luac.c+9−22
@@ -1,5 +1,5 @@
11 /*
2−** $Id: luac.c,v 1.57 2008/03/26 13:40:18 lhf Exp $
2+** $Id: luac.c,v 1.61 2010/05/14 11:40:22 lhf Exp $
33 ** Lua compiler (saves bytecodes to files; also list bytecodes)
44 ** See Copyright Notice in lua.h
55 */
@@ -60,7 +60,7 @@ static void usage(const char* message) · 54 unmodified lines
6060 " -s strip debug information\n"
6161 " -v show version information\n"
6262 " -- stop handling options\n"
63− " - process stdin and stop handling options\n"
63+ " - stop handling options and process stdin\n"
6464 ,progname,Output);
6565 exit(EXIT_FAILURE);
6666 }
@@ -89,7 +89,7 @@ static int doargs(int argc, char* argv[]) · 22 unmodified lines
8989 else if (IS("-o")) /* output file */
9090 {
9191 output=argv[++i];
92− if (output==NULL || *output==0) usage(LUA_QL("-o") " needs argument");
92+ if (output==NULL || *output==0 || *output=='-') usage(LUA_QL("-o") " needs argument");
9393 if (IS("-")) output=NULL;
9494 }
9595 else if (IS("-p")) /* parse only */
@@ -150,16 +150,10 @@ static int writer(lua_State* L, const void* p, size_t size, void* u) · 54 unmodified lines
150150 return (fwrite(p,size,1,(FILE*)u)!=1) && (size!=0);
151151 }
152152
153−struct Smain {
154− int argc;
155− char** argv;
156−};
157−
158153 static int pmain(lua_State* L)
159154 {
160− struct Smain* s = (struct Smain*)lua_touserdata(L, 1);
161− int argc=s->argc;
162− char** argv=s->argv;
155+ int argc=lua_tointeger(L,1);
156+ char** argv=lua_touserdata(L,2);
163157 const Proto* f;
164158 int i;
165159 if (!lua_checkstack(L,argc)) fatal("too many input files");
@@ -183,25 +177,18 @@ static int pmain(lua_State* L) · 17 unmodified lines
183177 return 0;
184178 }
185179
186−LUA_API int lua_cpcall (lua_State *L, lua_CFunction func, void *ud) {
187− lua_rawgeti(L, LUA_REGISTRYINDEX, LUA_RIDX_CPCALL);
188− lua_pushlightuserdata(L, &func);
189− lua_pushlightuserdata(L, ud);
190− return lua_pcall(L, 2, 0, 0);
191−}
192−
193180 int main(int argc, char* argv[])
194181 {
195182 lua_State* L;
196− struct Smain s;
197183 int i=doargs(argc,argv);
198184 argc-=i; argv+=i;
199185 if (argc<=0) usage("no input files given");
200186 L=luaL_newstate();
201187 if (L==NULL) fatal("not enough memory for state");
202− s.argc=argc;
203− s.argv=argv;
204− if (lua_cpcall(L,pmain,&s)!=0) fatal(lua_tostring(L,-1));
188+ lua_pushcfunction(L,&pmain);
189+ lua_pushinteger(L,argc);
190+ lua_pushlightuserdata(L,argv);
191+ if (lua_pcall(L,2,0,0)!=0) fatal(lua_tostring(L,-1));
205192 lua_close(L);
206193 return EXIT_SUCCESS;
207194 }
src/luaconf.h+37−34
@@ -1,5 +1,5 @@
11 /*
2−** $Id: luaconf.h,v 1.130 2010/01/11 17:15:30 roberto Exp $
2+** $Id: luaconf.h,v 1.137 2010/05/12 14:17:36 roberto Exp $
33 ** Configuration file for Lua
44 ** See Copyright Notice in lua.h
55 */
@@ -89,7 +89,7 @@ · 83 unmodified lines
8989 #define LUA_CPATH_DEFAULT \
9090 LUA_CDIR"?.dll;" LUA_CDIR"loadall.dll;" ".\\?.dll"
9191
92−#else
92+#else /* _WIN32 */
9393 #define LUA_ROOT "/usr/local/"
9494 #define LUA_LDIR LUA_ROOT "share/lua/5.2/"
9595 #define LUA_CDIR LUA_ROOT "lib/lua/5.2/"
@@ -98,7 +98,7 @@ · 2 unmodified lines
9898 LUA_CDIR"?.lua;" LUA_CDIR"?/init.lua;" "./?.lua"
9999 #define LUA_CPATH_DEFAULT \
100100 LUA_CDIR"?.so;" LUA_CDIR"loadall.so;" "./?.so"
101−#endif
101+#endif /* _WIN32 */
102102
103103
104104 /*
@@ -130,11 +130,12 @@ · 25 unmodified lines
130130 #define LUA_API __declspec(dllimport)
131131 #endif
132132
133−#else
133+#else /* LUA_BUILD_AS_DLL */
134134
135135 #define LUA_API extern
136136
137−#endif
137+#endif /* LUA_BUILD_AS_DLL */
138+
138139
139140 /* more often than not the libs go together with the core */
140141 #define LUALIB_API LUA_API
@@ -166,11 +167,11 @@ · 25 unmodified lines
166167 #define LUAI_DDEC LUAI_FUNC
167168 #define LUAI_DDEF /* empty */
168169
169−#else
170+#else /* luaall_c */
170171 #define LUAI_FUNC extern
171172 #define LUAI_DDEC extern
172173 #define LUAI_DDEF /* empty */
173−#endif
174+#endif /* luaall_c */
174175
175176
176177
@@ -192,10 +193,17 @@ · 15 unmodified lines
192193
193194 /*
194195 @@ luai_writestring defines how 'print' prints its results.
195−** CHANGE it if your system does not have a useful stdout.
196196 */
197+#include <stdio.h>
197198 #define luai_writestring(s,l) fwrite((s), sizeof(char), (l), stdout)
198199
200+/*
201+@@ luai_writestringerror defines how to print error messages.
202+** (A format string with one argument is enough for Lua...)
203+*/
204+#define luai_writestringerror(s,p) \
205+ (fprintf(stderr, (s), (p)), fflush(stderr))
206+
199207
200208
201209
@@ -220,18 +228,12 @@ · 18 unmodified lines
220228 #define LUA_COMPAT_UNPACK
221229
222230 /*
223−@@ LUA_COMPAT_CPCALL controls the presence of function 'lua_cpcall'.
231+@@ LUA_COMPAT_CPCALL controls the presence of macro 'lua_cpcall'.
224232 ** You can replace it with the preregistered function 'cpcall'.
225233 */
226−#define LUA_COMPAT_CPCALL
227−LUA_API int (lua_cpcall) (lua_State *L, lua_CFunction func, void *ud);
234+#define lua_cpcall(L,f,u) \
235+ (lua_pushlightuserdata(L,(u)), luaL_cpcall(L,(f),1,0))
228236
229−/*
230−@@ LUA_COMPAT_FENV controls the presence of functions 'setfenv/getfenv'.
231−** You can replace them with lexical environments, 'loadin', or the
232−** debug library.
233−*/
234−#define LUA_COMPAT_FENV
235237
236238 /*
237239 @@ LUA_COMPAT_LOG10 defines the function 'log10' in the math library.
@@ -267,7 +269,7 @@ LUA_API int (lua_cpcall) (lua_State *L, lua_CFunction func, void *ud); · 29 unmodified lines
267269 /* compatibility with previous wrong spelling */
268270 #define luaL_typerror luaL_typeerror
269271
270−#endif
272+#endif /* LUA_COMPAT_ALL */
271273
272274 /* }================================================================== */
273275
@@ -421,7 +423,7 @@ LUA_API int (lua_cpcall) (lua_State *L, lua_CFunction func, void *ud); · 147 unmodified lines
421423
422424 /*
423425 @@ lua_number2int is a macro to convert lua_Number to int.
424−@@ lua_number2integer is a macro to convert lua_Number to lUA_INTEGER.
426+@@ lua_number2integer is a macro to convert lua_Number to LUA_INTEGER.
425427 @@ lua_number2uint is a macro to convert a lua_Number to an unsigned
426428 @* LUA_INT32.
427429 @@ lua_uint2number is a macro to convert an unsigned LUA_INT32
@@ -439,30 +441,31 @@ LUA_API int (lua_cpcall) (lua_State *L, lua_CFunction func, void *ud); · 11 unmodified lines
439441 /* On a Microsoft compiler, use assembler */
440442 #if defined(_MSC_VER)
441443
442−#define lua_number2int(i,d) {__asm fld d __asm fistp i}
444+#define lua_number2int(i,n) __asm {__asm fld n __asm fistp i}
443445 #define lua_number2integer(i,n) lua_number2int(i, n)
444−#define lua_number2uint(i,n) lua_number2int(i, n)
446+#define lua_number2uint(i,n) \
447+ {__int64 l; __asm {__asm fld n __asm fistp l} i = (unsigned int)l;}
445448
446−#else
449+#else /* _MSC_VER */
447450 /* the next trick should work on any Pentium, but sometimes clashes
448451 with a DirectX idiosyncrasy */
449452
450453 union luai_Cast { double l_d; long l_l; };
451−#define lua_number2int(i,d) \
452− { volatile union luai_Cast u; u.l_d = (d) + 6755399441055744.0; (i) = u.l_l; }
454+#define lua_number2int(i,n) \
455+ { volatile union luai_Cast u; u.l_d = (n) + 6755399441055744.0; (i) = u.l_l; }
453456 #define lua_number2integer(i,n) lua_number2int(i, n)
454457 #define lua_number2uint(i,n) lua_number2int(i, n)
455458
456−#endif
459+#endif /* _MSC_VER */
457460
458461
459−#else
462+#else /* LUA_NUMBER_DOUBLE ... (Pentium) */
460463 /* this option always works, but may be slow */
461−#define lua_number2int(i,d) ((i)=(int)(d))
462−#define lua_number2integer(i,d) ((i)=(LUA_INTEGER)(d))
463−#define lua_number2uint(i,d) ((i)=(unsigned LUA_INT32)(d))
464+#define lua_number2int(i,n) ((i)=(int)(n))
465+#define lua_number2integer(i,n) ((i)=(LUA_INTEGER)(n))
466+#define lua_number2uint(i,n) ((i)=(unsigned LUA_INT32)(n))
464467
465−#endif
468+#endif /* LUA_NUMBER_DOUBLE ... (Pentium) */
466469
467470
468471 /* on several machines, coercion from unsigned to double is too slow,
@@ -483,11 +486,11 @@ union luai_Cast { double l_d; long l_l; }; · 14 unmodified lines
483486 #include <float.h>
484487 #include <math.h>
485488
486−#define luai_hashnum(i,d) { int e; \
487− d = frexp(d, &e) * (lua_Number)(INT_MAX - DBL_MAX_EXP); \
488− lua_number2int(i, d); i += e; }
489+#define luai_hashnum(i,n) { int e; \
490+ n = frexp(n, &e) * (lua_Number)(INT_MAX - DBL_MAX_EXP); \
491+ lua_number2int(i, n); i += e; }
489492
490−#endif
493+#endif /* ltable_c */
491494
492495 /* }================================================================== */
493496
src/lundump.c+1−2
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lundump.c,v 2.12 2009/09/30 15:38:37 roberto Exp $
2+** $Id: lundump.c,v 2.13 2010/03/12 19:14:06 roberto Exp $
33 ** load precompiled Lua chunks
44 ** See Copyright Notice in lua.h
55 */
@@ -180,7 +180,6 @@ static Proto* LoadFunction(LoadState* S, TString* p) · 174 unmodified lines
180180 f->numparams=LoadByte(S);
181181 f->is_vararg=LoadByte(S);
182182 f->maxstacksize=LoadByte(S);
183− f->envreg=LoadByte(S);
184183 LoadCode(S,f);
185184 LoadConstants(S,f);
186185 LoadUpvalues(S,f);
src/lvm.c+137−197
@@ -1,5 +1,5 @@
11 /*
2−** $Id: lvm.c,v 2.102 2009/12/17 16:20:01 roberto Exp $
2+** $Id: lvm.c,v 2.120 2010/05/13 19:53:05 roberto Exp $
33 ** Lua virtual machine
44 ** See Copyright Notice in lua.h
55 */
@@ -50,8 +50,8 @@ int luaV_tostring (lua_State *L, StkId obj) { · 44 unmodified lines
5050 else {
5151 char s[LUAI_MAXNUMBER2STR];
5252 lua_Number n = nvalue(obj);
53− lua_number2str(s, n);
54− setsvalue2s(L, obj, luaS_new(L, s));
53+ int l = lua_number2str(s, n);
54+ setsvalue2s(L, obj, luaS_newlstr(L, s, l));
5555 return 1;
5656 }
5757 }
@@ -74,6 +74,10 @@ static void traceexec (lua_State *L) { · 16 unmodified lines
7474 luaD_hook(L, LUA_HOOKLINE, newline);
7575 }
7676 L->oldpc = ci->u.l.savedpc;
77+ if (L->status == LUA_YIELD) { /* did hook yield? */
78+ ci->u.l.savedpc--; /* undo increment (resume will increment it again) */
79+ luaD_throw(L, LUA_YIELD);
80+ }
7781 }
7882
7983
@@ -102,7 +106,7 @@ void luaV_gettable (lua_State *L, const TValue *t, TValue *key, StkId val) { · 22 unmodified lines
102106 if (ttistable(t)) { /* `t' is a table? */
103107 Table *h = hvalue(t);
104108 const TValue *res = luaH_get(h, key); /* do a primitive get */
105− if (!ttisnil(res) || /* result is no nil? */
109+ if (!ttisnil(res) || /* result is not nil? */
106110 (tm = fasttm(L, h->metatable, TM_INDEX)) == NULL) { /* or no TM? */
107111 setobj2s(L, val, res);
108112 return;
@@ -129,7 +133,7 @@ void luaV_settable (lua_State *L, const TValue *t, TValue *key, StkId val) { · 20 unmodified lines
129133 if (ttistable(t)) { /* `t' is a table? */
130134 Table *h = hvalue(t);
131135 TValue *oldval = luaH_set(L, h, key); /* do a primitive set */
132− if (!ttisnil(oldval) || /* result is no nil? */
136+ if (!ttisnil(oldval) || /* result is not nil? */
133137 (tm = fasttm(L, h->metatable, TM_NEWINDEX)) == NULL) { /* or no TM? */
134138 setobj2t(L, oldval, val);
135139 luaC_barriert(L, h, val);
@@ -157,12 +161,13 @@ static int call_binTM (lua_State *L, const TValue *p1, const TValue *p2, · 21 unmodified lines
157161 if (ttisnil(tm))
158162 tm = luaT_gettmbyobj(L, p2, event); /* try second operand */
159163 if (ttisnil(tm)) return 0;
164+ if (event == TM_UNM) p2 = luaO_nilobject;
160165 callTM(L, tm, p1, p2, res, 1);
161166 return 1;
162167 }
163168
164169
165−static const TValue *get_compTM (lua_State *L, Table *mt1, Table *mt2,
170+static const TValue *get_equalTM (lua_State *L, Table *mt1, Table *mt2,
166171 TMS event) {
167172 const TValue *tm1 = fasttm(L, mt1, event);
168173 const TValue *tm2;
@@ -178,14 +183,10 @@ static const TValue *get_compTM (lua_State *L, Table *mt1, Table *mt2, · 9 unmodified lines
178183
179184 static int call_orderTM (lua_State *L, const TValue *p1, const TValue *p2,
180185 TMS event) {
181− const TValue *tm1 = luaT_gettmbyobj(L, p1, event);
182− const TValue *tm2;
183− if (ttisnil(tm1)) return -1; /* no metamethod? */
184− tm2 = luaT_gettmbyobj(L, p2, event);
185− if (!luaO_rawequalObj(tm1, tm2)) /* different metamethods? */
186− return -1;
187− callTM(L, tm1, p1, p2, L->top, 1);
188− return !l_isfalse(L->top);
186+ if (!call_binTM(L, p1, p2, L->top, event))
187+ return -1; /* no metamethod */
188+ else
189+ return !l_isfalse(L->top);
189190 }
190191
191192
@@ -213,11 +214,9 @@ static int l_strcmp (const TString *ls, const TString *rs) { · 21 unmodified lines
213214
214215 int luaV_lessthan (lua_State *L, const TValue *l, const TValue *r) {
215216 int res;
216− if (ttype(l) != ttype(r))
217− return luaG_ordererror(L, l, r);
218− else if (ttisnumber(l))
217+ if (ttisnumber(l) && ttisnumber(r))
219218 return luai_numlt(L, nvalue(l), nvalue(r));
220− else if (ttisstring(l))
219+ else if (ttisstring(l) && ttisstring(r))
221220 return l_strcmp(rawtsvalue(l), rawtsvalue(r)) < 0;
222221 else if ((res = call_orderTM(L, l, r, TM_LT)) != -1)
223222 return res;
@@ -227,11 +226,9 @@ int luaV_lessthan (lua_State *L, const TValue *l, const TValue *r) { · 3 unmodified lines
227226
228227 int luaV_lessequal (lua_State *L, const TValue *l, const TValue *r) {
229228 int res;
230− if (ttype(l) != ttype(r))
231− return luaG_ordererror(L, l, r);
232− else if (ttisnumber(l))
229+ if (ttisnumber(l) && ttisnumber(r))
233230 return luai_numle(L, nvalue(l), nvalue(r));
234− else if (ttisstring(l))
231+ else if (ttisstring(l) && ttisstring(r))
235232 return l_strcmp(rawtsvalue(l), rawtsvalue(r)) <= 0;
236233 else if ((res = call_orderTM(L, l, r, TM_LE)) != -1) /* first try `le' */
237234 return res;
@@ -249,14 +246,16 @@ int luaV_equalval_ (lua_State *L, const TValue *t1, const TValue *t2) { · 11 unmodified lines
249246 case LUA_TNUMBER: return luai_numeq(nvalue(t1), nvalue(t2));
250247 case LUA_TBOOLEAN: return bvalue(t1) == bvalue(t2); /* true must be 1 !! */
251248 case LUA_TLIGHTUSERDATA: return pvalue(t1) == pvalue(t2);
249+ case LUA_TLCF: return fvalue(t1) == fvalue(t2);
250+ case LUA_TSTRING: return eqstr(rawtsvalue(t1), rawtsvalue(t2));
252251 case LUA_TUSERDATA: {
253252 if (uvalue(t1) == uvalue(t2)) return 1;
254− tm = get_compTM(L, uvalue(t1)->metatable, uvalue(t2)->metatable, TM_EQ);
253+ tm = get_equalTM(L, uvalue(t1)->metatable, uvalue(t2)->metatable, TM_EQ);
255254 break; /* will try TM */
256255 }
257256 case LUA_TTABLE: {
258257 if (hvalue(t1) == hvalue(t2)) return 1;
259− tm = get_compTM(L, hvalue(t1)->metatable, hvalue(t2)->metatable, TM_EQ);
258+ tm = get_equalTM(L, hvalue(t1)->metatable, hvalue(t2)->metatable, TM_EQ);
260259 break; /* will try TM */
261260 }
262261 default: return gcvalue(t1) == gcvalue(t2);
@@ -354,14 +353,10 @@ void luaV_finishOp (lua_State *L) { · 91 unmodified lines
354353 StkId base = ci->u.l.base;
355354 Instruction inst = *(ci->u.l.savedpc - 1); /* interrupted instruction */
356355 OpCode op = GET_OPCODE(inst);
357− if (op == OP_EXTRAARG) { /* extra argument? */
358− inst = *(ci->u.l.savedpc - 2); /* get its 'main' instruction */
359− op = GET_OPCODE(inst);
360− }
361356 switch (op) { /* finish its execution */
362357 case OP_ADD: case OP_SUB: case OP_MUL: case OP_DIV:
363358 case OP_MOD: case OP_POW: case OP_UNM: case OP_LEN:
364− case OP_GETGLOBAL: case OP_GETTABLE: case OP_SELF: {
359+ case OP_GETTABUP: case OP_GETTABLE: case OP_SELF: {
365360 setobjs2s(L, base + GETARG_A(inst), --L->top);
366361 break;
367362 }
@@ -402,7 +397,7 @@ void luaV_finishOp (lua_State *L) { · 34 unmodified lines
402397 L->top = ci->top; /* adjust results */
403398 break;
404399 }
405− case OP_TAILCALL: case OP_SETGLOBAL: case OP_SETTABLE:
400+ case OP_TAILCALL: case OP_SETTABUP: case OP_SETTABLE:
406401 break;
407402 default: lua_assert(0);
408403 }
@@ -426,11 +421,13 @@ void luaV_finishOp (lua_State *L) { · 17 unmodified lines
426421 (k + (GETARG_Bx(i) != 0 ? GETARG_Bx(i) - 1 : GETARG_Ax(*ci->u.l.savedpc++)))
427422
428423
429−#define dojump(i) { ci->u.l.savedpc += (i); luai_threadyield(L);}
424+#define dojump(i) (ci->u.l.savedpc += (i))
430425
431426
432427 #define Protect(x) { {x;}; base = ci->u.l.base; }
433428
429+#define checkGC(L) Protect(luaC_checkGC(L); luai_threadyield(L);)
430+
434431
435432 #define arith_op(op,tm) { \
436433 TValue *rb = RKB(i); \
@@ -439,133 +436,109 @@ void luaV_finishOp (lua_State *L) { · 2 unmodified lines
439436 lua_Number nb = nvalue(rb), nc = nvalue(rc); \
440437 setnvalue(ra, op(L, nb, nc)); \
441438 } \
442− else \
443− Protect(luaV_arith(L, ra, rb, rc, tm)); \
444− }
439+ else { Protect(luaV_arith(L, ra, rb, rc, tm)); } }
445440
446441
442+#define vmdispatch(o) switch(o)
443+#define vmcase(l,b) case l: {b} break;
447444
448445 void luaV_execute (lua_State *L) {
449446 CallInfo *ci = L->ci;
450− LClosure *cl = &clvalue(ci->func)->l;
451− TValue *k = cl->p->k;
452− StkId base = ci->u.l.base;
447+ LClosure *cl;
448+ TValue *k;
449+ StkId base;
450+ newframe: /* reentry point when frame changes (call/return) */
453451 lua_assert(isLua(ci));
452+ lua_assert(ci == L->ci);
453+ cl = &clvalue(ci->func)->l;
454+ k = cl->p->k;
455+ base = ci->u.l.base;
454456 /* main loop of interpreter */
455457 for (;;) {
456458 Instruction i = *(ci->u.l.savedpc++);
457459 StkId ra;
458460 if ((L->hookmask & (LUA_MASKLINE | LUA_MASKCOUNT)) &&
459461 (--L->hookcount == 0 || L->hookmask & LUA_MASKLINE)) {
460− traceexec(L);
461− if (L->status == LUA_YIELD) { /* did hook yield? */
462− ci->u.l.savedpc--; /* undo increment */
463− luaD_throw(L, LUA_YIELD);
464− }
465− base = ci->u.l.base;
462+ Protect(traceexec(L));
466463 }
467464 /* warning!! several calls may realloc the stack and invalidate `ra' */
468465 ra = RA(i);
469466 lua_assert(base == ci->u.l.base);
470467 lua_assert(base <= L->top && L->top < L->stack + L->stacksize);
471− switch (GET_OPCODE(i)) {
472− case OP_MOVE: {
468+ vmdispatch (GET_OPCODE(i)) {
469+ vmcase(OP_MOVE,
473470 setobjs2s(L, ra, RB(i));
474− continue;
475− }
476− case OP_LOADK: {
471+ )
472+ vmcase(OP_LOADK,
477473 TValue *rb = KBx(i);
478474 setobj2s(L, ra, rb);
479− continue;
480− }
481− case OP_LOADBOOL: {
475+ )
476+ vmcase(OP_LOADBOOL,
482477 setbvalue(ra, GETARG_B(i));
483478 if (GETARG_C(i)) ci->u.l.savedpc++; /* skip next instruction (if C) */
484− continue;
485− }
486− case OP_LOADNIL: {
479+ )
480+ vmcase(OP_LOADNIL,
487481 TValue *rb = RB(i);
488482 do {
489483 setnilvalue(rb--);
490484 } while (rb >= ra);
491− continue;
492− }
493− case OP_GETUPVAL: {
485+ )
486+ vmcase(OP_GETUPVAL,
494487 int b = GETARG_B(i);
495488 setobj2s(L, ra, cl->upvals[b]->v);
496− continue;
497− }
498− case OP_GETGLOBAL: {
499− TValue g;
500− TValue *rb = KBx(i);
501− sethvalue(L, &g, cl->env);
502− lua_assert(ttisstring(rb));
503− Protect(luaV_gettable(L, &g, rb, ra));
504− continue;
505− }
506− case OP_GETTABLE: {
489+ )
490+ vmcase(OP_GETTABUP,
491+ int b = GETARG_B(i);
492+ Protect(luaV_gettable(L, cl->upvals[b]->v, RKC(i), ra));
493+ )
494+ vmcase(OP_GETTABLE,
507495 Protect(luaV_gettable(L, RB(i), RKC(i), ra));
508− continue;
509− }
510− case OP_SETGLOBAL: {
511− TValue g;
512− TValue *rb = KBx(i);
513− sethvalue(L, &g, cl->env);
514− lua_assert(ttisstring(rb));
515− Protect(luaV_settable(L, &g, rb, ra));
516− continue;
517− }
518− case OP_SETUPVAL: {
496+ )
497+ vmcase(OP_SETTABUP,
498+ int a = GETARG_A(i);
499+ Protect(luaV_settable(L, cl->upvals[a]->v, RKB(i), RKC(i)));
500+ )
501+ vmcase(OP_SETUPVAL,
519502 UpVal *uv = cl->upvals[GETARG_B(i)];
520503 setobj(L, uv->v, ra);
521504 luaC_barrier(L, uv, ra);
522− continue;
523− }
524− case OP_SETTABLE: {
505+ )
506+ vmcase(OP_SETTABLE,
525507 Protect(luaV_settable(L, ra, RKB(i), RKC(i)));
526− continue;
527− }
528− case OP_NEWTABLE: {
508+ )
509+ vmcase(OP_NEWTABLE,
529510 int b = GETARG_B(i);
530511 int c = GETARG_C(i);
531512 Table *t = luaH_new(L);
532513 sethvalue(L, ra, t);
533514 if (b != 0 || c != 0)
534515 luaH_resize(L, t, luaO_fb2int(b), luaO_fb2int(c));
535− Protect(luaC_checkGC(L));
536− continue;
537− }
538− case OP_SELF: {
516+ checkGC(L);
517+ )
518+ vmcase(OP_SELF,
539519 StkId rb = RB(i);
540520 setobjs2s(L, ra+1, rb);
541521 Protect(luaV_gettable(L, rb, RKC(i), ra));
542− continue;
543− }
544− case OP_ADD: {
522+ )
523+ vmcase(OP_ADD,
545524 arith_op(luai_numadd, TM_ADD);
546− continue;
547− }
548− case OP_SUB: {
525+ )
526+ vmcase(OP_SUB,
549527 arith_op(luai_numsub, TM_SUB);
550− continue;
551− }
552− case OP_MUL: {
528+ )
529+ vmcase(OP_MUL,
553530 arith_op(luai_nummul, TM_MUL);
554− continue;
555− }
556− case OP_DIV: {
531+ )
532+ vmcase(OP_DIV,
557533 arith_op(luai_numdiv, TM_DIV);
558− continue;
559− }
560− case OP_MOD: {
534+ )
535+ vmcase(OP_MOD,
561536 arith_op(luai_nummod, TM_MOD);
562− continue;
563− }
564− case OP_POW: {
537+ )
538+ vmcase(OP_POW,
565539 arith_op(luai_numpow, TM_POW);
566− continue;
567− }
568− case OP_UNM: {
540+ )
541+ vmcase(OP_UNM,
569542 TValue *rb = RB(i);
570543 if (ttisnumber(rb)) {
571544 lua_Number nb = nvalue(rb);
@@ -574,31 +547,26 @@ void luaV_execute (lua_State *L) { · 2 unmodified lines
574547 else {
575548 Protect(luaV_arith(L, ra, rb, rb, TM_UNM));
576549 }
577− continue;
578− }
579− case OP_NOT: {
550+ )
551+ vmcase(OP_NOT,
580552 int res = l_isfalse(RB(i)); /* next assignment may change this value */
581553 setbvalue(ra, res);
582− continue;
583− }
584− case OP_LEN: {
554+ )
555+ vmcase(OP_LEN,
585556 Protect(luaV_objlen(L, ra, RB(i)));
586− continue;
587− }
588− case OP_CONCAT: {
557+ )
558+ vmcase(OP_CONCAT,
589559 int b = GETARG_B(i);
590560 int c = GETARG_C(i);
591561 L->top = base + c + 1; /* mark the end of concat operands */
592− Protect(luaV_concat(L, c-b+1); luaC_checkGC(L));
562+ Protect(luaV_concat(L, c-b+1); checkGC(L);)
593563 L->top = ci->top; /* restore top */
594564 setobjs2s(L, RA(i), base+b);
595− continue;
596− }
597− case OP_JMP: {
565+ )
566+ vmcase(OP_JMP,
598567 dojump(GETARG_sBx(i));
599− continue;
600− }
601− case OP_EQ: {
568+ )
569+ vmcase(OP_EQ,
602570 TValue *rb = RKB(i);
603571 TValue *rc = RKC(i);
604572 Protect(
@@ -606,62 +574,54 @@ void luaV_execute (lua_State *L) { · 1 unmodified line
606574 dojump(GETARG_sBx(*ci->u.l.savedpc));
607575 )
608576 ci->u.l.savedpc++;
609− continue;
610− }
611− case OP_LT: {
577+ )
578+ vmcase(OP_LT,
612579 Protect(
613580 if (luaV_lessthan(L, RKB(i), RKC(i)) == GETARG_A(i))
614581 dojump(GETARG_sBx(*ci->u.l.savedpc));
615582 )
616583 ci->u.l.savedpc++;
617− continue;
618− }
619− case OP_LE: {
584+ )
585+ vmcase(OP_LE,
620586 Protect(
621587 if (luaV_lessequal(L, RKB(i), RKC(i)) == GETARG_A(i))
622588 dojump(GETARG_sBx(*ci->u.l.savedpc));
623589 )
624590 ci->u.l.savedpc++;
625− continue;
626− }
627− case OP_TEST: {
591+ )
592+ vmcase(OP_TEST,
628593 if (GETARG_C(i) ? !l_isfalse(ra) : l_isfalse(ra))
629594 dojump(GETARG_sBx(*ci->u.l.savedpc));
630595 ci->u.l.savedpc++;
631− continue;
632− }
633− case OP_TESTSET: {
596+ )
597+ vmcase(OP_TESTSET,
634598 TValue *rb = RB(i);
635599 if (GETARG_C(i) ? !l_isfalse(rb) : l_isfalse(rb)) {
636600 setobjs2s(L, ra, rb);
637601 dojump(GETARG_sBx(*ci->u.l.savedpc));
638602 }
639603 ci->u.l.savedpc++;
640− continue;
641− }
642− case OP_CALL: {
604+ )
605+ vmcase(OP_CALL,
643606 int b = GETARG_B(i);
644607 int nresults = GETARG_C(i) - 1;
645608 if (b != 0) L->top = ra+b; /* else previous instruction set top */
646609 if (luaD_precall(L, ra, nresults)) { /* C function? */
647610 if (nresults >= 0) L->top = ci->top; /* adjust results */
648611 base = ci->u.l.base;
649− continue;
650612 }
651613 else { /* Lua function */
652614 ci = L->ci;
653615 ci->callstatus |= CIST_REENTRY;
654− break; /* restart luaV_execute over new Lua function */
616+ goto newframe; /* restart luaV_execute over new Lua function */
655617 }
656− }
657− case OP_TAILCALL: {
618+ )
619+ vmcase(OP_TAILCALL,
658620 int b = GETARG_B(i);
659621 if (b != 0) L->top = ra+b; /* else previous instruction set top */
660622 lua_assert(GETARG_C(i) - 1 == LUA_MULTRET);
661− if (luaD_precall(L, ra, LUA_MULTRET)) { /* C function? */
623+ if (luaD_precall(L, ra, LUA_MULTRET)) /* C function? */
662624 base = ci->u.l.base;
663− continue;
664− }
665625 else {
666626 /* tail call: put called frame (n) in place of caller one (o) */
667627 CallInfo *nci = L->ci; /* called frame */
@@ -682,10 +642,10 @@ void luaV_execute (lua_State *L) { · 14 unmodified lines
682642 oci->callstatus |= CIST_TAIL; /* function was tail called */
683643 ci = L->ci = oci; /* remove new frame */
684644 lua_assert(L->top == oci->u.l.base + getproto(ofunc)->maxstacksize);
685− break; /* restart luaV_execute over new Lua function */
645+ goto newframe; /* restart luaV_execute over new Lua function */
686646 }
687− }
688− case OP_RETURN: {
647+ )
648+ vmcase(OP_RETURN,
689649 int b = GETARG_B(i);
690650 if (b != 0) L->top = ra+b-1;
691651 if (cl->p->sizep > 0) luaF_close(L, base);
@@ -697,10 +657,10 @@ void luaV_execute (lua_State *L) { · 5 unmodified lines
697657 if (b) L->top = ci->top;
698658 lua_assert(isLua(ci));
699659 lua_assert(GET_OPCODE(*((ci)->u.l.savedpc - 1)) == OP_CALL);
700− break; /* restart luaV_execute over new Lua function */
660+ goto newframe; /* restart luaV_execute over new Lua function */
701661 }
702− }
703− case OP_FORLOOP: {
662+ )
663+ vmcase(OP_FORLOOP,
704664 lua_Number step = nvalue(ra+2);
705665 lua_Number idx = luai_numadd(L, nvalue(ra), step); /* increment index */
706666 lua_Number limit = nvalue(ra+1);
@@ -710,9 +670,8 @@ void luaV_execute (lua_State *L) { · 3 unmodified lines
710670 setnvalue(ra, idx); /* update internal index... */
711671 setnvalue(ra+3, idx); /* ...and external index */
712672 }
713− continue;
714− }
715− case OP_FORPREP: {
673+ )
674+ vmcase(OP_FORPREP,
716675 const TValue *init = ra;
717676 const TValue *plimit = ra+1;
718677 const TValue *pstep = ra+2;
@@ -724,9 +683,8 @@ void luaV_execute (lua_State *L) { · 5 unmodified lines
724683 luaG_runerror(L, LUA_QL("for") " step must be a number");
725684 setnvalue(ra, luai_numsub(L, nvalue(ra), nvalue(pstep)));
726685 dojump(GETARG_sBx(i));
727− continue;
728− }
729− case OP_TFORCALL: {
686+ )
687+ vmcase(OP_TFORCALL,
730688 StkId cb = ra + 3; /* call base */
731689 setobjs2s(L, cb+2, ra+2);
732690 setobjs2s(L, cb+1, ra+1);
@@ -737,16 +695,16 @@ void luaV_execute (lua_State *L) { · 4 unmodified lines
737695 i = *(ci->u.l.savedpc++); /* go to next instruction */
738696 ra = RA(i);
739697 lua_assert(GET_OPCODE(i) == OP_TFORLOOP);
740− /* go through */
741− }
742− case OP_TFORLOOP: {
698+ goto l_tforloop;
699+ )
700+ vmcase(OP_TFORLOOP,
701+ l_tforloop:
743702 if (!ttisnil(ra + 1)) { /* continue loop? */
744703 setobjs2s(L, ra, ra + 1); /* save control variable */
745704 dojump(GETARG_sBx(i)); /* jump back */
746705 }
747− continue;
748− }
749− case OP_SETLIST: {
706+ )
707+ vmcase(OP_SETLIST,
750708 int n = GETARG_B(i);
751709 int c = GETARG_C(i);
752710 int last;
@@ -759,45 +717,34 @@ void luaV_execute (lua_State *L) { · 6 unmodified lines
759717 h = hvalue(ra);
760718 last = ((c-1)*LFIELDS_PER_FLUSH) + n;
761719 if (last > h->sizearray) /* needs more space? */
762− luaH_resizearray(L, h, last); /* pre-alloc it at once */
720+ luaH_resizearray(L, h, last); /* pre-allocate it at once */
763721 for (; n > 0; n--) {
764722 TValue *val = ra+n;
765723 setobj2t(L, luaH_setint(L, h, last--), val);
766724 luaC_barriert(L, h, val);
767725 }
768726 L->top = ci->top; /* correct top (in case of previous open call) */
769− continue;
770− }
771− case OP_CLOSE: {
727+ )
728+ vmcase(OP_CLOSE,
772729 luaF_close(L, ra);
773− continue;
774− }
775− case OP_CLOSURE: {
730+ )
731+ vmcase(OP_CLOSURE,
776732 Proto *p = cl->p->p[GETARG_Bx(i)]; /* prototype for new closure */
777733 int nup = p->sizeupvalues;
778− Closure *ncl = luaF_newLclosure(L, nup, cl->env);
734+ Closure *ncl = luaF_newLclosure(L, nup);
779735 Upvaldesc *uv = p->upvalues;
780736 int j;
781737 ncl->l.p = p;
782738 setclvalue(L, ra, ncl); /* anchor new closure in stack */
783− if (p->envreg != NO_REG) { /* lexical environment? */
784− StkId env = base + p->envreg;
785− if (!ttistable(env))
786− luaG_runerror(L, "environment is not a table: "
787− "cannot create closure");
788− else
789− ncl->l.env = hvalue(env);
790− }
791739 for (j = 0; j < nup; j++) { /* fill in upvalues */
792740 if (uv[j].instack) /* upvalue refers to local variable? */
793741 ncl->l.upvals[j] = luaF_findupval(L, base + uv[j].idx);
794742 else /* get upvalue from enclosing function */
795743 ncl->l.upvals[j] = cl->upvals[uv[j].idx];
796744 }
797− Protect(luaC_checkGC(L));
798− continue;
799− }
800− case OP_VARARG: {
745+ checkGC(L);
746+ )
747+ vmcase(OP_VARARG,
801748 int b = GETARG_B(i) - 1;
802749 int j;
803750 int n = cast_int(base - ci->func) - cl->p->numparams - 1;
@@ -815,18 +762,11 @@ void luaV_execute (lua_State *L) { · 11 unmodified lines
815762 setnilvalue(ra + j);
816763 }
817764 }
818− continue;
819− }
820− case OP_EXTRAARG: {
821− luaG_runerror(L, "bad opcode");
822− return;
823− }
765+ )
766+ vmcase(OP_EXTRAARG,
767+ lua_assert(0);
768+ )
824769 }
825− /* function changed (call/return): update pointers */
826− lua_assert(ci == L->ci);
827− cl = &clvalue(ci->func)->l;
828− k = cl->p->k;
829− base = ci->u.l.base;
830770 }
831771 }
832772
src/print.c+15−6
@@ -1,5 +1,5 @@
11 /*
2−** $Id: print.c,v 1.58 2008/09/11 12:05:06 lhf Exp $
2+** $Id: print.c,v 1.60 2010/05/17 22:27:10 lhf Exp $
33 ** print bytecodes
44 ** See Copyright Notice in lua.h
55 */
@@ -82,6 +82,7 @@ static void PrintCode(const Proto* f) · 76 unmodified lines
8282 int a=GETARG_A(i);
8383 int b=GETARG_B(i);
8484 int c=GETARG_C(i);
85+ int ax=GETARG_Ax(i);
8586 int bx=GETARG_Bx(i);
8687 int sbx=GETARG_sBx(i);
8788 int line=getfuncline(f,pc);
@@ -99,24 +100,32 @@ static void PrintCode(const Proto* f) · 11 unmodified lines
99100 if (getCMode(o)!=OpArgN) printf(" %d",ISK(c) ? (-1-INDEXK(c)) : c);
100101 break;
101102 case iABx:
102− if (getBMode(o)==OpArgK) printf("%d %d",a,-1-bx); else printf("%d %d",a,bx);
103+ if (getBMode(o)==OpArgK) printf("%d %d",a,-bx); else printf("%d %d",a,bx);
103104 break;
104105 case iAsBx:
105106 if (o==OP_JMP) printf("%d",sbx); else printf("%d %d",a,sbx);
106107 break;
108+ case iAx:
109+ printf("%d",ax);
110+ break;
107111 }
108112 switch (o)
109113 {
110114 case OP_LOADK:
111− printf("\t; "); PrintConstant(f,bx);
115+ printf("\t; "); PrintConstant(f,bx-1);
112116 break;
113117 case OP_GETUPVAL:
114118 case OP_SETUPVAL:
115119 printf("\t; %s", (f->sizeupvalues>0) ? getstr(f->upvalues[b].name) : "-");
116120 break;
117− case OP_GETGLOBAL:
118− case OP_SETGLOBAL:
119− printf("\t; %s",svalue(&f->k[bx]));
121+ case OP_GETTABUP:
122+ printf("\t; %s", (f->sizeupvalues>0) ? getstr(f->upvalues[b].name) : "-");
123+ if (ISK(c)) { printf(" "); PrintConstant(f,INDEXK(c)); }
124+ break;
125+ case OP_SETTABUP:
126+ printf("\t; %s", (f->sizeupvalues>0) ? getstr(f->upvalues[a].name) : "-");
127+ if (ISK(b)) { printf(" "); PrintConstant(f,INDEXK(b)); }
128+ if (ISK(c)) { printf(" "); PrintConstant(f,INDEXK(c)); }
120129 break;
121130 case OP_GETTABLE:
122131 case OP_SELF:

Keyboard shortcuts

General

Show keyboard shortcuts
?
Focus the current search
/

Issues and pull requests

Open filters
f

Issues, pull requests and Inbox

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

Repository code

Go to file
t