2
0

lobject.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718
  1. /*
  2. ** $Id: lobject.c $
  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 <float.h>
  10. #include <locale.h>
  11. #include <math.h>
  12. #include <stdarg.h>
  13. #include <stdio.h>
  14. #include <stdlib.h>
  15. #include <string.h>
  16. #include "lua.h"
  17. #include "lctype.h"
  18. #include "ldebug.h"
  19. #include "ldo.h"
  20. #include "lmem.h"
  21. #include "lobject.h"
  22. #include "lstate.h"
  23. #include "lstring.h"
  24. #include "lvm.h"
  25. /*
  26. ** Computes ceil(log2(x)), which is the smallest integer n such that
  27. ** x <= (1 << n).
  28. */
  29. lu_byte luaO_ceillog2 (unsigned int x) {
  30. static const lu_byte log_2[256] = { /* log_2[i - 1] = ceil(log2(i)) */
  31. 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,
  32. 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,
  33. 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,
  34. 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,
  35. 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,
  36. 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,
  37. 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,
  38. 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
  39. };
  40. int l = 0;
  41. x--;
  42. while (x >= 256) { l += 8; x >>= 8; }
  43. return cast_byte(l + log_2[x]);
  44. }
  45. /*
  46. ** Encodes 'p'% as a floating-point byte, represented as (eeeexxxx).
  47. ** The exponent is represented using excess-7. Mimicking IEEE 754, the
  48. ** representation normalizes the number when possible, assuming an extra
  49. ** 1 before the mantissa (xxxx) and adding one to the exponent (eeee)
  50. ** to signal that. So, the real value is (1xxxx) * 2^(eeee - 7 - 1) if
  51. ** eeee != 0, and (xxxx) * 2^-7 otherwise (subnormal numbers).
  52. */
  53. lu_byte luaO_codeparam (unsigned int p) {
  54. if (p >= (cast(lu_mem, 0x1F) << (0xF - 7 - 1)) * 100u) /* overflow? */
  55. return 0xFF; /* return maximum value */
  56. else {
  57. p = (cast(l_uint32, p) * 128 + 99) / 100; /* round up the division */
  58. if (p < 0x10) { /* subnormal number? */
  59. /* exponent bits are already zero; nothing else to do */
  60. return cast_byte(p);
  61. }
  62. else { /* p >= 0x10 implies ceil(log2(p + 1)) >= 5 */
  63. /* preserve 5 bits in 'p' */
  64. unsigned log = luaO_ceillog2(p + 1) - 5u;
  65. return cast_byte(((p >> log) - 0x10) | ((log + 1) << 4));
  66. }
  67. }
  68. }
  69. /*
  70. ** Computes 'p' times 'x', where 'p' is a floating-point byte. Roughly,
  71. ** we have to multiply 'x' by the mantissa and then shift accordingly to
  72. ** the exponent. If the exponent is positive, both the multiplication
  73. ** and the shift increase 'x', so we have to care only about overflows.
  74. ** For negative exponents, however, multiplying before the shift keeps
  75. ** more significant bits, as long as the multiplication does not
  76. ** overflow, so we check which order is best.
  77. */
  78. l_mem luaO_applyparam (lu_byte p, l_mem x) {
  79. unsigned int m = p & 0xF; /* mantissa */
  80. int e = (p >> 4); /* exponent */
  81. if (e > 0) { /* normalized? */
  82. e--; /* correct exponent */
  83. m += 0x10; /* correct mantissa; maximum value is 0x1F */
  84. }
  85. e -= 7; /* correct excess-7 */
  86. if (e >= 0) {
  87. if (x < (MAX_LMEM / 0x1F) >> e) /* no overflow? */
  88. return (x * m) << e; /* order doesn't matter here */
  89. else /* real overflow */
  90. return MAX_LMEM;
  91. }
  92. else { /* negative exponent */
  93. e = -e;
  94. if (x < MAX_LMEM / 0x1F) /* multiplication cannot overflow? */
  95. return (x * m) >> e; /* multiplying first gives more precision */
  96. else if ((x >> e) < MAX_LMEM / 0x1F) /* cannot overflow after shift? */
  97. return (x >> e) * m;
  98. else /* real overflow */
  99. return MAX_LMEM;
  100. }
  101. }
  102. static lua_Integer intarith (lua_State *L, int op, lua_Integer v1,
  103. lua_Integer v2) {
  104. switch (op) {
  105. case LUA_OPADD: return intop(+, v1, v2);
  106. case LUA_OPSUB:return intop(-, v1, v2);
  107. case LUA_OPMUL:return intop(*, v1, v2);
  108. case LUA_OPMOD: return luaV_mod(L, v1, v2);
  109. case LUA_OPIDIV: return luaV_idiv(L, v1, v2);
  110. case LUA_OPBAND: return intop(&, v1, v2);
  111. case LUA_OPBOR: return intop(|, v1, v2);
  112. case LUA_OPBXOR: return intop(^, v1, v2);
  113. case LUA_OPSHL: return luaV_shiftl(v1, v2);
  114. case LUA_OPSHR: return luaV_shiftr(v1, v2);
  115. case LUA_OPUNM: return intop(-, 0, v1);
  116. case LUA_OPBNOT: return intop(^, ~l_castS2U(0), v1);
  117. default: lua_assert(0); return 0;
  118. }
  119. }
  120. static lua_Number numarith (lua_State *L, int op, lua_Number v1,
  121. lua_Number v2) {
  122. switch (op) {
  123. case LUA_OPADD: return luai_numadd(L, v1, v2);
  124. case LUA_OPSUB: return luai_numsub(L, v1, v2);
  125. case LUA_OPMUL: return luai_nummul(L, v1, v2);
  126. case LUA_OPDIV: return luai_numdiv(L, v1, v2);
  127. case LUA_OPPOW: return luai_numpow(L, v1, v2);
  128. case LUA_OPIDIV: return luai_numidiv(L, v1, v2);
  129. case LUA_OPUNM: return luai_numunm(L, v1);
  130. case LUA_OPMOD: return luaV_modf(L, v1, v2);
  131. default: lua_assert(0); return 0;
  132. }
  133. }
  134. int luaO_rawarith (lua_State *L, int op, const TValue *p1, const TValue *p2,
  135. TValue *res) {
  136. switch (op) {
  137. case LUA_OPBAND: case LUA_OPBOR: case LUA_OPBXOR:
  138. case LUA_OPSHL: case LUA_OPSHR:
  139. case LUA_OPBNOT: { /* operate only on integers */
  140. lua_Integer i1; lua_Integer i2;
  141. if (tointegerns(p1, &i1) && tointegerns(p2, &i2)) {
  142. setivalue(res, intarith(L, op, i1, i2));
  143. return 1;
  144. }
  145. else return 0; /* fail */
  146. }
  147. case LUA_OPDIV: case LUA_OPPOW: { /* operate only on floats */
  148. lua_Number n1; lua_Number n2;
  149. if (tonumberns(p1, n1) && tonumberns(p2, n2)) {
  150. setfltvalue(res, numarith(L, op, n1, n2));
  151. return 1;
  152. }
  153. else return 0; /* fail */
  154. }
  155. default: { /* other operations */
  156. lua_Number n1; lua_Number n2;
  157. if (ttisinteger(p1) && ttisinteger(p2)) {
  158. setivalue(res, intarith(L, op, ivalue(p1), ivalue(p2)));
  159. return 1;
  160. }
  161. else if (tonumberns(p1, n1) && tonumberns(p2, n2)) {
  162. setfltvalue(res, numarith(L, op, n1, n2));
  163. return 1;
  164. }
  165. else return 0; /* fail */
  166. }
  167. }
  168. }
  169. void luaO_arith (lua_State *L, int op, const TValue *p1, const TValue *p2,
  170. StkId res) {
  171. if (!luaO_rawarith(L, op, p1, p2, s2v(res))) {
  172. /* could not perform raw operation; try metamethod */
  173. luaT_trybinTM(L, p1, p2, res, cast(TMS, (op - LUA_OPADD) + TM_ADD));
  174. }
  175. }
  176. lu_byte luaO_hexavalue (int c) {
  177. lua_assert(lisxdigit(c));
  178. if (lisdigit(c)) return cast_byte(c - '0');
  179. else return cast_byte((ltolower(c) - 'a') + 10);
  180. }
  181. static int isneg (const char **s) {
  182. if (**s == '-') { (*s)++; return 1; }
  183. else if (**s == '+') (*s)++;
  184. return 0;
  185. }
  186. /*
  187. ** {==================================================================
  188. ** Lua's implementation for 'lua_strx2number'
  189. ** ===================================================================
  190. */
  191. #if !defined(lua_strx2number)
  192. /* maximum number of significant digits to read (to avoid overflows
  193. even with single floats) */
  194. #define MAXSIGDIG 30
  195. /*
  196. ** convert a hexadecimal numeric string to a number, following
  197. ** C99 specification for 'strtod'
  198. */
  199. static lua_Number lua_strx2number (const char *s, char **endptr) {
  200. int dot = lua_getlocaledecpoint();
  201. lua_Number r = l_mathop(0.0); /* result (accumulator) */
  202. int sigdig = 0; /* number of significant digits */
  203. int nosigdig = 0; /* number of non-significant digits */
  204. int e = 0; /* exponent correction */
  205. int neg; /* 1 if number is negative */
  206. int hasdot = 0; /* true after seen a dot */
  207. *endptr = cast_charp(s); /* nothing is valid yet */
  208. while (lisspace(cast_uchar(*s))) s++; /* skip initial spaces */
  209. neg = isneg(&s); /* check sign */
  210. if (!(*s == '0' && (*(s + 1) == 'x' || *(s + 1) == 'X'))) /* check '0x' */
  211. return l_mathop(0.0); /* invalid format (no '0x') */
  212. for (s += 2; ; s++) { /* skip '0x' and read numeral */
  213. if (*s == dot) {
  214. if (hasdot) break; /* second dot? stop loop */
  215. else hasdot = 1;
  216. }
  217. else if (lisxdigit(cast_uchar(*s))) {
  218. if (sigdig == 0 && *s == '0') /* non-significant digit (zero)? */
  219. nosigdig++;
  220. else if (++sigdig <= MAXSIGDIG) /* can read it without overflow? */
  221. r = (r * l_mathop(16.0)) + luaO_hexavalue(*s);
  222. else e++; /* too many digits; ignore, but still count for exponent */
  223. if (hasdot) e--; /* decimal digit? correct exponent */
  224. }
  225. else break; /* neither a dot nor a digit */
  226. }
  227. if (nosigdig + sigdig == 0) /* no digits? */
  228. return l_mathop(0.0); /* invalid format */
  229. *endptr = cast_charp(s); /* valid up to here */
  230. e *= 4; /* each digit multiplies/divides value by 2^4 */
  231. if (*s == 'p' || *s == 'P') { /* exponent part? */
  232. int exp1 = 0; /* exponent value */
  233. int neg1; /* exponent sign */
  234. s++; /* skip 'p' */
  235. neg1 = isneg(&s); /* sign */
  236. if (!lisdigit(cast_uchar(*s)))
  237. return l_mathop(0.0); /* invalid; must have at least one digit */
  238. while (lisdigit(cast_uchar(*s))) /* read exponent */
  239. exp1 = exp1 * 10 + *(s++) - '0';
  240. if (neg1) exp1 = -exp1;
  241. e += exp1;
  242. *endptr = cast_charp(s); /* valid up to here */
  243. }
  244. if (neg) r = -r;
  245. return l_mathop(ldexp)(r, e);
  246. }
  247. #endif
  248. /* }====================================================== */
  249. /* maximum length of a numeral to be converted to a number */
  250. #if !defined (L_MAXLENNUM)
  251. #define L_MAXLENNUM 200
  252. #endif
  253. /*
  254. ** Convert string 's' to a Lua number (put in 'result'). Return NULL on
  255. ** fail or the address of the ending '\0' on success. ('mode' == 'x')
  256. ** means a hexadecimal numeral.
  257. */
  258. static const char *l_str2dloc (const char *s, lua_Number *result, int mode) {
  259. char *endptr;
  260. *result = (mode == 'x') ? lua_strx2number(s, &endptr) /* try to convert */
  261. : lua_str2number(s, &endptr);
  262. if (endptr == s) return NULL; /* nothing recognized? */
  263. while (lisspace(cast_uchar(*endptr))) endptr++; /* skip trailing spaces */
  264. return (*endptr == '\0') ? endptr : NULL; /* OK iff no trailing chars */
  265. }
  266. /*
  267. ** Convert string 's' to a Lua number (put in 'result') handling the
  268. ** current locale.
  269. ** This function accepts both the current locale or a dot as the radix
  270. ** mark. If the conversion fails, it may mean number has a dot but
  271. ** locale accepts something else. In that case, the code copies 's'
  272. ** to a buffer (because 's' is read-only), changes the dot to the
  273. ** current locale radix mark, and tries to convert again.
  274. ** The variable 'mode' checks for special characters in the string:
  275. ** - 'n' means 'inf' or 'nan' (which should be rejected)
  276. ** - 'x' means a hexadecimal numeral
  277. ** - '.' just optimizes the search for the common case (no special chars)
  278. */
  279. static const char *l_str2d (const char *s, lua_Number *result) {
  280. const char *endptr;
  281. const char *pmode = strpbrk(s, ".xXnN"); /* look for special chars */
  282. int mode = pmode ? ltolower(cast_uchar(*pmode)) : 0;
  283. if (mode == 'n') /* reject 'inf' and 'nan' */
  284. return NULL;
  285. endptr = l_str2dloc(s, result, mode); /* try to convert */
  286. if (endptr == NULL) { /* failed? may be a different locale */
  287. char buff[L_MAXLENNUM + 1];
  288. const char *pdot = strchr(s, '.');
  289. if (pdot == NULL || strlen(s) > L_MAXLENNUM)
  290. return NULL; /* string too long or no dot; fail */
  291. strcpy(buff, s); /* copy string to buffer */
  292. buff[pdot - s] = lua_getlocaledecpoint(); /* correct decimal point */
  293. endptr = l_str2dloc(buff, result, mode); /* try again */
  294. if (endptr != NULL)
  295. endptr = s + (endptr - buff); /* make relative to 's' */
  296. }
  297. return endptr;
  298. }
  299. #define MAXBY10 cast(lua_Unsigned, LUA_MAXINTEGER / 10)
  300. #define MAXLASTD cast_int(LUA_MAXINTEGER % 10)
  301. static const char *l_str2int (const char *s, lua_Integer *result) {
  302. lua_Unsigned a = 0;
  303. int empty = 1;
  304. int neg;
  305. while (lisspace(cast_uchar(*s))) s++; /* skip initial spaces */
  306. neg = isneg(&s);
  307. if (s[0] == '0' &&
  308. (s[1] == 'x' || s[1] == 'X')) { /* hex? */
  309. s += 2; /* skip '0x' */
  310. for (; lisxdigit(cast_uchar(*s)); s++) {
  311. a = a * 16 + luaO_hexavalue(*s);
  312. empty = 0;
  313. }
  314. }
  315. else { /* decimal */
  316. for (; lisdigit(cast_uchar(*s)); s++) {
  317. int d = *s - '0';
  318. if (a >= MAXBY10 && (a > MAXBY10 || d > MAXLASTD + neg)) /* overflow? */
  319. return NULL; /* do not accept it (as integer) */
  320. a = a * 10 + cast_uint(d);
  321. empty = 0;
  322. }
  323. }
  324. while (lisspace(cast_uchar(*s))) s++; /* skip trailing spaces */
  325. if (empty || *s != '\0') return NULL; /* something wrong in the numeral */
  326. else {
  327. *result = l_castU2S((neg) ? 0u - a : a);
  328. return s;
  329. }
  330. }
  331. size_t luaO_str2num (const char *s, TValue *o) {
  332. lua_Integer i; lua_Number n;
  333. const char *e;
  334. if ((e = l_str2int(s, &i)) != NULL) { /* try as an integer */
  335. setivalue(o, i);
  336. }
  337. else if ((e = l_str2d(s, &n)) != NULL) { /* else try as a float */
  338. setfltvalue(o, n);
  339. }
  340. else
  341. return 0; /* conversion failed */
  342. return ct_diff2sz(e - s) + 1; /* success; return string size */
  343. }
  344. int luaO_utf8esc (char *buff, l_uint32 x) {
  345. int n = 1; /* number of bytes put in buffer (backwards) */
  346. lua_assert(x <= 0x7FFFFFFFu);
  347. if (x < 0x80) /* ASCII? */
  348. buff[UTF8BUFFSZ - 1] = cast_char(x);
  349. else { /* need continuation bytes */
  350. unsigned int mfb = 0x3f; /* maximum that fits in first byte */
  351. do { /* add continuation bytes */
  352. buff[UTF8BUFFSZ - (n++)] = cast_char(0x80 | (x & 0x3f));
  353. x >>= 6; /* remove added bits */
  354. mfb >>= 1; /* now there is one less bit available in first byte */
  355. } while (x > mfb); /* still needs continuation byte? */
  356. buff[UTF8BUFFSZ - n] = cast_char((~mfb << 1) | x); /* add first byte */
  357. }
  358. return n;
  359. }
  360. /*
  361. ** The size of the buffer for the conversion of a number to a string
  362. ** 'LUA_N2SBUFFSZ' must be enough to accommodate both LUA_INTEGER_FMT
  363. ** and LUA_NUMBER_FMT. For a long long int, this is 19 digits plus a
  364. ** sign and a final '\0', adding to 21. For a long double, it can go to
  365. ** a sign, the dot, an exponent letter, an exponent sign, 4 exponent
  366. ** digits, the final '\0', plus the significant digits, which are
  367. ** approximately the *_DIG attribute.
  368. */
  369. #if LUA_N2SBUFFSZ < (20 + l_floatatt(DIG))
  370. #error "invalid value for LUA_N2SBUFFSZ"
  371. #endif
  372. /*
  373. ** Convert a float to a string, adding it to a buffer. First try with
  374. ** a not too large number of digits, to avoid noise (for instance,
  375. ** 1.1 going to "1.1000000000000001"). If that lose precision, so
  376. ** that reading the result back gives a different number, then do the
  377. ** conversion again with extra precision. Moreover, if the numeral looks
  378. ** like an integer (without a decimal point or an exponent), add ".0" to
  379. ** its end.
  380. */
  381. static int tostringbuffFloat (lua_Number n, char *buff) {
  382. /* first conversion */
  383. int len = l_sprintf(buff, LUA_N2SBUFFSZ, LUA_NUMBER_FMT,
  384. (LUAI_UACNUMBER)n);
  385. lua_Number check = lua_str2number(buff, NULL); /* read it back */
  386. if (check != n) { /* not enough precision? */
  387. /* convert again with more precision */
  388. len = l_sprintf(buff, LUA_N2SBUFFSZ, LUA_NUMBER_FMT_N,
  389. (LUAI_UACNUMBER)n);
  390. }
  391. /* looks like an integer? */
  392. if (buff[strspn(buff, "-0123456789")] == '\0') {
  393. buff[len++] = lua_getlocaledecpoint();
  394. buff[len++] = '0'; /* adds '.0' to result */
  395. }
  396. return len;
  397. }
  398. /*
  399. ** Convert a number object to a string, adding it to a buffer.
  400. */
  401. unsigned luaO_tostringbuff (const TValue *obj, char *buff) {
  402. int len;
  403. lua_assert(ttisnumber(obj));
  404. if (ttisinteger(obj))
  405. len = lua_integer2str(buff, LUA_N2SBUFFSZ, ivalue(obj));
  406. else
  407. len = tostringbuffFloat(fltvalue(obj), buff);
  408. lua_assert(len < LUA_N2SBUFFSZ);
  409. return cast_uint(len);
  410. }
  411. /*
  412. ** Convert a number object to a Lua string, replacing the value at 'obj'
  413. */
  414. void luaO_tostring (lua_State *L, TValue *obj) {
  415. char buff[LUA_N2SBUFFSZ];
  416. unsigned len = luaO_tostringbuff(obj, buff);
  417. setsvalue(L, obj, luaS_newlstr(L, buff, len));
  418. }
  419. /*
  420. ** {==================================================================
  421. ** 'luaO_pushvfstring'
  422. ** ===================================================================
  423. */
  424. /*
  425. ** Size for buffer space used by 'luaO_pushvfstring'. It should be
  426. ** (LUA_IDSIZE + LUA_N2SBUFFSZ) + a minimal space for basic messages,
  427. ** so that 'luaG_addinfo' can work directly on the static buffer.
  428. */
  429. #define BUFVFS cast_uint(LUA_IDSIZE + LUA_N2SBUFFSZ + 95)
  430. /*
  431. ** Buffer used by 'luaO_pushvfstring'. 'err' signals an error while
  432. ** building result (memory error [1] or buffer overflow [2]).
  433. */
  434. typedef struct BuffFS {
  435. lua_State *L;
  436. char *b;
  437. size_t buffsize;
  438. size_t blen; /* length of string in 'buff' */
  439. int err;
  440. char space[BUFVFS]; /* initial buffer */
  441. } BuffFS;
  442. static void initbuff (lua_State *L, BuffFS *buff) {
  443. buff->L = L;
  444. buff->b = buff->space;
  445. buff->buffsize = sizeof(buff->space);
  446. buff->blen = 0;
  447. buff->err = 0;
  448. }
  449. /*
  450. ** Push final result from 'luaO_pushvfstring'. This function may raise
  451. ** errors explicitly or through memory errors, so it must run protected.
  452. */
  453. static void pushbuff (lua_State *L, void *ud) {
  454. BuffFS *buff = cast(BuffFS*, ud);
  455. switch (buff->err) {
  456. case 1: /* memory error */
  457. luaD_throw(L, LUA_ERRMEM);
  458. break;
  459. case 2: /* length overflow: Add "..." at the end of result */
  460. if (buff->buffsize - buff->blen < 3)
  461. strcpy(buff->b + buff->blen - 3, "..."); /* 'blen' must be > 3 */
  462. else { /* there is enough space left for the "..." */
  463. strcpy(buff->b + buff->blen, "...");
  464. buff->blen += 3;
  465. }
  466. /* FALLTHROUGH */
  467. default: { /* no errors, but it can raise one creating the new string */
  468. TString *ts = luaS_newlstr(L, buff->b, buff->blen);
  469. setsvalue2s(L, L->top.p, ts);
  470. L->top.p++;
  471. }
  472. }
  473. }
  474. static const char *clearbuff (BuffFS *buff) {
  475. lua_State *L = buff->L;
  476. const char *res;
  477. if (luaD_rawrunprotected(L, pushbuff, buff) != LUA_OK) /* errors? */
  478. res = NULL; /* error message is on the top of the stack */
  479. else
  480. res = getstr(tsvalue(s2v(L->top.p - 1)));
  481. if (buff->b != buff->space) /* using dynamic buffer? */
  482. luaM_freearray(L, buff->b, buff->buffsize); /* free it */
  483. return res;
  484. }
  485. static void addstr2buff (BuffFS *buff, const char *str, size_t slen) {
  486. size_t left = buff->buffsize - buff->blen; /* space left in the buffer */
  487. if (buff->err) /* do nothing else after an error */
  488. return;
  489. if (slen > left) { /* new string doesn't fit into current buffer? */
  490. if (slen > ((MAX_SIZE/2) - buff->blen)) { /* overflow? */
  491. memcpy(buff->b + buff->blen, str, left); /* copy what it can */
  492. buff->blen = buff->buffsize;
  493. buff->err = 2; /* doesn't add anything else */
  494. return;
  495. }
  496. else {
  497. size_t newsize = buff->buffsize + slen; /* limited to MAX_SIZE/2 */
  498. char *newb =
  499. (buff->b == buff->space) /* still using static space? */
  500. ? luaM_reallocvector(buff->L, NULL, 0, newsize, char)
  501. : luaM_reallocvector(buff->L, buff->b, buff->buffsize, newsize,
  502. char);
  503. if (newb == NULL) { /* allocation error? */
  504. buff->err = 1; /* signal a memory error */
  505. return;
  506. }
  507. if (buff->b == buff->space) /* new buffer (not reallocated)? */
  508. memcpy(newb, buff->b, buff->blen); /* copy previous content */
  509. buff->b = newb; /* set new (larger) buffer... */
  510. buff->buffsize = newsize; /* ...and its new size */
  511. }
  512. }
  513. memcpy(buff->b + buff->blen, str, slen); /* copy new content */
  514. buff->blen += slen;
  515. }
  516. /*
  517. ** Add a numeral to the buffer.
  518. */
  519. static void addnum2buff (BuffFS *buff, TValue *num) {
  520. char numbuff[LUA_N2SBUFFSZ];
  521. unsigned len = luaO_tostringbuff(num, numbuff);
  522. addstr2buff(buff, numbuff, len);
  523. }
  524. /*
  525. ** this function handles only '%d', '%c', '%f', '%p', '%s', and '%%'
  526. conventional formats, plus Lua-specific '%I' and '%U'
  527. */
  528. const char *luaO_pushvfstring (lua_State *L, const char *fmt, va_list argp) {
  529. BuffFS buff; /* holds last part of the result */
  530. const char *e; /* points to next '%' */
  531. initbuff(L, &buff);
  532. while ((e = strchr(fmt, '%')) != NULL) {
  533. addstr2buff(&buff, fmt, ct_diff2sz(e - fmt)); /* add 'fmt' up to '%' */
  534. switch (*(e + 1)) { /* conversion specifier */
  535. case 's': { /* zero-terminated string */
  536. const char *s = va_arg(argp, char *);
  537. if (s == NULL) s = "(null)";
  538. addstr2buff(&buff, s, strlen(s));
  539. break;
  540. }
  541. case 'c': { /* an 'int' as a character */
  542. char c = cast_char(va_arg(argp, int));
  543. addstr2buff(&buff, &c, sizeof(char));
  544. break;
  545. }
  546. case 'd': { /* an 'int' */
  547. TValue num;
  548. setivalue(&num, va_arg(argp, int));
  549. addnum2buff(&buff, &num);
  550. break;
  551. }
  552. case 'I': { /* a 'lua_Integer' */
  553. TValue num;
  554. setivalue(&num, cast_Integer(va_arg(argp, l_uacInt)));
  555. addnum2buff(&buff, &num);
  556. break;
  557. }
  558. case 'f': { /* a 'lua_Number' */
  559. TValue num;
  560. setfltvalue(&num, cast_num(va_arg(argp, l_uacNumber)));
  561. addnum2buff(&buff, &num);
  562. break;
  563. }
  564. case 'p': { /* a pointer */
  565. char bf[LUA_N2SBUFFSZ]; /* enough space for '%p' */
  566. void *p = va_arg(argp, void *);
  567. int len = lua_pointer2str(bf, LUA_N2SBUFFSZ, p);
  568. addstr2buff(&buff, bf, cast_uint(len));
  569. break;
  570. }
  571. case 'U': { /* an 'unsigned long' as a UTF-8 sequence */
  572. char bf[UTF8BUFFSZ];
  573. unsigned long arg = va_arg(argp, unsigned long);
  574. int len = luaO_utf8esc(bf, cast(l_uint32, arg));
  575. addstr2buff(&buff, bf + UTF8BUFFSZ - len, cast_uint(len));
  576. break;
  577. }
  578. case '%': {
  579. addstr2buff(&buff, "%", 1);
  580. break;
  581. }
  582. default: {
  583. addstr2buff(&buff, e, 2); /* keep unknown format in the result */
  584. break;
  585. }
  586. }
  587. fmt = e + 2; /* skip '%' and the specifier */
  588. }
  589. addstr2buff(&buff, fmt, strlen(fmt)); /* rest of 'fmt' */
  590. return clearbuff(&buff); /* empty buffer into a new string */
  591. }
  592. const char *luaO_pushfstring (lua_State *L, const char *fmt, ...) {
  593. const char *msg;
  594. va_list argp;
  595. va_start(argp, fmt);
  596. msg = luaO_pushvfstring(L, fmt, argp);
  597. va_end(argp);
  598. if (msg == NULL) /* error? */
  599. luaD_throw(L, LUA_ERRMEM);
  600. return msg;
  601. }
  602. /* }================================================================== */
  603. #define RETS "..."
  604. #define PRE "[string \""
  605. #define POS "\"]"
  606. #define addstr(a,b,l) ( memcpy(a,b,(l) * sizeof(char)), a += (l) )
  607. void luaO_chunkid (char *out, const char *source, size_t srclen) {
  608. size_t bufflen = LUA_IDSIZE; /* free space in buffer */
  609. if (*source == '=') { /* 'literal' source */
  610. if (srclen <= bufflen) /* small enough? */
  611. memcpy(out, source + 1, srclen * sizeof(char));
  612. else { /* truncate it */
  613. addstr(out, source + 1, bufflen - 1);
  614. *out = '\0';
  615. }
  616. }
  617. else if (*source == '@') { /* file name */
  618. if (srclen <= bufflen) /* small enough? */
  619. memcpy(out, source + 1, srclen * sizeof(char));
  620. else { /* add '...' before rest of name */
  621. addstr(out, RETS, LL(RETS));
  622. bufflen -= LL(RETS);
  623. memcpy(out, source + 1 + srclen - bufflen, bufflen * sizeof(char));
  624. }
  625. }
  626. else { /* string; format as [string "source"] */
  627. const char *nl = strchr(source, '\n'); /* find first new line (if any) */
  628. addstr(out, PRE, LL(PRE)); /* add prefix */
  629. bufflen -= LL(PRE RETS POS) + 1; /* save space for prefix+suffix+'\0' */
  630. if (srclen < bufflen && nl == NULL) { /* small one-line source? */
  631. addstr(out, source, srclen); /* keep it */
  632. }
  633. else {
  634. if (nl != NULL)
  635. srclen = ct_diff2sz(nl - source); /* stop at first newline */
  636. if (srclen > bufflen) srclen = bufflen;
  637. addstr(out, source, srclen);
  638. addstr(out, RETS, LL(RETS));
  639. }
  640. memcpy(out, POS, (LL(POS) + 1) * sizeof(char));
  641. }
  642. }