2
0

lstrlib.c 26 KB

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