lstrlib.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  1. /*
  2. ** $Id: lstrlib.c,v 1.8 1998/01/27 19:11:36 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_pushlstr(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_pushlstr(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_ascii (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. /*
  83. ** =======================================================
  84. ** PATTERN MATCHING
  85. ** =======================================================
  86. */
  87. #define MAX_CAPT 9
  88. struct Capture {
  89. int level; /* total number of captures (finished or unfinished) */
  90. struct {
  91. char *init;
  92. int len; /* -1 signals unfinished capture */
  93. } capture[MAX_CAPT];
  94. };
  95. #define ESC '%'
  96. #define SPECIALS "^$*?.([%-"
  97. static void push_captures (struct Capture *cap)
  98. {
  99. int i;
  100. for (i=0; i<cap->level; i++)
  101. lua_pushlstr(cap->capture[i].init, cap->capture[i].len);
  102. }
  103. static int check_cap (int l, struct Capture *cap)
  104. {
  105. l -= '1';
  106. if (!(0 <= l && l < cap->level && cap->capture[l].len != -1))
  107. lua_error("invalid capture index");
  108. return l;
  109. }
  110. static int capture_to_close (struct Capture *cap)
  111. {
  112. int level = cap->level;
  113. for (level--; level>=0; level--)
  114. if (cap->capture[level].len == -1) return level;
  115. lua_error("invalid pattern capture");
  116. return 0; /* to avoid warnings */
  117. }
  118. static char *bracket_end (char *p)
  119. {
  120. return (*p == 0) ? NULL : strchr((*p=='^') ? p+2 : p+1, ']');
  121. }
  122. static int matchclass (int c, int cl)
  123. {
  124. int res;
  125. switch (tolower((unsigned char)cl)) {
  126. case 'w' : res = isalnum((unsigned char)c); break;
  127. case 'd' : res = isdigit((unsigned char)c); break;
  128. case 's' : res = isspace((unsigned char)c); break;
  129. case 'a' : res = isalpha((unsigned char)c); break;
  130. case 'p' : res = ispunct((unsigned char)c); break;
  131. case 'l' : res = islower((unsigned char)c); break;
  132. case 'u' : res = isupper((unsigned char)c); break;
  133. case 'c' : res = iscntrl((unsigned char)c); break;
  134. default: return (cl == c);
  135. }
  136. return (islower((unsigned char)cl) ? res : !res);
  137. }
  138. int luaI_singlematch (int c, char *p, char **ep)
  139. {
  140. switch (*p) {
  141. case '.':
  142. *ep = p+1;
  143. return 1;
  144. case '\0':
  145. *ep = p;
  146. return 0;
  147. case ESC:
  148. if (*(++p) == '\0')
  149. luaL_verror("incorrect pattern (ends with `%c')", ESC);
  150. *ep = p+1;
  151. return matchclass(c, *p);
  152. case '[': {
  153. char *end = bracket_end(p+1);
  154. int sig = *(p+1) == '^' ? (p++, 0) : 1;
  155. if (end == NULL) lua_error("incorrect pattern (missing `]')");
  156. *ep = end+1;
  157. while (++p < end) {
  158. if (*p == ESC) {
  159. if (((p+1) < end) && matchclass(c, *++p)) return sig;
  160. }
  161. else if ((*(p+1) == '-') && (p+2 < end)) {
  162. p+=2;
  163. if (*(p-2) <= c && c <= *p) return sig;
  164. }
  165. else if (*p == c) return sig;
  166. }
  167. return !sig;
  168. }
  169. default:
  170. *ep = p+1;
  171. return (*p == c);
  172. }
  173. }
  174. static char *matchbalance (char *s, int b, int e)
  175. {
  176. if (*s != b) return NULL;
  177. else {
  178. int cont = 1;
  179. while (*(++s)) {
  180. if (*s == e) {
  181. if (--cont == 0) return s+1;
  182. }
  183. else if (*s == b) cont++;
  184. }
  185. }
  186. return NULL; /* string ends out of balance */
  187. }
  188. static char *matchitem (char *s, char *p, struct Capture *cap, char **ep)
  189. {
  190. if (*p == ESC) {
  191. p++;
  192. if (isdigit((unsigned char)*p)) { /* capture */
  193. int l = check_cap(*p, cap);
  194. *ep = p+1;
  195. if (strncmp(cap->capture[l].init, s, cap->capture[l].len) == 0)
  196. return s+cap->capture[l].len;
  197. else return NULL;
  198. }
  199. else if (*p == 'b') { /* balanced string */
  200. p++;
  201. if (*p == 0 || *(p+1) == 0)
  202. lua_error("unbalanced pattern");
  203. *ep = p+2;
  204. return matchbalance(s, *p, *(p+1));
  205. }
  206. else p--; /* and go through */
  207. }
  208. /* "luaI_singlematch" sets "ep" (so must be called even when *s == 0) */
  209. return (luaI_singlematch(*s, p, ep) && *s) ? s+1 : NULL;
  210. }
  211. static char *match (char *s, char *p, struct Capture *cap)
  212. {
  213. init: /* using goto's to optimize tail recursion */
  214. switch (*p) {
  215. case '(': { /* start capture */
  216. char *res;
  217. if (cap->level >= MAX_CAPT) lua_error("too many captures");
  218. cap->capture[cap->level].init = s;
  219. cap->capture[cap->level].len = -1;
  220. cap->level++;
  221. if ((res=match(s, p+1, cap)) == NULL) /* match failed? */
  222. cap->level--; /* undo capture */
  223. return res;
  224. }
  225. case ')': { /* end capture */
  226. int l = capture_to_close(cap);
  227. char *res;
  228. cap->capture[l].len = s - cap->capture[l].init; /* close capture */
  229. if ((res = match(s, p+1, cap)) == NULL) /* match failed? */
  230. cap->capture[l].len = -1; /* undo capture */
  231. return res;
  232. }
  233. case '\0': case '$': /* (possibly) end of pattern */
  234. if (*p == 0 || (*(p+1) == 0 && *s == 0))
  235. return s;
  236. /* else go through */
  237. default: { /* it is a pattern item */
  238. char *ep; /* get what is next */
  239. char *s1 = matchitem(s, p, cap, &ep);
  240. switch (*ep) {
  241. case '*': { /* repetition */
  242. char *res;
  243. if (s1 && (res = match(s1, p, cap)))
  244. return res;
  245. p=ep+1; goto init; /* else return match(s, ep+1, cap); */
  246. }
  247. case '?': { /* optional */
  248. char *res;
  249. if (s1 && (res = match(s1, ep+1, cap)))
  250. return res;
  251. p=ep+1; goto init; /* else return match(s, ep+1, cap); */
  252. }
  253. case '-': { /* repetition */
  254. char *res;
  255. if ((res = match(s, ep+1, cap)) != 0)
  256. return res;
  257. else if (s1) {
  258. s = s1;
  259. goto init; /* return match(s1, p, cap); */
  260. }
  261. else
  262. return NULL;
  263. }
  264. default:
  265. if (s1) { s=s1; p=ep; goto init; } /* return match(s1, ep, cap); */
  266. else return NULL;
  267. }
  268. }
  269. }
  270. }
  271. static void str_find (void)
  272. {
  273. long l;
  274. char *s = luaL_check_lstr(1, &l);
  275. char *p = luaL_check_string(2);
  276. long init = posrelat(luaL_opt_number(3, 1), l) - 1;
  277. luaL_arg_check(0 <= init && init <= l, 3, "out of range");
  278. if (lua_getparam(4) != LUA_NOOBJECT ||
  279. strpbrk(p, SPECIALS) == NULL) { /* no special caracters? */
  280. char *s2 = strstr(s+init, p);
  281. if (s2) {
  282. lua_pushnumber(s2-s+1);
  283. lua_pushnumber(s2-s+strlen(p));
  284. }
  285. }
  286. else {
  287. int anchor = (*p == '^') ? (p++, 1) : 0;
  288. char *s1=s+init;
  289. do {
  290. struct Capture cap;
  291. char *res;
  292. cap.level = 0;
  293. if ((res=match(s1, p, &cap)) != NULL) {
  294. lua_pushnumber(s1-s+1); /* start */
  295. lua_pushnumber(res-s); /* end */
  296. push_captures(&cap);
  297. return;
  298. }
  299. } while (*s1++ && !anchor);
  300. }
  301. }
  302. static void add_s (lua_Object newp, struct Capture *cap)
  303. {
  304. if (lua_isstring(newp)) {
  305. char *news = lua_getstring(newp);
  306. while (*news) {
  307. if (*news != ESC || !isdigit((unsigned char)*++news))
  308. luaL_addchar(*news++);
  309. else {
  310. int l = check_cap(*news++, cap);
  311. addnchar(cap->capture[l].init, cap->capture[l].len);
  312. }
  313. }
  314. }
  315. else if (lua_isfunction(newp)) {
  316. lua_Object res;
  317. int status;
  318. int oldbuff;
  319. lua_beginblock();
  320. push_captures(cap);
  321. /* function may use buffer, so save it and create a new one */
  322. oldbuff = luaL_newbuffer(0);
  323. status = lua_callfunction(newp);
  324. /* restore old buffer */
  325. luaL_oldbuffer(oldbuff);
  326. if (status != 0) {
  327. lua_endblock();
  328. lua_error(NULL);
  329. }
  330. res = lua_getresult(1);
  331. if (lua_isstring(res))
  332. addnchar(lua_getstring(res), lua_getstrlen(res));
  333. else
  334. addnchar(NULL, 0);
  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. addnchar(src, strlen(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. if (isdigit((unsigned char)initf[0]) && initf[1] == '$') {
  397. arg = initf[0] - '0';
  398. initf += 2; /* skip the 'n$' */
  399. }
  400. arg++;
  401. strfrmt = match(initf, "[-+ #0]*(%d*)%.?(%d*)", &cap);
  402. if (cap.capture[0].len > 2 || cap.capture[1].len > 2) /* < 100? */
  403. lua_error("invalid format (width or precision too long)");
  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. }