strlib.c 13 KB

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