lstrlib.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  1. /*
  2. ** $Id: lstrlib.c,v 1.11 1998/03/09 18:28:08 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. {
  27. lua_pushlstring(luaL_buffer(), luaL_getsize());
  28. }
  29. static long posrelat (long pos, long len)
  30. {
  31. /* relative string position: negative means back from end */
  32. return (pos>=0) ? pos : len+pos+1;
  33. }
  34. static void str_sub (void)
  35. {
  36. long l;
  37. char *s = luaL_check_lstr(1, &l);
  38. long start = posrelat(luaL_check_number(2), l);
  39. long end = posrelat(luaL_opt_number(3, -1), l);
  40. if (1 <= start && start <= end && end <= l)
  41. lua_pushlstring(s+start-1, end-start+1);
  42. else lua_pushstring("");
  43. }
  44. static void str_lower (void)
  45. {
  46. long l;
  47. int i;
  48. char *s = luaL_check_lstr(1, &l);
  49. luaL_resetbuffer();
  50. for (i=0; i<l; i++)
  51. luaL_addchar(tolower((unsigned char)(s[i])));
  52. closeandpush();
  53. }
  54. static void str_upper (void)
  55. {
  56. long l;
  57. int i;
  58. char *s = luaL_check_lstr(1, &l);
  59. luaL_resetbuffer();
  60. for (i=0; i<l; i++)
  61. luaL_addchar(toupper((unsigned char)(s[i])));
  62. closeandpush();
  63. }
  64. static void str_rep (void)
  65. {
  66. long l;
  67. char *s = luaL_check_lstr(1, &l);
  68. int n = (int)luaL_check_number(2);
  69. luaL_resetbuffer();
  70. while (n-- > 0)
  71. addnchar(s, l);
  72. closeandpush();
  73. }
  74. static void str_ascii (void)
  75. {
  76. long l;
  77. char *s = luaL_check_lstr(1, &l);
  78. long pos = posrelat(luaL_opt_number(2, 1), l);
  79. luaL_arg_check(0<pos && pos<=l, 2, "out of range");
  80. lua_pushnumber((unsigned char)s[pos-1]);
  81. }
  82. static void str_int2str (void)
  83. {
  84. int i = 0;
  85. luaL_resetbuffer();
  86. while (lua_getparam(++i) != LUA_NOOBJECT)
  87. luaL_addchar((int)luaL_check_number(i));
  88. closeandpush();
  89. }
  90. /*
  91. ** =======================================================
  92. ** PATTERN MATCHING
  93. ** =======================================================
  94. */
  95. #define MAX_CAPT 9
  96. struct Capture {
  97. int level; /* total number of captures (finished or unfinished) */
  98. char *src_end; /* end ('\0') of source string */
  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. {
  108. int i;
  109. for (i=0; i<cap->level; i++)
  110. lua_pushlstring(cap->capture[i].init, cap->capture[i].len);
  111. }
  112. static int check_cap (int l, struct Capture *cap)
  113. {
  114. l -= '1';
  115. if (!(0 <= l && l < cap->level && cap->capture[l].len != -1))
  116. lua_error("invalid capture index");
  117. return l;
  118. }
  119. static int capture_to_close (struct Capture *cap)
  120. {
  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. static char *bracket_end (char *p)
  128. {
  129. return (*p == 0) ? NULL : strchr((*p=='^') ? p+2 : p+1, ']');
  130. }
  131. static int matchclass (int c, int cl)
  132. {
  133. int res;
  134. switch (tolower(cl)) {
  135. case 'a' : res = isalpha(c); break;
  136. case 'c' : res = iscntrl(c); break;
  137. case 'd' : res = isdigit(c); break;
  138. case 'l' : res = islower(c); break;
  139. case 'p' : res = ispunct(c); break;
  140. case 's' : res = isspace(c); break;
  141. case 'u' : res = isupper(c); break;
  142. case 'w' : res = isalnum(c); break;
  143. case 'z' : res = (c == '\0'); break;
  144. default: return (cl == c);
  145. }
  146. return (islower((unsigned char)cl) ? res : !res);
  147. }
  148. int luaI_singlematch (int c, char *p, char **ep)
  149. {
  150. switch (*p) {
  151. case '.': /* matches any char */
  152. *ep = p+1;
  153. return 1;
  154. case '\0': /* end of pattern; matches nothing */
  155. *ep = p;
  156. return 0;
  157. case ESC:
  158. if (*(++p) == '\0')
  159. luaL_verror("incorrect pattern (ends with `%c')", ESC);
  160. *ep = p+1;
  161. return matchclass(c, (unsigned char)*p);
  162. case '[': {
  163. char *end = bracket_end(p+1);
  164. int sig = *(p+1) == '^' ? (p++, 0) : 1;
  165. if (end == NULL) lua_error("incorrect pattern (missing `]')");
  166. *ep = end+1;
  167. while (++p < end) {
  168. if (*p == ESC) {
  169. if (((p+1) < end) && matchclass(c, (unsigned char)*++p))
  170. return sig;
  171. }
  172. else if ((*(p+1) == '-') && (p+2 < end)) {
  173. p+=2;
  174. if ((unsigned char)*(p-2) <= c && c <= (unsigned char)*p)
  175. return sig;
  176. }
  177. else if ((unsigned char)*p == c) return sig;
  178. }
  179. return !sig;
  180. }
  181. default:
  182. *ep = p+1;
  183. return ((unsigned char)*p == c);
  184. }
  185. }
  186. static char *matchbalance (char *s, int b, int e, struct Capture *cap)
  187. {
  188. if (*s != b) return NULL;
  189. else {
  190. int cont = 1;
  191. while (++s < cap->src_end) {
  192. if (*s == e) {
  193. if (--cont == 0) return s+1;
  194. }
  195. else if (*s == b) cont++;
  196. }
  197. }
  198. return NULL; /* string ends out of balance */
  199. }
  200. static char *matchitem (char *s, char *p, struct Capture *cap, char **ep)
  201. {
  202. if (*p == ESC) {
  203. p++;
  204. if (isdigit((unsigned char)*p)) { /* capture */
  205. int l = check_cap(*p, cap);
  206. int len = cap->capture[l].len;
  207. *ep = p+1;
  208. if (cap->src_end-s >= len && memcmp(cap->capture[l].init, s, len) == 0)
  209. return s+len;
  210. else return NULL;
  211. }
  212. else if (*p == 'b') { /* balanced string */
  213. p++;
  214. if (*p == 0 || *(p+1) == 0)
  215. lua_error("unbalanced pattern");
  216. *ep = p+2;
  217. return matchbalance(s, *p, *(p+1), cap);
  218. }
  219. else p--; /* and go through */
  220. }
  221. /* "luaI_singlematch" sets "ep" (so must be called even when *s == 0) */
  222. return (luaI_singlematch((unsigned char)*s, p, ep) && s<cap->src_end) ?
  223. s+1 : NULL;
  224. }
  225. static char *match (char *s, char *p, struct Capture *cap)
  226. {
  227. init: /* using goto's to optimize tail recursion */
  228. switch (*p) {
  229. case '(': { /* start capture */
  230. char *res;
  231. if (cap->level >= MAX_CAPT) lua_error("too many captures");
  232. cap->capture[cap->level].init = s;
  233. cap->capture[cap->level].len = -1;
  234. cap->level++;
  235. if ((res=match(s, p+1, cap)) == NULL) /* match failed? */
  236. cap->level--; /* undo capture */
  237. return res;
  238. }
  239. case ')': { /* end capture */
  240. int l = capture_to_close(cap);
  241. char *res;
  242. cap->capture[l].len = s - cap->capture[l].init; /* close capture */
  243. if ((res = match(s, p+1, cap)) == NULL) /* match failed? */
  244. cap->capture[l].len = -1; /* undo capture */
  245. return res;
  246. }
  247. case '\0': case '$': /* (possibly) end of pattern */
  248. if (*p == 0 || (*(p+1) == 0 && s == cap->src_end))
  249. return s;
  250. /* else go through */
  251. default: { /* it is a pattern item */
  252. char *ep; /* get what is next */
  253. char *s1 = matchitem(s, p, cap, &ep);
  254. switch (*ep) {
  255. case '*': { /* repetition */
  256. char *res;
  257. if (s1 && s1>s && (res = match(s1, p, cap)))
  258. return res;
  259. p=ep+1; goto init; /* else return match(s, ep+1, cap); */
  260. }
  261. case '?': { /* optional */
  262. char *res;
  263. if (s1 && (res = match(s1, ep+1, cap)))
  264. return res;
  265. p=ep+1; goto init; /* else return match(s, ep+1, cap); */
  266. }
  267. case '-': { /* repetition */
  268. char *res;
  269. if ((res = match(s, ep+1, cap)) != 0)
  270. return res;
  271. else if (s1 && s1>s) {
  272. s = s1;
  273. goto init; /* return match(s1, p, cap); */
  274. }
  275. else
  276. return NULL;
  277. }
  278. default:
  279. if (s1) { s=s1; p=ep; goto init; } /* return match(s1, ep, cap); */
  280. else return NULL;
  281. }
  282. }
  283. }
  284. }
  285. static void str_find (void)
  286. {
  287. long l;
  288. char *s = luaL_check_lstr(1, &l);
  289. char *p = luaL_check_string(2);
  290. long init = posrelat(luaL_opt_number(3, 1), l) - 1;
  291. struct Capture cap;
  292. luaL_arg_check(0 <= init && init <= l, 3, "out of range");
  293. if (lua_getparam(4) != LUA_NOOBJECT ||
  294. strpbrk(p, SPECIALS) == NULL) { /* no special caracters? */
  295. char *s2 = strstr(s+init, p);
  296. if (s2) {
  297. lua_pushnumber(s2-s+1);
  298. lua_pushnumber(s2-s+strlen(p));
  299. }
  300. }
  301. else {
  302. int anchor = (*p == '^') ? (p++, 1) : 0;
  303. char *s1=s+init;
  304. cap.src_end = s+l;
  305. do {
  306. char *res;
  307. cap.level = 0;
  308. if ((res=match(s1, p, &cap)) != NULL) {
  309. lua_pushnumber(s1-s+1); /* start */
  310. lua_pushnumber(res-s); /* end */
  311. push_captures(&cap);
  312. return;
  313. }
  314. } while (s1++<cap.src_end && !anchor);
  315. }
  316. }
  317. static void add_s (lua_Object newp, struct Capture *cap)
  318. {
  319. if (lua_isstring(newp)) {
  320. char *news = lua_getstring(newp);
  321. int l = lua_strlen(newp);
  322. int i;
  323. for (i=0; i<l; i++) {
  324. if (news[i] != ESC)
  325. luaL_addchar(news[i]);
  326. else {
  327. i++; /* skip ESC */
  328. if (!isdigit((unsigned char)news[i]))
  329. luaL_addchar(news[i]);
  330. else {
  331. int level = check_cap(news[i], cap);
  332. addnchar(cap->capture[level].init, cap->capture[level].len);
  333. }
  334. }
  335. }
  336. }
  337. else { /* is a function */
  338. lua_Object res;
  339. int status;
  340. int oldbuff;
  341. lua_beginblock();
  342. push_captures(cap);
  343. /* function may use buffer, so save it and create a new one */
  344. oldbuff = luaL_newbuffer(0);
  345. status = lua_callfunction(newp);
  346. /* restore old buffer */
  347. luaL_oldbuffer(oldbuff);
  348. if (status != 0) {
  349. lua_endblock();
  350. lua_error(NULL);
  351. }
  352. res = lua_getresult(1);
  353. if (lua_isstring(res))
  354. addnchar(lua_getstring(res), lua_strlen(res));
  355. lua_endblock();
  356. }
  357. }
  358. static void str_gsub (void)
  359. {
  360. long srcl;
  361. char *src = luaL_check_lstr(1, &srcl);
  362. char *p = luaL_check_string(2);
  363. lua_Object newp = lua_getparam(3);
  364. int max_s = (int)luaL_opt_number(4, srcl+1);
  365. int anchor = (*p == '^') ? (p++, 1) : 0;
  366. int n = 0;
  367. struct Capture cap;
  368. luaL_arg_check(lua_isstring(newp) || lua_isfunction(newp), 3,
  369. "string or function expected");
  370. luaL_resetbuffer();
  371. cap.src_end = src+srcl;
  372. while (n < max_s) {
  373. char *e;
  374. cap.level = 0;
  375. e = match(src, p, &cap);
  376. if (e) {
  377. n++;
  378. add_s(newp, &cap);
  379. }
  380. if (e && e>src) /* non empty match? */
  381. src = e; /* skip it */
  382. else if (src < cap.src_end)
  383. luaL_addchar(*src++);
  384. else break;
  385. if (anchor) break;
  386. }
  387. addnchar(src, cap.src_end-src);
  388. closeandpush();
  389. lua_pushnumber(n); /* number of substitutions */
  390. }
  391. static void luaI_addquoted (char *s)
  392. {
  393. luaL_addchar('"');
  394. for (; *s; s++) {
  395. if (strchr("\"\\\n", *s))
  396. luaL_addchar('\\');
  397. luaL_addchar(*s);
  398. }
  399. luaL_addchar('"');
  400. }
  401. #define MAX_FORMAT 200
  402. static void str_format (void)
  403. {
  404. int arg = 1;
  405. char *strfrmt = luaL_check_string(arg);
  406. struct Capture cap;
  407. cap.src_end = strfrmt+strlen(strfrmt)+1;
  408. luaL_resetbuffer();
  409. while (*strfrmt) {
  410. if (*strfrmt != '%')
  411. luaL_addchar(*strfrmt++);
  412. else if (*++strfrmt == '%')
  413. luaL_addchar(*strfrmt++); /* %% */
  414. else { /* format item */
  415. char form[MAX_FORMAT]; /* store the format ('%...') */
  416. char *buff;
  417. char *initf = strfrmt;
  418. form[0] = '%';
  419. cap.level = 0;
  420. if (isdigit((unsigned char)initf[0]) && initf[1] == '$') {
  421. arg = initf[0] - '0';
  422. initf += 2; /* skip the 'n$' */
  423. }
  424. arg++;
  425. strfrmt = match(initf, "[-+ #0]*(%d*)%.?(%d*)", &cap);
  426. if (cap.capture[0].len > 2 || cap.capture[1].len > 2) /* < 100? */
  427. lua_error("invalid format (width or precision too long)");
  428. strncpy(form+1, initf, strfrmt-initf+1); /* +1 to include convertion */
  429. form[strfrmt-initf+2] = 0;
  430. buff = luaL_openspace(1000); /* to store the formatted value */
  431. switch (*strfrmt++) {
  432. case 'q':
  433. luaI_addquoted(luaL_check_string(arg));
  434. continue;
  435. case 's': {
  436. char *s = luaL_check_string(arg);
  437. buff = luaL_openspace(strlen(s));
  438. sprintf(buff, form, s);
  439. break;
  440. }
  441. case 'c': case 'd': case 'i': case 'o':
  442. case 'u': case 'x': case 'X':
  443. sprintf(buff, form, (int)luaL_check_number(arg));
  444. break;
  445. case 'e': case 'E': case 'f': case 'g': case 'G':
  446. sprintf(buff, form, luaL_check_number(arg));
  447. break;
  448. default: /* also treat cases 'pnLlh' */
  449. lua_error("invalid option in `format'");
  450. }
  451. luaL_addsize(strlen(buff));
  452. }
  453. }
  454. closeandpush(); /* push the result */
  455. }
  456. static struct luaL_reg strlib[] = {
  457. {"strlen", str_len},
  458. {"strsub", str_sub},
  459. {"strlower", str_lower},
  460. {"strupper", str_upper},
  461. {"int2str", str_int2str},
  462. {"strrep", str_rep},
  463. {"ascii", str_ascii},
  464. {"format", str_format},
  465. {"strfind", str_find},
  466. {"gsub", str_gsub}
  467. };
  468. /*
  469. ** Open string library
  470. */
  471. void strlib_open (void)
  472. {
  473. luaL_openlib(strlib, (sizeof(strlib)/sizeof(strlib[0])));
  474. }