lobject.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  1. /*
  2. ** $Id: lobject.c,v 2.109 2015/12/14 11:53:27 roberto Exp roberto $
  3. ** Some generic functions over Lua objects
  4. ** See Copyright Notice in lua.h
  5. */
  6. #define lobject_c
  7. #define LUA_CORE
  8. #include "lprefix.h"
  9. #include <locale.h>
  10. #include <math.h>
  11. #include <stdarg.h>
  12. #include <stdio.h>
  13. #include <stdlib.h>
  14. #include <string.h>
  15. #include "lua.h"
  16. #include "lctype.h"
  17. #include "ldebug.h"
  18. #include "ldo.h"
  19. #include "lmem.h"
  20. #include "lobject.h"
  21. #include "lstate.h"
  22. #include "lstring.h"
  23. #include "lvm.h"
  24. LUAI_DDEF const TValue luaO_nilobject_ = {NILCONSTANT};
  25. /*
  26. ** converts an integer to a "floating point byte", represented as
  27. ** (eeeeexxx), where the real value is (1xxx) * 2^(eeeee - 1) if
  28. ** eeeee != 0 and (xxx) otherwise.
  29. */
  30. int luaO_int2fb (unsigned int x) {
  31. int e = 0; /* exponent */
  32. if (x < 8) return x;
  33. while (x >= (8 << 4)) { /* coarse steps */
  34. x = (x + 0xf) >> 4; /* x = ceil(x / 16) */
  35. e += 4;
  36. }
  37. while (x >= (8 << 1)) { /* fine steps */
  38. x = (x + 1) >> 1; /* x = ceil(x / 2) */
  39. e++;
  40. }
  41. return ((e+1) << 3) | (cast_int(x) - 8);
  42. }
  43. /* converts back */
  44. int luaO_fb2int (int x) {
  45. return (x < 8) ? x : ((x & 7) + 8) << ((x >> 3) - 1);
  46. }
  47. /*
  48. ** Computes ceil(log2(x))
  49. */
  50. int luaO_ceillog2 (unsigned int x) {
  51. static const lu_byte log_2[256] = { /* log_2[i] = ceil(log2(i - 1)) */
  52. 0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
  53. 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
  54. 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
  55. 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
  56. 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
  57. 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
  58. 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
  59. 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8
  60. };
  61. int l = 0;
  62. x--;
  63. while (x >= 256) { l += 8; x >>= 8; }
  64. return l + log_2[x];
  65. }
  66. static lua_Integer intarith (lua_State *L, int op, lua_Integer v1,
  67. lua_Integer v2) {
  68. switch (op) {
  69. case LUA_OPADD: return intop(+, v1, v2);
  70. case LUA_OPSUB:return intop(-, v1, v2);
  71. case LUA_OPMUL:return intop(*, v1, v2);
  72. case LUA_OPMOD: return luaV_mod(L, v1, v2);
  73. case LUA_OPIDIV: return luaV_div(L, v1, v2);
  74. case LUA_OPBAND: return intop(&, v1, v2);
  75. case LUA_OPBOR: return intop(|, v1, v2);
  76. case LUA_OPBXOR: return intop(^, v1, v2);
  77. case LUA_OPSHL: return luaV_shiftl(v1, v2);
  78. case LUA_OPSHR: return luaV_shiftl(v1, -v2);
  79. case LUA_OPUNM: return intop(-, 0, v1);
  80. case LUA_OPBNOT: return intop(^, ~l_castS2U(0), v1);
  81. default: lua_assert(0); return 0;
  82. }
  83. }
  84. static lua_Number numarith (lua_State *L, int op, lua_Number v1,
  85. lua_Number v2) {
  86. switch (op) {
  87. case LUA_OPADD: return luai_numadd(L, v1, v2);
  88. case LUA_OPSUB: return luai_numsub(L, v1, v2);
  89. case LUA_OPMUL: return luai_nummul(L, v1, v2);
  90. case LUA_OPDIV: return luai_numdiv(L, v1, v2);
  91. case LUA_OPPOW: return luai_numpow(L, v1, v2);
  92. case LUA_OPIDIV: return luai_numidiv(L, v1, v2);
  93. case LUA_OPUNM: return luai_numunm(L, v1);
  94. case LUA_OPMOD: {
  95. lua_Number m;
  96. luai_nummod(L, v1, v2, m);
  97. return m;
  98. }
  99. default: lua_assert(0); return 0;
  100. }
  101. }
  102. void luaO_arith (lua_State *L, int op, const TValue *p1, const TValue *p2,
  103. TValue *res) {
  104. switch (op) {
  105. case LUA_OPBAND: case LUA_OPBOR: case LUA_OPBXOR:
  106. case LUA_OPSHL: case LUA_OPSHR:
  107. case LUA_OPBNOT: { /* operate only on integers */
  108. lua_Integer i1; lua_Integer i2;
  109. if (tointeger(p1, &i1) && tointeger(p2, &i2)) {
  110. setivalue(res, intarith(L, op, i1, i2));
  111. return;
  112. }
  113. else break; /* go to the end */
  114. }
  115. case LUA_OPDIV: case LUA_OPPOW: { /* operate only on floats */
  116. lua_Number n1; lua_Number n2;
  117. if (tonumber(p1, &n1) && tonumber(p2, &n2)) {
  118. setfltvalue(res, numarith(L, op, n1, n2));
  119. return;
  120. }
  121. else break; /* go to the end */
  122. }
  123. default: { /* other operations */
  124. lua_Number n1; lua_Number n2;
  125. if (ttisinteger(p1) && ttisinteger(p2)) {
  126. setivalue(res, intarith(L, op, ivalue(p1), ivalue(p2)));
  127. return;
  128. }
  129. else if (tonumber(p1, &n1) && tonumber(p2, &n2)) {
  130. setfltvalue(res, numarith(L, op, n1, n2));
  131. return;
  132. }
  133. else break; /* go to the end */
  134. }
  135. }
  136. /* could not perform raw operation; try metamethod */
  137. lua_assert(L != NULL); /* should not fail when folding (compile time) */
  138. luaT_trybinTM(L, p1, p2, res, cast(TMS, (op - LUA_OPADD) + TM_ADD));
  139. }
  140. int luaO_hexavalue (int c) {
  141. if (lisdigit(c)) return c - '0';
  142. else return (ltolower(c) - 'a') + 10;
  143. }
  144. static int isneg (const char **s) {
  145. if (**s == '-') { (*s)++; return 1; }
  146. else if (**s == '+') (*s)++;
  147. return 0;
  148. }
  149. /*
  150. ** {==================================================================
  151. ** Lua's implementation for 'lua_strx2number'
  152. ** ===================================================================
  153. */
  154. #if !defined(lua_strx2number)
  155. /* maximum number of significant digits to read (to avoid overflows
  156. even with single floats) */
  157. #define MAXSIGDIG 30
  158. /*
  159. ** convert an hexadecimal numeric string to a number, following
  160. ** C99 specification for 'strtod'
  161. */
  162. static lua_Number lua_strx2number (const char *s, char **endptr) {
  163. int dot = lua_getlocaledecpoint();
  164. lua_Number r = 0.0; /* result (accumulator) */
  165. int sigdig = 0; /* number of significant digits */
  166. int nosigdig = 0; /* number of non-significant digits */
  167. int e = 0; /* exponent correction */
  168. int neg; /* 1 if number is negative */
  169. int hasdot = 0; /* true after seen a dot */
  170. *endptr = cast(char *, s); /* nothing is valid yet */
  171. while (lisspace(cast_uchar(*s))) s++; /* skip initial spaces */
  172. neg = isneg(&s); /* check signal */
  173. if (!(*s == '0' && (*(s + 1) == 'x' || *(s + 1) == 'X'))) /* check '0x' */
  174. return 0.0; /* invalid format (no '0x') */
  175. for (s += 2; ; s++) { /* skip '0x' and read numeral */
  176. if (*s == dot) {
  177. if (hasdot) break; /* second dot? stop loop */
  178. else hasdot = 1;
  179. }
  180. else if (lisxdigit(cast_uchar(*s))) {
  181. if (sigdig == 0 && *s == '0') /* non-significant digit (zero)? */
  182. nosigdig++;
  183. else if (++sigdig <= MAXSIGDIG) /* can read it without overflow? */
  184. r = (r * cast_num(16.0)) + luaO_hexavalue(*s);
  185. else e++; /* too many digits; ignore, but still count for exponent */
  186. if (hasdot) e--; /* decimal digit? correct exponent */
  187. }
  188. else break; /* neither a dot nor a digit */
  189. }
  190. if (nosigdig + sigdig == 0) /* no digits? */
  191. return 0.0; /* invalid format */
  192. *endptr = cast(char *, s); /* valid up to here */
  193. e *= 4; /* each digit multiplies/divides value by 2^4 */
  194. if (*s == 'p' || *s == 'P') { /* exponent part? */
  195. int exp1 = 0; /* exponent value */
  196. int neg1; /* exponent signal */
  197. s++; /* skip 'p' */
  198. neg1 = isneg(&s); /* signal */
  199. if (!lisdigit(cast_uchar(*s)))
  200. return 0.0; /* invalid; must have at least one digit */
  201. while (lisdigit(cast_uchar(*s))) /* read exponent */
  202. exp1 = exp1 * 10 + *(s++) - '0';
  203. if (neg1) exp1 = -exp1;
  204. e += exp1;
  205. *endptr = cast(char *, s); /* valid up to here */
  206. }
  207. if (neg) r = -r;
  208. return l_mathop(ldexp)(r, e);
  209. }
  210. #endif
  211. /* }====================================================== */
  212. /* maximum length of a numeral */
  213. #if !defined (L_MAXLENNUM)
  214. #define L_MAXLENNUM 200
  215. #endif
  216. static const char *l_str2dloc (const char *s, lua_Number *result, int mode) {
  217. char *endptr;
  218. *result = (mode == 'x') ? lua_strx2number(s, &endptr) /* try to convert */
  219. : lua_str2number(s, &endptr);
  220. if (endptr == s) return NULL; /* nothing recognized? */
  221. while (lisspace(cast_uchar(*endptr))) endptr++; /* skip trailing spaces */
  222. return (*endptr == '\0') ? endptr : NULL; /* OK if no trailing characters */
  223. }
  224. /*
  225. ** Convert string 's' to a Lua number (put in 'result'). Return NULL
  226. ** on fail or the address of the ending '\0' on success.
  227. ** 'pmode' points to (and 'mode' contains) special things in the string:
  228. ** - 'x'/'X' means an hexadecimal numeral
  229. ** - 'n'/'N' means 'inf' or 'nan' (which should be rejected)
  230. ** - '.' just optimizes the search for the common case (nothing special)
  231. ** This function accepts both the current locale or a dot as the radix
  232. ** mark. If the convertion fails, it may mean number has a dot but
  233. ** locale accepts something else. In that case, the code copies 's'
  234. ** to a buffer (because 's' is read-only), changes the dot to the
  235. ** current locale radix mark, and tries to convert again.
  236. */
  237. static const char *l_str2d (const char *s, lua_Number *result) {
  238. const char *endptr;
  239. const char *pmode = strpbrk(s, ".xXnN");
  240. int mode = pmode ? ltolower(cast_uchar(*pmode)) : 0;
  241. if (mode == 'n') /* reject 'inf' and 'nan' */
  242. return NULL;
  243. endptr = l_str2dloc(s, result, mode); /* try to convert */
  244. if (endptr == NULL) { /* failed? may be a different locale */
  245. char buff[L_MAXLENNUM + 1];
  246. char *pdot = strchr(s, '.');
  247. if (strlen(s) > L_MAXLENNUM || pdot == NULL)
  248. return NULL; /* string too long or no dot; fail */
  249. strcpy(buff, s); /* copy string to buffer */
  250. buff[pdot - s] = lua_getlocaledecpoint(); /* correct decimal point */
  251. endptr = l_str2dloc(buff, result, mode); /* try again */
  252. if (endptr != NULL)
  253. endptr = s + (endptr - buff); /* make relative to 's' */
  254. }
  255. return endptr;
  256. }
  257. static const char *l_str2int (const char *s, lua_Integer *result) {
  258. lua_Unsigned a = 0;
  259. int empty = 1;
  260. int neg;
  261. while (lisspace(cast_uchar(*s))) s++; /* skip initial spaces */
  262. neg = isneg(&s);
  263. if (s[0] == '0' &&
  264. (s[1] == 'x' || s[1] == 'X')) { /* hex? */
  265. s += 2; /* skip '0x' */
  266. for (; lisxdigit(cast_uchar(*s)); s++) {
  267. a = a * 16 + luaO_hexavalue(*s);
  268. empty = 0;
  269. }
  270. }
  271. else { /* decimal */
  272. for (; lisdigit(cast_uchar(*s)); s++) {
  273. a = a * 10 + *s - '0';
  274. empty = 0;
  275. }
  276. }
  277. while (lisspace(cast_uchar(*s))) s++; /* skip trailing spaces */
  278. if (empty || *s != '\0') return NULL; /* something wrong in the numeral */
  279. else {
  280. *result = l_castU2S((neg) ? 0u - a : a);
  281. return s;
  282. }
  283. }
  284. size_t luaO_str2num (const char *s, TValue *o) {
  285. lua_Integer i; lua_Number n;
  286. const char *e;
  287. if ((e = l_str2int(s, &i)) != NULL) { /* try as an integer */
  288. setivalue(o, i);
  289. }
  290. else if ((e = l_str2d(s, &n)) != NULL) { /* else try as a float */
  291. setfltvalue(o, n);
  292. }
  293. else
  294. return 0; /* conversion failed */
  295. return (e - s) + 1; /* success; return string size */
  296. }
  297. int luaO_utf8esc (char *buff, unsigned long x) {
  298. int n = 1; /* number of bytes put in buffer (backwards) */
  299. lua_assert(x <= 0x10FFFF);
  300. if (x < 0x80) /* ascii? */
  301. buff[UTF8BUFFSZ - 1] = cast(char, x);
  302. else { /* need continuation bytes */
  303. unsigned int mfb = 0x3f; /* maximum that fits in first byte */
  304. do { /* add continuation bytes */
  305. buff[UTF8BUFFSZ - (n++)] = cast(char, 0x80 | (x & 0x3f));
  306. x >>= 6; /* remove added bits */
  307. mfb >>= 1; /* now there is one less bit available in first byte */
  308. } while (x > mfb); /* still needs continuation byte? */
  309. buff[UTF8BUFFSZ - n] = cast(char, (~mfb << 1) | x); /* add first byte */
  310. }
  311. return n;
  312. }
  313. /* maximum length of the conversion of a number to a string */
  314. #define MAXNUMBER2STR 50
  315. /*
  316. ** Convert a number object to a string
  317. */
  318. void luaO_tostring (lua_State *L, StkId obj) {
  319. char buff[MAXNUMBER2STR];
  320. size_t len;
  321. lua_assert(ttisnumber(obj));
  322. if (ttisinteger(obj))
  323. len = lua_integer2str(buff, sizeof(buff), ivalue(obj));
  324. else {
  325. len = lua_number2str(buff, sizeof(buff), fltvalue(obj));
  326. #if !defined(LUA_COMPAT_FLOATSTRING)
  327. if (buff[strspn(buff, "-0123456789")] == '\0') { /* looks like an int? */
  328. buff[len++] = lua_getlocaledecpoint();
  329. buff[len++] = '0'; /* adds '.0' to result */
  330. }
  331. #endif
  332. }
  333. setsvalue2s(L, obj, luaS_newlstr(L, buff, len));
  334. }
  335. static void pushstr (lua_State *L, const char *str, size_t l) {
  336. setsvalue2s(L, L->top, luaS_newlstr(L, str, l));
  337. luaD_inctop(L);
  338. }
  339. /*
  340. ** this function handles only '%d', '%c', '%f', '%p', and '%s'
  341. conventional formats, plus Lua-specific '%I' and '%U'
  342. */
  343. const char *luaO_pushvfstring (lua_State *L, const char *fmt, va_list argp) {
  344. int n = 0;
  345. for (;;) {
  346. const char *e = strchr(fmt, '%');
  347. if (e == NULL) break;
  348. pushstr(L, fmt, e - fmt);
  349. switch (*(e+1)) {
  350. case 's': { /* zero-terminated string */
  351. const char *s = va_arg(argp, char *);
  352. if (s == NULL) s = "(null)";
  353. pushstr(L, s, strlen(s));
  354. break;
  355. }
  356. case 'c': { /* an 'int' as a character */
  357. char buff = cast(char, va_arg(argp, int));
  358. if (lisprint(cast_uchar(buff)))
  359. pushstr(L, &buff, 1);
  360. else /* non-printable character; print its code */
  361. luaO_pushfstring(L, "<\\%d>", cast_uchar(buff));
  362. break;
  363. }
  364. case 'd': { /* an 'int' */
  365. setivalue(L->top, va_arg(argp, int));
  366. goto top2str;
  367. }
  368. case 'I': { /* a 'lua_Integer' */
  369. setivalue(L->top, cast(lua_Integer, va_arg(argp, l_uacInt)));
  370. goto top2str;
  371. }
  372. case 'f': { /* a 'lua_Number' */
  373. setfltvalue(L->top, cast_num(va_arg(argp, l_uacNumber)));
  374. top2str: /* convert the top element to a string */
  375. luaD_inctop(L);
  376. luaO_tostring(L, L->top - 1);
  377. break;
  378. }
  379. case 'p': { /* a pointer */
  380. char buff[4*sizeof(void *) + 8]; /* should be enough space for a '%p' */
  381. int l = l_sprintf(buff, sizeof(buff), "%p", va_arg(argp, void *));
  382. pushstr(L, buff, l);
  383. break;
  384. }
  385. case 'U': { /* an 'int' as a UTF-8 sequence */
  386. char buff[UTF8BUFFSZ];
  387. int l = luaO_utf8esc(buff, cast(long, va_arg(argp, long)));
  388. pushstr(L, buff + UTF8BUFFSZ - l, l);
  389. break;
  390. }
  391. case '%': {
  392. pushstr(L, "%", 1);
  393. break;
  394. }
  395. default: {
  396. luaG_runerror(L, "invalid option '%%%c' to 'lua_pushfstring'",
  397. *(e + 1));
  398. }
  399. }
  400. n += 2;
  401. fmt = e+2;
  402. }
  403. luaD_checkstack(L, 1);
  404. pushstr(L, fmt, strlen(fmt));
  405. if (n > 0) luaV_concat(L, n + 1);
  406. return svalue(L->top - 1);
  407. }
  408. const char *luaO_pushfstring (lua_State *L, const char *fmt, ...) {
  409. const char *msg;
  410. va_list argp;
  411. va_start(argp, fmt);
  412. msg = luaO_pushvfstring(L, fmt, argp);
  413. va_end(argp);
  414. return msg;
  415. }
  416. /* number of chars of a literal string without the ending \0 */
  417. #define LL(x) (sizeof(x)/sizeof(char) - 1)
  418. #define RETS "..."
  419. #define PRE "[string \""
  420. #define POS "\"]"
  421. #define addstr(a,b,l) ( memcpy(a,b,(l) * sizeof(char)), a += (l) )
  422. void luaO_chunkid (char *out, const char *source, size_t bufflen) {
  423. size_t l = strlen(source);
  424. if (*source == '=') { /* 'literal' source */
  425. if (l <= bufflen) /* small enough? */
  426. memcpy(out, source + 1, l * sizeof(char));
  427. else { /* truncate it */
  428. addstr(out, source + 1, bufflen - 1);
  429. *out = '\0';
  430. }
  431. }
  432. else if (*source == '@') { /* file name */
  433. if (l <= bufflen) /* small enough? */
  434. memcpy(out, source + 1, l * sizeof(char));
  435. else { /* add '...' before rest of name */
  436. addstr(out, RETS, LL(RETS));
  437. bufflen -= LL(RETS);
  438. memcpy(out, source + 1 + l - bufflen, bufflen * sizeof(char));
  439. }
  440. }
  441. else { /* string; format as [string "source"] */
  442. const char *nl = strchr(source, '\n'); /* find first new line (if any) */
  443. addstr(out, PRE, LL(PRE)); /* add prefix */
  444. bufflen -= LL(PRE RETS POS) + 1; /* save space for prefix+suffix+'\0' */
  445. if (l < bufflen && nl == NULL) { /* small one-line source? */
  446. addstr(out, source, l); /* keep it */
  447. }
  448. else {
  449. if (nl != NULL) l = nl - source; /* stop at first newline */
  450. if (l > bufflen) l = bufflen;
  451. addstr(out, source, l);
  452. addstr(out, RETS, LL(RETS));
  453. }
  454. memcpy(out, POS, (LL(POS) + 1) * sizeof(char));
  455. }
  456. }