xref: /freebsd/contrib/lua/src/lvm.c (revision cfd6422a5217410fbd66f7a7a8a64d9d85e61229)
1 /*
2 ** $Id: lvm.c $
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 /*
35 ** By default, use jump tables in the main interpreter loop on gcc
36 ** and compatible compilers.
37 */
38 #if !defined(LUA_USE_JUMPTABLE)
39 #if defined(__GNUC__)
40 #define LUA_USE_JUMPTABLE	1
41 #else
42 #define LUA_USE_JUMPTABLE	0
43 #endif
44 #endif
45 
46 
47 
48 /* limit for table tag-method chains (to avoid infinite loops) */
49 #define MAXTAGLOOP	2000
50 
51 
52 /*
53 ** 'l_intfitsf' checks whether a given integer is in the range that
54 ** can be converted to a float without rounding. Used in comparisons.
55 */
56 #if !defined(l_intfitsf) && LUA_FLOAT_TYPE != LUA_FLOAT_INT64
57 
58 /* number of bits in the mantissa of a float */
59 #define NBM		(l_floatatt(MANT_DIG))
60 
61 /*
62 ** Check whether some integers may not fit in a float, testing whether
63 ** (maxinteger >> NBM) > 0. (That implies (1 << NBM) <= maxinteger.)
64 ** (The shifts are done in parts, to avoid shifting by more than the size
65 ** of an integer. In a worst case, NBM == 113 for long double and
66 ** sizeof(long) == 32.)
67 */
68 #if ((((LUA_MAXINTEGER >> (NBM / 4)) >> (NBM / 4)) >> (NBM / 4)) \
69 	>> (NBM - (3 * (NBM / 4))))  >  0
70 
71 /* limit for integers that fit in a float */
72 #define MAXINTFITSF	((lua_Unsigned)1 << NBM)
73 
74 /* check whether 'i' is in the interval [-MAXINTFITSF, MAXINTFITSF] */
75 #define l_intfitsf(i)	((MAXINTFITSF + l_castS2U(i)) <= (2 * MAXINTFITSF))
76 
77 #else  /* all integers fit in a float precisely */
78 
79 #define l_intfitsf(i)	1
80 
81 #endif
82 
83 #endif /* !defined(l_intfitsf) && LUA_FLOAT_TYPE != LUA_FLOAT_INT64 */
84 
85 #ifndef l_intfitsf
86 #define l_intfitsf(i)	1
87 #endif
88 
89 
90 /*
91 ** Try to convert a value from string to a number value.
92 ** If the value is not a string or is a string not representing
93 ** a valid numeral (or if coercions from strings to numbers
94 ** are disabled via macro 'cvt2num'), do not modify 'result'
95 ** and return 0.
96 */
97 static int l_strton (const TValue *obj, TValue *result) {
98   lua_assert(obj != result);
99   if (!cvt2num(obj))  /* is object not a string? */
100     return 0;
101   else
102     return (luaO_str2num(svalue(obj), result) == vslen(obj) + 1);
103 }
104 
105 
106 /*
107 ** Try to convert a value to a float. The float case is already handled
108 ** by the macro 'tonumber'.
109 */
110 int luaV_tonumber_ (const TValue *obj, lua_Number *n) {
111   TValue v;
112   if (ttisinteger(obj)) {
113     *n = cast_num(ivalue(obj));
114     return 1;
115   }
116   else if (l_strton(obj, &v)) {  /* string coercible to number? */
117     *n = nvalue(&v);  /* convert result of 'luaO_str2num' to a float */
118     return 1;
119   }
120   else
121     return 0;  /* conversion failed */
122 }
123 
124 
125 /*
126 ** try to convert a float to an integer, rounding according to 'mode'.
127 */
128 int luaV_flttointeger (lua_Number n, lua_Integer *p, F2Imod mode) {
129   lua_Number f = l_floor(n);
130   if (n != f) {  /* not an integral value? */
131     if (mode == F2Ieq) return 0;  /* fails if mode demands integral value */
132     else if (mode == F2Iceil)  /* needs ceil? */
133       f += 1;  /* convert floor to ceil (remember: n != f) */
134   }
135   return lua_numbertointeger(f, p);
136 }
137 
138 
139 /*
140 ** try to convert a value to an integer, rounding according to 'mode',
141 ** without string coercion.
142 ** ("Fast track" handled by macro 'tointegerns'.)
143 */
144 int luaV_tointegerns (const TValue *obj, lua_Integer *p, F2Imod mode) {
145   if (ttisfloat(obj))
146     return luaV_flttointeger(fltvalue(obj), p, mode);
147   else if (ttisinteger(obj)) {
148     *p = ivalue(obj);
149     return 1;
150   }
151   else
152     return 0;
153 }
154 
155 
156 /*
157 ** try to convert a value to an integer.
158 */
159 int luaV_tointeger (const TValue *obj, lua_Integer *p, F2Imod mode) {
160   TValue v;
161   if (l_strton(obj, &v))  /* does 'obj' point to a numerical string? */
162     obj = &v;  /* change it to point to its corresponding number */
163   return luaV_tointegerns(obj, p, mode);
164 }
165 
166 
167 /*
168 ** Try to convert a 'for' limit to an integer, preserving the semantics
169 ** of the loop. Return true if the loop must not run; otherwise, '*p'
170 ** gets the integer limit.
171 ** (The following explanation assumes a positive step; it is valid for
172 ** negative steps mutatis mutandis.)
173 ** If the limit is an integer or can be converted to an integer,
174 ** rounding down, that is the limit.
175 ** Otherwise, check whether the limit can be converted to a float. If
176 ** the float is too large, clip it to LUA_MAXINTEGER.  If the float
177 ** is too negative, the loop should not run, because any initial
178 ** integer value is greater than such limit; so, the function returns
179 ** true to signal that. (For this latter case, no integer limit would be
180 ** correct; even a limit of LUA_MININTEGER would run the loop once for
181 ** an initial value equal to LUA_MININTEGER.)
182 */
183 static int forlimit (lua_State *L, lua_Integer init, const TValue *lim,
184                                    lua_Integer *p, lua_Integer step) {
185   if (!luaV_tointeger(lim, p, (step < 0 ? F2Iceil : F2Ifloor))) {
186     /* not coercible to in integer */
187     lua_Number flim;  /* try to convert to float */
188     if (!tonumber(lim, &flim)) /* cannot convert to float? */
189       luaG_forerror(L, lim, "limit");
190     /* else 'flim' is a float out of integer bounds */
191     if (luai_numlt(0, flim)) {  /* if it is positive, it is too large */
192       if (step < 0) return 1;  /* initial value must be less than it */
193       *p = LUA_MAXINTEGER;  /* truncate */
194     }
195     else {  /* it is less than min integer */
196       if (step > 0) return 1;  /* initial value must be greater than it */
197       *p = LUA_MININTEGER;  /* truncate */
198     }
199   }
200   return (step > 0 ? init > *p : init < *p);  /* not to run? */
201 }
202 
203 
204 /*
205 ** Prepare a numerical for loop (opcode OP_FORPREP).
206 ** Return true to skip the loop. Otherwise,
207 ** after preparation, stack will be as follows:
208 **   ra : internal index (safe copy of the control variable)
209 **   ra + 1 : loop counter (integer loops) or limit (float loops)
210 **   ra + 2 : step
211 **   ra + 3 : control variable
212 */
213 static int forprep (lua_State *L, StkId ra) {
214   TValue *pinit = s2v(ra);
215   TValue *plimit = s2v(ra + 1);
216   TValue *pstep = s2v(ra + 2);
217   if (ttisinteger(pinit) && ttisinteger(pstep)) { /* integer loop? */
218     lua_Integer init = ivalue(pinit);
219     lua_Integer step = ivalue(pstep);
220     lua_Integer limit;
221     if (step == 0)
222       luaG_runerror(L, "'for' step is zero");
223     setivalue(s2v(ra + 3), init);  /* control variable */
224     if (forlimit(L, init, plimit, &limit, step))
225       return 1;  /* skip the loop */
226     else {  /* prepare loop counter */
227       lua_Unsigned count;
228       if (step > 0) {  /* ascending loop? */
229         count = l_castS2U(limit) - l_castS2U(init);
230         if (step != 1)  /* avoid division in the too common case */
231           count /= l_castS2U(step);
232       }
233       else {  /* step < 0; descending loop */
234         count = l_castS2U(init) - l_castS2U(limit);
235         /* 'step+1' avoids negating 'mininteger' */
236         count /= l_castS2U(-(step + 1)) + 1u;
237       }
238       /* store the counter in place of the limit (which won't be
239          needed anymore) */
240       setivalue(plimit, l_castU2S(count));
241     }
242   }
243   else {  /* try making all values floats */
244     lua_Number init; lua_Number limit; lua_Number step;
245     if (unlikely(!tonumber(plimit, &limit)))
246       luaG_forerror(L, plimit, "limit");
247     if (unlikely(!tonumber(pstep, &step)))
248       luaG_forerror(L, pstep, "step");
249     if (unlikely(!tonumber(pinit, &init)))
250       luaG_forerror(L, pinit, "initial value");
251     if (step == 0)
252       luaG_runerror(L, "'for' step is zero");
253     if (luai_numlt(0, step) ? luai_numlt(limit, init)
254                             : luai_numlt(init, limit))
255       return 1;  /* skip the loop */
256     else {
257       /* make sure internal values are all floats */
258       setfltvalue(plimit, limit);
259       setfltvalue(pstep, step);
260       setfltvalue(s2v(ra), init);  /* internal index */
261       setfltvalue(s2v(ra + 3), init);  /* control variable */
262     }
263   }
264   return 0;
265 }
266 
267 
268 /*
269 ** Execute a step of a float numerical for loop, returning
270 ** true iff the loop must continue. (The integer case is
271 ** written online with opcode OP_FORLOOP, for performance.)
272 */
273 static int floatforloop (StkId ra) {
274   lua_Number step = fltvalue(s2v(ra + 2));
275   lua_Number limit = fltvalue(s2v(ra + 1));
276   lua_Number idx = fltvalue(s2v(ra));  /* internal index */
277   idx = luai_numadd(L, idx, step);  /* increment index */
278   if (luai_numlt(0, step) ? luai_numle(idx, limit)
279                           : luai_numle(limit, idx)) {
280     chgfltvalue(s2v(ra), idx);  /* update internal index */
281     setfltvalue(s2v(ra + 3), idx);  /* and control variable */
282     return 1;  /* jump back */
283   }
284   else
285     return 0;  /* finish the loop */
286 }
287 
288 
289 /*
290 ** Finish the table access 'val = t[key]'.
291 ** if 'slot' is NULL, 't' is not a table; otherwise, 'slot' points to
292 ** t[k] entry (which must be empty).
293 */
294 void luaV_finishget (lua_State *L, const TValue *t, TValue *key, StkId val,
295                       const TValue *slot) {
296   int loop;  /* counter to avoid infinite loops */
297   const TValue *tm;  /* metamethod */
298   for (loop = 0; loop < MAXTAGLOOP; loop++) {
299     if (slot == NULL) {  /* 't' is not a table? */
300       lua_assert(!ttistable(t));
301       tm = luaT_gettmbyobj(L, t, TM_INDEX);
302       if (unlikely(notm(tm)))
303         luaG_typeerror(L, t, "index");  /* no metamethod */
304       /* else will try the metamethod */
305     }
306     else {  /* 't' is a table */
307       lua_assert(isempty(slot));
308       tm = fasttm(L, hvalue(t)->metatable, TM_INDEX);  /* table's metamethod */
309       if (tm == NULL) {  /* no metamethod? */
310         setnilvalue(s2v(val));  /* result is nil */
311         return;
312       }
313       /* else will try the metamethod */
314     }
315     if (ttisfunction(tm)) {  /* is metamethod a function? */
316       luaT_callTMres(L, tm, t, key, val);  /* call it */
317       return;
318     }
319     t = tm;  /* else try to access 'tm[key]' */
320     if (luaV_fastget(L, t, key, slot, luaH_get)) {  /* fast track? */
321       setobj2s(L, val, slot);  /* done */
322       return;
323     }
324     /* else repeat (tail call 'luaV_finishget') */
325   }
326   luaG_runerror(L, "'__index' chain too long; possible loop");
327 }
328 
329 
330 /*
331 ** Finish a table assignment 't[key] = val'.
332 ** If 'slot' is NULL, 't' is not a table.  Otherwise, 'slot' points
333 ** to the entry 't[key]', or to a value with an absent key if there
334 ** is no such entry.  (The value at 'slot' must be empty, otherwise
335 ** 'luaV_fastget' would have done the job.)
336 */
337 void luaV_finishset (lua_State *L, const TValue *t, TValue *key,
338                      TValue *val, const TValue *slot) {
339   int loop;  /* counter to avoid infinite loops */
340   for (loop = 0; loop < MAXTAGLOOP; loop++) {
341     const TValue *tm;  /* '__newindex' metamethod */
342     if (slot != NULL) {  /* is 't' a table? */
343       Table *h = hvalue(t);  /* save 't' table */
344       lua_assert(isempty(slot));  /* slot must be empty */
345       tm = fasttm(L, h->metatable, TM_NEWINDEX);  /* get metamethod */
346       if (tm == NULL) {  /* no metamethod? */
347         if (isabstkey(slot))  /* no previous entry? */
348           slot = luaH_newkey(L, h, key);  /* create one */
349         /* no metamethod and (now) there is an entry with given key */
350         setobj2t(L, cast(TValue *, slot), val);  /* set its new value */
351         invalidateTMcache(h);
352         luaC_barrierback(L, obj2gco(h), val);
353         return;
354       }
355       /* else will try the metamethod */
356     }
357     else {  /* not a table; check metamethod */
358       tm = luaT_gettmbyobj(L, t, TM_NEWINDEX);
359       if (unlikely(notm(tm)))
360         luaG_typeerror(L, t, "index");
361     }
362     /* try the metamethod */
363     if (ttisfunction(tm)) {
364       luaT_callTM(L, tm, t, key, val);
365       return;
366     }
367     t = tm;  /* else repeat assignment over 'tm' */
368     if (luaV_fastget(L, t, key, slot, luaH_get)) {
369       luaV_finishfastset(L, t, slot, val);
370       return;  /* done */
371     }
372     /* else 'return luaV_finishset(L, t, key, val, slot)' (loop) */
373   }
374   luaG_runerror(L, "'__newindex' chain too long; possible loop");
375 }
376 
377 
378 /*
379 ** Compare two strings 'ls' x 'rs', returning an integer less-equal-
380 ** -greater than zero if 'ls' is less-equal-greater than 'rs'.
381 ** The code is a little tricky because it allows '\0' in the strings
382 ** and it uses 'strcoll' (to respect locales) for each segments
383 ** of the strings.
384 */
385 static int l_strcmp (const TString *ls, const TString *rs) {
386   const char *l = getstr(ls);
387   size_t ll = tsslen(ls);
388   const char *r = getstr(rs);
389   size_t lr = tsslen(rs);
390   for (;;) {  /* for each segment */
391     int temp = strcoll(l, r);
392     if (temp != 0)  /* not equal? */
393       return temp;  /* done */
394     else {  /* strings are equal up to a '\0' */
395       size_t len = strlen(l);  /* index of first '\0' in both strings */
396       if (len == lr)  /* 'rs' is finished? */
397         return (len == ll) ? 0 : 1;  /* check 'ls' */
398       else if (len == ll)  /* 'ls' is finished? */
399         return -1;  /* 'ls' is less than 'rs' ('rs' is not finished) */
400       /* both strings longer than 'len'; go on comparing after the '\0' */
401       len++;
402       l += len; ll -= len; r += len; lr -= len;
403     }
404   }
405 }
406 
407 
408 /*
409 ** Check whether integer 'i' is less than float 'f'. If 'i' has an
410 ** exact representation as a float ('l_intfitsf'), compare numbers as
411 ** floats. Otherwise, use the equivalence 'i < f <=> i < ceil(f)'.
412 ** If 'ceil(f)' is out of integer range, either 'f' is greater than
413 ** all integers or less than all integers.
414 ** (The test with 'l_intfitsf' is only for performance; the else
415 ** case is correct for all values, but it is slow due to the conversion
416 ** from float to int.)
417 ** When 'f' is NaN, comparisons must result in false.
418 */
419 static int LTintfloat (lua_Integer i, lua_Number f) {
420   if (l_intfitsf(i))
421     return luai_numlt(cast_num(i), f);  /* compare them as floats */
422   else {  /* i < f <=> i < ceil(f) */
423     lua_Integer fi;
424     if (luaV_flttointeger(f, &fi, F2Iceil))  /* fi = ceil(f) */
425       return i < fi;   /* compare them as integers */
426     else  /* 'f' is either greater or less than all integers */
427       return f > 0;  /* greater? */
428   }
429 }
430 
431 
432 /*
433 ** Check whether integer 'i' is less than or equal to float 'f'.
434 ** See comments on previous function.
435 */
436 static int LEintfloat (lua_Integer i, lua_Number f) {
437   if (l_intfitsf(i))
438     return luai_numle(cast_num(i), f);  /* compare them as floats */
439   else {  /* i <= f <=> i <= floor(f) */
440     lua_Integer fi;
441     if (luaV_flttointeger(f, &fi, F2Ifloor))  /* fi = floor(f) */
442       return i <= fi;   /* compare them as integers */
443     else  /* 'f' is either greater or less than all integers */
444       return f > 0;  /* greater? */
445   }
446 }
447 
448 
449 /*
450 ** Check whether float 'f' is less than integer 'i'.
451 ** See comments on previous function.
452 */
453 static int LTfloatint (lua_Number f, lua_Integer i) {
454   if (l_intfitsf(i))
455     return luai_numlt(f, cast_num(i));  /* compare them as floats */
456   else {  /* f < i <=> floor(f) < i */
457     lua_Integer fi;
458     if (luaV_flttointeger(f, &fi, F2Ifloor))  /* fi = floor(f) */
459       return fi < i;   /* compare them as integers */
460     else  /* 'f' is either greater or less than all integers */
461       return f < 0;  /* less? */
462   }
463 }
464 
465 
466 /*
467 ** Check whether float 'f' is less than or equal to integer 'i'.
468 ** See comments on previous function.
469 */
470 static int LEfloatint (lua_Number f, lua_Integer i) {
471   if (l_intfitsf(i))
472     return luai_numle(f, cast_num(i));  /* compare them as floats */
473   else {  /* f <= i <=> ceil(f) <= i */
474     lua_Integer fi;
475     if (luaV_flttointeger(f, &fi, F2Iceil))  /* fi = ceil(f) */
476       return fi <= i;   /* compare them as integers */
477     else  /* 'f' is either greater or less than all integers */
478       return f < 0;  /* less? */
479   }
480 }
481 
482 
483 /*
484 ** Return 'l < r', for numbers.
485 */
486 static int LTnum (const TValue *l, const TValue *r) {
487   lua_assert(ttisnumber(l) && ttisnumber(r));
488   if (ttisinteger(l)) {
489     lua_Integer li = ivalue(l);
490     if (ttisinteger(r))
491       return li < ivalue(r);  /* both are integers */
492     else  /* 'l' is int and 'r' is float */
493       return LTintfloat(li, fltvalue(r));  /* l < r ? */
494   }
495   else {
496     lua_Number lf = fltvalue(l);  /* 'l' must be float */
497     if (ttisfloat(r))
498       return luai_numlt(lf, fltvalue(r));  /* both are float */
499     else  /* 'l' is float and 'r' is int */
500       return LTfloatint(lf, ivalue(r));
501   }
502 }
503 
504 
505 /*
506 ** Return 'l <= r', for numbers.
507 */
508 static int LEnum (const TValue *l, const TValue *r) {
509   lua_assert(ttisnumber(l) && ttisnumber(r));
510   if (ttisinteger(l)) {
511     lua_Integer li = ivalue(l);
512     if (ttisinteger(r))
513       return li <= ivalue(r);  /* both are integers */
514     else  /* 'l' is int and 'r' is float */
515       return LEintfloat(li, fltvalue(r));  /* l <= r ? */
516   }
517   else {
518     lua_Number lf = fltvalue(l);  /* 'l' must be float */
519     if (ttisfloat(r))
520       return luai_numle(lf, fltvalue(r));  /* both are float */
521     else  /* 'l' is float and 'r' is int */
522       return LEfloatint(lf, ivalue(r));
523   }
524 }
525 
526 
527 /*
528 ** return 'l < r' for non-numbers.
529 */
530 static int lessthanothers (lua_State *L, const TValue *l, const TValue *r) {
531   lua_assert(!ttisnumber(l) || !ttisnumber(r));
532   if (ttisstring(l) && ttisstring(r))  /* both are strings? */
533     return l_strcmp(tsvalue(l), tsvalue(r)) < 0;
534   else
535     return luaT_callorderTM(L, l, r, TM_LT);
536 }
537 
538 
539 /*
540 ** Main operation less than; return 'l < r'.
541 */
542 int luaV_lessthan (lua_State *L, const TValue *l, const TValue *r) {
543   if (ttisnumber(l) && ttisnumber(r))  /* both operands are numbers? */
544     return LTnum(l, r);
545   else return lessthanothers(L, l, r);
546 }
547 
548 
549 /*
550 ** return 'l <= r' for non-numbers.
551 */
552 static int lessequalothers (lua_State *L, const TValue *l, const TValue *r) {
553   lua_assert(!ttisnumber(l) || !ttisnumber(r));
554   if (ttisstring(l) && ttisstring(r))  /* both are strings? */
555     return l_strcmp(tsvalue(l), tsvalue(r)) <= 0;
556   else
557     return luaT_callorderTM(L, l, r, TM_LE);
558 }
559 
560 
561 /*
562 ** Main operation less than or equal to; return 'l <= r'.
563 */
564 int luaV_lessequal (lua_State *L, const TValue *l, const TValue *r) {
565   if (ttisnumber(l) && ttisnumber(r))  /* both operands are numbers? */
566     return LEnum(l, r);
567   else return lessequalothers(L, l, r);
568 }
569 
570 
571 /*
572 ** Main operation for equality of Lua values; return 't1 == t2'.
573 ** L == NULL means raw equality (no metamethods)
574 */
575 int luaV_equalobj (lua_State *L, const TValue *t1, const TValue *t2) {
576   const TValue *tm;
577   if (ttypetag(t1) != ttypetag(t2)) {  /* not the same variant? */
578     if (ttype(t1) != ttype(t2) || ttype(t1) != LUA_TNUMBER)
579       return 0;  /* only numbers can be equal with different variants */
580     else {  /* two numbers with different variants */
581       lua_Integer i1, i2;  /* compare them as integers */
582       return (tointegerns(t1, &i1) && tointegerns(t2, &i2) && i1 == i2);
583     }
584   }
585   /* values have same type and same variant */
586   switch (ttypetag(t1)) {
587     case LUA_VNIL: case LUA_VFALSE: case LUA_VTRUE: return 1;
588     case LUA_VNUMINT: return (ivalue(t1) == ivalue(t2));
589     case LUA_VNUMFLT: return luai_numeq(fltvalue(t1), fltvalue(t2));
590     case LUA_VLIGHTUSERDATA: return pvalue(t1) == pvalue(t2);
591     case LUA_VLCF: return fvalue(t1) == fvalue(t2);
592     case LUA_VSHRSTR: return eqshrstr(tsvalue(t1), tsvalue(t2));
593     case LUA_VLNGSTR: return luaS_eqlngstr(tsvalue(t1), tsvalue(t2));
594     case LUA_VUSERDATA: {
595       if (uvalue(t1) == uvalue(t2)) return 1;
596       else if (L == NULL) return 0;
597       tm = fasttm(L, uvalue(t1)->metatable, TM_EQ);
598       if (tm == NULL)
599         tm = fasttm(L, uvalue(t2)->metatable, TM_EQ);
600       break;  /* will try TM */
601     }
602     case LUA_VTABLE: {
603       if (hvalue(t1) == hvalue(t2)) return 1;
604       else if (L == NULL) return 0;
605       tm = fasttm(L, hvalue(t1)->metatable, TM_EQ);
606       if (tm == NULL)
607         tm = fasttm(L, hvalue(t2)->metatable, TM_EQ);
608       break;  /* will try TM */
609     }
610     default:
611       return gcvalue(t1) == gcvalue(t2);
612   }
613   if (tm == NULL)  /* no TM? */
614     return 0;  /* objects are different */
615   else {
616     luaT_callTMres(L, tm, t1, t2, L->top);  /* call TM */
617     return !l_isfalse(s2v(L->top));
618   }
619 }
620 
621 
622 /* macro used by 'luaV_concat' to ensure that element at 'o' is a string */
623 #define tostring(L,o)  \
624 	(ttisstring(o) || (cvt2str(o) && (luaO_tostring(L, o), 1)))
625 
626 #define isemptystr(o)	(ttisshrstring(o) && tsvalue(o)->shrlen == 0)
627 
628 /* copy strings in stack from top - n up to top - 1 to buffer */
629 static void copy2buff (StkId top, int n, char *buff) {
630   size_t tl = 0;  /* size already copied */
631   do {
632     size_t l = vslen(s2v(top - n));  /* length of string being copied */
633     memcpy(buff + tl, svalue(s2v(top - n)), l * sizeof(char));
634     tl += l;
635   } while (--n > 0);
636 }
637 
638 
639 /*
640 ** Main operation for concatenation: concat 'total' values in the stack,
641 ** from 'L->top - total' up to 'L->top - 1'.
642 */
643 void luaV_concat (lua_State *L, int total) {
644   if (total == 1)
645     return;  /* "all" values already concatenated */
646   do {
647     StkId top = L->top;
648     int n = 2;  /* number of elements handled in this pass (at least 2) */
649     if (!(ttisstring(s2v(top - 2)) || cvt2str(s2v(top - 2))) ||
650         !tostring(L, s2v(top - 1)))
651       luaT_tryconcatTM(L);
652     else if (isemptystr(s2v(top - 1)))  /* second operand is empty? */
653       cast_void(tostring(L, s2v(top - 2)));  /* result is first operand */
654     else if (isemptystr(s2v(top - 2))) {  /* first operand is empty string? */
655       setobjs2s(L, top - 2, top - 1);  /* result is second op. */
656     }
657     else {
658       /* at least two non-empty string values; get as many as possible */
659       size_t tl = vslen(s2v(top - 1));
660       TString *ts;
661       /* collect total length and number of strings */
662       for (n = 1; n < total && tostring(L, s2v(top - n - 1)); n++) {
663         size_t l = vslen(s2v(top - n - 1));
664         if (unlikely(l >= (MAX_SIZE/sizeof(char)) - tl))
665           luaG_runerror(L, "string length overflow");
666         tl += l;
667       }
668       if (tl <= LUAI_MAXSHORTLEN) {  /* is result a short string? */
669         char buff[LUAI_MAXSHORTLEN];
670         copy2buff(top, n, buff);  /* copy strings to buffer */
671         ts = luaS_newlstr(L, buff, tl);
672       }
673       else {  /* long string; copy strings directly to final result */
674         ts = luaS_createlngstrobj(L, tl);
675         copy2buff(top, n, getstr(ts));
676       }
677       setsvalue2s(L, top - n, ts);  /* create result */
678     }
679     total -= n-1;  /* got 'n' strings to create 1 new */
680     L->top -= n-1;  /* popped 'n' strings and pushed one */
681   } while (total > 1);  /* repeat until only 1 result left */
682 }
683 
684 
685 /*
686 ** Main operation 'ra = #rb'.
687 */
688 void luaV_objlen (lua_State *L, StkId ra, const TValue *rb) {
689   const TValue *tm;
690   switch (ttypetag(rb)) {
691     case LUA_VTABLE: {
692       Table *h = hvalue(rb);
693       tm = fasttm(L, h->metatable, TM_LEN);
694       if (tm) break;  /* metamethod? break switch to call it */
695       setivalue(s2v(ra), luaH_getn(h));  /* else primitive len */
696       return;
697     }
698     case LUA_VSHRSTR: {
699       setivalue(s2v(ra), tsvalue(rb)->shrlen);
700       return;
701     }
702     case LUA_VLNGSTR: {
703       setivalue(s2v(ra), tsvalue(rb)->u.lnglen);
704       return;
705     }
706     default: {  /* try metamethod */
707       tm = luaT_gettmbyobj(L, rb, TM_LEN);
708       if (unlikely(notm(tm)))  /* no metamethod? */
709         luaG_typeerror(L, rb, "get length of");
710       break;
711     }
712   }
713   luaT_callTMres(L, tm, rb, rb, ra);
714 }
715 
716 
717 /*
718 ** Integer division; return 'm // n', that is, floor(m/n).
719 ** C division truncates its result (rounds towards zero).
720 ** 'floor(q) == trunc(q)' when 'q >= 0' or when 'q' is integer,
721 ** otherwise 'floor(q) == trunc(q) - 1'.
722 */
723 lua_Integer luaV_idiv (lua_State *L, lua_Integer m, lua_Integer n) {
724   if (unlikely(l_castS2U(n) + 1u <= 1u)) {  /* special cases: -1 or 0 */
725     if (n == 0)
726       luaG_runerror(L, "attempt to divide by zero");
727     return intop(-, 0, m);   /* n==-1; avoid overflow with 0x80000...//-1 */
728   }
729   else {
730     lua_Integer q = m / n;  /* perform C division */
731     if ((m ^ n) < 0 && m % n != 0)  /* 'm/n' would be negative non-integer? */
732       q -= 1;  /* correct result for different rounding */
733     return q;
734   }
735 }
736 
737 
738 /*
739 ** Integer modulus; return 'm % n'. (Assume that C '%' with
740 ** negative operands follows C99 behavior. See previous comment
741 ** about luaV_idiv.)
742 */
743 lua_Integer luaV_mod (lua_State *L, lua_Integer m, lua_Integer n) {
744   if (unlikely(l_castS2U(n) + 1u <= 1u)) {  /* special cases: -1 or 0 */
745     if (n == 0)
746       luaG_runerror(L, "attempt to perform 'n%%0'");
747     return 0;   /* m % -1 == 0; avoid overflow with 0x80000...%-1 */
748   }
749   else {
750     lua_Integer r = m % n;
751     if (r != 0 && (r ^ n) < 0)  /* 'm/n' would be non-integer negative? */
752       r += n;  /* correct result for different rounding */
753     return r;
754   }
755 }
756 
757 
758 /*
759 ** Float modulus
760 */
761 lua_Number luaV_modf (lua_State *L, lua_Number m, lua_Number n) {
762   lua_Number r;
763   luai_nummod(L, m, n, r);
764   return r;
765 }
766 
767 
768 /* number of bits in an integer */
769 #define NBITS	cast_int(sizeof(lua_Integer) * CHAR_BIT)
770 
771 /*
772 ** Shift left operation. (Shift right just negates 'y'.)
773 */
774 #define luaV_shiftr(x,y)	luaV_shiftl(x,-(y))
775 
776 lua_Integer luaV_shiftl (lua_Integer x, lua_Integer y) {
777   if (y < 0) {  /* shift right? */
778     if (y <= -NBITS) return 0;
779     else return intop(>>, x, -y);
780   }
781   else {  /* shift left */
782     if (y >= NBITS) return 0;
783     else return intop(<<, x, y);
784   }
785 }
786 
787 
788 /*
789 ** create a new Lua closure, push it in the stack, and initialize
790 ** its upvalues.
791 */
792 static void pushclosure (lua_State *L, Proto *p, UpVal **encup, StkId base,
793                          StkId ra) {
794   int nup = p->sizeupvalues;
795   Upvaldesc *uv = p->upvalues;
796   int i;
797   LClosure *ncl = luaF_newLclosure(L, nup);
798   ncl->p = p;
799   setclLvalue2s(L, ra, ncl);  /* anchor new closure in stack */
800   for (i = 0; i < nup; i++) {  /* fill in its upvalues */
801     if (uv[i].instack)  /* upvalue refers to local variable? */
802       ncl->upvals[i] = luaF_findupval(L, base + uv[i].idx);
803     else  /* get upvalue from enclosing function */
804       ncl->upvals[i] = encup[uv[i].idx];
805     luaC_objbarrier(L, ncl, ncl->upvals[i]);
806   }
807 }
808 
809 
810 /*
811 ** finish execution of an opcode interrupted by a yield
812 */
813 void luaV_finishOp (lua_State *L) {
814   CallInfo *ci = L->ci;
815   StkId base = ci->func + 1;
816   Instruction inst = *(ci->u.l.savedpc - 1);  /* interrupted instruction */
817   OpCode op = GET_OPCODE(inst);
818   switch (op) {  /* finish its execution */
819     case OP_MMBIN: case OP_MMBINI: case OP_MMBINK: {
820       setobjs2s(L, base + GETARG_A(*(ci->u.l.savedpc - 2)), --L->top);
821       break;
822     }
823     case OP_UNM: case OP_BNOT: case OP_LEN:
824     case OP_GETTABUP: case OP_GETTABLE: case OP_GETI:
825     case OP_GETFIELD: case OP_SELF: {
826       setobjs2s(L, base + GETARG_A(inst), --L->top);
827       break;
828     }
829     case OP_LT: case OP_LE:
830     case OP_LTI: case OP_LEI:
831     case OP_GTI: case OP_GEI:
832     case OP_EQ: {  /* note that 'OP_EQI'/'OP_EQK' cannot yield */
833       int res = !l_isfalse(s2v(L->top - 1));
834       L->top--;
835 #if defined(LUA_COMPAT_LT_LE)
836       if (ci->callstatus & CIST_LEQ) {  /* "<=" using "<" instead? */
837         ci->callstatus ^= CIST_LEQ;  /* clear mark */
838         res = !res;  /* negate result */
839       }
840 #endif
841       lua_assert(GET_OPCODE(*ci->u.l.savedpc) == OP_JMP);
842       if (res != GETARG_k(inst))  /* condition failed? */
843         ci->u.l.savedpc++;  /* skip jump instruction */
844       break;
845     }
846     case OP_CONCAT: {
847       StkId top = L->top - 1;  /* top when 'luaT_tryconcatTM' was called */
848       int a = GETARG_A(inst);      /* first element to concatenate */
849       int total = cast_int(top - 1 - (base + a));  /* yet to concatenate */
850       setobjs2s(L, top - 2, top);  /* put TM result in proper position */
851       L->top = top - 1;  /* top is one after last element (at top-2) */
852       luaV_concat(L, total);  /* concat them (may yield again) */
853       break;
854     }
855     default: {
856       /* only these other opcodes can yield */
857       lua_assert(op == OP_TFORCALL || op == OP_CALL ||
858            op == OP_TAILCALL || op == OP_SETTABUP || op == OP_SETTABLE ||
859            op == OP_SETI || op == OP_SETFIELD);
860       break;
861     }
862   }
863 }
864 
865 
866 
867 
868 /*
869 ** {==================================================================
870 ** Macros for arithmetic/bitwise/comparison opcodes in 'luaV_execute'
871 ** ===================================================================
872 */
873 
874 #define l_addi(L,a,b)	intop(+, a, b)
875 #define l_subi(L,a,b)	intop(-, a, b)
876 #define l_muli(L,a,b)	intop(*, a, b)
877 #define l_band(a,b)	intop(&, a, b)
878 #define l_bor(a,b)	intop(|, a, b)
879 #define l_bxor(a,b)	intop(^, a, b)
880 
881 #define l_lti(a,b)	(a < b)
882 #define l_lei(a,b)	(a <= b)
883 #define l_gti(a,b)	(a > b)
884 #define l_gei(a,b)	(a >= b)
885 
886 
887 /*
888 ** Arithmetic operations with immediate operands. 'iop' is the integer
889 ** operation, 'fop' is the float operation.
890 */
891 #define op_arithI(L,iop,fop) {  \
892   TValue *v1 = vRB(i);  \
893   int imm = GETARG_sC(i);  \
894   if (ttisinteger(v1)) {  \
895     lua_Integer iv1 = ivalue(v1);  \
896     pc++; setivalue(s2v(ra), iop(L, iv1, imm));  \
897   }  \
898   else if (ttisfloat(v1)) {  \
899     lua_Number nb = fltvalue(v1);  \
900     lua_Number fimm = cast_num(imm);  \
901     pc++; setfltvalue(s2v(ra), fop(L, nb, fimm)); \
902   }}
903 
904 
905 /*
906 ** Auxiliary function for arithmetic operations over floats and others
907 ** with two register operands.
908 */
909 #define op_arithf_aux(L,v1,v2,fop) {  \
910   lua_Number n1; lua_Number n2;  \
911   if (tonumberns(v1, n1) && tonumberns(v2, n2)) {  \
912     pc++; setfltvalue(s2v(ra), fop(L, n1, n2));  \
913   }}
914 
915 
916 /*
917 ** Arithmetic operations over floats and others with register operands.
918 */
919 #define op_arithf(L,fop) {  \
920   TValue *v1 = vRB(i);  \
921   TValue *v2 = vRC(i);  \
922   op_arithf_aux(L, v1, v2, fop); }
923 
924 
925 /*
926 ** Arithmetic operations with K operands for floats.
927 */
928 #define op_arithfK(L,fop) {  \
929   TValue *v1 = vRB(i);  \
930   TValue *v2 = KC(i);  \
931   op_arithf_aux(L, v1, v2, fop); }
932 
933 
934 /*
935 ** Arithmetic operations over integers and floats.
936 */
937 #define op_arith_aux(L,v1,v2,iop,fop) {  \
938   if (ttisinteger(v1) && ttisinteger(v2)) {  \
939     lua_Integer i1 = ivalue(v1); lua_Integer i2 = ivalue(v2);  \
940     pc++; setivalue(s2v(ra), iop(L, i1, i2));  \
941   }  \
942   else op_arithf_aux(L, v1, v2, fop); }
943 
944 
945 /*
946 ** Arithmetic operations with register operands.
947 */
948 #define op_arith(L,iop,fop) {  \
949   TValue *v1 = vRB(i);  \
950   TValue *v2 = vRC(i);  \
951   op_arith_aux(L, v1, v2, iop, fop); }
952 
953 
954 /*
955 ** Arithmetic operations with K operands.
956 */
957 #define op_arithK(L,iop,fop) {  \
958   TValue *v1 = vRB(i);  \
959   TValue *v2 = KC(i);  \
960   op_arith_aux(L, v1, v2, iop, fop); }
961 
962 
963 /*
964 ** Bitwise operations with constant operand.
965 */
966 #define op_bitwiseK(L,op) {  \
967   TValue *v1 = vRB(i);  \
968   TValue *v2 = KC(i);  \
969   lua_Integer i1;  \
970   lua_Integer i2 = ivalue(v2);  \
971   if (tointegerns(v1, &i1)) {  \
972     pc++; setivalue(s2v(ra), op(i1, i2));  \
973   }}
974 
975 
976 /*
977 ** Bitwise operations with register operands.
978 */
979 #define op_bitwise(L,op) {  \
980   TValue *v1 = vRB(i);  \
981   TValue *v2 = vRC(i);  \
982   lua_Integer i1; lua_Integer i2;  \
983   if (tointegerns(v1, &i1) && tointegerns(v2, &i2)) {  \
984     pc++; setivalue(s2v(ra), op(i1, i2));  \
985   }}
986 
987 
988 /*
989 ** Order operations with register operands. 'opn' actually works
990 ** for all numbers, but the fast track improves performance for
991 ** integers.
992 */
993 #define op_order(L,opi,opn,other) {  \
994         int cond;  \
995         TValue *rb = vRB(i);  \
996         if (ttisinteger(s2v(ra)) && ttisinteger(rb)) {  \
997           lua_Integer ia = ivalue(s2v(ra));  \
998           lua_Integer ib = ivalue(rb);  \
999           cond = opi(ia, ib);  \
1000         }  \
1001         else if (ttisnumber(s2v(ra)) && ttisnumber(rb))  \
1002           cond = opn(s2v(ra), rb);  \
1003         else  \
1004           Protect(cond = other(L, s2v(ra), rb));  \
1005         docondjump(); }
1006 
1007 
1008 /*
1009 ** Order operations with immediate operand. (Immediate operand is
1010 ** always small enough to have an exact representation as a float.)
1011 */
1012 #define op_orderI(L,opi,opf,inv,tm) {  \
1013         int cond;  \
1014         int im = GETARG_sB(i);  \
1015         if (ttisinteger(s2v(ra)))  \
1016           cond = opi(ivalue(s2v(ra)), im);  \
1017         else if (ttisfloat(s2v(ra))) {  \
1018           lua_Number fa = fltvalue(s2v(ra));  \
1019           lua_Number fim = cast_num(im);  \
1020           cond = opf(fa, fim);  \
1021         }  \
1022         else {  \
1023           int isf = GETARG_C(i);  \
1024           Protect(cond = luaT_callorderiTM(L, s2v(ra), im, inv, isf, tm));  \
1025         }  \
1026         docondjump(); }
1027 
1028 /* }================================================================== */
1029 
1030 
1031 /*
1032 ** {==================================================================
1033 ** Function 'luaV_execute': main interpreter loop
1034 ** ===================================================================
1035 */
1036 
1037 /*
1038 ** some macros for common tasks in 'luaV_execute'
1039 */
1040 
1041 
1042 #define RA(i)	(base+GETARG_A(i))
1043 #define RB(i)	(base+GETARG_B(i))
1044 #define vRB(i)	s2v(RB(i))
1045 #define KB(i)	(k+GETARG_B(i))
1046 #define RC(i)	(base+GETARG_C(i))
1047 #define vRC(i)	s2v(RC(i))
1048 #define KC(i)	(k+GETARG_C(i))
1049 #define RKC(i)	((TESTARG_k(i)) ? k + GETARG_C(i) : s2v(base + GETARG_C(i)))
1050 
1051 
1052 
1053 #define updatetrap(ci)  (trap = ci->u.l.trap)
1054 
1055 #define updatebase(ci)	(base = ci->func + 1)
1056 
1057 
1058 #define updatestack(ci) { if (trap) { updatebase(ci); ra = RA(i); } }
1059 
1060 
1061 /*
1062 ** Execute a jump instruction. The 'updatetrap' allows signals to stop
1063 ** tight loops. (Without it, the local copy of 'trap' could never change.)
1064 */
1065 #define dojump(ci,i,e)	{ pc += GETARG_sJ(i) + e; updatetrap(ci); }
1066 
1067 
1068 /* for test instructions, execute the jump instruction that follows it */
1069 #define donextjump(ci)	{ Instruction ni = *pc; dojump(ci, ni, 1); }
1070 
1071 /*
1072 ** do a conditional jump: skip next instruction if 'cond' is not what
1073 ** was expected (parameter 'k'), else do next instruction, which must
1074 ** be a jump.
1075 */
1076 #define docondjump()	if (cond != GETARG_k(i)) pc++; else donextjump(ci);
1077 
1078 
1079 /*
1080 ** Correct global 'pc'.
1081 */
1082 #define savepc(L)	(ci->u.l.savedpc = pc)
1083 
1084 
1085 /*
1086 ** Whenever code can raise errors, the global 'pc' and the global
1087 ** 'top' must be correct to report occasional errors.
1088 */
1089 #define savestate(L,ci)		(savepc(L), L->top = ci->top)
1090 
1091 
1092 /*
1093 ** Protect code that, in general, can raise errors, reallocate the
1094 ** stack, and change the hooks.
1095 */
1096 #define Protect(exp)  (savestate(L,ci), (exp), updatetrap(ci))
1097 
1098 /* special version that does not change the top */
1099 #define ProtectNT(exp)  (savepc(L), (exp), updatetrap(ci))
1100 
1101 /*
1102 ** Protect code that can only raise errors. (That is, it cannnot change
1103 ** the stack or hooks.)
1104 */
1105 #define halfProtect(exp)  (savestate(L,ci), (exp))
1106 
1107 /* 'c' is the limit of live values in the stack */
1108 #define checkGC(L,c)  \
1109 	{ luaC_condGC(L, (savepc(L), L->top = (c)), \
1110                          updatetrap(ci)); \
1111            luai_threadyield(L); }
1112 
1113 
1114 /* fetch an instruction and prepare its execution */
1115 #define vmfetch()	{ \
1116   if (trap) {  /* stack reallocation or hooks? */ \
1117     trap = luaG_traceexec(L, pc);  /* handle hooks */ \
1118     updatebase(ci);  /* correct stack */ \
1119   } \
1120   i = *(pc++); \
1121   ra = RA(i); /* WARNING: any stack reallocation invalidates 'ra' */ \
1122 }
1123 
1124 #define vmdispatch(o)	switch(o)
1125 #define vmcase(l)	case l:
1126 #define vmbreak		break
1127 
1128 
1129 void luaV_execute (lua_State *L, CallInfo *ci) {
1130   LClosure *cl;
1131   TValue *k;
1132   StkId base;
1133   const Instruction *pc;
1134   int trap;
1135 #if LUA_USE_JUMPTABLE
1136 #include "ljumptab.h"
1137 #endif
1138  startfunc:
1139   trap = L->hookmask;
1140  returning:  /* trap already set */
1141   cl = clLvalue(s2v(ci->func));
1142   k = cl->p->k;
1143   pc = ci->u.l.savedpc;
1144   if (trap) {
1145     if (pc == cl->p->code) {  /* first instruction (not resuming)? */
1146       if (cl->p->is_vararg)
1147         trap = 0;  /* hooks will start after VARARGPREP instruction */
1148       else  /* check 'call' hook */
1149         luaD_hookcall(L, ci);
1150     }
1151     ci->u.l.trap = 1;  /* assume trap is on, for now */
1152   }
1153   base = ci->func + 1;
1154   /* main loop of interpreter */
1155   for (;;) {
1156     Instruction i;  /* instruction being executed */
1157     StkId ra;  /* instruction's A register */
1158     vmfetch();
1159     lua_assert(base == ci->func + 1);
1160     lua_assert(base <= L->top && L->top < L->stack_last);
1161     /* invalidate top for instructions not expecting it */
1162     lua_assert(isIT(i) || (cast_void(L->top = base), 1));
1163     vmdispatch (GET_OPCODE(i)) {
1164       vmcase(OP_MOVE) {
1165         setobjs2s(L, ra, RB(i));
1166         vmbreak;
1167       }
1168       vmcase(OP_LOADI) {
1169         lua_Integer b = GETARG_sBx(i);
1170         setivalue(s2v(ra), b);
1171         vmbreak;
1172       }
1173       vmcase(OP_LOADF) {
1174         int b = GETARG_sBx(i);
1175         setfltvalue(s2v(ra), cast_num(b));
1176         vmbreak;
1177       }
1178       vmcase(OP_LOADK) {
1179         TValue *rb = k + GETARG_Bx(i);
1180         setobj2s(L, ra, rb);
1181         vmbreak;
1182       }
1183       vmcase(OP_LOADKX) {
1184         TValue *rb;
1185         rb = k + GETARG_Ax(*pc); pc++;
1186         setobj2s(L, ra, rb);
1187         vmbreak;
1188       }
1189       vmcase(OP_LOADFALSE) {
1190         setbfvalue(s2v(ra));
1191         vmbreak;
1192       }
1193       vmcase(OP_LFALSESKIP) {
1194         setbfvalue(s2v(ra));
1195         pc++;  /* skip next instruction */
1196         vmbreak;
1197       }
1198       vmcase(OP_LOADTRUE) {
1199         setbtvalue(s2v(ra));
1200         vmbreak;
1201       }
1202       vmcase(OP_LOADNIL) {
1203         int b = GETARG_B(i);
1204         do {
1205           setnilvalue(s2v(ra++));
1206         } while (b--);
1207         vmbreak;
1208       }
1209       vmcase(OP_GETUPVAL) {
1210         int b = GETARG_B(i);
1211         setobj2s(L, ra, cl->upvals[b]->v);
1212         vmbreak;
1213       }
1214       vmcase(OP_SETUPVAL) {
1215         UpVal *uv = cl->upvals[GETARG_B(i)];
1216         setobj(L, uv->v, s2v(ra));
1217         luaC_barrier(L, uv, s2v(ra));
1218         vmbreak;
1219       }
1220       vmcase(OP_GETTABUP) {
1221         const TValue *slot;
1222         TValue *upval = cl->upvals[GETARG_B(i)]->v;
1223         TValue *rc = KC(i);
1224         TString *key = tsvalue(rc);  /* key must be a string */
1225         if (luaV_fastget(L, upval, key, slot, luaH_getshortstr)) {
1226           setobj2s(L, ra, slot);
1227         }
1228         else
1229           Protect(luaV_finishget(L, upval, rc, ra, slot));
1230         vmbreak;
1231       }
1232       vmcase(OP_GETTABLE) {
1233         const TValue *slot;
1234         TValue *rb = vRB(i);
1235         TValue *rc = vRC(i);
1236         lua_Unsigned n;
1237         if (ttisinteger(rc)  /* fast track for integers? */
1238             ? (cast_void(n = ivalue(rc)), luaV_fastgeti(L, rb, n, slot))
1239             : luaV_fastget(L, rb, rc, slot, luaH_get)) {
1240           setobj2s(L, ra, slot);
1241         }
1242         else
1243           Protect(luaV_finishget(L, rb, rc, ra, slot));
1244         vmbreak;
1245       }
1246       vmcase(OP_GETI) {
1247         const TValue *slot;
1248         TValue *rb = vRB(i);
1249         int c = GETARG_C(i);
1250         if (luaV_fastgeti(L, rb, c, slot)) {
1251           setobj2s(L, ra, slot);
1252         }
1253         else {
1254           TValue key;
1255           setivalue(&key, c);
1256           Protect(luaV_finishget(L, rb, &key, ra, slot));
1257         }
1258         vmbreak;
1259       }
1260       vmcase(OP_GETFIELD) {
1261         const TValue *slot;
1262         TValue *rb = vRB(i);
1263         TValue *rc = KC(i);
1264         TString *key = tsvalue(rc);  /* key must be a string */
1265         if (luaV_fastget(L, rb, key, slot, luaH_getshortstr)) {
1266           setobj2s(L, ra, slot);
1267         }
1268         else
1269           Protect(luaV_finishget(L, rb, rc, ra, slot));
1270         vmbreak;
1271       }
1272       vmcase(OP_SETTABUP) {
1273         const TValue *slot;
1274         TValue *upval = cl->upvals[GETARG_A(i)]->v;
1275         TValue *rb = KB(i);
1276         TValue *rc = RKC(i);
1277         TString *key = tsvalue(rb);  /* key must be a string */
1278         if (luaV_fastget(L, upval, key, slot, luaH_getshortstr)) {
1279           luaV_finishfastset(L, upval, slot, rc);
1280         }
1281         else
1282           Protect(luaV_finishset(L, upval, rb, rc, slot));
1283         vmbreak;
1284       }
1285       vmcase(OP_SETTABLE) {
1286         const TValue *slot;
1287         TValue *rb = vRB(i);  /* key (table is in 'ra') */
1288         TValue *rc = RKC(i);  /* value */
1289         lua_Unsigned n;
1290         if (ttisinteger(rb)  /* fast track for integers? */
1291             ? (cast_void(n = ivalue(rb)), luaV_fastgeti(L, s2v(ra), n, slot))
1292             : luaV_fastget(L, s2v(ra), rb, slot, luaH_get)) {
1293           luaV_finishfastset(L, s2v(ra), slot, rc);
1294         }
1295         else
1296           Protect(luaV_finishset(L, s2v(ra), rb, rc, slot));
1297         vmbreak;
1298       }
1299       vmcase(OP_SETI) {
1300         const TValue *slot;
1301         int c = GETARG_B(i);
1302         TValue *rc = RKC(i);
1303         if (luaV_fastgeti(L, s2v(ra), c, slot)) {
1304           luaV_finishfastset(L, s2v(ra), slot, rc);
1305         }
1306         else {
1307           TValue key;
1308           setivalue(&key, c);
1309           Protect(luaV_finishset(L, s2v(ra), &key, rc, slot));
1310         }
1311         vmbreak;
1312       }
1313       vmcase(OP_SETFIELD) {
1314         const TValue *slot;
1315         TValue *rb = KB(i);
1316         TValue *rc = RKC(i);
1317         TString *key = tsvalue(rb);  /* key must be a string */
1318         if (luaV_fastget(L, s2v(ra), key, slot, luaH_getshortstr)) {
1319           luaV_finishfastset(L, s2v(ra), slot, rc);
1320         }
1321         else
1322           Protect(luaV_finishset(L, s2v(ra), rb, rc, slot));
1323         vmbreak;
1324       }
1325       vmcase(OP_NEWTABLE) {
1326         int b = GETARG_B(i);  /* log2(hash size) + 1 */
1327         int c = GETARG_C(i);  /* array size */
1328         Table *t;
1329         if (b > 0)
1330           b = 1 << (b - 1);  /* size is 2^(b - 1) */
1331         lua_assert((!TESTARG_k(i)) == (GETARG_Ax(*pc) == 0));
1332         if (TESTARG_k(i))  /* non-zero extra argument? */
1333           c += GETARG_Ax(*pc) * (MAXARG_C + 1);  /* add it to size */
1334         pc++;  /* skip extra argument */
1335         L->top = ra + 1;  /* correct top in case of emergency GC */
1336         t = luaH_new(L);  /* memory allocation */
1337         sethvalue2s(L, ra, t);
1338         if (b != 0 || c != 0)
1339           luaH_resize(L, t, c, b);  /* idem */
1340         checkGC(L, ra + 1);
1341         vmbreak;
1342       }
1343       vmcase(OP_SELF) {
1344         const TValue *slot;
1345         TValue *rb = vRB(i);
1346         TValue *rc = RKC(i);
1347         TString *key = tsvalue(rc);  /* key must be a string */
1348         setobj2s(L, ra + 1, rb);
1349         if (luaV_fastget(L, rb, key, slot, luaH_getstr)) {
1350           setobj2s(L, ra, slot);
1351         }
1352         else
1353           Protect(luaV_finishget(L, rb, rc, ra, slot));
1354         vmbreak;
1355       }
1356       vmcase(OP_ADDI) {
1357         op_arithI(L, l_addi, luai_numadd);
1358         vmbreak;
1359       }
1360       vmcase(OP_ADDK) {
1361         op_arithK(L, l_addi, luai_numadd);
1362         vmbreak;
1363       }
1364       vmcase(OP_SUBK) {
1365         op_arithK(L, l_subi, luai_numsub);
1366         vmbreak;
1367       }
1368       vmcase(OP_MULK) {
1369         op_arithK(L, l_muli, luai_nummul);
1370         vmbreak;
1371       }
1372       vmcase(OP_MODK) {
1373         op_arithK(L, luaV_mod, luaV_modf);
1374         vmbreak;
1375       }
1376       vmcase(OP_POWK) {
1377         op_arithfK(L, luai_numpow);
1378         vmbreak;
1379       }
1380       vmcase(OP_DIVK) {
1381         op_arithfK(L, luai_numdiv);
1382         vmbreak;
1383       }
1384       vmcase(OP_IDIVK) {
1385         op_arithK(L, luaV_idiv, luai_numidiv);
1386         vmbreak;
1387       }
1388       vmcase(OP_BANDK) {
1389         op_bitwiseK(L, l_band);
1390         vmbreak;
1391       }
1392       vmcase(OP_BORK) {
1393         op_bitwiseK(L, l_bor);
1394         vmbreak;
1395       }
1396       vmcase(OP_BXORK) {
1397         op_bitwiseK(L, l_bxor);
1398         vmbreak;
1399       }
1400       vmcase(OP_SHRI) {
1401         TValue *rb = vRB(i);
1402         int ic = GETARG_sC(i);
1403         lua_Integer ib;
1404         if (tointegerns(rb, &ib)) {
1405           pc++; setivalue(s2v(ra), luaV_shiftl(ib, -ic));
1406         }
1407         vmbreak;
1408       }
1409       vmcase(OP_SHLI) {
1410         TValue *rb = vRB(i);
1411         int ic = GETARG_sC(i);
1412         lua_Integer ib;
1413         if (tointegerns(rb, &ib)) {
1414           pc++; setivalue(s2v(ra), luaV_shiftl(ic, ib));
1415         }
1416         vmbreak;
1417       }
1418       vmcase(OP_ADD) {
1419         op_arith(L, l_addi, luai_numadd);
1420         vmbreak;
1421       }
1422       vmcase(OP_SUB) {
1423         op_arith(L, l_subi, luai_numsub);
1424         vmbreak;
1425       }
1426       vmcase(OP_MUL) {
1427         op_arith(L, l_muli, luai_nummul);
1428         vmbreak;
1429       }
1430       vmcase(OP_MOD) {
1431         op_arith(L, luaV_mod, luaV_modf);
1432         vmbreak;
1433       }
1434       vmcase(OP_POW) {
1435         op_arithf(L, luai_numpow);
1436         vmbreak;
1437       }
1438       vmcase(OP_DIV) {  /* float division (always with floats) */
1439         op_arithf(L, luai_numdiv);
1440         vmbreak;
1441       }
1442       vmcase(OP_IDIV) {  /* floor division */
1443         op_arith(L, luaV_idiv, luai_numidiv);
1444         vmbreak;
1445       }
1446       vmcase(OP_BAND) {
1447         op_bitwise(L, l_band);
1448         vmbreak;
1449       }
1450       vmcase(OP_BOR) {
1451         op_bitwise(L, l_bor);
1452         vmbreak;
1453       }
1454       vmcase(OP_BXOR) {
1455         op_bitwise(L, l_bxor);
1456         vmbreak;
1457       }
1458       vmcase(OP_SHR) {
1459         op_bitwise(L, luaV_shiftr);
1460         vmbreak;
1461       }
1462       vmcase(OP_SHL) {
1463         op_bitwise(L, luaV_shiftl);
1464         vmbreak;
1465       }
1466       vmcase(OP_MMBIN) {
1467         Instruction pi = *(pc - 2);  /* original arith. expression */
1468         TValue *rb = vRB(i);
1469         TMS tm = (TMS)GETARG_C(i);
1470         StkId result = RA(pi);
1471         lua_assert(OP_ADD <= GET_OPCODE(pi) && GET_OPCODE(pi) <= OP_SHR);
1472         Protect(luaT_trybinTM(L, s2v(ra), rb, result, tm));
1473         vmbreak;
1474       }
1475       vmcase(OP_MMBINI) {
1476         Instruction pi = *(pc - 2);  /* original arith. expression */
1477         int imm = GETARG_sB(i);
1478         TMS tm = (TMS)GETARG_C(i);
1479         int flip = GETARG_k(i);
1480         StkId result = RA(pi);
1481         Protect(luaT_trybiniTM(L, s2v(ra), imm, flip, result, tm));
1482         vmbreak;
1483       }
1484       vmcase(OP_MMBINK) {
1485         Instruction pi = *(pc - 2);  /* original arith. expression */
1486         TValue *imm = KB(i);
1487         TMS tm = (TMS)GETARG_C(i);
1488         int flip = GETARG_k(i);
1489         StkId result = RA(pi);
1490         Protect(luaT_trybinassocTM(L, s2v(ra), imm, flip, result, tm));
1491         vmbreak;
1492       }
1493       vmcase(OP_UNM) {
1494         TValue *rb = vRB(i);
1495         lua_Number nb;
1496         if (ttisinteger(rb)) {
1497           lua_Integer ib = ivalue(rb);
1498           setivalue(s2v(ra), intop(-, 0, ib));
1499         }
1500         else if (tonumberns(rb, nb)) {
1501           setfltvalue(s2v(ra), luai_numunm(L, nb));
1502         }
1503         else
1504           Protect(luaT_trybinTM(L, rb, rb, ra, TM_UNM));
1505         vmbreak;
1506       }
1507       vmcase(OP_BNOT) {
1508         TValue *rb = vRB(i);
1509         lua_Integer ib;
1510         if (tointegerns(rb, &ib)) {
1511           setivalue(s2v(ra), intop(^, ~l_castS2U(0), ib));
1512         }
1513         else
1514           Protect(luaT_trybinTM(L, rb, rb, ra, TM_BNOT));
1515         vmbreak;
1516       }
1517       vmcase(OP_NOT) {
1518         TValue *rb = vRB(i);
1519         if (l_isfalse(rb))
1520           setbtvalue(s2v(ra));
1521         else
1522           setbfvalue(s2v(ra));
1523         vmbreak;
1524       }
1525       vmcase(OP_LEN) {
1526         Protect(luaV_objlen(L, ra, vRB(i)));
1527         vmbreak;
1528       }
1529       vmcase(OP_CONCAT) {
1530         int n = GETARG_B(i);  /* number of elements to concatenate */
1531         L->top = ra + n;  /* mark the end of concat operands */
1532         ProtectNT(luaV_concat(L, n));
1533         checkGC(L, L->top); /* 'luaV_concat' ensures correct top */
1534         vmbreak;
1535       }
1536       vmcase(OP_CLOSE) {
1537         Protect(luaF_close(L, ra, LUA_OK));
1538         vmbreak;
1539       }
1540       vmcase(OP_TBC) {
1541         /* create new to-be-closed upvalue */
1542         halfProtect(luaF_newtbcupval(L, ra));
1543         vmbreak;
1544       }
1545       vmcase(OP_JMP) {
1546         dojump(ci, i, 0);
1547         vmbreak;
1548       }
1549       vmcase(OP_EQ) {
1550         int cond;
1551         TValue *rb = vRB(i);
1552         Protect(cond = luaV_equalobj(L, s2v(ra), rb));
1553         docondjump();
1554         vmbreak;
1555       }
1556       vmcase(OP_LT) {
1557         op_order(L, l_lti, LTnum, lessthanothers);
1558         vmbreak;
1559       }
1560       vmcase(OP_LE) {
1561         op_order(L, l_lei, LEnum, lessequalothers);
1562         vmbreak;
1563       }
1564       vmcase(OP_EQK) {
1565         TValue *rb = KB(i);
1566         /* basic types do not use '__eq'; we can use raw equality */
1567         int cond = luaV_rawequalobj(s2v(ra), rb);
1568         docondjump();
1569         vmbreak;
1570       }
1571       vmcase(OP_EQI) {
1572         int cond;
1573         int im = GETARG_sB(i);
1574         if (ttisinteger(s2v(ra)))
1575           cond = (ivalue(s2v(ra)) == im);
1576         else if (ttisfloat(s2v(ra)))
1577           cond = luai_numeq(fltvalue(s2v(ra)), cast_num(im));
1578         else
1579           cond = 0;  /* other types cannot be equal to a number */
1580         docondjump();
1581         vmbreak;
1582       }
1583       vmcase(OP_LTI) {
1584         op_orderI(L, l_lti, luai_numlt, 0, TM_LT);
1585         vmbreak;
1586       }
1587       vmcase(OP_LEI) {
1588         op_orderI(L, l_lei, luai_numle, 0, TM_LE);
1589         vmbreak;
1590       }
1591       vmcase(OP_GTI) {
1592         op_orderI(L, l_gti, luai_numgt, 1, TM_LT);
1593         vmbreak;
1594       }
1595       vmcase(OP_GEI) {
1596         op_orderI(L, l_gei, luai_numge, 1, TM_LE);
1597         vmbreak;
1598       }
1599       vmcase(OP_TEST) {
1600         int cond = !l_isfalse(s2v(ra));
1601         docondjump();
1602         vmbreak;
1603       }
1604       vmcase(OP_TESTSET) {
1605         TValue *rb = vRB(i);
1606         if (l_isfalse(rb) == GETARG_k(i))
1607           pc++;
1608         else {
1609           setobj2s(L, ra, rb);
1610           donextjump(ci);
1611         }
1612         vmbreak;
1613       }
1614       vmcase(OP_CALL) {
1615         CallInfo *newci;
1616         int b = GETARG_B(i);
1617         int nresults = GETARG_C(i) - 1;
1618         if (b != 0)  /* fixed number of arguments? */
1619           L->top = ra + b;  /* top signals number of arguments */
1620         /* else previous instruction set top */
1621         savepc(L);  /* in case of errors */
1622         if ((newci = luaD_precall(L, ra, nresults)) == NULL)
1623           updatetrap(ci);  /* C call; nothing else to be done */
1624         else {  /* Lua call: run function in this same C frame */
1625           ci = newci;
1626           ci->callstatus = 0;  /* call re-uses 'luaV_execute' */
1627           goto startfunc;
1628         }
1629         vmbreak;
1630       }
1631       vmcase(OP_TAILCALL) {
1632         int b = GETARG_B(i);  /* number of arguments + 1 (function) */
1633         int nparams1 = GETARG_C(i);
1634         /* delta is virtual 'func' - real 'func' (vararg functions) */
1635         int delta = (nparams1) ? ci->u.l.nextraargs + nparams1 : 0;
1636         if (b != 0)
1637           L->top = ra + b;
1638         else  /* previous instruction set top */
1639           b = cast_int(L->top - ra);
1640         savepc(ci);  /* several calls here can raise errors */
1641         if (TESTARG_k(i)) {
1642           /* close upvalues from current call; the compiler ensures
1643              that there are no to-be-closed variables here, so this
1644              call cannot change the stack */
1645           luaF_close(L, base, NOCLOSINGMETH);
1646           lua_assert(base == ci->func + 1);
1647         }
1648         while (!ttisfunction(s2v(ra))) {  /* not a function? */
1649           luaD_tryfuncTM(L, ra);  /* try '__call' metamethod */
1650           b++;  /* there is now one extra argument */
1651           checkstackGCp(L, 1, ra);
1652         }
1653         if (!ttisLclosure(s2v(ra))) {  /* C function? */
1654           luaD_precall(L, ra, LUA_MULTRET);  /* call it */
1655           updatetrap(ci);
1656           updatestack(ci);  /* stack may have been relocated */
1657           ci->func -= delta;  /* restore 'func' (if vararg) */
1658           luaD_poscall(L, ci, cast_int(L->top - ra));  /* finish caller */
1659           updatetrap(ci);  /* 'luaD_poscall' can change hooks */
1660           goto ret;  /* caller returns after the tail call */
1661         }
1662         ci->func -= delta;  /* restore 'func' (if vararg) */
1663         luaD_pretailcall(L, ci, ra, b);  /* prepare call frame */
1664         goto startfunc;  /* execute the callee */
1665       }
1666       vmcase(OP_RETURN) {
1667         int n = GETARG_B(i) - 1;  /* number of results */
1668         int nparams1 = GETARG_C(i);
1669         if (n < 0)  /* not fixed? */
1670           n = cast_int(L->top - ra);  /* get what is available */
1671         savepc(ci);
1672         if (TESTARG_k(i)) {  /* may there be open upvalues? */
1673           if (L->top < ci->top)
1674             L->top = ci->top;
1675           luaF_close(L, base, LUA_OK);
1676           updatetrap(ci);
1677           updatestack(ci);
1678         }
1679         if (nparams1)  /* vararg function? */
1680           ci->func -= ci->u.l.nextraargs + nparams1;
1681         L->top = ra + n;  /* set call for 'luaD_poscall' */
1682         luaD_poscall(L, ci, n);
1683         updatetrap(ci);  /* 'luaD_poscall' can change hooks */
1684         goto ret;
1685       }
1686       vmcase(OP_RETURN0) {
1687         if (L->hookmask) {
1688           L->top = ra;
1689           savepc(ci);
1690           luaD_poscall(L, ci, 0);  /* no hurry... */
1691           trap = 1;
1692         }
1693         else {  /* do the 'poscall' here */
1694           int nres = ci->nresults;
1695           L->ci = ci->previous;  /* back to caller */
1696           L->top = base - 1;
1697           while (nres-- > 0)
1698             setnilvalue(s2v(L->top++));  /* all results are nil */
1699         }
1700         goto ret;
1701       }
1702       vmcase(OP_RETURN1) {
1703         if (L->hookmask) {
1704           L->top = ra + 1;
1705           savepc(ci);
1706           luaD_poscall(L, ci, 1);  /* no hurry... */
1707           trap = 1;
1708         }
1709         else {  /* do the 'poscall' here */
1710           int nres = ci->nresults;
1711           L->ci = ci->previous;  /* back to caller */
1712           if (nres == 0)
1713             L->top = base - 1;  /* asked for no results */
1714           else {
1715             setobjs2s(L, base - 1, ra);  /* at least this result */
1716             L->top = base;
1717             while (--nres > 0)  /* complete missing results */
1718               setnilvalue(s2v(L->top++));
1719           }
1720         }
1721        ret:  /* return from a Lua function */
1722         if (ci->callstatus & CIST_FRESH)
1723           return;  /* end this frame */
1724         else {
1725           ci = ci->previous;
1726           goto returning;  /* continue running caller in this frame */
1727         }
1728       }
1729       vmcase(OP_FORLOOP) {
1730         if (ttisinteger(s2v(ra + 2))) {  /* integer loop? */
1731           lua_Unsigned count = l_castS2U(ivalue(s2v(ra + 1)));
1732           if (count > 0) {  /* still more iterations? */
1733             lua_Integer step = ivalue(s2v(ra + 2));
1734             lua_Integer idx = ivalue(s2v(ra));  /* internal index */
1735             chgivalue(s2v(ra + 1), count - 1);  /* update counter */
1736             idx = intop(+, idx, step);  /* add step to index */
1737             chgivalue(s2v(ra), idx);  /* update internal index */
1738             setivalue(s2v(ra + 3), idx);  /* and control variable */
1739             pc -= GETARG_Bx(i);  /* jump back */
1740           }
1741         }
1742         else if (floatforloop(ra))  /* float loop */
1743           pc -= GETARG_Bx(i);  /* jump back */
1744         updatetrap(ci);  /* allows a signal to break the loop */
1745         vmbreak;
1746       }
1747       vmcase(OP_FORPREP) {
1748         savestate(L, ci);  /* in case of errors */
1749         if (forprep(L, ra))
1750           pc += GETARG_Bx(i) + 1;  /* skip the loop */
1751         vmbreak;
1752       }
1753       vmcase(OP_TFORPREP) {
1754         /* create to-be-closed upvalue (if needed) */
1755         halfProtect(luaF_newtbcupval(L, ra + 3));
1756         pc += GETARG_Bx(i);
1757         i = *(pc++);  /* go to next instruction */
1758         lua_assert(GET_OPCODE(i) == OP_TFORCALL && ra == RA(i));
1759         goto l_tforcall;
1760       }
1761       vmcase(OP_TFORCALL) {
1762        l_tforcall:
1763         /* 'ra' has the iterator function, 'ra + 1' has the state,
1764            'ra + 2' has the control variable, and 'ra + 3' has the
1765            to-be-closed variable. The call will use the stack after
1766            these values (starting at 'ra + 4')
1767         */
1768         /* push function, state, and control variable */
1769         memcpy(ra + 4, ra, 3 * sizeof(*ra));
1770         L->top = ra + 4 + 3;
1771         ProtectNT(luaD_call(L, ra + 4, GETARG_C(i)));  /* do the call */
1772         updatestack(ci);  /* stack may have changed */
1773         i = *(pc++);  /* go to next instruction */
1774         lua_assert(GET_OPCODE(i) == OP_TFORLOOP && ra == RA(i));
1775         goto l_tforloop;
1776       }
1777       vmcase(OP_TFORLOOP) {
1778         l_tforloop:
1779         if (!ttisnil(s2v(ra + 4))) {  /* continue loop? */
1780           setobjs2s(L, ra + 2, ra + 4);  /* save control variable */
1781           pc -= GETARG_Bx(i);  /* jump back */
1782         }
1783         vmbreak;
1784       }
1785       vmcase(OP_SETLIST) {
1786         int n = GETARG_B(i);
1787         unsigned int last = GETARG_C(i);
1788         Table *h = hvalue(s2v(ra));
1789         if (n == 0)
1790           n = cast_int(L->top - ra) - 1;  /* get up to the top */
1791         else
1792           L->top = ci->top;  /* correct top in case of emergency GC */
1793         last += n;
1794         if (TESTARG_k(i)) {
1795           last += GETARG_Ax(*pc) * (MAXARG_C + 1);
1796           pc++;
1797         }
1798         if (last > luaH_realasize(h))  /* needs more space? */
1799           luaH_resizearray(L, h, last);  /* preallocate it at once */
1800         for (; n > 0; n--) {
1801           TValue *val = s2v(ra + n);
1802           setobj2t(L, &h->array[last - 1], val);
1803           last--;
1804           luaC_barrierback(L, obj2gco(h), val);
1805         }
1806         vmbreak;
1807       }
1808       vmcase(OP_CLOSURE) {
1809         Proto *p = cl->p->p[GETARG_Bx(i)];
1810         halfProtect(pushclosure(L, p, cl->upvals, base, ra));
1811         checkGC(L, ra + 1);
1812         vmbreak;
1813       }
1814       vmcase(OP_VARARG) {
1815         int n = GETARG_C(i) - 1;  /* required results */
1816         Protect(luaT_getvarargs(L, ci, ra, n));
1817         vmbreak;
1818       }
1819       vmcase(OP_VARARGPREP) {
1820         ProtectNT(luaT_adjustvarargs(L, GETARG_A(i), ci, cl->p));
1821         if (trap) {
1822           luaD_hookcall(L, ci);
1823           L->oldpc = 1;  /* next opcode will be seen as a "new" line */
1824         }
1825         updatebase(ci);  /* function has new base after adjustment */
1826         vmbreak;
1827       }
1828       vmcase(OP_EXTRAARG) {
1829         lua_assert(0);
1830         vmbreak;
1831       }
1832     }
1833   }
1834 }
1835 
1836 /* }================================================================== */
1837