xref: /freebsd/contrib/lua/src/lvm.c (revision b0a5c9889882332a976fa379176c249dc55efa63)
1 /*
2 ** $Id: lvm.c,v 2.268 2016/02/05 19:59:14 roberto Exp $
3 ** Lua virtual machine
4 ** See Copyright Notice in lua.h
5 */
6 
7 #define lvm_c
8 #define LUA_CORE
9 
10 #include "lprefix.h"
11 
12 #include <float.h>
13 #include <limits.h>
14 #include <math.h>
15 #include <stdio.h>
16 #include <stdlib.h>
17 #include <string.h>
18 
19 #include "lua.h"
20 
21 #include "ldebug.h"
22 #include "ldo.h"
23 #include "lfunc.h"
24 #include "lgc.h"
25 #include "lobject.h"
26 #include "lopcodes.h"
27 #include "lstate.h"
28 #include "lstring.h"
29 #include "ltable.h"
30 #include "ltm.h"
31 #include "lvm.h"
32 
33 
34 /* limit for table tag-method chains (to avoid loops) */
35 #define MAXTAGLOOP	2000
36 
37 
38 
39 /*
40 ** 'l_intfitsf' checks whether a given integer can be converted to a
41 ** float without rounding. Used in comparisons. Left undefined if
42 ** all integers fit in a float precisely.
43 */
44 #if !defined(l_intfitsf)
45 
46 /* number of bits in the mantissa of a float */
47 #define NBM		(l_mathlim(MANT_DIG))
48 
49 /*
50 ** Check whether some integers may not fit in a float, that is, whether
51 ** (maxinteger >> NBM) > 0 (that implies (1 << NBM) <= maxinteger).
52 ** (The shifts are done in parts to avoid shifting by more than the size
53 ** of an integer. In a worst case, NBM == 113 for long double and
54 ** sizeof(integer) == 32.)
55 */
56 #if ((((LUA_MAXINTEGER >> (NBM / 4)) >> (NBM / 4)) >> (NBM / 4)) \
57 	>> (NBM - (3 * (NBM / 4))))  >  0
58 
59 #define l_intfitsf(i)  \
60   (-((lua_Integer)1 << NBM) <= (i) && (i) <= ((lua_Integer)1 << NBM))
61 
62 #endif
63 
64 #endif
65 
66 
67 
68 /*
69 ** Try to convert a value to a float. The float case is already handled
70 ** by the macro 'tonumber'.
71 */
72 int luaV_tonumber_ (const TValue *obj, lua_Number *n) {
73   TValue v;
74   if (ttisinteger(obj)) {
75     *n = cast_num(ivalue(obj));
76     return 1;
77   }
78   else if (cvt2num(obj) &&  /* string convertible to number? */
79             luaO_str2num(svalue(obj), &v) == vslen(obj) + 1) {
80     *n = nvalue(&v);  /* convert result of 'luaO_str2num' to a float */
81     return 1;
82   }
83   else
84     return 0;  /* conversion failed */
85 }
86 
87 
88 /*
89 ** try to convert a value to an integer, rounding according to 'mode':
90 ** mode == 0: accepts only integral values
91 ** mode == 1: takes the floor of the number
92 ** mode == 2: takes the ceil of the number
93 */
94 int luaV_tointeger (const TValue *obj, lua_Integer *p, int mode) {
95   TValue v;
96  again:
97   if (ttisfloat(obj)) {
98     lua_Number n = fltvalue(obj);
99     lua_Number f = l_floor(n);
100     if (n != f) {  /* not an integral value? */
101       if (mode == 0) return 0;  /* fails if mode demands integral value */
102       else if (mode > 1)  /* needs ceil? */
103         f += 1;  /* convert floor to ceil (remember: n != f) */
104     }
105     return lua_numbertointeger(f, p);
106   }
107   else if (ttisinteger(obj)) {
108     *p = ivalue(obj);
109     return 1;
110   }
111   else if (cvt2num(obj) &&
112             luaO_str2num(svalue(obj), &v) == vslen(obj) + 1) {
113     obj = &v;
114     goto again;  /* convert result from 'luaO_str2num' to an integer */
115   }
116   return 0;  /* conversion failed */
117 }
118 
119 
120 /*
121 ** Try to convert a 'for' limit to an integer, preserving the
122 ** semantics of the loop.
123 ** (The following explanation assumes a non-negative step; it is valid
124 ** for negative steps mutatis mutandis.)
125 ** If the limit can be converted to an integer, rounding down, that is
126 ** it.
127 ** Otherwise, check whether the limit can be converted to a number.  If
128 ** the number is too large, it is OK to set the limit as LUA_MAXINTEGER,
129 ** which means no limit.  If the number is too negative, the loop
130 ** should not run, because any initial integer value is larger than the
131 ** limit. So, it sets the limit to LUA_MININTEGER. 'stopnow' corrects
132 ** the extreme case when the initial value is LUA_MININTEGER, in which
133 ** case the LUA_MININTEGER limit would still run the loop once.
134 */
135 static int forlimit (const TValue *obj, lua_Integer *p, lua_Integer step,
136                      int *stopnow) {
137   *stopnow = 0;  /* usually, let loops run */
138   if (!luaV_tointeger(obj, p, (step < 0 ? 2 : 1))) {  /* not fit in integer? */
139     lua_Number n;  /* try to convert to float */
140     if (!tonumber(obj, &n)) /* cannot convert to float? */
141       return 0;  /* not a number */
142     if (luai_numlt(0, n)) {  /* if true, float is larger than max integer */
143       *p = LUA_MAXINTEGER;
144       if (step < 0) *stopnow = 1;
145     }
146     else {  /* float is smaller than min integer */
147       *p = LUA_MININTEGER;
148       if (step >= 0) *stopnow = 1;
149     }
150   }
151   return 1;
152 }
153 
154 
155 /*
156 ** Finish the table access 'val = t[key]'.
157 ** if 'slot' is NULL, 't' is not a table; otherwise, 'slot' points to
158 ** t[k] entry (which must be nil).
159 */
160 void luaV_finishget (lua_State *L, const TValue *t, TValue *key, StkId val,
161                       const TValue *slot) {
162   int loop;  /* counter to avoid infinite loops */
163   const TValue *tm;  /* metamethod */
164   for (loop = 0; loop < MAXTAGLOOP; loop++) {
165     if (slot == NULL) {  /* 't' is not a table? */
166       lua_assert(!ttistable(t));
167       tm = luaT_gettmbyobj(L, t, TM_INDEX);
168       if (ttisnil(tm))
169         luaG_typeerror(L, t, "index");  /* no metamethod */
170       /* else will try the metamethod */
171     }
172     else {  /* 't' is a table */
173       lua_assert(ttisnil(slot));
174       tm = fasttm(L, hvalue(t)->metatable, TM_INDEX);  /* table's metamethod */
175       if (tm == NULL) {  /* no metamethod? */
176         setnilvalue(val);  /* result is nil */
177         return;
178       }
179       /* else will try the metamethod */
180     }
181     if (ttisfunction(tm)) {  /* is metamethod a function? */
182       luaT_callTM(L, tm, t, key, val, 1);  /* call it */
183       return;
184     }
185     t = tm;  /* else try to access 'tm[key]' */
186     if (luaV_fastget(L,t,key,slot,luaH_get)) {  /* fast track? */
187       setobj2s(L, val, slot);  /* done */
188       return;
189     }
190     /* else repeat (tail call 'luaV_finishget') */
191   }
192   luaG_runerror(L, "'__index' chain too long; possible loop");
193 }
194 
195 
196 /*
197 ** Finish a table assignment 't[key] = val'.
198 ** If 'slot' is NULL, 't' is not a table.  Otherwise, 'slot' points
199 ** to the entry 't[key]', or to 'luaO_nilobject' if there is no such
200 ** entry.  (The value at 'slot' must be nil, otherwise 'luaV_fastset'
201 ** would have done the job.)
202 */
203 void luaV_finishset (lua_State *L, const TValue *t, TValue *key,
204                      StkId val, const TValue *slot) {
205   int loop;  /* counter to avoid infinite loops */
206   for (loop = 0; loop < MAXTAGLOOP; loop++) {
207     const TValue *tm;  /* '__newindex' metamethod */
208     if (slot != NULL) {  /* is 't' a table? */
209       Table *h = hvalue(t);  /* save 't' table */
210       lua_assert(ttisnil(slot));  /* old value must be nil */
211       tm = fasttm(L, h->metatable, TM_NEWINDEX);  /* get metamethod */
212       if (tm == NULL) {  /* no metamethod? */
213         if (slot == luaO_nilobject)  /* no previous entry? */
214           slot = luaH_newkey(L, h, key);  /* create one */
215         /* no metamethod and (now) there is an entry with given key */
216         setobj2t(L, cast(TValue *, slot), val);  /* set its new value */
217         invalidateTMcache(h);
218         luaC_barrierback(L, h, val);
219         return;
220       }
221       /* else will try the metamethod */
222     }
223     else {  /* not a table; check metamethod */
224       if (ttisnil(tm = luaT_gettmbyobj(L, t, TM_NEWINDEX)))
225         luaG_typeerror(L, t, "index");
226     }
227     /* try the metamethod */
228     if (ttisfunction(tm)) {
229       luaT_callTM(L, tm, t, key, val, 0);
230       return;
231     }
232     t = tm;  /* else repeat assignment over 'tm' */
233     if (luaV_fastset(L, t, key, slot, luaH_get, val))
234       return;  /* done */
235     /* else loop */
236   }
237   luaG_runerror(L, "'__newindex' chain too long; possible loop");
238 }
239 
240 
241 /*
242 ** Compare two strings 'ls' x 'rs', returning an integer smaller-equal-
243 ** -larger than zero if 'ls' is smaller-equal-larger than 'rs'.
244 ** The code is a little tricky because it allows '\0' in the strings
245 ** and it uses 'strcoll' (to respect locales) for each segments
246 ** of the strings.
247 */
248 static int l_strcmp (const TString *ls, const TString *rs) {
249   const char *l = getstr(ls);
250   size_t ll = tsslen(ls);
251   const char *r = getstr(rs);
252   size_t lr = tsslen(rs);
253   for (;;) {  /* for each segment */
254     int temp = strcoll(l, r);
255     if (temp != 0)  /* not equal? */
256       return temp;  /* done */
257     else {  /* strings are equal up to a '\0' */
258       size_t len = strlen(l);  /* index of first '\0' in both strings */
259       if (len == lr)  /* 'rs' is finished? */
260         return (len == ll) ? 0 : 1;  /* check 'ls' */
261       else if (len == ll)  /* 'ls' is finished? */
262         return -1;  /* 'ls' is smaller than 'rs' ('rs' is not finished) */
263       /* both strings longer than 'len'; go on comparing after the '\0' */
264       len++;
265       l += len; ll -= len; r += len; lr -= len;
266     }
267   }
268 }
269 
270 
271 /*
272 ** Check whether integer 'i' is less than float 'f'. If 'i' has an
273 ** exact representation as a float ('l_intfitsf'), compare numbers as
274 ** floats. Otherwise, if 'f' is outside the range for integers, result
275 ** is trivial. Otherwise, compare them as integers. (When 'i' has no
276 ** float representation, either 'f' is "far away" from 'i' or 'f' has
277 ** no precision left for a fractional part; either way, how 'f' is
278 ** truncated is irrelevant.) When 'f' is NaN, comparisons must result
279 ** in false.
280 */
281 static int LTintfloat (lua_Integer i, lua_Number f) {
282 #if defined(l_intfitsf)
283   if (!l_intfitsf(i)) {
284     if (f >= -cast_num(LUA_MININTEGER))  /* -minint == maxint + 1 */
285       return 1;  /* f >= maxint + 1 > i */
286     else if (f > cast_num(LUA_MININTEGER))  /* minint < f <= maxint ? */
287       return (i < cast(lua_Integer, f));  /* compare them as integers */
288     else  /* f <= minint <= i (or 'f' is NaN)  -->  not(i < f) */
289       return 0;
290   }
291 #endif
292   return luai_numlt(cast_num(i), f);  /* compare them as floats */
293 }
294 
295 
296 /*
297 ** Check whether integer 'i' is less than or equal to float 'f'.
298 ** See comments on previous function.
299 */
300 static int LEintfloat (lua_Integer i, lua_Number f) {
301 #if defined(l_intfitsf)
302   if (!l_intfitsf(i)) {
303     if (f >= -cast_num(LUA_MININTEGER))  /* -minint == maxint + 1 */
304       return 1;  /* f >= maxint + 1 > i */
305     else if (f >= cast_num(LUA_MININTEGER))  /* minint <= f <= maxint ? */
306       return (i <= cast(lua_Integer, f));  /* compare them as integers */
307     else  /* f < minint <= i (or 'f' is NaN)  -->  not(i <= f) */
308       return 0;
309   }
310 #endif
311   return luai_numle(cast_num(i), f);  /* compare them as floats */
312 }
313 
314 
315 /*
316 ** Return 'l < r', for numbers.
317 */
318 static int LTnum (const TValue *l, const TValue *r) {
319   if (ttisinteger(l)) {
320     lua_Integer li = ivalue(l);
321     if (ttisinteger(r))
322       return li < ivalue(r);  /* both are integers */
323     else  /* 'l' is int and 'r' is float */
324       return LTintfloat(li, fltvalue(r));  /* l < r ? */
325   }
326   else {
327     lua_Number lf = fltvalue(l);  /* 'l' must be float */
328     if (ttisfloat(r))
329       return luai_numlt(lf, fltvalue(r));  /* both are float */
330     else if (luai_numisnan(lf))  /* 'r' is int and 'l' is float */
331       return 0;  /* NaN < i is always false */
332     else  /* without NaN, (l < r)  <-->  not(r <= l) */
333       return !LEintfloat(ivalue(r), lf);  /* not (r <= l) ? */
334   }
335 }
336 
337 
338 /*
339 ** Return 'l <= r', for numbers.
340 */
341 static int LEnum (const TValue *l, const TValue *r) {
342   if (ttisinteger(l)) {
343     lua_Integer li = ivalue(l);
344     if (ttisinteger(r))
345       return li <= ivalue(r);  /* both are integers */
346     else  /* 'l' is int and 'r' is float */
347       return LEintfloat(li, fltvalue(r));  /* l <= r ? */
348   }
349   else {
350     lua_Number lf = fltvalue(l);  /* 'l' must be float */
351     if (ttisfloat(r))
352       return luai_numle(lf, fltvalue(r));  /* both are float */
353     else if (luai_numisnan(lf))  /* 'r' is int and 'l' is float */
354       return 0;  /*  NaN <= i is always false */
355     else  /* without NaN, (l <= r)  <-->  not(r < l) */
356       return !LTintfloat(ivalue(r), lf);  /* not (r < l) ? */
357   }
358 }
359 
360 
361 /*
362 ** Main operation less than; return 'l < r'.
363 */
364 int luaV_lessthan (lua_State *L, const TValue *l, const TValue *r) {
365   int res;
366   if (ttisnumber(l) && ttisnumber(r))  /* both operands are numbers? */
367     return LTnum(l, r);
368   else if (ttisstring(l) && ttisstring(r))  /* both are strings? */
369     return l_strcmp(tsvalue(l), tsvalue(r)) < 0;
370   else if ((res = luaT_callorderTM(L, l, r, TM_LT)) < 0)  /* no metamethod? */
371     luaG_ordererror(L, l, r);  /* error */
372   return res;
373 }
374 
375 
376 /*
377 ** Main operation less than or equal to; return 'l <= r'. If it needs
378 ** a metamethod and there is no '__le', try '__lt', based on
379 ** l <= r iff !(r < l) (assuming a total order). If the metamethod
380 ** yields during this substitution, the continuation has to know
381 ** about it (to negate the result of r<l); bit CIST_LEQ in the call
382 ** status keeps that information.
383 */
384 int luaV_lessequal (lua_State *L, const TValue *l, const TValue *r) {
385   int res;
386   if (ttisnumber(l) && ttisnumber(r))  /* both operands are numbers? */
387     return LEnum(l, r);
388   else if (ttisstring(l) && ttisstring(r))  /* both are strings? */
389     return l_strcmp(tsvalue(l), tsvalue(r)) <= 0;
390   else if ((res = luaT_callorderTM(L, l, r, TM_LE)) >= 0)  /* try 'le' */
391     return res;
392   else {  /* try 'lt': */
393     L->ci->callstatus |= CIST_LEQ;  /* mark it is doing 'lt' for 'le' */
394     res = luaT_callorderTM(L, r, l, TM_LT);
395     L->ci->callstatus ^= CIST_LEQ;  /* clear mark */
396     if (res < 0)
397       luaG_ordererror(L, l, r);
398     return !res;  /* result is negated */
399   }
400 }
401 
402 
403 /*
404 ** Main operation for equality of Lua values; return 't1 == t2'.
405 ** L == NULL means raw equality (no metamethods)
406 */
407 int luaV_equalobj (lua_State *L, const TValue *t1, const TValue *t2) {
408   const TValue *tm;
409   if (ttype(t1) != ttype(t2)) {  /* not the same variant? */
410     if (ttnov(t1) != ttnov(t2) || ttnov(t1) != LUA_TNUMBER)
411       return 0;  /* only numbers can be equal with different variants */
412     else {  /* two numbers with different variants */
413       lua_Integer i1, i2;  /* compare them as integers */
414       return (tointeger(t1, &i1) && tointeger(t2, &i2) && i1 == i2);
415     }
416   }
417   /* values have same type and same variant */
418   switch (ttype(t1)) {
419     case LUA_TNIL: return 1;
420     case LUA_TNUMINT: return (ivalue(t1) == ivalue(t2));
421     case LUA_TNUMFLT: return luai_numeq(fltvalue(t1), fltvalue(t2));
422     case LUA_TBOOLEAN: return bvalue(t1) == bvalue(t2);  /* true must be 1 !! */
423     case LUA_TLIGHTUSERDATA: return pvalue(t1) == pvalue(t2);
424     case LUA_TLCF: return fvalue(t1) == fvalue(t2);
425     case LUA_TSHRSTR: return eqshrstr(tsvalue(t1), tsvalue(t2));
426     case LUA_TLNGSTR: return luaS_eqlngstr(tsvalue(t1), tsvalue(t2));
427     case LUA_TUSERDATA: {
428       if (uvalue(t1) == uvalue(t2)) return 1;
429       else if (L == NULL) return 0;
430       tm = fasttm(L, uvalue(t1)->metatable, TM_EQ);
431       if (tm == NULL)
432         tm = fasttm(L, uvalue(t2)->metatable, TM_EQ);
433       break;  /* will try TM */
434     }
435     case LUA_TTABLE: {
436       if (hvalue(t1) == hvalue(t2)) return 1;
437       else if (L == NULL) return 0;
438       tm = fasttm(L, hvalue(t1)->metatable, TM_EQ);
439       if (tm == NULL)
440         tm = fasttm(L, hvalue(t2)->metatable, TM_EQ);
441       break;  /* will try TM */
442     }
443     default:
444       return gcvalue(t1) == gcvalue(t2);
445   }
446   if (tm == NULL)  /* no TM? */
447     return 0;  /* objects are different */
448   luaT_callTM(L, tm, t1, t2, L->top, 1);  /* call TM */
449   return !l_isfalse(L->top);
450 }
451 
452 
453 /* macro used by 'luaV_concat' to ensure that element at 'o' is a string */
454 #define tostring(L,o)  \
455 	(ttisstring(o) || (cvt2str(o) && (luaO_tostring(L, o), 1)))
456 
457 #define isemptystr(o)	(ttisshrstring(o) && tsvalue(o)->shrlen == 0)
458 
459 /* copy strings in stack from top - n up to top - 1 to buffer */
460 static void copy2buff (StkId top, int n, char *buff) {
461   size_t tl = 0;  /* size already copied */
462   do {
463     size_t l = vslen(top - n);  /* length of string being copied */
464     memcpy(buff + tl, svalue(top - n), l * sizeof(char));
465     tl += l;
466   } while (--n > 0);
467 }
468 
469 
470 /*
471 ** Main operation for concatenation: concat 'total' values in the stack,
472 ** from 'L->top - total' up to 'L->top - 1'.
473 */
474 void luaV_concat (lua_State *L, int total) {
475   lua_assert(total >= 2);
476   do {
477     StkId top = L->top;
478     int n = 2;  /* number of elements handled in this pass (at least 2) */
479     if (!(ttisstring(top-2) || cvt2str(top-2)) || !tostring(L, top-1))
480       luaT_trybinTM(L, top-2, top-1, top-2, TM_CONCAT);
481     else if (isemptystr(top - 1))  /* second operand is empty? */
482       cast_void(tostring(L, top - 2));  /* result is first operand */
483     else if (isemptystr(top - 2)) {  /* first operand is an empty string? */
484       setobjs2s(L, top - 2, top - 1);  /* result is second op. */
485     }
486     else {
487       /* at least two non-empty string values; get as many as possible */
488       size_t tl = vslen(top - 1);
489       TString *ts;
490       /* collect total length and number of strings */
491       for (n = 1; n < total && tostring(L, top - n - 1); n++) {
492         size_t l = vslen(top - n - 1);
493         if (l >= (MAX_SIZE/sizeof(char)) - tl)
494           luaG_runerror(L, "string length overflow");
495         tl += l;
496       }
497       if (tl <= LUAI_MAXSHORTLEN) {  /* is result a short string? */
498         char buff[LUAI_MAXSHORTLEN];
499         copy2buff(top, n, buff);  /* copy strings to buffer */
500         ts = luaS_newlstr(L, buff, tl);
501       }
502       else {  /* long string; copy strings directly to final result */
503         ts = luaS_createlngstrobj(L, tl);
504         copy2buff(top, n, getstr(ts));
505       }
506       setsvalue2s(L, top - n, ts);  /* create result */
507     }
508     total -= n-1;  /* got 'n' strings to create 1 new */
509     L->top -= n-1;  /* popped 'n' strings and pushed one */
510   } while (total > 1);  /* repeat until only 1 result left */
511 }
512 
513 
514 /*
515 ** Main operation 'ra' = #rb'.
516 */
517 void luaV_objlen (lua_State *L, StkId ra, const TValue *rb) {
518   const TValue *tm;
519   switch (ttype(rb)) {
520     case LUA_TTABLE: {
521       Table *h = hvalue(rb);
522       tm = fasttm(L, h->metatable, TM_LEN);
523       if (tm) break;  /* metamethod? break switch to call it */
524       setivalue(ra, luaH_getn(h));  /* else primitive len */
525       return;
526     }
527     case LUA_TSHRSTR: {
528       setivalue(ra, tsvalue(rb)->shrlen);
529       return;
530     }
531     case LUA_TLNGSTR: {
532       setivalue(ra, tsvalue(rb)->u.lnglen);
533       return;
534     }
535     default: {  /* try metamethod */
536       tm = luaT_gettmbyobj(L, rb, TM_LEN);
537       if (ttisnil(tm))  /* no metamethod? */
538         luaG_typeerror(L, rb, "get length of");
539       break;
540     }
541   }
542   luaT_callTM(L, tm, rb, rb, ra, 1);
543 }
544 
545 
546 /*
547 ** Integer division; return 'm // n', that is, floor(m/n).
548 ** C division truncates its result (rounds towards zero).
549 ** 'floor(q) == trunc(q)' when 'q >= 0' or when 'q' is integer,
550 ** otherwise 'floor(q) == trunc(q) - 1'.
551 */
552 lua_Integer luaV_div (lua_State *L, lua_Integer m, lua_Integer n) {
553   if (l_castS2U(n) + 1u <= 1u) {  /* special cases: -1 or 0 */
554     if (n == 0)
555       luaG_runerror(L, "attempt to divide by zero");
556     return intop(-, 0, m);   /* n==-1; avoid overflow with 0x80000...//-1 */
557   }
558   else {
559     lua_Integer q = m / n;  /* perform C division */
560     if ((m ^ n) < 0 && m % n != 0)  /* 'm/n' would be negative non-integer? */
561       q -= 1;  /* correct result for different rounding */
562     return q;
563   }
564 }
565 
566 
567 /*
568 ** Integer modulus; return 'm % n'. (Assume that C '%' with
569 ** negative operands follows C99 behavior. See previous comment
570 ** about luaV_div.)
571 */
572 lua_Integer luaV_mod (lua_State *L, lua_Integer m, lua_Integer n) {
573   if (l_castS2U(n) + 1u <= 1u) {  /* special cases: -1 or 0 */
574     if (n == 0)
575       luaG_runerror(L, "attempt to perform 'n%%0'");
576     return 0;   /* m % -1 == 0; avoid overflow with 0x80000...%-1 */
577   }
578   else {
579     lua_Integer r = m % n;
580     if (r != 0 && (m ^ n) < 0)  /* 'm/n' would be non-integer negative? */
581       r += n;  /* correct result for different rounding */
582     return r;
583   }
584 }
585 
586 
587 /* number of bits in an integer */
588 #define NBITS	cast_int(sizeof(lua_Integer) * CHAR_BIT)
589 
590 /*
591 ** Shift left operation. (Shift right just negates 'y'.)
592 */
593 lua_Integer luaV_shiftl (lua_Integer x, lua_Integer y) {
594   if (y < 0) {  /* shift right? */
595     if (y <= -NBITS) return 0;
596     else return intop(>>, x, -y);
597   }
598   else {  /* shift left */
599     if (y >= NBITS) return 0;
600     else return intop(<<, x, y);
601   }
602 }
603 
604 
605 /*
606 ** check whether cached closure in prototype 'p' may be reused, that is,
607 ** whether there is a cached closure with the same upvalues needed by
608 ** new closure to be created.
609 */
610 static LClosure *getcached (Proto *p, UpVal **encup, StkId base) {
611   LClosure *c = p->cache;
612   if (c != NULL) {  /* is there a cached closure? */
613     int nup = p->sizeupvalues;
614     Upvaldesc *uv = p->upvalues;
615     int i;
616     for (i = 0; i < nup; i++) {  /* check whether it has right upvalues */
617       TValue *v = uv[i].instack ? base + uv[i].idx : encup[uv[i].idx]->v;
618       if (c->upvals[i]->v != v)
619         return NULL;  /* wrong upvalue; cannot reuse closure */
620     }
621   }
622   return c;  /* return cached closure (or NULL if no cached closure) */
623 }
624 
625 
626 /*
627 ** create a new Lua closure, push it in the stack, and initialize
628 ** its upvalues. Note that the closure is not cached if prototype is
629 ** already black (which means that 'cache' was already cleared by the
630 ** GC).
631 */
632 static void pushclosure (lua_State *L, Proto *p, UpVal **encup, StkId base,
633                          StkId ra) {
634   int nup = p->sizeupvalues;
635   Upvaldesc *uv = p->upvalues;
636   int i;
637   LClosure *ncl = luaF_newLclosure(L, nup);
638   ncl->p = p;
639   setclLvalue(L, ra, ncl);  /* anchor new closure in stack */
640   for (i = 0; i < nup; i++) {  /* fill in its upvalues */
641     if (uv[i].instack)  /* upvalue refers to local variable? */
642       ncl->upvals[i] = luaF_findupval(L, base + uv[i].idx);
643     else  /* get upvalue from enclosing function */
644       ncl->upvals[i] = encup[uv[i].idx];
645     ncl->upvals[i]->refcount++;
646     /* new closure is white, so we do not need a barrier here */
647   }
648   if (!isblack(p))  /* cache will not break GC invariant? */
649     p->cache = ncl;  /* save it on cache for reuse */
650 }
651 
652 
653 /*
654 ** finish execution of an opcode interrupted by an yield
655 */
656 void luaV_finishOp (lua_State *L) {
657   CallInfo *ci = L->ci;
658   StkId base = ci->u.l.base;
659   Instruction inst = *(ci->u.l.savedpc - 1);  /* interrupted instruction */
660   OpCode op = GET_OPCODE(inst);
661   switch (op) {  /* finish its execution */
662     case OP_ADD: case OP_SUB: case OP_MUL: case OP_DIV: case OP_IDIV:
663     case OP_BAND: case OP_BOR: case OP_BXOR: case OP_SHL: case OP_SHR:
664     case OP_MOD: case OP_POW:
665     case OP_UNM: case OP_BNOT: case OP_LEN:
666     case OP_GETTABUP: case OP_GETTABLE: case OP_SELF: {
667       setobjs2s(L, base + GETARG_A(inst), --L->top);
668       break;
669     }
670     case OP_LE: case OP_LT: case OP_EQ: {
671       int res = !l_isfalse(L->top - 1);
672       L->top--;
673       if (ci->callstatus & CIST_LEQ) {  /* "<=" using "<" instead? */
674         lua_assert(op == OP_LE);
675         ci->callstatus ^= CIST_LEQ;  /* clear mark */
676         res = !res;  /* negate result */
677       }
678       lua_assert(GET_OPCODE(*ci->u.l.savedpc) == OP_JMP);
679       if (res != GETARG_A(inst))  /* condition failed? */
680         ci->u.l.savedpc++;  /* skip jump instruction */
681       break;
682     }
683     case OP_CONCAT: {
684       StkId top = L->top - 1;  /* top when 'luaT_trybinTM' was called */
685       int b = GETARG_B(inst);      /* first element to concatenate */
686       int total = cast_int(top - 1 - (base + b));  /* yet to concatenate */
687       setobj2s(L, top - 2, top);  /* put TM result in proper position */
688       if (total > 1) {  /* are there elements to concat? */
689         L->top = top - 1;  /* top is one after last element (at top-2) */
690         luaV_concat(L, total);  /* concat them (may yield again) */
691       }
692       /* move final result to final position */
693       setobj2s(L, ci->u.l.base + GETARG_A(inst), L->top - 1);
694       L->top = ci->top;  /* restore top */
695       break;
696     }
697     case OP_TFORCALL: {
698       lua_assert(GET_OPCODE(*ci->u.l.savedpc) == OP_TFORLOOP);
699       L->top = ci->top;  /* correct top */
700       break;
701     }
702     case OP_CALL: {
703       if (GETARG_C(inst) - 1 >= 0)  /* nresults >= 0? */
704         L->top = ci->top;  /* adjust results */
705       break;
706     }
707     case OP_TAILCALL: case OP_SETTABUP: case OP_SETTABLE:
708       break;
709     default: lua_assert(0);
710   }
711 }
712 
713 
714 
715 
716 /*
717 ** {==================================================================
718 ** Function 'luaV_execute': main interpreter loop
719 ** ===================================================================
720 */
721 
722 
723 /*
724 ** some macros for common tasks in 'luaV_execute'
725 */
726 
727 
728 #define RA(i)	(base+GETARG_A(i))
729 #define RB(i)	check_exp(getBMode(GET_OPCODE(i)) == OpArgR, base+GETARG_B(i))
730 #define RC(i)	check_exp(getCMode(GET_OPCODE(i)) == OpArgR, base+GETARG_C(i))
731 #define RKB(i)	check_exp(getBMode(GET_OPCODE(i)) == OpArgK, \
732 	ISK(GETARG_B(i)) ? k+INDEXK(GETARG_B(i)) : base+GETARG_B(i))
733 #define RKC(i)	check_exp(getCMode(GET_OPCODE(i)) == OpArgK, \
734 	ISK(GETARG_C(i)) ? k+INDEXK(GETARG_C(i)) : base+GETARG_C(i))
735 
736 
737 /* execute a jump instruction */
738 #define dojump(ci,i,e) \
739   { int a = GETARG_A(i); \
740     if (a != 0) luaF_close(L, ci->u.l.base + a - 1); \
741     ci->u.l.savedpc += GETARG_sBx(i) + e; }
742 
743 /* for test instructions, execute the jump instruction that follows it */
744 #define donextjump(ci)	{ i = *ci->u.l.savedpc; dojump(ci, i, 1); }
745 
746 
747 #define Protect(x)	{ {x;}; base = ci->u.l.base; }
748 
749 #define checkGC(L,c)  \
750 	{ luaC_condGC(L, L->top = (c),  /* limit of live values */ \
751                          Protect(L->top = ci->top));  /* restore top */ \
752            luai_threadyield(L); }
753 
754 
755 /* fetch an instruction and prepare its execution */
756 #define vmfetch()	{ \
757   i = *(ci->u.l.savedpc++); \
758   if (L->hookmask & (LUA_MASKLINE | LUA_MASKCOUNT)) \
759     Protect(luaG_traceexec(L)); \
760   ra = RA(i); /* WARNING: any stack reallocation invalidates 'ra' */ \
761   lua_assert(base == ci->u.l.base); \
762   lua_assert(base <= L->top && L->top < L->stack + L->stacksize); \
763 }
764 
765 #define vmdispatch(o)	switch(o)
766 #define vmcase(l)	case l:
767 #define vmbreak		break
768 
769 
770 /*
771 ** copy of 'luaV_gettable', but protecting the call to potential
772 ** metamethod (which can reallocate the stack)
773 */
774 #define gettableProtected(L,t,k,v)  { const TValue *slot; \
775   if (luaV_fastget(L,t,k,slot,luaH_get)) { setobj2s(L, v, slot); } \
776   else Protect(luaV_finishget(L,t,k,v,slot)); }
777 
778 
779 /* same for 'luaV_settable' */
780 #define settableProtected(L,t,k,v) { const TValue *slot; \
781   if (!luaV_fastset(L,t,k,slot,luaH_get,v)) \
782     Protect(luaV_finishset(L,t,k,v,slot)); }
783 
784 
785 
786 void luaV_execute (lua_State *L) {
787   CallInfo *ci = L->ci;
788   LClosure *cl;
789   TValue *k;
790   StkId base;
791   ci->callstatus |= CIST_FRESH;  /* fresh invocation of 'luaV_execute" */
792  newframe:  /* reentry point when frame changes (call/return) */
793   lua_assert(ci == L->ci);
794   cl = clLvalue(ci->func);  /* local reference to function's closure */
795   k = cl->p->k;  /* local reference to function's constant table */
796   base = ci->u.l.base;  /* local copy of function's base */
797   /* main loop of interpreter */
798   for (;;) {
799     Instruction i;
800     StkId ra;
801     vmfetch();
802     vmdispatch (GET_OPCODE(i)) {
803       vmcase(OP_MOVE) {
804         setobjs2s(L, ra, RB(i));
805         vmbreak;
806       }
807       vmcase(OP_LOADK) {
808         TValue *rb = k + GETARG_Bx(i);
809         setobj2s(L, ra, rb);
810         vmbreak;
811       }
812       vmcase(OP_LOADKX) {
813         TValue *rb;
814         lua_assert(GET_OPCODE(*ci->u.l.savedpc) == OP_EXTRAARG);
815         rb = k + GETARG_Ax(*ci->u.l.savedpc++);
816         setobj2s(L, ra, rb);
817         vmbreak;
818       }
819       vmcase(OP_LOADBOOL) {
820         setbvalue(ra, GETARG_B(i));
821         if (GETARG_C(i)) ci->u.l.savedpc++;  /* skip next instruction (if C) */
822         vmbreak;
823       }
824       vmcase(OP_LOADNIL) {
825         int b = GETARG_B(i);
826         do {
827           setnilvalue(ra++);
828         } while (b--);
829         vmbreak;
830       }
831       vmcase(OP_GETUPVAL) {
832         int b = GETARG_B(i);
833         setobj2s(L, ra, cl->upvals[b]->v);
834         vmbreak;
835       }
836       vmcase(OP_GETTABUP) {
837         TValue *upval = cl->upvals[GETARG_B(i)]->v;
838         TValue *rc = RKC(i);
839         gettableProtected(L, upval, rc, ra);
840         vmbreak;
841       }
842       vmcase(OP_GETTABLE) {
843         StkId rb = RB(i);
844         TValue *rc = RKC(i);
845         gettableProtected(L, rb, rc, ra);
846         vmbreak;
847       }
848       vmcase(OP_SETTABUP) {
849         TValue *upval = cl->upvals[GETARG_A(i)]->v;
850         TValue *rb = RKB(i);
851         TValue *rc = RKC(i);
852         settableProtected(L, upval, rb, rc);
853         vmbreak;
854       }
855       vmcase(OP_SETUPVAL) {
856         UpVal *uv = cl->upvals[GETARG_B(i)];
857         setobj(L, uv->v, ra);
858         luaC_upvalbarrier(L, uv);
859         vmbreak;
860       }
861       vmcase(OP_SETTABLE) {
862         TValue *rb = RKB(i);
863         TValue *rc = RKC(i);
864         settableProtected(L, ra, rb, rc);
865         vmbreak;
866       }
867       vmcase(OP_NEWTABLE) {
868         int b = GETARG_B(i);
869         int c = GETARG_C(i);
870         Table *t = luaH_new(L);
871         sethvalue(L, ra, t);
872         if (b != 0 || c != 0)
873           luaH_resize(L, t, luaO_fb2int(b), luaO_fb2int(c));
874         checkGC(L, ra + 1);
875         vmbreak;
876       }
877       vmcase(OP_SELF) {
878         const TValue *aux;
879         StkId rb = RB(i);
880         TValue *rc = RKC(i);
881         TString *key = tsvalue(rc);  /* key must be a string */
882         setobjs2s(L, ra + 1, rb);
883         if (luaV_fastget(L, rb, key, aux, luaH_getstr)) {
884           setobj2s(L, ra, aux);
885         }
886         else Protect(luaV_finishget(L, rb, rc, ra, aux));
887         vmbreak;
888       }
889       vmcase(OP_ADD) {
890         TValue *rb = RKB(i);
891         TValue *rc = RKC(i);
892         lua_Number nb; lua_Number nc;
893         if (ttisinteger(rb) && ttisinteger(rc)) {
894           lua_Integer ib = ivalue(rb); lua_Integer ic = ivalue(rc);
895           setivalue(ra, intop(+, ib, ic));
896         }
897         else if (tonumber(rb, &nb) && tonumber(rc, &nc)) {
898           setfltvalue(ra, luai_numadd(L, nb, nc));
899         }
900         else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_ADD)); }
901         vmbreak;
902       }
903       vmcase(OP_SUB) {
904         TValue *rb = RKB(i);
905         TValue *rc = RKC(i);
906         lua_Number nb; lua_Number nc;
907         if (ttisinteger(rb) && ttisinteger(rc)) {
908           lua_Integer ib = ivalue(rb); lua_Integer ic = ivalue(rc);
909           setivalue(ra, intop(-, ib, ic));
910         }
911         else if (tonumber(rb, &nb) && tonumber(rc, &nc)) {
912           setfltvalue(ra, luai_numsub(L, nb, nc));
913         }
914         else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_SUB)); }
915         vmbreak;
916       }
917       vmcase(OP_MUL) {
918         TValue *rb = RKB(i);
919         TValue *rc = RKC(i);
920         lua_Number nb; lua_Number nc;
921         if (ttisinteger(rb) && ttisinteger(rc)) {
922           lua_Integer ib = ivalue(rb); lua_Integer ic = ivalue(rc);
923           setivalue(ra, intop(*, ib, ic));
924         }
925         else if (tonumber(rb, &nb) && tonumber(rc, &nc)) {
926           setfltvalue(ra, luai_nummul(L, nb, nc));
927         }
928         else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_MUL)); }
929         vmbreak;
930       }
931       vmcase(OP_DIV) {  /* float division (always with floats) */
932         TValue *rb = RKB(i);
933         TValue *rc = RKC(i);
934         lua_Number nb; lua_Number nc;
935         if (tonumber(rb, &nb) && tonumber(rc, &nc)) {
936           setfltvalue(ra, luai_numdiv(L, nb, nc));
937         }
938         else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_DIV)); }
939         vmbreak;
940       }
941       vmcase(OP_BAND) {
942         TValue *rb = RKB(i);
943         TValue *rc = RKC(i);
944         lua_Integer ib; lua_Integer ic;
945         if (tointeger(rb, &ib) && tointeger(rc, &ic)) {
946           setivalue(ra, intop(&, ib, ic));
947         }
948         else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_BAND)); }
949         vmbreak;
950       }
951       vmcase(OP_BOR) {
952         TValue *rb = RKB(i);
953         TValue *rc = RKC(i);
954         lua_Integer ib; lua_Integer ic;
955         if (tointeger(rb, &ib) && tointeger(rc, &ic)) {
956           setivalue(ra, intop(|, ib, ic));
957         }
958         else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_BOR)); }
959         vmbreak;
960       }
961       vmcase(OP_BXOR) {
962         TValue *rb = RKB(i);
963         TValue *rc = RKC(i);
964         lua_Integer ib; lua_Integer ic;
965         if (tointeger(rb, &ib) && tointeger(rc, &ic)) {
966           setivalue(ra, intop(^, ib, ic));
967         }
968         else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_BXOR)); }
969         vmbreak;
970       }
971       vmcase(OP_SHL) {
972         TValue *rb = RKB(i);
973         TValue *rc = RKC(i);
974         lua_Integer ib; lua_Integer ic;
975         if (tointeger(rb, &ib) && tointeger(rc, &ic)) {
976           setivalue(ra, luaV_shiftl(ib, ic));
977         }
978         else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_SHL)); }
979         vmbreak;
980       }
981       vmcase(OP_SHR) {
982         TValue *rb = RKB(i);
983         TValue *rc = RKC(i);
984         lua_Integer ib; lua_Integer ic;
985         if (tointeger(rb, &ib) && tointeger(rc, &ic)) {
986           setivalue(ra, luaV_shiftl(ib, -ic));
987         }
988         else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_SHR)); }
989         vmbreak;
990       }
991       vmcase(OP_MOD) {
992         TValue *rb = RKB(i);
993         TValue *rc = RKC(i);
994         lua_Number nb; lua_Number nc;
995         if (ttisinteger(rb) && ttisinteger(rc)) {
996           lua_Integer ib = ivalue(rb); lua_Integer ic = ivalue(rc);
997           setivalue(ra, luaV_mod(L, ib, ic));
998         }
999         else if (tonumber(rb, &nb) && tonumber(rc, &nc)) {
1000           lua_Number m;
1001           luai_nummod(L, nb, nc, m);
1002           setfltvalue(ra, m);
1003         }
1004         else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_MOD)); }
1005         vmbreak;
1006       }
1007       vmcase(OP_IDIV) {  /* floor division */
1008         TValue *rb = RKB(i);
1009         TValue *rc = RKC(i);
1010         lua_Number nb; lua_Number nc;
1011         if (ttisinteger(rb) && ttisinteger(rc)) {
1012           lua_Integer ib = ivalue(rb); lua_Integer ic = ivalue(rc);
1013           setivalue(ra, luaV_div(L, ib, ic));
1014         }
1015         else if (tonumber(rb, &nb) && tonumber(rc, &nc)) {
1016           setfltvalue(ra, luai_numidiv(L, nb, nc));
1017         }
1018         else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_IDIV)); }
1019         vmbreak;
1020       }
1021       vmcase(OP_POW) {
1022         TValue *rb = RKB(i);
1023         TValue *rc = RKC(i);
1024         lua_Number nb; lua_Number nc;
1025         if (tonumber(rb, &nb) && tonumber(rc, &nc)) {
1026           setfltvalue(ra, luai_numpow(L, nb, nc));
1027         }
1028         else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_POW)); }
1029         vmbreak;
1030       }
1031       vmcase(OP_UNM) {
1032         TValue *rb = RB(i);
1033         lua_Number nb;
1034         if (ttisinteger(rb)) {
1035           lua_Integer ib = ivalue(rb);
1036           setivalue(ra, intop(-, 0, ib));
1037         }
1038         else if (tonumber(rb, &nb)) {
1039           setfltvalue(ra, luai_numunm(L, nb));
1040         }
1041         else {
1042           Protect(luaT_trybinTM(L, rb, rb, ra, TM_UNM));
1043         }
1044         vmbreak;
1045       }
1046       vmcase(OP_BNOT) {
1047         TValue *rb = RB(i);
1048         lua_Integer ib;
1049         if (tointeger(rb, &ib)) {
1050           setivalue(ra, intop(^, ~l_castS2U(0), ib));
1051         }
1052         else {
1053           Protect(luaT_trybinTM(L, rb, rb, ra, TM_BNOT));
1054         }
1055         vmbreak;
1056       }
1057       vmcase(OP_NOT) {
1058         TValue *rb = RB(i);
1059         int res = l_isfalse(rb);  /* next assignment may change this value */
1060         setbvalue(ra, res);
1061         vmbreak;
1062       }
1063       vmcase(OP_LEN) {
1064         Protect(luaV_objlen(L, ra, RB(i)));
1065         vmbreak;
1066       }
1067       vmcase(OP_CONCAT) {
1068         int b = GETARG_B(i);
1069         int c = GETARG_C(i);
1070         StkId rb;
1071         L->top = base + c + 1;  /* mark the end of concat operands */
1072         Protect(luaV_concat(L, c - b + 1));
1073         ra = RA(i);  /* 'luaV_concat' may invoke TMs and move the stack */
1074         rb = base + b;
1075         setobjs2s(L, ra, rb);
1076         checkGC(L, (ra >= rb ? ra + 1 : rb));
1077         L->top = ci->top;  /* restore top */
1078         vmbreak;
1079       }
1080       vmcase(OP_JMP) {
1081         dojump(ci, i, 0);
1082         vmbreak;
1083       }
1084       vmcase(OP_EQ) {
1085         TValue *rb = RKB(i);
1086         TValue *rc = RKC(i);
1087         Protect(
1088           if (luaV_equalobj(L, rb, rc) != GETARG_A(i))
1089             ci->u.l.savedpc++;
1090           else
1091             donextjump(ci);
1092         )
1093         vmbreak;
1094       }
1095       vmcase(OP_LT) {
1096         Protect(
1097           if (luaV_lessthan(L, RKB(i), RKC(i)) != GETARG_A(i))
1098             ci->u.l.savedpc++;
1099           else
1100             donextjump(ci);
1101         )
1102         vmbreak;
1103       }
1104       vmcase(OP_LE) {
1105         Protect(
1106           if (luaV_lessequal(L, RKB(i), RKC(i)) != GETARG_A(i))
1107             ci->u.l.savedpc++;
1108           else
1109             donextjump(ci);
1110         )
1111         vmbreak;
1112       }
1113       vmcase(OP_TEST) {
1114         if (GETARG_C(i) ? l_isfalse(ra) : !l_isfalse(ra))
1115             ci->u.l.savedpc++;
1116           else
1117           donextjump(ci);
1118         vmbreak;
1119       }
1120       vmcase(OP_TESTSET) {
1121         TValue *rb = RB(i);
1122         if (GETARG_C(i) ? l_isfalse(rb) : !l_isfalse(rb))
1123           ci->u.l.savedpc++;
1124         else {
1125           setobjs2s(L, ra, rb);
1126           donextjump(ci);
1127         }
1128         vmbreak;
1129       }
1130       vmcase(OP_CALL) {
1131         int b = GETARG_B(i);
1132         int nresults = GETARG_C(i) - 1;
1133         if (b != 0) L->top = ra+b;  /* else previous instruction set top */
1134         if (luaD_precall(L, ra, nresults)) {  /* C function? */
1135           if (nresults >= 0)
1136             L->top = ci->top;  /* adjust results */
1137           Protect((void)0);  /* update 'base' */
1138         }
1139         else {  /* Lua function */
1140           ci = L->ci;
1141           goto newframe;  /* restart luaV_execute over new Lua function */
1142         }
1143         vmbreak;
1144       }
1145       vmcase(OP_TAILCALL) {
1146         int b = GETARG_B(i);
1147         if (b != 0) L->top = ra+b;  /* else previous instruction set top */
1148         lua_assert(GETARG_C(i) - 1 == LUA_MULTRET);
1149         if (luaD_precall(L, ra, LUA_MULTRET)) {  /* C function? */
1150           Protect((void)0);  /* update 'base' */
1151         }
1152         else {
1153           /* tail call: put called frame (n) in place of caller one (o) */
1154           CallInfo *nci = L->ci;  /* called frame */
1155           CallInfo *oci = nci->previous;  /* caller frame */
1156           StkId nfunc = nci->func;  /* called function */
1157           StkId ofunc = oci->func;  /* caller function */
1158           /* last stack slot filled by 'precall' */
1159           StkId lim = nci->u.l.base + getproto(nfunc)->numparams;
1160           int aux;
1161           /* close all upvalues from previous call */
1162           if (cl->p->sizep > 0) luaF_close(L, oci->u.l.base);
1163           /* move new frame into old one */
1164           for (aux = 0; nfunc + aux < lim; aux++)
1165             setobjs2s(L, ofunc + aux, nfunc + aux);
1166           oci->u.l.base = ofunc + (nci->u.l.base - nfunc);  /* correct base */
1167           oci->top = L->top = ofunc + (L->top - nfunc);  /* correct top */
1168           oci->u.l.savedpc = nci->u.l.savedpc;
1169           oci->callstatus |= CIST_TAIL;  /* function was tail called */
1170           ci = L->ci = oci;  /* remove new frame */
1171           lua_assert(L->top == oci->u.l.base + getproto(ofunc)->maxstacksize);
1172           goto newframe;  /* restart luaV_execute over new Lua function */
1173         }
1174         vmbreak;
1175       }
1176       vmcase(OP_RETURN) {
1177         int b = GETARG_B(i);
1178         if (cl->p->sizep > 0) luaF_close(L, base);
1179         b = luaD_poscall(L, ci, ra, (b != 0 ? b - 1 : cast_int(L->top - ra)));
1180         if (ci->callstatus & CIST_FRESH)  /* local 'ci' still from callee */
1181           return;  /* external invocation: return */
1182         else {  /* invocation via reentry: continue execution */
1183           ci = L->ci;
1184           if (b) L->top = ci->top;
1185           lua_assert(isLua(ci));
1186           lua_assert(GET_OPCODE(*((ci)->u.l.savedpc - 1)) == OP_CALL);
1187           goto newframe;  /* restart luaV_execute over new Lua function */
1188         }
1189       }
1190       vmcase(OP_FORLOOP) {
1191         if (ttisinteger(ra)) {  /* integer loop? */
1192           lua_Integer step = ivalue(ra + 2);
1193           lua_Integer idx = intop(+, ivalue(ra), step); /* increment index */
1194           lua_Integer limit = ivalue(ra + 1);
1195           if ((0 < step) ? (idx <= limit) : (limit <= idx)) {
1196             ci->u.l.savedpc += GETARG_sBx(i);  /* jump back */
1197             chgivalue(ra, idx);  /* update internal index... */
1198             setivalue(ra + 3, idx);  /* ...and external index */
1199           }
1200         }
1201         else {  /* floating loop */
1202           lua_Number step = fltvalue(ra + 2);
1203           lua_Number idx = luai_numadd(L, fltvalue(ra), step); /* inc. index */
1204           lua_Number limit = fltvalue(ra + 1);
1205           if (luai_numlt(0, step) ? luai_numle(idx, limit)
1206                                   : luai_numle(limit, idx)) {
1207             ci->u.l.savedpc += GETARG_sBx(i);  /* jump back */
1208             chgfltvalue(ra, idx);  /* update internal index... */
1209             setfltvalue(ra + 3, idx);  /* ...and external index */
1210           }
1211         }
1212         vmbreak;
1213       }
1214       vmcase(OP_FORPREP) {
1215         TValue *init = ra;
1216         TValue *plimit = ra + 1;
1217         TValue *pstep = ra + 2;
1218         lua_Integer ilimit;
1219         int stopnow;
1220         if (ttisinteger(init) && ttisinteger(pstep) &&
1221             forlimit(plimit, &ilimit, ivalue(pstep), &stopnow)) {
1222           /* all values are integer */
1223           lua_Integer initv = (stopnow ? 0 : ivalue(init));
1224           setivalue(plimit, ilimit);
1225           setivalue(init, intop(-, initv, ivalue(pstep)));
1226         }
1227         else {  /* try making all values floats */
1228           lua_Number ninit; lua_Number nlimit; lua_Number nstep;
1229           if (!tonumber(plimit, &nlimit))
1230             luaG_runerror(L, "'for' limit must be a number");
1231           setfltvalue(plimit, nlimit);
1232           if (!tonumber(pstep, &nstep))
1233             luaG_runerror(L, "'for' step must be a number");
1234           setfltvalue(pstep, nstep);
1235           if (!tonumber(init, &ninit))
1236             luaG_runerror(L, "'for' initial value must be a number");
1237           setfltvalue(init, luai_numsub(L, ninit, nstep));
1238         }
1239         ci->u.l.savedpc += GETARG_sBx(i);
1240         vmbreak;
1241       }
1242       vmcase(OP_TFORCALL) {
1243         StkId cb = ra + 3;  /* call base */
1244         setobjs2s(L, cb+2, ra+2);
1245         setobjs2s(L, cb+1, ra+1);
1246         setobjs2s(L, cb, ra);
1247         L->top = cb + 3;  /* func. + 2 args (state and index) */
1248         Protect(luaD_call(L, cb, GETARG_C(i)));
1249         L->top = ci->top;
1250         i = *(ci->u.l.savedpc++);  /* go to next instruction */
1251         ra = RA(i);
1252         lua_assert(GET_OPCODE(i) == OP_TFORLOOP);
1253         goto l_tforloop;
1254       }
1255       vmcase(OP_TFORLOOP) {
1256         l_tforloop:
1257         if (!ttisnil(ra + 1)) {  /* continue loop? */
1258           setobjs2s(L, ra, ra + 1);  /* save control variable */
1259            ci->u.l.savedpc += GETARG_sBx(i);  /* jump back */
1260         }
1261         vmbreak;
1262       }
1263       vmcase(OP_SETLIST) {
1264         int n = GETARG_B(i);
1265         int c = GETARG_C(i);
1266         unsigned int last;
1267         Table *h;
1268         if (n == 0) n = cast_int(L->top - ra) - 1;
1269         if (c == 0) {
1270           lua_assert(GET_OPCODE(*ci->u.l.savedpc) == OP_EXTRAARG);
1271           c = GETARG_Ax(*ci->u.l.savedpc++);
1272         }
1273         h = hvalue(ra);
1274         last = ((c-1)*LFIELDS_PER_FLUSH) + n;
1275         if (last > h->sizearray)  /* needs more space? */
1276           luaH_resizearray(L, h, last);  /* preallocate it at once */
1277         for (; n > 0; n--) {
1278           TValue *val = ra+n;
1279           luaH_setint(L, h, last--, val);
1280           luaC_barrierback(L, h, val);
1281         }
1282         L->top = ci->top;  /* correct top (in case of previous open call) */
1283         vmbreak;
1284       }
1285       vmcase(OP_CLOSURE) {
1286         Proto *p = cl->p->p[GETARG_Bx(i)];
1287         LClosure *ncl = getcached(p, cl->upvals, base);  /* cached closure */
1288         if (ncl == NULL)  /* no match? */
1289           pushclosure(L, p, cl->upvals, base, ra);  /* create a new one */
1290         else
1291           setclLvalue(L, ra, ncl);  /* push cashed closure */
1292         checkGC(L, ra + 1);
1293         vmbreak;
1294       }
1295       vmcase(OP_VARARG) {
1296         int b = GETARG_B(i) - 1;  /* required results */
1297         int j;
1298         int n = cast_int(base - ci->func) - cl->p->numparams - 1;
1299         if (n < 0)  /* less arguments than parameters? */
1300           n = 0;  /* no vararg arguments */
1301         if (b < 0) {  /* B == 0? */
1302           b = n;  /* get all var. arguments */
1303           Protect(luaD_checkstack(L, n));
1304           ra = RA(i);  /* previous call may change the stack */
1305           L->top = ra + n;
1306         }
1307         for (j = 0; j < b && j < n; j++)
1308           setobjs2s(L, ra + j, base - n + j);
1309         for (; j < b; j++)  /* complete required results with nil */
1310           setnilvalue(ra + j);
1311         vmbreak;
1312       }
1313       vmcase(OP_EXTRAARG) {
1314         lua_assert(0);
1315         vmbreak;
1316       }
1317     }
1318   }
1319 }
1320 
1321 /* }================================================================== */
1322 
1323