lstrlib.c 18 KB

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