Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 

976 řádky
26 KiB

  1. /*
  2. ** $Id: lstrlib.c,v 1.176 2012/05/23 15:37:09 roberto Exp $
  3. ** Standard library for string operations and pattern-matching
  4. ** See Copyright Notice in lua.h
  5. */
  6. #if defined HAVE_CONFIG_H // LOL BEGIN
  7. # include "config.h"
  8. #endif // LOL END
  9. #include <ctype.h>
  10. #include <stddef.h>
  11. #include <stdio.h>
  12. #include <stdlib.h>
  13. #include <string.h>
  14. #define lstrlib_c
  15. #define LUA_LIB
  16. #include "lua.h"
  17. #include "lauxlib.h"
  18. #include "lualib.h"
  19. /*
  20. ** maximum number of captures that a pattern can do during
  21. ** pattern-matching. This limit is arbitrary.
  22. */
  23. #if !defined(LUA_MAXCAPTURES)
  24. #define LUA_MAXCAPTURES 32
  25. #endif
  26. /* macro to `unsign' a character */
  27. #define uchar(c) ((unsigned char)(c))
  28. static int str_len (lua_State *L) {
  29. size_t l;
  30. luaL_checklstring(L, 1, &l);
  31. lua_pushinteger(L, (lua_Integer)l);
  32. return 1;
  33. }
  34. /* translate a relative string position: negative means back from end */
  35. static size_t posrelat (ptrdiff_t pos, size_t len) {
  36. if (pos >= 0) return (size_t)pos;
  37. else if (0u - (size_t)pos > len) return 0;
  38. else return len - ((size_t)-pos) + 1;
  39. }
  40. static int str_sub (lua_State *L) {
  41. size_t l;
  42. const char *s = luaL_checklstring(L, 1, &l);
  43. size_t start = posrelat(luaL_checkinteger(L, 2), l);
  44. size_t end = posrelat(luaL_optinteger(L, 3, -1), l);
  45. if (start < 1) start = 1;
  46. if (end > l) end = l;
  47. if (start <= end)
  48. lua_pushlstring(L, s + start - 1, end - start + 1);
  49. else lua_pushliteral(L, "");
  50. return 1;
  51. }
  52. static int str_reverse (lua_State *L) {
  53. size_t l, i;
  54. luaL_Buffer b;
  55. const char *s = luaL_checklstring(L, 1, &l);
  56. char *p = luaL_buffinitsize(L, &b, l);
  57. for (i = 0; i < l; i++)
  58. p[i] = s[l - i - 1];
  59. luaL_pushresultsize(&b, l);
  60. return 1;
  61. }
  62. static int str_lower (lua_State *L) {
  63. size_t l;
  64. size_t i;
  65. luaL_Buffer b;
  66. const char *s = luaL_checklstring(L, 1, &l);
  67. char *p = luaL_buffinitsize(L, &b, l);
  68. for (i=0; i<l; i++)
  69. p[i] = tolower(uchar(s[i]));
  70. luaL_pushresultsize(&b, l);
  71. return 1;
  72. }
  73. static int str_upper (lua_State *L) {
  74. size_t l;
  75. size_t i;
  76. luaL_Buffer b;
  77. const char *s = luaL_checklstring(L, 1, &l);
  78. char *p = luaL_buffinitsize(L, &b, l);
  79. for (i=0; i<l; i++)
  80. p[i] = toupper(uchar(s[i]));
  81. luaL_pushresultsize(&b, l);
  82. return 1;
  83. }
  84. /* reasonable limit to avoid arithmetic overflow */
  85. #define MAXSIZE ((~(size_t)0) >> 1)
  86. static int str_rep (lua_State *L) {
  87. size_t l, lsep;
  88. const char *s = luaL_checklstring(L, 1, &l);
  89. int n = luaL_checkint(L, 2);
  90. const char *sep = luaL_optlstring(L, 3, "", &lsep);
  91. if (n <= 0) lua_pushliteral(L, "");
  92. else if (l + lsep < l || l + lsep >= MAXSIZE / n) /* may overflow? */
  93. return luaL_error(L, "resulting string too large");
  94. else {
  95. size_t totallen = n * l + (n - 1) * lsep;
  96. luaL_Buffer b;
  97. char *p = luaL_buffinitsize(L, &b, totallen);
  98. while (n-- > 1) { /* first n-1 copies (followed by separator) */
  99. memcpy(p, s, l * sizeof(char)); p += l;
  100. if (lsep > 0) { /* avoid empty 'memcpy' (may be expensive) */
  101. memcpy(p, sep, lsep * sizeof(char)); p += lsep;
  102. }
  103. }
  104. memcpy(p, s, l * sizeof(char)); /* last copy (not followed by separator) */
  105. luaL_pushresultsize(&b, totallen);
  106. }
  107. return 1;
  108. }
  109. static int str_byte (lua_State *L) {
  110. size_t l;
  111. const char *s = luaL_checklstring(L, 1, &l);
  112. size_t posi = posrelat(luaL_optinteger(L, 2, 1), l);
  113. size_t pose = posrelat(luaL_optinteger(L, 3, posi), l);
  114. int n, i;
  115. if (posi < 1) posi = 1;
  116. if (pose > l) pose = l;
  117. if (posi > pose) return 0; /* empty interval; return no values */
  118. n = (int)(pose - posi + 1);
  119. if (posi + n <= pose) /* (size_t -> int) overflow? */
  120. return luaL_error(L, "string slice too long");
  121. luaL_checkstack(L, n, "string slice too long");
  122. for (i=0; i<n; i++)
  123. lua_pushinteger(L, uchar(s[posi+i-1]));
  124. return n;
  125. }
  126. static int str_char (lua_State *L) {
  127. int n = lua_gettop(L); /* number of arguments */
  128. int i;
  129. luaL_Buffer b;
  130. char *p = luaL_buffinitsize(L, &b, n);
  131. for (i=1; i<=n; i++) {
  132. int c = luaL_checkint(L, i);
  133. luaL_argcheck(L, uchar(c) == c, i, "value out of range");
  134. p[i - 1] = uchar(c);
  135. }
  136. luaL_pushresultsize(&b, n);
  137. return 1;
  138. }
  139. static int writer (lua_State *L, const void* b, size_t size, void* B) {
  140. (void)L;
  141. luaL_addlstring((luaL_Buffer*) B, (const char *)b, size);
  142. return 0;
  143. }
  144. static int str_dump (lua_State *L) {
  145. luaL_Buffer b;
  146. luaL_checktype(L, 1, LUA_TFUNCTION);
  147. lua_settop(L, 1);
  148. luaL_buffinit(L,&b);
  149. if (lua_dump(L, writer, &b) != 0)
  150. return luaL_error(L, "unable to dump given function");
  151. luaL_pushresult(&b);
  152. return 1;
  153. }
  154. /*
  155. ** {======================================================
  156. ** PATTERN MATCHING
  157. ** =======================================================
  158. */
  159. #define CAP_UNFINISHED (-1)
  160. #define CAP_POSITION (-2)
  161. typedef struct MatchState {
  162. const char *src_init; /* init of source string */
  163. const char *src_end; /* end ('\0') of source string */
  164. const char *p_end; /* end ('\0') of pattern */
  165. lua_State *L;
  166. int level; /* total number of captures (finished or unfinished) */
  167. struct {
  168. const char *init;
  169. ptrdiff_t len;
  170. } capture[LUA_MAXCAPTURES];
  171. } MatchState;
  172. #define L_ESC '%'
  173. #define SPECIALS "^$*+?.([%-"
  174. static int check_capture (MatchState *ms, int l) {
  175. l -= '1';
  176. if (l < 0 || l >= ms->level || ms->capture[l].len == CAP_UNFINISHED)
  177. return luaL_error(ms->L, "invalid capture index %%%d", l + 1);
  178. return l;
  179. }
  180. static int capture_to_close (MatchState *ms) {
  181. int level = ms->level;
  182. for (level--; level>=0; level--)
  183. if (ms->capture[level].len == CAP_UNFINISHED) return level;
  184. return luaL_error(ms->L, "invalid pattern capture");
  185. }
  186. static const char *classend (MatchState *ms, const char *p) {
  187. switch (*p++) {
  188. case L_ESC: {
  189. if (p == ms->p_end)
  190. luaL_error(ms->L, "malformed pattern (ends with " LUA_QL("%%") ")");
  191. return p+1;
  192. }
  193. case '[': {
  194. if (*p == '^') p++;
  195. do { /* look for a `]' */
  196. if (p == ms->p_end)
  197. luaL_error(ms->L, "malformed pattern (missing " LUA_QL("]") ")");
  198. if (*(p++) == L_ESC && p < ms->p_end)
  199. p++; /* skip escapes (e.g. `%]') */
  200. } while (*p != ']');
  201. return p+1;
  202. }
  203. default: {
  204. return p;
  205. }
  206. }
  207. }
  208. static int match_class (int c, int cl) {
  209. int res;
  210. switch (tolower(cl)) {
  211. case 'a' : res = isalpha(c); break;
  212. case 'c' : res = iscntrl(c); break;
  213. case 'd' : res = isdigit(c); break;
  214. case 'g' : res = isgraph(c); break;
  215. case 'l' : res = islower(c); break;
  216. case 'p' : res = ispunct(c); break;
  217. case 's' : res = isspace(c); break;
  218. case 'u' : res = isupper(c); break;
  219. case 'w' : res = isalnum(c); break;
  220. case 'x' : res = isxdigit(c); break;
  221. case 'z' : res = (c == 0); break; /* deprecated option */
  222. default: return (cl == c);
  223. }
  224. return (islower(cl) ? res : !res);
  225. }
  226. static int matchbracketclass (int c, const char *p, const char *ec) {
  227. int sig = 1;
  228. if (*(p+1) == '^') {
  229. sig = 0;
  230. p++; /* skip the `^' */
  231. }
  232. while (++p < ec) {
  233. if (*p == L_ESC) {
  234. p++;
  235. if (match_class(c, uchar(*p)))
  236. return sig;
  237. }
  238. else if ((*(p+1) == '-') && (p+2 < ec)) {
  239. p+=2;
  240. if (uchar(*(p-2)) <= c && c <= uchar(*p))
  241. return sig;
  242. }
  243. else if (uchar(*p) == c) return sig;
  244. }
  245. return !sig;
  246. }
  247. static int singlematch (int c, const char *p, const char *ep) {
  248. switch (*p) {
  249. case '.': return 1; /* matches any char */
  250. case L_ESC: return match_class(c, uchar(*(p+1)));
  251. case '[': return matchbracketclass(c, p, ep-1);
  252. default: return (uchar(*p) == c);
  253. }
  254. }
  255. static const char *match (MatchState *ms, const char *s, const char *p);
  256. static const char *matchbalance (MatchState *ms, const char *s,
  257. const char *p) {
  258. if (p >= ms->p_end - 1)
  259. luaL_error(ms->L, "malformed pattern "
  260. "(missing arguments to " LUA_QL("%%b") ")");
  261. if (*s != *p) return NULL;
  262. else {
  263. int b = *p;
  264. int e = *(p+1);
  265. int cont = 1;
  266. while (++s < ms->src_end) {
  267. if (*s == e) {
  268. if (--cont == 0) return s+1;
  269. }
  270. else if (*s == b) cont++;
  271. }
  272. }
  273. return NULL; /* string ends out of balance */
  274. }
  275. static const char *max_expand (MatchState *ms, const char *s,
  276. const char *p, const char *ep) {
  277. ptrdiff_t i = 0; /* counts maximum expand for item */
  278. while ((s+i)<ms->src_end && singlematch(uchar(*(s+i)), p, ep))
  279. i++;
  280. /* keeps trying to match with the maximum repetitions */
  281. while (i>=0) {
  282. const char *res = match(ms, (s+i), ep+1);
  283. if (res) return res;
  284. i--; /* else didn't match; reduce 1 repetition to try again */
  285. }
  286. return NULL;
  287. }
  288. static const char *min_expand (MatchState *ms, const char *s,
  289. const char *p, const char *ep) {
  290. for (;;) {
  291. const char *res = match(ms, s, ep+1);
  292. if (res != NULL)
  293. return res;
  294. else if (s<ms->src_end && singlematch(uchar(*s), p, ep))
  295. s++; /* try with one more repetition */
  296. else return NULL;
  297. }
  298. }
  299. static const char *start_capture (MatchState *ms, const char *s,
  300. const char *p, int what) {
  301. const char *res;
  302. int level = ms->level;
  303. if (level >= LUA_MAXCAPTURES) luaL_error(ms->L, "too many captures");
  304. ms->capture[level].init = s;
  305. ms->capture[level].len = what;
  306. ms->level = level+1;
  307. if ((res=match(ms, s, p)) == NULL) /* match failed? */
  308. ms->level--; /* undo capture */
  309. return res;
  310. }
  311. static const char *end_capture (MatchState *ms, const char *s,
  312. const char *p) {
  313. int l = capture_to_close(ms);
  314. const char *res;
  315. ms->capture[l].len = s - ms->capture[l].init; /* close capture */
  316. if ((res = match(ms, s, p)) == NULL) /* match failed? */
  317. ms->capture[l].len = CAP_UNFINISHED; /* undo capture */
  318. return res;
  319. }
  320. static const char *match_capture (MatchState *ms, const char *s, int l) {
  321. size_t len;
  322. l = check_capture(ms, l);
  323. len = ms->capture[l].len;
  324. if ((size_t)(ms->src_end-s) >= len &&
  325. memcmp(ms->capture[l].init, s, len) == 0)
  326. return s+len;
  327. else return NULL;
  328. }
  329. static const char *match (MatchState *ms, const char *s, const char *p) {
  330. init: /* using goto's to optimize tail recursion */
  331. if (p == ms->p_end) /* end of pattern? */
  332. return s; /* match succeeded */
  333. switch (*p) {
  334. case '(': { /* start capture */
  335. if (*(p+1) == ')') /* position capture? */
  336. return start_capture(ms, s, p+2, CAP_POSITION);
  337. else
  338. return start_capture(ms, s, p+1, CAP_UNFINISHED);
  339. }
  340. case ')': { /* end capture */
  341. return end_capture(ms, s, p+1);
  342. }
  343. case '$': {
  344. if ((p+1) == ms->p_end) /* is the `$' the last char in pattern? */
  345. return (s == ms->src_end) ? s : NULL; /* check end of string */
  346. else goto dflt;
  347. }
  348. case L_ESC: { /* escaped sequences not in the format class[*+?-]? */
  349. switch (*(p+1)) {
  350. case 'b': { /* balanced string? */
  351. s = matchbalance(ms, s, p+2);
  352. if (s == NULL) return NULL;
  353. p+=4; goto init; /* else return match(ms, s, p+4); */
  354. }
  355. case 'f': { /* frontier? */
  356. const char *ep; char previous;
  357. p += 2;
  358. if (*p != '[')
  359. luaL_error(ms->L, "missing " LUA_QL("[") " after "
  360. LUA_QL("%%f") " in pattern");
  361. ep = classend(ms, p); /* points to what is next */
  362. previous = (s == ms->src_init) ? '\0' : *(s-1);
  363. if (matchbracketclass(uchar(previous), p, ep-1) ||
  364. !matchbracketclass(uchar(*s), p, ep-1)) return NULL;
  365. p=ep; goto init; /* else return match(ms, s, ep); */
  366. }
  367. case '0': case '1': case '2': case '3':
  368. case '4': case '5': case '6': case '7':
  369. case '8': case '9': { /* capture results (%0-%9)? */
  370. s = match_capture(ms, s, uchar(*(p+1)));
  371. if (s == NULL) return NULL;
  372. p+=2; goto init; /* else return match(ms, s, p+2) */
  373. }
  374. default: goto dflt;
  375. }
  376. }
  377. default: dflt: { /* pattern class plus optional suffix */
  378. const char *ep = classend(ms, p); /* points to what is next */
  379. int m = s < ms->src_end && singlematch(uchar(*s), p, ep);
  380. switch (*ep) {
  381. case '?': { /* optional */
  382. const char *res;
  383. if (m && ((res=match(ms, s+1, ep+1)) != NULL))
  384. return res;
  385. p=ep+1; goto init; /* else return match(ms, s, ep+1); */
  386. }
  387. case '*': { /* 0 or more repetitions */
  388. return max_expand(ms, s, p, ep);
  389. }
  390. case '+': { /* 1 or more repetitions */
  391. return (m ? max_expand(ms, s+1, p, ep) : NULL);
  392. }
  393. case '-': { /* 0 or more repetitions (minimum) */
  394. return min_expand(ms, s, p, ep);
  395. }
  396. default: {
  397. if (!m) return NULL;
  398. s++; p=ep; goto init; /* else return match(ms, s+1, ep); */
  399. }
  400. }
  401. }
  402. }
  403. }
  404. static const char *lmemfind (const char *s1, size_t l1,
  405. const char *s2, size_t l2) {
  406. if (l2 == 0) return s1; /* empty strings are everywhere */
  407. else if (l2 > l1) return NULL; /* avoids a negative `l1' */
  408. else {
  409. const char *init; /* to search for a `*s2' inside `s1' */
  410. l2--; /* 1st char will be checked by `memchr' */
  411. l1 = l1-l2; /* `s2' cannot be found after that */
  412. while (l1 > 0 && (init = (const char *)memchr(s1, *s2, l1)) != NULL) {
  413. init++; /* 1st char is already checked */
  414. if (memcmp(init, s2+1, l2) == 0)
  415. return init-1;
  416. else { /* correct `l1' and `s1' to try again */
  417. l1 -= init-s1;
  418. s1 = init;
  419. }
  420. }
  421. return NULL; /* not found */
  422. }
  423. }
  424. static void push_onecapture (MatchState *ms, int i, const char *s,
  425. const char *e) {
  426. if (i >= ms->level) {
  427. if (i == 0) /* ms->level == 0, too */
  428. lua_pushlstring(ms->L, s, e - s); /* add whole match */
  429. else
  430. luaL_error(ms->L, "invalid capture index");
  431. }
  432. else {
  433. ptrdiff_t l = ms->capture[i].len;
  434. if (l == CAP_UNFINISHED) luaL_error(ms->L, "unfinished capture");
  435. if (l == CAP_POSITION)
  436. lua_pushinteger(ms->L, ms->capture[i].init - ms->src_init + 1);
  437. else
  438. lua_pushlstring(ms->L, ms->capture[i].init, l);
  439. }
  440. }
  441. static int push_captures (MatchState *ms, const char *s, const char *e) {
  442. int i;
  443. int nlevels = (ms->level == 0 && s) ? 1 : ms->level;
  444. luaL_checkstack(ms->L, nlevels, "too many captures");
  445. for (i = 0; i < nlevels; i++)
  446. push_onecapture(ms, i, s, e);
  447. return nlevels; /* number of strings pushed */
  448. }
  449. /* check whether pattern has no special characters */
  450. static int nospecials (const char *p, size_t l) {
  451. size_t upto = 0;
  452. do {
  453. if (strpbrk(p + upto, SPECIALS))
  454. return 0; /* pattern has a special character */
  455. upto += strlen(p + upto) + 1; /* may have more after \0 */
  456. } while (upto <= l);
  457. return 1; /* no special chars found */
  458. }
  459. static int str_find_aux (lua_State *L, int find) {
  460. size_t ls, lp;
  461. const char *s = luaL_checklstring(L, 1, &ls);
  462. const char *p = luaL_checklstring(L, 2, &lp);
  463. size_t init = posrelat(luaL_optinteger(L, 3, 1), ls);
  464. if (init < 1) init = 1;
  465. else if (init > ls + 1) { /* start after string's end? */
  466. lua_pushnil(L); /* cannot find anything */
  467. return 1;
  468. }
  469. /* explicit request or no special characters? */
  470. if (find && (lua_toboolean(L, 4) || nospecials(p, lp))) {
  471. /* do a plain search */
  472. const char *s2 = lmemfind(s + init - 1, ls - init + 1, p, lp);
  473. if (s2) {
  474. lua_pushinteger(L, s2 - s + 1);
  475. lua_pushinteger(L, s2 - s + lp);
  476. return 2;
  477. }
  478. }
  479. else {
  480. MatchState ms;
  481. const char *s1 = s + init - 1;
  482. int anchor = (*p == '^');
  483. if (anchor) {
  484. p++; lp--; /* skip anchor character */
  485. }
  486. ms.L = L;
  487. ms.src_init = s;
  488. ms.src_end = s + ls;
  489. ms.p_end = p + lp;
  490. do {
  491. const char *res;
  492. ms.level = 0;
  493. if ((res=match(&ms, s1, p)) != NULL) {
  494. if (find) {
  495. lua_pushinteger(L, s1 - s + 1); /* start */
  496. lua_pushinteger(L, res - s); /* end */
  497. return push_captures(&ms, NULL, 0) + 2;
  498. }
  499. else
  500. return push_captures(&ms, s1, res);
  501. }
  502. } while (s1++ < ms.src_end && !anchor);
  503. }
  504. lua_pushnil(L); /* not found */
  505. return 1;
  506. }
  507. static int str_find (lua_State *L) {
  508. return str_find_aux(L, 1);
  509. }
  510. static int str_match (lua_State *L) {
  511. return str_find_aux(L, 0);
  512. }
  513. static int gmatch_aux (lua_State *L) {
  514. MatchState ms;
  515. size_t ls, lp;
  516. const char *s = lua_tolstring(L, lua_upvalueindex(1), &ls);
  517. const char *p = lua_tolstring(L, lua_upvalueindex(2), &lp);
  518. const char *src;
  519. ms.L = L;
  520. ms.src_init = s;
  521. ms.src_end = s+ls;
  522. ms.p_end = p + lp;
  523. for (src = s + (size_t)lua_tointeger(L, lua_upvalueindex(3));
  524. src <= ms.src_end;
  525. src++) {
  526. const char *e;
  527. ms.level = 0;
  528. if ((e = match(&ms, src, p)) != NULL) {
  529. lua_Integer newstart = e-s;
  530. if (e == src) newstart++; /* empty match? go at least one position */
  531. lua_pushinteger(L, newstart);
  532. lua_replace(L, lua_upvalueindex(3));
  533. return push_captures(&ms, src, e);
  534. }
  535. }
  536. return 0; /* not found */
  537. }
  538. static int gmatch (lua_State *L) {
  539. luaL_checkstring(L, 1);
  540. luaL_checkstring(L, 2);
  541. lua_settop(L, 2);
  542. lua_pushinteger(L, 0);
  543. lua_pushcclosure(L, gmatch_aux, 3);
  544. return 1;
  545. }
  546. static void add_s (MatchState *ms, luaL_Buffer *b, const char *s,
  547. const char *e) {
  548. size_t l, i;
  549. const char *news = lua_tolstring(ms->L, 3, &l);
  550. for (i = 0; i < l; i++) {
  551. if (news[i] != L_ESC)
  552. luaL_addchar(b, news[i]);
  553. else {
  554. i++; /* skip ESC */
  555. if (!isdigit(uchar(news[i]))) {
  556. if (news[i] != L_ESC)
  557. luaL_error(ms->L, "invalid use of " LUA_QL("%c")
  558. " in replacement string", L_ESC);
  559. luaL_addchar(b, news[i]);
  560. }
  561. else if (news[i] == '0')
  562. luaL_addlstring(b, s, e - s);
  563. else {
  564. push_onecapture(ms, news[i] - '1', s, e);
  565. luaL_addvalue(b); /* add capture to accumulated result */
  566. }
  567. }
  568. }
  569. }
  570. static void add_value (MatchState *ms, luaL_Buffer *b, const char *s,
  571. const char *e, int tr) {
  572. lua_State *L = ms->L;
  573. switch (tr) {
  574. case LUA_TFUNCTION: {
  575. int n;
  576. lua_pushvalue(L, 3);
  577. n = push_captures(ms, s, e);
  578. lua_call(L, n, 1);
  579. break;
  580. }
  581. case LUA_TTABLE: {
  582. push_onecapture(ms, 0, s, e);
  583. lua_gettable(L, 3);
  584. break;
  585. }
  586. default: { /* LUA_TNUMBER or LUA_TSTRING */
  587. add_s(ms, b, s, e);
  588. return;
  589. }
  590. }
  591. if (!lua_toboolean(L, -1)) { /* nil or false? */
  592. lua_pop(L, 1);
  593. lua_pushlstring(L, s, e - s); /* keep original text */
  594. }
  595. else if (!lua_isstring(L, -1))
  596. luaL_error(L, "invalid replacement value (a %s)", luaL_typename(L, -1));
  597. luaL_addvalue(b); /* add result to accumulator */
  598. }
  599. static int str_gsub (lua_State *L) {
  600. size_t srcl, lp;
  601. const char *src = luaL_checklstring(L, 1, &srcl);
  602. const char *p = luaL_checklstring(L, 2, &lp);
  603. int tr = lua_type(L, 3);
  604. size_t max_s = luaL_optinteger(L, 4, srcl+1);
  605. int anchor = (*p == '^');
  606. size_t n = 0;
  607. MatchState ms;
  608. luaL_Buffer b;
  609. luaL_argcheck(L, tr == LUA_TNUMBER || tr == LUA_TSTRING ||
  610. tr == LUA_TFUNCTION || tr == LUA_TTABLE, 3,
  611. "string/function/table expected");
  612. luaL_buffinit(L, &b);
  613. if (anchor) {
  614. p++; lp--; /* skip anchor character */
  615. }
  616. ms.L = L;
  617. ms.src_init = src;
  618. ms.src_end = src+srcl;
  619. ms.p_end = p + lp;
  620. while (n < max_s) {
  621. const char *e;
  622. ms.level = 0;
  623. e = match(&ms, src, p);
  624. if (e) {
  625. n++;
  626. add_value(&ms, &b, src, e, tr);
  627. }
  628. if (e && e>src) /* non empty match? */
  629. src = e; /* skip it */
  630. else if (src < ms.src_end)
  631. luaL_addchar(&b, *src++);
  632. else break;
  633. if (anchor) break;
  634. }
  635. luaL_addlstring(&b, src, ms.src_end-src);
  636. luaL_pushresult(&b);
  637. lua_pushinteger(L, n); /* number of substitutions */
  638. return 2;
  639. }
  640. /* }====================================================== */
  641. /*
  642. ** {======================================================
  643. ** STRING FORMAT
  644. ** =======================================================
  645. */
  646. /*
  647. ** LUA_INTFRMLEN is the length modifier for integer conversions in
  648. ** 'string.format'; LUA_INTFRM_T is the integer type corresponding to
  649. ** the previous length
  650. */
  651. #if !defined(LUA_INTFRMLEN) /* { */
  652. #if defined(LUA_USE_LONGLONG)
  653. #define LUA_INTFRMLEN "ll"
  654. #define LUA_INTFRM_T long long
  655. #else
  656. #define LUA_INTFRMLEN "l"
  657. #define LUA_INTFRM_T long
  658. #endif
  659. #endif /* } */
  660. /*
  661. ** LUA_FLTFRMLEN is the length modifier for float conversions in
  662. ** 'string.format'; LUA_FLTFRM_T is the float type corresponding to
  663. ** the previous length
  664. */
  665. #if !defined(LUA_FLTFRMLEN)
  666. #define LUA_FLTFRMLEN ""
  667. #define LUA_FLTFRM_T double
  668. #endif
  669. /* maximum size of each formatted item (> len(format('%99.99f', -1e308))) */
  670. #define MAX_ITEM 512
  671. /* valid flags in a format specification */
  672. #define FLAGS "-+ #0"
  673. /*
  674. ** maximum size of each format specification (such as '%-099.99d')
  675. ** (+10 accounts for %99.99x plus margin of error)
  676. */
  677. #define MAX_FORMAT (sizeof(FLAGS) + sizeof(LUA_INTFRMLEN) + 10)
  678. static void addquoted (lua_State *L, luaL_Buffer *b, int arg) {
  679. size_t l;
  680. const char *s = luaL_checklstring(L, arg, &l);
  681. luaL_addchar(b, '"');
  682. while (l--) {
  683. if (*s == '"' || *s == '\\' || *s == '\n') {
  684. luaL_addchar(b, '\\');
  685. luaL_addchar(b, *s);
  686. }
  687. else if (*s == '\0' || iscntrl(uchar(*s))) {
  688. char buff[10];
  689. if (!isdigit(uchar(*(s+1))))
  690. sprintf(buff, "\\%d", (int)uchar(*s));
  691. else
  692. sprintf(buff, "\\%03d", (int)uchar(*s));
  693. luaL_addstring(b, buff);
  694. }
  695. else
  696. luaL_addchar(b, *s);
  697. s++;
  698. }
  699. luaL_addchar(b, '"');
  700. }
  701. static const char *scanformat (lua_State *L, const char *strfrmt, char *form) {
  702. const char *p = strfrmt;
  703. while (*p != '\0' && strchr(FLAGS, *p) != NULL) p++; /* skip flags */
  704. if ((size_t)(p - strfrmt) >= sizeof(FLAGS)/sizeof(char))
  705. luaL_error(L, "invalid format (repeated flags)");
  706. if (isdigit(uchar(*p))) p++; /* skip width */
  707. if (isdigit(uchar(*p))) p++; /* (2 digits at most) */
  708. if (*p == '.') {
  709. p++;
  710. if (isdigit(uchar(*p))) p++; /* skip precision */
  711. if (isdigit(uchar(*p))) p++; /* (2 digits at most) */
  712. }
  713. if (isdigit(uchar(*p)))
  714. luaL_error(L, "invalid format (width or precision too long)");
  715. *(form++) = '%';
  716. memcpy(form, strfrmt, (p - strfrmt + 1) * sizeof(char));
  717. form += p - strfrmt + 1;
  718. *form = '\0';
  719. return p;
  720. }
  721. /*
  722. ** add length modifier into formats
  723. */
  724. static void addlenmod (char *form, const char *lenmod) {
  725. size_t l = strlen(form);
  726. size_t lm = strlen(lenmod);
  727. char spec = form[l - 1];
  728. strcpy(form + l - 1, lenmod);
  729. form[l + lm - 1] = spec;
  730. form[l + lm] = '\0';
  731. }
  732. static int str_format (lua_State *L) {
  733. int top = lua_gettop(L);
  734. int arg = 1;
  735. size_t sfl;
  736. const char *strfrmt = luaL_checklstring(L, arg, &sfl);
  737. const char *strfrmt_end = strfrmt+sfl;
  738. luaL_Buffer b;
  739. luaL_buffinit(L, &b);
  740. while (strfrmt < strfrmt_end) {
  741. if (*strfrmt != L_ESC)
  742. luaL_addchar(&b, *strfrmt++);
  743. else if (*++strfrmt == L_ESC)
  744. luaL_addchar(&b, *strfrmt++); /* %% */
  745. else { /* format item */
  746. char form[MAX_FORMAT]; /* to store the format (`%...') */
  747. char *buff = luaL_prepbuffsize(&b, MAX_ITEM); /* to put formatted item */
  748. int nb = 0; /* number of bytes in added item */
  749. if (++arg > top)
  750. luaL_argerror(L, arg, "no value");
  751. strfrmt = scanformat(L, strfrmt, form);
  752. switch (*strfrmt++) {
  753. case 'c': {
  754. nb = sprintf(buff, form, luaL_checkint(L, arg));
  755. break;
  756. }
  757. case 'd': case 'i': {
  758. lua_Number n = luaL_checknumber(L, arg);
  759. LUA_INTFRM_T ni = (LUA_INTFRM_T)n;
  760. lua_Number diff = n - (lua_Number)ni;
  761. luaL_argcheck(L, -1 < diff && diff < 1, arg,
  762. "not a number in proper range");
  763. addlenmod(form, LUA_INTFRMLEN);
  764. nb = sprintf(buff, form, ni);
  765. break;
  766. }
  767. case 'o': case 'u': case 'x': case 'X': {
  768. lua_Number n = luaL_checknumber(L, arg);
  769. unsigned LUA_INTFRM_T ni = (unsigned LUA_INTFRM_T)n;
  770. lua_Number diff = n - (lua_Number)ni;
  771. luaL_argcheck(L, -1 < diff && diff < 1, arg,
  772. "not a non-negative number in proper range");
  773. addlenmod(form, LUA_INTFRMLEN);
  774. nb = sprintf(buff, form, ni);
  775. break;
  776. }
  777. case 'e': case 'E': case 'f':
  778. #if defined(LUA_USE_AFORMAT)
  779. case 'a': case 'A':
  780. #endif
  781. case 'g': case 'G': {
  782. addlenmod(form, LUA_FLTFRMLEN);
  783. nb = sprintf(buff, form, (LUA_FLTFRM_T)luaL_checknumber(L, arg));
  784. break;
  785. }
  786. case 'q': {
  787. addquoted(L, &b, arg);
  788. break;
  789. }
  790. case 's': {
  791. size_t l;
  792. const char *s = luaL_tolstring(L, arg, &l);
  793. if (!strchr(form, '.') && l >= 100) {
  794. /* no precision and string is too long to be formatted;
  795. keep original string */
  796. luaL_addvalue(&b);
  797. break;
  798. }
  799. else {
  800. nb = sprintf(buff, form, s);
  801. lua_pop(L, 1); /* remove result from 'luaL_tolstring' */
  802. break;
  803. }
  804. }
  805. default: { /* also treat cases `pnLlh' */
  806. return luaL_error(L, "invalid option " LUA_QL("%%%c") " to "
  807. LUA_QL("format"), *(strfrmt - 1));
  808. }
  809. }
  810. luaL_addsize(&b, nb);
  811. }
  812. }
  813. luaL_pushresult(&b);
  814. return 1;
  815. }
  816. /* }====================================================== */
  817. static const luaL_Reg strlib[] = {
  818. {"byte", str_byte},
  819. {"char", str_char},
  820. {"dump", str_dump},
  821. {"find", str_find},
  822. {"format", str_format},
  823. {"gmatch", gmatch},
  824. {"gsub", str_gsub},
  825. {"len", str_len},
  826. {"lower", str_lower},
  827. {"match", str_match},
  828. {"rep", str_rep},
  829. {"reverse", str_reverse},
  830. {"sub", str_sub},
  831. {"upper", str_upper},
  832. {NULL, NULL}
  833. };
  834. static void createmetatable (lua_State *L) {
  835. lua_createtable(L, 0, 1); /* table to be metatable for strings */
  836. lua_pushliteral(L, ""); /* dummy string */
  837. lua_pushvalue(L, -2); /* copy table */
  838. lua_setmetatable(L, -2); /* set table as metatable for strings */
  839. lua_pop(L, 1); /* pop dummy string */
  840. lua_pushvalue(L, -2); /* get string library */
  841. lua_setfield(L, -2, "__index"); /* metatable.__index = string */
  842. lua_pop(L, 1); /* pop metatable */
  843. }
  844. /*
  845. ** Open string library
  846. */
  847. LUAMOD_API int luaopen_string (lua_State *L) {
  848. luaL_newlib(L, strlib);
  849. createmetatable(L);
  850. return 1;
  851. }