lstrlib.c 12 KB

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