lstrlib.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  1. /*
  2. ** $Id: lstrlib.c,v 1.29 1999/04/30 14:12:05 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. #define MAX_CAPT 9
  94. struct Capture {
  95. char *src_end; /* end ('\0') of source string */
  96. int level; /* total number of captures (finished or unfinished) */
  97. struct {
  98. char *init;
  99. int len; /* -1 signals unfinished capture */
  100. } capture[MAX_CAPT];
  101. };
  102. #define ESC '%'
  103. #define SPECIALS "^$*+?.([%-"
  104. static void push_captures (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("unfinished capture");
  109. lua_pushlstring(cap->capture[i].init, l);
  110. }
  111. }
  112. static int check_cap (int l, struct Capture *cap) {
  113. l -= '1';
  114. if (!(0 <= l && l < cap->level && cap->capture[l].len != -1))
  115. lua_error("invalid capture index");
  116. return l;
  117. }
  118. static int capture_to_close (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("invalid pattern capture");
  123. return 0; /* to avoid warnings */
  124. }
  125. char *luaI_classend (char *p) {
  126. switch (*p++) {
  127. case ESC:
  128. if (*p == '\0')
  129. luaL_verror("incorrect pattern (ends with `%c')", ESC);
  130. return p+1;
  131. case '[':
  132. if (*p == '^') p++;
  133. if (*p == ']') p++;
  134. p = strchr(p, ']');
  135. if (!p) lua_error("incorrect pattern (missing `]')");
  136. return p+1;
  137. default:
  138. return p;
  139. }
  140. }
  141. static int matchclass (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, char *p, char *end) {
  159. int sig = 1;
  160. if (*(p+1) == '^') {
  161. sig = 0;
  162. p++; /* skip the '^' */
  163. }
  164. while (++p < end) {
  165. if (*p == ESC) {
  166. p++;
  167. if ((p < end) && matchclass(c, (unsigned char)*p))
  168. return sig;
  169. }
  170. else if ((*(p+1) == '-') && (p+2 < end)) {
  171. p+=2;
  172. if ((int)(unsigned char)*(p-2) <= c && c <= (int)(unsigned char)*p)
  173. return sig;
  174. }
  175. else if ((unsigned char)*p == c) return sig;
  176. }
  177. return !sig;
  178. }
  179. int luaI_singlematch (int c, char *p, char *ep) {
  180. switch (*p) {
  181. case '.': /* matches any char */
  182. return 1;
  183. case ESC:
  184. return matchclass(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 char *match (char *s, char *p, struct Capture *cap);
  192. static char *matchbalance (char *s, char *p, struct Capture *cap) {
  193. if (*p == 0 || *(p+1) == 0)
  194. lua_error("unbalanced pattern");
  195. if (*s != *p) return NULL;
  196. else {
  197. int b = *p;
  198. int e = *(p+1);
  199. int cont = 1;
  200. while (++s < cap->src_end) {
  201. if (*s == e) {
  202. if (--cont == 0) return s+1;
  203. }
  204. else if (*s == b) cont++;
  205. }
  206. }
  207. return NULL; /* string ends out of balance */
  208. }
  209. static char *max_expand (char *s, char *p, char *ep, struct Capture *cap) {
  210. int i = 0; /* counts maximum expand for item */
  211. while ((s+i)<cap->src_end && luaI_singlematch((unsigned char)*(s+i), p, ep))
  212. i++;
  213. /* keeps trying to match mith the maximum repetitions */
  214. while (i>=0) {
  215. char *res = match((s+i), ep+1, cap);
  216. if (res) return res;
  217. i--; /* else didn't match; reduce 1 repetition to try again */
  218. }
  219. return NULL;
  220. }
  221. static char *min_expand (char *s, char *p, char *ep, struct Capture *cap) {
  222. for (;;) {
  223. char *res = match(s, ep+1, cap);
  224. if (res != NULL)
  225. return res;
  226. else if (s<cap->src_end && luaI_singlematch((unsigned char)*s, p, ep))
  227. s++; /* try with one more repetition */
  228. else return NULL;
  229. }
  230. }
  231. static char *start_capt (char *s, char *p, struct Capture *cap) {
  232. char *res;
  233. int level = cap->level;
  234. if (level >= MAX_CAPT) lua_error("too many captures");
  235. cap->capture[level].init = s;
  236. cap->capture[level].len = -1;
  237. cap->level = level+1;
  238. if ((res=match(s, p+1, cap)) == NULL) /* match failed? */
  239. cap->level--; /* undo capture */
  240. return res;
  241. }
  242. static char *end_capt (char *s, char *p, struct Capture *cap) {
  243. int l = capture_to_close(cap);
  244. char *res;
  245. cap->capture[l].len = s - cap->capture[l].init; /* close capture */
  246. if ((res = match(s, p+1, cap)) == NULL) /* match failed? */
  247. cap->capture[l].len = -1; /* undo capture */
  248. return res;
  249. }
  250. static char *match_capture (char *s, int level, struct Capture *cap) {
  251. int l = check_cap(level, cap);
  252. int len = cap->capture[l].len;
  253. if (cap->src_end-s >= len &&
  254. memcmp(cap->capture[l].init, s, len) == 0)
  255. return s+len;
  256. else return NULL;
  257. }
  258. static char *match (char *s, char *p, struct Capture *cap) {
  259. init: /* using goto's to optimize tail recursion */
  260. switch (*p) {
  261. case '(': /* start capture */
  262. return start_capt(s, p, cap);
  263. case ')': /* end capture */
  264. return end_capt(s, p, cap);
  265. case ESC: /* may be %[0-9] or %b */
  266. if (isdigit((unsigned char)(*(p+1)))) { /* capture? */
  267. s = match_capture(s, *(p+1), cap);
  268. if (s == NULL) return NULL;
  269. p+=2; goto init; /* else return match(p+2, s, cap) */
  270. }
  271. else if (*(p+1) == 'b') { /* balanced string? */
  272. s = matchbalance(s, p+2, cap);
  273. if (s == NULL) return NULL;
  274. p+=4; goto init; /* else return match(p+4, s, cap); */
  275. }
  276. else goto dflt; /* case default */
  277. case '\0': /* end of pattern */
  278. return s; /* match succeeded */
  279. case '$':
  280. if (*(p+1) == '\0') /* is the '$' the last char in pattern? */
  281. return (s == cap->src_end) ? s : NULL; /* check end of string */
  282. else goto dflt;
  283. default: dflt: { /* it is a pattern item */
  284. char *ep = luaI_classend(p); /* points to what is next */
  285. int m = s<cap->src_end && luaI_singlematch((unsigned char)*s, p, ep);
  286. switch (*ep) {
  287. case '?': { /* optional */
  288. char *res;
  289. if (m && ((res=match(s+1, ep+1, cap)) != NULL))
  290. return res;
  291. p=ep+1; goto init; /* else return match(s, ep+1, cap); */
  292. }
  293. case '*': /* 0 or more repetitions */
  294. return max_expand(s, p, ep, cap);
  295. case '+': /* 1 or more repetitions */
  296. return (m ? max_expand(s+1, p, ep, cap) : NULL);
  297. case '-': /* 0 or more repetitions (minimum) */
  298. return min_expand(s, p, ep, cap);
  299. default:
  300. if (!m) return NULL;
  301. s++; p=ep; goto init; /* else return match(s+1, ep, cap); */
  302. }
  303. }
  304. }
  305. }
  306. static void str_find (void) {
  307. long l;
  308. char *s = luaL_check_lstr(1, &l);
  309. char *p = luaL_check_string(2);
  310. long init = posrelat(luaL_opt_long(3, 1), l) - 1;
  311. struct Capture cap;
  312. luaL_arg_check(0 <= init && init <= l, 3, "out of range");
  313. if (lua_getparam(4) != LUA_NOOBJECT ||
  314. strpbrk(p, SPECIALS) == NULL) { /* no special characters? */
  315. char *s2 = strstr(s+init, p);
  316. if (s2) {
  317. lua_pushnumber(s2-s+1);
  318. lua_pushnumber(s2-s+strlen(p));
  319. return;
  320. }
  321. }
  322. else {
  323. int anchor = (*p == '^') ? (p++, 1) : 0;
  324. char *s1=s+init;
  325. cap.src_end = s+l;
  326. do {
  327. char *res;
  328. cap.level = 0;
  329. if ((res=match(s1, p, &cap)) != NULL) {
  330. lua_pushnumber(s1-s+1); /* start */
  331. lua_pushnumber(res-s); /* end */
  332. push_captures(&cap);
  333. return;
  334. }
  335. } while (s1++<cap.src_end && !anchor);
  336. }
  337. lua_pushnil(); /* if arrives here, it didn't find */
  338. }
  339. static void add_s (lua_Object newp, struct Capture *cap) {
  340. if (lua_isstring(newp)) {
  341. char *news = lua_getstring(newp);
  342. int l = lua_strlen(newp);
  343. int i;
  344. for (i=0; i<l; i++) {
  345. if (news[i] != ESC)
  346. luaL_addchar(news[i]);
  347. else {
  348. i++; /* skip ESC */
  349. if (!isdigit((unsigned char)news[i]))
  350. luaL_addchar(news[i]);
  351. else {
  352. int level = check_cap(news[i], cap);
  353. addnchar(cap->capture[level].init, cap->capture[level].len);
  354. }
  355. }
  356. }
  357. }
  358. else { /* is a function */
  359. lua_Object res;
  360. int status;
  361. int oldbuff;
  362. lua_beginblock();
  363. push_captures(cap);
  364. /* function may use buffer, so save it and create a new one */
  365. oldbuff = luaL_newbuffer(0);
  366. status = lua_callfunction(newp);
  367. /* restore old buffer */
  368. luaL_oldbuffer(oldbuff);
  369. if (status != 0) {
  370. lua_endblock();
  371. lua_error(NULL);
  372. }
  373. res = lua_getresult(1);
  374. if (lua_isstring(res))
  375. addnchar(lua_getstring(res), lua_strlen(res));
  376. lua_endblock();
  377. }
  378. }
  379. static void str_gsub (void) {
  380. long srcl;
  381. char *src = luaL_check_lstr(1, &srcl);
  382. char *p = luaL_check_string(2);
  383. lua_Object newp = lua_getparam(3);
  384. int max_s = luaL_opt_int(4, srcl+1);
  385. int anchor = (*p == '^') ? (p++, 1) : 0;
  386. int n = 0;
  387. struct Capture cap;
  388. luaL_arg_check(lua_isstring(newp) || lua_isfunction(newp), 3,
  389. "string or function expected");
  390. luaL_resetbuffer();
  391. cap.src_end = src+srcl;
  392. while (n < max_s) {
  393. char *e;
  394. cap.level = 0;
  395. e = match(src, p, &cap);
  396. if (e) {
  397. n++;
  398. add_s(newp, &cap);
  399. }
  400. if (e && e>src) /* non empty match? */
  401. src = e; /* skip it */
  402. else if (src < cap.src_end)
  403. luaL_addchar(*src++);
  404. else break;
  405. if (anchor) break;
  406. }
  407. addnchar(src, cap.src_end-src);
  408. closeandpush();
  409. lua_pushnumber(n); /* number of substitutions */
  410. }
  411. /* }====================================================== */
  412. static void luaI_addquoted (int arg) {
  413. long l;
  414. char *s = luaL_check_lstr(arg, &l);
  415. luaL_addchar('"');
  416. while (l--) {
  417. switch (*s) {
  418. case '"': case '\\': case '\n':
  419. luaL_addchar('\\');
  420. luaL_addchar(*s);
  421. break;
  422. case '\0': addnchar("\\000", 4); break;
  423. default: luaL_addchar(*s);
  424. }
  425. s++;
  426. }
  427. luaL_addchar('"');
  428. }
  429. /* maximum size of each format specification (such as '%-099.99d') */
  430. #define MAX_FORMAT 20
  431. static void str_format (void) {
  432. int arg = 1;
  433. char *strfrmt = luaL_check_string(arg);
  434. luaL_resetbuffer();
  435. while (*strfrmt) {
  436. if (*strfrmt != '%')
  437. luaL_addchar(*strfrmt++);
  438. else if (*++strfrmt == '%')
  439. luaL_addchar(*strfrmt++); /* %% */
  440. else { /* format item */
  441. struct Capture cap;
  442. char form[MAX_FORMAT]; /* to store the format ('%...') */
  443. char *buff; /* to store the formatted item */
  444. char *initf = strfrmt;
  445. form[0] = '%';
  446. if (isdigit((unsigned char)*initf) && *(initf+1) == '$') {
  447. arg = *initf - '0';
  448. initf += 2; /* skip the 'n$' */
  449. }
  450. arg++;
  451. cap.src_end = strfrmt+strlen(strfrmt)+1;
  452. cap.level = 0;
  453. strfrmt = match(initf, "[-+ #0]*(%d*)%.?(%d*)", &cap);
  454. if (cap.capture[0].len > 2 || cap.capture[1].len > 2 || /* < 100? */
  455. strfrmt-initf > MAX_FORMAT-2)
  456. lua_error("invalid format (width or precision too long)");
  457. strncpy(form+1, initf, strfrmt-initf+1); /* +1 to include conversion */
  458. form[strfrmt-initf+2] = 0;
  459. buff = luaL_openspace(512); /* 512 > soid luaI_addquot99.99f', -1e308) */
  460. switch (*strfrmt++) {
  461. case 'c': case 'd': case 'i':
  462. sprintf(buff, form, luaL_check_int(arg));
  463. break;
  464. case 'o': case 'u': case 'x': case 'X':
  465. sprintf(buff, form, (unsigned int)luaL_check_number(arg));
  466. break;
  467. case 'e': case 'E': case 'f': case 'g': case 'G':
  468. sprintf(buff, form, luaL_check_number(arg));
  469. break;
  470. case 'q':
  471. luaI_addquoted(arg);
  472. continue; /* skip the "addsize" at the end */
  473. case 's': {
  474. long l;
  475. char *s = luaL_check_lstr(arg, &l);
  476. if (cap.capture[1].len == 0 && l >= 100) {
  477. /* no precision and string is too big to be formatted;
  478. keep original string */
  479. addnchar(s, l);
  480. continue; /* skip the "addsize" at the end */
  481. }
  482. else {
  483. sprintf(buff, form, s);
  484. break;
  485. }
  486. }
  487. default: /* also treat cases 'pnLlh' */
  488. lua_error("invalid option in `format'");
  489. }
  490. luaL_addsize(strlen(buff));
  491. }
  492. }
  493. closeandpush(); /* push the result */
  494. }
  495. static struct luaL_reg strlib[] = {
  496. {"strlen", str_len},
  497. {"strsub", str_sub},
  498. {"strlower", str_lower},
  499. {"strupper", str_upper},
  500. {"strchar", str_char},
  501. {"strrep", str_rep},
  502. {"ascii", str_byte}, /* for compatibility with 3.0 and earlier */
  503. {"strbyte", str_byte},
  504. {"format", str_format},
  505. {"strfind", str_find},
  506. {"gsub", str_gsub}
  507. };
  508. /*
  509. ** Open string library
  510. */
  511. void strlib_open (void)
  512. {
  513. luaL_openlib(strlib, (sizeof(strlib)/sizeof(strlib[0])));
  514. }