lstrlib.c 17 KB

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