lstrlib.c 13 KB

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