2
0

lstrlib.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870
  1. /*
  2. ** $Id: lstrlib.c,v 1.142 2009/02/03 19:39:19 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. /* macro to `unsign' a character */
  17. #define uchar(c) ((unsigned char)(c))
  18. static int str_len (lua_State *L) {
  19. size_t l;
  20. luaL_checklstring(L, 1, &l);
  21. lua_pushinteger(L, (lua_Integer)l);
  22. return 1;
  23. }
  24. /* translate a relative string position: negative means back from end */
  25. static size_t posrelat (ptrdiff_t pos, size_t len) {
  26. if (pos >= 0) return (size_t)pos;
  27. else if (pos == -pos || (size_t)-pos > len) return 0;
  28. else return len - ((size_t)-pos) + 1;
  29. }
  30. static int str_sub (lua_State *L) {
  31. size_t l;
  32. const char *s = luaL_checklstring(L, 1, &l);
  33. size_t start = posrelat(luaL_checkinteger(L, 2), l);
  34. size_t end = posrelat(luaL_optinteger(L, 3, -1), l);
  35. if (start < 1) start = 1;
  36. if (end > l) end = 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. size_t posi = posrelat(luaL_optinteger(L, 2, 1), l);
  88. size_t pose = posrelat(luaL_optinteger(L, 3, posi), l);
  89. int n, i;
  90. if (posi < 1) posi = 1;
  91. if (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 %%%d", l + 1);
  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. size_t init = posrelat(luaL_optinteger(L, 3, 1), l1);
  427. if (init < 1) init = 1;
  428. else if (init > l1 + 1) { /* start after string's end? */
  429. lua_pushnil(L); /* cannot find anything */
  430. return 1;
  431. }
  432. if (find && (lua_toboolean(L, 4) || /* explicit request? */
  433. strpbrk(p, SPECIALS) == NULL)) { /* or no special characters? */
  434. /* do a plain search */
  435. const char *s2 = lmemfind(s + init - 1, l1 - init + 1, p, l2);
  436. if (s2) {
  437. lua_pushinteger(L, s2 - s + 1);
  438. lua_pushinteger(L, s2 - s + l2);
  439. return 2;
  440. }
  441. }
  442. else {
  443. MatchState ms;
  444. int anchor = (*p == '^') ? (p++, 1) : 0;
  445. const char *s1 = s + init - 1;
  446. ms.L = L;
  447. ms.src_init = s;
  448. ms.src_end = s + l1;
  449. do {
  450. const char *res;
  451. ms.level = 0;
  452. if ((res=match(&ms, s1, p)) != NULL) {
  453. if (find) {
  454. lua_pushinteger(L, s1 - s + 1); /* start */
  455. lua_pushinteger(L, res - s); /* end */
  456. return push_captures(&ms, NULL, 0) + 2;
  457. }
  458. else
  459. return push_captures(&ms, s1, res);
  460. }
  461. } while (s1++ < ms.src_end && !anchor);
  462. }
  463. lua_pushnil(L); /* not found */
  464. return 1;
  465. }
  466. static int str_find (lua_State *L) {
  467. return str_find_aux(L, 1);
  468. }
  469. static int str_match (lua_State *L) {
  470. return str_find_aux(L, 0);
  471. }
  472. static int gmatch_aux (lua_State *L) {
  473. MatchState ms;
  474. size_t ls;
  475. const char *s = lua_tolstring(L, lua_upvalueindex(1), &ls);
  476. const char *p = lua_tostring(L, lua_upvalueindex(2));
  477. const char *src;
  478. ms.L = L;
  479. ms.src_init = s;
  480. ms.src_end = s+ls;
  481. for (src = s + (size_t)lua_tointeger(L, lua_upvalueindex(3));
  482. src <= ms.src_end;
  483. src++) {
  484. const char *e;
  485. ms.level = 0;
  486. if ((e = match(&ms, src, p)) != NULL) {
  487. lua_Integer newstart = e-s;
  488. if (e == src) newstart++; /* empty match? go at least one position */
  489. lua_pushinteger(L, newstart);
  490. lua_replace(L, lua_upvalueindex(3));
  491. return push_captures(&ms, src, e);
  492. }
  493. }
  494. return 0; /* not found */
  495. }
  496. static int gmatch (lua_State *L) {
  497. luaL_checkstring(L, 1);
  498. luaL_checkstring(L, 2);
  499. lua_settop(L, 2);
  500. lua_pushinteger(L, 0);
  501. lua_pushcclosure(L, gmatch_aux, 3);
  502. return 1;
  503. }
  504. static int gfind_nodef (lua_State *L) {
  505. return luaL_error(L, LUA_QL("string.gfind") " was renamed to "
  506. LUA_QL("string.gmatch"));
  507. }
  508. static void add_s (MatchState *ms, luaL_Buffer *b, const char *s,
  509. const char *e) {
  510. size_t l, i;
  511. const char *news = lua_tolstring(ms->L, 3, &l);
  512. for (i = 0; i < l; i++) {
  513. if (news[i] != L_ESC)
  514. luaL_addchar(b, news[i]);
  515. else {
  516. i++; /* skip ESC */
  517. if (!isdigit(uchar(news[i]))) {
  518. if (news[i] != L_ESC)
  519. luaL_error(ms->L, "invalid use of " LUA_QL("%c")
  520. " in replacement string", L_ESC);
  521. luaL_addchar(b, news[i]);
  522. }
  523. else if (news[i] == '0')
  524. luaL_addlstring(b, s, e - s);
  525. else {
  526. push_onecapture(ms, news[i] - '1', s, e);
  527. luaL_addvalue(b); /* add capture to accumulated result */
  528. }
  529. }
  530. }
  531. }
  532. static void add_value (MatchState *ms, luaL_Buffer *b, const char *s,
  533. const char *e, int tr) {
  534. lua_State *L = ms->L;
  535. switch (tr) {
  536. case LUA_TFUNCTION: {
  537. int n;
  538. lua_pushvalue(L, 3);
  539. n = push_captures(ms, s, e);
  540. lua_call(L, n, 1);
  541. break;
  542. }
  543. case LUA_TTABLE: {
  544. push_onecapture(ms, 0, s, e);
  545. lua_gettable(L, 3);
  546. break;
  547. }
  548. default: { /* LUA_TNUMBER or LUA_TSTRING */
  549. add_s(ms, b, s, e);
  550. return;
  551. }
  552. }
  553. if (!lua_toboolean(L, -1)) { /* nil or false? */
  554. lua_pop(L, 1);
  555. lua_pushlstring(L, s, e - s); /* keep original text */
  556. }
  557. else if (!lua_isstring(L, -1))
  558. luaL_error(L, "invalid replacement value (a %s)", luaL_typename(L, -1));
  559. luaL_addvalue(b); /* add result to accumulator */
  560. }
  561. static int str_gsub (lua_State *L) {
  562. size_t srcl;
  563. const char *src = luaL_checklstring(L, 1, &srcl);
  564. const char *p = luaL_checkstring(L, 2);
  565. int tr = lua_type(L, 3);
  566. size_t max_s = luaL_optinteger(L, 4, srcl+1);
  567. int anchor = (*p == '^') ? (p++, 1) : 0;
  568. size_t n = 0;
  569. MatchState ms;
  570. luaL_Buffer b;
  571. luaL_argcheck(L, tr == LUA_TNUMBER || tr == LUA_TSTRING ||
  572. tr == LUA_TFUNCTION || tr == LUA_TTABLE, 3,
  573. "string/function/table expected");
  574. luaL_buffinit(L, &b);
  575. ms.L = L;
  576. ms.src_init = src;
  577. ms.src_end = src+srcl;
  578. while (n < max_s) {
  579. const char *e;
  580. ms.level = 0;
  581. e = match(&ms, src, p);
  582. if (e) {
  583. n++;
  584. add_value(&ms, &b, src, e, tr);
  585. }
  586. if (e && e>src) /* non empty match? */
  587. src = e; /* skip it */
  588. else if (src < ms.src_end)
  589. luaL_addchar(&b, *src++);
  590. else break;
  591. if (anchor) break;
  592. }
  593. luaL_addlstring(&b, src, ms.src_end-src);
  594. luaL_pushresult(&b);
  595. lua_pushinteger(L, n); /* number of substitutions */
  596. return 2;
  597. }
  598. /* }====================================================== */
  599. /* maximum size of each formatted item (> len(format('%99.99f', -1e308))) */
  600. #define MAX_ITEM 512
  601. /* valid flags in a format specification */
  602. #define FLAGS "-+ #0"
  603. /*
  604. ** maximum size of each format specification (such as '%-099.99d')
  605. ** (+10 accounts for %99.99x plus margin of error)
  606. */
  607. #define MAX_FORMAT (sizeof(FLAGS) + sizeof(LUA_INTFRMLEN) + 10)
  608. static void addquoted (lua_State *L, luaL_Buffer *b, int arg) {
  609. size_t l;
  610. const char *s = luaL_checklstring(L, arg, &l);
  611. luaL_addchar(b, '"');
  612. while (l--) {
  613. if (*s == '"' || *s == '\\' || *s == '\n') {
  614. luaL_addchar(b, '\\');
  615. luaL_addchar(b, *s);
  616. }
  617. else if (*s == '\0' || iscntrl(uchar(*s))) {
  618. char buff[10];
  619. if (*s != '\0' && !isdigit(uchar(*(s+1))))
  620. sprintf(buff, "\\%d", uchar(*s));
  621. else
  622. sprintf(buff, "\\%03d", uchar(*s));
  623. luaL_addstring(b, buff);
  624. }
  625. else
  626. luaL_addchar(b, *s);
  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. memcpy(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. sprintf(buff, form, (int)luaL_checknumber(L, arg));
  678. break;
  679. }
  680. case 'd': case 'i':
  681. case 'o': case 'u': case 'x': case 'X': {
  682. lua_Number n = luaL_checknumber(L, arg);
  683. LUA_INTFRM_T r = (n < 0) ? (LUA_INTFRM_T)n :
  684. (LUA_INTFRM_T)(unsigned LUA_INTFRM_T)n;
  685. addintlen(form);
  686. sprintf(buff, form, r);
  687. break;
  688. }
  689. case 'e': case 'E': case 'f':
  690. case 'g': case 'G': {
  691. sprintf(buff, form, (double)luaL_checknumber(L, arg));
  692. break;
  693. }
  694. case 'q': {
  695. addquoted(L, &b, arg);
  696. continue; /* skip the 'addsize' at the end */
  697. }
  698. case 's': {
  699. size_t l;
  700. const char *s = luaL_checklstring(L, arg, &l);
  701. if (!strchr(form, '.') && l >= 100) {
  702. /* no precision and string is too long to be formatted;
  703. keep original string */
  704. lua_pushvalue(L, arg);
  705. luaL_addvalue(&b);
  706. continue; /* skip the `addsize' at the end */
  707. }
  708. else {
  709. sprintf(buff, form, s);
  710. break;
  711. }
  712. }
  713. default: { /* also treat cases `pnLlh' */
  714. return luaL_error(L, "invalid option " LUA_QL("%%%c") " to "
  715. LUA_QL("format"), *(strfrmt - 1));
  716. }
  717. }
  718. luaL_addlstring(&b, buff, strlen(buff));
  719. }
  720. }
  721. luaL_pushresult(&b);
  722. return 1;
  723. }
  724. static const luaL_Reg strlib[] = {
  725. {"byte", str_byte},
  726. {"char", str_char},
  727. {"dump", str_dump},
  728. {"find", str_find},
  729. {"format", str_format},
  730. {"gfind", gfind_nodef},
  731. {"gmatch", gmatch},
  732. {"gsub", str_gsub},
  733. {"len", str_len},
  734. {"lower", str_lower},
  735. {"match", str_match},
  736. {"rep", str_rep},
  737. {"reverse", str_reverse},
  738. {"sub", str_sub},
  739. {"upper", str_upper},
  740. {NULL, NULL}
  741. };
  742. static void createmetatable (lua_State *L) {
  743. lua_createtable(L, 0, 1); /* create metatable for strings */
  744. lua_pushliteral(L, ""); /* dummy string */
  745. lua_pushvalue(L, -2);
  746. lua_setmetatable(L, -2); /* set string metatable */
  747. lua_pop(L, 1); /* pop dummy string */
  748. lua_pushvalue(L, -2); /* string library... */
  749. lua_setfield(L, -2, "__index"); /* ...is the __index metamethod */
  750. lua_pop(L, 1); /* pop metatable */
  751. }
  752. /*
  753. ** Open string library
  754. */
  755. LUALIB_API int luaopen_string (lua_State *L) {
  756. luaL_register(L, LUA_STRLIBNAME, strlib);
  757. #if defined(LUA_COMPAT_GFIND)
  758. lua_getfield(L, -1, "gmatch");
  759. lua_setfield(L, -2, "gfind");
  760. #endif
  761. createmetatable(L);
  762. return 1;
  763. }