lobject.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689
  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. if (lisdigit(c)) return cast_byte(c - '0');
  177. else return cast_byte((ltolower(c) - 'a') + 10);
  178. }
  179. static int isneg (const char **s) {
  180. if (**s == '-') { (*s)++; return 1; }
  181. else if (**s == '+') (*s)++;
  182. return 0;
  183. }
  184. /*
  185. ** {==================================================================
  186. ** Lua's implementation for 'lua_strx2number'
  187. ** ===================================================================
  188. */
  189. #if !defined(lua_strx2number)
  190. /* maximum number of significant digits to read (to avoid overflows
  191. even with single floats) */
  192. #define MAXSIGDIG 30
  193. /*
  194. ** convert a hexadecimal numeric string to a number, following
  195. ** C99 specification for 'strtod'
  196. */
  197. static lua_Number lua_strx2number (const char *s, char **endptr) {
  198. int dot = lua_getlocaledecpoint();
  199. lua_Number r = l_mathop(0.0); /* result (accumulator) */
  200. int sigdig = 0; /* number of significant digits */
  201. int nosigdig = 0; /* number of non-significant digits */
  202. int e = 0; /* exponent correction */
  203. int neg; /* 1 if number is negative */
  204. int hasdot = 0; /* true after seen a dot */
  205. *endptr = cast_charp(s); /* nothing is valid yet */
  206. while (lisspace(cast_uchar(*s))) s++; /* skip initial spaces */
  207. neg = isneg(&s); /* check sign */
  208. if (!(*s == '0' && (*(s + 1) == 'x' || *(s + 1) == 'X'))) /* check '0x' */
  209. return l_mathop(0.0); /* invalid format (no '0x') */
  210. for (s += 2; ; s++) { /* skip '0x' and read numeral */
  211. if (*s == dot) {
  212. if (hasdot) break; /* second dot? stop loop */
  213. else hasdot = 1;
  214. }
  215. else if (lisxdigit(cast_uchar(*s))) {
  216. if (sigdig == 0 && *s == '0') /* non-significant digit (zero)? */
  217. nosigdig++;
  218. else if (++sigdig <= MAXSIGDIG) /* can read it without overflow? */
  219. r = (r * l_mathop(16.0)) + luaO_hexavalue(*s);
  220. else e++; /* too many digits; ignore, but still count for exponent */
  221. if (hasdot) e--; /* decimal digit? correct exponent */
  222. }
  223. else break; /* neither a dot nor a digit */
  224. }
  225. if (nosigdig + sigdig == 0) /* no digits? */
  226. return l_mathop(0.0); /* invalid format */
  227. *endptr = cast_charp(s); /* valid up to here */
  228. e *= 4; /* each digit multiplies/divides value by 2^4 */
  229. if (*s == 'p' || *s == 'P') { /* exponent part? */
  230. int exp1 = 0; /* exponent value */
  231. int neg1; /* exponent sign */
  232. s++; /* skip 'p' */
  233. neg1 = isneg(&s); /* sign */
  234. if (!lisdigit(cast_uchar(*s)))
  235. return l_mathop(0.0); /* invalid; must have at least one digit */
  236. while (lisdigit(cast_uchar(*s))) /* read exponent */
  237. exp1 = exp1 * 10 + *(s++) - '0';
  238. if (neg1) exp1 = -exp1;
  239. e += exp1;
  240. *endptr = cast_charp(s); /* valid up to here */
  241. }
  242. if (neg) r = -r;
  243. return l_mathop(ldexp)(r, e);
  244. }
  245. #endif
  246. /* }====================================================== */
  247. /* maximum length of a numeral to be converted to a number */
  248. #if !defined (L_MAXLENNUM)
  249. #define L_MAXLENNUM 200
  250. #endif
  251. /*
  252. ** Convert string 's' to a Lua number (put in 'result'). Return NULL on
  253. ** fail or the address of the ending '\0' on success. ('mode' == 'x')
  254. ** means a hexadecimal numeral.
  255. */
  256. static const char *l_str2dloc (const char *s, lua_Number *result, int mode) {
  257. char *endptr;
  258. *result = (mode == 'x') ? lua_strx2number(s, &endptr) /* try to convert */
  259. : lua_str2number(s, &endptr);
  260. if (endptr == s) return NULL; /* nothing recognized? */
  261. while (lisspace(cast_uchar(*endptr))) endptr++; /* skip trailing spaces */
  262. return (*endptr == '\0') ? endptr : NULL; /* OK iff no trailing chars */
  263. }
  264. /*
  265. ** Convert string 's' to a Lua number (put in 'result') handling the
  266. ** current locale.
  267. ** This function accepts both the current locale or a dot as the radix
  268. ** mark. If the conversion fails, it may mean number has a dot but
  269. ** locale accepts something else. In that case, the code copies 's'
  270. ** to a buffer (because 's' is read-only), changes the dot to the
  271. ** current locale radix mark, and tries to convert again.
  272. ** The variable 'mode' checks for special characters in the string:
  273. ** - 'n' means 'inf' or 'nan' (which should be rejected)
  274. ** - 'x' means a hexadecimal numeral
  275. ** - '.' just optimizes the search for the common case (no special chars)
  276. */
  277. static const char *l_str2d (const char *s, lua_Number *result) {
  278. const char *endptr;
  279. const char *pmode = strpbrk(s, ".xXnN"); /* look for special chars */
  280. int mode = pmode ? ltolower(cast_uchar(*pmode)) : 0;
  281. if (mode == 'n') /* reject 'inf' and 'nan' */
  282. return NULL;
  283. endptr = l_str2dloc(s, result, mode); /* try to convert */
  284. if (endptr == NULL) { /* failed? may be a different locale */
  285. char buff[L_MAXLENNUM + 1];
  286. const char *pdot = strchr(s, '.');
  287. if (pdot == NULL || strlen(s) > L_MAXLENNUM)
  288. return NULL; /* string too long or no dot; fail */
  289. strcpy(buff, s); /* copy string to buffer */
  290. buff[pdot - s] = lua_getlocaledecpoint(); /* correct decimal point */
  291. endptr = l_str2dloc(buff, result, mode); /* try again */
  292. if (endptr != NULL)
  293. endptr = s + (endptr - buff); /* make relative to 's' */
  294. }
  295. return endptr;
  296. }
  297. #define MAXBY10 cast(lua_Unsigned, LUA_MAXINTEGER / 10)
  298. #define MAXLASTD cast_int(LUA_MAXINTEGER % 10)
  299. static const char *l_str2int (const char *s, lua_Integer *result) {
  300. lua_Unsigned a = 0;
  301. int empty = 1;
  302. int neg;
  303. while (lisspace(cast_uchar(*s))) s++; /* skip initial spaces */
  304. neg = isneg(&s);
  305. if (s[0] == '0' &&
  306. (s[1] == 'x' || s[1] == 'X')) { /* hex? */
  307. s += 2; /* skip '0x' */
  308. for (; lisxdigit(cast_uchar(*s)); s++) {
  309. a = a * 16 + luaO_hexavalue(*s);
  310. empty = 0;
  311. }
  312. }
  313. else { /* decimal */
  314. for (; lisdigit(cast_uchar(*s)); s++) {
  315. int d = *s - '0';
  316. if (a >= MAXBY10 && (a > MAXBY10 || d > MAXLASTD + neg)) /* overflow? */
  317. return NULL; /* do not accept it (as integer) */
  318. a = a * 10 + cast_uint(d);
  319. empty = 0;
  320. }
  321. }
  322. while (lisspace(cast_uchar(*s))) s++; /* skip trailing spaces */
  323. if (empty || *s != '\0') return NULL; /* something wrong in the numeral */
  324. else {
  325. *result = l_castU2S((neg) ? 0u - a : a);
  326. return s;
  327. }
  328. }
  329. size_t luaO_str2num (const char *s, TValue *o) {
  330. lua_Integer i; lua_Number n;
  331. const char *e;
  332. if ((e = l_str2int(s, &i)) != NULL) { /* try as an integer */
  333. setivalue(o, i);
  334. }
  335. else if ((e = l_str2d(s, &n)) != NULL) { /* else try as a float */
  336. setfltvalue(o, n);
  337. }
  338. else
  339. return 0; /* conversion failed */
  340. return ct_diff2sz(e - s) + 1; /* success; return string size */
  341. }
  342. int luaO_utf8esc (char *buff, unsigned long x) {
  343. int n = 1; /* number of bytes put in buffer (backwards) */
  344. lua_assert(x <= 0x7FFFFFFFu);
  345. if (x < 0x80) /* ascii? */
  346. buff[UTF8BUFFSZ - 1] = cast_char(x);
  347. else { /* need continuation bytes */
  348. unsigned int mfb = 0x3f; /* maximum that fits in first byte */
  349. do { /* add continuation bytes */
  350. buff[UTF8BUFFSZ - (n++)] = cast_char(0x80 | (x & 0x3f));
  351. x >>= 6; /* remove added bits */
  352. mfb >>= 1; /* now there is one less bit available in first byte */
  353. } while (x > mfb); /* still needs continuation byte? */
  354. buff[UTF8BUFFSZ - n] = cast_char((~mfb << 1) | x); /* add first byte */
  355. }
  356. return n;
  357. }
  358. /*
  359. ** Maximum length of the conversion of a number to a string. Must be
  360. ** enough to accommodate both LUA_INTEGER_FMT and LUA_NUMBER_FMT.
  361. ** For a long long int, this is 19 digits plus a sign and a final '\0',
  362. ** adding to 21. For a long double, it can go to a sign, the dot, an
  363. ** exponent letter, an exponent sign, 4 exponent digits, the final
  364. ** '\0', plus the significant digits, which are approximately the *_DIG
  365. ** attribute.
  366. */
  367. #define MAXNUMBER2STR (20 + l_floatatt(DIG))
  368. /*
  369. ** Convert a float to a string, adding it to a buffer. First try with
  370. ** a not too large number of digits, to avoid noise (for instance,
  371. ** 1.1 going to "1.1000000000000001"). If that lose precision, so
  372. ** that reading the result back gives a different number, then do the
  373. ** conversion again with extra precision. Moreover, if the numeral looks
  374. ** like an integer (without a decimal point or an exponent), add ".0" to
  375. ** its end.
  376. */
  377. static int tostringbuffFloat (lua_Number n, char *buff) {
  378. /* first conversion */
  379. int len = l_sprintf(buff, MAXNUMBER2STR, LUA_NUMBER_FMT,
  380. (LUAI_UACNUMBER)n);
  381. lua_Number check = lua_str2number(buff, NULL); /* read it back */
  382. if (check != n) { /* not enough precision? */
  383. /* convert again with more precision */
  384. len = l_sprintf(buff, MAXNUMBER2STR, LUA_NUMBER_FMT_N,
  385. (LUAI_UACNUMBER)n);
  386. }
  387. /* looks like an integer? */
  388. if (buff[strspn(buff, "-0123456789")] == '\0') {
  389. buff[len++] = lua_getlocaledecpoint();
  390. buff[len++] = '0'; /* adds '.0' to result */
  391. }
  392. return len;
  393. }
  394. /*
  395. ** Convert a number object to a string, adding it to a buffer.
  396. */
  397. static unsigned tostringbuff (TValue *obj, char *buff) {
  398. int len;
  399. lua_assert(ttisnumber(obj));
  400. if (ttisinteger(obj))
  401. len = lua_integer2str(buff, MAXNUMBER2STR, ivalue(obj));
  402. else
  403. len = tostringbuffFloat(fltvalue(obj), buff);
  404. lua_assert(len < MAXNUMBER2STR);
  405. return cast_uint(len);
  406. }
  407. /*
  408. ** Convert a number object to a Lua string, replacing the value at 'obj'
  409. */
  410. void luaO_tostring (lua_State *L, TValue *obj) {
  411. char buff[MAXNUMBER2STR];
  412. unsigned len = tostringbuff(obj, buff);
  413. setsvalue(L, obj, luaS_newlstr(L, buff, len));
  414. }
  415. /*
  416. ** {==================================================================
  417. ** 'luaO_pushvfstring'
  418. ** ===================================================================
  419. */
  420. /*
  421. ** Size for buffer space used by 'luaO_pushvfstring'. It should be
  422. ** (LUA_IDSIZE + MAXNUMBER2STR) + a minimal space for basic messages,
  423. ** so that 'luaG_addinfo' can work directly on the buffer.
  424. */
  425. #define BUFVFS cast_uint(LUA_IDSIZE + MAXNUMBER2STR + 95)
  426. /* buffer used by 'luaO_pushvfstring' */
  427. typedef struct BuffFS {
  428. lua_State *L;
  429. int pushed; /* true if there is a part of the result on the stack */
  430. unsigned blen; /* length of partial string in 'space' */
  431. char space[BUFVFS]; /* holds last part of the result */
  432. } BuffFS;
  433. /*
  434. ** Push given string to the stack, as part of the result, and
  435. ** join it to previous partial result if there is one.
  436. ** It may call 'luaV_concat' while using one slot from EXTRA_STACK.
  437. ** This call cannot invoke metamethods, as both operands must be
  438. ** strings. It can, however, raise an error if the result is too
  439. ** long. In that case, 'luaV_concat' frees the extra slot before
  440. ** raising the error.
  441. */
  442. static void pushstr (BuffFS *buff, const char *str, size_t lstr) {
  443. lua_State *L = buff->L;
  444. setsvalue2s(L, L->top.p, luaS_newlstr(L, str, lstr));
  445. L->top.p++; /* may use one slot from EXTRA_STACK */
  446. if (!buff->pushed) /* no previous string on the stack? */
  447. buff->pushed = 1; /* now there is one */
  448. else /* join previous string with new one */
  449. luaV_concat(L, 2);
  450. }
  451. /*
  452. ** empty the buffer space into the stack
  453. */
  454. static void clearbuff (BuffFS *buff) {
  455. pushstr(buff, buff->space, buff->blen); /* push buffer contents */
  456. buff->blen = 0; /* space now is empty */
  457. }
  458. /*
  459. ** Get a space of size 'sz' in the buffer. If buffer has not enough
  460. ** space, empty it. 'sz' must fit in an empty buffer.
  461. */
  462. static char *getbuff (BuffFS *buff, unsigned sz) {
  463. lua_assert(buff->blen <= BUFVFS); lua_assert(sz <= BUFVFS);
  464. if (sz > BUFVFS - buff->blen) /* not enough space? */
  465. clearbuff(buff);
  466. return buff->space + buff->blen;
  467. }
  468. #define addsize(b,sz) ((b)->blen += (sz))
  469. /*
  470. ** Add 'str' to the buffer. If string is larger than the buffer space,
  471. ** push the string directly to the stack.
  472. */
  473. static void addstr2buff (BuffFS *buff, const char *str, size_t slen) {
  474. if (slen <= BUFVFS) { /* does string fit into buffer? */
  475. char *bf = getbuff(buff, cast_uint(slen));
  476. memcpy(bf, str, slen); /* add string to buffer */
  477. addsize(buff, cast_uint(slen));
  478. }
  479. else { /* string larger than buffer */
  480. clearbuff(buff); /* string comes after buffer's content */
  481. pushstr(buff, str, slen); /* push string */
  482. }
  483. }
  484. /*
  485. ** Add a numeral to the buffer.
  486. */
  487. static void addnum2buff (BuffFS *buff, TValue *num) {
  488. char *numbuff = getbuff(buff, MAXNUMBER2STR);
  489. unsigned len = tostringbuff(num, numbuff); /* format number into 'numbuff' */
  490. addsize(buff, len);
  491. }
  492. /*
  493. ** this function handles only '%d', '%c', '%f', '%p', '%s', and '%%'
  494. conventional formats, plus Lua-specific '%I' and '%U'
  495. */
  496. const char *luaO_pushvfstring (lua_State *L, const char *fmt, va_list argp) {
  497. BuffFS buff; /* holds last part of the result */
  498. const char *e; /* points to next '%' */
  499. buff.pushed = 0; buff.blen = 0;
  500. buff.L = L;
  501. while ((e = strchr(fmt, '%')) != NULL) {
  502. addstr2buff(&buff, fmt, ct_diff2sz(e - fmt)); /* add 'fmt' up to '%' */
  503. switch (*(e + 1)) { /* conversion specifier */
  504. case 's': { /* zero-terminated string */
  505. const char *s = va_arg(argp, char *);
  506. if (s == NULL) s = "(null)";
  507. addstr2buff(&buff, s, strlen(s));
  508. break;
  509. }
  510. case 'c': { /* an 'int' as a character */
  511. char c = cast_char(va_arg(argp, int));
  512. addstr2buff(&buff, &c, sizeof(char));
  513. break;
  514. }
  515. case 'd': { /* an 'int' */
  516. TValue num;
  517. setivalue(&num, va_arg(argp, int));
  518. addnum2buff(&buff, &num);
  519. break;
  520. }
  521. case 'I': { /* a 'lua_Integer' */
  522. TValue num;
  523. setivalue(&num, cast(lua_Integer, va_arg(argp, l_uacInt)));
  524. addnum2buff(&buff, &num);
  525. break;
  526. }
  527. case 'f': { /* a 'lua_Number' */
  528. TValue num;
  529. setfltvalue(&num, cast_num(va_arg(argp, l_uacNumber)));
  530. addnum2buff(&buff, &num);
  531. break;
  532. }
  533. case 'p': { /* a pointer */
  534. const unsigned sz = 3 * sizeof(void*) + 8; /* enough space for '%p' */
  535. char *bf = getbuff(&buff, sz);
  536. void *p = va_arg(argp, void *);
  537. int len = lua_pointer2str(bf, sz, p);
  538. addsize(&buff, cast_uint(len));
  539. break;
  540. }
  541. case 'U': { /* an 'unsigned long' as a UTF-8 sequence */
  542. char bf[UTF8BUFFSZ];
  543. int len = luaO_utf8esc(bf, va_arg(argp, unsigned long));
  544. addstr2buff(&buff, bf + UTF8BUFFSZ - len, cast_uint(len));
  545. break;
  546. }
  547. case '%': {
  548. addstr2buff(&buff, "%", 1);
  549. break;
  550. }
  551. default: {
  552. luaG_runerror(L, "invalid option '%%%c' to 'lua_pushfstring'",
  553. *(e + 1));
  554. }
  555. }
  556. fmt = e + 2; /* skip '%' and the specifier */
  557. }
  558. addstr2buff(&buff, fmt, strlen(fmt)); /* rest of 'fmt' */
  559. clearbuff(&buff); /* empty buffer into the stack */
  560. lua_assert(buff.pushed == 1);
  561. return getstr(tsvalue(s2v(L->top.p - 1)));
  562. }
  563. const char *luaO_pushfstring (lua_State *L, const char *fmt, ...) {
  564. const char *msg;
  565. va_list argp;
  566. va_start(argp, fmt);
  567. msg = luaO_pushvfstring(L, fmt, argp);
  568. va_end(argp);
  569. return msg;
  570. }
  571. /* }================================================================== */
  572. #define RETS "..."
  573. #define PRE "[string \""
  574. #define POS "\"]"
  575. #define addstr(a,b,l) ( memcpy(a,b,(l) * sizeof(char)), a += (l) )
  576. void luaO_chunkid (char *out, const char *source, size_t srclen) {
  577. size_t bufflen = LUA_IDSIZE; /* free space in buffer */
  578. if (*source == '=') { /* 'literal' source */
  579. if (srclen <= bufflen) /* small enough? */
  580. memcpy(out, source + 1, srclen * sizeof(char));
  581. else { /* truncate it */
  582. addstr(out, source + 1, bufflen - 1);
  583. *out = '\0';
  584. }
  585. }
  586. else if (*source == '@') { /* file name */
  587. if (srclen <= bufflen) /* small enough? */
  588. memcpy(out, source + 1, srclen * sizeof(char));
  589. else { /* add '...' before rest of name */
  590. addstr(out, RETS, LL(RETS));
  591. bufflen -= LL(RETS);
  592. memcpy(out, source + 1 + srclen - bufflen, bufflen * sizeof(char));
  593. }
  594. }
  595. else { /* string; format as [string "source"] */
  596. const char *nl = strchr(source, '\n'); /* find first new line (if any) */
  597. addstr(out, PRE, LL(PRE)); /* add prefix */
  598. bufflen -= LL(PRE RETS POS) + 1; /* save space for prefix+suffix+'\0' */
  599. if (srclen < bufflen && nl == NULL) { /* small one-line source? */
  600. addstr(out, source, srclen); /* keep it */
  601. }
  602. else {
  603. if (nl != NULL)
  604. srclen = ct_diff2sz(nl - source); /* stop at first newline */
  605. if (srclen > bufflen) srclen = bufflen;
  606. addstr(out, source, srclen);
  607. addstr(out, RETS, LL(RETS));
  608. }
  609. memcpy(out, POS, (LL(POS) + 1) * sizeof(char));
  610. }
  611. }