lstrlib.c 17 KB

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