lstrlib.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  1. /*
  2. ** $Id: lstrlib.c,v 1.56 2000/10/27 16:15:53 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. #include "lua.h"
  12. #include "lauxlib.h"
  13. #include "lualib.h"
  14. static int str_len (lua_State *L) {
  15. size_t l;
  16. luaL_check_lstr(L, 1, &l);
  17. lua_pushnumber(L, l);
  18. return 1;
  19. }
  20. static long posrelat (long pos, size_t len) {
  21. /* relative string position: negative means back from end */
  22. return (pos>=0) ? pos : (long)len+pos+1;
  23. }
  24. static int str_sub (lua_State *L) {
  25. size_t l;
  26. const char *s = luaL_check_lstr(L, 1, &l);
  27. long start = posrelat(luaL_check_long(L, 2), l);
  28. long end = posrelat(luaL_opt_long(L, 3, -1), l);
  29. if (start < 1) start = 1;
  30. if (end > (long)l) end = l;
  31. if (start <= end)
  32. lua_pushlstring(L, s+start-1, end-start+1);
  33. else lua_pushstring(L, "");
  34. return 1;
  35. }
  36. static int str_lower (lua_State *L) {
  37. size_t l;
  38. size_t i;
  39. luaL_Buffer b;
  40. const char *s = luaL_check_lstr(L, 1, &l);
  41. luaL_buffinit(L, &b);
  42. for (i=0; i<l; i++)
  43. luaL_putchar(&b, tolower((unsigned char)(s[i])));
  44. luaL_pushresult(&b);
  45. return 1;
  46. }
  47. static int str_upper (lua_State *L) {
  48. size_t l;
  49. size_t i;
  50. luaL_Buffer b;
  51. const char *s = luaL_check_lstr(L, 1, &l);
  52. luaL_buffinit(L, &b);
  53. for (i=0; i<l; i++)
  54. luaL_putchar(&b, toupper((unsigned char)(s[i])));
  55. luaL_pushresult(&b);
  56. return 1;
  57. }
  58. static int str_rep (lua_State *L) {
  59. size_t l;
  60. luaL_Buffer b;
  61. const char *s = luaL_check_lstr(L, 1, &l);
  62. int n = luaL_check_int(L, 2);
  63. luaL_buffinit(L, &b);
  64. while (n-- > 0)
  65. luaL_addlstring(&b, s, l);
  66. luaL_pushresult(&b);
  67. return 1;
  68. }
  69. static int str_byte (lua_State *L) {
  70. size_t l;
  71. const char *s = luaL_check_lstr(L, 1, &l);
  72. long pos = posrelat(luaL_opt_long(L, 2, 1), l);
  73. luaL_arg_check(L, 0<pos && (size_t)pos<=l, 2, "out of range");
  74. lua_pushnumber(L, (unsigned char)s[pos-1]);
  75. return 1;
  76. }
  77. static int str_char (lua_State *L) {
  78. int n = lua_gettop(L); /* number of arguments */
  79. int i;
  80. luaL_Buffer b;
  81. luaL_buffinit(L, &b);
  82. for (i=1; i<=n; i++) {
  83. int c = luaL_check_int(L, i);
  84. luaL_arg_check(L, (unsigned char)c == c, i, "invalid value");
  85. luaL_putchar(&b, (unsigned char)c);
  86. }
  87. luaL_pushresult(&b);
  88. return 1;
  89. }
  90. /*
  91. ** {======================================================
  92. ** PATTERN MATCHING
  93. ** =======================================================
  94. */
  95. #ifndef MAX_CAPTURES
  96. #define MAX_CAPTURES 32 /* arbitrary limit */
  97. #endif
  98. typedef struct MatchState {
  99. const char *src_end; /* end ('\0') of source string */
  100. int level; /* total number of captures (finished or unfinished) */
  101. struct {
  102. const char *init;
  103. long len; /* -1 signals unfinished capture */
  104. } capture[MAX_CAPTURES];
  105. lua_State *L;
  106. } MatchState;
  107. #define ESC '%'
  108. #define SPECIALS "^$*+?.([%-"
  109. static int check_capture (MatchState *ms, int l) {
  110. l -= '1';
  111. if (!(0 <= l && l < ms->level && ms->capture[l].len != -1))
  112. lua_error(ms->L, "invalid capture index");
  113. return l;
  114. }
  115. static int capture_to_close (MatchState *ms) {
  116. int level = ms->level;
  117. for (level--; level>=0; level--)
  118. if (ms->capture[level].len == -1) return level;
  119. lua_error(ms->L, "invalid pattern capture");
  120. return 0; /* to avoid warnings */
  121. }
  122. static const char *luaI_classend (MatchState *ms, const char *p) {
  123. switch (*p++) {
  124. case ESC:
  125. if (*p == '\0') lua_error(ms->L, "malformed pattern (ends with `%')");
  126. return p+1;
  127. case '[':
  128. if (*p == '^') p++;
  129. do { /* look for a ']' */
  130. if (*p == '\0') lua_error(ms->L, "malformed pattern (missing `]')");
  131. if (*(p++) == ESC && *p != '\0') p++; /* skip escapes (e.g. '%]') */
  132. } while (*p != ']');
  133. return p+1;
  134. default:
  135. return p;
  136. }
  137. }
  138. static int match_class (int c, int cl) {
  139. int res;
  140. switch (tolower(cl)) {
  141. case 'a' : res = isalpha(c); break;
  142. case 'c' : res = iscntrl(c); break;
  143. case 'd' : res = isdigit(c); break;
  144. case 'l' : res = islower(c); break;
  145. case 'p' : res = ispunct(c); break;
  146. case 's' : res = isspace(c); break;
  147. case 'u' : res = isupper(c); break;
  148. case 'w' : res = isalnum(c); break;
  149. case 'x' : res = isxdigit(c); break;
  150. case 'z' : res = (c == '\0'); break;
  151. default: return (cl == c);
  152. }
  153. return (islower(cl) ? res : !res);
  154. }
  155. static int matchbracketclass (int c, const char *p, const char *endclass) {
  156. int sig = 1;
  157. if (*(p+1) == '^') {
  158. sig = 0;
  159. p++; /* skip the '^' */
  160. }
  161. while (++p < endclass) {
  162. if (*p == ESC) {
  163. p++;
  164. if (match_class(c, (unsigned char)*p))
  165. return sig;
  166. }
  167. else if ((*(p+1) == '-') && (p+2 < endclass)) {
  168. p+=2;
  169. if ((int)(unsigned char)*(p-2) <= c && c <= (int)(unsigned char)*p)
  170. return sig;
  171. }
  172. else if ((int)(unsigned char)*p == c) return sig;
  173. }
  174. return !sig;
  175. }
  176. static int luaI_singlematch (int c, const char *p, const char *ep) {
  177. switch (*p) {
  178. case '.': /* matches any char */
  179. return 1;
  180. case ESC:
  181. return match_class(c, (unsigned char)*(p+1));
  182. case '[':
  183. return matchbracketclass(c, p, ep-1);
  184. default:
  185. return ((unsigned char)*p == c);
  186. }
  187. }
  188. static const char *match (MatchState *ms, const char *s, const char *p);
  189. static const char *matchbalance (MatchState *ms, const char *s, const char *p) {
  190. if (*p == 0 || *(p+1) == 0)
  191. lua_error(ms->L, "unbalanced pattern");
  192. if (*s != *p) return NULL;
  193. else {
  194. int b = *p;
  195. int e = *(p+1);
  196. int cont = 1;
  197. while (++s < ms->src_end) {
  198. if (*s == e) {
  199. if (--cont == 0) return s+1;
  200. }
  201. else if (*s == b) cont++;
  202. }
  203. }
  204. return NULL; /* string ends out of balance */
  205. }
  206. static const char *max_expand (MatchState *ms, const char *s, const char *p,
  207. const char *ep) {
  208. long i = 0; /* counts maximum expand for item */
  209. while ((s+i)<ms->src_end && luaI_singlematch((unsigned char)*(s+i), p, ep))
  210. i++;
  211. /* keeps trying to match with the maximum repetitions */
  212. while (i>=0) {
  213. const char *res = match(ms, (s+i), ep+1);
  214. if (res) return res;
  215. i--; /* else didn't match; reduce 1 repetition to try again */
  216. }
  217. return NULL;
  218. }
  219. static const char *min_expand (MatchState *ms, const char *s, const char *p,
  220. const char *ep) {
  221. for (;;) {
  222. const char *res = match(ms, s, ep+1);
  223. if (res != NULL)
  224. return res;
  225. else if (s<ms->src_end && luaI_singlematch((unsigned char)*s, p, ep))
  226. s++; /* try with one more repetition */
  227. else return NULL;
  228. }
  229. }
  230. static const char *start_capture (MatchState *ms, const char *s, const char *p){
  231. const char *res;
  232. int level = ms->level;
  233. if (level >= MAX_CAPTURES) lua_error(ms->L, "too many captures");
  234. ms->capture[level].init = s;
  235. ms->capture[level].len = -1;
  236. ms->level = level+1;
  237. if ((res=match(ms, s, p+1)) == NULL) /* match failed? */
  238. ms->level--; /* undo capture */
  239. return res;
  240. }
  241. static const char *end_capture (MatchState *ms, const char *s, const char *p) {
  242. int l = capture_to_close(ms);
  243. const char *res;
  244. ms->capture[l].len = s - ms->capture[l].init; /* close capture */
  245. if ((res = match(ms, s, p+1)) == NULL) /* match failed? */
  246. ms->capture[l].len = -1; /* undo capture */
  247. return res;
  248. }
  249. static const char *match_capture (MatchState *ms, const char *s, int level) {
  250. int l = check_capture(ms, level);
  251. size_t len = ms->capture[l].len;
  252. if ((size_t)(ms->src_end-s) >= len &&
  253. memcmp(ms->capture[l].init, s, len) == 0)
  254. return s+len;
  255. else return NULL;
  256. }
  257. static const char *match (MatchState *ms, const char *s, const char *p) {
  258. init: /* using goto's to optimize tail recursion */
  259. switch (*p) {
  260. case '(': /* start capture */
  261. return start_capture(ms, s, p);
  262. case ')': /* end capture */
  263. return end_capture(ms, s, p);
  264. case ESC: /* may be %[0-9] or %b */
  265. if (isdigit((unsigned char)(*(p+1)))) { /* capture? */
  266. s = match_capture(ms, s, *(p+1));
  267. if (s == NULL) return NULL;
  268. p+=2; goto init; /* else return match(ms, s, p+2) */
  269. }
  270. else if (*(p+1) == 'b') { /* balanced string? */
  271. s = matchbalance(ms, s, p+2);
  272. if (s == NULL) return NULL;
  273. p+=4; goto init; /* else return match(ms, s, p+4); */
  274. }
  275. else goto dflt; /* case default */
  276. case '\0': /* end of pattern */
  277. return s; /* match succeeded */
  278. case '$':
  279. if (*(p+1) == '\0') /* is the '$' the last char in pattern? */
  280. return (s == ms->src_end) ? s : NULL; /* check end of string */
  281. else goto dflt;
  282. default: dflt: { /* it is a pattern item */
  283. const char *ep = luaI_classend(ms, p); /* points to what is next */
  284. int m = s<ms->src_end && luaI_singlematch((unsigned char)*s, p, ep);
  285. switch (*ep) {
  286. case '?': { /* optional */
  287. const char *res;
  288. if (m && ((res=match(ms, s+1, ep+1)) != NULL))
  289. return res;
  290. p=ep+1; goto init; /* else return match(ms, s, ep+1); */
  291. }
  292. case '*': /* 0 or more repetitions */
  293. return max_expand(ms, s, p, ep);
  294. case '+': /* 1 or more repetitions */
  295. return (m ? max_expand(ms, s+1, p, ep) : NULL);
  296. case '-': /* 0 or more repetitions (minimum) */
  297. return min_expand(ms, s, p, ep);
  298. default:
  299. if (!m) return NULL;
  300. s++; p=ep; goto init; /* else return match(ms, s+1, ep); */
  301. }
  302. }
  303. }
  304. }
  305. static const char *lmemfind (const char *s1, size_t l1,
  306. const char *s2, size_t l2) {
  307. if (l2 == 0) return s1; /* empty strings are everywhere */
  308. else if (l2 > l1) return NULL; /* avoids a negative `l1' */
  309. else {
  310. const char *init; /* to search for a `*s2' inside `s1' */
  311. l2--; /* 1st char will be checked by `memchr' */
  312. l1 = l1-l2; /* `s2' cannot be found after that */
  313. while (l1 > 0 && (init = (const char *)memchr(s1, *s2, l1)) != NULL) {
  314. init++; /* 1st char is already checked */
  315. if (memcmp(init, s2+1, l2) == 0)
  316. return init-1;
  317. else { /* correct `l1' and `s1' to try again */
  318. l1 -= init-s1;
  319. s1 = init;
  320. }
  321. }
  322. return NULL; /* not found */
  323. }
  324. }
  325. static int push_captures (MatchState *ms) {
  326. int i;
  327. luaL_checkstack(ms->L, ms->level, "too many captures");
  328. for (i=0; i<ms->level; i++) {
  329. int l = ms->capture[i].len;
  330. if (l == -1) lua_error(ms->L, "unfinished capture");
  331. lua_pushlstring(ms->L, ms->capture[i].init, l);
  332. }
  333. return ms->level; /* number of strings pushed */
  334. }
  335. static int str_find (lua_State *L) {
  336. size_t l1, l2;
  337. const char *s = luaL_check_lstr(L, 1, &l1);
  338. const char *p = luaL_check_lstr(L, 2, &l2);
  339. long init = posrelat(luaL_opt_long(L, 3, 1), l1) - 1;
  340. luaL_arg_check(L, 0 <= init && (size_t)init <= l1, 3, "out of range");
  341. if (lua_gettop(L) > 3 || /* extra argument? */
  342. strpbrk(p, SPECIALS) == NULL) { /* or no special characters? */
  343. const char *s2 = lmemfind(s+init, l1-init, p, l2);
  344. if (s2) {
  345. lua_pushnumber(L, s2-s+1);
  346. lua_pushnumber(L, s2-s+l2);
  347. return 2;
  348. }
  349. }
  350. else {
  351. MatchState ms;
  352. int anchor = (*p == '^') ? (p++, 1) : 0;
  353. const char *s1=s+init;
  354. ms.L = L;
  355. ms.src_end = s+l1;
  356. do {
  357. const char *res;
  358. ms.level = 0;
  359. if ((res=match(&ms, s1, p)) != NULL) {
  360. lua_pushnumber(L, s1-s+1); /* start */
  361. lua_pushnumber(L, res-s); /* end */
  362. return push_captures(&ms) + 2;
  363. }
  364. } while (s1++<ms.src_end && !anchor);
  365. }
  366. lua_pushnil(L); /* not found */
  367. return 1;
  368. }
  369. static void add_s (MatchState *ms, luaL_Buffer *b) {
  370. lua_State *L = ms->L;
  371. if (lua_isstring(L, 3)) {
  372. const char *news = lua_tostring(L, 3);
  373. size_t l = lua_strlen(L, 3);
  374. size_t i;
  375. for (i=0; i<l; i++) {
  376. if (news[i] != ESC)
  377. luaL_putchar(b, news[i]);
  378. else {
  379. i++; /* skip ESC */
  380. if (!isdigit((unsigned char)news[i]))
  381. luaL_putchar(b, news[i]);
  382. else {
  383. int level = check_capture(ms, news[i]);
  384. luaL_addlstring(b, ms->capture[level].init, ms->capture[level].len);
  385. }
  386. }
  387. }
  388. }
  389. else { /* is a function */
  390. int n;
  391. lua_pushvalue(L, 3);
  392. n = push_captures(ms);
  393. lua_rawcall(L, n, 1);
  394. if (lua_isstring(L, -1))
  395. luaL_addvalue(b); /* add return to accumulated result */
  396. else
  397. lua_pop(L, 1); /* function result is not a string: pop it */
  398. }
  399. }
  400. static int str_gsub (lua_State *L) {
  401. size_t srcl;
  402. const char *src = luaL_check_lstr(L, 1, &srcl);
  403. const char *p = luaL_check_string(L, 2);
  404. int max_s = luaL_opt_int(L, 4, srcl+1);
  405. int anchor = (*p == '^') ? (p++, 1) : 0;
  406. int n = 0;
  407. MatchState ms;
  408. luaL_Buffer b;
  409. luaL_arg_check(L,
  410. lua_gettop(L) >= 3 && (lua_isstring(L, 3) || lua_isfunction(L, 3)),
  411. 3, "string or function expected");
  412. luaL_buffinit(L, &b);
  413. ms.L = L;
  414. ms.src_end = src+srcl;
  415. while (n < max_s) {
  416. const char *e;
  417. ms.level = 0;
  418. e = match(&ms, src, p);
  419. if (e) {
  420. n++;
  421. add_s(&ms, &b);
  422. }
  423. if (e && e>src) /* non empty match? */
  424. src = e; /* skip it */
  425. else if (src < ms.src_end)
  426. luaL_putchar(&b, *src++);
  427. else break;
  428. if (anchor) break;
  429. }
  430. luaL_addlstring(&b, src, ms.src_end-src);
  431. luaL_pushresult(&b);
  432. lua_pushnumber(L, n); /* number of substitutions */
  433. return 2;
  434. }
  435. /* }====================================================== */
  436. /* maximum size of each formatted item (> len(format('%99.99f', -1e308))) */
  437. #define MAX_ITEM 512
  438. /* maximum size of each format specification (such as '%-099.99d') */
  439. #define MAX_FORMAT 20
  440. static void luaI_addquoted (lua_State *L, luaL_Buffer *b, int arg) {
  441. size_t l;
  442. const char *s = luaL_check_lstr(L, arg, &l);
  443. luaL_putchar(b, '"');
  444. while (l--) {
  445. switch (*s) {
  446. case '"': case '\\': case '\n':
  447. luaL_putchar(b, '\\');
  448. luaL_putchar(b, *s);
  449. break;
  450. case '\0': luaL_addlstring(b, "\\000", 4); break;
  451. default: luaL_putchar(b, *s);
  452. }
  453. s++;
  454. }
  455. luaL_putchar(b, '"');
  456. }
  457. static const char *scanformat (lua_State *L, const char *strfrmt, char *form,
  458. int *hasprecision) {
  459. const char *p = strfrmt;
  460. while (strchr("-+ #0", *p)) p++; /* skip flags */
  461. if (isdigit((unsigned char)*p)) p++; /* skip width */
  462. if (isdigit((unsigned char)*p)) p++; /* (2 digits at most) */
  463. if (*p == '.') {
  464. p++;
  465. *hasprecision = 1;
  466. if (isdigit((unsigned char)*p)) p++; /* skip precision */
  467. if (isdigit((unsigned char)*p)) p++; /* (2 digits at most) */
  468. }
  469. if (isdigit((unsigned char)*p))
  470. lua_error(L, "invalid format (width or precision too long)");
  471. if (p-strfrmt+2 > MAX_FORMAT) /* +2 to include `%' and the specifier */
  472. lua_error(L, "invalid format (too long)");
  473. form[0] = '%';
  474. strncpy(form+1, strfrmt, p-strfrmt+1);
  475. form[p-strfrmt+2] = 0;
  476. return p;
  477. }
  478. static int str_format (lua_State *L) {
  479. int arg = 1;
  480. const char *strfrmt = luaL_check_string(L, arg);
  481. luaL_Buffer b;
  482. luaL_buffinit(L, &b);
  483. while (*strfrmt) {
  484. if (*strfrmt != '%')
  485. luaL_putchar(&b, *strfrmt++);
  486. else if (*++strfrmt == '%')
  487. luaL_putchar(&b, *strfrmt++); /* %% */
  488. else { /* format item */
  489. char form[MAX_FORMAT]; /* to store the format (`%...') */
  490. char buff[MAX_ITEM]; /* to store the formatted item */
  491. int hasprecision = 0;
  492. if (isdigit((unsigned char)*strfrmt) && *(strfrmt+1) == '$') {
  493. arg = *strfrmt - '0';
  494. strfrmt += 2; /* skip the `n$' */
  495. }
  496. arg++;
  497. strfrmt = scanformat(L, strfrmt, form, &hasprecision);
  498. switch (*strfrmt++) {
  499. case 'c': case 'd': case 'i':
  500. sprintf(buff, form, luaL_check_int(L, arg));
  501. break;
  502. case 'o': case 'u': case 'x': case 'X':
  503. sprintf(buff, form, (unsigned int)luaL_check_number(L, arg));
  504. break;
  505. case 'e': case 'E': case 'f': case 'g': case 'G':
  506. sprintf(buff, form, luaL_check_number(L, arg));
  507. break;
  508. case 'q':
  509. luaI_addquoted(L, &b, arg);
  510. continue; /* skip the "addsize" at the end */
  511. case 's': {
  512. size_t l;
  513. const char *s = luaL_check_lstr(L, arg, &l);
  514. if (!hasprecision && l >= 100) {
  515. /* no precision and string is too long to be formatted;
  516. keep original string */
  517. lua_pushvalue(L, arg);
  518. luaL_addvalue(&b);
  519. continue; /* skip the "addsize" at the end */
  520. }
  521. else {
  522. sprintf(buff, form, s);
  523. break;
  524. }
  525. }
  526. default: /* also treat cases `pnLlh' */
  527. lua_error(L, "invalid option in `format'");
  528. }
  529. luaL_addlstring(&b, buff, strlen(buff));
  530. }
  531. }
  532. luaL_pushresult(&b);
  533. return 1;
  534. }
  535. static const struct luaL_reg strlib[] = {
  536. {"strlen", str_len},
  537. {"strsub", str_sub},
  538. {"strlower", str_lower},
  539. {"strupper", str_upper},
  540. {"strchar", str_char},
  541. {"strrep", str_rep},
  542. {"strbyte", str_byte},
  543. {"format", str_format},
  544. {"strfind", str_find},
  545. {"gsub", str_gsub}
  546. };
  547. /*
  548. ** Open string library
  549. */
  550. LUALIB_API void lua_strlibopen (lua_State *L) {
  551. luaL_openl(L, strlib);
  552. }