lstrlib.c 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920
  1. /*
  2. ** $Id: lstrlib.c,v 1.154 2010/07/02 11:38:13 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 sufix */
  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. static int str_find_aux (lua_State *L, int find) {
  433. size_t ls, lp;
  434. const char *s = luaL_checklstring(L, 1, &ls);
  435. const char *p = luaL_checklstring(L, 2, &lp);
  436. size_t init = posrelat(luaL_optinteger(L, 3, 1), ls);
  437. if (init < 1) init = 1;
  438. else if (init > ls + 1) { /* start after string's end? */
  439. lua_pushnil(L); /* cannot find anything */
  440. return 1;
  441. }
  442. if (find && (lua_toboolean(L, 4) || /* explicit request? */
  443. strpbrk(p, SPECIALS) == NULL)) { /* or no special characters? */
  444. /* do a plain search */
  445. const char *s2 = lmemfind(s + init - 1, ls - init + 1, p, lp);
  446. if (s2) {
  447. lua_pushinteger(L, s2 - s + 1);
  448. lua_pushinteger(L, s2 - s + lp);
  449. return 2;
  450. }
  451. }
  452. else {
  453. MatchState ms;
  454. const char *s1 = s + init - 1;
  455. int anchor = (*p == '^');
  456. if (anchor) {
  457. p++; lp--; /* skip anchor character */
  458. }
  459. ms.L = L;
  460. ms.src_init = s;
  461. ms.src_end = s + ls;
  462. ms.p_end = p + lp;
  463. do {
  464. const char *res;
  465. ms.level = 0;
  466. if ((res=match(&ms, s1, p)) != NULL) {
  467. if (find) {
  468. lua_pushinteger(L, s1 - s + 1); /* start */
  469. lua_pushinteger(L, res - s); /* end */
  470. return push_captures(&ms, NULL, 0) + 2;
  471. }
  472. else
  473. return push_captures(&ms, s1, res);
  474. }
  475. } while (s1++ < ms.src_end && !anchor);
  476. }
  477. lua_pushnil(L); /* not found */
  478. return 1;
  479. }
  480. static int str_find (lua_State *L) {
  481. return str_find_aux(L, 1);
  482. }
  483. static int str_match (lua_State *L) {
  484. return str_find_aux(L, 0);
  485. }
  486. static int gmatch_aux (lua_State *L) {
  487. MatchState ms;
  488. size_t ls, lp;
  489. const char *s = lua_tolstring(L, lua_upvalueindex(1), &ls);
  490. const char *p = lua_tolstring(L, lua_upvalueindex(2), &lp);
  491. const char *src;
  492. ms.L = L;
  493. ms.src_init = s;
  494. ms.src_end = s+ls;
  495. ms.p_end = p + lp;
  496. for (src = s + (size_t)lua_tointeger(L, lua_upvalueindex(3));
  497. src <= ms.src_end;
  498. src++) {
  499. const char *e;
  500. ms.level = 0;
  501. if ((e = match(&ms, src, p)) != NULL) {
  502. lua_Integer newstart = e-s;
  503. if (e == src) newstart++; /* empty match? go at least one position */
  504. lua_pushinteger(L, newstart);
  505. lua_replace(L, lua_upvalueindex(3));
  506. return push_captures(&ms, src, e);
  507. }
  508. }
  509. return 0; /* not found */
  510. }
  511. static int gmatch (lua_State *L) {
  512. luaL_checkstring(L, 1);
  513. luaL_checkstring(L, 2);
  514. lua_settop(L, 2);
  515. lua_pushinteger(L, 0);
  516. lua_pushcclosure(L, gmatch_aux, 3);
  517. return 1;
  518. }
  519. static int gfind_nodef (lua_State *L) {
  520. return luaL_error(L, LUA_QL("string.gfind") " was renamed to "
  521. LUA_QL("string.gmatch"));
  522. }
  523. static void add_s (MatchState *ms, luaL_Buffer *b, const char *s,
  524. const char *e) {
  525. size_t l, i;
  526. const char *news = lua_tolstring(ms->L, 3, &l);
  527. for (i = 0; i < l; i++) {
  528. if (news[i] != L_ESC)
  529. luaL_addchar(b, news[i]);
  530. else {
  531. i++; /* skip ESC */
  532. if (!isdigit(uchar(news[i]))) {
  533. if (news[i] != L_ESC)
  534. luaL_error(ms->L, "invalid use of " LUA_QL("%c")
  535. " in replacement string", L_ESC);
  536. luaL_addchar(b, news[i]);
  537. }
  538. else if (news[i] == '0')
  539. luaL_addlstring(b, s, e - s);
  540. else {
  541. push_onecapture(ms, news[i] - '1', s, e);
  542. luaL_addvalue(b); /* add capture to accumulated result */
  543. }
  544. }
  545. }
  546. }
  547. static void add_value (MatchState *ms, luaL_Buffer *b, const char *s,
  548. const char *e, int tr) {
  549. lua_State *L = ms->L;
  550. switch (tr) {
  551. case LUA_TFUNCTION: {
  552. int n;
  553. lua_pushvalue(L, 3);
  554. n = push_captures(ms, s, e);
  555. lua_call(L, n, 1);
  556. break;
  557. }
  558. case LUA_TTABLE: {
  559. push_onecapture(ms, 0, s, e);
  560. lua_gettable(L, 3);
  561. break;
  562. }
  563. default: { /* LUA_TNUMBER or LUA_TSTRING */
  564. add_s(ms, b, s, e);
  565. return;
  566. }
  567. }
  568. if (!lua_toboolean(L, -1)) { /* nil or false? */
  569. lua_pop(L, 1);
  570. lua_pushlstring(L, s, e - s); /* keep original text */
  571. }
  572. else if (!lua_isstring(L, -1))
  573. luaL_error(L, "invalid replacement value (a %s)", luaL_typename(L, -1));
  574. luaL_addvalue(b); /* add result to accumulator */
  575. }
  576. static int str_gsub (lua_State *L) {
  577. size_t srcl, lp;
  578. const char *src = luaL_checklstring(L, 1, &srcl);
  579. const char *p = luaL_checklstring(L, 2, &lp);
  580. int tr = lua_type(L, 3);
  581. size_t max_s = luaL_optinteger(L, 4, srcl+1);
  582. int anchor = (*p == '^');
  583. size_t n = 0;
  584. MatchState ms;
  585. luaL_Buffer b;
  586. luaL_argcheck(L, tr == LUA_TNUMBER || tr == LUA_TSTRING ||
  587. tr == LUA_TFUNCTION || tr == LUA_TTABLE, 3,
  588. "string/function/table expected");
  589. luaL_buffinit(L, &b);
  590. if (anchor) {
  591. p++; lp--; /* skip anchor character */
  592. }
  593. ms.L = L;
  594. ms.src_init = src;
  595. ms.src_end = src+srcl;
  596. ms.p_end = p + lp;
  597. while (n < max_s) {
  598. const char *e;
  599. ms.level = 0;
  600. e = match(&ms, src, p);
  601. if (e) {
  602. n++;
  603. add_value(&ms, &b, src, e, tr);
  604. }
  605. if (e && e>src) /* non empty match? */
  606. src = e; /* skip it */
  607. else if (src < ms.src_end)
  608. luaL_addchar(&b, *src++);
  609. else break;
  610. if (anchor) break;
  611. }
  612. luaL_addlstring(&b, src, ms.src_end-src);
  613. luaL_pushresult(&b);
  614. lua_pushinteger(L, n); /* number of substitutions */
  615. return 2;
  616. }
  617. /* }====================================================== */
  618. /*
  619. ** {======================================================
  620. ** STRING FORMAT
  621. ** =======================================================
  622. */
  623. /*
  624. ** LUA_INTFRMLEN is the length modifier for integer conversions in
  625. ** 'string.format'; LUA_INTFRM_T is the integer type corresponding to
  626. ** the previous length
  627. */
  628. #if defined(LUA_USELONGLONG)
  629. #define LUA_INTFRMLEN "ll"
  630. #define LUA_INTFRM_T long long
  631. #else
  632. #define LUA_INTFRMLEN "l"
  633. #define LUA_INTFRM_T long
  634. #endif
  635. /* maximum size of each formatted item (> len(format('%99.99f', -1e308))) */
  636. #define MAX_ITEM 512
  637. /* valid flags in a format specification */
  638. #define FLAGS "-+ #0"
  639. /*
  640. ** maximum size of each format specification (such as '%-099.99d')
  641. ** (+10 accounts for %99.99x plus margin of error)
  642. */
  643. #define MAX_FORMAT (sizeof(FLAGS) + sizeof(LUA_INTFRMLEN) + 10)
  644. static void addquoted (lua_State *L, luaL_Buffer *b, int arg) {
  645. size_t l;
  646. const char *s = luaL_checklstring(L, arg, &l);
  647. luaL_addchar(b, '"');
  648. while (l--) {
  649. if (*s == '"' || *s == '\\' || *s == '\n') {
  650. luaL_addchar(b, '\\');
  651. luaL_addchar(b, *s);
  652. }
  653. else if (*s == '\0' || iscntrl(uchar(*s))) {
  654. char buff[10];
  655. if (!isdigit(uchar(*(s+1))))
  656. sprintf(buff, "\\%d", (int)uchar(*s));
  657. else
  658. sprintf(buff, "\\%03d", (int)uchar(*s));
  659. luaL_addstring(b, buff);
  660. }
  661. else
  662. luaL_addchar(b, *s);
  663. s++;
  664. }
  665. luaL_addchar(b, '"');
  666. }
  667. static const char *scanformat (lua_State *L, const char *strfrmt, char *form) {
  668. const char *p = strfrmt;
  669. while (*p != '\0' && strchr(FLAGS, *p) != NULL) p++; /* skip flags */
  670. if ((size_t)(p - strfrmt) >= sizeof(FLAGS))
  671. luaL_error(L, "invalid format (repeated flags)");
  672. if (isdigit(uchar(*p))) p++; /* skip width */
  673. if (isdigit(uchar(*p))) p++; /* (2 digits at most) */
  674. if (*p == '.') {
  675. p++;
  676. if (isdigit(uchar(*p))) p++; /* skip precision */
  677. if (isdigit(uchar(*p))) p++; /* (2 digits at most) */
  678. }
  679. if (isdigit(uchar(*p)))
  680. luaL_error(L, "invalid format (width or precision too long)");
  681. *(form++) = '%';
  682. memcpy(form, strfrmt, p - strfrmt + 1);
  683. form += p - strfrmt + 1;
  684. *form = '\0';
  685. return p;
  686. }
  687. /*
  688. ** add length modifier into integer formats
  689. */
  690. static void addintlen (char *form) {
  691. size_t l = strlen(form);
  692. char spec = form[l - 1];
  693. strcpy(form + l - 1, LUA_INTFRMLEN);
  694. form[l + sizeof(LUA_INTFRMLEN) - 2] = spec;
  695. form[l + sizeof(LUA_INTFRMLEN) - 1] = '\0';
  696. }
  697. static int str_format (lua_State *L) {
  698. int top = lua_gettop(L);
  699. int arg = 1;
  700. size_t sfl;
  701. const char *strfrmt = luaL_checklstring(L, arg, &sfl);
  702. const char *strfrmt_end = strfrmt+sfl;
  703. luaL_Buffer b;
  704. luaL_buffinit(L, &b);
  705. while (strfrmt < strfrmt_end) {
  706. if (*strfrmt != L_ESC)
  707. luaL_addchar(&b, *strfrmt++);
  708. else if (*++strfrmt == L_ESC)
  709. luaL_addchar(&b, *strfrmt++); /* %% */
  710. else { /* format item */
  711. char form[MAX_FORMAT]; /* to store the format (`%...') */
  712. char *buff = luaL_prepbuffsize(&b, MAX_ITEM); /* to put formatted item */
  713. int nb = 0; /* number of bytes in added item */
  714. if (++arg > top)
  715. luaL_argerror(L, arg, "no value");
  716. strfrmt = scanformat(L, strfrmt, form);
  717. switch (*strfrmt++) {
  718. case 'c': {
  719. nb = sprintf(buff, form, luaL_checkint(L, arg));
  720. break;
  721. }
  722. case 'd': case 'i':
  723. case 'o': case 'u': case 'x': case 'X': {
  724. lua_Number n = luaL_checknumber(L, arg);
  725. LUA_INTFRM_T r = (n < 0) ? (LUA_INTFRM_T)n :
  726. (LUA_INTFRM_T)(unsigned LUA_INTFRM_T)n;
  727. addintlen(form);
  728. nb = sprintf(buff, form, r);
  729. break;
  730. }
  731. case 'e': case 'E': case 'f':
  732. case 'g': case 'G': {
  733. nb = sprintf(buff, form, (double)luaL_checknumber(L, arg));
  734. break;
  735. }
  736. case 'q': {
  737. addquoted(L, &b, arg);
  738. break;
  739. }
  740. case 's': {
  741. size_t l;
  742. const char *s = luaL_checklstring(L, arg, &l);
  743. if (!strchr(form, '.') && l >= 100) {
  744. /* no precision and string is too long to be formatted;
  745. keep original string */
  746. lua_pushvalue(L, arg);
  747. luaL_addvalue(&b);
  748. break;
  749. }
  750. else {
  751. nb = sprintf(buff, form, s);
  752. break;
  753. }
  754. }
  755. default: { /* also treat cases `pnLlh' */
  756. return luaL_error(L, "invalid option " LUA_QL("%%%c") " to "
  757. LUA_QL("format"), *(strfrmt - 1));
  758. }
  759. }
  760. luaL_addsize(&b, nb);
  761. }
  762. }
  763. luaL_pushresult(&b);
  764. return 1;
  765. }
  766. /* }====================================================== */
  767. static const luaL_Reg strlib[] = {
  768. {"byte", str_byte},
  769. {"char", str_char},
  770. {"dump", str_dump},
  771. {"find", str_find},
  772. {"format", str_format},
  773. {"gfind", gfind_nodef},
  774. {"gmatch", gmatch},
  775. {"gsub", str_gsub},
  776. {"len", str_len},
  777. {"lower", str_lower},
  778. {"match", str_match},
  779. {"rep", str_rep},
  780. {"reverse", str_reverse},
  781. {"sub", str_sub},
  782. {"upper", str_upper},
  783. {NULL, NULL}
  784. };
  785. static void createmetatable (lua_State *L) {
  786. lua_createtable(L, 0, 1); /* create metatable for strings */
  787. lua_pushliteral(L, ""); /* dummy string */
  788. lua_pushvalue(L, -2);
  789. lua_setmetatable(L, -2); /* set string metatable */
  790. lua_pop(L, 1); /* pop dummy string */
  791. lua_pushvalue(L, -2); /* string library... */
  792. lua_setfield(L, -2, "__index"); /* ...is the __index metamethod */
  793. lua_pop(L, 1); /* pop metatable */
  794. }
  795. /*
  796. ** Open string library
  797. */
  798. LUAMOD_API int luaopen_string (lua_State *L) {
  799. luaL_newlib(L, strlib);
  800. createmetatable(L);
  801. return 1;
  802. }