lstrlib.c 23 KB

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