lstrlib.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  1. /*
  2. ** $Id: lstrlib.c,v 1.31 1999/05/14 12:24:04 roberto Exp roberto $
  3. ** Standard library for strings 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. #include "lauxlib.h"
  11. #include "lua.h"
  12. #include "lualib.h"
  13. static void addnchar (char *s, int n)
  14. {
  15. char *b = luaL_openspace(n);
  16. memcpy(b, s, n);
  17. luaL_addsize(n);
  18. }
  19. static void str_len (void)
  20. {
  21. long l;
  22. luaL_check_lstr(1, &l);
  23. lua_pushnumber(l);
  24. }
  25. static void closeandpush (void) {
  26. lua_pushlstring(luaL_buffer(), luaL_getsize());
  27. }
  28. static long posrelat (long pos, long len) {
  29. /* relative string position: negative means back from end */
  30. return (pos>=0) ? pos : len+pos+1;
  31. }
  32. static void str_sub (void) {
  33. long l;
  34. char *s = luaL_check_lstr(1, &l);
  35. long start = posrelat(luaL_check_long(2), l);
  36. long end = posrelat(luaL_opt_long(3, -1), l);
  37. if (start < 1) start = 1;
  38. if (end > l) end = l;
  39. if (start <= end)
  40. lua_pushlstring(s+start-1, end-start+1);
  41. else lua_pushstring("");
  42. }
  43. static void str_lower (void) {
  44. long l;
  45. int i;
  46. char *s = luaL_check_lstr(1, &l);
  47. luaL_resetbuffer();
  48. for (i=0; i<l; i++)
  49. luaL_addchar(tolower((unsigned char)(s[i])));
  50. closeandpush();
  51. }
  52. static void str_upper (void) {
  53. long l;
  54. int i;
  55. char *s = luaL_check_lstr(1, &l);
  56. luaL_resetbuffer();
  57. for (i=0; i<l; i++)
  58. luaL_addchar(toupper((unsigned char)(s[i])));
  59. closeandpush();
  60. }
  61. static void str_rep (void)
  62. {
  63. long l;
  64. char *s = luaL_check_lstr(1, &l);
  65. int n = luaL_check_int(2);
  66. luaL_resetbuffer();
  67. while (n-- > 0)
  68. addnchar(s, l);
  69. closeandpush();
  70. }
  71. static void str_byte (void) {
  72. long l;
  73. char *s = luaL_check_lstr(1, &l);
  74. long pos = posrelat(luaL_opt_long(2, 1), l);
  75. luaL_arg_check(0<pos && pos<=l, 2, "out of range");
  76. lua_pushnumber((unsigned char)s[pos-1]);
  77. }
  78. static void str_char (void) {
  79. int i = 0;
  80. luaL_resetbuffer();
  81. while (lua_getparam(++i) != LUA_NOOBJECT) {
  82. double c = luaL_check_number(i);
  83. luaL_arg_check((unsigned char)c == c, i, "invalid value");
  84. luaL_addchar((unsigned char)c);
  85. }
  86. closeandpush();
  87. }
  88. /*
  89. ** {======================================================
  90. ** PATTERN MATCHING
  91. ** =======================================================
  92. */
  93. #ifndef MAX_CAPT
  94. #define MAX_CAPT 32 /* arbitrary limit */
  95. #endif
  96. struct Capture {
  97. char *src_end; /* end ('\0') of source string */
  98. int level; /* total number of captures (finished or unfinished) */
  99. struct {
  100. char *init;
  101. int len; /* -1 signals unfinished capture */
  102. } capture[MAX_CAPT];
  103. };
  104. #define ESC '%'
  105. #define SPECIALS "^$*+?.([%-"
  106. static void push_captures (struct Capture *cap) {
  107. int i;
  108. for (i=0; i<cap->level; i++) {
  109. int l = cap->capture[i].len;
  110. if (l == -1) lua_error("unfinished capture");
  111. lua_pushlstring(cap->capture[i].init, l);
  112. }
  113. }
  114. static int check_cap (int l, struct Capture *cap) {
  115. l -= '1';
  116. if (!(0 <= l && l < cap->level && cap->capture[l].len != -1))
  117. lua_error("invalid capture index");
  118. return l;
  119. }
  120. static int capture_to_close (struct Capture *cap) {
  121. int level = cap->level;
  122. for (level--; level>=0; level--)
  123. if (cap->capture[level].len == -1) return level;
  124. lua_error("invalid pattern capture");
  125. return 0; /* to avoid warnings */
  126. }
  127. char *luaI_classend (char *p) {
  128. switch (*p++) {
  129. case ESC:
  130. if (*p == '\0')
  131. luaL_verror("incorrect pattern (ends with `%c')", ESC);
  132. return p+1;
  133. case '[':
  134. if (*p == '^') p++;
  135. if (*p == ']') p++;
  136. p = strchr(p, ']');
  137. if (!p) lua_error("incorrect pattern (missing `]')");
  138. return p+1;
  139. default:
  140. return p;
  141. }
  142. }
  143. static int matchclass (int c, int cl) {
  144. int res;
  145. switch (tolower(cl)) {
  146. case 'a' : res = isalpha(c); break;
  147. case 'c' : res = iscntrl(c); break;
  148. case 'd' : res = isdigit(c); break;
  149. case 'l' : res = islower(c); break;
  150. case 'p' : res = ispunct(c); break;
  151. case 's' : res = isspace(c); break;
  152. case 'u' : res = isupper(c); break;
  153. case 'w' : res = isalnum(c); break;
  154. case 'x' : res = isxdigit(c); break;
  155. case 'z' : res = (c == '\0'); break;
  156. default: return (cl == c);
  157. }
  158. return (islower(cl) ? res : !res);
  159. }
  160. static int matchbracketclass (int c, char *p, char *end) {
  161. int sig = 1;
  162. if (*(p+1) == '^') {
  163. sig = 0;
  164. p++; /* skip the '^' */
  165. }
  166. while (++p < end) {
  167. if (*p == ESC) {
  168. p++;
  169. if ((p < end) && matchclass(c, (unsigned char)*p))
  170. return sig;
  171. }
  172. else if ((*(p+1) == '-') && (p+2 < end)) {
  173. p+=2;
  174. if ((int)(unsigned char)*(p-2) <= c && c <= (int)(unsigned char)*p)
  175. return sig;
  176. }
  177. else if ((unsigned char)*p == c) return sig;
  178. }
  179. return !sig;
  180. }
  181. int luaI_singlematch (int c, char *p, char *ep) {
  182. switch (*p) {
  183. case '.': /* matches any char */
  184. return 1;
  185. case ESC:
  186. return matchclass(c, (unsigned char)*(p+1));
  187. case '[':
  188. return matchbracketclass(c, p, ep-1);
  189. default:
  190. return ((unsigned char)*p == c);
  191. }
  192. }
  193. static char *match (char *s, char *p, struct Capture *cap);
  194. static char *matchbalance (char *s, char *p, struct Capture *cap) {
  195. if (*p == 0 || *(p+1) == 0)
  196. lua_error("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 char *max_expand (char *s, char *p, char *ep, 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. char *res = match((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 char *min_expand (char *s, char *p, char *ep, struct Capture *cap) {
  224. for (;;) {
  225. char *res = match(s, ep+1, cap);
  226. if (res != NULL)
  227. return res;
  228. else if (s<cap->src_end && luaI_singlematch((unsigned char)*s, p, ep))
  229. s++; /* try with one more repetition */
  230. else return NULL;
  231. }
  232. }
  233. static char *start_capt (char *s, char *p, struct Capture *cap) {
  234. char *res;
  235. int level = cap->level;
  236. if (level >= MAX_CAPT) lua_error("too many captures");
  237. cap->capture[level].init = s;
  238. cap->capture[level].len = -1;
  239. cap->level = level+1;
  240. if ((res=match(s, p+1, cap)) == NULL) /* match failed? */
  241. cap->level--; /* undo capture */
  242. return res;
  243. }
  244. static char *end_capt (char *s, char *p, struct Capture *cap) {
  245. int l = capture_to_close(cap);
  246. char *res;
  247. cap->capture[l].len = s - cap->capture[l].init; /* close capture */
  248. if ((res = match(s, p+1, cap)) == NULL) /* match failed? */
  249. cap->capture[l].len = -1; /* undo capture */
  250. return res;
  251. }
  252. static char *match_capture (char *s, int level, struct Capture *cap) {
  253. int l = check_cap(level, cap);
  254. int len = cap->capture[l].len;
  255. if (cap->src_end-s >= len &&
  256. memcmp(cap->capture[l].init, s, len) == 0)
  257. return s+len;
  258. else return NULL;
  259. }
  260. static char *match (char *s, char *p, struct Capture *cap) {
  261. init: /* using goto's to optimize tail recursion */
  262. switch (*p) {
  263. case '(': /* start capture */
  264. return start_capt(s, p, cap);
  265. case ')': /* end capture */
  266. return end_capt(s, p, cap);
  267. case ESC: /* may be %[0-9] or %b */
  268. if (isdigit((unsigned char)(*(p+1)))) { /* capture? */
  269. s = match_capture(s, *(p+1), cap);
  270. if (s == NULL) return NULL;
  271. p+=2; goto init; /* else return match(p+2, s, cap) */
  272. }
  273. else if (*(p+1) == 'b') { /* balanced string? */
  274. s = matchbalance(s, p+2, cap);
  275. if (s == NULL) return NULL;
  276. p+=4; goto init; /* else return match(p+4, s, cap); */
  277. }
  278. else goto dflt; /* case default */
  279. case '\0': /* end of pattern */
  280. return s; /* match succeeded */
  281. case '$':
  282. if (*(p+1) == '\0') /* is the '$' the last char in pattern? */
  283. return (s == cap->src_end) ? s : NULL; /* check end of string */
  284. else goto dflt;
  285. default: dflt: { /* it is a pattern item */
  286. char *ep = luaI_classend(p); /* points to what is next */
  287. int m = s<cap->src_end && luaI_singlematch((unsigned char)*s, p, ep);
  288. switch (*ep) {
  289. case '?': { /* optional */
  290. char *res;
  291. if (m && ((res=match(s+1, ep+1, cap)) != NULL))
  292. return res;
  293. p=ep+1; goto init; /* else return match(s, ep+1, cap); */
  294. }
  295. case '*': /* 0 or more repetitions */
  296. return max_expand(s, p, ep, cap);
  297. case '+': /* 1 or more repetitions */
  298. return (m ? max_expand(s+1, p, ep, cap) : NULL);
  299. case '-': /* 0 or more repetitions (minimum) */
  300. return min_expand(s, p, ep, cap);
  301. default:
  302. if (!m) return NULL;
  303. s++; p=ep; goto init; /* else return match(s+1, ep, cap); */
  304. }
  305. }
  306. }
  307. }
  308. static void str_find (void) {
  309. long l;
  310. char *s = luaL_check_lstr(1, &l);
  311. char *p = luaL_check_string(2);
  312. long init = posrelat(luaL_opt_long(3, 1), l) - 1;
  313. struct Capture cap;
  314. luaL_arg_check(0 <= init && init <= l, 3, "out of range");
  315. if (lua_getparam(4) != LUA_NOOBJECT ||
  316. strpbrk(p, SPECIALS) == NULL) { /* no special characters? */
  317. char *s2 = strstr(s+init, p);
  318. if (s2) {
  319. lua_pushnumber(s2-s+1);
  320. lua_pushnumber(s2-s+strlen(p));
  321. return;
  322. }
  323. }
  324. else {
  325. int anchor = (*p == '^') ? (p++, 1) : 0;
  326. char *s1=s+init;
  327. cap.src_end = s+l;
  328. do {
  329. char *res;
  330. cap.level = 0;
  331. if ((res=match(s1, p, &cap)) != NULL) {
  332. lua_pushnumber(s1-s+1); /* start */
  333. lua_pushnumber(res-s); /* end */
  334. push_captures(&cap);
  335. return;
  336. }
  337. } while (s1++<cap.src_end && !anchor);
  338. }
  339. lua_pushnil(); /* if arrives here, it didn't find */
  340. }
  341. static void add_s (lua_Object newp, struct Capture *cap) {
  342. if (lua_isstring(newp)) {
  343. char *news = lua_getstring(newp);
  344. int l = lua_strlen(newp);
  345. int i;
  346. for (i=0; i<l; i++) {
  347. if (news[i] != ESC)
  348. luaL_addchar(news[i]);
  349. else {
  350. i++; /* skip ESC */
  351. if (!isdigit((unsigned char)news[i]))
  352. luaL_addchar(news[i]);
  353. else {
  354. int level = check_cap(news[i], cap);
  355. addnchar(cap->capture[level].init, cap->capture[level].len);
  356. }
  357. }
  358. }
  359. }
  360. else { /* is a function */
  361. lua_Object res;
  362. int status;
  363. int oldbuff;
  364. lua_beginblock();
  365. push_captures(cap);
  366. /* function may use buffer, so save it and create a new one */
  367. oldbuff = luaL_newbuffer(0);
  368. status = lua_callfunction(newp);
  369. /* restore old buffer */
  370. luaL_oldbuffer(oldbuff);
  371. if (status != 0) {
  372. lua_endblock();
  373. lua_error(NULL);
  374. }
  375. res = lua_getresult(1);
  376. if (lua_isstring(res))
  377. addnchar(lua_getstring(res), lua_strlen(res));
  378. lua_endblock();
  379. }
  380. }
  381. static void str_gsub (void) {
  382. long srcl;
  383. char *src = luaL_check_lstr(1, &srcl);
  384. char *p = luaL_check_string(2);
  385. lua_Object newp = lua_getparam(3);
  386. int max_s = luaL_opt_int(4, srcl+1);
  387. int anchor = (*p == '^') ? (p++, 1) : 0;
  388. int n = 0;
  389. struct Capture cap;
  390. luaL_arg_check(lua_isstring(newp) || lua_isfunction(newp), 3,
  391. "string or function expected");
  392. luaL_resetbuffer();
  393. cap.src_end = src+srcl;
  394. while (n < max_s) {
  395. char *e;
  396. cap.level = 0;
  397. e = match(src, p, &cap);
  398. if (e) {
  399. n++;
  400. add_s(newp, &cap);
  401. }
  402. if (e && e>src) /* non empty match? */
  403. src = e; /* skip it */
  404. else if (src < cap.src_end)
  405. luaL_addchar(*src++);
  406. else break;
  407. if (anchor) break;
  408. }
  409. addnchar(src, cap.src_end-src);
  410. closeandpush();
  411. lua_pushnumber(n); /* number of substitutions */
  412. }
  413. /* }====================================================== */
  414. static void luaI_addquoted (int arg) {
  415. long l;
  416. char *s = luaL_check_lstr(arg, &l);
  417. luaL_addchar('"');
  418. while (l--) {
  419. switch (*s) {
  420. case '"': case '\\': case '\n':
  421. luaL_addchar('\\');
  422. luaL_addchar(*s);
  423. break;
  424. case '\0': addnchar("\\000", 4); break;
  425. default: luaL_addchar(*s);
  426. }
  427. s++;
  428. }
  429. luaL_addchar('"');
  430. }
  431. /* maximum size of each format specification (such as '%-099.99d') */
  432. #define MAX_FORMAT 20 /* arbitrary limit */
  433. static void str_format (void) {
  434. int arg = 1;
  435. char *strfrmt = luaL_check_string(arg);
  436. luaL_resetbuffer();
  437. while (*strfrmt) {
  438. if (*strfrmt != '%')
  439. luaL_addchar(*strfrmt++);
  440. else if (*++strfrmt == '%')
  441. luaL_addchar(*strfrmt++); /* %% */
  442. else { /* format item */
  443. struct Capture cap;
  444. char form[MAX_FORMAT]; /* to store the format ('%...') */
  445. char *buff; /* to store the formatted item */
  446. char *initf = strfrmt;
  447. form[0] = '%';
  448. if (isdigit((unsigned char)*initf) && *(initf+1) == '$') {
  449. arg = *initf - '0';
  450. initf += 2; /* skip the 'n$' */
  451. }
  452. arg++;
  453. cap.src_end = strfrmt+strlen(strfrmt)+1;
  454. cap.level = 0;
  455. strfrmt = match(initf, "[-+ #0]*(%d*)%.?(%d*)", &cap);
  456. if (cap.capture[0].len > 2 || cap.capture[1].len > 2 || /* < 100? */
  457. strfrmt-initf > MAX_FORMAT-2)
  458. lua_error("invalid format (width or precision too long)");
  459. strncpy(form+1, initf, strfrmt-initf+1); /* +1 to include conversion */
  460. form[strfrmt-initf+2] = 0;
  461. buff = luaL_openspace(512); /* 512 > soid luaI_addquot99.99f', -1e308) */
  462. switch (*strfrmt++) {
  463. case 'c': case 'd': case 'i':
  464. sprintf(buff, form, luaL_check_int(arg));
  465. break;
  466. case 'o': case 'u': case 'x': case 'X':
  467. sprintf(buff, form, (unsigned int)luaL_check_number(arg));
  468. break;
  469. case 'e': case 'E': case 'f': case 'g': case 'G':
  470. sprintf(buff, form, luaL_check_number(arg));
  471. break;
  472. case 'q':
  473. luaI_addquoted(arg);
  474. continue; /* skip the "addsize" at the end */
  475. case 's': {
  476. long l;
  477. char *s = luaL_check_lstr(arg, &l);
  478. if (cap.capture[1].len == 0 && l >= 100) {
  479. /* no precision and string is too big to be formatted;
  480. keep original string */
  481. addnchar(s, l);
  482. continue; /* skip the "addsize" at the end */
  483. }
  484. else {
  485. sprintf(buff, form, s);
  486. break;
  487. }
  488. }
  489. default: /* also treat cases 'pnLlh' */
  490. lua_error("invalid option in `format'");
  491. }
  492. luaL_addsize(strlen(buff));
  493. }
  494. }
  495. closeandpush(); /* push the result */
  496. }
  497. static struct luaL_reg strlib[] = {
  498. {"strlen", str_len},
  499. {"strsub", str_sub},
  500. {"strlower", str_lower},
  501. {"strupper", str_upper},
  502. {"strchar", str_char},
  503. {"strrep", str_rep},
  504. {"ascii", str_byte}, /* for compatibility with 3.0 and earlier */
  505. {"strbyte", str_byte},
  506. {"format", str_format},
  507. {"strfind", str_find},
  508. {"gsub", str_gsub}
  509. };
  510. /*
  511. ** Open string library
  512. */
  513. void strlib_open (void)
  514. {
  515. luaL_openlib(strlib, (sizeof(strlib)/sizeof(strlib[0])));
  516. }