lvm.c 41 KB

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