lstrlib.c 17 KB

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