lstrlib.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633
  1. /*
  2. ** $Id: lstrlib.c,v 1.46 2000/08/09 19:16:57 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 mith 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. for (i=0; i<cap->level; i++) {
  337. int l = cap->capture[i].len;
  338. if (l == -1) lua_error(L, "unfinished capture");
  339. lua_pushlstring(L, cap->capture[i].init, l);
  340. }
  341. return cap->level; /* number of strings pushed */
  342. }
  343. static int str_find (lua_State *L) {
  344. size_t l1, l2;
  345. const char *s = luaL_check_lstr(L, 1, &l1);
  346. const char *p = luaL_check_lstr(L, 2, &l2);
  347. long init = posrelat(luaL_opt_long(L, 3, 1), l1) - 1;
  348. struct Capture cap;
  349. luaL_arg_check(L, 0 <= init && (size_t)init <= l1, 3, "out of range");
  350. if (lua_gettop(L) > 3 || /* extra argument? */
  351. strpbrk(p, SPECIALS) == NULL) { /* or no special characters? */
  352. const char *s2 = lmemfind(s+init, l1-init, p, l2);
  353. if (s2) {
  354. lua_pushnumber(L, s2-s+1);
  355. lua_pushnumber(L, s2-s+l2);
  356. return 2;
  357. }
  358. }
  359. else {
  360. int anchor = (*p == '^') ? (p++, 1) : 0;
  361. const char *s1=s+init;
  362. cap.src_end = s+l1;
  363. do {
  364. const char *res;
  365. cap.level = 0;
  366. if ((res=match(L, s1, p, &cap)) != NULL) {
  367. lua_pushnumber(L, s1-s+1); /* start */
  368. lua_pushnumber(L, res-s); /* end */
  369. return push_captures(L, &cap) + 2;
  370. }
  371. } while (s1++<cap.src_end && !anchor);
  372. }
  373. lua_pushnil(L); /* not found */
  374. return 1;
  375. }
  376. static void add_s (lua_State *L, struct Capture *cap) {
  377. if (lua_isstring(L, 3)) {
  378. const char *news = lua_tostring(L, 3);
  379. size_t l = lua_strlen(L, 3);
  380. size_t i;
  381. for (i=0; i<l; i++) {
  382. if (news[i] != ESC)
  383. luaL_addchar(L, news[i]);
  384. else {
  385. i++; /* skip ESC */
  386. if (!isdigit((unsigned char)news[i]))
  387. luaL_addchar(L, news[i]);
  388. else {
  389. int level = check_capture(L, news[i], cap);
  390. addnchar(L, cap->capture[level].init, cap->capture[level].len);
  391. }
  392. }
  393. }
  394. }
  395. else { /* is a function */
  396. int status;
  397. size_t oldbuff;
  398. int n;
  399. const char *s;
  400. lua_pushobject(L, 3);
  401. n = push_captures(L, cap);
  402. /* function may use buffer, so save it and create a new one */
  403. oldbuff = luaL_newbuffer(L, 0);
  404. status = lua_call(L, n, 1);
  405. /* restore old buffer */
  406. luaL_oldbuffer(L, oldbuff);
  407. if (status != 0)
  408. lua_error(L, NULL);
  409. s = lua_tostring(L, -1);
  410. if (s)
  411. addnchar(L, lua_tostring(L, -1), lua_strlen(L, -1));
  412. lua_settop(L, -1); /* pop function result */
  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. struct Capture cap;
  423. luaL_arg_check(L,
  424. lua_gettop(L) >= 3 && (lua_isstring(L, 3) || lua_isfunction(L, 3)),
  425. 3, "string or function expected");
  426. luaL_resetbuffer(L);
  427. cap.src_end = src+srcl;
  428. while (n < max_s) {
  429. const char *e;
  430. cap.level = 0;
  431. e = match(L, src, p, &cap);
  432. if (e) {
  433. n++;
  434. add_s(L, &cap);
  435. }
  436. if (e && e>src) /* non empty match? */
  437. src = e; /* skip it */
  438. else if (src < cap.src_end)
  439. luaL_addchar(L, *src++);
  440. else break;
  441. if (anchor) break;
  442. }
  443. addnchar(L, src, cap.src_end-src);
  444. closeandpush(L);
  445. lua_pushnumber(L, n); /* number of substitutions */
  446. return 2;
  447. }
  448. /* }====================================================== */
  449. static void luaI_addquoted (lua_State *L, int arg) {
  450. size_t l;
  451. const char *s = luaL_check_lstr(L, arg, &l);
  452. luaL_addchar(L, '"');
  453. while (l--) {
  454. switch (*s) {
  455. case '"': case '\\': case '\n':
  456. luaL_addchar(L, '\\');
  457. luaL_addchar(L, *s);
  458. break;
  459. case '\0': addnchar(L, "\\000", 4); break;
  460. default: luaL_addchar(L, *s);
  461. }
  462. s++;
  463. }
  464. luaL_addchar(L, '"');
  465. }
  466. /* maximum size of each format specification (such as '%-099.99d') */
  467. #define MAX_FORMAT 20 /* arbitrary limit */
  468. static int str_format (lua_State *L) {
  469. int arg = 1;
  470. const char *strfrmt = luaL_check_string(L, arg);
  471. luaL_resetbuffer(L);
  472. while (*strfrmt) {
  473. if (*strfrmt != '%')
  474. luaL_addchar(L, *strfrmt++);
  475. else if (*++strfrmt == '%')
  476. luaL_addchar(L, *strfrmt++); /* %% */
  477. else { /* format item */
  478. struct Capture cap;
  479. char form[MAX_FORMAT]; /* to store the format ('%...') */
  480. char *buff; /* to store the formatted item */
  481. const char *initf = strfrmt;
  482. form[0] = '%';
  483. if (isdigit((unsigned char)*initf) && *(initf+1) == '$') {
  484. arg = *initf - '0';
  485. initf += 2; /* skip the 'n$' */
  486. }
  487. arg++;
  488. cap.src_end = strfrmt+strlen(strfrmt)+1;
  489. cap.level = 0;
  490. strfrmt = match(L, initf, "[-+ #0]*(%d*)%.?(%d*)", &cap);
  491. if (cap.capture[0].len > 2 || cap.capture[1].len > 2 || /* < 100? */
  492. strfrmt-initf > MAX_FORMAT-2)
  493. lua_error(L, "invalid format (width or precision too long)");
  494. strncpy(form+1, initf, strfrmt-initf+1); /* +1 to include conversion */
  495. form[strfrmt-initf+2] = 0;
  496. buff = luaL_openspace(L, 512); /* 512 > len(format('%99.99f', -1e308)) */
  497. switch (*strfrmt++) {
  498. case 'c': case 'd': case 'i':
  499. sprintf(buff, form, luaL_check_int(L, arg));
  500. break;
  501. case 'o': case 'u': case 'x': case 'X':
  502. sprintf(buff, form, (unsigned int)luaL_check_number(L, arg));
  503. break;
  504. case 'e': case 'E': case 'f': case 'g': case 'G':
  505. sprintf(buff, form, luaL_check_number(L, arg));
  506. break;
  507. case 'q':
  508. luaI_addquoted(L, arg);
  509. continue; /* skip the "addsize" at the end */
  510. case 's': {
  511. size_t l;
  512. const char *s = luaL_check_lstr(L, arg, &l);
  513. if (cap.capture[1].len == 0 && l >= 100) {
  514. /* no precision and string is too long to be formatted;
  515. keep original string */
  516. addnchar(L, s, l);
  517. continue; /* skip the "addsize" at the end */
  518. }
  519. else {
  520. sprintf(buff, form, s);
  521. break;
  522. }
  523. }
  524. default: /* also treat cases 'pnLlh' */
  525. lua_error(L, "invalid option in `format'");
  526. }
  527. luaL_addsize(L, strlen(buff));
  528. }
  529. }
  530. closeandpush(L); /* push the result */
  531. return 1;
  532. }
  533. static const struct luaL_reg strlib[] = {
  534. {"strlen", str_len},
  535. {"strsub", str_sub},
  536. {"strlower", str_lower},
  537. {"strupper", str_upper},
  538. {"strchar", str_char},
  539. {"strrep", str_rep},
  540. {"ascii", str_byte}, /* for compatibility with 3.0 and earlier */
  541. {"strbyte", str_byte},
  542. {"format", str_format},
  543. {"strfind", str_find},
  544. {"gsub", str_gsub}
  545. };
  546. /*
  547. ** Open string library
  548. */
  549. void lua_strlibopen (lua_State *L) {
  550. luaL_openl(L, strlib);
  551. }