lstrlib.c 13 KB

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