src/lib_string.c - luajit-2.0-src

Global variables defined

Data types defined

Functions defined

Macros defined

Source code

  1. /*
  2. ** String library.
  3. ** Copyright (C) 2005-2015 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. #define lib_string_c
  9. #define LUA_LIB

  10. #include "lua.h"
  11. #include "lauxlib.h"
  12. #include "lualib.h"

  13. #include "lj_obj.h"
  14. #include "lj_gc.h"
  15. #include "lj_err.h"
  16. #include "lj_buf.h"
  17. #include "lj_str.h"
  18. #include "lj_tab.h"
  19. #include "lj_meta.h"
  20. #include "lj_state.h"
  21. #include "lj_ff.h"
  22. #include "lj_bcdump.h"
  23. #include "lj_char.h"
  24. #include "lj_strfmt.h"
  25. #include "lj_lib.h"

  26. /* ------------------------------------------------------------------------ */

  27. #define LJLIB_MODULE_string

  28. LJLIB_LUA(string_len) /*
  29.   function(s)
  30.     CHECK_str(s)
  31.     return #s
  32.   end
  33. */

  34. LJLIB_ASM(string_byte)                LJLIB_REC(string_range 0)
  35. {
  36.   GCstr *s = lj_lib_checkstr(L, 1);
  37.   int32_t len = (int32_t)s->len;
  38.   int32_t start = lj_lib_optint(L, 2, 1);
  39.   int32_t stop = lj_lib_optint(L, 3, start);
  40.   int32_t n, i;
  41.   const unsigned char *p;
  42.   if (stop < 0) stop += len+1;
  43.   if (start < 0) start += len+1;
  44.   if (start <= 0) start = 1;
  45.   if (stop > len) stop = len;
  46.   if (start > stop) return FFH_RES(0);  /* Empty interval: return no results. */
  47.   start--;
  48.   n = stop - start;
  49.   if ((uint32_t)n > LUAI_MAXCSTACK)
  50.     lj_err_caller(L, LJ_ERR_STRSLC);
  51.   lj_state_checkstack(L, (MSize)n);
  52.   p = (const unsigned char *)strdata(s) + start;
  53.   for (i = 0; i < n; i++)
  54.     setintV(L->base + i-1-LJ_FR2, p[i]);
  55.   return FFH_RES(n);
  56. }

  57. LJLIB_ASM(string_char)                LJLIB_REC(.)
  58. {
  59.   int i, nargs = (int)(L->top - L->base);
  60.   char *buf = lj_buf_tmp(L, (MSize)nargs);
  61.   for (i = 1; i <= nargs; i++) {
  62.     int32_t k = lj_lib_checkint(L, i);
  63.     if (!checku8(k))
  64.       lj_err_arg(L, i, LJ_ERR_BADVAL);
  65.     buf[i-1] = (char)k;
  66.   }
  67.   setstrV(L, L->base-1-LJ_FR2, lj_str_new(L, buf, (size_t)nargs));
  68.   return FFH_RES(1);
  69. }

  70. LJLIB_ASM(string_sub)                LJLIB_REC(string_range 1)
  71. {
  72.   lj_lib_checkstr(L, 1);
  73.   lj_lib_checkint(L, 2);
  74.   setintV(L->base+2, lj_lib_optint(L, 3, -1));
  75.   return FFH_RETRY;
  76. }

  77. LJLIB_CF(string_rep)                LJLIB_REC(.)
  78. {
  79.   GCstr *s = lj_lib_checkstr(L, 1);
  80.   int32_t rep = lj_lib_checkint(L, 2);
  81.   GCstr *sep = lj_lib_optstr(L, 3);
  82.   SBuf *sb = lj_buf_tmp_(L);
  83.   if (sep && rep > 1) {
  84.     GCstr *s2 = lj_buf_cat2str(L, sep, s);
  85.     lj_buf_reset(sb);
  86.     lj_buf_putstr(sb, s);
  87.     s = s2;
  88.     rep--;
  89.   }
  90.   sb = lj_buf_putstr_rep(sb, s, rep);
  91.   setstrV(L, L->top-1, lj_buf_str(L, sb));
  92.   lj_gc_check(L);
  93.   return 1;
  94. }

  95. LJLIB_ASM(string_reverse)  LJLIB_REC(string_op IRCALL_lj_buf_putstr_reverse)
  96. {
  97.   lj_lib_checkstr(L, 1);
  98.   return FFH_RETRY;
  99. }
  100. LJLIB_ASM_(string_lower)  LJLIB_REC(string_op IRCALL_lj_buf_putstr_lower)
  101. LJLIB_ASM_(string_upper)  LJLIB_REC(string_op IRCALL_lj_buf_putstr_upper)

  102. /* ------------------------------------------------------------------------ */

  103. static int writer_buf(lua_State *L, const void *p, size_t size, void *sb)
  104. {
  105.   lj_buf_putmem((SBuf *)sb, p, (MSize)size);
  106.   UNUSED(L);
  107.   return 0;
  108. }

  109. LJLIB_CF(string_dump)
  110. {
  111.   GCfunc *fn = lj_lib_checkfunc(L, 1);
  112.   int strip = L->base+1 < L->top && tvistruecond(L->base+1);
  113.   SBuf *sb = lj_buf_tmp_(L);  /* Assumes lj_bcwrite() doesn't use tmpbuf. */
  114.   L->top = L->base+1;
  115.   if (!isluafunc(fn) || lj_bcwrite(L, funcproto(fn), writer_buf, sb, strip))
  116.     lj_err_caller(L, LJ_ERR_STRDUMP);
  117.   setstrV(L, L->top-1, lj_buf_str(L, sb));
  118.   lj_gc_check(L);
  119.   return 1;
  120. }

  121. /* ------------------------------------------------------------------------ */

  122. /* macro to `unsign' a character */
  123. #define uchar(c)        ((unsigned char)(c))

  124. #define CAP_UNFINISHED        (-1)
  125. #define CAP_POSITION        (-2)

  126. typedef struct MatchState {
  127.   const char *src_init;  /* init of source string */
  128.   const char *src_end;  /* end (`\0') of source string */
  129.   lua_State *L;
  130.   int level;  /* total number of captures (finished or unfinished) */
  131.   int depth;
  132.   struct {
  133.     const char *init;
  134.     ptrdiff_t len;
  135.   } capture[LUA_MAXCAPTURES];
  136. } MatchState;

  137. #define L_ESC                '%'

  138. static int check_capture(MatchState *ms, int l)
  139. {
  140.   l -= '1';
  141.   if (l < 0 || l >= ms->level || ms->capture[l].len == CAP_UNFINISHED)
  142.     lj_err_caller(ms->L, LJ_ERR_STRCAPI);
  143.   return l;
  144. }

  145. static int capture_to_close(MatchState *ms)
  146. {
  147.   int level = ms->level;
  148.   for (level--; level>=0; level--)
  149.     if (ms->capture[level].len == CAP_UNFINISHED) return level;
  150.   lj_err_caller(ms->L, LJ_ERR_STRPATC);
  151.   return 0/* unreachable */
  152. }

  153. static const char *classend(MatchState *ms, const char *p)
  154. {
  155.   switch (*p++) {
  156.   case L_ESC:
  157.     if (*p == '\0')
  158.       lj_err_caller(ms->L, LJ_ERR_STRPATE);
  159.     return p+1;
  160.   case '[':
  161.     if (*p == '^') p++;
  162.     do/* look for a `]' */
  163.       if (*p == '\0')
  164.         lj_err_caller(ms->L, LJ_ERR_STRPATM);
  165.       if (*(p++) == L_ESC && *p != '\0')
  166.         p++;  /* skip escapes (e.g. `%]') */
  167.     } while (*p != ']');
  168.     return p+1;
  169.   default:
  170.     return p;
  171.   }
  172. }

  173. static const unsigned char match_class_map[32] = {
  174.   0,LJ_CHAR_ALPHA,0,LJ_CHAR_CNTRL,LJ_CHAR_DIGIT,0,0,LJ_CHAR_GRAPH,0,0,0,0,
  175.   LJ_CHAR_LOWER,0,0,0,LJ_CHAR_PUNCT,0,0,LJ_CHAR_SPACE,0,
  176.   LJ_CHAR_UPPER,0,LJ_CHAR_ALNUM,LJ_CHAR_XDIGIT,0,0,0,0,0,0,0
  177. };

  178. static int match_class(int c, int cl)
  179. {
  180.   if ((cl & 0xc0) == 0x40) {
  181.     int t = match_class_map[(cl&0x1f)];
  182.     if (t) {
  183.       t = lj_char_isa(c, t);
  184.       return (cl & 0x20) ? t : !t;
  185.     }
  186.     if (cl == 'z') return c == 0;
  187.     if (cl == 'Z') return c != 0;
  188.   }
  189.   return (cl == c);
  190. }

  191. static int matchbracketclass(int c, const char *p, const char *ec)
  192. {
  193.   int sig = 1;
  194.   if (*(p+1) == '^') {
  195.     sig = 0;
  196.     p++;  /* skip the `^' */
  197.   }
  198.   while (++p < ec) {
  199.     if (*p == L_ESC) {
  200.       p++;
  201.       if (match_class(c, uchar(*p)))
  202.         return sig;
  203.     }
  204.     else if ((*(p+1) == '-') && (p+2 < ec)) {
  205.       p+=2;
  206.       if (uchar(*(p-2)) <= c && c <= uchar(*p))
  207.         return sig;
  208.     }
  209.     else if (uchar(*p) == c) return sig;
  210.   }
  211.   return !sig;
  212. }

  213. static int singlematch(int c, const char *p, const char *ep)
  214. {
  215.   switch (*p) {
  216.   case '.': return 1/* matches any char */
  217.   case L_ESC: return match_class(c, uchar(*(p+1)));
  218.   case '[': return matchbracketclass(c, p, ep-1);
  219.   default:  return (uchar(*p) == c);
  220.   }
  221. }

  222. static const char *match(MatchState *ms, const char *s, const char *p);

  223. static const char *matchbalance(MatchState *ms, const char *s, const char *p)
  224. {
  225.   if (*p == 0 || *(p+1) == 0)
  226.     lj_err_caller(ms->L, LJ_ERR_STRPATU);
  227.   if (*s != *p) {
  228.     return NULL;
  229.   } else {
  230.     int b = *p;
  231.     int e = *(p+1);
  232.     int cont = 1;
  233.     while (++s < ms->src_end) {
  234.       if (*s == e) {
  235.         if (--cont == 0) return s+1;
  236.       } else if (*s == b) {
  237.         cont++;
  238.       }
  239.     }
  240.   }
  241.   return NULL/* string ends out of balance */
  242. }

  243. static const char *max_expand(MatchState *ms, const char *s,
  244.                               const char *p, const char *ep)
  245. {
  246.   ptrdiff_t i = 0/* counts maximum expand for item */
  247.   while ((s+i)<ms->src_end && singlematch(uchar(*(s+i)), p, ep))
  248.     i++;
  249.   /* keeps trying to match with the maximum repetitions */
  250.   while (i>=0) {
  251.     const char *res = match(ms, (s+i), ep+1);
  252.     if (res) return res;
  253.     i--;  /* else didn't match; reduce 1 repetition to try again */
  254.   }
  255.   return NULL;
  256. }

  257. static const char *min_expand(MatchState *ms, const char *s,
  258.                               const char *p, const char *ep)
  259. {
  260.   for (;;) {
  261.     const char *res = match(ms, s, ep+1);
  262.     if (res != NULL)
  263.       return res;
  264.     else if (s<ms->src_end && singlematch(uchar(*s), p, ep))
  265.       s++;  /* try with one more repetition */
  266.     else
  267.       return NULL;
  268.   }
  269. }

  270. static const char *start_capture(MatchState *ms, const char *s,
  271.                                  const char *p, int what)
  272. {
  273.   const char *res;
  274.   int level = ms->level;
  275.   if (level >= LUA_MAXCAPTURES) lj_err_caller(ms->L, LJ_ERR_STRCAPN);
  276.   ms->capture[level].init = s;
  277.   ms->capture[level].len = what;
  278.   ms->level = level+1;
  279.   if ((res=match(ms, s, p)) == NULL/* match failed? */
  280.     ms->level--;  /* undo capture */
  281.   return res;
  282. }

  283. static const char *end_capture(MatchState *ms, const char *s,
  284.                                const char *p)
  285. {
  286.   int l = capture_to_close(ms);
  287.   const char *res;
  288.   ms->capture[l].len = s - ms->capture[l].init;  /* close capture */
  289.   if ((res = match(ms, s, p)) == NULL/* match failed? */
  290.     ms->capture[l].len = CAP_UNFINISHED/* undo capture */
  291.   return res;
  292. }

  293. static const char *match_capture(MatchState *ms, const char *s, int l)
  294. {
  295.   size_t len;
  296.   l = check_capture(ms, l);
  297.   len = (size_t)ms->capture[l].len;
  298.   if ((size_t)(ms->src_end-s) >= len &&
  299.       memcmp(ms->capture[l].init, s, len) == 0)
  300.     return s+len;
  301.   else
  302.     return NULL;
  303. }

  304. static const char *match(MatchState *ms, const char *s, const char *p)
  305. {
  306.   if (++ms->depth > LJ_MAX_XLEVEL)
  307.     lj_err_caller(ms->L, LJ_ERR_STRPATX);
  308.   init: /* using goto's to optimize tail recursion */
  309.   switch (*p) {
  310.   case '('/* start capture */
  311.     if (*(p+1) == ')'/* position capture? */
  312.       s = start_capture(ms, s, p+2, CAP_POSITION);
  313.     else
  314.       s = start_capture(ms, s, p+1, CAP_UNFINISHED);
  315.     break;
  316.   case ')'/* end capture */
  317.     s = end_capture(ms, s, p+1);
  318.     break;
  319.   case L_ESC:
  320.     switch (*(p+1)) {
  321.     case 'b'/* balanced string? */
  322.       s = matchbalance(ms, s, p+2);
  323.       if (s == NULL) break;
  324.       p+=4;
  325.       goto init;  /* else s = match(ms, s, p+4); */
  326.     case 'f': {  /* frontier? */
  327.       const char *ep; char previous;
  328.       p += 2;
  329.       if (*p != '[')
  330.         lj_err_caller(ms->L, LJ_ERR_STRPATB);
  331.       ep = classend(ms, p);  /* points to what is next */
  332.       previous = (s == ms->src_init) ? '\0' : *(s-1);
  333.       if (matchbracketclass(uchar(previous), p, ep-1) ||
  334.          !matchbracketclass(uchar(*s), p, ep-1)) { s = NULL; break; }
  335.       p=ep;
  336.       goto init;  /* else s = match(ms, s, ep); */
  337.       }
  338.     default:
  339.       if (lj_char_isdigit(uchar(*(p+1)))) {  /* capture results (%0-%9)? */
  340.         s = match_capture(ms, s, uchar(*(p+1)));
  341.         if (s == NULL) break;
  342.         p+=2;
  343.         goto init;  /* else s = match(ms, s, p+2) */
  344.       }
  345.       goto dflt;  /* case default */
  346.     }
  347.     break;
  348.   case '\0'/* end of pattern */
  349.     break/* match succeeded */
  350.   case '$':
  351.     /* is the `$' the last char in pattern? */
  352.     if (*(p+1) != '\0') goto dflt;
  353.     if (s != ms->src_end) s = NULL/* check end of string */
  354.     break;
  355.   default: dflt: {  /* it is a pattern item */
  356.     const char *ep = classend(ms, p);  /* points to what is next */
  357.     int m = s<ms->src_end && singlematch(uchar(*s), p, ep);
  358.     switch (*ep) {
  359.     case '?': {  /* optional */
  360.       const char *res;
  361.       if (m && ((res=match(ms, s+1, ep+1)) != NULL)) {
  362.         s = res;
  363.         break;
  364.       }
  365.       p=ep+1;
  366.       goto init;  /* else s = match(ms, s, ep+1); */
  367.       }
  368.     case '*'/* 0 or more repetitions */
  369.       s = max_expand(ms, s, p, ep);
  370.       break;
  371.     case '+'/* 1 or more repetitions */
  372.       s = (m ? max_expand(ms, s+1, p, ep) : NULL);
  373.       break;
  374.     case '-'/* 0 or more repetitions (minimum) */
  375.       s = min_expand(ms, s, p, ep);
  376.       break;
  377.     default:
  378.       if (m) { s++; p=ep; goto init; }  /* else s = match(ms, s+1, ep); */
  379.       s = NULL;
  380.       break;
  381.     }
  382.     break;
  383.     }
  384.   }
  385.   ms->depth--;
  386.   return s;
  387. }

  388. static void push_onecapture(MatchState *ms, int i, const char *s, const char *e)
  389. {
  390.   if (i >= ms->level) {
  391.     if (i == 0/* ms->level == 0, too */
  392.       lua_pushlstring(ms->L, s, (size_t)(e - s));  /* add whole match */
  393.     else
  394.       lj_err_caller(ms->L, LJ_ERR_STRCAPI);
  395.   } else {
  396.     ptrdiff_t l = ms->capture[i].len;
  397.     if (l == CAP_UNFINISHED) lj_err_caller(ms->L, LJ_ERR_STRCAPU);
  398.     if (l == CAP_POSITION)
  399.       lua_pushinteger(ms->L, ms->capture[i].init - ms->src_init + 1);
  400.     else
  401.       lua_pushlstring(ms->L, ms->capture[i].init, (size_t)l);
  402.   }
  403. }

  404. static int push_captures(MatchState *ms, const char *s, const char *e)
  405. {
  406.   int i;
  407.   int nlevels = (ms->level == 0 && s) ? 1 : ms->level;
  408.   luaL_checkstack(ms->L, nlevels, "too many captures");
  409.   for (i = 0; i < nlevels; i++)
  410.     push_onecapture(ms, i, s, e);
  411.   return nlevels;  /* number of strings pushed */
  412. }

  413. static int str_find_aux(lua_State *L, int find)
  414. {
  415.   GCstr *s = lj_lib_checkstr(L, 1);
  416.   GCstr *p = lj_lib_checkstr(L, 2);
  417.   int32_t start = lj_lib_optint(L, 3, 1);
  418.   MSize st;
  419.   if (start < 0) start += (int32_t)s->len; else start--;
  420.   if (start < 0) start = 0;
  421.   st = (MSize)start;
  422.   if (st > s->len) {
  423. #if LJ_52
  424.     setnilV(L->top-1);
  425.     return 1;
  426. #else
  427.     st = s->len;
  428. #endif
  429.   }
  430.   if (find && ((L->base+3 < L->top && tvistruecond(L->base+3)) ||
  431.                !lj_str_haspattern(p))) {  /* Search for fixed string. */
  432.     const char *q = lj_str_find(strdata(s)+st, strdata(p), s->len-st, p->len);
  433.     if (q) {
  434.       setintV(L->top-2, (int32_t)(q-strdata(s)) + 1);
  435.       setintV(L->top-1, (int32_t)(q-strdata(s)) + (int32_t)p->len);
  436.       return 2;
  437.     }
  438.   } else/* Search for pattern. */
  439.     MatchState ms;
  440.     const char *pstr = strdata(p);
  441.     const char *sstr = strdata(s) + st;
  442.     int anchor = 0;
  443.     if (*pstr == '^') { pstr++; anchor = 1; }
  444.     ms.L = L;
  445.     ms.src_init = strdata(s);
  446.     ms.src_end = strdata(s) + s->len;
  447.     do/* Loop through string and try to match the pattern. */
  448.       const char *q;
  449.       ms.level = ms.depth = 0;
  450.       q = match(&ms, sstr, pstr);
  451.       if (q) {
  452.         if (find) {
  453.           setintV(L->top++, (int32_t)(sstr-(strdata(s)-1)));
  454.           setintV(L->top++, (int32_t)(q-strdata(s)));
  455.           return push_captures(&ms, NULL, NULL) + 2;
  456.         } else {
  457.           return push_captures(&ms, sstr, q);
  458.         }
  459.       }
  460.     } while (sstr++ < ms.src_end && !anchor);
  461.   }
  462.   setnilV(L->top-1);  /* Not found. */
  463.   return 1;
  464. }

  465. LJLIB_CF(string_find)                LJLIB_REC(.)
  466. {
  467.   return str_find_aux(L, 1);
  468. }

  469. LJLIB_CF(string_match)
  470. {
  471.   return str_find_aux(L, 0);
  472. }

  473. LJLIB_NOREG LJLIB_CF(string_gmatch_aux)
  474. {
  475.   const char *p = strVdata(lj_lib_upvalue(L, 2));
  476.   GCstr *str = strV(lj_lib_upvalue(L, 1));
  477.   const char *s = strdata(str);
  478.   TValue *tvpos = lj_lib_upvalue(L, 3);
  479.   const char *src = s + tvpos->u32.lo;
  480.   MatchState ms;
  481.   ms.L = L;
  482.   ms.src_init = s;
  483.   ms.src_end = s + str->len;
  484.   for (; src <= ms.src_end; src++) {
  485.     const char *e;
  486.     ms.level = ms.depth = 0;
  487.     if ((e = match(&ms, src, p)) != NULL) {
  488.       int32_t pos = (int32_t)(e - s);
  489.       if (e == src) pos++;  /* Ensure progress for empty match. */
  490.       tvpos->u32.lo = (uint32_t)pos;
  491.       return push_captures(&ms, src, e);
  492.     }
  493.   }
  494.   return 0/* not found */
  495. }

  496. LJLIB_CF(string_gmatch)
  497. {
  498.   lj_lib_checkstr(L, 1);
  499.   lj_lib_checkstr(L, 2);
  500.   L->top = L->base+3;
  501.   (L->top-1)->u64 = 0;
  502.   lj_lib_pushcc(L, lj_cf_string_gmatch_aux, FF_string_gmatch_aux, 3);
  503.   return 1;
  504. }

  505. static void add_s(MatchState *ms, luaL_Buffer *b, const char *s, const char *e)
  506. {
  507.   size_t l, i;
  508.   const char *news = lua_tolstring(ms->L, 3, &l);
  509.   for (i = 0; i < l; i++) {
  510.     if (news[i] != L_ESC) {
  511.       luaL_addchar(b, news[i]);
  512.     } else {
  513.       i++;  /* skip ESC */
  514.       if (!lj_char_isdigit(uchar(news[i]))) {
  515.         luaL_addchar(b, news[i]);
  516.       } else if (news[i] == '0') {
  517.         luaL_addlstring(b, s, (size_t)(e - s));
  518.       } else {
  519.         push_onecapture(ms, news[i] - '1', s, e);
  520.         luaL_addvalue(b);  /* add capture to accumulated result */
  521.       }
  522.     }
  523.   }
  524. }

  525. static void add_value(MatchState *ms, luaL_Buffer *b,
  526.                       const char *s, const char *e)
  527. {
  528.   lua_State *L = ms->L;
  529.   switch (lua_type(L, 3)) {
  530.     case LUA_TNUMBER:
  531.     case LUA_TSTRING: {
  532.       add_s(ms, b, s, e);
  533.       return;
  534.     }
  535.     case LUA_TFUNCTION: {
  536.       int n;
  537.       lua_pushvalue(L, 3);
  538.       n = push_captures(ms, s, e);
  539.       lua_call(L, n, 1);
  540.       break;
  541.     }
  542.     case LUA_TTABLE: {
  543.       push_onecapture(ms, 0, s, e);
  544.       lua_gettable(L, 3);
  545.       break;
  546.     }
  547.   }
  548.   if (!lua_toboolean(L, -1)) {  /* nil or false? */
  549.     lua_pop(L, 1);
  550.     lua_pushlstring(L, s, (size_t)(e - s));  /* keep original text */
  551.   } else if (!lua_isstring(L, -1)) {
  552.     lj_err_callerv(L, LJ_ERR_STRGSRV, luaL_typename(L, -1));
  553.   }
  554.   luaL_addvalue(b);  /* add result to accumulator */
  555. }

  556. LJLIB_CF(string_gsub)
  557. {
  558.   size_t srcl;
  559.   const char *src = luaL_checklstring(L, 1, &srcl);
  560.   const char *p = luaL_checkstring(L, 2);
  561.   int  tr = lua_type(L, 3);
  562.   int max_s = luaL_optint(L, 4, (int)(srcl+1));
  563.   int anchor = (*p == '^') ? (p++, 1) : 0;
  564.   int n = 0;
  565.   MatchState ms;
  566.   luaL_Buffer b;
  567.   if (!(tr == LUA_TNUMBER || tr == LUA_TSTRING ||
  568.         tr == LUA_TFUNCTION || tr == LUA_TTABLE))
  569.     lj_err_arg(L, 3, LJ_ERR_NOSFT);
  570.   luaL_buffinit(L, &b);
  571.   ms.L = L;
  572.   ms.src_init = src;
  573.   ms.src_end = src+srcl;
  574.   while (n < max_s) {
  575.     const char *e;
  576.     ms.level = ms.depth = 0;
  577.     e = match(&ms, src, p);
  578.     if (e) {
  579.       n++;
  580.       add_value(&ms, &b, src, e);
  581.     }
  582.     if (e && e>src) /* non empty match? */
  583.       src = e;  /* skip it */
  584.     else if (src < ms.src_end)
  585.       luaL_addchar(&b, *src++);
  586.     else
  587.       break;
  588.     if (anchor)
  589.       break;
  590.   }
  591.   luaL_addlstring(&b, src, (size_t)(ms.src_end-src));
  592.   luaL_pushresult(&b);
  593.   lua_pushinteger(L, n);  /* number of substitutions */
  594.   return 2;
  595. }

  596. /* ------------------------------------------------------------------------ */

  597. /* Emulate tostring() inline. */
  598. static GCstr *string_fmt_tostring(lua_State *L, int arg, int retry)
  599. {
  600.   TValue *o = L->base+arg-1;
  601.   cTValue *mo;
  602.   lua_assert(o < L->top);  /* Caller already checks for existence. */
  603.   if (LJ_LIKELY(tvisstr(o)))
  604.     return strV(o);
  605.   if (retry != 2 && !tvisnil(mo = lj_meta_lookup(L, o, MM_tostring))) {
  606.     copyTV(L, L->top++, mo);
  607.     copyTV(L, L->top++, o);
  608.     lua_call(L, 1, 1);
  609.     copyTV(L, L->base+arg-1, --L->top);
  610.     return NULL/* Buffer may be overwritten, retry. */
  611.   }
  612.   return lj_strfmt_obj(L, o);
  613. }

  614. LJLIB_CF(string_format)                LJLIB_REC(.)
  615. {
  616.   int arg, top = (int)(L->top - L->base);
  617.   GCstr *fmt;
  618.   SBuf *sb;
  619.   FormatState fs;
  620.   SFormat sf;
  621.   int retry = 0;
  622. again:
  623.   arg = 1;
  624.   sb = lj_buf_tmp_(L);
  625.   fmt = lj_lib_checkstr(L, arg);
  626.   lj_strfmt_init(&fs, strdata(fmt), fmt->len);
  627.   while ((sf = lj_strfmt_parse(&fs)) != STRFMT_EOF) {
  628.     if (sf == STRFMT_LIT) {
  629.       lj_buf_putmem(sb, fs.str, fs.len);
  630.     } else if (sf == STRFMT_ERR) {
  631.       lj_err_callerv(L, LJ_ERR_STRFMT, strdata(lj_str_new(L, fs.str, fs.len)));
  632.     } else {
  633.       if (++arg > top)
  634.         luaL_argerror(L, arg, lj_obj_typename[0]);
  635.       switch (STRFMT_TYPE(sf)) {
  636.       case STRFMT_INT:
  637.         if (tvisint(L->base+arg-1)) {
  638.           int32_t k = intV(L->base+arg-1);
  639.           if (sf == STRFMT_INT)
  640.             lj_strfmt_putint(sb, k);  /* Shortcut for plain %d. */
  641.           else
  642.             lj_strfmt_putfxint(sb, sf, k);
  643.         } else {
  644.           lj_strfmt_putfnum_int(sb, sf, lj_lib_checknum(L, arg));
  645.         }
  646.         break;
  647.       case STRFMT_UINT:
  648.         if (tvisint(L->base+arg-1))
  649.           lj_strfmt_putfxint(sb, sf, intV(L->base+arg-1));
  650.         else
  651.           lj_strfmt_putfnum_uint(sb, sf, lj_lib_checknum(L, arg));
  652.         break;
  653.       case STRFMT_NUM:
  654.         lj_strfmt_putfnum(sb, sf, lj_lib_checknum(L, arg));
  655.         break;
  656.       case STRFMT_STR: {
  657.         GCstr *str = string_fmt_tostring(L, arg, retry);
  658.         if (str == NULL)
  659.           retry = 1;
  660.         else if ((sf & STRFMT_T_QUOTED))
  661.           lj_strfmt_putquoted(sb, str);  /* No formatting. */
  662.         else
  663.           lj_strfmt_putfstr(sb, sf, str);
  664.         break;
  665.         }
  666.       case STRFMT_CHAR:
  667.         lj_strfmt_putfchar(sb, sf, lj_lib_checkint(L, arg));
  668.         break;
  669.       case STRFMT_PTR:  /* No formatting. */
  670.         lj_strfmt_putptr(sb, lj_obj_ptr(L->base+arg-1));
  671.         break;
  672.       default:
  673.         lua_assert(0);
  674.         break;
  675.       }
  676.     }
  677.   }
  678.   if (retry++ == 1) goto again;
  679.   setstrV(L, L->top-1, lj_buf_str(L, sb));
  680.   lj_gc_check(L);
  681.   return 1;
  682. }

  683. /* ------------------------------------------------------------------------ */

  684. #include "lj_libdef.h"

  685. LUALIB_API int luaopen_string(lua_State *L)
  686. {
  687.   GCtab *mt;
  688.   global_State *g;
  689.   LJ_LIB_REG(L, LUA_STRLIBNAME, string);
  690. #if defined(LUA_COMPAT_GFIND) && !LJ_52
  691.   lua_getfield(L, -1, "gmatch");
  692.   lua_setfield(L, -2, "gfind");
  693. #endif
  694.   mt = lj_tab_new(L, 0, 1);
  695.   /* NOBARRIER: basemt is a GC root. */
  696.   g = G(L);
  697.   setgcref(basemt_it(g, LJ_TSTR), obj2gco(mt));
  698.   settabV(L, lj_tab_setstr(L, mt, mmname_str(g, MM_index)), tabV(L->top-1));
  699.   mt->nomm = (uint8_t)(~(1u<<MM_index));
  700.   return 1;
  701. }