lstrlib.c 23 KB

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