lstrlib.c 13 KB

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