lobject.c 16 KB

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