lstrlib.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865
  1. /*
  2. ** $Id: lstrlib.c,v 1.136 2007/02/07 17:53:08 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 ((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) init = l1 + 1;
  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 - 1, l1 - init + 1, 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 - 1;
  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. static int gfind_nodef (lua_State *L) {
  502. return luaL_error(L, LUA_QL("string.gfind") " was renamed to "
  503. LUA_QL("string.gmatch"));
  504. }
  505. static void add_s (MatchState *ms, luaL_Buffer *b, const char *s,
  506. const char *e) {
  507. size_t l, i;
  508. const char *news = lua_tolstring(ms->L, 3, &l);
  509. for (i = 0; i < l; i++) {
  510. if (news[i] != L_ESC)
  511. luaL_addchar(b, news[i]);
  512. else {
  513. i++; /* skip ESC */
  514. if (!isdigit(uchar(news[i])))
  515. luaL_addchar(b, news[i]);
  516. else if (news[i] == '0')
  517. luaL_addlstring(b, s, e - s);
  518. else {
  519. push_onecapture(ms, news[i] - '1', s, e);
  520. luaL_addvalue(b); /* add capture to accumulated result */
  521. }
  522. }
  523. }
  524. }
  525. static void add_value (MatchState *ms, luaL_Buffer *b, const char *s,
  526. const char *e) {
  527. lua_State *L = ms->L;
  528. switch (lua_type(L, 3)) {
  529. case LUA_TNUMBER:
  530. case LUA_TSTRING: {
  531. add_s(ms, b, s, e);
  532. return;
  533. }
  534. case LUA_TFUNCTION: {
  535. int n;
  536. lua_pushvalue(L, 3);
  537. n = push_captures(ms, s, e);
  538. lua_call(L, n, 1);
  539. break;
  540. }
  541. case LUA_TTABLE: {
  542. push_onecapture(ms, 0, s, e);
  543. lua_gettable(L, 3);
  544. break;
  545. }
  546. default: {
  547. luaL_argerror(L, 3, "string/function/table expected");
  548. return;
  549. }
  550. }
  551. if (!lua_toboolean(L, -1)) { /* nil or false? */
  552. lua_pop(L, 1);
  553. lua_pushlstring(L, s, e - s); /* keep original text */
  554. }
  555. else if (!lua_isstring(L, -1))
  556. luaL_error(L, "invalid replacement value (a %s)", luaL_typename(L, -1));
  557. luaL_addvalue(b); /* add result to accumulator */
  558. }
  559. static int str_gsub (lua_State *L) {
  560. size_t srcl;
  561. const char *src = luaL_checklstring(L, 1, &srcl);
  562. const char *p = luaL_checkstring(L, 2);
  563. size_t max_s = luaL_optinteger(L, 4, srcl+1);
  564. int anchor = (*p == '^') ? (p++, 1) : 0;
  565. size_t n = 0;
  566. MatchState ms;
  567. luaL_Buffer b;
  568. luaL_buffinit(L, &b);
  569. ms.L = L;
  570. ms.src_init = src;
  571. ms.src_end = src+srcl;
  572. while (n < max_s) {
  573. const char *e;
  574. ms.level = 0;
  575. e = match(&ms, src, p);
  576. if (e) {
  577. n++;
  578. add_value(&ms, &b, src, e);
  579. }
  580. if (e && e>src) /* non empty match? */
  581. src = e; /* skip it */
  582. else if (src < ms.src_end)
  583. luaL_addchar(&b, *src++);
  584. else break;
  585. if (anchor) break;
  586. }
  587. luaL_addlstring(&b, src, ms.src_end-src);
  588. luaL_pushresult(&b);
  589. lua_pushinteger(L, n); /* number of substitutions */
  590. return 2;
  591. }
  592. /* }====================================================== */
  593. /* maximum size of each formatted item (> len(format('%99.99f', -1e308))) */
  594. #define MAX_ITEM 512
  595. /* valid flags in a format specification */
  596. #define FLAGS "-+ #0"
  597. /*
  598. ** maximum size of each format specification (such as '%-099.99d')
  599. ** (+10 accounts for %99.99x plus margin of error)
  600. */
  601. #define MAX_FORMAT (sizeof(FLAGS) + sizeof(LUA_INTFRMLEN) + 10)
  602. static void addquoted (lua_State *L, luaL_Buffer *b, int arg) {
  603. size_t l;
  604. const char *s = luaL_checklstring(L, arg, &l);
  605. luaL_addchar(b, '"');
  606. while (l--) {
  607. if (*s == '"' || *s == '\\' || *s == '\n') {
  608. luaL_addchar(b, '\\');
  609. luaL_addchar(b, *s);
  610. }
  611. else if (*s == '\0' || iscntrl(uchar(*s))) {
  612. char buff[10];
  613. if (*s != '\0' && !isdigit(uchar(*(s+1))))
  614. sprintf(buff, "\\%d", uchar(*s));
  615. else
  616. sprintf(buff, "\\%03d", uchar(*s));
  617. luaL_addstring(b, buff);
  618. }
  619. else
  620. luaL_addchar(b, *s);
  621. s++;
  622. }
  623. luaL_addchar(b, '"');
  624. }
  625. static const char *scanformat (lua_State *L, const char *strfrmt, char *form) {
  626. const char *p = strfrmt;
  627. while (*p != '\0' && strchr(FLAGS, *p) != NULL) p++; /* skip flags */
  628. if ((size_t)(p - strfrmt) >= sizeof(FLAGS))
  629. luaL_error(L, "invalid format (repeated flags)");
  630. if (isdigit(uchar(*p))) p++; /* skip width */
  631. if (isdigit(uchar(*p))) p++; /* (2 digits at most) */
  632. if (*p == '.') {
  633. p++;
  634. if (isdigit(uchar(*p))) p++; /* skip precision */
  635. if (isdigit(uchar(*p))) p++; /* (2 digits at most) */
  636. }
  637. if (isdigit(uchar(*p)))
  638. luaL_error(L, "invalid format (width or precision too long)");
  639. *(form++) = '%';
  640. strncpy(form, strfrmt, p - strfrmt + 1);
  641. form += p - strfrmt + 1;
  642. *form = '\0';
  643. return p;
  644. }
  645. static void addintlen (char *form) {
  646. size_t l = strlen(form);
  647. char spec = form[l - 1];
  648. strcpy(form + l - 1, LUA_INTFRMLEN);
  649. form[l + sizeof(LUA_INTFRMLEN) - 2] = spec;
  650. form[l + sizeof(LUA_INTFRMLEN) - 1] = '\0';
  651. }
  652. static int str_format (lua_State *L) {
  653. int arg = 1;
  654. size_t sfl;
  655. const char *strfrmt = luaL_checklstring(L, arg, &sfl);
  656. const char *strfrmt_end = strfrmt+sfl;
  657. luaL_Buffer b;
  658. luaL_buffinit(L, &b);
  659. while (strfrmt < strfrmt_end) {
  660. if (*strfrmt != L_ESC)
  661. luaL_addchar(&b, *strfrmt++);
  662. else if (*++strfrmt == L_ESC)
  663. luaL_addchar(&b, *strfrmt++); /* %% */
  664. else { /* format item */
  665. char form[MAX_FORMAT]; /* to store the format (`%...') */
  666. char buff[MAX_ITEM]; /* to store the formatted item */
  667. arg++;
  668. strfrmt = scanformat(L, strfrmt, form);
  669. switch (*strfrmt++) {
  670. case 'c': {
  671. sprintf(buff, form, (int)luaL_checknumber(L, arg));
  672. break;
  673. }
  674. case 'd': case 'i': {
  675. addintlen(form);
  676. sprintf(buff, form, (LUA_INTFRM_T)luaL_checknumber(L, arg));
  677. break;
  678. }
  679. case 'o': case 'u': case 'x': case 'X': {
  680. addintlen(form);
  681. sprintf(buff, form, (unsigned LUA_INTFRM_T)luaL_checknumber(L, arg));
  682. break;
  683. }
  684. case 'e': case 'E': case 'f':
  685. case 'g': case 'G': {
  686. sprintf(buff, form, (double)luaL_checknumber(L, arg));
  687. break;
  688. }
  689. case 'q': {
  690. addquoted(L, &b, arg);
  691. continue; /* skip the 'addsize' at the end */
  692. }
  693. case 's': {
  694. size_t l;
  695. const char *s = luaL_checklstring(L, arg, &l);
  696. if (!strchr(form, '.') && l >= 100) {
  697. /* no precision and string is too long to be formatted;
  698. keep original string */
  699. lua_pushvalue(L, arg);
  700. luaL_addvalue(&b);
  701. continue; /* skip the `addsize' at the end */
  702. }
  703. else {
  704. sprintf(buff, form, s);
  705. break;
  706. }
  707. }
  708. default: { /* also treat cases `pnLlh' */
  709. return luaL_error(L, "invalid option " LUA_QL("%%%c") " to "
  710. LUA_QL("format"), *(strfrmt - 1));
  711. }
  712. }
  713. luaL_addlstring(&b, buff, strlen(buff));
  714. }
  715. }
  716. luaL_pushresult(&b);
  717. return 1;
  718. }
  719. static const luaL_Reg strlib[] = {
  720. {"byte", str_byte},
  721. {"char", str_char},
  722. {"dump", str_dump},
  723. {"find", str_find},
  724. {"format", str_format},
  725. {"gfind", gfind_nodef},
  726. {"gmatch", gmatch},
  727. {"gsub", str_gsub},
  728. {"len", str_len},
  729. {"lower", str_lower},
  730. {"match", str_match},
  731. {"rep", str_rep},
  732. {"reverse", str_reverse},
  733. {"sub", str_sub},
  734. {"upper", str_upper},
  735. {NULL, NULL}
  736. };
  737. static void createmetatable (lua_State *L) {
  738. lua_createtable(L, 0, 1); /* create metatable for strings */
  739. lua_pushliteral(L, ""); /* dummy string */
  740. lua_pushvalue(L, -2);
  741. lua_setmetatable(L, -2); /* set string metatable */
  742. lua_pop(L, 1); /* pop dummy string */
  743. lua_pushvalue(L, -2); /* string library... */
  744. lua_setfield(L, -2, "__index"); /* ...is the __index metamethod */
  745. lua_pop(L, 1); /* pop metatable */
  746. }
  747. /*
  748. ** Open string library
  749. */
  750. LUALIB_API int luaopen_string (lua_State *L) {
  751. luaL_register(L, LUA_STRLIBNAME, strlib);
  752. #if defined(LUA_COMPAT_GFIND)
  753. lua_getfield(L, -1, "gmatch");
  754. lua_setfield(L, -2, "gfind");
  755. #endif
  756. createmetatable(L);
  757. return 1;
  758. }