2 ** $Id: lvm.c,v 2.63.1.5 2011/08/17 20:43:11 roberto Exp $
4 ** See Copyright Notice in lua.h
31 /* limit for table tag-method chains (to avoid loops) */
32 #define MAXTAGLOOP 100
35 const TValue *luaV_tonumber (const TValue *obj, TValue *n) {
37 if (ttisnumber(obj)) return obj;
38 if (ttisstring(obj) && luaO_str2d(svalue(obj), &num)) {
47 int luaV_tostring (lua_State *L, StkId obj) {
51 char s[LUAI_MAXNUMBER2STR];
52 lua_Number n = nvalue(obj);
54 setsvalue2s(L, obj, luaS_new(L, s));
60 static void traceexec (lua_State *L, const Instruction *pc) {
61 lu_byte mask = L->hookmask;
62 const Instruction *oldpc = L->savedpc;
64 if ((mask & LUA_MASKCOUNT) && L->hookcount == 0) {
66 luaD_callhook(L, LUA_HOOKCOUNT, -1);
68 if (mask & LUA_MASKLINE) {
69 Proto *p = ci_func(L->ci)->l.p;
70 int npc = pcRel(pc, p);
71 int newline = getline(p, npc);
72 /* call linehook when enter a new function, when jump back (loop),
73 or when enter a new line */
74 if (npc == 0 || pc <= oldpc || newline != getline(p, pcRel(oldpc, p)))
75 luaD_callhook(L, LUA_HOOKLINE, newline);
80 static void callTMres (lua_State *L, StkId res, const TValue *f,
81 const TValue *p1, const TValue *p2) {
82 ptrdiff_t result = savestack(L, res);
83 setobj2s(L, L->top, f); /* push function */
84 setobj2s(L, L->top+1, p1); /* 1st argument */
85 setobj2s(L, L->top+2, p2); /* 2nd argument */
86 luaD_checkstack(L, 3);
88 luaD_call(L, L->top - 3, 1);
89 res = restorestack(L, result);
91 setobjs2s(L, res, L->top);
96 static void callTM (lua_State *L, const TValue *f, const TValue *p1,
97 const TValue *p2, const TValue *p3) {
98 setobj2s(L, L->top, f); /* push function */
99 setobj2s(L, L->top+1, p1); /* 1st argument */
100 setobj2s(L, L->top+2, p2); /* 2nd argument */
101 setobj2s(L, L->top+3, p3); /* 3th argument */
102 luaD_checkstack(L, 4);
104 luaD_call(L, L->top - 4, 0);
108 void luaV_gettable (lua_State *L, const TValue *t, TValue *key, StkId val) {
110 for (loop = 0; loop < MAXTAGLOOP; loop++) {
112 if (ttistable(t)) { /* `t' is a table? */
113 Table *h = hvalue(t);
114 const TValue *res = luaH_get(h, key); /* do a primitive get */
115 if (!ttisnil(res) || /* result is no nil? */
116 (tm = fasttm(L, h->metatable, TM_INDEX)) == NULL) { /* or no TM? */
117 setobj2s(L, val, res);
120 /* else will try the tag method */
122 else if (ttisnil(tm = luaT_gettmbyobj(L, t, TM_INDEX)))
123 luaG_typeerror(L, t, "index");
124 if (ttisfunction(tm)) {
125 callTMres(L, val, tm, t, key);
128 t = tm; /* else repeat with `tm' */
130 luaG_runerror(L, "loop in gettable");
134 void luaV_settable (lua_State *L, const TValue *t, TValue *key, StkId val) {
137 for (loop = 0; loop < MAXTAGLOOP; loop++) {
139 if (ttistable(t)) { /* `t' is a table? */
140 Table *h = hvalue(t);
141 TValue *oldval = luaH_set(L, h, key); /* do a primitive set */
142 if (!ttisnil(oldval) || /* result is no nil? */
143 (tm = fasttm(L, h->metatable, TM_NEWINDEX)) == NULL) { /* or no TM? */
144 setobj2t(L, oldval, val);
146 luaC_barriert(L, h, val);
149 /* else will try the tag method */
151 else if (ttisnil(tm = luaT_gettmbyobj(L, t, TM_NEWINDEX)))
152 luaG_typeerror(L, t, "index");
153 if (ttisfunction(tm)) {
154 callTM(L, tm, t, key, val);
157 /* else repeat with `tm' */
158 setobj(L, &temp, tm); /* avoid pointing inside table (may rehash) */
161 luaG_runerror(L, "loop in settable");
165 static int call_binTM (lua_State *L, const TValue *p1, const TValue *p2,
166 StkId res, TMS event) {
167 const TValue *tm = luaT_gettmbyobj(L, p1, event); /* try first operand */
169 tm = luaT_gettmbyobj(L, p2, event); /* try second operand */
170 if (ttisnil(tm)) return 0;
171 callTMres(L, res, tm, p1, p2);
176 static const TValue *get_compTM (lua_State *L, Table *mt1, Table *mt2,
178 const TValue *tm1 = fasttm(L, mt1, event);
180 if (tm1 == NULL) return NULL; /* no metamethod */
181 if (mt1 == mt2) return tm1; /* same metatables => same metamethods */
182 tm2 = fasttm(L, mt2, event);
183 if (tm2 == NULL) return NULL; /* no metamethod */
184 if (luaO_rawequalObj(tm1, tm2)) /* same metamethods? */
190 static int call_orderTM (lua_State *L, const TValue *p1, const TValue *p2,
192 const TValue *tm1 = luaT_gettmbyobj(L, p1, event);
194 if (ttisnil(tm1)) return -1; /* no metamethod? */
195 tm2 = luaT_gettmbyobj(L, p2, event);
196 if (!luaO_rawequalObj(tm1, tm2)) /* different metamethods? */
198 callTMres(L, L->top, tm1, p1, p2);
199 return !l_isfalse(L->top);
203 static int l_strcmp (const TString *ls, const TString *rs) {
204 const char *l = getstr(ls);
205 size_t ll = ls->tsv.len;
206 const char *r = getstr(rs);
207 size_t lr = rs->tsv.len;
209 int temp = strcoll(l, r);
210 if (temp != 0) return temp;
211 else { /* strings are equal up to a `\0' */
212 size_t len = strlen(l); /* index of first `\0' in both strings */
213 if (len == lr) /* r is finished? */
214 return (len == ll) ? 0 : 1;
215 else if (len == ll) /* l is finished? */
216 return -1; /* l is smaller than r (because r is not finished) */
217 /* both strings longer than `len'; go on comparing (after the `\0') */
219 l += len; ll -= len; r += len; lr -= len;
225 int luaV_lessthan (lua_State *L, const TValue *l, const TValue *r) {
227 if (ttype(l) != ttype(r))
228 return luaG_ordererror(L, l, r);
229 else if (ttisnumber(l))
230 return luai_numlt(nvalue(l), nvalue(r));
231 else if (ttisstring(l))
232 return l_strcmp(rawtsvalue(l), rawtsvalue(r)) < 0;
233 else if ((res = call_orderTM(L, l, r, TM_LT)) != -1)
235 return luaG_ordererror(L, l, r);
239 static int lessequal (lua_State *L, const TValue *l, const TValue *r) {
241 if (ttype(l) != ttype(r))
242 return luaG_ordererror(L, l, r);
243 else if (ttisnumber(l))
244 return luai_numle(nvalue(l), nvalue(r));
245 else if (ttisstring(l))
246 return l_strcmp(rawtsvalue(l), rawtsvalue(r)) <= 0;
247 else if ((res = call_orderTM(L, l, r, TM_LE)) != -1) /* first try `le' */
249 else if ((res = call_orderTM(L, r, l, TM_LT)) != -1) /* else try `lt' */
251 return luaG_ordererror(L, l, r);
255 int luaV_equalval (lua_State *L, const TValue *t1, const TValue *t2) {
257 lua_assert(ttype(t1) == ttype(t2));
259 case LUA_TNIL: return 1;
260 case LUA_TNUMBER: return luai_numeq(nvalue(t1), nvalue(t2));
261 case LUA_TBOOLEAN: return bvalue(t1) == bvalue(t2); /* true must be 1 !! */
262 case LUA_TLIGHTUSERDATA: return pvalue(t1) == pvalue(t2);
263 case LUA_TUSERDATA: {
264 if (uvalue(t1) == uvalue(t2)) return 1;
265 tm = get_compTM(L, uvalue(t1)->metatable, uvalue(t2)->metatable,
267 break; /* will try TM */
270 if (hvalue(t1) == hvalue(t2)) return 1;
271 tm = get_compTM(L, hvalue(t1)->metatable, hvalue(t2)->metatable, TM_EQ);
272 break; /* will try TM */
274 default: return gcvalue(t1) == gcvalue(t2);
276 if (tm == NULL) return 0; /* no TM? */
277 callTMres(L, L->top, tm, t1, t2); /* call TM */
278 return !l_isfalse(L->top);
282 void luaV_concat (lua_State *L, int total, int last) {
284 StkId top = L->base + last + 1;
285 int n = 2; /* number of elements handled in this pass (at least 2) */
286 if (!(ttisstring(top-2) || ttisnumber(top-2)) || !tostring(L, top-1)) {
287 if (!call_binTM(L, top-2, top-1, top-2, TM_CONCAT))
288 luaG_concaterror(L, top-2, top-1);
289 } else if (tsvalue(top-1)->len == 0) /* second op is empty? */
290 (void)tostring(L, top - 2); /* result is first op (as string) */
292 /* at least two string values; get as many as possible */
293 size_t tl = tsvalue(top-1)->len;
296 /* collect total length */
297 for (n = 1; n < total && tostring(L, top-n-1); n++) {
298 size_t l = tsvalue(top-n-1)->len;
299 if (l >= MAX_SIZET - tl) luaG_runerror(L, "string length overflow");
302 buffer = luaZ_openspace(L, &G(L)->buff, tl);
304 for (i=n; i>0; i--) { /* concat all strings */
305 size_t l = tsvalue(top-i)->len;
306 memcpy(buffer+tl, svalue(top-i), l);
309 setsvalue2s(L, top-n, luaS_newlstr(L, buffer, tl));
311 total -= n-1; /* got `n' strings to create 1 new */
313 } while (total > 1); /* repeat until only 1 result left */
317 static void Arith (lua_State *L, StkId ra, const TValue *rb,
318 const TValue *rc, TMS op) {
321 if ((b = luaV_tonumber(rb, &tempb)) != NULL &&
322 (c = luaV_tonumber(rc, &tempc)) != NULL) {
323 lua_Number nb = nvalue(b), nc = nvalue(c);
325 case TM_ADD: setnvalue(ra, luai_numadd(nb, nc)); break;
326 case TM_SUB: setnvalue(ra, luai_numsub(nb, nc)); break;
327 case TM_MUL: setnvalue(ra, luai_nummul(nb, nc)); break;
328 case TM_DIV: setnvalue(ra, luai_numdiv(nb, nc)); break;
329 case TM_MOD: setnvalue(ra, luai_nummod(nb, nc)); break;
330 case TM_POW: setnvalue(ra, luai_numpow(nb, nc)); break;
331 case TM_UNM: setnvalue(ra, luai_numunm(nb)); break;
332 default: lua_assert(0); break;
335 else if (!call_binTM(L, rb, rc, ra, op))
336 luaG_aritherror(L, rb, rc);
342 ** some macros for common tasks in `luaV_execute'
345 #define runtime_check(L, c) { if (!(c)) break; }
347 #define RA(i) (base+GETARG_A(i))
348 /* to be used after possible stack reallocation */
349 #define RB(i) check_exp(getBMode(GET_OPCODE(i)) == OpArgR, base+GETARG_B(i))
350 #define RC(i) check_exp(getCMode(GET_OPCODE(i)) == OpArgR, base+GETARG_C(i))
351 #define RKB(i) check_exp(getBMode(GET_OPCODE(i)) == OpArgK, \
352 ISK(GETARG_B(i)) ? k+INDEXK(GETARG_B(i)) : base+GETARG_B(i))
353 #define RKC(i) check_exp(getCMode(GET_OPCODE(i)) == OpArgK, \
354 ISK(GETARG_C(i)) ? k+INDEXK(GETARG_C(i)) : base+GETARG_C(i))
355 #define KBx(i) check_exp(getBMode(GET_OPCODE(i)) == OpArgK, k+GETARG_Bx(i))
358 #define dojump(L,pc,i) {(pc) += (i); luai_threadyield(L);}
361 #define Protect(x) { L->savedpc = pc; {x;}; base = L->base; }
364 #define arith_op(op,tm) { \
365 TValue *rb = RKB(i); \
366 TValue *rc = RKC(i); \
367 if (ttisnumber(rb) && ttisnumber(rc)) { \
368 lua_Number nb = nvalue(rb), nc = nvalue(rc); \
369 setnvalue(ra, op(nb, nc)); \
372 Protect(Arith(L, ra, rb, rc, tm)); \
377 void luaV_execute (lua_State *L, int nexeccalls) {
381 const Instruction *pc;
382 reentry: /* entry point */
383 lua_assert(isLua(L->ci));
385 cl = &clvalue(L->ci->func)->l;
388 /* main loop of interpreter */
390 const Instruction i = *pc++;
392 if ((L->hookmask & (LUA_MASKLINE | LUA_MASKCOUNT)) &&
393 (--L->hookcount == 0 || L->hookmask & LUA_MASKLINE)) {
395 if (L->status == LUA_YIELD) { /* did hook yield? */
401 /* warning!! several calls may realloc the stack and invalidate `ra' */
403 lua_assert(base == L->base && L->base == L->ci->base);
404 lua_assert(base <= L->top && L->top <= L->stack + L->stacksize);
405 lua_assert(L->top == L->ci->top || luaG_checkopenop(i));
406 switch (GET_OPCODE(i)) {
408 setobjs2s(L, ra, RB(i));
412 setobj2s(L, ra, KBx(i));
416 setbvalue(ra, GETARG_B(i));
417 if (GETARG_C(i)) pc++; /* skip next instruction (if C) */
429 setobj2s(L, ra, cl->upvals[b]->v);
435 sethvalue(L, &g, cl->env);
436 lua_assert(ttisstring(rb));
437 Protect(luaV_gettable(L, &g, rb, ra));
441 Protect(luaV_gettable(L, RB(i), RKC(i), ra));
446 sethvalue(L, &g, cl->env);
447 lua_assert(ttisstring(KBx(i)));
448 Protect(luaV_settable(L, &g, KBx(i), ra));
452 UpVal *uv = cl->upvals[GETARG_B(i)];
453 setobj(L, uv->v, ra);
454 luaC_barrier(L, uv, ra);
458 Protect(luaV_settable(L, ra, RKB(i), RKC(i)));
464 sethvalue(L, ra, luaH_new(L, luaO_fb2int(b), luaO_fb2int(c)));
465 Protect(luaC_checkGC(L));
470 setobjs2s(L, ra+1, rb);
471 Protect(luaV_gettable(L, rb, RKC(i), ra));
475 arith_op(luai_numadd, TM_ADD);
479 arith_op(luai_numsub, TM_SUB);
483 arith_op(luai_nummul, TM_MUL);
487 arith_op(luai_numdiv, TM_DIV);
491 arith_op(luai_nummod, TM_MOD);
495 arith_op(luai_numpow, TM_POW);
500 if (ttisnumber(rb)) {
501 lua_Number nb = nvalue(rb);
502 setnvalue(ra, luai_numunm(nb));
505 Protect(Arith(L, ra, rb, rb, TM_UNM));
510 int res = l_isfalse(RB(i)); /* next assignment may change this value */
515 const TValue *rb = RB(i);
518 setnvalue(ra, cast_num(luaH_getn(hvalue(rb))));
522 setnvalue(ra, cast_num(tsvalue(rb)->len));
525 default: { /* try metamethod */
527 if (!call_binTM(L, rb, luaO_nilobject, ra, TM_LEN))
528 luaG_typeerror(L, rb, "get length of");
537 Protect(luaV_concat(L, c-b+1, c); luaC_checkGC(L));
538 setobjs2s(L, RA(i), base+b);
542 dojump(L, pc, GETARG_sBx(i));
549 if (equalobj(L, rb, rc) == GETARG_A(i))
550 dojump(L, pc, GETARG_sBx(*pc));
557 if (luaV_lessthan(L, RKB(i), RKC(i)) == GETARG_A(i))
558 dojump(L, pc, GETARG_sBx(*pc));
565 if (lessequal(L, RKB(i), RKC(i)) == GETARG_A(i))
566 dojump(L, pc, GETARG_sBx(*pc));
572 if (l_isfalse(ra) != GETARG_C(i))
573 dojump(L, pc, GETARG_sBx(*pc));
579 if (l_isfalse(rb) != GETARG_C(i)) {
580 setobjs2s(L, ra, rb);
581 dojump(L, pc, GETARG_sBx(*pc));
588 int nresults = GETARG_C(i) - 1;
589 if (b != 0) L->top = ra+b; /* else previous instruction set top */
591 switch (luaD_precall(L, ra, nresults)) {
594 goto reentry; /* restart luaV_execute over new Lua function */
597 /* it was a C function (`precall' called it); adjust results */
598 if (nresults >= 0) L->top = L->ci->top;
609 if (b != 0) L->top = ra+b; /* else previous instruction set top */
611 lua_assert(GETARG_C(i) - 1 == LUA_MULTRET);
612 switch (luaD_precall(L, ra, LUA_MULTRET)) {
614 /* tail call: put new frame in place of previous one */
615 CallInfo *ci = L->ci - 1; /* previous frame */
617 StkId func = ci->func;
618 StkId pfunc = (ci+1)->func; /* previous function index */
619 if (L->openupval) luaF_close(L, ci->base);
620 L->base = ci->base = ci->func + ((ci+1)->base - pfunc);
621 for (aux = 0; pfunc+aux < L->top; aux++) /* move frame down */
622 setobjs2s(L, func+aux, pfunc+aux);
623 ci->top = L->top = func+aux; /* correct top */
624 lua_assert(L->top == L->base + clvalue(func)->l.p->maxstacksize);
625 ci->savedpc = L->savedpc;
626 ci->tailcalls++; /* one more call lost */
627 L->ci--; /* remove new frame */
630 case PCRC: { /* it was a C function (`precall' called it) */
641 if (b != 0) L->top = ra+b-1;
642 if (L->openupval) luaF_close(L, base);
644 b = luaD_poscall(L, ra);
645 if (--nexeccalls == 0) /* was previous function running `here'? */
646 return; /* no: return */
647 else { /* yes: continue its execution */
648 if (b) L->top = L->ci->top;
649 lua_assert(isLua(L->ci));
650 lua_assert(GET_OPCODE(*((L->ci)->savedpc - 1)) == OP_CALL);
655 lua_Number step = nvalue(ra+2);
656 lua_Number idx = luai_numadd(nvalue(ra), step); /* increment index */
657 lua_Number limit = nvalue(ra+1);
658 if (luai_numlt(0, step) ? luai_numle(idx, limit)
659 : luai_numle(limit, idx)) {
660 dojump(L, pc, GETARG_sBx(i)); /* jump back */
661 setnvalue(ra, idx); /* update internal index... */
662 setnvalue(ra+3, idx); /* ...and external index */
667 const TValue *init = ra;
668 const TValue *plimit = ra+1;
669 const TValue *pstep = ra+2;
670 L->savedpc = pc; /* next steps may throw errors */
671 if (!tonumber(init, ra))
672 luaG_runerror(L, LUA_QL("for") " initial value must be a number");
673 else if (!tonumber(plimit, ra+1))
674 luaG_runerror(L, LUA_QL("for") " limit must be a number");
675 else if (!tonumber(pstep, ra+2))
676 luaG_runerror(L, LUA_QL("for") " step must be a number");
677 setnvalue(ra, luai_numsub(nvalue(ra), nvalue(pstep)));
678 dojump(L, pc, GETARG_sBx(i));
682 StkId cb = ra + 3; /* call base */
683 setobjs2s(L, cb+2, ra+2);
684 setobjs2s(L, cb+1, ra+1);
685 setobjs2s(L, cb, ra);
686 L->top = cb+3; /* func. + 2 args (state and index) */
687 Protect(luaD_call(L, cb, GETARG_C(i)));
689 cb = RA(i) + 3; /* previous call may change the stack */
690 if (!ttisnil(cb)) { /* continue loop? */
691 setobjs2s(L, cb-1, cb); /* save control variable */
692 dojump(L, pc, GETARG_sBx(*pc)); /* jump back */
703 n = cast_int(L->top - ra) - 1;
706 if (c == 0) c = cast_int(*pc++);
707 runtime_check(L, ttistable(ra));
709 last = ((c-1)*LFIELDS_PER_FLUSH) + n;
710 if (last > h->sizearray) /* needs more space? */
711 luaH_resizearray(L, h, last); /* pre-alloc it at once */
714 setobj2t(L, luaH_setnum(L, h, last--), val);
715 luaC_barriert(L, h, val);
727 p = cl->p->p[GETARG_Bx(i)];
729 ncl = luaF_newLclosure(L, nup, cl->env);
731 for (j=0; j<nup; j++, pc++) {
732 if (GET_OPCODE(*pc) == OP_GETUPVAL)
733 ncl->l.upvals[j] = cl->upvals[GETARG_B(*pc)];
735 lua_assert(GET_OPCODE(*pc) == OP_MOVE);
736 ncl->l.upvals[j] = luaF_findupval(L, base + GETARG_B(*pc));
739 setclvalue(L, ra, ncl);
740 Protect(luaC_checkGC(L));
744 int b = GETARG_B(i) - 1;
746 CallInfo *ci = L->ci;
747 int n = cast_int(ci->base - ci->func) - cl->p->numparams - 1;
748 if (b == LUA_MULTRET) {
749 Protect(luaD_checkstack(L, n));
750 ra = RA(i); /* previous call may change the stack */
754 for (j = 0; j < b; j++) {
756 setobjs2s(L, ra + j, ci->base - n + j);