lstrlib.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625
  1. /*
  2. ** $Id: lstrlib.c,v 1.44 2000/06/12 13:52:05 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. #define LUA_REENTRANT
  12. #include "lua.h"
  13. #include "lauxlib.h"
  14. #include "lualib.h"
  15. static void addnchar (lua_State *L, const char *s, size_t n) {
  16. char *b = luaL_openspace(L, n);
  17. memcpy(b, s, n);
  18. luaL_addsize(L, n);
  19. }
  20. static void str_len (lua_State *L) {
  21. size_t l;
  22. luaL_check_lstr(L, 1, &l);
  23. lua_pushnumber(L, l);
  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 void 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. }
  43. static void str_lower (lua_State *L) {
  44. size_t l;
  45. size_t i;
  46. const char *s = luaL_check_lstr(L, 1, &l);
  47. luaL_resetbuffer(L);
  48. for (i=0; i<l; i++)
  49. luaL_addchar(L, tolower((unsigned char)(s[i])));
  50. closeandpush(L);
  51. }
  52. static void str_upper (lua_State *L) {
  53. size_t l;
  54. size_t i;
  55. const char *s = luaL_check_lstr(L, 1, &l);
  56. luaL_resetbuffer(L);
  57. for (i=0; i<l; i++)
  58. luaL_addchar(L, toupper((unsigned char)(s[i])));
  59. closeandpush(L);
  60. }
  61. static void str_rep (lua_State *L) {
  62. size_t l;
  63. const char *s = luaL_check_lstr(L, 1, &l);
  64. int n = luaL_check_int(L, 2);
  65. luaL_resetbuffer(L);
  66. while (n-- > 0)
  67. addnchar(L, s, l);
  68. closeandpush(L);
  69. }
  70. static void str_byte (lua_State *L) {
  71. size_t l;
  72. const char *s = luaL_check_lstr(L, 1, &l);
  73. long 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. }
  77. static void str_char (lua_State *L) {
  78. int i = 0;
  79. luaL_resetbuffer(L);
  80. while (lua_getparam(L, ++i) != LUA_NOOBJECT) {
  81. int c = luaL_check_int(L, i);
  82. luaL_arg_check(L, (unsigned char)c == c, i, "invalid value");
  83. luaL_addchar(L, (unsigned char)c);
  84. }
  85. closeandpush(L);
  86. }
  87. /*
  88. ** {======================================================
  89. ** PATTERN MATCHING
  90. ** =======================================================
  91. */
  92. #ifndef MAX_CAPTURES
  93. #define MAX_CAPTURES 32 /* arbitrary limit */
  94. #endif
  95. struct Capture {
  96. const char *src_end; /* end ('\0') of source string */
  97. int level; /* total number of captures (finished or unfinished) */
  98. struct {
  99. const char *init;
  100. long len; /* -1 signals unfinished capture */
  101. } capture[MAX_CAPTURES];
  102. };
  103. #define ESC '%'
  104. #define SPECIALS "^$*+?.([%-"
  105. static void push_captures (lua_State *L, struct Capture *cap) {
  106. int i;
  107. for (i=0; i<cap->level; i++) {
  108. int l = cap->capture[i].len;
  109. if (l == -1) lua_error(L, "unfinished capture");
  110. lua_pushlstring(L, cap->capture[i].init, l);
  111. }
  112. }
  113. static int check_capture (lua_State *L, int l, struct Capture *cap) {
  114. l -= '1';
  115. if (!(0 <= l && l < cap->level && cap->capture[l].len != -1))
  116. lua_error(L, "invalid capture index");
  117. return l;
  118. }
  119. static int capture_to_close (lua_State *L, struct Capture *cap) {
  120. int level = cap->level;
  121. for (level--; level>=0; level--)
  122. if (cap->capture[level].len == -1) return level;
  123. lua_error(L, "invalid pattern capture");
  124. return 0; /* to avoid warnings */
  125. }
  126. const char *luaI_classend (lua_State *L, const char *p) {
  127. switch (*p++) {
  128. case ESC:
  129. if (*p == '\0') lua_error(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(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. 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 (lua_State *L, const char *s, const char *p,
  193. struct Capture *cap);
  194. static const char *matchbalance (lua_State *L, const char *s, const char *p,
  195. struct Capture *cap) {
  196. if (*p == 0 || *(p+1) == 0)
  197. lua_error(L, "unbalanced pattern");
  198. if (*s != *p) return NULL;
  199. else {
  200. int b = *p;
  201. int e = *(p+1);
  202. int cont = 1;
  203. while (++s < cap->src_end) {
  204. if (*s == e) {
  205. if (--cont == 0) return s+1;
  206. }
  207. else if (*s == b) cont++;
  208. }
  209. }
  210. return NULL; /* string ends out of balance */
  211. }
  212. static const char *max_expand (lua_State *L, const char *s, const char *p,
  213. const char *ep, struct Capture *cap) {
  214. long i = 0; /* counts maximum expand for item */
  215. while ((s+i)<cap->src_end && luaI_singlematch((unsigned char)*(s+i), p, ep))
  216. i++;
  217. /* keeps trying to match mith the maximum repetitions */
  218. while (i>=0) {
  219. const char *res = match(L, (s+i), ep+1, cap);
  220. if (res) return res;
  221. i--; /* else didn't match; reduce 1 repetition to try again */
  222. }
  223. return NULL;
  224. }
  225. static const char *min_expand (lua_State *L, const char *s, const char *p,
  226. const char *ep, struct Capture *cap) {
  227. for (;;) {
  228. const char *res = match(L, s, ep+1, cap);
  229. if (res != NULL)
  230. return res;
  231. else if (s<cap->src_end && luaI_singlematch((unsigned char)*s, p, ep))
  232. s++; /* try with one more repetition */
  233. else return NULL;
  234. }
  235. }
  236. static const char *start_capture (lua_State *L, const char *s, const char *p,
  237. struct Capture *cap) {
  238. const char *res;
  239. int level = cap->level;
  240. if (level >= MAX_CAPTURES) lua_error(L, "too many captures");
  241. cap->capture[level].init = s;
  242. cap->capture[level].len = -1;
  243. cap->level = level+1;
  244. if ((res=match(L, s, p+1, cap)) == NULL) /* match failed? */
  245. cap->level--; /* undo capture */
  246. return res;
  247. }
  248. static const char *end_capture (lua_State *L, const char *s, const char *p,
  249. struct Capture *cap) {
  250. int l = capture_to_close(L, cap);
  251. const char *res;
  252. cap->capture[l].len = s - cap->capture[l].init; /* close capture */
  253. if ((res = match(L, s, p+1, cap)) == NULL) /* match failed? */
  254. cap->capture[l].len = -1; /* undo capture */
  255. return res;
  256. }
  257. static const char *match_capture (lua_State *L, const char *s, int level,
  258. struct Capture *cap) {
  259. int l = check_capture(L, level, cap);
  260. size_t len = cap->capture[l].len;
  261. if ((size_t)(cap->src_end-s) >= len &&
  262. memcmp(cap->capture[l].init, s, len) == 0)
  263. return s+len;
  264. else return NULL;
  265. }
  266. static const char *match (lua_State *L, const char *s, const char *p,
  267. struct Capture *cap) {
  268. init: /* using goto's to optimize tail recursion */
  269. switch (*p) {
  270. case '(': /* start capture */
  271. return start_capture(L, s, p, cap);
  272. case ')': /* end capture */
  273. return end_capture(L, s, p, cap);
  274. case ESC: /* may be %[0-9] or %b */
  275. if (isdigit((unsigned char)(*(p+1)))) { /* capture? */
  276. s = match_capture(L, s, *(p+1), cap);
  277. if (s == NULL) return NULL;
  278. p+=2; goto init; /* else return match(L, s, p+2, cap) */
  279. }
  280. else if (*(p+1) == 'b') { /* balanced string? */
  281. s = matchbalance(L, s, p+2, cap);
  282. if (s == NULL) return NULL;
  283. p+=4; goto init; /* else return match(L, s, p+4, cap); */
  284. }
  285. else goto dflt; /* case default */
  286. case '\0': /* end of pattern */
  287. return s; /* match succeeded */
  288. case '$':
  289. if (*(p+1) == '\0') /* is the '$' the last char in pattern? */
  290. return (s == cap->src_end) ? s : NULL; /* check end of string */
  291. else goto dflt;
  292. default: dflt: { /* it is a pattern item */
  293. const char *ep = luaI_classend(L, p); /* points to what is next */
  294. int m = s<cap->src_end && luaI_singlematch((unsigned char)*s, p, ep);
  295. switch (*ep) {
  296. case '?': { /* optional */
  297. const char *res;
  298. if (m && ((res=match(L, s+1, ep+1, cap)) != NULL))
  299. return res;
  300. p=ep+1; goto init; /* else return match(L, s, ep+1, cap); */
  301. }
  302. case '*': /* 0 or more repetitions */
  303. return max_expand(L, s, p, ep, cap);
  304. case '+': /* 1 or more repetitions */
  305. return (m ? max_expand(L, s+1, p, ep, cap) : NULL);
  306. case '-': /* 0 or more repetitions (minimum) */
  307. return min_expand(L, s, p, ep, cap);
  308. default:
  309. if (!m) return NULL;
  310. s++; p=ep; goto init; /* else return match(L, s+1, ep, cap); */
  311. }
  312. }
  313. }
  314. }
  315. static const char *lmemfind (const char *s1, size_t l1,
  316. const char *s2, size_t l2) {
  317. if (l2 == 0) return s1; /* empty strings are everywhere */
  318. else if (l2 > l1) return NULL; /* avoids a negative `l1' */
  319. else {
  320. const char *init; /* to search for a `*s2' inside `s1' */
  321. l2--; /* 1st char will be checked by `memchr' */
  322. l1 = l1-l2; /* `s2' cannot be found after that */
  323. while (l1 > 0 && (init = (const char *)memchr(s1, *s2, l1)) != NULL) {
  324. init++; /* 1st char is already checked */
  325. if (memcmp(init, s2+1, l2) == 0)
  326. return init-1;
  327. else { /* correct `l1' and `s1' to try again */
  328. l1 -= init-s1;
  329. s1 = init;
  330. }
  331. }
  332. return NULL; /* not found */
  333. }
  334. }
  335. static void 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. struct Capture cap;
  341. luaL_arg_check(L, 0 <= init && (size_t)init <= l1, 3, "out of range");
  342. if (lua_getparam(L, 4) != LUA_NOOBJECT ||
  343. strpbrk(p, SPECIALS) == NULL) { /* 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;
  349. }
  350. }
  351. else {
  352. int anchor = (*p == '^') ? (p++, 1) : 0;
  353. const char *s1=s+init;
  354. cap.src_end = s+l1;
  355. do {
  356. const char *res;
  357. cap.level = 0;
  358. if ((res=match(L, s1, p, &cap)) != NULL) {
  359. lua_pushnumber(L, s1-s+1); /* start */
  360. lua_pushnumber(L, res-s); /* end */
  361. push_captures(L, &cap);
  362. return;
  363. }
  364. } while (s1++<cap.src_end && !anchor);
  365. }
  366. lua_pushnil(L); /* not found */
  367. }
  368. static void add_s (lua_State *L, lua_Object newp, struct Capture *cap) {
  369. if (lua_isstring(L, newp)) {
  370. const char *news = lua_getstring(L, newp);
  371. size_t l = lua_strlen(L, newp);
  372. size_t i;
  373. for (i=0; i<l; i++) {
  374. if (news[i] != ESC)
  375. luaL_addchar(L, news[i]);
  376. else {
  377. i++; /* skip ESC */
  378. if (!isdigit((unsigned char)news[i]))
  379. luaL_addchar(L, news[i]);
  380. else {
  381. int level = check_capture(L, news[i], cap);
  382. addnchar(L, cap->capture[level].init, cap->capture[level].len);
  383. }
  384. }
  385. }
  386. }
  387. else { /* is a function */
  388. lua_Object res;
  389. int status;
  390. size_t oldbuff;
  391. lua_beginblock(L);
  392. push_captures(L, cap);
  393. /* function may use buffer, so save it and create a new one */
  394. oldbuff = luaL_newbuffer(L, 0);
  395. status = lua_callfunction(L, newp);
  396. /* restore old buffer */
  397. luaL_oldbuffer(L, oldbuff);
  398. if (status != 0) {
  399. lua_endblock(L);
  400. lua_error(L, NULL);
  401. }
  402. res = lua_getresult(L, 1);
  403. if (lua_isstring(L, res))
  404. addnchar(L, lua_getstring(L, res), lua_strlen(L, res));
  405. lua_endblock(L);
  406. }
  407. }
  408. static void str_gsub (lua_State *L) {
  409. size_t srcl;
  410. const char *src = luaL_check_lstr(L, 1, &srcl);
  411. const char *p = luaL_check_string(L, 2);
  412. lua_Object newp = lua_getparam(L, 3);
  413. int max_s = luaL_opt_int(L, 4, srcl+1);
  414. int anchor = (*p == '^') ? (p++, 1) : 0;
  415. int n = 0;
  416. struct Capture cap;
  417. luaL_arg_check(L, lua_isstring(L, newp) || lua_isfunction(L, newp), 3,
  418. "string or function expected");
  419. luaL_resetbuffer(L);
  420. cap.src_end = src+srcl;
  421. while (n < max_s) {
  422. const char *e;
  423. cap.level = 0;
  424. e = match(L, src, p, &cap);
  425. if (e) {
  426. n++;
  427. add_s(L, newp, &cap);
  428. }
  429. if (e && e>src) /* non empty match? */
  430. src = e; /* skip it */
  431. else if (src < cap.src_end)
  432. luaL_addchar(L, *src++);
  433. else break;
  434. if (anchor) break;
  435. }
  436. addnchar(L, src, cap.src_end-src);
  437. closeandpush(L);
  438. lua_pushnumber(L, n); /* number of substitutions */
  439. }
  440. /* }====================================================== */
  441. static void luaI_addquoted (lua_State *L, int arg) {
  442. size_t l;
  443. const char *s = luaL_check_lstr(L, arg, &l);
  444. luaL_addchar(L, '"');
  445. while (l--) {
  446. switch (*s) {
  447. case '"': case '\\': case '\n':
  448. luaL_addchar(L, '\\');
  449. luaL_addchar(L, *s);
  450. break;
  451. case '\0': addnchar(L, "\\000", 4); break;
  452. default: luaL_addchar(L, *s);
  453. }
  454. s++;
  455. }
  456. luaL_addchar(L, '"');
  457. }
  458. /* maximum size of each format specification (such as '%-099.99d') */
  459. #define MAX_FORMAT 20 /* arbitrary limit */
  460. static void str_format (lua_State *L) {
  461. int arg = 1;
  462. const char *strfrmt = luaL_check_string(L, arg);
  463. luaL_resetbuffer(L);
  464. while (*strfrmt) {
  465. if (*strfrmt != '%')
  466. luaL_addchar(L, *strfrmt++);
  467. else if (*++strfrmt == '%')
  468. luaL_addchar(L, *strfrmt++); /* %% */
  469. else { /* format item */
  470. struct Capture cap;
  471. char form[MAX_FORMAT]; /* to store the format ('%...') */
  472. char *buff; /* to store the formatted item */
  473. const char *initf = strfrmt;
  474. form[0] = '%';
  475. if (isdigit((unsigned char)*initf) && *(initf+1) == '$') {
  476. arg = *initf - '0';
  477. initf += 2; /* skip the 'n$' */
  478. }
  479. arg++;
  480. cap.src_end = strfrmt+strlen(strfrmt)+1;
  481. cap.level = 0;
  482. strfrmt = match(L, initf, "[-+ #0]*(%d*)%.?(%d*)", &cap);
  483. if (cap.capture[0].len > 2 || cap.capture[1].len > 2 || /* < 100? */
  484. strfrmt-initf > MAX_FORMAT-2)
  485. lua_error(L, "invalid format (width or precision too long)");
  486. strncpy(form+1, initf, strfrmt-initf+1); /* +1 to include conversion */
  487. form[strfrmt-initf+2] = 0;
  488. buff = luaL_openspace(L, 512); /* 512 > len(format('%99.99f', -1e308)) */
  489. switch (*strfrmt++) {
  490. case 'c': case 'd': case 'i':
  491. sprintf(buff, form, luaL_check_int(L, arg));
  492. break;
  493. case 'o': case 'u': case 'x': case 'X':
  494. sprintf(buff, form, (unsigned int)luaL_check_number(L, arg));
  495. break;
  496. case 'e': case 'E': case 'f': case 'g': case 'G':
  497. sprintf(buff, form, luaL_check_number(L, arg));
  498. break;
  499. case 'q':
  500. luaI_addquoted(L, arg);
  501. continue; /* skip the "addsize" at the end */
  502. case 's': {
  503. size_t l;
  504. const char *s = luaL_check_lstr(L, arg, &l);
  505. if (cap.capture[1].len == 0 && l >= 100) {
  506. /* no precision and string is too long to be formatted;
  507. keep original string */
  508. addnchar(L, s, l);
  509. continue; /* skip the "addsize" at the end */
  510. }
  511. else {
  512. sprintf(buff, form, s);
  513. break;
  514. }
  515. }
  516. default: /* also treat cases 'pnLlh' */
  517. lua_error(L, "invalid option in `format'");
  518. }
  519. luaL_addsize(L, strlen(buff));
  520. }
  521. }
  522. closeandpush(L); /* push the result */
  523. }
  524. static const struct luaL_reg strlib[] = {
  525. {"strlen", str_len},
  526. {"strsub", str_sub},
  527. {"strlower", str_lower},
  528. {"strupper", str_upper},
  529. {"strchar", str_char},
  530. {"strrep", str_rep},
  531. {"ascii", str_byte}, /* for compatibility with 3.0 and earlier */
  532. {"strbyte", str_byte},
  533. {"format", str_format},
  534. {"strfind", str_find},
  535. {"gsub", str_gsub}
  536. };
  537. /*
  538. ** Open string library
  539. */
  540. void lua_strlibopen (lua_State *L) {
  541. luaL_openl(L, strlib);
  542. }