strlib.c 13 KB

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