lstrlib.c 24 KB

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