lstrlib.c 17 KB

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