lstrlib.c 26 KB

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