Merge pull request #2672 from kitsunehunter/laundry-keys
[RRG-proxmark3.git] / client / deps / liblua / lvm.c
blob3a67b28180c241a0ee1d60a50636514277c7f9e4
1 /*
2 ** $Id: lvm.c $
3 ** Lua virtual machine
4 ** See Copyright Notice in lua.h
5 */
7 #define lvm_c
8 #define LUA_CORE
10 #include "lprefix.h"
12 #include <float.h>
13 #include <limits.h>
14 #include <math.h>
15 #include <stdio.h>
16 #include <stdlib.h>
17 #include <string.h>
19 #include "lua.h"
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"
35 ** By default, use jump tables in the main interpreter loop on gcc
36 ** and compatible compilers.
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
48 /* limit for table tag-method chains (to avoid infinite loops) */
49 #define MAXTAGLOOP 2000
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.
57 /* number of bits in the mantissa of a float */
58 #define NBM (l_floatatt(MANT_DIG))
61 ** Check whether some integers may not fit in a float, testing whether
62 ** (maxinteger >> NBM) > 0. (That implies (1 << NBM) <= maxinteger.)
63 ** (The shifts are done in parts, to avoid shifting by more than the size
64 ** of an integer. In a worst case, NBM == 113 for long double and
65 ** sizeof(long) == 32.)
67 #if ((((LUA_MAXINTEGER >> (NBM / 4)) >> (NBM / 4)) >> (NBM / 4)) \
68 >> (NBM - (3 * (NBM / 4)))) > 0
70 /* limit for integers that fit in a float */
71 #define MAXINTFITSF ((lua_Unsigned)1 << NBM)
73 /* check whether 'i' is in the interval [-MAXINTFITSF, MAXINTFITSF] */
74 #define l_intfitsf(i) ((MAXINTFITSF + l_castS2U(i)) <= (2 * MAXINTFITSF))
76 #else /* all integers fit in a float precisely */
78 #define l_intfitsf(i) 1
80 #endif
84 ** Try to convert a value from string to a number value.
85 ** If the value is not a string or is a string not representing
86 ** a valid numeral (or if coercions from strings to numbers
87 ** are disabled via macro 'cvt2num'), do not modify 'result'
88 ** and return 0.
90 static int l_strton(const TValue *obj, TValue *result) {
91 lua_assert(obj != result);
92 if (!cvt2num(obj)) /* is object not a string? */
93 return 0;
94 else {
95 TString *st = tsvalue(obj);
96 return (luaO_str2num(getstr(st), result) == tsslen(st) + 1);
102 ** Try to convert a value to a float. The float case is already handled
103 ** by the macro 'tonumber'.
105 int luaV_tonumber_(const TValue *obj, lua_Number *n) {
106 TValue v;
107 if (ttisinteger(obj)) {
108 *n = cast_num(ivalue(obj));
109 return 1;
110 } else if (l_strton(obj, &v)) { /* string coercible to number? */
111 *n = nvalue(&v); /* convert result of 'luaO_str2num' to a float */
112 return 1;
113 } else
114 return 0; /* conversion failed */
119 ** try to convert a float to an integer, rounding according to 'mode'.
121 int luaV_flttointeger(lua_Number n, lua_Integer *p, F2Imod mode) {
122 lua_Number f = l_floor(n);
123 if (n != f) { /* not an integral value? */
124 if (mode == F2Ieq) return 0; /* fails if mode demands integral value */
125 else if (mode == F2Iceil) /* needs ceil? */
126 f += 1; /* convert floor to ceil (remember: n != f) */
128 return lua_numbertointeger(f, p);
133 ** try to convert a value to an integer, rounding according to 'mode',
134 ** without string coercion.
135 ** ("Fast track" handled by macro 'tointegerns'.)
137 int luaV_tointegerns(const TValue *obj, lua_Integer *p, F2Imod mode) {
138 if (ttisfloat(obj))
139 return luaV_flttointeger(fltvalue(obj), p, mode);
140 else if (ttisinteger(obj)) {
141 *p = ivalue(obj);
142 return 1;
143 } else
144 return 0;
149 ** try to convert a value to an integer.
151 int luaV_tointeger(const TValue *obj, lua_Integer *p, F2Imod mode) {
152 TValue v;
153 if (l_strton(obj, &v)) /* does 'obj' point to a numerical string? */
154 obj = &v; /* change it to point to its corresponding number */
155 return luaV_tointegerns(obj, p, mode);
160 ** Try to convert a 'for' limit to an integer, preserving the semantics
161 ** of the loop. Return true if the loop must not run; otherwise, '*p'
162 ** gets the integer limit.
163 ** (The following explanation assumes a positive step; it is valid for
164 ** negative steps mutatis mutandis.)
165 ** If the limit is an integer or can be converted to an integer,
166 ** rounding down, that is the limit.
167 ** Otherwise, check whether the limit can be converted to a float. If
168 ** the float is too large, clip it to LUA_MAXINTEGER. If the float
169 ** is too negative, the loop should not run, because any initial
170 ** integer value is greater than such limit; so, the function returns
171 ** true to signal that. (For this latter case, no integer limit would be
172 ** correct; even a limit of LUA_MININTEGER would run the loop once for
173 ** an initial value equal to LUA_MININTEGER.)
175 static int forlimit(lua_State *L, lua_Integer init, const TValue *lim,
176 lua_Integer *p, lua_Integer step) {
177 if (!luaV_tointeger(lim, p, (step < 0 ? F2Iceil : F2Ifloor))) {
178 /* not coercible to in integer */
179 lua_Number flim; /* try to convert to float */
180 if (!tonumber(lim, &flim)) /* cannot convert to float? */
181 luaG_forerror(L, lim, "limit");
182 /* else 'flim' is a float out of integer bounds */
183 if (luai_numlt(0, flim)) { /* if it is positive, it is too large */
184 if (step < 0) return 1; /* initial value must be less than it */
185 *p = LUA_MAXINTEGER; /* truncate */
186 } else { /* it is less than min integer */
187 if (step > 0) return 1; /* initial value must be greater than it */
188 *p = LUA_MININTEGER; /* truncate */
191 return (step > 0 ? init > *p : init < *p); /* not to run? */
196 ** Prepare a numerical for loop (opcode OP_FORPREP).
197 ** Return true to skip the loop. Otherwise,
198 ** after preparation, stack will be as follows:
199 ** ra : internal index (safe copy of the control variable)
200 ** ra + 1 : loop counter (integer loops) or limit (float loops)
201 ** ra + 2 : step
202 ** ra + 3 : control variable
204 static int forprep(lua_State *L, StkId ra) {
205 TValue *pinit = s2v(ra);
206 TValue *plimit = s2v(ra + 1);
207 TValue *pstep = s2v(ra + 2);
208 if (ttisinteger(pinit) && ttisinteger(pstep)) { /* integer loop? */
209 lua_Integer init = ivalue(pinit);
210 lua_Integer step = ivalue(pstep);
211 lua_Integer limit;
212 if (step == 0)
213 luaG_runerror(L, "'for' step is zero");
214 setivalue(s2v(ra + 3), init); /* control variable */
215 if (forlimit(L, init, plimit, &limit, step))
216 return 1; /* skip the loop */
217 else { /* prepare loop counter */
218 lua_Unsigned count;
219 if (step > 0) { /* ascending loop? */
220 count = l_castS2U(limit) - l_castS2U(init);
221 if (step != 1) /* avoid division in the too common case */
222 count /= l_castS2U(step);
223 } else { /* step < 0; descending loop */
224 count = l_castS2U(init) - l_castS2U(limit);
225 /* 'step+1' avoids negating 'mininteger' */
226 count /= l_castS2U(-(step + 1)) + 1u;
228 /* store the counter in place of the limit (which won't be
229 needed anymore) */
230 setivalue(plimit, l_castU2S(count));
232 } else { /* try making all values floats */
233 lua_Number init;
234 lua_Number limit;
235 lua_Number step;
236 if (l_unlikely(!tonumber(plimit, &limit)))
237 luaG_forerror(L, plimit, "limit");
238 if (l_unlikely(!tonumber(pstep, &step)))
239 luaG_forerror(L, pstep, "step");
240 if (l_unlikely(!tonumber(pinit, &init)))
241 luaG_forerror(L, pinit, "initial value");
242 if (step == 0)
243 luaG_runerror(L, "'for' step is zero");
244 if (luai_numlt(0, step) ? luai_numlt(limit, init)
245 : luai_numlt(init, limit))
246 return 1; /* skip the loop */
247 else {
248 /* make sure internal values are all floats */
249 setfltvalue(plimit, limit);
250 setfltvalue(pstep, step);
251 setfltvalue(s2v(ra), init); /* internal index */
252 setfltvalue(s2v(ra + 3), init); /* control variable */
255 return 0;
260 ** Execute a step of a float numerical for loop, returning
261 ** true iff the loop must continue. (The integer case is
262 ** written online with opcode OP_FORLOOP, for performance.)
264 static int floatforloop(StkId ra) {
265 lua_Number step = fltvalue(s2v(ra + 2));
266 lua_Number limit = fltvalue(s2v(ra + 1));
267 lua_Number idx = fltvalue(s2v(ra)); /* internal index */
268 idx = luai_numadd(L, idx, step); /* increment index */
269 if (luai_numlt(0, step) ? luai_numle(idx, limit)
270 : luai_numle(limit, idx)) {
271 chgfltvalue(s2v(ra), idx); /* update internal index */
272 setfltvalue(s2v(ra + 3), idx); /* and control variable */
273 return 1; /* jump back */
274 } else
275 return 0; /* finish the loop */
280 ** Finish the table access 'val = t[key]'.
281 ** if 'slot' is NULL, 't' is not a table; otherwise, 'slot' points to
282 ** t[k] entry (which must be empty).
284 void luaV_finishget(lua_State *L, const TValue *t, TValue *key, StkId val,
285 const TValue *slot) {
286 int loop; /* counter to avoid infinite loops */
287 const TValue *tm; /* metamethod */
288 for (loop = 0; loop < MAXTAGLOOP; loop++) {
289 if (slot == NULL) { /* 't' is not a table? */
290 lua_assert(!ttistable(t));
291 tm = luaT_gettmbyobj(L, t, TM_INDEX);
292 if (l_unlikely(notm(tm)))
293 luaG_typeerror(L, t, "index"); /* no metamethod */
294 /* else will try the metamethod */
295 } else { /* 't' is a table */
296 lua_assert(isempty(slot));
297 tm = fasttm(L, hvalue(t)->metatable, TM_INDEX); /* table's metamethod */
298 if (tm == NULL) { /* no metamethod? */
299 setnilvalue(s2v(val)); /* result is nil */
300 return;
302 /* else will try the metamethod */
304 if (ttisfunction(tm)) { /* is metamethod a function? */
305 luaT_callTMres(L, tm, t, key, val); /* call it */
306 return;
308 t = tm; /* else try to access 'tm[key]' */
309 if (luaV_fastget(L, t, key, slot, luaH_get)) { /* fast track? */
310 setobj2s(L, val, slot); /* done */
311 return;
313 /* else repeat (tail call 'luaV_finishget') */
315 luaG_runerror(L, "'__index' chain too long; possible loop");
320 ** Finish a table assignment 't[key] = val'.
321 ** If 'slot' is NULL, 't' is not a table. Otherwise, 'slot' points
322 ** to the entry 't[key]', or to a value with an absent key if there
323 ** is no such entry. (The value at 'slot' must be empty, otherwise
324 ** 'luaV_fastget' would have done the job.)
326 void luaV_finishset(lua_State *L, const TValue *t, TValue *key,
327 TValue *val, const TValue *slot) {
328 int loop; /* counter to avoid infinite loops */
329 for (loop = 0; loop < MAXTAGLOOP; loop++) {
330 const TValue *tm; /* '__newindex' metamethod */
331 if (slot != NULL) { /* is 't' a table? */
332 Table *h = hvalue(t); /* save 't' table */
333 lua_assert(isempty(slot)); /* slot must be empty */
334 tm = fasttm(L, h->metatable, TM_NEWINDEX); /* get metamethod */
335 if (tm == NULL) { /* no metamethod? */
336 luaH_finishset(L, h, key, slot, val); /* set new value */
337 invalidateTMcache(h);
338 luaC_barrierback(L, obj2gco(h), val);
339 return;
341 /* else will try the metamethod */
342 } else { /* not a table; check metamethod */
343 tm = luaT_gettmbyobj(L, t, TM_NEWINDEX);
344 if (l_unlikely(notm(tm)))
345 luaG_typeerror(L, t, "index");
347 /* try the metamethod */
348 if (ttisfunction(tm)) {
349 luaT_callTM(L, tm, t, key, val);
350 return;
352 t = tm; /* else repeat assignment over 'tm' */
353 if (luaV_fastget(L, t, key, slot, luaH_get)) {
354 luaV_finishfastset(L, t, slot, val);
355 return; /* done */
357 /* else 'return luaV_finishset(L, t, key, val, slot)' (loop) */
359 luaG_runerror(L, "'__newindex' chain too long; possible loop");
364 ** Compare two strings 'ts1' x 'ts2', returning an integer less-equal-
365 ** -greater than zero if 'ts1' is less-equal-greater than 'ts2'.
366 ** The code is a little tricky because it allows '\0' in the strings
367 ** and it uses 'strcoll' (to respect locales) for each segment
368 ** of the strings. Note that segments can compare equal but still
369 ** have different lengths.
371 static int l_strcmp(const TString *ts1, const TString *ts2) {
372 const char *s1 = getstr(ts1);
373 size_t rl1 = tsslen(ts1); /* real length */
374 const char *s2 = getstr(ts2);
375 size_t rl2 = tsslen(ts2);
376 for (;;) { /* for each segment */
377 int temp = strcoll(s1, s2);
378 if (temp != 0) /* not equal? */
379 return temp; /* done */
380 else { /* strings are equal up to a '\0' */
381 size_t zl1 = strlen(s1); /* index of first '\0' in 's1' */
382 size_t zl2 = strlen(s2); /* index of first '\0' in 's2' */
383 if (zl2 == rl2) /* 's2' is finished? */
384 return (zl1 == rl1) ? 0 : 1; /* check 's1' */
385 else if (zl1 == rl1) /* 's1' is finished? */
386 return -1; /* 's1' is less than 's2' ('s2' is not finished) */
387 /* both strings longer than 'zl'; go on comparing after the '\0' */
388 zl1++;
389 zl2++;
390 s1 += zl1;
391 rl1 -= zl1;
392 s2 += zl2;
393 rl2 -= zl2;
400 ** Check whether integer 'i' is less than float 'f'. If 'i' has an
401 ** exact representation as a float ('l_intfitsf'), compare numbers as
402 ** floats. Otherwise, use the equivalence 'i < f <=> i < ceil(f)'.
403 ** If 'ceil(f)' is out of integer range, either 'f' is greater than
404 ** all integers or less than all integers.
405 ** (The test with 'l_intfitsf' is only for performance; the else
406 ** case is correct for all values, but it is slow due to the conversion
407 ** from float to int.)
408 ** When 'f' is NaN, comparisons must result in false.
410 l_sinline int LTintfloat(lua_Integer i, lua_Number f) {
411 if (l_intfitsf(i))
412 return luai_numlt(cast_num(i), f); /* compare them as floats */
413 else { /* i < f <=> i < ceil(f) */
414 lua_Integer fi;
415 if (luaV_flttointeger(f, &fi, F2Iceil)) /* fi = ceil(f) */
416 return i < fi; /* compare them as integers */
417 else /* 'f' is either greater or less than all integers */
418 return f > 0; /* greater? */
424 ** Check whether integer 'i' is less than or equal to float 'f'.
425 ** See comments on previous function.
427 l_sinline int LEintfloat(lua_Integer i, lua_Number f) {
428 if (l_intfitsf(i))
429 return luai_numle(cast_num(i), f); /* compare them as floats */
430 else { /* i <= f <=> i <= floor(f) */
431 lua_Integer fi;
432 if (luaV_flttointeger(f, &fi, F2Ifloor)) /* fi = floor(f) */
433 return i <= fi; /* compare them as integers */
434 else /* 'f' is either greater or less than all integers */
435 return f > 0; /* greater? */
441 ** Check whether float 'f' is less than integer 'i'.
442 ** See comments on previous function.
444 l_sinline int LTfloatint(lua_Number f, lua_Integer i) {
445 if (l_intfitsf(i))
446 return luai_numlt(f, cast_num(i)); /* compare them as floats */
447 else { /* f < i <=> floor(f) < i */
448 lua_Integer fi;
449 if (luaV_flttointeger(f, &fi, F2Ifloor)) /* fi = floor(f) */
450 return fi < i; /* compare them as integers */
451 else /* 'f' is either greater or less than all integers */
452 return f < 0; /* less? */
458 ** Check whether float 'f' is less than or equal to integer 'i'.
459 ** See comments on previous function.
461 l_sinline int LEfloatint(lua_Number f, lua_Integer i) {
462 if (l_intfitsf(i))
463 return luai_numle(f, cast_num(i)); /* compare them as floats */
464 else { /* f <= i <=> ceil(f) <= i */
465 lua_Integer fi;
466 if (luaV_flttointeger(f, &fi, F2Iceil)) /* fi = ceil(f) */
467 return fi <= i; /* compare them as integers */
468 else /* 'f' is either greater or less than all integers */
469 return f < 0; /* less? */
475 ** Return 'l < r', for numbers.
477 l_sinline int LTnum(const TValue *l, const TValue *r) {
478 lua_assert(ttisnumber(l) && ttisnumber(r));
479 if (ttisinteger(l)) {
480 lua_Integer li = ivalue(l);
481 if (ttisinteger(r))
482 return li < ivalue(r); /* both are integers */
483 else /* 'l' is int and 'r' is float */
484 return LTintfloat(li, fltvalue(r)); /* l < r ? */
485 } else {
486 lua_Number lf = fltvalue(l); /* 'l' must be float */
487 if (ttisfloat(r))
488 return luai_numlt(lf, fltvalue(r)); /* both are float */
489 else /* 'l' is float and 'r' is int */
490 return LTfloatint(lf, ivalue(r));
496 ** Return 'l <= r', for numbers.
498 l_sinline int LEnum(const TValue *l, const TValue *r) {
499 lua_assert(ttisnumber(l) && ttisnumber(r));
500 if (ttisinteger(l)) {
501 lua_Integer li = ivalue(l);
502 if (ttisinteger(r))
503 return li <= ivalue(r); /* both are integers */
504 else /* 'l' is int and 'r' is float */
505 return LEintfloat(li, fltvalue(r)); /* l <= r ? */
506 } else {
507 lua_Number lf = fltvalue(l); /* 'l' must be float */
508 if (ttisfloat(r))
509 return luai_numle(lf, fltvalue(r)); /* both are float */
510 else /* 'l' is float and 'r' is int */
511 return LEfloatint(lf, ivalue(r));
517 ** return 'l < r' for non-numbers.
519 static int lessthanothers(lua_State *L, const TValue *l, const TValue *r) {
520 lua_assert(!ttisnumber(l) || !ttisnumber(r));
521 if (ttisstring(l) && ttisstring(r)) /* both are strings? */
522 return l_strcmp(tsvalue(l), tsvalue(r)) < 0;
523 else
524 return luaT_callorderTM(L, l, r, TM_LT);
529 ** Main operation less than; return 'l < r'.
531 int luaV_lessthan(lua_State *L, const TValue *l, const TValue *r) {
532 if (ttisnumber(l) && ttisnumber(r)) /* both operands are numbers? */
533 return LTnum(l, r);
534 else return lessthanothers(L, l, r);
539 ** return 'l <= r' for non-numbers.
541 static int lessequalothers(lua_State *L, const TValue *l, const TValue *r) {
542 lua_assert(!ttisnumber(l) || !ttisnumber(r));
543 if (ttisstring(l) && ttisstring(r)) /* both are strings? */
544 return l_strcmp(tsvalue(l), tsvalue(r)) <= 0;
545 else
546 return luaT_callorderTM(L, l, r, TM_LE);
551 ** Main operation less than or equal to; return 'l <= r'.
553 int luaV_lessequal(lua_State *L, const TValue *l, const TValue *r) {
554 if (ttisnumber(l) && ttisnumber(r)) /* both operands are numbers? */
555 return LEnum(l, r);
556 else return lessequalothers(L, l, r);
561 ** Main operation for equality of Lua values; return 't1 == t2'.
562 ** L == NULL means raw equality (no metamethods)
564 int luaV_equalobj(lua_State *L, const TValue *t1, const TValue *t2) {
565 const TValue *tm;
566 if (ttypetag(t1) != ttypetag(t2)) { /* not the same variant? */
567 if (ttype(t1) != ttype(t2) || ttype(t1) != LUA_TNUMBER)
568 return 0; /* only numbers can be equal with different variants */
569 else { /* two numbers with different variants */
570 /* One of them is an integer. If the other does not have an
571 integer value, they cannot be equal; otherwise, compare their
572 integer values. */
573 lua_Integer i1, i2;
574 return (luaV_tointegerns(t1, &i1, F2Ieq) &&
575 luaV_tointegerns(t2, &i2, F2Ieq) &&
576 i1 == i2);
579 /* values have same type and same variant */
580 switch (ttypetag(t1)) {
581 case LUA_VNIL:
582 case LUA_VFALSE:
583 case LUA_VTRUE:
584 return 1;
585 case LUA_VNUMINT:
586 return (ivalue(t1) == ivalue(t2));
587 case LUA_VNUMFLT:
588 return luai_numeq(fltvalue(t1), fltvalue(t2));
589 case LUA_VLIGHTUSERDATA:
590 return pvalue(t1) == pvalue(t2);
591 case LUA_VLCF:
592 return fvalue(t1) == fvalue(t2);
593 case LUA_VSHRSTR:
594 return eqshrstr(tsvalue(t1), tsvalue(t2));
595 case LUA_VLNGSTR:
596 return luaS_eqlngstr(tsvalue(t1), tsvalue(t2));
597 case LUA_VUSERDATA: {
598 if (uvalue(t1) == uvalue(t2)) return 1;
599 else if (L == NULL) return 0;
600 tm = fasttm(L, uvalue(t1)->metatable, TM_EQ);
601 if (tm == NULL)
602 tm = fasttm(L, uvalue(t2)->metatable, TM_EQ);
603 break; /* will try TM */
605 case LUA_VTABLE: {
606 if (hvalue(t1) == hvalue(t2)) return 1;
607 else if (L == NULL) return 0;
608 tm = fasttm(L, hvalue(t1)->metatable, TM_EQ);
609 if (tm == NULL)
610 tm = fasttm(L, hvalue(t2)->metatable, TM_EQ);
611 break; /* will try TM */
613 default:
614 return gcvalue(t1) == gcvalue(t2);
616 if (tm == NULL) /* no TM? */
617 return 0; /* objects are different */
618 else {
619 luaT_callTMres(L, tm, t1, t2, L->top.p); /* call TM */
620 return !l_isfalse(s2v(L->top.p));
625 /* macro used by 'luaV_concat' to ensure that element at 'o' is a string */
626 #define tostring(L,o) \
627 (ttisstring(o) || (cvt2str(o) && (luaO_tostring(L, o), 1)))
629 #define isemptystr(o) (ttisshrstring(o) && tsvalue(o)->shrlen == 0)
631 /* copy strings in stack from top - n up to top - 1 to buffer */
632 static void copy2buff(StkId top, int n, char *buff) {
633 size_t tl = 0; /* size already copied */
634 do {
635 TString *st = tsvalue(s2v(top - n));
636 size_t l = tsslen(st); /* length of string being copied */
637 memcpy(buff + tl, getstr(st), l * sizeof(char));
638 tl += l;
639 } while (--n > 0);
644 ** Main operation for concatenation: concat 'total' values in the stack,
645 ** from 'L->top.p - total' up to 'L->top.p - 1'.
647 void luaV_concat(lua_State *L, int total) {
648 if (total == 1)
649 return; /* "all" values already concatenated */
650 do {
651 StkId top = L->top.p;
652 int n = 2; /* number of elements handled in this pass (at least 2) */
653 if (!(ttisstring(s2v(top - 2)) || cvt2str(s2v(top - 2))) ||
654 !tostring(L, s2v(top - 1)))
655 luaT_tryconcatTM(L); /* may invalidate 'top' */
656 else if (isemptystr(s2v(top - 1))) /* second operand is empty? */
657 cast_void(tostring(L, s2v(top - 2))); /* result is first operand */
658 else if (isemptystr(s2v(top - 2))) { /* first operand is empty string? */
659 setobjs2s(L, top - 2, top - 1); /* result is second op. */
660 } else {
661 /* at least two non-empty string values; get as many as possible */
662 size_t tl = tsslen(tsvalue(s2v(top - 1)));
663 TString *ts;
664 /* collect total length and number of strings */
665 for (n = 1; n < total && tostring(L, s2v(top - n - 1)); n++) {
666 size_t l = tsslen(tsvalue(s2v(top - n - 1)));
667 if (l_unlikely(l >= MAX_SIZE - sizeof(TString) - tl)) {
668 L->top.p = top - total; /* pop strings to avoid wasting stack */
669 luaG_runerror(L, "string length overflow");
671 tl += l;
673 if (tl <= LUAI_MAXSHORTLEN) { /* is result a short string? */
674 char buff[LUAI_MAXSHORTLEN];
675 copy2buff(top, n, buff); /* copy strings to buffer */
676 ts = luaS_newlstr(L, buff, tl);
677 } else { /* long string; copy strings directly to final result */
678 ts = luaS_createlngstrobj(L, tl);
679 copy2buff(top, n, getlngstr(ts));
681 setsvalue2s(L, top - n, ts); /* create result */
683 total -= n - 1; /* got 'n' strings to create one new */
684 L->top.p -= n - 1; /* popped 'n' strings and pushed one */
685 } while (total > 1); /* repeat until only 1 result left */
690 ** Main operation 'ra = #rb'.
692 void luaV_objlen(lua_State *L, StkId ra, const TValue *rb) {
693 const TValue *tm;
694 switch (ttypetag(rb)) {
695 case LUA_VTABLE: {
696 Table *h = hvalue(rb);
697 tm = fasttm(L, h->metatable, TM_LEN);
698 if (tm) break; /* metamethod? break switch to call it */
699 setivalue(s2v(ra), luaH_getn(h)); /* else primitive len */
700 return;
702 case LUA_VSHRSTR: {
703 setivalue(s2v(ra), tsvalue(rb)->shrlen);
704 return;
706 case LUA_VLNGSTR: {
707 setivalue(s2v(ra), tsvalue(rb)->u.lnglen);
708 return;
710 default: { /* try metamethod */
711 tm = luaT_gettmbyobj(L, rb, TM_LEN);
712 if (l_unlikely(notm(tm))) /* no metamethod? */
713 luaG_typeerror(L, rb, "get length of");
714 break;
717 luaT_callTMres(L, tm, rb, rb, ra);
722 ** Integer division; return 'm // n', that is, floor(m/n).
723 ** C division truncates its result (rounds towards zero).
724 ** 'floor(q) == trunc(q)' when 'q >= 0' or when 'q' is integer,
725 ** otherwise 'floor(q) == trunc(q) - 1'.
727 lua_Integer luaV_idiv(lua_State *L, lua_Integer m, lua_Integer n) {
728 if (l_unlikely(l_castS2U(n) + 1u <= 1u)) { /* special cases: -1 or 0 */
729 if (n == 0)
730 luaG_runerror(L, "attempt to divide by zero");
731 return intop(-, 0, m); /* n==-1; avoid overflow with 0x80000...//-1 */
732 } else {
733 lua_Integer q = m / n; /* perform C division */
734 if ((m ^ n) < 0 && m % n != 0) /* 'm/n' would be negative non-integer? */
735 q -= 1; /* correct result for different rounding */
736 return q;
742 ** Integer modulus; return 'm % n'. (Assume that C '%' with
743 ** negative operands follows C99 behavior. See previous comment
744 ** about luaV_idiv.)
746 lua_Integer luaV_mod(lua_State *L, lua_Integer m, lua_Integer n) {
747 if (l_unlikely(l_castS2U(n) + 1u <= 1u)) { /* special cases: -1 or 0 */
748 if (n == 0)
749 luaG_runerror(L, "attempt to perform 'n%%0'");
750 return 0; /* m % -1 == 0; avoid overflow with 0x80000...%-1 */
751 } else {
752 lua_Integer r = m % n;
753 if (r != 0 && (r ^ n) < 0) /* 'm/n' would be non-integer negative? */
754 r += n; /* correct result for different rounding */
755 return r;
761 ** Float modulus
763 lua_Number luaV_modf(lua_State *L, lua_Number m, lua_Number n) {
764 lua_Number r;
765 luai_nummod(L, m, n, r);
766 return r;
770 /* number of bits in an integer */
771 #define NBITS cast_int(sizeof(lua_Integer) * CHAR_BIT)
775 ** Shift left operation. (Shift right just negates 'y'.)
777 lua_Integer luaV_shiftl(lua_Integer x, lua_Integer y) {
778 if (y < 0) { /* shift right? */
779 if (y <= -NBITS) return 0;
780 else return intop( >>, x, -y);
781 } else { /* shift left */
782 if (y >= NBITS) return 0;
783 else return intop( <<, x, y);
789 ** create a new Lua closure, push it in the stack, and initialize
790 ** its upvalues.
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]);
811 ** finish execution of an opcode interrupted by a yield
813 void luaV_finishOp(lua_State *L) {
814 CallInfo *ci = L->ci;
815 StkId base = ci->func.p + 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:
820 case OP_MMBINI:
821 case OP_MMBINK: {
822 setobjs2s(L, base + GETARG_A(*(ci->u.l.savedpc - 2)), --L->top.p);
823 break;
825 case OP_UNM:
826 case OP_BNOT:
827 case OP_LEN:
828 case OP_GETTABUP:
829 case OP_GETTABLE:
830 case OP_GETI:
831 case OP_GETFIELD:
832 case OP_SELF: {
833 setobjs2s(L, base + GETARG_A(inst), --L->top.p);
834 break;
836 case OP_LT:
837 case OP_LE:
838 case OP_LTI:
839 case OP_LEI:
840 case OP_GTI:
841 case OP_GEI:
842 case OP_EQ: { /* note that 'OP_EQI'/'OP_EQK' cannot yield */
843 int res = !l_isfalse(s2v(L->top.p - 1));
844 L->top.p--;
845 #if defined(LUA_COMPAT_LT_LE)
846 if (ci->callstatus & CIST_LEQ) { /* "<=" using "<" instead? */
847 ci->callstatus ^= CIST_LEQ; /* clear mark */
848 res = !res; /* negate result */
850 #endif
851 lua_assert(GET_OPCODE(*ci->u.l.savedpc) == OP_JMP);
852 if (res != GETARG_k(inst)) /* condition failed? */
853 ci->u.l.savedpc++; /* skip jump instruction */
854 break;
856 case OP_CONCAT: {
857 StkId top = L->top.p - 1; /* top when 'luaT_tryconcatTM' was called */
858 int a = GETARG_A(inst); /* first element to concatenate */
859 int total = cast_int(top - 1 - (base + a)); /* yet to concatenate */
860 setobjs2s(L, top - 2, top); /* put TM result in proper position */
861 L->top.p = top - 1; /* top is one after last element (at top-2) */
862 luaV_concat(L, total); /* concat them (may yield again) */
863 break;
865 case OP_CLOSE: { /* yielded closing variables */
866 ci->u.l.savedpc--; /* repeat instruction to close other vars. */
867 break;
869 case OP_RETURN: { /* yielded closing variables */
870 StkId ra = base + GETARG_A(inst);
871 /* adjust top to signal correct number of returns, in case the
872 return is "up to top" ('isIT') */
873 L->top.p = ra + ci->u2.nres;
874 /* repeat instruction to close other vars. and complete the return */
875 ci->u.l.savedpc--;
876 break;
878 default: {
879 /* only these other opcodes can yield */
880 lua_assert(op == OP_TFORCALL || op == OP_CALL ||
881 op == OP_TAILCALL || op == OP_SETTABUP || op == OP_SETTABLE ||
882 op == OP_SETI || op == OP_SETFIELD);
883 break;
892 ** {==================================================================
893 ** Macros for arithmetic/bitwise/comparison opcodes in 'luaV_execute'
894 ** ===================================================================
897 #define l_addi(L,a,b) intop(+, a, b)
898 #define l_subi(L,a,b) intop(-, a, b)
899 #define l_muli(L,a,b) intop(*, a, b)
900 #define l_band(a,b) intop(&, a, b)
901 #define l_bor(a,b) intop(|, a, b)
902 #define l_bxor(a,b) intop(^, a, b)
904 #define l_lti(a,b) (a < b)
905 #define l_lei(a,b) (a <= b)
906 #define l_gti(a,b) (a > b)
907 #define l_gei(a,b) (a >= b)
911 ** Arithmetic operations with immediate operands. 'iop' is the integer
912 ** operation, 'fop' is the float operation.
914 #define op_arithI(L,iop,fop) { \
915 StkId ra = RA(i); \
916 TValue *v1 = vRB(i); \
917 int imm = GETARG_sC(i); \
918 if (ttisinteger(v1)) { \
919 lua_Integer iv1 = ivalue(v1); \
920 pc++; setivalue(s2v(ra), iop(L, iv1, imm)); \
922 else if (ttisfloat(v1)) { \
923 lua_Number nb = fltvalue(v1); \
924 lua_Number fimm = cast_num(imm); \
925 pc++; setfltvalue(s2v(ra), fop(L, nb, fimm)); \
930 ** Auxiliary function for arithmetic operations over floats and others
931 ** with two register operands.
933 #define op_arithf_aux(L,v1,v2,fop) { \
934 lua_Number n1; lua_Number n2; \
935 if (tonumberns(v1, n1) && tonumberns(v2, n2)) { \
936 pc++; setfltvalue(s2v(ra), fop(L, n1, n2)); \
941 ** Arithmetic operations over floats and others with register operands.
943 #define op_arithf(L,fop) { \
944 StkId ra = RA(i); \
945 TValue *v1 = vRB(i); \
946 TValue *v2 = vRC(i); \
947 op_arithf_aux(L, v1, v2, fop); }
951 ** Arithmetic operations with K operands for floats.
953 #define op_arithfK(L,fop) { \
954 StkId ra = RA(i); \
955 TValue *v1 = vRB(i); \
956 TValue *v2 = KC(i); lua_assert(ttisnumber(v2)); \
957 op_arithf_aux(L, v1, v2, fop); }
961 ** Arithmetic operations over integers and floats.
963 #define op_arith_aux(L,v1,v2,iop,fop) { \
964 StkId ra = RA(i); \
965 if (ttisinteger(v1) && ttisinteger(v2)) { \
966 lua_Integer i1 = ivalue(v1); lua_Integer i2 = ivalue(v2); \
967 pc++; setivalue(s2v(ra), iop(L, i1, i2)); \
969 else op_arithf_aux(L, v1, v2, fop); }
973 ** Arithmetic operations with register operands.
975 #define op_arith(L,iop,fop) { \
976 TValue *v1 = vRB(i); \
977 TValue *v2 = vRC(i); \
978 op_arith_aux(L, v1, v2, iop, fop); }
982 ** Arithmetic operations with K operands.
984 #define op_arithK(L,iop,fop) { \
985 TValue *v1 = vRB(i); \
986 TValue *v2 = KC(i); lua_assert(ttisnumber(v2)); \
987 op_arith_aux(L, v1, v2, iop, fop); }
991 ** Bitwise operations with constant operand.
993 #define op_bitwiseK(L,op) { \
994 StkId ra = RA(i); \
995 TValue *v1 = vRB(i); \
996 TValue *v2 = KC(i); \
997 lua_Integer i1; \
998 lua_Integer i2 = ivalue(v2); \
999 if (tointegerns(v1, &i1)) { \
1000 pc++; setivalue(s2v(ra), op(i1, i2)); \
1005 ** Bitwise operations with register operands.
1007 #define op_bitwise(L,op) { \
1008 StkId ra = RA(i); \
1009 TValue *v1 = vRB(i); \
1010 TValue *v2 = vRC(i); \
1011 lua_Integer i1; lua_Integer i2; \
1012 if (tointegerns(v1, &i1) && tointegerns(v2, &i2)) { \
1013 pc++; setivalue(s2v(ra), op(i1, i2)); \
1018 ** Order operations with register operands. 'opn' actually works
1019 ** for all numbers, but the fast track improves performance for
1020 ** integers.
1022 #define op_order(L,opi,opn,other) { \
1023 StkId ra = RA(i); \
1024 int cond; \
1025 TValue *rb = vRB(i); \
1026 if (ttisinteger(s2v(ra)) && ttisinteger(rb)) { \
1027 lua_Integer ia = ivalue(s2v(ra)); \
1028 lua_Integer ib = ivalue(rb); \
1029 cond = opi(ia, ib); \
1031 else if (ttisnumber(s2v(ra)) && ttisnumber(rb)) \
1032 cond = opn(s2v(ra), rb); \
1033 else \
1034 Protect(cond = other(L, s2v(ra), rb)); \
1035 docondjump(); }
1039 ** Order operations with immediate operand. (Immediate operand is
1040 ** always small enough to have an exact representation as a float.)
1042 #define op_orderI(L,opi,opf,inv,tm) { \
1043 StkId ra = RA(i); \
1044 int cond; \
1045 int im = GETARG_sB(i); \
1046 if (ttisinteger(s2v(ra))) \
1047 cond = opi(ivalue(s2v(ra)), im); \
1048 else if (ttisfloat(s2v(ra))) { \
1049 lua_Number fa = fltvalue(s2v(ra)); \
1050 lua_Number fim = cast_num(im); \
1051 cond = opf(fa, fim); \
1053 else { \
1054 int isf = GETARG_C(i); \
1055 Protect(cond = luaT_callorderiTM(L, s2v(ra), im, inv, isf, tm)); \
1057 docondjump(); }
1059 /* }================================================================== */
1063 ** {==================================================================
1064 ** Function 'luaV_execute': main interpreter loop
1065 ** ===================================================================
1069 ** some macros for common tasks in 'luaV_execute'
1073 #define RA(i) (base+GETARG_A(i))
1074 #define RB(i) (base+GETARG_B(i))
1075 #define vRB(i) s2v(RB(i))
1076 #define KB(i) (k+GETARG_B(i))
1077 #define RC(i) (base+GETARG_C(i))
1078 #define vRC(i) s2v(RC(i))
1079 #define KC(i) (k+GETARG_C(i))
1080 #define RKC(i) ((TESTARG_k(i)) ? k + GETARG_C(i) : s2v(base + GETARG_C(i)))
1084 #define updatetrap(ci) (trap = ci->u.l.trap)
1086 #define updatebase(ci) (base = ci->func.p + 1)
1089 #define updatestack(ci) \
1090 { if (l_unlikely(trap)) { updatebase(ci); ra = RA(i); } }
1094 ** Execute a jump instruction. The 'updatetrap' allows signals to stop
1095 ** tight loops. (Without it, the local copy of 'trap' could never change.)
1097 #define dojump(ci,i,e) { pc += GETARG_sJ(i) + e; updatetrap(ci); }
1100 /* for test instructions, execute the jump instruction that follows it */
1101 #define donextjump(ci) { Instruction ni = *pc; dojump(ci, ni, 1); }
1104 ** do a conditional jump: skip next instruction if 'cond' is not what
1105 ** was expected (parameter 'k'), else do next instruction, which must
1106 ** be a jump.
1108 #define docondjump() if (cond != GETARG_k(i)) pc++; else donextjump(ci);
1112 ** Correct global 'pc'.
1114 #define savepc(L) (ci->u.l.savedpc = pc)
1118 ** Whenever code can raise errors, the global 'pc' and the global
1119 ** 'top' must be correct to report occasional errors.
1121 #define savestate(L,ci) (savepc(L), L->top.p = ci->top.p)
1125 ** Protect code that, in general, can raise errors, reallocate the
1126 ** stack, and change the hooks.
1128 #define Protect(exp) (savestate(L,ci), (exp), updatetrap(ci))
1130 /* special version that does not change the top */
1131 #define ProtectNT(exp) (savepc(L), (exp), updatetrap(ci))
1134 ** Protect code that can only raise errors. (That is, it cannot change
1135 ** the stack or hooks.)
1137 #define halfProtect(exp) (savestate(L,ci), (exp))
1139 /* 'c' is the limit of live values in the stack */
1140 #define checkGC(L,c) \
1141 { luaC_condGC(L, (savepc(L), L->top.p = (c)), \
1142 updatetrap(ci)); \
1143 luai_threadyield(L); }
1146 /* fetch an instruction and prepare its execution */
1147 #define vmfetch() { \
1148 if (l_unlikely(trap)) { /* stack reallocation or hooks? */ \
1149 trap = luaG_traceexec(L, pc); /* handle hooks */ \
1150 updatebase(ci); /* correct stack */ \
1152 i = *(pc++); \
1155 #define vmdispatch(o) switch(o)
1156 #define vmcase(l) case l:
1157 #define vmbreak break
1160 void luaV_execute(lua_State *L, CallInfo *ci) {
1161 LClosure *cl;
1162 TValue *k;
1163 StkId base;
1164 const Instruction *pc;
1165 int trap;
1166 #if LUA_USE_JUMPTABLE
1167 #include "ljumptab.h"
1168 #endif
1169 startfunc:
1170 trap = L->hookmask;
1171 returning: /* trap already set */
1172 cl = ci_func(ci);
1173 k = cl->p->k;
1174 pc = ci->u.l.savedpc;
1175 if (l_unlikely(trap))
1176 trap = luaG_tracecall(L);
1177 base = ci->func.p + 1;
1178 /* main loop of interpreter */
1179 for (;;) {
1180 Instruction i; /* instruction being executed */
1181 vmfetch();
1182 #if 0
1183 /* low-level line tracing for debugging Lua */
1184 printf("line: %d\n", luaG_getfuncline(cl->p, pcRel(pc, cl->p)));
1185 #endif
1186 lua_assert(base == ci->func.p + 1);
1187 lua_assert(base <= L->top.p && L->top.p <= L->stack_last.p);
1188 /* invalidate top for instructions not expecting it */
1189 lua_assert(isIT(i) || (cast_void(L->top.p = base), 1));
1190 vmdispatch(GET_OPCODE(i)) {
1191 vmcase(OP_MOVE) {
1192 StkId ra = RA(i);
1193 setobjs2s(L, ra, RB(i));
1194 vmbreak;
1196 vmcase(OP_LOADI) {
1197 StkId ra = RA(i);
1198 lua_Integer b = GETARG_sBx(i);
1199 setivalue(s2v(ra), b);
1200 vmbreak;
1202 vmcase(OP_LOADF) {
1203 StkId ra = RA(i);
1204 int b = GETARG_sBx(i);
1205 setfltvalue(s2v(ra), cast_num(b));
1206 vmbreak;
1208 vmcase(OP_LOADK) {
1209 StkId ra = RA(i);
1210 TValue *rb = k + GETARG_Bx(i);
1211 setobj2s(L, ra, rb);
1212 vmbreak;
1214 vmcase(OP_LOADKX) {
1215 StkId ra = RA(i);
1216 TValue *rb;
1217 rb = k + GETARG_Ax(*pc);
1218 pc++;
1219 setobj2s(L, ra, rb);
1220 vmbreak;
1222 vmcase(OP_LOADFALSE) {
1223 StkId ra = RA(i);
1224 setbfvalue(s2v(ra));
1225 vmbreak;
1227 vmcase(OP_LFALSESKIP) {
1228 StkId ra = RA(i);
1229 setbfvalue(s2v(ra));
1230 pc++; /* skip next instruction */
1231 vmbreak;
1233 vmcase(OP_LOADTRUE) {
1234 StkId ra = RA(i);
1235 setbtvalue(s2v(ra));
1236 vmbreak;
1238 vmcase(OP_LOADNIL) {
1239 StkId ra = RA(i);
1240 int b = GETARG_B(i);
1241 do {
1242 setnilvalue(s2v(ra++));
1243 } while (b--);
1244 vmbreak;
1246 vmcase(OP_GETUPVAL) {
1247 StkId ra = RA(i);
1248 int b = GETARG_B(i);
1249 setobj2s(L, ra, cl->upvals[b]->v.p);
1250 vmbreak;
1252 vmcase(OP_SETUPVAL) {
1253 StkId ra = RA(i);
1254 UpVal *uv = cl->upvals[GETARG_B(i)];
1255 setobj(L, uv->v.p, s2v(ra));
1256 luaC_barrier(L, uv, s2v(ra));
1257 vmbreak;
1259 vmcase(OP_GETTABUP) {
1260 StkId ra = RA(i);
1261 const TValue *slot;
1262 TValue *upval = cl->upvals[GETARG_B(i)]->v.p;
1263 TValue *rc = KC(i);
1264 TString *key = tsvalue(rc); /* key must be a short string */
1265 if (luaV_fastget(L, upval, key, slot, luaH_getshortstr)) {
1266 setobj2s(L, ra, slot);
1267 } else
1268 Protect(luaV_finishget(L, upval, rc, ra, slot));
1269 vmbreak;
1271 vmcase(OP_GETTABLE) {
1272 StkId ra = RA(i);
1273 const TValue *slot;
1274 TValue *rb = vRB(i);
1275 TValue *rc = vRC(i);
1276 lua_Unsigned n;
1277 if (ttisinteger(rc) /* fast track for integers? */
1278 ? (cast_void(n = ivalue(rc)), luaV_fastgeti(L, rb, n, slot))
1279 : luaV_fastget(L, rb, rc, slot, luaH_get)) {
1280 setobj2s(L, ra, slot);
1281 } else
1282 Protect(luaV_finishget(L, rb, rc, ra, slot));
1283 vmbreak;
1285 vmcase(OP_GETI) {
1286 StkId ra = RA(i);
1287 const TValue *slot;
1288 TValue *rb = vRB(i);
1289 int c = GETARG_C(i);
1290 if (luaV_fastgeti(L, rb, c, slot)) {
1291 setobj2s(L, ra, slot);
1292 } else {
1293 TValue key;
1294 setivalue(&key, c);
1295 Protect(luaV_finishget(L, rb, &key, ra, slot));
1297 vmbreak;
1299 vmcase(OP_GETFIELD) {
1300 StkId ra = RA(i);
1301 const TValue *slot;
1302 TValue *rb = vRB(i);
1303 TValue *rc = KC(i);
1304 TString *key = tsvalue(rc); /* key must be a short string */
1305 if (luaV_fastget(L, rb, key, slot, luaH_getshortstr)) {
1306 setobj2s(L, ra, slot);
1307 } else
1308 Protect(luaV_finishget(L, rb, rc, ra, slot));
1309 vmbreak;
1311 vmcase(OP_SETTABUP) {
1312 const TValue *slot;
1313 TValue *upval = cl->upvals[GETARG_A(i)]->v.p;
1314 TValue *rb = KB(i);
1315 TValue *rc = RKC(i);
1316 TString *key = tsvalue(rb); /* key must be a short string */
1317 if (luaV_fastget(L, upval, key, slot, luaH_getshortstr)) {
1318 luaV_finishfastset(L, upval, slot, rc);
1319 } else
1320 Protect(luaV_finishset(L, upval, rb, rc, slot));
1321 vmbreak;
1323 vmcase(OP_SETTABLE) {
1324 StkId ra = RA(i);
1325 const TValue *slot;
1326 TValue *rb = vRB(i); /* key (table is in 'ra') */
1327 TValue *rc = RKC(i); /* value */
1328 lua_Unsigned n;
1329 if (ttisinteger(rb) /* fast track for integers? */
1330 ? (cast_void(n = ivalue(rb)), luaV_fastgeti(L, s2v(ra), n, slot))
1331 : luaV_fastget(L, s2v(ra), rb, slot, luaH_get)) {
1332 luaV_finishfastset(L, s2v(ra), slot, rc);
1333 } else
1334 Protect(luaV_finishset(L, s2v(ra), rb, rc, slot));
1335 vmbreak;
1337 vmcase(OP_SETI) {
1338 StkId ra = RA(i);
1339 const TValue *slot;
1340 int c = GETARG_B(i);
1341 TValue *rc = RKC(i);
1342 if (luaV_fastgeti(L, s2v(ra), c, slot)) {
1343 luaV_finishfastset(L, s2v(ra), slot, rc);
1344 } else {
1345 TValue key;
1346 setivalue(&key, c);
1347 Protect(luaV_finishset(L, s2v(ra), &key, rc, slot));
1349 vmbreak;
1351 vmcase(OP_SETFIELD) {
1352 StkId ra = RA(i);
1353 const TValue *slot;
1354 TValue *rb = KB(i);
1355 TValue *rc = RKC(i);
1356 TString *key = tsvalue(rb); /* key must be a short string */
1357 if (luaV_fastget(L, s2v(ra), key, slot, luaH_getshortstr)) {
1358 luaV_finishfastset(L, s2v(ra), slot, rc);
1359 } else
1360 Protect(luaV_finishset(L, s2v(ra), rb, rc, slot));
1361 vmbreak;
1363 vmcase(OP_NEWTABLE) {
1364 StkId ra = RA(i);
1365 int b = GETARG_B(i); /* log2(hash size) + 1 */
1366 int c = GETARG_C(i); /* array size */
1367 Table *t;
1368 if (b > 0)
1369 b = 1 << (b - 1); /* size is 2^(b - 1) */
1370 lua_assert((!TESTARG_k(i)) == (GETARG_Ax(*pc) == 0));
1371 if (TESTARG_k(i)) /* non-zero extra argument? */
1372 c += GETARG_Ax(*pc) * (MAXARG_C + 1); /* add it to size */
1373 pc++; /* skip extra argument */
1374 L->top.p = ra + 1; /* correct top in case of emergency GC */
1375 t = luaH_new(L); /* memory allocation */
1376 sethvalue2s(L, ra, t);
1377 if (b != 0 || c != 0)
1378 luaH_resize(L, t, c, b); /* idem */
1379 checkGC(L, ra + 1);
1380 vmbreak;
1382 vmcase(OP_SELF) {
1383 StkId ra = RA(i);
1384 const TValue *slot;
1385 TValue *rb = vRB(i);
1386 TValue *rc = RKC(i);
1387 TString *key = tsvalue(rc); /* key must be a string */
1388 setobj2s(L, ra + 1, rb);
1389 if (luaV_fastget(L, rb, key, slot, luaH_getstr)) {
1390 setobj2s(L, ra, slot);
1391 } else
1392 Protect(luaV_finishget(L, rb, rc, ra, slot));
1393 vmbreak;
1395 vmcase(OP_ADDI) {
1396 op_arithI(L, l_addi, luai_numadd);
1397 vmbreak;
1399 vmcase(OP_ADDK) {
1400 op_arithK(L, l_addi, luai_numadd);
1401 vmbreak;
1403 vmcase(OP_SUBK) {
1404 op_arithK(L, l_subi, luai_numsub);
1405 vmbreak;
1407 vmcase(OP_MULK) {
1408 op_arithK(L, l_muli, luai_nummul);
1409 vmbreak;
1411 vmcase(OP_MODK) {
1412 savestate(L, ci); /* in case of division by 0 */
1413 op_arithK(L, luaV_mod, luaV_modf);
1414 vmbreak;
1416 vmcase(OP_POWK) {
1417 op_arithfK(L, luai_numpow);
1418 vmbreak;
1420 vmcase(OP_DIVK) {
1421 op_arithfK(L, luai_numdiv);
1422 vmbreak;
1424 vmcase(OP_IDIVK) {
1425 savestate(L, ci); /* in case of division by 0 */
1426 op_arithK(L, luaV_idiv, luai_numidiv);
1427 vmbreak;
1429 vmcase(OP_BANDK) {
1430 op_bitwiseK(L, l_band);
1431 vmbreak;
1433 vmcase(OP_BORK) {
1434 op_bitwiseK(L, l_bor);
1435 vmbreak;
1437 vmcase(OP_BXORK) {
1438 op_bitwiseK(L, l_bxor);
1439 vmbreak;
1441 vmcase(OP_SHRI) {
1442 StkId ra = RA(i);
1443 TValue *rb = vRB(i);
1444 int ic = GETARG_sC(i);
1445 lua_Integer ib;
1446 if (tointegerns(rb, &ib)) {
1447 pc++;
1448 setivalue(s2v(ra), luaV_shiftl(ib, -ic));
1450 vmbreak;
1452 vmcase(OP_SHLI) {
1453 StkId ra = RA(i);
1454 TValue *rb = vRB(i);
1455 int ic = GETARG_sC(i);
1456 lua_Integer ib;
1457 if (tointegerns(rb, &ib)) {
1458 pc++;
1459 setivalue(s2v(ra), luaV_shiftl(ic, ib));
1461 vmbreak;
1463 vmcase(OP_ADD) {
1464 op_arith(L, l_addi, luai_numadd);
1465 vmbreak;
1467 vmcase(OP_SUB) {
1468 op_arith(L, l_subi, luai_numsub);
1469 vmbreak;
1471 vmcase(OP_MUL) {
1472 op_arith(L, l_muli, luai_nummul);
1473 vmbreak;
1475 vmcase(OP_MOD) {
1476 savestate(L, ci); /* in case of division by 0 */
1477 op_arith(L, luaV_mod, luaV_modf);
1478 vmbreak;
1480 vmcase(OP_POW) {
1481 op_arithf(L, luai_numpow);
1482 vmbreak;
1484 vmcase(OP_DIV) { /* float division (always with floats) */
1485 op_arithf(L, luai_numdiv);
1486 vmbreak;
1488 vmcase(OP_IDIV) { /* floor division */
1489 savestate(L, ci); /* in case of division by 0 */
1490 op_arith(L, luaV_idiv, luai_numidiv);
1491 vmbreak;
1493 vmcase(OP_BAND) {
1494 op_bitwise(L, l_band);
1495 vmbreak;
1497 vmcase(OP_BOR) {
1498 op_bitwise(L, l_bor);
1499 vmbreak;
1501 vmcase(OP_BXOR) {
1502 op_bitwise(L, l_bxor);
1503 vmbreak;
1505 vmcase(OP_SHR) {
1506 op_bitwise(L, luaV_shiftr);
1507 vmbreak;
1509 vmcase(OP_SHL) {
1510 op_bitwise(L, luaV_shiftl);
1511 vmbreak;
1513 vmcase(OP_MMBIN) {
1514 StkId ra = RA(i);
1515 Instruction pi = *(pc - 2); /* original arith. expression */
1516 TValue *rb = vRB(i);
1517 TMS tm = (TMS)GETARG_C(i);
1518 StkId result = RA(pi);
1519 lua_assert(OP_ADD <= GET_OPCODE(pi) && GET_OPCODE(pi) <= OP_SHR);
1520 Protect(luaT_trybinTM(L, s2v(ra), rb, result, tm));
1521 vmbreak;
1523 vmcase(OP_MMBINI) {
1524 StkId ra = RA(i);
1525 Instruction pi = *(pc - 2); /* original arith. expression */
1526 int imm = GETARG_sB(i);
1527 TMS tm = (TMS)GETARG_C(i);
1528 int flip = GETARG_k(i);
1529 StkId result = RA(pi);
1530 Protect(luaT_trybiniTM(L, s2v(ra), imm, flip, result, tm));
1531 vmbreak;
1533 vmcase(OP_MMBINK) {
1534 StkId ra = RA(i);
1535 Instruction pi = *(pc - 2); /* original arith. expression */
1536 TValue *imm = KB(i);
1537 TMS tm = (TMS)GETARG_C(i);
1538 int flip = GETARG_k(i);
1539 StkId result = RA(pi);
1540 Protect(luaT_trybinassocTM(L, s2v(ra), imm, flip, result, tm));
1541 vmbreak;
1543 vmcase(OP_UNM) {
1544 StkId ra = RA(i);
1545 TValue *rb = vRB(i);
1546 lua_Number nb;
1547 if (ttisinteger(rb)) {
1548 lua_Integer ib = ivalue(rb);
1549 setivalue(s2v(ra), intop(-, 0, ib));
1550 } else if (tonumberns(rb, nb)) {
1551 setfltvalue(s2v(ra), luai_numunm(L, nb));
1552 } else
1553 Protect(luaT_trybinTM(L, rb, rb, ra, TM_UNM));
1554 vmbreak;
1556 vmcase(OP_BNOT) {
1557 StkId ra = RA(i);
1558 TValue *rb = vRB(i);
1559 lua_Integer ib;
1560 if (tointegerns(rb, &ib)) {
1561 setivalue(s2v(ra), intop(^, ~l_castS2U(0), ib));
1562 } else
1563 Protect(luaT_trybinTM(L, rb, rb, ra, TM_BNOT));
1564 vmbreak;
1566 vmcase(OP_NOT) {
1567 StkId ra = RA(i);
1568 TValue *rb = vRB(i);
1569 if (l_isfalse(rb))
1570 setbtvalue(s2v(ra));
1571 else
1572 setbfvalue(s2v(ra));
1573 vmbreak;
1575 vmcase(OP_LEN) {
1576 StkId ra = RA(i);
1577 Protect(luaV_objlen(L, ra, vRB(i)));
1578 vmbreak;
1580 vmcase(OP_CONCAT) {
1581 StkId ra = RA(i);
1582 int n = GETARG_B(i); /* number of elements to concatenate */
1583 L->top.p = ra + n; /* mark the end of concat operands */
1584 ProtectNT(luaV_concat(L, n));
1585 checkGC(L, L->top.p); /* 'luaV_concat' ensures correct top */
1586 vmbreak;
1588 vmcase(OP_CLOSE) {
1589 StkId ra = RA(i);
1590 Protect(luaF_close(L, ra, LUA_OK, 1));
1591 vmbreak;
1593 vmcase(OP_TBC) {
1594 StkId ra = RA(i);
1595 /* create new to-be-closed upvalue */
1596 halfProtect(luaF_newtbcupval(L, ra));
1597 vmbreak;
1599 vmcase(OP_JMP) {
1600 dojump(ci, i, 0);
1601 vmbreak;
1603 vmcase(OP_EQ) {
1604 StkId ra = RA(i);
1605 int cond;
1606 TValue *rb = vRB(i);
1607 Protect(cond = luaV_equalobj(L, s2v(ra), rb));
1608 docondjump();
1609 vmbreak;
1611 vmcase(OP_LT) {
1612 op_order(L, l_lti, LTnum, lessthanothers);
1613 vmbreak;
1615 vmcase(OP_LE) {
1616 op_order(L, l_lei, LEnum, lessequalothers);
1617 vmbreak;
1619 vmcase(OP_EQK) {
1620 StkId ra = RA(i);
1621 TValue *rb = KB(i);
1622 /* basic types do not use '__eq'; we can use raw equality */
1623 int cond = luaV_rawequalobj(s2v(ra), rb);
1624 docondjump();
1625 vmbreak;
1627 vmcase(OP_EQI) {
1628 StkId ra = RA(i);
1629 int cond;
1630 int im = GETARG_sB(i);
1631 if (ttisinteger(s2v(ra)))
1632 cond = (ivalue(s2v(ra)) == im);
1633 else if (ttisfloat(s2v(ra)))
1634 cond = luai_numeq(fltvalue(s2v(ra)), cast_num(im));
1635 else
1636 cond = 0; /* other types cannot be equal to a number */
1637 docondjump();
1638 vmbreak;
1640 vmcase(OP_LTI) {
1641 op_orderI(L, l_lti, luai_numlt, 0, TM_LT);
1642 vmbreak;
1644 vmcase(OP_LEI) {
1645 op_orderI(L, l_lei, luai_numle, 0, TM_LE);
1646 vmbreak;
1648 vmcase(OP_GTI) {
1649 op_orderI(L, l_gti, luai_numgt, 1, TM_LT);
1650 vmbreak;
1652 vmcase(OP_GEI) {
1653 op_orderI(L, l_gei, luai_numge, 1, TM_LE);
1654 vmbreak;
1656 vmcase(OP_TEST) {
1657 StkId ra = RA(i);
1658 int cond = !l_isfalse(s2v(ra));
1659 docondjump();
1660 vmbreak;
1662 vmcase(OP_TESTSET) {
1663 StkId ra = RA(i);
1664 TValue *rb = vRB(i);
1665 if (l_isfalse(rb) == GETARG_k(i))
1666 pc++;
1667 else {
1668 setobj2s(L, ra, rb);
1669 donextjump(ci);
1671 vmbreak;
1673 vmcase(OP_CALL) {
1674 StkId ra = RA(i);
1675 CallInfo *newci;
1676 int b = GETARG_B(i);
1677 int nresults = GETARG_C(i) - 1;
1678 if (b != 0) /* fixed number of arguments? */
1679 L->top.p = ra + b; /* top signals number of arguments */
1680 /* else previous instruction set top */
1681 savepc(L); /* in case of errors */
1682 if ((newci = luaD_precall(L, ra, nresults)) == NULL)
1683 updatetrap(ci); /* C call; nothing else to be done */
1684 else { /* Lua call: run function in this same C frame */
1685 ci = newci;
1686 goto startfunc;
1688 vmbreak;
1690 vmcase(OP_TAILCALL) {
1691 StkId ra = RA(i);
1692 int b = GETARG_B(i); /* number of arguments + 1 (function) */
1693 int n; /* number of results when calling a C function */
1694 int nparams1 = GETARG_C(i);
1695 /* delta is virtual 'func' - real 'func' (vararg functions) */
1696 int delta = (nparams1) ? ci->u.l.nextraargs + nparams1 : 0;
1697 if (b != 0)
1698 L->top.p = ra + b;
1699 else /* previous instruction set top */
1700 b = cast_int(L->top.p - ra);
1701 savepc(ci); /* several calls here can raise errors */
1702 if (TESTARG_k(i)) {
1703 luaF_closeupval(L, base); /* close upvalues from current call */
1704 lua_assert(L->tbclist.p < base); /* no pending tbc variables */
1705 lua_assert(base == ci->func.p + 1);
1707 if ((n = luaD_pretailcall(L, ci, ra, b, delta)) < 0) /* Lua function? */
1708 goto startfunc; /* execute the callee */
1709 else { /* C function? */
1710 ci->func.p -= delta; /* restore 'func' (if vararg) */
1711 luaD_poscall(L, ci, n); /* finish caller */
1712 updatetrap(ci); /* 'luaD_poscall' can change hooks */
1713 goto ret; /* caller returns after the tail call */
1716 vmcase(OP_RETURN) {
1717 StkId ra = RA(i);
1718 int n = GETARG_B(i) - 1; /* number of results */
1719 int nparams1 = GETARG_C(i);
1720 if (n < 0) /* not fixed? */
1721 n = cast_int(L->top.p - ra); /* get what is available */
1722 savepc(ci);
1723 if (TESTARG_k(i)) { /* may there be open upvalues? */
1724 ci->u2.nres = n; /* save number of returns */
1725 if (L->top.p < ci->top.p)
1726 L->top.p = ci->top.p;
1727 luaF_close(L, base, CLOSEKTOP, 1);
1728 updatetrap(ci);
1729 updatestack(ci);
1731 if (nparams1) /* vararg function? */
1732 ci->func.p -= ci->u.l.nextraargs + nparams1;
1733 L->top.p = ra + n; /* set call for 'luaD_poscall' */
1734 luaD_poscall(L, ci, n);
1735 updatetrap(ci); /* 'luaD_poscall' can change hooks */
1736 goto ret;
1738 vmcase(OP_RETURN0) {
1739 if (l_unlikely(L->hookmask)) {
1740 StkId ra = RA(i);
1741 L->top.p = ra;
1742 savepc(ci);
1743 luaD_poscall(L, ci, 0); /* no hurry... */
1744 trap = 1;
1745 } else { /* do the 'poscall' here */
1746 int nres;
1747 L->ci = ci->previous; /* back to caller */
1748 L->top.p = base - 1;
1749 for (nres = ci->nresults; l_unlikely(nres > 0); nres--)
1750 setnilvalue(s2v(L->top.p++)); /* all results are nil */
1752 goto ret;
1754 vmcase(OP_RETURN1) {
1755 if (l_unlikely(L->hookmask)) {
1756 StkId ra = RA(i);
1757 L->top.p = ra + 1;
1758 savepc(ci);
1759 luaD_poscall(L, ci, 1); /* no hurry... */
1760 trap = 1;
1761 } else { /* do the 'poscall' here */
1762 int nres = ci->nresults;
1763 L->ci = ci->previous; /* back to caller */
1764 if (nres == 0)
1765 L->top.p = base - 1; /* asked for no results */
1766 else {
1767 StkId ra = RA(i);
1768 setobjs2s(L, base - 1, ra); /* at least this result */
1769 L->top.p = base;
1770 for (; l_unlikely(nres > 1); nres--)
1771 setnilvalue(s2v(L->top.p++)); /* complete missing results */
1774 ret: /* return from a Lua function */
1775 if (ci->callstatus & CIST_FRESH)
1776 return; /* end this frame */
1777 else {
1778 ci = ci->previous;
1779 goto returning; /* continue running caller in this frame */
1782 vmcase(OP_FORLOOP) {
1783 StkId ra = RA(i);
1784 if (ttisinteger(s2v(ra + 2))) { /* integer loop? */
1785 lua_Unsigned count = l_castS2U(ivalue(s2v(ra + 1)));
1786 if (count > 0) { /* still more iterations? */
1787 lua_Integer step = ivalue(s2v(ra + 2));
1788 lua_Integer idx = ivalue(s2v(ra)); /* internal index */
1789 chgivalue(s2v(ra + 1), count - 1); /* update counter */
1790 idx = intop(+, idx, step); /* add step to index */
1791 chgivalue(s2v(ra), idx); /* update internal index */
1792 setivalue(s2v(ra + 3), idx); /* and control variable */
1793 pc -= GETARG_Bx(i); /* jump back */
1795 } else if (floatforloop(ra)) /* float loop */
1796 pc -= GETARG_Bx(i); /* jump back */
1797 updatetrap(ci); /* allows a signal to break the loop */
1798 vmbreak;
1800 vmcase(OP_FORPREP) {
1801 StkId ra = RA(i);
1802 savestate(L, ci); /* in case of errors */
1803 if (forprep(L, ra))
1804 pc += GETARG_Bx(i) + 1; /* skip the loop */
1805 vmbreak;
1807 vmcase(OP_TFORPREP) {
1808 StkId ra = RA(i);
1809 /* create to-be-closed upvalue (if needed) */
1810 halfProtect(luaF_newtbcupval(L, ra + 3));
1811 pc += GETARG_Bx(i);
1812 i = *(pc++); /* go to next instruction */
1813 lua_assert(GET_OPCODE(i) == OP_TFORCALL && ra == RA(i));
1814 goto l_tforcall;
1816 vmcase(OP_TFORCALL) {
1817 l_tforcall: {
1818 StkId ra = RA(i);
1819 /* 'ra' has the iterator function, 'ra + 1' has the state,
1820 'ra + 2' has the control variable, and 'ra + 3' has the
1821 to-be-closed variable. The call will use the stack after
1822 these values (starting at 'ra + 4')
1824 /* push function, state, and control variable */
1825 memcpy(ra + 4, ra, 3 * sizeof(*ra));
1826 L->top.p = ra + 4 + 3;
1827 ProtectNT(luaD_call(L, ra + 4, GETARG_C(i))); /* do the call */
1828 updatestack(ci); /* stack may have changed */
1829 i = *(pc++); /* go to next instruction */
1830 lua_assert(GET_OPCODE(i) == OP_TFORLOOP && ra == RA(i));
1831 goto l_tforloop;
1834 vmcase(OP_TFORLOOP) {
1835 l_tforloop: {
1836 StkId ra = RA(i);
1837 if (!ttisnil(s2v(ra + 4))) { /* continue loop? */
1838 setobjs2s(L, ra + 2, ra + 4); /* save control variable */
1839 pc -= GETARG_Bx(i); /* jump back */
1841 vmbreak;
1844 vmcase(OP_SETLIST) {
1845 StkId ra = RA(i);
1846 int n = GETARG_B(i);
1847 unsigned int last = GETARG_C(i);
1848 Table *h = hvalue(s2v(ra));
1849 if (n == 0)
1850 n = cast_int(L->top.p - ra) - 1; /* get up to the top */
1851 else
1852 L->top.p = ci->top.p; /* correct top in case of emergency GC */
1853 last += n;
1854 if (TESTARG_k(i)) {
1855 last += GETARG_Ax(*pc) * (MAXARG_C + 1);
1856 pc++;
1858 if (last > luaH_realasize(h)) /* needs more space? */
1859 luaH_resizearray(L, h, last); /* preallocate it at once */
1860 for (; n > 0; n--) {
1861 TValue *val = s2v(ra + n);
1862 setobj2t(L, &h->array[last - 1], val);
1863 last--;
1864 luaC_barrierback(L, obj2gco(h), val);
1866 vmbreak;
1868 vmcase(OP_CLOSURE) {
1869 StkId ra = RA(i);
1870 Proto *p = cl->p->p[GETARG_Bx(i)];
1871 halfProtect(pushclosure(L, p, cl->upvals, base, ra));
1872 checkGC(L, ra + 1);
1873 vmbreak;
1875 vmcase(OP_VARARG) {
1876 StkId ra = RA(i);
1877 int n = GETARG_C(i) - 1; /* required results */
1878 Protect(luaT_getvarargs(L, ci, ra, n));
1879 vmbreak;
1881 vmcase(OP_VARARGPREP) {
1882 ProtectNT(luaT_adjustvarargs(L, GETARG_A(i), ci, cl->p));
1883 if (l_unlikely(trap)) { /* previous "Protect" updated trap */
1884 luaD_hookcall(L, ci);
1885 L->oldpc = 1; /* next opcode will be seen as a "new" line */
1887 updatebase(ci); /* function has new base after adjustment */
1888 vmbreak;
1890 vmcase(OP_EXTRAARG) {
1891 lua_assert(0);
1892 vmbreak;
1898 /* }================================================================== */