strlib.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  1. /*
  2. ** strlib.c
  3. ** String library to LUA
  4. */
  5. char *rcs_strlib="$Id: strlib.c,v 1.45 1997/06/19 17:45:28 roberto Exp roberto $";
  6. #include <string.h>
  7. #include <stdio.h>
  8. #include <stdlib.h>
  9. #include <ctype.h>
  10. #include "lua.h"
  11. #include "auxlib.h"
  12. #include "lualib.h"
  13. struct lbuff {
  14. char *b;
  15. size_t max;
  16. size_t size;
  17. };
  18. static struct lbuff lbuffer = {NULL, 0, 0};
  19. static char *strbuffer (unsigned long size)
  20. {
  21. if (size > lbuffer.max) {
  22. /* ANSI "realloc" doesn't need this test, but some machines (Sun!)
  23. don't follow ANSI */
  24. lbuffer.b = (lbuffer.b) ? realloc(lbuffer.b, lbuffer.max=size) :
  25. malloc(lbuffer.max=size);
  26. if (lbuffer.b == NULL)
  27. lua_error("memory overflow");
  28. }
  29. return lbuffer.b;
  30. }
  31. static char *openspace (unsigned long size)
  32. {
  33. char *buff = strbuffer(lbuffer.size+size);
  34. return buff+lbuffer.size;
  35. }
  36. char *luaI_addchar (int c)
  37. {
  38. if (lbuffer.size >= lbuffer.max)
  39. strbuffer(lbuffer.max == 0 ? 100 : lbuffer.max*2);
  40. lbuffer.b[lbuffer.size++] = c;
  41. return lbuffer.b;
  42. }
  43. void luaI_emptybuff (void)
  44. {
  45. lbuffer.size = 0; /* prepare for next string */
  46. }
  47. static void addnchar (char *s, int n)
  48. {
  49. char *b = openspace(n);
  50. strncpy(b, s, n);
  51. lbuffer.size += n;
  52. }
  53. static void addstr (char *s)
  54. {
  55. addnchar(s, strlen(s));
  56. }
  57. /*
  58. ** Return the string length
  59. */
  60. static void str_len (void)
  61. {
  62. lua_pushnumber(strlen(luaL_check_string(1)));
  63. }
  64. /*
  65. ** Return the substring of a string
  66. */
  67. static void str_sub (void)
  68. {
  69. char *s = luaL_check_string(1);
  70. long l = strlen(s);
  71. long start = (long)luaL_check_number(2);
  72. long end = (long)luaL_opt_number(3, -1);
  73. if (start < 0) start = l+start+1;
  74. if (end < 0) end = l+end+1;
  75. if (1 <= start && start <= end && end <= l) {
  76. luaI_emptybuff();
  77. addnchar(s+start-1, end-start+1);
  78. lua_pushstring(luaI_addchar(0));
  79. }
  80. else lua_pushstring("");
  81. }
  82. /*
  83. ** Convert a string to lower case.
  84. */
  85. static void str_lower (void)
  86. {
  87. char *s;
  88. luaI_emptybuff();
  89. for (s = luaL_check_string(1); *s; s++)
  90. luaI_addchar(tolower((unsigned char)*s));
  91. lua_pushstring(luaI_addchar(0));
  92. }
  93. /*
  94. ** Convert a string to upper case.
  95. */
  96. static void str_upper (void)
  97. {
  98. char *s;
  99. luaI_emptybuff();
  100. for (s = luaL_check_string(1); *s; s++)
  101. luaI_addchar(toupper((unsigned char)*s));
  102. lua_pushstring(luaI_addchar(0));
  103. }
  104. static void str_rep (void)
  105. {
  106. char *s = luaL_check_string(1);
  107. int n = (int)luaL_check_number(2);
  108. luaI_emptybuff();
  109. while (n-- > 0)
  110. addstr(s);
  111. lua_pushstring(luaI_addchar(0));
  112. }
  113. /*
  114. ** get ascii value of a character in a string
  115. */
  116. static void str_ascii (void)
  117. {
  118. char *s = luaL_check_string(1);
  119. long pos = (long)luaL_opt_number(2, 1) - 1;
  120. luaL_arg_check(0<=pos && pos<strlen(s), 2, "out of range");
  121. lua_pushnumber((unsigned char)s[pos]);
  122. }
  123. /* pattern matching */
  124. #define ESC '%'
  125. #define SPECIALS "^$*?.([%-"
  126. static char *bracket_end (char *p)
  127. {
  128. return (*p == 0) ? NULL : strchr((*p=='^') ? p+2 : p+1, ']');
  129. }
  130. char *luaL_item_end (char *p)
  131. {
  132. switch (*p++) {
  133. case '\0': return p-1;
  134. case ESC:
  135. if (*p == 0) luaL_verror("incorrect pattern (ends with `%c')", ESC);
  136. return p+1;
  137. case '[': {
  138. char *end = bracket_end(p);
  139. if (end == NULL) lua_error("incorrect pattern (missing `]')");
  140. return end+1;
  141. }
  142. default:
  143. return p;
  144. }
  145. }
  146. static int matchclass (int c, int cl)
  147. {
  148. int res;
  149. switch (tolower((unsigned char)cl)) {
  150. case 'a' : res = isalpha((unsigned char)c); break;
  151. case 'c' : res = iscntrl((unsigned char)c); break;
  152. case 'd' : res = isdigit((unsigned char)c); break;
  153. case 'l' : res = islower((unsigned char)c); break;
  154. case 'p' : res = ispunct((unsigned char)c); break;
  155. case 's' : res = isspace((unsigned char)c); break;
  156. case 'u' : res = isupper((unsigned char)c); break;
  157. case 'w' : res = isalnum((unsigned char)c); break;
  158. default: return (cl == c);
  159. }
  160. return (islower((unsigned char)cl) ? res : !res);
  161. }
  162. int luaL_singlematch (int c, char *p)
  163. {
  164. if (c == 0) return 0;
  165. switch (*p) {
  166. case '.': return 1;
  167. case ESC: return matchclass(c, *(p+1));
  168. case '[': {
  169. char *end = bracket_end(p+1);
  170. int sig = *(p+1) == '^' ? (p++, 0) : 1;
  171. while (++p < end) {
  172. if (*p == ESC) {
  173. if (((p+1) < end) && matchclass(c, *++p)) return sig;
  174. }
  175. else if ((*(p+1) == '-') && (p+2 < end)) {
  176. p+=2;
  177. if (*(p-2) <= c && c <= *p) return sig;
  178. }
  179. else if (*p == c) return sig;
  180. }
  181. return !sig;
  182. }
  183. default: return (*p == c);
  184. }
  185. }
  186. #define MAX_CAPT 9
  187. static struct {
  188. char *init;
  189. int len; /* -1 signals unfinished capture */
  190. } capture[MAX_CAPT];
  191. static int num_captures; /* only valid after a sucessful call to match */
  192. static void push_captures (void)
  193. {
  194. int i;
  195. for (i=0; i<num_captures; i++) {
  196. int l = capture[i].len;
  197. char *buff = openspace(l+1);
  198. if (l == -1) lua_error("unfinished capture");
  199. strncpy(buff, capture[i].init, l);
  200. buff[l] = 0;
  201. lua_pushstring(buff);
  202. }
  203. }
  204. static int check_cap (int l, int level)
  205. {
  206. l -= '1';
  207. if (!(0 <= l && l < level && capture[l].len != -1))
  208. lua_error("invalid capture index");
  209. return l;
  210. }
  211. static int capture_to_close (int level)
  212. {
  213. for (level--; level>=0; level--)
  214. if (capture[level].len == -1) return level;
  215. lua_error("invalid pattern capture");
  216. return 0; /* to avoid warnings */
  217. }
  218. static char *matchbalance (char *s, int b, int e)
  219. {
  220. if (*s != b) return NULL;
  221. else {
  222. int cont = 1;
  223. while (*(++s)) {
  224. if (*s == e) {
  225. if (--cont == 0) return s+1;
  226. }
  227. else if (*s == b) cont++;
  228. }
  229. }
  230. return NULL; /* string ends out of balance */
  231. }
  232. static char *match (char *s, char *p, int level)
  233. {
  234. init: /* using goto's to optimize tail recursion */
  235. switch (*p) {
  236. case '(': /* start capture */
  237. if (level >= MAX_CAPT) lua_error("too many captures");
  238. capture[level].init = s;
  239. capture[level].len = -1;
  240. level++; p++; goto init; /* return match(s, p+1, level); */
  241. case ')': { /* end capture */
  242. int l = capture_to_close(level);
  243. char *res;
  244. capture[l].len = s - capture[l].init; /* close capture */
  245. if ((res = match(s, p+1, level)) == NULL) /* match failed? */
  246. capture[l].len = -1; /* undo capture */
  247. return res;
  248. }
  249. case ESC:
  250. if (isdigit((unsigned char)(*(p+1)))) { /* capture */
  251. int l = check_cap(*(p+1), level);
  252. if (strncmp(capture[l].init, s, capture[l].len) == 0) {
  253. /* return match(p+2, s+capture[l].len, level); */
  254. p+=2; s+=capture[l].len; goto init;
  255. }
  256. else return NULL;
  257. }
  258. else if (*(p+1) == 'b') { /* balanced string */
  259. if (*(p+2) == 0 || *(p+3) == 0)
  260. lua_error("bad balanced pattern specification");
  261. s = matchbalance(s, *(p+2), *(p+3));
  262. if (s == NULL) return NULL;
  263. else { /* return match(p+4, s, level); */
  264. p+=4; goto init;
  265. }
  266. }
  267. else goto dflt;
  268. case '\0': case '$': /* (possibly) end of pattern */
  269. if (*p == 0 || (*(p+1) == 0 && *s == 0)) {
  270. num_captures = level;
  271. return s;
  272. }
  273. else goto dflt;
  274. default: dflt: { /* it is a pattern item */
  275. int m = luaL_singlematch(*s, p);
  276. char *ep = luaL_item_end(p); /* get what is next */
  277. switch (*ep) {
  278. case '*': { /* repetition */
  279. char *res;
  280. if (m && (res = match(s+1, p, level)))
  281. return res;
  282. p=ep+1; goto init; /* else return match(s, ep+1, level); */
  283. }
  284. case '-': { /* repetition */
  285. char *res;
  286. if ((res = match(s, ep+1, level)) != 0)
  287. return res;
  288. else if (m) {
  289. s++;
  290. goto init; /* return match(s+1, p, level); */
  291. }
  292. else
  293. return NULL;
  294. }
  295. case '?': { /* optional */
  296. char *res;
  297. if (m && (res = match(s+1, ep+1, level)))
  298. return res;
  299. p=ep+1; goto init; /* else return match(s, ep+1, level); */
  300. }
  301. default:
  302. if (m) { s++; p=ep; goto init; } /* return match(s+1, ep, level); */
  303. else return NULL;
  304. }
  305. }
  306. }
  307. }
  308. static void str_find (void)
  309. {
  310. char *s = luaL_check_string(1);
  311. char *p = luaL_check_string(2);
  312. long init = (long)luaL_opt_number(3, 1) - 1;
  313. luaL_arg_check(0 <= init && init <= strlen(s), 3, "out of range");
  314. if (lua_getparam(4) != LUA_NOOBJECT ||
  315. strpbrk(p, SPECIALS) == NULL) { /* no special caracters? */
  316. char *s2 = strstr(s+init, p);
  317. if (s2) {
  318. lua_pushnumber(s2-s+1);
  319. lua_pushnumber(s2-s+strlen(p));
  320. }
  321. }
  322. else {
  323. int anchor = (*p == '^') ? (p++, 1) : 0;
  324. char *s1=s+init;
  325. do {
  326. char *res;
  327. if ((res=match(s1, p, 0)) != NULL) {
  328. lua_pushnumber(s1-s+1); /* start */
  329. lua_pushnumber(res-s); /* end */
  330. push_captures();
  331. return;
  332. }
  333. } while (*s1++ && !anchor);
  334. }
  335. }
  336. static void add_s (lua_Object newp, lua_Object table, int n)
  337. {
  338. if (lua_isstring(newp)) {
  339. char *news = lua_getstring(newp);
  340. while (*news) {
  341. if (*news != ESC || !isdigit((unsigned char)*++news))
  342. luaI_addchar(*news++);
  343. else {
  344. int l = check_cap(*news++, num_captures);
  345. addnchar(capture[l].init, capture[l].len);
  346. }
  347. }
  348. }
  349. else if (lua_isfunction(newp)) {
  350. lua_Object res;
  351. struct lbuff oldbuff;
  352. int status;
  353. lua_beginblock();
  354. if (lua_istable(table)) {
  355. lua_pushobject(table);
  356. lua_pushnumber(n);
  357. }
  358. push_captures();
  359. /* function may use lbuffer, so save it and create a new one */
  360. oldbuff = lbuffer;
  361. lbuffer.b = NULL; lbuffer.max = lbuffer.size = 0;
  362. status = lua_callfunction(newp);
  363. /* restore old buffer */
  364. free(lbuffer.b);
  365. lbuffer = oldbuff;
  366. if (status != 0)
  367. lua_error(NULL);
  368. res = lua_getresult(1);
  369. addstr(lua_isstring(res) ? lua_getstring(res) : "");
  370. lua_endblock();
  371. }
  372. else luaL_arg_check(0, 3, NULL);
  373. }
  374. static void str_gsub (void)
  375. {
  376. char *src = luaL_check_string(1);
  377. char *p = luaL_check_string(2);
  378. lua_Object newp = lua_getparam(3);
  379. lua_Object table = lua_getparam(4);
  380. int max_s = (int)luaL_opt_number(lua_istable(table)?5:4, strlen(src)+1);
  381. int anchor = (*p == '^') ? (p++, 1) : 0;
  382. int n = 0;
  383. luaI_emptybuff();
  384. while (n < max_s) {
  385. char *e = match(src, p, 0);
  386. if (e) {
  387. n++;
  388. add_s(newp, table, n);
  389. }
  390. if (e && e>src) /* non empty match? */
  391. src = e; /* skip it */
  392. else if (*src)
  393. luaI_addchar(*src++);
  394. else break;
  395. if (anchor) break;
  396. }
  397. addstr(src);
  398. lua_pushstring(luaI_addchar(0));
  399. lua_pushnumber(n); /* number of substitutions */
  400. }
  401. static void str_set (void)
  402. {
  403. char *item = luaL_check_string(1);
  404. int i;
  405. luaL_arg_check(*luaL_item_end(item) == 0, 1, "wrong format");
  406. luaI_emptybuff();
  407. for (i=1; i<256; i++) /* 0 cannot be part of a set */
  408. if (luaL_singlematch(i, item))
  409. luaI_addchar(i);
  410. lua_pushstring(luaI_addchar(0));
  411. }
  412. void luaI_addquoted (char *s)
  413. {
  414. luaI_addchar('"');
  415. for (; *s; s++) {
  416. if (strchr("\"\\\n", *s))
  417. luaI_addchar('\\');
  418. luaI_addchar(*s);
  419. }
  420. luaI_addchar('"');
  421. }
  422. #define MAX_FORMAT 200
  423. static void str_format (void)
  424. {
  425. int arg = 1;
  426. char *strfrmt = luaL_check_string(arg++);
  427. luaI_emptybuff(); /* initialize */
  428. while (*strfrmt) {
  429. if (*strfrmt != '%')
  430. luaI_addchar(*strfrmt++);
  431. else if (*++strfrmt == '%')
  432. luaI_addchar(*strfrmt++); /* %% */
  433. else { /* format item */
  434. char form[MAX_FORMAT]; /* store the format ('%...') */
  435. char *buff;
  436. char *initf = strfrmt-1; /* -1 to include % */
  437. strfrmt = match(strfrmt, "[-+ #]*(%d*)%.?(%d*)", 0);
  438. if (capture[0].len > 3 || capture[1].len > 3) /* < 1000? */
  439. lua_error("invalid format (width or precision too long)");
  440. strncpy(form, initf, strfrmt-initf+1); /* +1 to include convertion */
  441. form[strfrmt-initf+1] = 0;
  442. buff = openspace(1000); /* to store the formated value */
  443. switch (*strfrmt++) {
  444. case 'q':
  445. luaI_addquoted(luaL_check_string(arg++));
  446. continue;
  447. case 's': {
  448. char *s = luaL_check_string(arg++);
  449. buff = openspace(strlen(s));
  450. sprintf(buff, form, s);
  451. break;
  452. }
  453. case 'c': case 'd': case 'i': case 'o':
  454. case 'u': case 'x': case 'X':
  455. sprintf(buff, form, (int)luaL_check_number(arg++));
  456. break;
  457. case 'e': case 'E': case 'f': case 'g':
  458. sprintf(buff, form, luaL_check_number(arg++));
  459. break;
  460. default: /* also treat cases 'pnLlh' */
  461. lua_error("invalid format option in function `format'");
  462. }
  463. lbuffer.size += strlen(buff);
  464. }
  465. }
  466. lua_pushstring(luaI_addchar(0)); /* push the result */
  467. }
  468. static struct luaL_reg strlib[] = {
  469. {"strlen", str_len},
  470. {"strsub", str_sub},
  471. {"strset", str_set},
  472. {"strlower", str_lower},
  473. {"strupper", str_upper},
  474. {"strrep", str_rep},
  475. {"ascii", str_ascii},
  476. {"format", str_format},
  477. {"strfind", str_find},
  478. {"gsub", str_gsub}
  479. };
  480. /*
  481. ** Open string library
  482. */
  483. void strlib_open (void)
  484. {
  485. luaL_openlib(strlib, (sizeof(strlib)/sizeof(strlib[0])));
  486. }