lstrlib.c 27 KB

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