strlib.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  1. /*
  2. ** strlib.c
  3. ** String library to LUA
  4. */
  5. char *rcs_strlib="$Id: strlib.c,v 1.31 1996/10/31 20:18:05 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; /* \0, EOF or other strange flags */
  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 *match (char *s, char *p, int level)
  264. {
  265. init: /* using goto's to optimize tail recursion */
  266. switch (*p) {
  267. case '(': /* start capture */
  268. if (level >= MAX_CAPT) lua_error("too many captures");
  269. capture[level].init = s;
  270. capture[level].len = -1;
  271. level++; p++; goto init; /* return match(s, p+1, level); */
  272. case ')': { /* end capture */
  273. int l = capture_to_close(level);
  274. char *res;
  275. capture[l].len = s - capture[l].init; /* close capture */
  276. if ((res = match(s, p+1, level)) == NULL) /* match failed? */
  277. capture[l].len = -1; /* undo capture */
  278. return res;
  279. }
  280. case ESC: /* possibly a capture (if followed by a digit) */
  281. if (!isdigit(*(p+1))) goto dflt;
  282. else {
  283. int l = check_cap(*(p+1), level);
  284. if (strncmp(capture[l].init, s, capture[l].len) == 0) {
  285. /* return match(p+2, s+capture[l].len, level); */
  286. p+=2; s+=capture[l].len; goto init;
  287. }
  288. else return NULL;
  289. }
  290. case '\0': case '$': /* (possibly) end of pattern */
  291. if (*p == 0 || (*(p+1) == 0 && *s == 0)) {
  292. num_captures = level;
  293. return s;
  294. }
  295. else goto dflt;
  296. default: dflt: { /* it is a pattern item */
  297. int m = singlematch(*s, p);
  298. char *ep = item_end(p); /* get what is next */
  299. switch (*ep) {
  300. case '*': { /* repetition */
  301. char *res;
  302. if (m && (res = match(s+1, p, level)))
  303. return res;
  304. p=ep+1; goto init; /* else return match(s, ep+1, level); */
  305. }
  306. case '?': { /* optional */
  307. char *res;
  308. if (m && (res = match(s+1, ep+1, level)))
  309. return res;
  310. p=ep+1; goto init; /* else return match(s, ep+1, level); */
  311. }
  312. default:
  313. if (m) { s++; p=ep; goto init; } /* return match(s+1, ep, level); */
  314. else return NULL;
  315. }
  316. }
  317. }
  318. }
  319. static void str_find (void)
  320. {
  321. char *s = lua_check_string(1, "strfind");
  322. char *p = lua_check_string(2, "strfind");
  323. long init = lua_opt_number(3, 1, "strfind") - 1;
  324. lua_arg_check(0 <= init && init <= strlen(s), "strfind");
  325. if (lua_getparam(4) != LUA_NOOBJECT ||
  326. strpbrk(p, SPECIALS) == NULL) { /* no special caracters? */
  327. char *s2 = strstr(s+init, p);
  328. if (s2) {
  329. lua_pushnumber(s2-s+1);
  330. lua_pushnumber(s2-s+strlen(p));
  331. }
  332. }
  333. else {
  334. int anchor = (*p == '^') ? (p++, 1) : 0;
  335. char *s1=s+init;
  336. do {
  337. char *res;
  338. if ((res=match(s1, p, 0)) != NULL) {
  339. lua_pushnumber(s1-s+1); /* start */
  340. lua_pushnumber(res-s); /* end */
  341. push_captures();
  342. return;
  343. }
  344. } while (*s1++ && !anchor);
  345. }
  346. }
  347. static void add_s (lua_Object newp)
  348. {
  349. if (lua_isstring(newp)) {
  350. char *news = lua_getstring(newp);
  351. while (*news) {
  352. if (*news != ESC || !isdigit(*++news))
  353. luaI_addchar(*news++);
  354. else {
  355. int l = check_cap(*news++, num_captures);
  356. addnchar(capture[l].init, capture[l].len);
  357. }
  358. }
  359. }
  360. else if (lua_isfunction(newp)) {
  361. lua_Object res;
  362. struct lbuff oldbuff;
  363. lua_beginblock();
  364. push_captures();
  365. /* function may use lbuffer, so save it and create a new one */
  366. oldbuff = lbuffer;
  367. lbuffer.b = NULL; lbuffer.max = lbuffer.size = 0;
  368. lua_callfunction(newp);
  369. /* restore old buffer */
  370. free(lbuffer.b);
  371. lbuffer = oldbuff;
  372. res = lua_getresult(1);
  373. addstr(lua_isstring(res) ? lua_getstring(res) : "");
  374. lua_endblock();
  375. }
  376. else lua_arg_check(0, "gsub");
  377. }
  378. static void str_gsub (void)
  379. {
  380. char *src = lua_check_string(1, "gsub");
  381. char *p = lua_check_string(2, "gsub");
  382. lua_Object newp = lua_getparam(3);
  383. int max_s = lua_opt_number(4, strlen(src), "gsub");
  384. int anchor = (*p == '^') ? (p++, 1) : 0;
  385. int n = 0;
  386. luaI_addchar(0);
  387. while (*src && n < max_s) {
  388. char *e;
  389. if ((e=match(src, p, 0)) == NULL)
  390. luaI_addchar(*src++);
  391. else {
  392. if (e == src) lua_error("empty pattern in substitution");
  393. add_s(newp);
  394. src = e;
  395. n++;
  396. }
  397. if (anchor) break;
  398. }
  399. addstr(src);
  400. lua_pushstring(luaI_addchar(0));
  401. lua_pushnumber(n); /* number of substitutions */
  402. }
  403. static void str_set (void)
  404. {
  405. char *item = lua_check_string(1, "strset");
  406. int i;
  407. lua_arg_check(*item_end(item) == 0, "strset");
  408. luaI_addchar(0);
  409. for (i=1; i<256; i++) /* 0 cannot be part of a set */
  410. if (singlematch(i, item))
  411. luaI_addchar(i);
  412. lua_pushstring(luaI_addchar(0));
  413. }
  414. void luaI_addquoted (char *s)
  415. {
  416. luaI_addchar('"');
  417. for (; *s; s++) {
  418. if (strchr("\"\\\n", *s))
  419. luaI_addchar('\\');
  420. luaI_addchar(*s);
  421. }
  422. luaI_addchar('"');
  423. }
  424. #define MAX_FORMAT 200
  425. static void str_format (void)
  426. {
  427. int arg = 1;
  428. char *strfrmt = lua_check_string(arg++, "format");
  429. luaI_addchar(0); /* initialize */
  430. while (*strfrmt) {
  431. if (*strfrmt != '%')
  432. luaI_addchar(*strfrmt++);
  433. else if (*++strfrmt == '%')
  434. luaI_addchar(*strfrmt++); /* %% */
  435. else { /* format item */
  436. char form[MAX_FORMAT]; /* store the format ('%...') */
  437. char *buff;
  438. char *initf = strfrmt-1; /* -1 to include % */
  439. strfrmt = match(strfrmt, "[-+ #]*(%d*)%.?(%d*)", 0);
  440. if (capture[0].len > 3 || capture[1].len > 3) /* < 1000? */
  441. lua_error("invalid format (width/precision too long)");
  442. strncpy(form, initf, strfrmt-initf+1); /* +1 to include convertion */
  443. form[strfrmt-initf+1] = 0;
  444. buff = openspace(1000); /* to store the formated value */
  445. switch (*strfrmt++) {
  446. case 'q':
  447. luaI_addquoted(lua_check_string(arg++, "format"));
  448. continue;
  449. case 's': {
  450. char *s = lua_check_string(arg++, "format");
  451. buff = openspace(strlen(s));
  452. sprintf(buff, form, s);
  453. break;
  454. }
  455. case 'c': case 'd': case 'i': case 'o':
  456. case 'u': case 'x': case 'X':
  457. sprintf(buff, form, (int)lua_check_number(arg++, "format"));
  458. break;
  459. case 'e': case 'E': case 'f': case 'g':
  460. sprintf(buff, form, lua_check_number(arg++, "format"));
  461. break;
  462. default: /* also treat cases 'pnLlh' */
  463. lua_error("invalid format option in function `format'");
  464. }
  465. lbuffer.size += strlen(buff);
  466. }
  467. }
  468. lua_pushstring(luaI_addchar(0)); /* push the result */
  469. }
  470. void luaI_openlib (struct lua_reg *l, int n)
  471. {
  472. int i;
  473. for (i=0; i<n; i++)
  474. lua_register(l[i].name, l[i].func);
  475. }
  476. static struct lua_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. luaI_openlib(strlib, (sizeof(strlib)/sizeof(strlib[0])));
  495. }