lstrlib.c 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019
  1. /*
  2. ** $Id: lstrlib.c,v 1.178.1.1 2013/04/12 18:48:47 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. /*
  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 (0u - (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, i;
  51. luaL_Buffer b;
  52. const char *s = luaL_checklstring(L, 1, &l);
  53. char *p = luaL_buffinitsize(L, &b, l);
  54. for (i = 0; i < l; i++)
  55. p[i] = s[l - i - 1];
  56. luaL_pushresultsize(&b, l);
  57. return 1;
  58. }
  59. static int str_lower (lua_State *L) {
  60. size_t l;
  61. size_t i;
  62. luaL_Buffer b;
  63. const char *s = luaL_checklstring(L, 1, &l);
  64. char *p = luaL_buffinitsize(L, &b, l);
  65. for (i=0; i<l; i++)
  66. p[i] = tolower(uchar(s[i]));
  67. luaL_pushresultsize(&b, l);
  68. return 1;
  69. }
  70. static int str_upper (lua_State *L) {
  71. size_t l;
  72. size_t i;
  73. luaL_Buffer b;
  74. const char *s = luaL_checklstring(L, 1, &l);
  75. char *p = luaL_buffinitsize(L, &b, l);
  76. for (i=0; i<l; i++)
  77. p[i] = toupper(uchar(s[i]));
  78. luaL_pushresultsize(&b, l);
  79. return 1;
  80. }
  81. /* reasonable limit to avoid arithmetic overflow */
  82. #define MAXSIZE ((~(size_t)0) >> 1)
  83. static int str_rep (lua_State *L) {
  84. size_t l, lsep;
  85. const char *s = luaL_checklstring(L, 1, &l);
  86. int n = luaL_checkint(L, 2);
  87. const char *sep = luaL_optlstring(L, 3, "", &lsep);
  88. if (n <= 0) lua_pushliteral(L, "");
  89. else if (l + lsep < l || l + lsep >= MAXSIZE / n) /* may overflow? */
  90. return luaL_error(L, "resulting string too large");
  91. else {
  92. size_t totallen = n * l + (n - 1) * lsep;
  93. luaL_Buffer b;
  94. char *p = luaL_buffinitsize(L, &b, totallen);
  95. while (n-- > 1) { /* first n-1 copies (followed by separator) */
  96. memcpy(p, s, l * sizeof(char)); p += l;
  97. if (lsep > 0) { /* avoid empty 'memcpy' (may be expensive) */
  98. memcpy(p, sep, lsep * sizeof(char)); p += lsep;
  99. }
  100. }
  101. memcpy(p, s, l * sizeof(char)); /* last copy (not followed by separator) */
  102. luaL_pushresultsize(&b, totallen);
  103. }
  104. return 1;
  105. }
  106. static int str_byte (lua_State *L) {
  107. size_t l;
  108. const char *s = luaL_checklstring(L, 1, &l);
  109. size_t posi = posrelat(luaL_optinteger(L, 2, 1), l);
  110. size_t pose = posrelat(luaL_optinteger(L, 3, posi), l);
  111. int n, i;
  112. if (posi < 1) posi = 1;
  113. if (pose > l) pose = l;
  114. if (posi > pose) return 0; /* empty interval; return no values */
  115. n = (int)(pose - posi + 1);
  116. if (posi + n <= pose) /* (size_t -> int) overflow? */
  117. return luaL_error(L, "string slice too long");
  118. luaL_checkstack(L, n, "string slice too long");
  119. for (i=0; i<n; i++)
  120. lua_pushinteger(L, uchar(s[posi+i-1]));
  121. return n;
  122. }
  123. static int str_char (lua_State *L) {
  124. int n = lua_gettop(L); /* number of arguments */
  125. int i;
  126. luaL_Buffer b;
  127. char *p = luaL_buffinitsize(L, &b, n);
  128. for (i=1; i<=n; i++) {
  129. int c = luaL_checkint(L, i);
  130. luaL_argcheck(L, uchar(c) == c, i, "value out of range");
  131. p[i - 1] = uchar(c);
  132. }
  133. luaL_pushresultsize(&b, n);
  134. return 1;
  135. }
  136. static int writer (lua_State *L, const void* b, size_t size, void* B) {
  137. (void)L;
  138. luaL_addlstring((luaL_Buffer*) B, (const char *)b, size);
  139. return 0;
  140. }
  141. static int str_dump (lua_State *L) {
  142. luaL_Buffer b;
  143. luaL_checktype(L, 1, LUA_TFUNCTION);
  144. lua_settop(L, 1);
  145. luaL_buffinit(L,&b);
  146. if (lua_dump(L, writer, &b) != 0)
  147. return luaL_error(L, "unable to dump given function");
  148. luaL_pushresult(&b);
  149. return 1;
  150. }
  151. /*
  152. ** {======================================================
  153. ** PATTERN MATCHING
  154. ** =======================================================
  155. */
  156. #define CAP_UNFINISHED (-1)
  157. #define CAP_POSITION (-2)
  158. typedef struct MatchState {
  159. int matchdepth; /* control for recursive depth (to avoid C stack overflow) */
  160. const char *src_init; /* init of source string */
  161. const char *src_end; /* end ('\0') of source string */
  162. const char *p_end; /* end ('\0') of pattern */
  163. lua_State *L;
  164. int level; /* total number of captures (finished or unfinished) */
  165. struct {
  166. const char *init;
  167. ptrdiff_t len;
  168. } capture[LUA_MAXCAPTURES];
  169. } MatchState;
  170. /* recursive function */
  171. static const char *match (MatchState *ms, const char *s, const char *p);
  172. /* maximum recursion depth for 'match' */
  173. #if !defined(MAXCCALLS)
  174. #define MAXCCALLS 200
  175. #endif
  176. #define L_ESC '%'
  177. #define SPECIALS "^$*+?.([%-"
  178. static int check_capture (MatchState *ms, int l) {
  179. l -= '1';
  180. if (l < 0 || l >= ms->level || ms->capture[l].len == CAP_UNFINISHED)
  181. return luaL_error(ms->L, "invalid capture index %%%d", l + 1);
  182. return l;
  183. }
  184. static int capture_to_close (MatchState *ms) {
  185. int level = ms->level;
  186. for (level--; level>=0; level--)
  187. if (ms->capture[level].len == CAP_UNFINISHED) return level;
  188. return luaL_error(ms->L, "invalid pattern capture");
  189. }
  190. static const char *classend (MatchState *ms, const char *p) {
  191. switch (*p++) {
  192. case L_ESC: {
  193. if (p == ms->p_end)
  194. luaL_error(ms->L, "malformed pattern (ends with " LUA_QL("%%") ")");
  195. return p+1;
  196. }
  197. case '[': {
  198. if (*p == '^') p++;
  199. do { /* look for a `]' */
  200. if (p == ms->p_end)
  201. luaL_error(ms->L, "malformed pattern (missing " LUA_QL("]") ")");
  202. if (*(p++) == L_ESC && p < ms->p_end)
  203. p++; /* skip escapes (e.g. `%]') */
  204. } while (*p != ']');
  205. return p+1;
  206. }
  207. default: {
  208. return p;
  209. }
  210. }
  211. }
  212. static int match_class (int c, int cl) {
  213. int res;
  214. switch (tolower(cl)) {
  215. case 'a' : res = isalpha(c); break;
  216. case 'c' : res = iscntrl(c); break;
  217. case 'd' : res = isdigit(c); break;
  218. case 'g' : res = isgraph(c); break;
  219. case 'l' : res = islower(c); break;
  220. case 'p' : res = ispunct(c); break;
  221. case 's' : res = isspace(c); break;
  222. case 'u' : res = isupper(c); break;
  223. case 'w' : res = isalnum(c); break;
  224. case 'x' : res = isxdigit(c); break;
  225. case 'z' : res = (c == 0); break; /* deprecated option */
  226. default: return (cl == c);
  227. }
  228. return (islower(cl) ? res : !res);
  229. }
  230. static int matchbracketclass (int c, const char *p, const char *ec) {
  231. int sig = 1;
  232. if (*(p+1) == '^') {
  233. sig = 0;
  234. p++; /* skip the `^' */
  235. }
  236. while (++p < ec) {
  237. if (*p == L_ESC) {
  238. p++;
  239. if (match_class(c, uchar(*p)))
  240. return sig;
  241. }
  242. else if ((*(p+1) == '-') && (p+2 < ec)) {
  243. p+=2;
  244. if (uchar(*(p-2)) <= c && c <= uchar(*p))
  245. return sig;
  246. }
  247. else if (uchar(*p) == c) return sig;
  248. }
  249. return !sig;
  250. }
  251. static int singlematch (MatchState *ms, const char *s, const char *p,
  252. const char *ep) {
  253. if (s >= ms->src_end)
  254. return 0;
  255. else {
  256. int c = uchar(*s);
  257. switch (*p) {
  258. case '.': return 1; /* matches any char */
  259. case L_ESC: return match_class(c, uchar(*(p+1)));
  260. case '[': return matchbracketclass(c, p, ep-1);
  261. default: return (uchar(*p) == c);
  262. }
  263. }
  264. }
  265. static const char *matchbalance (MatchState *ms, const char *s,
  266. const char *p) {
  267. if (p >= ms->p_end - 1)
  268. luaL_error(ms->L, "malformed pattern "
  269. "(missing arguments to " LUA_QL("%%b") ")");
  270. if (*s != *p) return NULL;
  271. else {
  272. int b = *p;
  273. int e = *(p+1);
  274. int cont = 1;
  275. while (++s < ms->src_end) {
  276. if (*s == e) {
  277. if (--cont == 0) return s+1;
  278. }
  279. else if (*s == b) cont++;
  280. }
  281. }
  282. return NULL; /* string ends out of balance */
  283. }
  284. static const char *max_expand (MatchState *ms, const char *s,
  285. const char *p, const char *ep) {
  286. ptrdiff_t i = 0; /* counts maximum expand for item */
  287. while (singlematch(ms, s + i, p, ep))
  288. i++;
  289. /* keeps trying to match with the maximum repetitions */
  290. while (i>=0) {
  291. const char *res = match(ms, (s+i), ep+1);
  292. if (res) return res;
  293. i--; /* else didn't match; reduce 1 repetition to try again */
  294. }
  295. return NULL;
  296. }
  297. static const char *min_expand (MatchState *ms, const char *s,
  298. const char *p, const char *ep) {
  299. for (;;) {
  300. const char *res = match(ms, s, ep+1);
  301. if (res != NULL)
  302. return res;
  303. else if (singlematch(ms, s, p, ep))
  304. s++; /* try with one more repetition */
  305. else return NULL;
  306. }
  307. }
  308. static const char *start_capture (MatchState *ms, const char *s,
  309. const char *p, int what) {
  310. const char *res;
  311. int level = ms->level;
  312. if (level >= LUA_MAXCAPTURES) luaL_error(ms->L, "too many captures");
  313. ms->capture[level].init = s;
  314. ms->capture[level].len = what;
  315. ms->level = level+1;
  316. if ((res=match(ms, s, p)) == NULL) /* match failed? */
  317. ms->level--; /* undo capture */
  318. return res;
  319. }
  320. static const char *end_capture (MatchState *ms, const char *s,
  321. const char *p) {
  322. int l = capture_to_close(ms);
  323. const char *res;
  324. ms->capture[l].len = s - ms->capture[l].init; /* close capture */
  325. if ((res = match(ms, s, p)) == NULL) /* match failed? */
  326. ms->capture[l].len = CAP_UNFINISHED; /* undo capture */
  327. return res;
  328. }
  329. static const char *match_capture (MatchState *ms, const char *s, int l) {
  330. size_t len;
  331. l = check_capture(ms, l);
  332. len = ms->capture[l].len;
  333. if ((size_t)(ms->src_end-s) >= len &&
  334. memcmp(ms->capture[l].init, s, len) == 0)
  335. return s+len;
  336. else return NULL;
  337. }
  338. static const char *match (MatchState *ms, const char *s, const char *p) {
  339. if (ms->matchdepth-- == 0)
  340. luaL_error(ms->L, "pattern too complex");
  341. init: /* using goto's to optimize tail recursion */
  342. if (p != ms->p_end) { /* end of pattern? */
  343. switch (*p) {
  344. case '(': { /* start capture */
  345. if (*(p + 1) == ')') /* position capture? */
  346. s = start_capture(ms, s, p + 2, CAP_POSITION);
  347. else
  348. s = start_capture(ms, s, p + 1, CAP_UNFINISHED);
  349. break;
  350. }
  351. case ')': { /* end capture */
  352. s = end_capture(ms, s, p + 1);
  353. break;
  354. }
  355. case '$': {
  356. if ((p + 1) != ms->p_end) /* is the `$' the last char in pattern? */
  357. goto dflt; /* no; go to default */
  358. s = (s == ms->src_end) ? s : NULL; /* check end of string */
  359. break;
  360. }
  361. case L_ESC: { /* escaped sequences not in the format class[*+?-]? */
  362. switch (*(p + 1)) {
  363. case 'b': { /* balanced string? */
  364. s = matchbalance(ms, s, p + 2);
  365. if (s != NULL) {
  366. p += 4; goto init; /* return match(ms, s, p + 4); */
  367. } /* else fail (s == NULL) */
  368. break;
  369. }
  370. case 'f': { /* frontier? */
  371. const char *ep; char previous;
  372. p += 2;
  373. if (*p != '[')
  374. luaL_error(ms->L, "missing " LUA_QL("[") " after "
  375. LUA_QL("%%f") " in pattern");
  376. ep = classend(ms, p); /* points to what is next */
  377. previous = (s == ms->src_init) ? '\0' : *(s - 1);
  378. if (!matchbracketclass(uchar(previous), p, ep - 1) &&
  379. matchbracketclass(uchar(*s), p, ep - 1)) {
  380. p = ep; goto init; /* return match(ms, s, ep); */
  381. }
  382. s = NULL; /* match failed */
  383. break;
  384. }
  385. case '0': case '1': case '2': case '3':
  386. case '4': case '5': case '6': case '7':
  387. case '8': case '9': { /* capture results (%0-%9)? */
  388. s = match_capture(ms, s, uchar(*(p + 1)));
  389. if (s != NULL) {
  390. p += 2; goto init; /* return match(ms, s, p + 2) */
  391. }
  392. break;
  393. }
  394. default: goto dflt;
  395. }
  396. break;
  397. }
  398. default: dflt: { /* pattern class plus optional suffix */
  399. const char *ep = classend(ms, p); /* points to optional suffix */
  400. /* does not match at least once? */
  401. if (!singlematch(ms, s, p, ep)) {
  402. if (*ep == '*' || *ep == '?' || *ep == '-') { /* accept empty? */
  403. p = ep + 1; goto init; /* return match(ms, s, ep + 1); */
  404. }
  405. else /* '+' or no suffix */
  406. s = NULL; /* fail */
  407. }
  408. else { /* matched once */
  409. switch (*ep) { /* handle optional suffix */
  410. case '?': { /* optional */
  411. const char *res;
  412. if ((res = match(ms, s + 1, ep + 1)) != NULL)
  413. s = res;
  414. else {
  415. p = ep + 1; goto init; /* else return match(ms, s, ep + 1); */
  416. }
  417. break;
  418. }
  419. case '+': /* 1 or more repetitions */
  420. s++; /* 1 match already done */
  421. /* go through */
  422. case '*': /* 0 or more repetitions */
  423. s = max_expand(ms, s, p, ep);
  424. break;
  425. case '-': /* 0 or more repetitions (minimum) */
  426. s = min_expand(ms, s, p, ep);
  427. break;
  428. default: /* no suffix */
  429. s++; p = ep; goto init; /* return match(ms, s + 1, ep); */
  430. }
  431. }
  432. break;
  433. }
  434. }
  435. }
  436. ms->matchdepth++;
  437. return s;
  438. }
  439. static const char *lmemfind (const char *s1, size_t l1,
  440. const char *s2, size_t l2) {
  441. if (l2 == 0) return s1; /* empty strings are everywhere */
  442. else if (l2 > l1) return NULL; /* avoids a negative `l1' */
  443. else {
  444. const char *init; /* to search for a `*s2' inside `s1' */
  445. l2--; /* 1st char will be checked by `memchr' */
  446. l1 = l1-l2; /* `s2' cannot be found after that */
  447. while (l1 > 0 && (init = (const char *)memchr(s1, *s2, l1)) != NULL) {
  448. init++; /* 1st char is already checked */
  449. if (memcmp(init, s2+1, l2) == 0)
  450. return init-1;
  451. else { /* correct `l1' and `s1' to try again */
  452. l1 -= init-s1;
  453. s1 = init;
  454. }
  455. }
  456. return NULL; /* not found */
  457. }
  458. }
  459. static void push_onecapture (MatchState *ms, int i, const char *s,
  460. const char *e) {
  461. if (i >= ms->level) {
  462. if (i == 0) /* ms->level == 0, too */
  463. lua_pushlstring(ms->L, s, e - s); /* add whole match */
  464. else
  465. luaL_error(ms->L, "invalid capture index");
  466. }
  467. else {
  468. ptrdiff_t l = ms->capture[i].len;
  469. if (l == CAP_UNFINISHED) luaL_error(ms->L, "unfinished capture");
  470. if (l == CAP_POSITION)
  471. lua_pushinteger(ms->L, ms->capture[i].init - ms->src_init + 1);
  472. else
  473. lua_pushlstring(ms->L, ms->capture[i].init, l);
  474. }
  475. }
  476. static int push_captures (MatchState *ms, const char *s, const char *e) {
  477. int i;
  478. int nlevels = (ms->level == 0 && s) ? 1 : ms->level;
  479. luaL_checkstack(ms->L, nlevels, "too many captures");
  480. for (i = 0; i < nlevels; i++)
  481. push_onecapture(ms, i, s, e);
  482. return nlevels; /* number of strings pushed */
  483. }
  484. /* check whether pattern has no special characters */
  485. static int nospecials (const char *p, size_t l) {
  486. size_t upto = 0;
  487. do {
  488. if (strpbrk(p + upto, SPECIALS))
  489. return 0; /* pattern has a special character */
  490. upto += strlen(p + upto) + 1; /* may have more after \0 */
  491. } while (upto <= l);
  492. return 1; /* no special chars found */
  493. }
  494. static int str_find_aux (lua_State *L, int find) {
  495. size_t ls, lp;
  496. const char *s = luaL_checklstring(L, 1, &ls);
  497. const char *p = luaL_checklstring(L, 2, &lp);
  498. size_t init = posrelat(luaL_optinteger(L, 3, 1), ls);
  499. if (init < 1) init = 1;
  500. else if (init > ls + 1) { /* start after string's end? */
  501. lua_pushnil(L); /* cannot find anything */
  502. return 1;
  503. }
  504. /* explicit request or no special characters? */
  505. if (find && (lua_toboolean(L, 4) || nospecials(p, lp))) {
  506. /* do a plain search */
  507. const char *s2 = lmemfind(s + init - 1, ls - init + 1, p, lp);
  508. if (s2) {
  509. lua_pushinteger(L, s2 - s + 1);
  510. lua_pushinteger(L, s2 - s + lp);
  511. return 2;
  512. }
  513. }
  514. else {
  515. MatchState ms;
  516. const char *s1 = s + init - 1;
  517. int anchor = (*p == '^');
  518. if (anchor) {
  519. p++; lp--; /* skip anchor character */
  520. }
  521. ms.L = L;
  522. ms.matchdepth = MAXCCALLS;
  523. ms.src_init = s;
  524. ms.src_end = s + ls;
  525. ms.p_end = p + lp;
  526. do {
  527. const char *res;
  528. ms.level = 0;
  529. lua_assert(ms.matchdepth == MAXCCALLS);
  530. if ((res=match(&ms, s1, p)) != NULL) {
  531. if (find) {
  532. lua_pushinteger(L, s1 - s + 1); /* start */
  533. lua_pushinteger(L, res - s); /* end */
  534. return push_captures(&ms, NULL, 0) + 2;
  535. }
  536. else
  537. return push_captures(&ms, s1, res);
  538. }
  539. } while (s1++ < ms.src_end && !anchor);
  540. }
  541. lua_pushnil(L); /* not found */
  542. return 1;
  543. }
  544. static int str_find (lua_State *L) {
  545. return str_find_aux(L, 1);
  546. }
  547. static int str_match (lua_State *L) {
  548. return str_find_aux(L, 0);
  549. }
  550. static int gmatch_aux (lua_State *L) {
  551. MatchState ms;
  552. size_t ls, lp;
  553. const char *s = lua_tolstring(L, lua_upvalueindex(1), &ls);
  554. const char *p = lua_tolstring(L, lua_upvalueindex(2), &lp);
  555. const char *src;
  556. ms.L = L;
  557. ms.matchdepth = MAXCCALLS;
  558. ms.src_init = s;
  559. ms.src_end = s+ls;
  560. ms.p_end = p + lp;
  561. for (src = s + (size_t)lua_tointeger(L, lua_upvalueindex(3));
  562. src <= ms.src_end;
  563. src++) {
  564. const char *e;
  565. ms.level = 0;
  566. lua_assert(ms.matchdepth == MAXCCALLS);
  567. if ((e = match(&ms, src, p)) != NULL) {
  568. lua_Integer newstart = e-s;
  569. if (e == src) newstart++; /* empty match? go at least one position */
  570. lua_pushinteger(L, newstart);
  571. lua_replace(L, lua_upvalueindex(3));
  572. return push_captures(&ms, src, e);
  573. }
  574. }
  575. return 0; /* not found */
  576. }
  577. static int gmatch (lua_State *L) {
  578. luaL_checkstring(L, 1);
  579. luaL_checkstring(L, 2);
  580. lua_settop(L, 2);
  581. lua_pushinteger(L, 0);
  582. lua_pushcclosure(L, gmatch_aux, 3);
  583. return 1;
  584. }
  585. static void add_s (MatchState *ms, luaL_Buffer *b, const char *s,
  586. const char *e) {
  587. size_t l, i;
  588. const char *news = lua_tolstring(ms->L, 3, &l);
  589. for (i = 0; i < l; i++) {
  590. if (news[i] != L_ESC)
  591. luaL_addchar(b, news[i]);
  592. else {
  593. i++; /* skip ESC */
  594. if (!isdigit(uchar(news[i]))) {
  595. if (news[i] != L_ESC)
  596. luaL_error(ms->L, "invalid use of " LUA_QL("%c")
  597. " in replacement string", L_ESC);
  598. luaL_addchar(b, news[i]);
  599. }
  600. else if (news[i] == '0')
  601. luaL_addlstring(b, s, e - s);
  602. else {
  603. push_onecapture(ms, news[i] - '1', s, e);
  604. luaL_addvalue(b); /* add capture to accumulated result */
  605. }
  606. }
  607. }
  608. }
  609. static void add_value (MatchState *ms, luaL_Buffer *b, const char *s,
  610. const char *e, int tr) {
  611. lua_State *L = ms->L;
  612. switch (tr) {
  613. case LUA_TFUNCTION: {
  614. int n;
  615. lua_pushvalue(L, 3);
  616. n = push_captures(ms, s, e);
  617. lua_call(L, n, 1);
  618. break;
  619. }
  620. case LUA_TTABLE: {
  621. push_onecapture(ms, 0, s, e);
  622. lua_gettable(L, 3);
  623. break;
  624. }
  625. default: { /* LUA_TNUMBER or LUA_TSTRING */
  626. add_s(ms, b, s, e);
  627. return;
  628. }
  629. }
  630. if (!lua_toboolean(L, -1)) { /* nil or false? */
  631. lua_pop(L, 1);
  632. lua_pushlstring(L, s, e - s); /* keep original text */
  633. }
  634. else if (!lua_isstring(L, -1))
  635. luaL_error(L, "invalid replacement value (a %s)", luaL_typename(L, -1));
  636. luaL_addvalue(b); /* add result to accumulator */
  637. }
  638. static int str_gsub (lua_State *L) {
  639. size_t srcl, lp;
  640. const char *src = luaL_checklstring(L, 1, &srcl);
  641. const char *p = luaL_checklstring(L, 2, &lp);
  642. int tr = lua_type(L, 3);
  643. size_t max_s = luaL_optinteger(L, 4, srcl+1);
  644. int anchor = (*p == '^');
  645. size_t n = 0;
  646. MatchState ms;
  647. luaL_Buffer b;
  648. luaL_argcheck(L, tr == LUA_TNUMBER || tr == LUA_TSTRING ||
  649. tr == LUA_TFUNCTION || tr == LUA_TTABLE, 3,
  650. "string/function/table expected");
  651. luaL_buffinit(L, &b);
  652. if (anchor) {
  653. p++; lp--; /* skip anchor character */
  654. }
  655. ms.L = L;
  656. ms.matchdepth = MAXCCALLS;
  657. ms.src_init = src;
  658. ms.src_end = src+srcl;
  659. ms.p_end = p + lp;
  660. while (n < max_s) {
  661. const char *e;
  662. ms.level = 0;
  663. lua_assert(ms.matchdepth == MAXCCALLS);
  664. e = match(&ms, src, p);
  665. if (e) {
  666. n++;
  667. add_value(&ms, &b, src, e, tr);
  668. }
  669. if (e && e>src) /* non empty match? */
  670. src = e; /* skip it */
  671. else if (src < ms.src_end)
  672. luaL_addchar(&b, *src++);
  673. else break;
  674. if (anchor) break;
  675. }
  676. luaL_addlstring(&b, src, ms.src_end-src);
  677. luaL_pushresult(&b);
  678. lua_pushinteger(L, n); /* number of substitutions */
  679. return 2;
  680. }
  681. /* }====================================================== */
  682. /*
  683. ** {======================================================
  684. ** STRING FORMAT
  685. ** =======================================================
  686. */
  687. /*
  688. ** LUA_INTFRMLEN is the length modifier for integer conversions in
  689. ** 'string.format'; LUA_INTFRM_T is the integer type corresponding to
  690. ** the previous length
  691. */
  692. #if !defined(LUA_INTFRMLEN) /* { */
  693. #if defined(LUA_USE_LONGLONG)
  694. #define LUA_INTFRMLEN "ll"
  695. #define LUA_INTFRM_T long long
  696. #else
  697. #define LUA_INTFRMLEN "l"
  698. #define LUA_INTFRM_T long
  699. #endif
  700. #endif /* } */
  701. /*
  702. ** LUA_FLTFRMLEN is the length modifier for float conversions in
  703. ** 'string.format'; LUA_FLTFRM_T is the float type corresponding to
  704. ** the previous length
  705. */
  706. #if !defined(LUA_FLTFRMLEN)
  707. #define LUA_FLTFRMLEN ""
  708. #define LUA_FLTFRM_T double
  709. #endif
  710. /* maximum size of each formatted item (> len(format('%99.99f', -1e308))) */
  711. #define MAX_ITEM 512
  712. /* valid flags in a format specification */
  713. #define FLAGS "-+ #0"
  714. /*
  715. ** maximum size of each format specification (such as '%-099.99d')
  716. ** (+10 accounts for %99.99x plus margin of error)
  717. */
  718. #define MAX_FORMAT (sizeof(FLAGS) + sizeof(LUA_INTFRMLEN) + 10)
  719. static void addquoted (lua_State *L, luaL_Buffer *b, int arg) {
  720. size_t l;
  721. const char *s = luaL_checklstring(L, arg, &l);
  722. luaL_addchar(b, '"');
  723. while (l--) {
  724. if (*s == '"' || *s == '\\' || *s == '\n') {
  725. luaL_addchar(b, '\\');
  726. luaL_addchar(b, *s);
  727. }
  728. else if (*s == '\0' || iscntrl(uchar(*s))) {
  729. char buff[10];
  730. if (!isdigit(uchar(*(s+1))))
  731. sprintf(buff, "\\%d", (int)uchar(*s));
  732. else
  733. sprintf(buff, "\\%03d", (int)uchar(*s));
  734. luaL_addstring(b, buff);
  735. }
  736. else
  737. luaL_addchar(b, *s);
  738. s++;
  739. }
  740. luaL_addchar(b, '"');
  741. }
  742. static const char *scanformat (lua_State *L, const char *strfrmt, char *form) {
  743. const char *p = strfrmt;
  744. while (*p != '\0' && strchr(FLAGS, *p) != NULL) p++; /* skip flags */
  745. if ((size_t)(p - strfrmt) >= sizeof(FLAGS)/sizeof(char))
  746. luaL_error(L, "invalid format (repeated flags)");
  747. if (isdigit(uchar(*p))) p++; /* skip width */
  748. if (isdigit(uchar(*p))) p++; /* (2 digits at most) */
  749. if (*p == '.') {
  750. p++;
  751. if (isdigit(uchar(*p))) p++; /* skip precision */
  752. if (isdigit(uchar(*p))) p++; /* (2 digits at most) */
  753. }
  754. if (isdigit(uchar(*p)))
  755. luaL_error(L, "invalid format (width or precision too long)");
  756. *(form++) = '%';
  757. memcpy(form, strfrmt, (p - strfrmt + 1) * sizeof(char));
  758. form += p - strfrmt + 1;
  759. *form = '\0';
  760. return p;
  761. }
  762. /*
  763. ** add length modifier into formats
  764. */
  765. static void addlenmod (char *form, const char *lenmod) {
  766. size_t l = strlen(form);
  767. size_t lm = strlen(lenmod);
  768. char spec = form[l - 1];
  769. strcpy(form + l - 1, lenmod);
  770. form[l + lm - 1] = spec;
  771. form[l + lm] = '\0';
  772. }
  773. static int str_format (lua_State *L) {
  774. int top = lua_gettop(L);
  775. int arg = 1;
  776. size_t sfl;
  777. const char *strfrmt = luaL_checklstring(L, arg, &sfl);
  778. const char *strfrmt_end = strfrmt+sfl;
  779. luaL_Buffer b;
  780. luaL_buffinit(L, &b);
  781. while (strfrmt < strfrmt_end) {
  782. if (*strfrmt != L_ESC)
  783. luaL_addchar(&b, *strfrmt++);
  784. else if (*++strfrmt == L_ESC)
  785. luaL_addchar(&b, *strfrmt++); /* %% */
  786. else { /* format item */
  787. char form[MAX_FORMAT]; /* to store the format (`%...') */
  788. char *buff = luaL_prepbuffsize(&b, MAX_ITEM); /* to put formatted item */
  789. int nb = 0; /* number of bytes in added item */
  790. if (++arg > top)
  791. luaL_argerror(L, arg, "no value");
  792. strfrmt = scanformat(L, strfrmt, form);
  793. switch (*strfrmt++) {
  794. case 'c': {
  795. nb = sprintf(buff, form, luaL_checkint(L, arg));
  796. break;
  797. }
  798. case 'd': case 'i': {
  799. lua_Number n = luaL_checknumber(L, arg);
  800. LUA_INTFRM_T ni = (LUA_INTFRM_T)n;
  801. lua_Number diff = n - (lua_Number)ni;
  802. luaL_argcheck(L, -1 < diff && diff < 1, arg,
  803. "not a number in proper range");
  804. addlenmod(form, LUA_INTFRMLEN);
  805. nb = sprintf(buff, form, ni);
  806. break;
  807. }
  808. case 'o': case 'u': case 'x': case 'X': {
  809. lua_Number n = luaL_checknumber(L, arg);
  810. unsigned LUA_INTFRM_T ni = (unsigned LUA_INTFRM_T)n;
  811. lua_Number diff = n - (lua_Number)ni;
  812. luaL_argcheck(L, -1 < diff && diff < 1, arg,
  813. "not a non-negative number in proper range");
  814. addlenmod(form, LUA_INTFRMLEN);
  815. nb = sprintf(buff, form, ni);
  816. break;
  817. }
  818. case 'e': case 'E': case 'f':
  819. #if defined(LUA_USE_AFORMAT)
  820. case 'a': case 'A':
  821. #endif
  822. case 'g': case 'G': {
  823. addlenmod(form, LUA_FLTFRMLEN);
  824. nb = sprintf(buff, form, (LUA_FLTFRM_T)luaL_checknumber(L, arg));
  825. break;
  826. }
  827. case 'q': {
  828. addquoted(L, &b, arg);
  829. break;
  830. }
  831. case 's': {
  832. size_t l;
  833. const char *s = luaL_tolstring(L, arg, &l);
  834. if (!strchr(form, '.') && l >= 100) {
  835. /* no precision and string is too long to be formatted;
  836. keep original string */
  837. luaL_addvalue(&b);
  838. break;
  839. }
  840. else {
  841. nb = sprintf(buff, form, s);
  842. lua_pop(L, 1); /* remove result from 'luaL_tolstring' */
  843. break;
  844. }
  845. }
  846. default: { /* also treat cases `pnLlh' */
  847. return luaL_error(L, "invalid option " LUA_QL("%%%c") " to "
  848. LUA_QL("format"), *(strfrmt - 1));
  849. }
  850. }
  851. luaL_addsize(&b, nb);
  852. }
  853. }
  854. luaL_pushresult(&b);
  855. return 1;
  856. }
  857. /* }====================================================== */
  858. static const luaL_Reg strlib[] = {
  859. {"byte", str_byte},
  860. {"char", str_char},
  861. {"dump", str_dump},
  862. {"find", str_find},
  863. {"format", str_format},
  864. {"gmatch", gmatch},
  865. {"gsub", str_gsub},
  866. {"len", str_len},
  867. {"lower", str_lower},
  868. {"match", str_match},
  869. {"rep", str_rep},
  870. {"reverse", str_reverse},
  871. {"sub", str_sub},
  872. {"upper", str_upper},
  873. {NULL, NULL}
  874. };
  875. static void createmetatable (lua_State *L) {
  876. lua_createtable(L, 0, 1); /* table to be metatable for strings */
  877. lua_pushliteral(L, ""); /* dummy string */
  878. lua_pushvalue(L, -2); /* copy table */
  879. lua_setmetatable(L, -2); /* set table as metatable for strings */
  880. lua_pop(L, 1); /* pop dummy string */
  881. lua_pushvalue(L, -2); /* get string library */
  882. lua_setfield(L, -2, "__index"); /* metatable.__index = string */
  883. lua_pop(L, 1); /* pop metatable */
  884. }
  885. /*
  886. ** Open string library
  887. */
  888. LUAMOD_API int luaopen_string (lua_State *L) {
  889. luaL_newlib(L, strlib);
  890. createmetatable(L);
  891. return 1;
  892. }