lstrlib.c 25 KB

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