strlib.c 14 KB

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