lstrlib.c 23 KB

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