lstrlib.c 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207
  1. /*
  2. ** $Id: lstrlib.c,v 1.199 2014/07/29 16:01:00 roberto Exp roberto $
  3. ** Standard library for string operations and pattern-matching
  4. ** See Copyright Notice in lua.h
  5. */
  6. #include <ctype.h>
  7. #include <limits.h>
  8. #include <stddef.h>
  9. #include <stdio.h>
  10. #include <stdlib.h>
  11. #include <string.h>
  12. #define lstrlib_c
  13. #define LUA_LIB
  14. #include "lua.h"
  15. #include "lauxlib.h"
  16. #include "lualib.h"
  17. /*
  18. ** maximum number of captures that a pattern can do during
  19. ** pattern-matching. This limit is arbitrary.
  20. */
  21. #if !defined(LUA_MAXCAPTURES)
  22. #define LUA_MAXCAPTURES 32
  23. #endif
  24. /* macro to `unsign' a character */
  25. #define uchar(c) ((unsigned char)(c))
  26. static int str_len (lua_State *L) {
  27. size_t l;
  28. luaL_checklstring(L, 1, &l);
  29. lua_pushinteger(L, (lua_Integer)l);
  30. return 1;
  31. }
  32. /* translate a relative string position: negative means back from end */
  33. static lua_Integer posrelat (lua_Integer pos, size_t len) {
  34. if (pos >= 0) return pos;
  35. else if (0u - (size_t)pos > len) return 0;
  36. else return (lua_Integer)len + pos + 1;
  37. }
  38. static int str_sub (lua_State *L) {
  39. size_t l;
  40. const char *s = luaL_checklstring(L, 1, &l);
  41. lua_Integer start = posrelat(luaL_checkinteger(L, 2), l);
  42. lua_Integer end = posrelat(luaL_optinteger(L, 3, -1), l);
  43. if (start < 1) start = 1;
  44. if (end > (lua_Integer)l) end = l;
  45. if (start <= end)
  46. lua_pushlstring(L, s + start - 1, (size_t)(end - start + 1));
  47. else lua_pushliteral(L, "");
  48. return 1;
  49. }
  50. static int str_reverse (lua_State *L) {
  51. size_t l, i;
  52. luaL_Buffer b;
  53. const char *s = luaL_checklstring(L, 1, &l);
  54. char *p = luaL_buffinitsize(L, &b, l);
  55. for (i = 0; i < l; i++)
  56. p[i] = s[l - i - 1];
  57. luaL_pushresultsize(&b, l);
  58. return 1;
  59. }
  60. static int str_lower (lua_State *L) {
  61. size_t l;
  62. size_t i;
  63. luaL_Buffer b;
  64. const char *s = luaL_checklstring(L, 1, &l);
  65. char *p = luaL_buffinitsize(L, &b, l);
  66. for (i=0; i<l; i++)
  67. p[i] = tolower(uchar(s[i]));
  68. luaL_pushresultsize(&b, l);
  69. return 1;
  70. }
  71. static int str_upper (lua_State *L) {
  72. size_t l;
  73. size_t i;
  74. luaL_Buffer b;
  75. const char *s = luaL_checklstring(L, 1, &l);
  76. char *p = luaL_buffinitsize(L, &b, l);
  77. for (i=0; i<l; i++)
  78. p[i] = toupper(uchar(s[i]));
  79. luaL_pushresultsize(&b, l);
  80. return 1;
  81. }
  82. /* reasonable limit to avoid arithmetic overflow and strings too big */
  83. #if LUA_MAXINTEGER / 2 <= 0x10000000
  84. #define MAXSIZE ((size_t)(LUA_MAXINTEGER / 2))
  85. #else
  86. #define MAXSIZE ((size_t)0x10000000)
  87. #endif
  88. static int str_rep (lua_State *L) {
  89. size_t l, lsep;
  90. const char *s = luaL_checklstring(L, 1, &l);
  91. lua_Integer n = luaL_checkinteger(L, 2);
  92. const char *sep = luaL_optlstring(L, 3, "", &lsep);
  93. if (n <= 0) lua_pushliteral(L, "");
  94. else if (l + lsep < l || l + lsep > MAXSIZE / n) /* may overflow? */
  95. return luaL_error(L, "resulting string too large");
  96. else {
  97. size_t totallen = (size_t)n * l + (size_t)(n - 1) * lsep;
  98. luaL_Buffer b;
  99. char *p = luaL_buffinitsize(L, &b, totallen);
  100. while (n-- > 1) { /* first n-1 copies (followed by separator) */
  101. memcpy(p, s, l * sizeof(char)); p += l;
  102. if (lsep > 0) { /* empty 'memcpy' is not that cheap */
  103. memcpy(p, sep, lsep * sizeof(char));
  104. p += lsep;
  105. }
  106. }
  107. memcpy(p, s, l * sizeof(char)); /* last copy (not followed by separator) */
  108. luaL_pushresultsize(&b, totallen);
  109. }
  110. return 1;
  111. }
  112. static int str_byte (lua_State *L) {
  113. size_t l;
  114. const char *s = luaL_checklstring(L, 1, &l);
  115. lua_Integer posi = posrelat(luaL_optinteger(L, 2, 1), l);
  116. lua_Integer pose = posrelat(luaL_optinteger(L, 3, posi), l);
  117. int n, i;
  118. if (posi < 1) posi = 1;
  119. if (pose > (lua_Integer)l) pose = l;
  120. if (posi > pose) return 0; /* empty interval; return no values */
  121. n = (int)(pose - posi + 1);
  122. if (posi + n <= pose) /* arithmetic overflow? */
  123. return luaL_error(L, "string slice too long");
  124. luaL_checkstack(L, n, "string slice too long");
  125. for (i=0; i<n; i++)
  126. lua_pushinteger(L, uchar(s[posi+i-1]));
  127. return n;
  128. }
  129. static int str_char (lua_State *L) {
  130. int n = lua_gettop(L); /* number of arguments */
  131. int i;
  132. luaL_Buffer b;
  133. char *p = luaL_buffinitsize(L, &b, n);
  134. for (i=1; i<=n; i++) {
  135. lua_Integer c = luaL_checkinteger(L, i);
  136. luaL_argcheck(L, uchar(c) == c, i, "value out of range");
  137. p[i - 1] = uchar(c);
  138. }
  139. luaL_pushresultsize(&b, n);
  140. return 1;
  141. }
  142. static int writer (lua_State *L, const void *b, size_t size, void *B) {
  143. (void)L;
  144. luaL_addlstring((luaL_Buffer *) B, (const char *)b, size);
  145. return 0;
  146. }
  147. static int str_dump (lua_State *L) {
  148. luaL_Buffer b;
  149. int strip = lua_toboolean(L, 2);
  150. luaL_checktype(L, 1, LUA_TFUNCTION);
  151. lua_settop(L, 1);
  152. luaL_buffinit(L,&b);
  153. if (lua_dump(L, writer, &b, strip) != 0)
  154. return luaL_error(L, "unable to dump given function");
  155. luaL_pushresult(&b);
  156. return 1;
  157. }
  158. /*
  159. ** {======================================================
  160. ** PATTERN MATCHING
  161. ** =======================================================
  162. */
  163. #define CAP_UNFINISHED (-1)
  164. #define CAP_POSITION (-2)
  165. typedef struct MatchState {
  166. int matchdepth; /* control for recursive depth (to avoid C stack overflow) */
  167. const char *src_init; /* init of source string */
  168. const char *src_end; /* end ('\0') of source string */
  169. const char *p_end; /* end ('\0') of pattern */
  170. lua_State *L;
  171. int level; /* total number of captures (finished or unfinished) */
  172. struct {
  173. const char *init;
  174. ptrdiff_t len;
  175. } capture[LUA_MAXCAPTURES];
  176. } MatchState;
  177. /* recursive function */
  178. static const char *match (MatchState *ms, const char *s, const char *p);
  179. /* maximum recursion depth for 'match' */
  180. #if !defined(MAXCCALLS)
  181. #define MAXCCALLS 200
  182. #endif
  183. #define L_ESC '%'
  184. #define SPECIALS "^$*+?.([%-"
  185. static int check_capture (MatchState *ms, int l) {
  186. l -= '1';
  187. if (l < 0 || l >= ms->level || ms->capture[l].len == CAP_UNFINISHED)
  188. return luaL_error(ms->L, "invalid capture index %%%d", l + 1);
  189. return l;
  190. }
  191. static int capture_to_close (MatchState *ms) {
  192. int level = ms->level;
  193. for (level--; level>=0; level--)
  194. if (ms->capture[level].len == CAP_UNFINISHED) return level;
  195. return luaL_error(ms->L, "invalid pattern capture");
  196. }
  197. static const char *classend (MatchState *ms, const char *p) {
  198. switch (*p++) {
  199. case L_ESC: {
  200. if (p == ms->p_end)
  201. luaL_error(ms->L, "malformed pattern (ends with " LUA_QL("%%") ")");
  202. return p+1;
  203. }
  204. case '[': {
  205. if (*p == '^') p++;
  206. do { /* look for a `]' */
  207. if (p == ms->p_end)
  208. luaL_error(ms->L, "malformed pattern (missing " LUA_QL("]") ")");
  209. if (*(p++) == L_ESC && p < ms->p_end)
  210. p++; /* skip escapes (e.g. `%]') */
  211. } while (*p != ']');
  212. return p+1;
  213. }
  214. default: {
  215. return p;
  216. }
  217. }
  218. }
  219. static int match_class (int c, int cl) {
  220. int res;
  221. switch (tolower(cl)) {
  222. case 'a' : res = isalpha(c); break;
  223. case 'c' : res = iscntrl(c); break;
  224. case 'd' : res = isdigit(c); break;
  225. case 'g' : res = isgraph(c); break;
  226. case 'l' : res = islower(c); break;
  227. case 'p' : res = ispunct(c); break;
  228. case 's' : res = isspace(c); break;
  229. case 'u' : res = isupper(c); break;
  230. case 'w' : res = isalnum(c); break;
  231. case 'x' : res = isxdigit(c); break;
  232. case 'z' : res = (c == 0); break; /* deprecated option */
  233. default: return (cl == c);
  234. }
  235. return (islower(cl) ? res : !res);
  236. }
  237. static int matchbracketclass (int c, const char *p, const char *ec) {
  238. int sig = 1;
  239. if (*(p+1) == '^') {
  240. sig = 0;
  241. p++; /* skip the `^' */
  242. }
  243. while (++p < ec) {
  244. if (*p == L_ESC) {
  245. p++;
  246. if (match_class(c, uchar(*p)))
  247. return sig;
  248. }
  249. else if ((*(p+1) == '-') && (p+2 < ec)) {
  250. p+=2;
  251. if (uchar(*(p-2)) <= c && c <= uchar(*p))
  252. return sig;
  253. }
  254. else if (uchar(*p) == c) return sig;
  255. }
  256. return !sig;
  257. }
  258. static int singlematch (MatchState *ms, const char *s, const char *p,
  259. const char *ep) {
  260. if (s >= ms->src_end)
  261. return 0;
  262. else {
  263. int c = uchar(*s);
  264. switch (*p) {
  265. case '.': return 1; /* matches any char */
  266. case L_ESC: return match_class(c, uchar(*(p+1)));
  267. case '[': return matchbracketclass(c, p, ep-1);
  268. default: return (uchar(*p) == c);
  269. }
  270. }
  271. }
  272. static const char *matchbalance (MatchState *ms, const char *s,
  273. const char *p) {
  274. if (p >= ms->p_end - 1)
  275. luaL_error(ms->L, "malformed pattern "
  276. "(missing arguments to " LUA_QL("%%b") ")");
  277. if (*s != *p) return NULL;
  278. else {
  279. int b = *p;
  280. int e = *(p+1);
  281. int cont = 1;
  282. while (++s < ms->src_end) {
  283. if (*s == e) {
  284. if (--cont == 0) return s+1;
  285. }
  286. else if (*s == b) cont++;
  287. }
  288. }
  289. return NULL; /* string ends out of balance */
  290. }
  291. static const char *max_expand (MatchState *ms, const char *s,
  292. const char *p, const char *ep) {
  293. ptrdiff_t i = 0; /* counts maximum expand for item */
  294. while (singlematch(ms, s + i, p, ep))
  295. i++;
  296. /* keeps trying to match with the maximum repetitions */
  297. while (i>=0) {
  298. const char *res = match(ms, (s+i), ep+1);
  299. if (res) return res;
  300. i--; /* else didn't match; reduce 1 repetition to try again */
  301. }
  302. return NULL;
  303. }
  304. static const char *min_expand (MatchState *ms, const char *s,
  305. const char *p, const char *ep) {
  306. for (;;) {
  307. const char *res = match(ms, s, ep+1);
  308. if (res != NULL)
  309. return res;
  310. else if (singlematch(ms, s, p, ep))
  311. s++; /* try with one more repetition */
  312. else return NULL;
  313. }
  314. }
  315. static const char *start_capture (MatchState *ms, const char *s,
  316. const char *p, int what) {
  317. const char *res;
  318. int level = ms->level;
  319. if (level >= LUA_MAXCAPTURES) luaL_error(ms->L, "too many captures");
  320. ms->capture[level].init = s;
  321. ms->capture[level].len = what;
  322. ms->level = level+1;
  323. if ((res=match(ms, s, p)) == NULL) /* match failed? */
  324. ms->level--; /* undo capture */
  325. return res;
  326. }
  327. static const char *end_capture (MatchState *ms, const char *s,
  328. const char *p) {
  329. int l = capture_to_close(ms);
  330. const char *res;
  331. ms->capture[l].len = s - ms->capture[l].init; /* close capture */
  332. if ((res = match(ms, s, p)) == NULL) /* match failed? */
  333. ms->capture[l].len = CAP_UNFINISHED; /* undo capture */
  334. return res;
  335. }
  336. static const char *match_capture (MatchState *ms, const char *s, int l) {
  337. size_t len;
  338. l = check_capture(ms, l);
  339. len = ms->capture[l].len;
  340. if ((size_t)(ms->src_end-s) >= len &&
  341. memcmp(ms->capture[l].init, s, len) == 0)
  342. return s+len;
  343. else return NULL;
  344. }
  345. static const char *match (MatchState *ms, const char *s, const char *p) {
  346. if (ms->matchdepth-- == 0)
  347. luaL_error(ms->L, "pattern too complex");
  348. init: /* using goto's to optimize tail recursion */
  349. if (p != ms->p_end) { /* end of pattern? */
  350. switch (*p) {
  351. case '(': { /* start capture */
  352. if (*(p + 1) == ')') /* position capture? */
  353. s = start_capture(ms, s, p + 2, CAP_POSITION);
  354. else
  355. s = start_capture(ms, s, p + 1, CAP_UNFINISHED);
  356. break;
  357. }
  358. case ')': { /* end capture */
  359. s = end_capture(ms, s, p + 1);
  360. break;
  361. }
  362. case '$': {
  363. if ((p + 1) != ms->p_end) /* is the `$' the last char in pattern? */
  364. goto dflt; /* no; go to default */
  365. s = (s == ms->src_end) ? s : NULL; /* check end of string */
  366. break;
  367. }
  368. case L_ESC: { /* escaped sequences not in the format class[*+?-]? */
  369. switch (*(p + 1)) {
  370. case 'b': { /* balanced string? */
  371. s = matchbalance(ms, s, p + 2);
  372. if (s != NULL) {
  373. p += 4; goto init; /* return match(ms, s, p + 4); */
  374. } /* else fail (s == NULL) */
  375. break;
  376. }
  377. case 'f': { /* frontier? */
  378. const char *ep; char previous;
  379. p += 2;
  380. if (*p != '[')
  381. luaL_error(ms->L, "missing " LUA_QL("[") " after "
  382. LUA_QL("%%f") " in pattern");
  383. ep = classend(ms, p); /* points to what is next */
  384. previous = (s == ms->src_init) ? '\0' : *(s - 1);
  385. if (!matchbracketclass(uchar(previous), p, ep - 1) &&
  386. matchbracketclass(uchar(*s), p, ep - 1)) {
  387. p = ep; goto init; /* return match(ms, s, ep); */
  388. }
  389. s = NULL; /* match failed */
  390. break;
  391. }
  392. case '0': case '1': case '2': case '3':
  393. case '4': case '5': case '6': case '7':
  394. case '8': case '9': { /* capture results (%0-%9)? */
  395. s = match_capture(ms, s, uchar(*(p + 1)));
  396. if (s != NULL) {
  397. p += 2; goto init; /* return match(ms, s, p + 2) */
  398. }
  399. break;
  400. }
  401. default: goto dflt;
  402. }
  403. break;
  404. }
  405. default: dflt: { /* pattern class plus optional suffix */
  406. const char *ep = classend(ms, p); /* points to optional suffix */
  407. /* does not match at least once? */
  408. if (!singlematch(ms, s, p, ep)) {
  409. if (*ep == '*' || *ep == '?' || *ep == '-') { /* accept empty? */
  410. p = ep + 1; goto init; /* return match(ms, s, ep + 1); */
  411. }
  412. else /* '+' or no suffix */
  413. s = NULL; /* fail */
  414. }
  415. else { /* matched once */
  416. switch (*ep) { /* handle optional suffix */
  417. case '?': { /* optional */
  418. const char *res;
  419. if ((res = match(ms, s + 1, ep + 1)) != NULL)
  420. s = res;
  421. else {
  422. p = ep + 1; goto init; /* else return match(ms, s, ep + 1); */
  423. }
  424. break;
  425. }
  426. case '+': /* 1 or more repetitions */
  427. s++; /* 1 match already done */
  428. /* go through */
  429. case '*': /* 0 or more repetitions */
  430. s = max_expand(ms, s, p, ep);
  431. break;
  432. case '-': /* 0 or more repetitions (minimum) */
  433. s = min_expand(ms, s, p, ep);
  434. break;
  435. default: /* no suffix */
  436. s++; p = ep; goto init; /* return match(ms, s + 1, ep); */
  437. }
  438. }
  439. break;
  440. }
  441. }
  442. }
  443. ms->matchdepth++;
  444. return s;
  445. }
  446. static const char *lmemfind (const char *s1, size_t l1,
  447. const char *s2, size_t l2) {
  448. if (l2 == 0) return s1; /* empty strings are everywhere */
  449. else if (l2 > l1) return NULL; /* avoids a negative `l1' */
  450. else {
  451. const char *init; /* to search for a `*s2' inside `s1' */
  452. l2--; /* 1st char will be checked by `memchr' */
  453. l1 = l1-l2; /* `s2' cannot be found after that */
  454. while (l1 > 0 && (init = (const char *)memchr(s1, *s2, l1)) != NULL) {
  455. init++; /* 1st char is already checked */
  456. if (memcmp(init, s2+1, l2) == 0)
  457. return init-1;
  458. else { /* correct `l1' and `s1' to try again */
  459. l1 -= init-s1;
  460. s1 = init;
  461. }
  462. }
  463. return NULL; /* not found */
  464. }
  465. }
  466. static void push_onecapture (MatchState *ms, int i, const char *s,
  467. const char *e) {
  468. if (i >= ms->level) {
  469. if (i == 0) /* ms->level == 0, too */
  470. lua_pushlstring(ms->L, s, e - s); /* add whole match */
  471. else
  472. luaL_error(ms->L, "invalid capture index");
  473. }
  474. else {
  475. ptrdiff_t l = ms->capture[i].len;
  476. if (l == CAP_UNFINISHED) luaL_error(ms->L, "unfinished capture");
  477. if (l == CAP_POSITION)
  478. lua_pushinteger(ms->L, ms->capture[i].init - ms->src_init + 1);
  479. else
  480. lua_pushlstring(ms->L, ms->capture[i].init, l);
  481. }
  482. }
  483. static int push_captures (MatchState *ms, const char *s, const char *e) {
  484. int i;
  485. int nlevels = (ms->level == 0 && s) ? 1 : ms->level;
  486. luaL_checkstack(ms->L, nlevels, "too many captures");
  487. for (i = 0; i < nlevels; i++)
  488. push_onecapture(ms, i, s, e);
  489. return nlevels; /* number of strings pushed */
  490. }
  491. /* check whether pattern has no special characters */
  492. static int nospecials (const char *p, size_t l) {
  493. size_t upto = 0;
  494. do {
  495. if (strpbrk(p + upto, SPECIALS))
  496. return 0; /* pattern has a special character */
  497. upto += strlen(p + upto) + 1; /* may have more after \0 */
  498. } while (upto <= l);
  499. return 1; /* no special chars found */
  500. }
  501. static int str_find_aux (lua_State *L, int find) {
  502. size_t ls, lp;
  503. const char *s = luaL_checklstring(L, 1, &ls);
  504. const char *p = luaL_checklstring(L, 2, &lp);
  505. lua_Integer init = posrelat(luaL_optinteger(L, 3, 1), ls);
  506. if (init < 1) init = 1;
  507. else if (init > (lua_Integer)ls + 1) { /* start after string's end? */
  508. lua_pushnil(L); /* cannot find anything */
  509. return 1;
  510. }
  511. /* explicit request or no special characters? */
  512. if (find && (lua_toboolean(L, 4) || nospecials(p, lp))) {
  513. /* do a plain search */
  514. const char *s2 = lmemfind(s + init - 1, ls - (size_t)init + 1, p, lp);
  515. if (s2) {
  516. lua_pushinteger(L, s2 - s + 1);
  517. lua_pushinteger(L, s2 - s + lp);
  518. return 2;
  519. }
  520. }
  521. else {
  522. MatchState ms;
  523. const char *s1 = s + init - 1;
  524. int anchor = (*p == '^');
  525. if (anchor) {
  526. p++; lp--; /* skip anchor character */
  527. }
  528. ms.L = L;
  529. ms.matchdepth = MAXCCALLS;
  530. ms.src_init = s;
  531. ms.src_end = s + ls;
  532. ms.p_end = p + lp;
  533. do {
  534. const char *res;
  535. ms.level = 0;
  536. lua_assert(ms.matchdepth == MAXCCALLS);
  537. if ((res=match(&ms, s1, p)) != NULL) {
  538. if (find) {
  539. lua_pushinteger(L, s1 - s + 1); /* start */
  540. lua_pushinteger(L, res - s); /* end */
  541. return push_captures(&ms, NULL, 0) + 2;
  542. }
  543. else
  544. return push_captures(&ms, s1, res);
  545. }
  546. } while (s1++ < ms.src_end && !anchor);
  547. }
  548. lua_pushnil(L); /* not found */
  549. return 1;
  550. }
  551. static int str_find (lua_State *L) {
  552. return str_find_aux(L, 1);
  553. }
  554. static int str_match (lua_State *L) {
  555. return str_find_aux(L, 0);
  556. }
  557. static int gmatch_aux (lua_State *L) {
  558. MatchState ms;
  559. size_t ls, lp;
  560. const char *s = lua_tolstring(L, lua_upvalueindex(1), &ls);
  561. const char *p = lua_tolstring(L, lua_upvalueindex(2), &lp);
  562. const char *src;
  563. ms.L = L;
  564. ms.matchdepth = MAXCCALLS;
  565. ms.src_init = s;
  566. ms.src_end = s+ls;
  567. ms.p_end = p + lp;
  568. for (src = s + (size_t)lua_tointeger(L, lua_upvalueindex(3));
  569. src <= ms.src_end;
  570. src++) {
  571. const char *e;
  572. ms.level = 0;
  573. lua_assert(ms.matchdepth == MAXCCALLS);
  574. if ((e = match(&ms, src, p)) != NULL) {
  575. lua_Integer newstart = e-s;
  576. if (e == src) newstart++; /* empty match? go at least one position */
  577. lua_pushinteger(L, newstart);
  578. lua_replace(L, lua_upvalueindex(3));
  579. return push_captures(&ms, src, e);
  580. }
  581. }
  582. return 0; /* not found */
  583. }
  584. static int gmatch (lua_State *L) {
  585. luaL_checkstring(L, 1);
  586. luaL_checkstring(L, 2);
  587. lua_settop(L, 2);
  588. lua_pushinteger(L, 0);
  589. lua_pushcclosure(L, gmatch_aux, 3);
  590. return 1;
  591. }
  592. static void add_s (MatchState *ms, luaL_Buffer *b, const char *s,
  593. const char *e) {
  594. size_t l, i;
  595. lua_State *L = ms->L;
  596. const char *news = lua_tolstring(L, 3, &l);
  597. for (i = 0; i < l; i++) {
  598. if (news[i] != L_ESC)
  599. luaL_addchar(b, news[i]);
  600. else {
  601. i++; /* skip ESC */
  602. if (!isdigit(uchar(news[i]))) {
  603. if (news[i] != L_ESC)
  604. luaL_error(L, "invalid use of " LUA_QL("%c")
  605. " in replacement string", L_ESC);
  606. luaL_addchar(b, news[i]);
  607. }
  608. else if (news[i] == '0')
  609. luaL_addlstring(b, s, e - s);
  610. else {
  611. push_onecapture(ms, news[i] - '1', s, e);
  612. luaL_tolstring(L, -1, NULL); /* if number, convert it to string */
  613. lua_remove(L, -2); /* remove original value */
  614. luaL_addvalue(b); /* add capture to accumulated result */
  615. }
  616. }
  617. }
  618. }
  619. static void add_value (MatchState *ms, luaL_Buffer *b, const char *s,
  620. const char *e, int tr) {
  621. lua_State *L = ms->L;
  622. switch (tr) {
  623. case LUA_TFUNCTION: {
  624. int n;
  625. lua_pushvalue(L, 3);
  626. n = push_captures(ms, s, e);
  627. lua_call(L, n, 1);
  628. break;
  629. }
  630. case LUA_TTABLE: {
  631. push_onecapture(ms, 0, s, e);
  632. lua_gettable(L, 3);
  633. break;
  634. }
  635. default: { /* LUA_TNUMBER or LUA_TSTRING */
  636. add_s(ms, b, s, e);
  637. return;
  638. }
  639. }
  640. if (!lua_toboolean(L, -1)) { /* nil or false? */
  641. lua_pop(L, 1);
  642. lua_pushlstring(L, s, e - s); /* keep original text */
  643. }
  644. else if (!lua_isstring(L, -1))
  645. luaL_error(L, "invalid replacement value (a %s)", luaL_typename(L, -1));
  646. luaL_addvalue(b); /* add result to accumulator */
  647. }
  648. static int str_gsub (lua_State *L) {
  649. size_t srcl, lp;
  650. const char *src = luaL_checklstring(L, 1, &srcl);
  651. const char *p = luaL_checklstring(L, 2, &lp);
  652. int tr = lua_type(L, 3);
  653. lua_Integer max_s = luaL_optinteger(L, 4, srcl + 1);
  654. int anchor = (*p == '^');
  655. lua_Integer n = 0;
  656. MatchState ms;
  657. luaL_Buffer b;
  658. luaL_argcheck(L, tr == LUA_TNUMBER || tr == LUA_TSTRING ||
  659. tr == LUA_TFUNCTION || tr == LUA_TTABLE, 3,
  660. "string/function/table expected");
  661. luaL_buffinit(L, &b);
  662. if (anchor) {
  663. p++; lp--; /* skip anchor character */
  664. }
  665. ms.L = L;
  666. ms.matchdepth = MAXCCALLS;
  667. ms.src_init = src;
  668. ms.src_end = src+srcl;
  669. ms.p_end = p + lp;
  670. while (n < max_s) {
  671. const char *e;
  672. ms.level = 0;
  673. lua_assert(ms.matchdepth == MAXCCALLS);
  674. e = match(&ms, src, p);
  675. if (e) {
  676. n++;
  677. add_value(&ms, &b, src, e, tr);
  678. }
  679. if (e && e>src) /* non empty match? */
  680. src = e; /* skip it */
  681. else if (src < ms.src_end)
  682. luaL_addchar(&b, *src++);
  683. else break;
  684. if (anchor) break;
  685. }
  686. luaL_addlstring(&b, src, ms.src_end-src);
  687. luaL_pushresult(&b);
  688. lua_pushinteger(L, n); /* number of substitutions */
  689. return 2;
  690. }
  691. /* }====================================================== */
  692. /*
  693. ** {======================================================
  694. ** STRING FORMAT
  695. ** =======================================================
  696. */
  697. /* maximum size of each formatted item (> len(format('%99.99f', -1e308))) */
  698. #define MAX_ITEM 512
  699. /* valid flags in a format specification */
  700. #define FLAGS "-+ #0"
  701. /*
  702. ** maximum size of each format specification (such as "%-099.99d")
  703. ** (+2 for length modifiers; +10 accounts for %99.99x plus margin of error)
  704. */
  705. #define MAX_FORMAT (sizeof(FLAGS) + 2 + 10)
  706. static void addquoted (lua_State *L, luaL_Buffer *b, int arg) {
  707. size_t l;
  708. const char *s = luaL_checklstring(L, arg, &l);
  709. luaL_addchar(b, '"');
  710. while (l--) {
  711. if (*s == '"' || *s == '\\' || *s == '\n') {
  712. luaL_addchar(b, '\\');
  713. luaL_addchar(b, *s);
  714. }
  715. else if (*s == '\0' || iscntrl(uchar(*s))) {
  716. char buff[10];
  717. if (!isdigit(uchar(*(s+1))))
  718. sprintf(buff, "\\%d", (int)uchar(*s));
  719. else
  720. sprintf(buff, "\\%03d", (int)uchar(*s));
  721. luaL_addstring(b, buff);
  722. }
  723. else
  724. luaL_addchar(b, *s);
  725. s++;
  726. }
  727. luaL_addchar(b, '"');
  728. }
  729. static const char *scanformat (lua_State *L, const char *strfrmt, char *form) {
  730. const char *p = strfrmt;
  731. while (*p != '\0' && strchr(FLAGS, *p) != NULL) p++; /* skip flags */
  732. if ((size_t)(p - strfrmt) >= sizeof(FLAGS)/sizeof(char))
  733. luaL_error(L, "invalid format (repeated flags)");
  734. if (isdigit(uchar(*p))) p++; /* skip width */
  735. if (isdigit(uchar(*p))) p++; /* (2 digits at most) */
  736. if (*p == '.') {
  737. p++;
  738. if (isdigit(uchar(*p))) p++; /* skip precision */
  739. if (isdigit(uchar(*p))) p++; /* (2 digits at most) */
  740. }
  741. if (isdigit(uchar(*p)))
  742. luaL_error(L, "invalid format (width or precision too long)");
  743. *(form++) = '%';
  744. memcpy(form, strfrmt, (p - strfrmt + 1) * sizeof(char));
  745. form += p - strfrmt + 1;
  746. *form = '\0';
  747. return p;
  748. }
  749. /*
  750. ** add length modifier into formats
  751. */
  752. static void addlenmod (char *form, const char *lenmod) {
  753. size_t l = strlen(form);
  754. size_t lm = strlen(lenmod);
  755. char spec = form[l - 1];
  756. strcpy(form + l - 1, lenmod);
  757. form[l + lm - 1] = spec;
  758. form[l + lm] = '\0';
  759. }
  760. static int str_format (lua_State *L) {
  761. int top = lua_gettop(L);
  762. int arg = 1;
  763. size_t sfl;
  764. const char *strfrmt = luaL_checklstring(L, arg, &sfl);
  765. const char *strfrmt_end = strfrmt+sfl;
  766. luaL_Buffer b;
  767. luaL_buffinit(L, &b);
  768. while (strfrmt < strfrmt_end) {
  769. if (*strfrmt != L_ESC)
  770. luaL_addchar(&b, *strfrmt++);
  771. else if (*++strfrmt == L_ESC)
  772. luaL_addchar(&b, *strfrmt++); /* %% */
  773. else { /* format item */
  774. char form[MAX_FORMAT]; /* to store the format (`%...') */
  775. char *buff = luaL_prepbuffsize(&b, MAX_ITEM); /* to put formatted item */
  776. int nb = 0; /* number of bytes in added item */
  777. if (++arg > top)
  778. luaL_argerror(L, arg, "no value");
  779. strfrmt = scanformat(L, strfrmt, form);
  780. switch (*strfrmt++) {
  781. case 'c': {
  782. nb = sprintf(buff, form, luaL_checkint(L, arg));
  783. break;
  784. }
  785. case 'd': case 'i':
  786. case 'o': case 'u': case 'x': case 'X': {
  787. lua_Integer n = luaL_checkinteger(L, arg);
  788. addlenmod(form, LUA_INTEGER_FRMLEN);
  789. nb = sprintf(buff, form, n);
  790. break;
  791. }
  792. case 'e': case 'E': case 'f':
  793. #if defined(LUA_USE_AFORMAT)
  794. case 'a': case 'A':
  795. #endif
  796. case 'g': case 'G': {
  797. addlenmod(form, LUA_NUMBER_FRMLEN);
  798. nb = sprintf(buff, form, luaL_checknumber(L, arg));
  799. break;
  800. }
  801. case 'q': {
  802. addquoted(L, &b, arg);
  803. break;
  804. }
  805. case 's': {
  806. size_t l;
  807. const char *s = luaL_tolstring(L, arg, &l);
  808. if (!strchr(form, '.') && l >= 100) {
  809. /* no precision and string is too long to be formatted;
  810. keep original string */
  811. luaL_addvalue(&b);
  812. break;
  813. }
  814. else {
  815. nb = sprintf(buff, form, s);
  816. lua_pop(L, 1); /* remove result from 'luaL_tolstring' */
  817. break;
  818. }
  819. }
  820. default: { /* also treat cases `pnLlh' */
  821. return luaL_error(L, "invalid option " LUA_QL("%%%c") " to "
  822. LUA_QL("format"), *(strfrmt - 1));
  823. }
  824. }
  825. luaL_addsize(&b, nb);
  826. }
  827. }
  828. luaL_pushresult(&b);
  829. return 1;
  830. }
  831. /* }====================================================== */
  832. /*
  833. ** {======================================================
  834. ** PACK/UNPACK
  835. ** =======================================================
  836. */
  837. /* number of bits in a character */
  838. #define NB CHAR_BIT
  839. /* mask for one character (NB 1's) */
  840. #define MC ((1 << NB) - 1)
  841. /* mask for one character without sign bit ((NB - 1) 1's) */
  842. #define SM (MC >> 1)
  843. /* size of a lua_Integer */
  844. #define SZINT ((int)sizeof(lua_Integer))
  845. /* maximum size for the binary representation of an integer */
  846. #define MAXINTSIZE 12
  847. static union {
  848. int dummy;
  849. char little; /* true iff machine is little endian */
  850. } const nativeendian = {1};
  851. static int getendian (lua_State *L, int arg) {
  852. const char *endian = luaL_optstring(L, arg,
  853. (nativeendian.little ? "l" : "b"));
  854. if (*endian == 'n') /* native? */
  855. return nativeendian.little;
  856. luaL_argcheck(L, *endian == 'l' || *endian == 'b', arg,
  857. "endianness must be 'l'/'b'/'n'");
  858. return (*endian == 'l');
  859. }
  860. static int getintsize (lua_State *L, int arg) {
  861. int size = luaL_optint(L, arg, 0);
  862. if (size == 0) size = SZINT;
  863. luaL_argcheck(L, 1 <= size && size <= MAXINTSIZE, arg,
  864. "integer size out of valid range");
  865. return size;
  866. }
  867. /* mask for all ones in last byte in a lua Integer */
  868. #define HIGHERBYTE ((lua_Unsigned)MC << (NB * (SZINT - 1)))
  869. static int dumpint (char *buff, lua_Integer m, int littleendian, int size) {
  870. int i;
  871. lua_Unsigned n = (lua_Unsigned)m;
  872. lua_Unsigned mask = (m >= 0) ? 0 : HIGHERBYTE; /* sign extension */
  873. if (littleendian) {
  874. for (i = 0; i < size - 1; i++) {
  875. buff[i] = (n & MC);
  876. n = (n >> NB) | mask;
  877. }
  878. }
  879. else {
  880. for (i = size - 1; i > 0; i--) {
  881. buff[i] = (n & MC);
  882. n = (n >> NB) | mask;
  883. }
  884. }
  885. buff[i] = (n & MC); /* last byte */
  886. if (size < SZINT) { /* need test for overflow? */
  887. /* OK if there are only zeros left in higher bytes,
  888. or only ones left (excluding non-signal bits in last byte) */
  889. return ((n & ~(lua_Unsigned)MC) == 0 ||
  890. (n | SM) == ~(lua_Unsigned)0);
  891. }
  892. else return 1; /* no overflow can occur with full size */
  893. }
  894. static int dumpint_l (lua_State *L) {
  895. char buff[MAXINTSIZE];
  896. lua_Integer n = luaL_checkinteger(L, 1);
  897. int size = getintsize(L, 2);
  898. int endian = getendian(L, 3);
  899. if (dumpint(buff, n, endian, size))
  900. lua_pushlstring(L, buff, size);
  901. else
  902. luaL_error(L, "integer does not fit into given size (%d)", size);
  903. return 1;
  904. }
  905. /* mask to check higher-order byte + signal bit of next (lower) byte */
  906. #define HIGHERBYTE1 (HIGHERBYTE | (HIGHERBYTE >> 1))
  907. static int undumpint (const char *buff, lua_Integer *res,
  908. int littleendian, int size) {
  909. lua_Unsigned n = 0;
  910. int i;
  911. for (i = 0; i < size; i++) {
  912. if (i >= SZINT) { /* will throw away a byte? */
  913. /* check for overflow: it is OK to throw away leading zeros for a
  914. positive number, leading ones for a negative number, and a
  915. leading zero byte to allow unsigned integers with a 1 in
  916. its "signal bit" */
  917. if (!((n & HIGHERBYTE1) == 0 || /* zeros for positive number */
  918. (n & HIGHERBYTE1) == HIGHERBYTE1 || /* ones for negative number */
  919. (i == size - 1 && (n & HIGHERBYTE) == 0))) /* leading zero */
  920. return 0; /* overflow */
  921. }
  922. n <<= NB;
  923. n |= (lua_Unsigned)(unsigned char)buff[littleendian ? size - 1 - i : i];
  924. }
  925. if (size < SZINT) { /* need sign extension? */
  926. lua_Unsigned mask = (lua_Unsigned)1 << (size*NB - 1);
  927. *res = (lua_Integer)((n ^ mask) - mask); /* do sign extension */
  928. }
  929. else
  930. *res = (lua_Integer)n;
  931. return 1;
  932. }
  933. static int undumpint_l (lua_State *L) {
  934. lua_Integer res;
  935. size_t len;
  936. const char *s = luaL_checklstring(L, 1, &len);
  937. lua_Integer pos = posrelat(luaL_optinteger(L, 2, 1), len);
  938. int size = getintsize(L, 3);
  939. int endian = getendian(L, 4);
  940. luaL_argcheck(L, 1 <= pos && (size_t)pos + size - 1 <= len, 1,
  941. "string too short");
  942. if(undumpint(s + pos - 1, &res, endian, size))
  943. lua_pushinteger(L, res);
  944. else
  945. luaL_error(L, "result does not fit into a Lua integer");
  946. return 1;
  947. }
  948. static void correctendianness (lua_State *L, char *b, int size, int endianarg) {
  949. int endian = getendian(L, endianarg);
  950. if (endian != nativeendian.little) { /* not native endianness? */
  951. int i = 0;
  952. while (i < --size) {
  953. char temp = b[i];
  954. b[i++] = b[size];
  955. b[size] = temp;
  956. }
  957. }
  958. }
  959. static int getfloatsize (lua_State *L, int arg) {
  960. const char *size = luaL_optstring(L, arg, "n");
  961. if (*size == 'n') return sizeof(lua_Number);
  962. luaL_argcheck(L, *size == 'd' || *size == 'f', arg,
  963. "size must be 'f'/'d'/'n'");
  964. return (*size == 'd' ? sizeof(double) : sizeof(float));
  965. }
  966. static int dumpfloat_l (lua_State *L) {
  967. float f; double d;
  968. char *pn; /* pointer to number */
  969. lua_Number n = luaL_checknumber(L, 1);
  970. int size = getfloatsize(L, 2);
  971. if (size == sizeof(lua_Number))
  972. pn = (char*)&n;
  973. else if (size == sizeof(float)) {
  974. f = (float)n;
  975. pn = (char*)&f;
  976. }
  977. else { /* native lua_Number may be neither float nor double */
  978. lua_assert(size == sizeof(double));
  979. d = (double)n;
  980. pn = (char*)&d;
  981. }
  982. correctendianness(L, pn, size, 3);
  983. lua_pushlstring(L, pn, size);
  984. return 1;
  985. }
  986. static int undumpfloat_l (lua_State *L) {
  987. lua_Number res;
  988. size_t len;
  989. const char *s = luaL_checklstring(L, 1, &len);
  990. lua_Integer pos = posrelat(luaL_optinteger(L, 2, 1), len);
  991. int size = getfloatsize(L, 3);
  992. luaL_argcheck(L, 1 <= pos && (size_t)pos + size - 1 <= len, 1,
  993. "string too short");
  994. if (size == sizeof(lua_Number)) {
  995. memcpy(&res, s + pos - 1, size);
  996. correctendianness(L, (char*)&res, size, 4);
  997. }
  998. else if (size == sizeof(float)) {
  999. float f;
  1000. memcpy(&f, s + pos - 1, size);
  1001. correctendianness(L, (char*)&f, size, 4);
  1002. res = (lua_Number)f;
  1003. }
  1004. else { /* native lua_Number may be neither float nor double */
  1005. double d;
  1006. lua_assert(size == sizeof(double));
  1007. memcpy(&d, s + pos - 1, size);
  1008. correctendianness(L, (char*)&d, size, 4);
  1009. res = (lua_Number)d;
  1010. }
  1011. lua_pushnumber(L, res);
  1012. return 1;
  1013. }
  1014. /* }====================================================== */
  1015. static const luaL_Reg strlib[] = {
  1016. {"byte", str_byte},
  1017. {"char", str_char},
  1018. {"dump", str_dump},
  1019. {"find", str_find},
  1020. {"format", str_format},
  1021. {"gmatch", gmatch},
  1022. {"gsub", str_gsub},
  1023. {"len", str_len},
  1024. {"lower", str_lower},
  1025. {"match", str_match},
  1026. {"rep", str_rep},
  1027. {"reverse", str_reverse},
  1028. {"sub", str_sub},
  1029. {"upper", str_upper},
  1030. {"dumpfloat", dumpfloat_l},
  1031. {"dumpint", dumpint_l},
  1032. {"undumpfloat", undumpfloat_l},
  1033. {"undumpint", undumpint_l},
  1034. {NULL, NULL}
  1035. };
  1036. static void createmetatable (lua_State *L) {
  1037. lua_createtable(L, 0, 1); /* table to be metatable for strings */
  1038. lua_pushliteral(L, ""); /* dummy string */
  1039. lua_pushvalue(L, -2); /* copy table */
  1040. lua_setmetatable(L, -2); /* set table as metatable for strings */
  1041. lua_pop(L, 1); /* pop dummy string */
  1042. lua_pushvalue(L, -2); /* get string library */
  1043. lua_setfield(L, -2, "__index"); /* metatable.__index = string */
  1044. lua_pop(L, 1); /* pop metatable */
  1045. }
  1046. /*
  1047. ** Open string library
  1048. */
  1049. LUAMOD_API int luaopen_string (lua_State *L) {
  1050. luaL_newlib(L, strlib);
  1051. createmetatable(L);
  1052. return 1;
  1053. }