lstrlib.c 24 KB

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