lstrlib.c 25 KB

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