lstrlib.c 14 KB

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