lobject.c 23 KB

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