lib_string.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855
  1. /*
  2. ** String library.
  3. ** Copyright (C) 2005-2012 Mike Pall. See Copyright Notice in luajit.h
  4. **
  5. ** Major portions taken verbatim or adapted from the Lua interpreter.
  6. ** Copyright (C) 1994-2008 Lua.org, PUC-Rio. See Copyright Notice in lua.h
  7. */
  8. #include <stdio.h>
  9. #define lib_string_c
  10. #define LUA_LIB
  11. #include "lua.h"
  12. #include "lauxlib.h"
  13. #include "lualib.h"
  14. #include "lj_obj.h"
  15. #include "lj_gc.h"
  16. #include "lj_err.h"
  17. #include "lj_str.h"
  18. #include "lj_tab.h"
  19. #include "lj_state.h"
  20. #include "lj_ff.h"
  21. #include "lj_bcdump.h"
  22. #include "lj_char.h"
  23. #include "lj_lib.h"
  24. /* ------------------------------------------------------------------------ */
  25. #define LJLIB_MODULE_string
  26. LJLIB_ASM(string_len) LJLIB_REC(.)
  27. {
  28. lj_lib_checkstr(L, 1);
  29. return FFH_RETRY;
  30. }
  31. LJLIB_ASM(string_byte) LJLIB_REC(string_range 0)
  32. {
  33. GCstr *s = lj_lib_checkstr(L, 1);
  34. int32_t len = (int32_t)s->len;
  35. int32_t start = lj_lib_optint(L, 2, 1);
  36. int32_t stop = lj_lib_optint(L, 3, start);
  37. int32_t n, i;
  38. const unsigned char *p;
  39. if (stop < 0) stop += len+1;
  40. if (start < 0) start += len+1;
  41. if (start <= 0) start = 1;
  42. if (stop > len) stop = len;
  43. if (start > stop) return FFH_RES(0); /* Empty interval: return no results. */
  44. start--;
  45. n = stop - start;
  46. if ((uint32_t)n > LUAI_MAXCSTACK)
  47. lj_err_caller(L, LJ_ERR_STRSLC);
  48. lj_state_checkstack(L, (MSize)n);
  49. p = (const unsigned char *)strdata(s) + start;
  50. for (i = 0; i < n; i++)
  51. setintV(L->base + i-1, p[i]);
  52. return FFH_RES(n);
  53. }
  54. LJLIB_ASM(string_char)
  55. {
  56. int i, nargs = (int)(L->top - L->base);
  57. char *buf = lj_str_needbuf(L, &G(L)->tmpbuf, (size_t)nargs);
  58. for (i = 1; i <= nargs; i++) {
  59. int32_t k = lj_lib_checkint(L, i);
  60. if (!checku8(k))
  61. lj_err_arg(L, i, LJ_ERR_BADVAL);
  62. buf[i-1] = (char)k;
  63. }
  64. setstrV(L, L->base-1, lj_str_new(L, buf, (size_t)nargs));
  65. return FFH_RES(1);
  66. }
  67. LJLIB_ASM(string_sub) LJLIB_REC(string_range 1)
  68. {
  69. lj_lib_checkstr(L, 1);
  70. lj_lib_checkint(L, 2);
  71. setintV(L->base+2, lj_lib_optint(L, 3, -1));
  72. return FFH_RETRY;
  73. }
  74. LJLIB_ASM(string_rep)
  75. {
  76. GCstr *s = lj_lib_checkstr(L, 1);
  77. int32_t len = (int32_t)s->len;
  78. int32_t k = lj_lib_checkint(L, 2);
  79. int64_t tlen = (int64_t)k * len;
  80. const char *src;
  81. char *buf;
  82. if (k <= 0) return FFH_RETRY;
  83. if (tlen > LJ_MAX_STR)
  84. lj_err_caller(L, LJ_ERR_STROV);
  85. buf = lj_str_needbuf(L, &G(L)->tmpbuf, (MSize)tlen);
  86. if (len <= 1) return FFH_RETRY; /* ASM code only needed buffer resize. */
  87. src = strdata(s);
  88. do {
  89. int32_t i = 0;
  90. do { *buf++ = src[i++]; } while (i < len);
  91. } while (--k > 0);
  92. setstrV(L, L->base-1, lj_str_new(L, G(L)->tmpbuf.buf, (size_t)tlen));
  93. return FFH_RES(1);
  94. }
  95. LJLIB_ASM(string_reverse)
  96. {
  97. GCstr *s = lj_lib_checkstr(L, 1);
  98. lj_str_needbuf(L, &G(L)->tmpbuf, s->len);
  99. return FFH_RETRY;
  100. }
  101. LJLIB_ASM_(string_lower)
  102. LJLIB_ASM_(string_upper)
  103. /* ------------------------------------------------------------------------ */
  104. static int writer_buf(lua_State *L, const void *p, size_t size, void *b)
  105. {
  106. luaL_addlstring((luaL_Buffer *)b, (const char *)p, size);
  107. UNUSED(L);
  108. return 0;
  109. }
  110. LJLIB_CF(string_dump)
  111. {
  112. GCfunc *fn = lj_lib_checkfunc(L, 1);
  113. int strip = L->base+1 < L->top && tvistruecond(L->base+1);
  114. luaL_Buffer b;
  115. L->top = L->base+1;
  116. luaL_buffinit(L, &b);
  117. if (!isluafunc(fn) || lj_bcwrite(L, funcproto(fn), writer_buf, &b, strip))
  118. lj_err_caller(L, LJ_ERR_STRDUMP);
  119. luaL_pushresult(&b);
  120. return 1;
  121. }
  122. /* ------------------------------------------------------------------------ */
  123. /* macro to `unsign' a character */
  124. #define uchar(c) ((unsigned char)(c))
  125. #define CAP_UNFINISHED (-1)
  126. #define CAP_POSITION (-2)
  127. typedef struct MatchState {
  128. const char *src_init; /* init of source string */
  129. const char *src_end; /* end (`\0') of source string */
  130. lua_State *L;
  131. int level; /* total number of captures (finished or unfinished) */
  132. struct {
  133. const char *init;
  134. ptrdiff_t len;
  135. } capture[LUA_MAXCAPTURES];
  136. } MatchState;
  137. #define L_ESC '%'
  138. #define SPECIALS "^$*+?.([%-"
  139. static int check_capture(MatchState *ms, int l)
  140. {
  141. l -= '1';
  142. if (l < 0 || l >= ms->level || ms->capture[l].len == CAP_UNFINISHED)
  143. lj_err_caller(ms->L, LJ_ERR_STRCAPI);
  144. return l;
  145. }
  146. static int capture_to_close(MatchState *ms)
  147. {
  148. int level = ms->level;
  149. for (level--; level>=0; level--)
  150. if (ms->capture[level].len == CAP_UNFINISHED) return level;
  151. lj_err_caller(ms->L, LJ_ERR_STRPATC);
  152. return 0; /* unreachable */
  153. }
  154. static const char *classend(MatchState *ms, const char *p)
  155. {
  156. switch (*p++) {
  157. case L_ESC:
  158. if (*p == '\0')
  159. lj_err_caller(ms->L, LJ_ERR_STRPATE);
  160. return p+1;
  161. case '[':
  162. if (*p == '^') p++;
  163. do { /* look for a `]' */
  164. if (*p == '\0')
  165. lj_err_caller(ms->L, LJ_ERR_STRPATM);
  166. if (*(p++) == L_ESC && *p != '\0')
  167. p++; /* skip escapes (e.g. `%]') */
  168. } while (*p != ']');
  169. return p+1;
  170. default:
  171. return p;
  172. }
  173. }
  174. static const unsigned char match_class_map[32] = {
  175. 0,LJ_CHAR_ALPHA,0,LJ_CHAR_CNTRL,LJ_CHAR_DIGIT,0,0,LJ_CHAR_GRAPH,0,0,0,0,
  176. LJ_CHAR_LOWER,0,0,0,LJ_CHAR_PUNCT,0,0,LJ_CHAR_SPACE,0,
  177. LJ_CHAR_UPPER,0,LJ_CHAR_ALNUM,LJ_CHAR_XDIGIT,0,0,0,0,0,0,0
  178. };
  179. static int match_class(int c, int cl)
  180. {
  181. if ((cl & 0xc0) == 0x40) {
  182. int t = match_class_map[(cl&0x1f)];
  183. if (t) {
  184. t = lj_char_isa(c, t);
  185. return (cl & 0x20) ? t : !t;
  186. }
  187. if (cl == 'z') return c == 0;
  188. if (cl == 'Z') return c != 0;
  189. }
  190. return (cl == c);
  191. }
  192. static int matchbracketclass(int c, const char *p, const char *ec)
  193. {
  194. int sig = 1;
  195. if (*(p+1) == '^') {
  196. sig = 0;
  197. p++; /* skip the `^' */
  198. }
  199. while (++p < ec) {
  200. if (*p == L_ESC) {
  201. p++;
  202. if (match_class(c, uchar(*p)))
  203. return sig;
  204. }
  205. else if ((*(p+1) == '-') && (p+2 < ec)) {
  206. p+=2;
  207. if (uchar(*(p-2)) <= c && c <= uchar(*p))
  208. return sig;
  209. }
  210. else if (uchar(*p) == c) return sig;
  211. }
  212. return !sig;
  213. }
  214. static int singlematch(int c, const char *p, const char *ep)
  215. {
  216. switch (*p) {
  217. case '.': return 1; /* matches any char */
  218. case L_ESC: return match_class(c, uchar(*(p+1)));
  219. case '[': return matchbracketclass(c, p, ep-1);
  220. default: return (uchar(*p) == c);
  221. }
  222. }
  223. static const char *match(MatchState *ms, const char *s, const char *p);
  224. static const char *matchbalance(MatchState *ms, const char *s, const char *p)
  225. {
  226. if (*p == 0 || *(p+1) == 0)
  227. lj_err_caller(ms->L, LJ_ERR_STRPATU);
  228. if (*s != *p) {
  229. return NULL;
  230. } else {
  231. int b = *p;
  232. int e = *(p+1);
  233. int cont = 1;
  234. while (++s < ms->src_end) {
  235. if (*s == e) {
  236. if (--cont == 0) return s+1;
  237. } else if (*s == b) {
  238. cont++;
  239. }
  240. }
  241. }
  242. return NULL; /* string ends out of balance */
  243. }
  244. static const char *max_expand(MatchState *ms, const char *s,
  245. const char *p, const char *ep)
  246. {
  247. ptrdiff_t i = 0; /* counts maximum expand for item */
  248. while ((s+i)<ms->src_end && singlematch(uchar(*(s+i)), p, ep))
  249. i++;
  250. /* keeps trying to match with the maximum repetitions */
  251. while (i>=0) {
  252. const char *res = match(ms, (s+i), ep+1);
  253. if (res) return res;
  254. i--; /* else didn't match; reduce 1 repetition to try again */
  255. }
  256. return NULL;
  257. }
  258. static const char *min_expand(MatchState *ms, const char *s,
  259. const char *p, const char *ep)
  260. {
  261. for (;;) {
  262. const char *res = match(ms, s, ep+1);
  263. if (res != NULL)
  264. return res;
  265. else if (s<ms->src_end && singlematch(uchar(*s), p, ep))
  266. s++; /* try with one more repetition */
  267. else
  268. return NULL;
  269. }
  270. }
  271. static const char *start_capture(MatchState *ms, const char *s,
  272. const char *p, int what)
  273. {
  274. const char *res;
  275. int level = ms->level;
  276. if (level >= LUA_MAXCAPTURES) lj_err_caller(ms->L, LJ_ERR_STRCAPN);
  277. ms->capture[level].init = s;
  278. ms->capture[level].len = what;
  279. ms->level = level+1;
  280. if ((res=match(ms, s, p)) == NULL) /* match failed? */
  281. ms->level--; /* undo capture */
  282. return res;
  283. }
  284. static const char *end_capture(MatchState *ms, const char *s,
  285. const char *p)
  286. {
  287. int l = capture_to_close(ms);
  288. const char *res;
  289. ms->capture[l].len = s - ms->capture[l].init; /* close capture */
  290. if ((res = match(ms, s, p)) == NULL) /* match failed? */
  291. ms->capture[l].len = CAP_UNFINISHED; /* undo capture */
  292. return res;
  293. }
  294. static const char *match_capture(MatchState *ms, const char *s, int l)
  295. {
  296. size_t len;
  297. l = check_capture(ms, l);
  298. len = (size_t)ms->capture[l].len;
  299. if ((size_t)(ms->src_end-s) >= len &&
  300. memcmp(ms->capture[l].init, s, len) == 0)
  301. return s+len;
  302. else
  303. return NULL;
  304. }
  305. static const char *match(MatchState *ms, const char *s, const char *p)
  306. {
  307. init: /* using goto's to optimize tail recursion */
  308. switch (*p) {
  309. case '(': /* start capture */
  310. if (*(p+1) == ')') /* position capture? */
  311. return start_capture(ms, s, p+2, CAP_POSITION);
  312. else
  313. return start_capture(ms, s, p+1, CAP_UNFINISHED);
  314. case ')': /* end capture */
  315. return end_capture(ms, s, p+1);
  316. case L_ESC:
  317. switch (*(p+1)) {
  318. case 'b': /* balanced string? */
  319. s = matchbalance(ms, s, p+2);
  320. if (s == NULL) return NULL;
  321. p+=4;
  322. goto init; /* else return match(ms, s, p+4); */
  323. case 'f': { /* frontier? */
  324. const char *ep; char previous;
  325. p += 2;
  326. if (*p != '[')
  327. lj_err_caller(ms->L, LJ_ERR_STRPATB);
  328. ep = classend(ms, p); /* points to what is next */
  329. previous = (s == ms->src_init) ? '\0' : *(s-1);
  330. if (matchbracketclass(uchar(previous), p, ep-1) ||
  331. !matchbracketclass(uchar(*s), p, ep-1)) return NULL;
  332. p=ep;
  333. goto init; /* else return match(ms, s, ep); */
  334. }
  335. default:
  336. if (lj_char_isdigit(uchar(*(p+1)))) { /* capture results (%0-%9)? */
  337. s = match_capture(ms, s, uchar(*(p+1)));
  338. if (s == NULL) return NULL;
  339. p+=2;
  340. goto init; /* else return match(ms, s, p+2) */
  341. }
  342. goto dflt; /* case default */
  343. }
  344. case '\0': /* end of pattern */
  345. return s; /* match succeeded */
  346. case '$':
  347. if (*(p+1) == '\0') /* is the `$' the last char in pattern? */
  348. return (s == ms->src_end) ? s : NULL; /* check end of string */
  349. else
  350. goto dflt;
  351. default: dflt: { /* it is a pattern item */
  352. const char *ep = classend(ms, p); /* points to what is next */
  353. int m = s<ms->src_end && singlematch(uchar(*s), p, ep);
  354. switch (*ep) {
  355. case '?': { /* optional */
  356. const char *res;
  357. if (m && ((res=match(ms, s+1, ep+1)) != NULL))
  358. return res;
  359. p=ep+1;
  360. goto init; /* else return match(ms, s, ep+1); */
  361. }
  362. case '*': /* 0 or more repetitions */
  363. return max_expand(ms, s, p, ep);
  364. case '+': /* 1 or more repetitions */
  365. return (m ? max_expand(ms, s+1, p, ep) : NULL);
  366. case '-': /* 0 or more repetitions (minimum) */
  367. return min_expand(ms, s, p, ep);
  368. default:
  369. if (!m) return NULL;
  370. s++; p=ep;
  371. goto init; /* else return match(ms, s+1, ep); */
  372. }
  373. }
  374. }
  375. }
  376. static const char *lmemfind(const char *s1, size_t l1,
  377. const char *s2, size_t l2)
  378. {
  379. if (l2 == 0) {
  380. return s1; /* empty strings are everywhere */
  381. } else if (l2 > l1) {
  382. return NULL; /* avoids a negative `l1' */
  383. } else {
  384. const char *init; /* to search for a `*s2' inside `s1' */
  385. l2--; /* 1st char will be checked by `memchr' */
  386. l1 = l1-l2; /* `s2' cannot be found after that */
  387. while (l1 > 0 && (init = (const char *)memchr(s1, *s2, l1)) != NULL) {
  388. init++; /* 1st char is already checked */
  389. if (memcmp(init, s2+1, l2) == 0) {
  390. return init-1;
  391. } else { /* correct `l1' and `s1' to try again */
  392. l1 -= (size_t)(init-s1);
  393. s1 = init;
  394. }
  395. }
  396. return NULL; /* not found */
  397. }
  398. }
  399. static void push_onecapture(MatchState *ms, int i, const char *s, const char *e)
  400. {
  401. if (i >= ms->level) {
  402. if (i == 0) /* ms->level == 0, too */
  403. lua_pushlstring(ms->L, s, (size_t)(e - s)); /* add whole match */
  404. else
  405. lj_err_caller(ms->L, LJ_ERR_STRCAPI);
  406. } else {
  407. ptrdiff_t l = ms->capture[i].len;
  408. if (l == CAP_UNFINISHED) lj_err_caller(ms->L, LJ_ERR_STRCAPU);
  409. if (l == CAP_POSITION)
  410. lua_pushinteger(ms->L, ms->capture[i].init - ms->src_init + 1);
  411. else
  412. lua_pushlstring(ms->L, ms->capture[i].init, (size_t)l);
  413. }
  414. }
  415. static int push_captures(MatchState *ms, const char *s, const char *e)
  416. {
  417. int i;
  418. int nlevels = (ms->level == 0 && s) ? 1 : ms->level;
  419. luaL_checkstack(ms->L, nlevels, "too many captures");
  420. for (i = 0; i < nlevels; i++)
  421. push_onecapture(ms, i, s, e);
  422. return nlevels; /* number of strings pushed */
  423. }
  424. static ptrdiff_t posrelat(ptrdiff_t pos, size_t len)
  425. {
  426. /* relative string position: negative means back from end */
  427. if (pos < 0) pos += (ptrdiff_t)len + 1;
  428. return (pos >= 0) ? pos : 0;
  429. }
  430. static int str_find_aux(lua_State *L, int find)
  431. {
  432. size_t l1, l2;
  433. const char *s = luaL_checklstring(L, 1, &l1);
  434. const char *p = luaL_checklstring(L, 2, &l2);
  435. ptrdiff_t init = posrelat(luaL_optinteger(L, 3, 1), l1) - 1;
  436. if (init < 0)
  437. init = 0;
  438. else if ((size_t)(init) > l1)
  439. init = (ptrdiff_t)l1;
  440. if (find && (lua_toboolean(L, 4) || /* explicit request? */
  441. strpbrk(p, SPECIALS) == NULL)) { /* or no special characters? */
  442. /* do a plain search */
  443. const char *s2 = lmemfind(s+init, l1-(size_t)init, p, l2);
  444. if (s2) {
  445. lua_pushinteger(L, s2-s+1);
  446. lua_pushinteger(L, s2-s+(ptrdiff_t)l2);
  447. return 2;
  448. }
  449. } else {
  450. MatchState ms;
  451. int anchor = (*p == '^') ? (p++, 1) : 0;
  452. const char *s1=s+init;
  453. ms.L = L;
  454. ms.src_init = s;
  455. ms.src_end = s+l1;
  456. do {
  457. const char *res;
  458. ms.level = 0;
  459. if ((res=match(&ms, s1, p)) != NULL) {
  460. if (find) {
  461. lua_pushinteger(L, s1-s+1); /* start */
  462. lua_pushinteger(L, res-s); /* end */
  463. return push_captures(&ms, NULL, 0) + 2;
  464. } else {
  465. return push_captures(&ms, s1, res);
  466. }
  467. }
  468. } while (s1++ < ms.src_end && !anchor);
  469. }
  470. lua_pushnil(L); /* not found */
  471. return 1;
  472. }
  473. LJLIB_CF(string_find)
  474. {
  475. return str_find_aux(L, 1);
  476. }
  477. LJLIB_CF(string_match)
  478. {
  479. return str_find_aux(L, 0);
  480. }
  481. LJLIB_NOREG LJLIB_CF(string_gmatch_aux)
  482. {
  483. const char *p = strVdata(lj_lib_upvalue(L, 2));
  484. GCstr *str = strV(lj_lib_upvalue(L, 1));
  485. const char *s = strdata(str);
  486. TValue *tvpos = lj_lib_upvalue(L, 3);
  487. const char *src = s + tvpos->u32.lo;
  488. MatchState ms;
  489. ms.L = L;
  490. ms.src_init = s;
  491. ms.src_end = s + str->len;
  492. for (; src <= ms.src_end; src++) {
  493. const char *e;
  494. ms.level = 0;
  495. if ((e = match(&ms, src, p)) != NULL) {
  496. int32_t pos = (int32_t)(e - s);
  497. if (e == src) pos++; /* Ensure progress for empty match. */
  498. tvpos->u32.lo = (uint32_t)pos;
  499. return push_captures(&ms, src, e);
  500. }
  501. }
  502. return 0; /* not found */
  503. }
  504. LJLIB_CF(string_gmatch)
  505. {
  506. lj_lib_checkstr(L, 1);
  507. lj_lib_checkstr(L, 2);
  508. L->top = L->base+3;
  509. (L->top-1)->u64 = 0;
  510. lj_lib_pushcc(L, lj_cf_string_gmatch_aux, FF_string_gmatch_aux, 3);
  511. return 1;
  512. }
  513. static void add_s(MatchState *ms, luaL_Buffer *b, const char *s, const char *e)
  514. {
  515. size_t l, i;
  516. const char *news = lua_tolstring(ms->L, 3, &l);
  517. for (i = 0; i < l; i++) {
  518. if (news[i] != L_ESC) {
  519. luaL_addchar(b, news[i]);
  520. } else {
  521. i++; /* skip ESC */
  522. if (!lj_char_isdigit(uchar(news[i]))) {
  523. luaL_addchar(b, news[i]);
  524. } else if (news[i] == '0') {
  525. luaL_addlstring(b, s, (size_t)(e - s));
  526. } else {
  527. push_onecapture(ms, news[i] - '1', s, e);
  528. luaL_addvalue(b); /* add capture to accumulated result */
  529. }
  530. }
  531. }
  532. }
  533. static void add_value(MatchState *ms, luaL_Buffer *b,
  534. const char *s, const char *e)
  535. {
  536. lua_State *L = ms->L;
  537. switch (lua_type(L, 3)) {
  538. case LUA_TNUMBER:
  539. case LUA_TSTRING: {
  540. add_s(ms, b, s, e);
  541. return;
  542. }
  543. case LUA_TFUNCTION: {
  544. int n;
  545. lua_pushvalue(L, 3);
  546. n = push_captures(ms, s, e);
  547. lua_call(L, n, 1);
  548. break;
  549. }
  550. case LUA_TTABLE: {
  551. push_onecapture(ms, 0, s, e);
  552. lua_gettable(L, 3);
  553. break;
  554. }
  555. }
  556. if (!lua_toboolean(L, -1)) { /* nil or false? */
  557. lua_pop(L, 1);
  558. lua_pushlstring(L, s, (size_t)(e - s)); /* keep original text */
  559. } else if (!lua_isstring(L, -1)) {
  560. lj_err_callerv(L, LJ_ERR_STRGSRV, luaL_typename(L, -1));
  561. }
  562. luaL_addvalue(b); /* add result to accumulator */
  563. }
  564. LJLIB_CF(string_gsub)
  565. {
  566. size_t srcl;
  567. const char *src = luaL_checklstring(L, 1, &srcl);
  568. const char *p = luaL_checkstring(L, 2);
  569. int tr = lua_type(L, 3);
  570. int max_s = luaL_optint(L, 4, (int)(srcl+1));
  571. int anchor = (*p == '^') ? (p++, 1) : 0;
  572. int n = 0;
  573. MatchState ms;
  574. luaL_Buffer b;
  575. if (!(tr == LUA_TNUMBER || tr == LUA_TSTRING ||
  576. tr == LUA_TFUNCTION || tr == LUA_TTABLE))
  577. lj_err_arg(L, 3, LJ_ERR_NOSFT);
  578. luaL_buffinit(L, &b);
  579. ms.L = L;
  580. ms.src_init = src;
  581. ms.src_end = src+srcl;
  582. while (n < max_s) {
  583. const char *e;
  584. ms.level = 0;
  585. e = match(&ms, src, p);
  586. if (e) {
  587. n++;
  588. add_value(&ms, &b, src, e);
  589. }
  590. if (e && e>src) /* non empty match? */
  591. src = e; /* skip it */
  592. else if (src < ms.src_end)
  593. luaL_addchar(&b, *src++);
  594. else
  595. break;
  596. if (anchor)
  597. break;
  598. }
  599. luaL_addlstring(&b, src, (size_t)(ms.src_end-src));
  600. luaL_pushresult(&b);
  601. lua_pushinteger(L, n); /* number of substitutions */
  602. return 2;
  603. }
  604. /* ------------------------------------------------------------------------ */
  605. /* maximum size of each formatted item (> len(format('%99.99f', -1e308))) */
  606. #define MAX_FMTITEM 512
  607. /* valid flags in a format specification */
  608. #define FMT_FLAGS "-+ #0"
  609. /*
  610. ** maximum size of each format specification (such as '%-099.99d')
  611. ** (+10 accounts for %99.99x plus margin of error)
  612. */
  613. #define MAX_FMTSPEC (sizeof(FMT_FLAGS) + sizeof(LUA_INTFRMLEN) + 10)
  614. static void addquoted(lua_State *L, luaL_Buffer *b, int arg)
  615. {
  616. GCstr *str = lj_lib_checkstr(L, arg);
  617. int32_t len = (int32_t)str->len;
  618. const char *s = strdata(str);
  619. luaL_addchar(b, '"');
  620. while (len--) {
  621. if (*s == '"' || *s == '\\' || *s == '\n') {
  622. luaL_addchar(b, '\\');
  623. luaL_addchar(b, *s);
  624. } else if (lj_char_iscntrl(uchar(*s))) {
  625. uint32_t c1, c2, c3;
  626. luaL_addchar(b, '\\');
  627. c1 = uchar(*s); c3 = c1 % 10; c1 /= 10; c2 = c1 % 10; c1 /= 10;
  628. if (c1 + lj_char_isdigit(uchar(s[1]))) luaL_addchar(b, '0' + c1);
  629. if (c2 + (c1 + lj_char_isdigit(uchar(s[1])))) luaL_addchar(b, '0' + c2);
  630. luaL_addchar(b, '0' + c3);
  631. } else {
  632. luaL_addchar(b, *s);
  633. }
  634. s++;
  635. }
  636. luaL_addchar(b, '"');
  637. }
  638. static const char *scanformat(lua_State *L, const char *strfrmt, char *form)
  639. {
  640. const char *p = strfrmt;
  641. while (*p != '\0' && strchr(FMT_FLAGS, *p) != NULL) p++; /* skip flags */
  642. if ((size_t)(p - strfrmt) >= sizeof(FMT_FLAGS))
  643. lj_err_caller(L, LJ_ERR_STRFMTR);
  644. if (lj_char_isdigit(uchar(*p))) p++; /* skip width */
  645. if (lj_char_isdigit(uchar(*p))) p++; /* (2 digits at most) */
  646. if (*p == '.') {
  647. p++;
  648. if (lj_char_isdigit(uchar(*p))) p++; /* skip precision */
  649. if (lj_char_isdigit(uchar(*p))) p++; /* (2 digits at most) */
  650. }
  651. if (lj_char_isdigit(uchar(*p)))
  652. lj_err_caller(L, LJ_ERR_STRFMTW);
  653. *(form++) = '%';
  654. strncpy(form, strfrmt, (size_t)(p - strfrmt + 1));
  655. form += p - strfrmt + 1;
  656. *form = '\0';
  657. return p;
  658. }
  659. static void addintlen(char *form)
  660. {
  661. size_t l = strlen(form);
  662. char spec = form[l - 1];
  663. strcpy(form + l - 1, LUA_INTFRMLEN);
  664. form[l + sizeof(LUA_INTFRMLEN) - 2] = spec;
  665. form[l + sizeof(LUA_INTFRMLEN) - 1] = '\0';
  666. }
  667. static unsigned LUA_INTFRM_T num2intfrm(lua_State *L, int arg)
  668. {
  669. if (sizeof(LUA_INTFRM_T) == 4) {
  670. return (LUA_INTFRM_T)lj_lib_checkbit(L, arg);
  671. } else {
  672. cTValue *o;
  673. lj_lib_checknumber(L, arg);
  674. o = L->base+arg-1;
  675. if (tvisint(o))
  676. return (LUA_INTFRM_T)intV(o);
  677. else
  678. return (LUA_INTFRM_T)numV(o);
  679. }
  680. }
  681. static unsigned LUA_INTFRM_T num2uintfrm(lua_State *L, int arg)
  682. {
  683. if (sizeof(LUA_INTFRM_T) == 4) {
  684. return (unsigned LUA_INTFRM_T)lj_lib_checkbit(L, arg);
  685. } else {
  686. cTValue *o;
  687. lj_lib_checknumber(L, arg);
  688. o = L->base+arg-1;
  689. if (tvisint(o))
  690. return (unsigned LUA_INTFRM_T)intV(o);
  691. else if ((int32_t)o->u32.hi < 0)
  692. return (unsigned LUA_INTFRM_T)(LUA_INTFRM_T)numV(o);
  693. else
  694. return (unsigned LUA_INTFRM_T)numV(o);
  695. }
  696. }
  697. LJLIB_CF(string_format)
  698. {
  699. int arg = 1, top = (int)(L->top - L->base);
  700. GCstr *fmt = lj_lib_checkstr(L, arg);
  701. const char *strfrmt = strdata(fmt);
  702. const char *strfrmt_end = strfrmt + fmt->len;
  703. luaL_Buffer b;
  704. luaL_buffinit(L, &b);
  705. while (strfrmt < strfrmt_end) {
  706. if (*strfrmt != L_ESC) {
  707. luaL_addchar(&b, *strfrmt++);
  708. } else if (*++strfrmt == L_ESC) {
  709. luaL_addchar(&b, *strfrmt++); /* %% */
  710. } else { /* format item */
  711. char form[MAX_FMTSPEC]; /* to store the format (`%...') */
  712. char buff[MAX_FMTITEM]; /* to store the formatted item */
  713. if (++arg > top)
  714. luaL_argerror(L, arg, lj_obj_typename[0]);
  715. strfrmt = scanformat(L, strfrmt, form);
  716. switch (*strfrmt++) {
  717. case 'c':
  718. sprintf(buff, form, lj_lib_checkint(L, arg));
  719. break;
  720. case 'd': case 'i':
  721. addintlen(form);
  722. sprintf(buff, form, num2intfrm(L, arg));
  723. break;
  724. case 'o': case 'u': case 'x': case 'X':
  725. addintlen(form);
  726. sprintf(buff, form, num2uintfrm(L, arg));
  727. break;
  728. case 'e': case 'E': case 'f': case 'g': case 'G': {
  729. TValue tv;
  730. tv.n = lj_lib_checknum(L, arg);
  731. if (LJ_UNLIKELY((tv.u32.hi << 1) >= 0xffe00000)) {
  732. /* Canonicalize output of non-finite values. */
  733. char *p, nbuf[LJ_STR_NUMBUF];
  734. size_t len = lj_str_bufnum(nbuf, &tv);
  735. if (strfrmt[-1] == 'E' || strfrmt[-1] == 'G') {
  736. nbuf[len-3] = nbuf[len-3] - 0x20;
  737. nbuf[len-2] = nbuf[len-2] - 0x20;
  738. nbuf[len-1] = nbuf[len-1] - 0x20;
  739. }
  740. nbuf[len] = '\0';
  741. for (p = form; *p < 'e' && *p != '.'; p++) ;
  742. *p++ = 's'; *p = '\0';
  743. sprintf(buff, form, nbuf);
  744. break;
  745. }
  746. sprintf(buff, form, (double)tv.n);
  747. break;
  748. }
  749. case 'q':
  750. addquoted(L, &b, arg);
  751. continue;
  752. case 'p':
  753. lj_str_pushf(L, "%p", lua_topointer(L, arg));
  754. luaL_addvalue(&b);
  755. continue;
  756. case 's': {
  757. GCstr *str = lj_lib_checkstr(L, arg);
  758. if (!strchr(form, '.') && str->len >= 100) {
  759. /* no precision and string is too long to be formatted;
  760. keep original string */
  761. setstrV(L, L->top++, str);
  762. luaL_addvalue(&b);
  763. continue;
  764. }
  765. sprintf(buff, form, strdata(str));
  766. break;
  767. }
  768. default:
  769. lj_err_callerv(L, LJ_ERR_STRFMTO, *(strfrmt -1));
  770. break;
  771. }
  772. luaL_addlstring(&b, buff, strlen(buff));
  773. }
  774. }
  775. luaL_pushresult(&b);
  776. return 1;
  777. }
  778. /* ------------------------------------------------------------------------ */
  779. #include "lj_libdef.h"
  780. LUALIB_API int luaopen_string(lua_State *L)
  781. {
  782. GCtab *mt;
  783. global_State *g;
  784. LJ_LIB_REG(L, LUA_STRLIBNAME, string);
  785. #if defined(LUA_COMPAT_GFIND)
  786. lua_getfield(L, -1, "gmatch");
  787. lua_setfield(L, -2, "gfind");
  788. #endif
  789. mt = lj_tab_new(L, 0, 1);
  790. /* NOBARRIER: basemt is a GC root. */
  791. g = G(L);
  792. setgcref(basemt_it(g, LJ_TSTR), obj2gco(mt));
  793. settabV(L, lj_tab_setstr(L, mt, mmname_str(g, MM_index)), tabV(L->top-1));
  794. mt->nomm = (uint8_t)(~(1u<<MM_index));
  795. return 1;
  796. }