2
0

lstrlib.c 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829
  1. /*
  2. ** $Id: lstrlib.c,v 1.122 2005/08/15 14:12:32 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 <stddef.h>
  8. #include <stdio.h>
  9. #include <stdlib.h>
  10. #include <string.h>
  11. #define lstrlib_c
  12. #define LUA_LIB
  13. #include "lua.h"
  14. #include "lauxlib.h"
  15. #include "lualib.h"
  16. /* macro to `unsign' a character */
  17. #define uchar(c) ((unsigned char)(c))
  18. static int str_len (lua_State *L) {
  19. size_t l;
  20. luaL_checklstring(L, 1, &l);
  21. lua_pushinteger(L, l);
  22. return 1;
  23. }
  24. static ptrdiff_t posrelat (ptrdiff_t pos, size_t len) {
  25. /* relative string position: negative means back from end */
  26. return (pos>=0) ? pos : (ptrdiff_t)len+pos+1;
  27. }
  28. static int str_sub (lua_State *L) {
  29. size_t l;
  30. const char *s = luaL_checklstring(L, 1, &l);
  31. ptrdiff_t start = posrelat(luaL_checkinteger(L, 2), l);
  32. ptrdiff_t end = posrelat(luaL_optinteger(L, 3, -1), l);
  33. if (start < 1) start = 1;
  34. if (end > (ptrdiff_t)l) end = (ptrdiff_t)l;
  35. if (start <= end)
  36. lua_pushlstring(L, s+start-1, end-start+1);
  37. else lua_pushliteral(L, "");
  38. return 1;
  39. }
  40. static int str_reverse (lua_State *L) {
  41. size_t l;
  42. luaL_Buffer b;
  43. const char *s = luaL_checklstring(L, 1, &l);
  44. luaL_buffinit(L, &b);
  45. while (l--) luaL_addchar(&b, s[l]);
  46. luaL_pushresult(&b);
  47. return 1;
  48. }
  49. static int str_lower (lua_State *L) {
  50. size_t l;
  51. size_t i;
  52. luaL_Buffer b;
  53. const char *s = luaL_checklstring(L, 1, &l);
  54. luaL_buffinit(L, &b);
  55. for (i=0; i<l; i++)
  56. luaL_addchar(&b, tolower(uchar(s[i])));
  57. luaL_pushresult(&b);
  58. return 1;
  59. }
  60. static int str_upper (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. luaL_buffinit(L, &b);
  66. for (i=0; i<l; i++)
  67. luaL_addchar(&b, toupper(uchar(s[i])));
  68. luaL_pushresult(&b);
  69. return 1;
  70. }
  71. static int str_rep (lua_State *L) {
  72. size_t l;
  73. luaL_Buffer b;
  74. const char *s = luaL_checklstring(L, 1, &l);
  75. int n = luaL_checkint(L, 2);
  76. luaL_buffinit(L, &b);
  77. while (n-- > 0)
  78. luaL_addlstring(&b, s, l);
  79. luaL_pushresult(&b);
  80. return 1;
  81. }
  82. static int str_byte (lua_State *L) {
  83. size_t l;
  84. const char *s = luaL_checklstring(L, 1, &l);
  85. ptrdiff_t posi = posrelat(luaL_optinteger(L, 2, 1), l);
  86. ptrdiff_t pose = posrelat(luaL_optinteger(L, 3, posi), l);
  87. int n, i;
  88. if (posi <= 0) posi = 1;
  89. if ((size_t)pose > l) pose = l;
  90. if (posi > pose) return 0; /* empty interval; return no values */
  91. n = pose - posi + 1;
  92. luaL_checkstack(L, n, "string slice too long");
  93. for (i=0; i<n; i++)
  94. lua_pushinteger(L, uchar(s[posi+i-1]));
  95. return n;
  96. }
  97. static int str_char (lua_State *L) {
  98. int n = lua_gettop(L); /* number of arguments */
  99. int i;
  100. luaL_Buffer b;
  101. luaL_buffinit(L, &b);
  102. for (i=1; i<=n; i++) {
  103. int c = luaL_checkint(L, i);
  104. luaL_argcheck(L, uchar(c) == c, i, "invalid value");
  105. luaL_addchar(&b, uchar(c));
  106. }
  107. luaL_pushresult(&b);
  108. return 1;
  109. }
  110. static int writer (lua_State *L, const void* b, size_t size, void* B) {
  111. (void)L;
  112. luaL_addlstring((luaL_Buffer*) B, (const char *)b, size);
  113. return 0;
  114. }
  115. static int str_dump (lua_State *L) {
  116. luaL_Buffer b;
  117. luaL_checktype(L, 1, LUA_TFUNCTION);
  118. lua_settop(L, 1);
  119. luaL_buffinit(L,&b);
  120. if (lua_dump(L, writer, &b) != 0)
  121. luaL_error(L, "unable to dump given function");
  122. luaL_pushresult(&b);
  123. return 1;
  124. }
  125. /*
  126. ** {======================================================
  127. ** PATTERN MATCHING
  128. ** =======================================================
  129. */
  130. #define CAP_UNFINISHED (-1)
  131. #define CAP_POSITION (-2)
  132. typedef struct MatchState {
  133. const char *src_init; /* init of source string */
  134. const char *src_end; /* end (`\0') of source string */
  135. lua_State *L;
  136. int level; /* total number of captures (finished or unfinished) */
  137. struct {
  138. const char *init;
  139. ptrdiff_t len;
  140. } capture[LUA_MAXCAPTURES];
  141. } MatchState;
  142. #define L_ESC '%'
  143. #define SPECIALS "^$*+?.([%-"
  144. static int check_capture (MatchState *ms, int l) {
  145. l -= '1';
  146. if (l < 0 || l >= ms->level || ms->capture[l].len == CAP_UNFINISHED)
  147. return luaL_error(ms->L, "invalid capture index");
  148. return l;
  149. }
  150. static int capture_to_close (MatchState *ms) {
  151. int level = ms->level;
  152. for (level--; level>=0; level--)
  153. if (ms->capture[level].len == CAP_UNFINISHED) return level;
  154. return luaL_error(ms->L, "invalid pattern capture");
  155. }
  156. static const char *classend (MatchState *ms, const char *p) {
  157. switch (*p++) {
  158. case L_ESC: {
  159. if (*p == '\0')
  160. luaL_error(ms->L, "malformed pattern (ends with " LUA_QL("%%") ")");
  161. return p+1;
  162. }
  163. case '[': {
  164. if (*p == '^') p++;
  165. do { /* look for a `]' */
  166. if (*p == '\0')
  167. luaL_error(ms->L, "malformed pattern (missing " LUA_QL("]") ")");
  168. if (*(p++) == L_ESC && *p != '\0')
  169. p++; /* skip escapes (e.g. `%]') */
  170. } while (*p != ']');
  171. return p+1;
  172. }
  173. default: {
  174. return p;
  175. }
  176. }
  177. }
  178. static int match_class (int c, int cl) {
  179. int res;
  180. switch (tolower(cl)) {
  181. case 'a' : res = isalpha(c); break;
  182. case 'c' : res = iscntrl(c); break;
  183. case 'd' : res = isdigit(c); break;
  184. case 'l' : res = islower(c); break;
  185. case 'p' : res = ispunct(c); break;
  186. case 's' : res = isspace(c); break;
  187. case 'u' : res = isupper(c); break;
  188. case 'w' : res = isalnum(c); break;
  189. case 'x' : res = isxdigit(c); break;
  190. case 'z' : res = (c == 0); break;
  191. default: return (cl == c);
  192. }
  193. return (islower(cl) ? res : !res);
  194. }
  195. static int matchbracketclass (int c, const char *p, const char *ec) {
  196. int sig = 1;
  197. if (*(p+1) == '^') {
  198. sig = 0;
  199. p++; /* skip the `^' */
  200. }
  201. while (++p < ec) {
  202. if (*p == L_ESC) {
  203. p++;
  204. if (match_class(c, uchar(*p)))
  205. return sig;
  206. }
  207. else if ((*(p+1) == '-') && (p+2 < ec)) {
  208. p+=2;
  209. if (uchar(*(p-2)) <= c && c <= uchar(*p))
  210. return sig;
  211. }
  212. else if (uchar(*p) == c) return sig;
  213. }
  214. return !sig;
  215. }
  216. static int singlematch (int c, const char *p, const char *ep) {
  217. switch (*p) {
  218. case '.': return 1; /* matches any char */
  219. case L_ESC: return match_class(c, uchar(*(p+1)));
  220. case '[': return matchbracketclass(c, p, ep-1);
  221. default: return (uchar(*p) == c);
  222. }
  223. }
  224. static const char *match (MatchState *ms, const char *s, const char *p);
  225. static const char *matchbalance (MatchState *ms, const char *s,
  226. const char *p) {
  227. if (*p == 0 || *(p+1) == 0)
  228. luaL_error(ms->L, "unbalanced pattern");
  229. if (*s != *p) return NULL;
  230. else {
  231. int b = *p;
  232. int e = *(p+1);
  233. int cont = 1;
  234. while (++s < ms->src_end) {
  235. if (*s == e) {
  236. if (--cont == 0) return s+1;
  237. }
  238. else if (*s == b) cont++;
  239. }
  240. }
  241. return NULL; /* string ends out of balance */
  242. }
  243. static const char *max_expand (MatchState *ms, const char *s,
  244. const char *p, const char *ep) {
  245. ptrdiff_t i = 0; /* counts maximum expand for item */
  246. while ((s+i)<ms->src_end && singlematch(uchar(*(s+i)), p, ep))
  247. i++;
  248. /* keeps trying to match with the maximum repetitions */
  249. while (i>=0) {
  250. const char *res = match(ms, (s+i), ep+1);
  251. if (res) return res;
  252. i--; /* else didn't match; reduce 1 repetition to try again */
  253. }
  254. return NULL;
  255. }
  256. static const char *min_expand (MatchState *ms, const char *s,
  257. const char *p, const char *ep) {
  258. for (;;) {
  259. const char *res = match(ms, s, ep+1);
  260. if (res != NULL)
  261. return res;
  262. else if (s<ms->src_end && singlematch(uchar(*s), p, ep))
  263. s++; /* try with one more repetition */
  264. else return NULL;
  265. }
  266. }
  267. static const char *start_capture (MatchState *ms, const char *s,
  268. const char *p, int what) {
  269. const char *res;
  270. int level = ms->level;
  271. if (level >= LUA_MAXCAPTURES) luaL_error(ms->L, "too many captures");
  272. ms->capture[level].init = s;
  273. ms->capture[level].len = what;
  274. ms->level = level+1;
  275. if ((res=match(ms, s, p)) == NULL) /* match failed? */
  276. ms->level--; /* undo capture */
  277. return res;
  278. }
  279. static const char *end_capture (MatchState *ms, const char *s,
  280. const char *p) {
  281. int l = capture_to_close(ms);
  282. const char *res;
  283. ms->capture[l].len = s - ms->capture[l].init; /* close capture */
  284. if ((res = match(ms, s, p)) == NULL) /* match failed? */
  285. ms->capture[l].len = CAP_UNFINISHED; /* undo capture */
  286. return res;
  287. }
  288. static const char *match_capture (MatchState *ms, const char *s, int l) {
  289. size_t len;
  290. l = check_capture(ms, l);
  291. len = ms->capture[l].len;
  292. if ((size_t)(ms->src_end-s) >= len &&
  293. memcmp(ms->capture[l].init, s, len) == 0)
  294. return s+len;
  295. else return NULL;
  296. }
  297. static const char *match (MatchState *ms, const char *s, const char *p) {
  298. init: /* using goto's to optimize tail recursion */
  299. switch (*p) {
  300. case '(': { /* start capture */
  301. if (*(p+1) == ')') /* position capture? */
  302. return start_capture(ms, s, p+2, CAP_POSITION);
  303. else
  304. return start_capture(ms, s, p+1, CAP_UNFINISHED);
  305. }
  306. case ')': { /* end capture */
  307. return end_capture(ms, s, p+1);
  308. }
  309. case L_ESC: {
  310. switch (*(p+1)) {
  311. case 'b': { /* balanced string? */
  312. s = matchbalance(ms, s, p+2);
  313. if (s == NULL) return NULL;
  314. p+=4; goto init; /* else return match(ms, s, p+4); */
  315. }
  316. case 'f': { /* frontier? */
  317. const char *ep; char previous;
  318. p += 2;
  319. if (*p != '[')
  320. luaL_error(ms->L, "missing " LUA_QL("[") " after "
  321. LUA_QL("%%f") " in pattern");
  322. ep = classend(ms, p); /* points to what is next */
  323. previous = (s == ms->src_init) ? '\0' : *(s-1);
  324. if (matchbracketclass(uchar(previous), p, ep-1) ||
  325. !matchbracketclass(uchar(*s), p, ep-1)) return NULL;
  326. p=ep; goto init; /* else return match(ms, s, ep); */
  327. }
  328. default: {
  329. if (isdigit(uchar(*(p+1)))) { /* capture results (%0-%9)? */
  330. s = match_capture(ms, s, uchar(*(p+1)));
  331. if (s == NULL) return NULL;
  332. p+=2; goto init; /* else return match(ms, s, p+2) */
  333. }
  334. goto dflt; /* case default */
  335. }
  336. }
  337. }
  338. case '\0': { /* end of pattern */
  339. return s; /* match succeeded */
  340. }
  341. case '$': {
  342. if (*(p+1) == '\0') /* is the `$' the last char in pattern? */
  343. return (s == ms->src_end) ? s : NULL; /* check end of string */
  344. else goto dflt;
  345. }
  346. default: dflt: { /* it is a pattern item */
  347. const char *ep = classend(ms, p); /* points to what is next */
  348. int m = s<ms->src_end && singlematch(uchar(*s), p, ep);
  349. switch (*ep) {
  350. case '?': { /* optional */
  351. const char *res;
  352. if (m && ((res=match(ms, s+1, ep+1)) != NULL))
  353. return res;
  354. p=ep+1; goto init; /* else return match(ms, s, ep+1); */
  355. }
  356. case '*': { /* 0 or more repetitions */
  357. return max_expand(ms, s, p, ep);
  358. }
  359. case '+': { /* 1 or more repetitions */
  360. return (m ? max_expand(ms, s+1, p, ep) : NULL);
  361. }
  362. case '-': { /* 0 or more repetitions (minimum) */
  363. return min_expand(ms, s, p, ep);
  364. }
  365. default: {
  366. if (!m) return NULL;
  367. s++; p=ep; goto init; /* else return match(ms, s+1, ep); */
  368. }
  369. }
  370. }
  371. }
  372. }
  373. static const char *lmemfind (const char *s1, size_t l1,
  374. const char *s2, size_t l2) {
  375. if (l2 == 0) return s1; /* empty strings are everywhere */
  376. else if (l2 > l1) return NULL; /* avoids a negative `l1' */
  377. else {
  378. const char *init; /* to search for a `*s2' inside `s1' */
  379. l2--; /* 1st char will be checked by `memchr' */
  380. l1 = l1-l2; /* `s2' cannot be found after that */
  381. while (l1 > 0 && (init = (const char *)memchr(s1, *s2, l1)) != NULL) {
  382. init++; /* 1st char is already checked */
  383. if (memcmp(init, s2+1, l2) == 0)
  384. return init-1;
  385. else { /* correct `l1' and `s1' to try again */
  386. l1 -= init-s1;
  387. s1 = init;
  388. }
  389. }
  390. return NULL; /* not found */
  391. }
  392. }
  393. static void push_onecapture (MatchState *ms, int i) {
  394. ptrdiff_t l = ms->capture[i].len;
  395. if (l == CAP_UNFINISHED) luaL_error(ms->L, "unfinished capture");
  396. if (l == CAP_POSITION)
  397. lua_pushinteger(ms->L, ms->capture[i].init - ms->src_init + 1);
  398. else
  399. lua_pushlstring(ms->L, ms->capture[i].init, l);
  400. }
  401. static int push_captures (MatchState *ms, const char *s, const char *e) {
  402. int i;
  403. luaL_checkstack(ms->L, ms->level, "too many captures");
  404. if (ms->level == 0 && s) { /* no explicit captures? */
  405. lua_pushlstring(ms->L, s, e-s); /* return whole match */
  406. return 1;
  407. }
  408. else { /* return all captures */
  409. for (i=0; i<ms->level; i++)
  410. push_onecapture(ms, i);
  411. return ms->level; /* number of strings pushed */
  412. }
  413. }
  414. static int str_find_aux (lua_State *L, int find) {
  415. size_t l1, l2;
  416. const char *s = luaL_checklstring(L, 1, &l1);
  417. const char *p = luaL_checklstring(L, 2, &l2);
  418. ptrdiff_t init = posrelat(luaL_optinteger(L, 3, 1), l1) - 1;
  419. if (init < 0) init = 0;
  420. else if ((size_t)(init) > l1) init = (ptrdiff_t)l1;
  421. if (find && (lua_toboolean(L, 4) || /* explicit request? */
  422. strpbrk(p, SPECIALS) == NULL)) { /* or no special characters? */
  423. /* do a plain search */
  424. const char *s2 = lmemfind(s+init, l1-init, p, l2);
  425. if (s2) {
  426. lua_pushinteger(L, s2-s+1);
  427. lua_pushinteger(L, s2-s+l2);
  428. return 2;
  429. }
  430. }
  431. else {
  432. MatchState ms;
  433. int anchor = (*p == '^') ? (p++, 1) : 0;
  434. const char *s1=s+init;
  435. ms.L = L;
  436. ms.src_init = s;
  437. ms.src_end = s+l1;
  438. do {
  439. const char *res;
  440. ms.level = 0;
  441. if ((res=match(&ms, s1, p)) != NULL) {
  442. if (find) {
  443. lua_pushinteger(L, s1-s+1); /* start */
  444. lua_pushinteger(L, res-s); /* end */
  445. #if defined(LUA_COMPAT_FIND)
  446. return push_captures(&ms, NULL, 0) + 2;
  447. #else
  448. return 2;
  449. #endif
  450. }
  451. else
  452. return push_captures(&ms, s1, res);
  453. }
  454. } while (s1++ < ms.src_end && !anchor);
  455. }
  456. lua_pushnil(L); /* not found */
  457. return 1;
  458. }
  459. static int str_find (lua_State *L) {
  460. return str_find_aux(L, 1);
  461. }
  462. static int str_match (lua_State *L) {
  463. return str_find_aux(L, 0);
  464. }
  465. static int gmatch_aux (lua_State *L) {
  466. MatchState ms;
  467. size_t ls;
  468. const char *s = lua_tolstring(L, lua_upvalueindex(1), &ls);
  469. const char *p = lua_tostring(L, lua_upvalueindex(2));
  470. const char *src;
  471. ms.L = L;
  472. ms.src_init = s;
  473. ms.src_end = s+ls;
  474. for (src = s + (size_t)lua_tointeger(L, lua_upvalueindex(3));
  475. src <= ms.src_end;
  476. src++) {
  477. const char *e;
  478. ms.level = 0;
  479. if ((e = match(&ms, src, p)) != NULL) {
  480. lua_Integer newstart = e-s;
  481. if (e == src) newstart++; /* empty match? go at least one position */
  482. lua_pushinteger(L, newstart);
  483. lua_replace(L, lua_upvalueindex(3));
  484. return push_captures(&ms, src, e);
  485. }
  486. }
  487. return 0; /* not found */
  488. }
  489. static int gmatch (lua_State *L) {
  490. luaL_checkstring(L, 1);
  491. luaL_checkstring(L, 2);
  492. lua_settop(L, 2);
  493. lua_pushinteger(L, 0);
  494. lua_pushcclosure(L, gmatch_aux, 3);
  495. return 1;
  496. }
  497. static int gfind_nodef (lua_State *L) {
  498. return luaL_error(L, LUA_QL("string.gfind") " was renamed to "
  499. LUA_QL("string.gmatch"));
  500. }
  501. static void add_s (MatchState *ms, luaL_Buffer *b,
  502. const char *s, const char *e) {
  503. lua_State *L = ms->L;
  504. if (lua_isstring(L, 3)) {
  505. size_t l;
  506. const char *news = lua_tolstring(L, 3, &l);
  507. size_t i;
  508. for (i=0; i<l; i++) {
  509. if (news[i] != L_ESC)
  510. luaL_addchar(b, news[i]);
  511. else {
  512. i++; /* skip ESC */
  513. if (!isdigit(uchar(news[i])))
  514. luaL_addchar(b, news[i]);
  515. else {
  516. if (news[i] == '0')
  517. lua_pushlstring(L, s, e - s); /* add whole match */
  518. else {
  519. int level = check_capture(ms, news[i]);
  520. push_onecapture(ms, level);
  521. }
  522. luaL_addvalue(b); /* add capture to accumulated result */
  523. }
  524. }
  525. }
  526. }
  527. else { /* is a function */
  528. int n;
  529. lua_pushvalue(L, 3);
  530. n = push_captures(ms, s, e);
  531. lua_call(L, n, 1);
  532. if (lua_isstring(L, -1))
  533. luaL_addvalue(b); /* add return to accumulated result */
  534. else
  535. lua_pop(L, 1); /* function result is not a string: pop it */
  536. }
  537. }
  538. static int str_gsub (lua_State *L) {
  539. size_t srcl;
  540. const char *src = luaL_checklstring(L, 1, &srcl);
  541. const char *p = luaL_checkstring(L, 2);
  542. int max_s = luaL_optint(L, 4, srcl+1);
  543. int anchor = (*p == '^') ? (p++, 1) : 0;
  544. int n = 0;
  545. MatchState ms;
  546. luaL_Buffer b;
  547. luaL_argcheck(L,
  548. lua_gettop(L) >= 3 && (lua_isstring(L, 3) || lua_isfunction(L, 3)),
  549. 3, "string or function expected");
  550. luaL_buffinit(L, &b);
  551. ms.L = L;
  552. ms.src_init = src;
  553. ms.src_end = src+srcl;
  554. while (n < max_s) {
  555. const char *e;
  556. ms.level = 0;
  557. e = match(&ms, src, p);
  558. if (e) {
  559. n++;
  560. add_s(&ms, &b, src, e);
  561. }
  562. if (e && e>src) /* non empty match? */
  563. src = e; /* skip it */
  564. else if (src < ms.src_end)
  565. luaL_addchar(&b, *src++);
  566. else break;
  567. if (anchor) break;
  568. }
  569. luaL_addlstring(&b, src, ms.src_end-src);
  570. luaL_pushresult(&b);
  571. lua_pushinteger(L, n); /* number of substitutions */
  572. return 2;
  573. }
  574. /* }====================================================== */
  575. /* maximum size of each formatted item (> len(format('%99.99f', -1e308))) */
  576. #define MAX_ITEM 512
  577. /* maximum size of each format specification (such as '%-099.99d') */
  578. #define MAX_FORMAT 20
  579. static void addquoted (lua_State *L, luaL_Buffer *b, int arg) {
  580. size_t l;
  581. const char *s = luaL_checklstring(L, arg, &l);
  582. luaL_addchar(b, '"');
  583. while (l--) {
  584. switch (*s) {
  585. case '"': case '\\': case '\n': {
  586. luaL_addchar(b, '\\');
  587. luaL_addchar(b, *s);
  588. break;
  589. }
  590. case '\0': {
  591. luaL_addlstring(b, "\\000", 4);
  592. break;
  593. }
  594. default: {
  595. luaL_addchar(b, *s);
  596. break;
  597. }
  598. }
  599. s++;
  600. }
  601. luaL_addchar(b, '"');
  602. }
  603. static const char *scanformat (lua_State *L, const char *strfrmt,
  604. char *form, int *hasprecision) {
  605. const char *p = strfrmt;
  606. while (strchr("-+ #0", *p)) p++; /* skip flags */
  607. if (isdigit(uchar(*p))) p++; /* skip width */
  608. if (isdigit(uchar(*p))) p++; /* (2 digits at most) */
  609. if (*p == '.') {
  610. p++;
  611. *hasprecision = 1;
  612. if (isdigit(uchar(*p))) p++; /* skip precision */
  613. if (isdigit(uchar(*p))) p++; /* (2 digits at most) */
  614. }
  615. if (isdigit(uchar(*p)))
  616. luaL_error(L, "invalid format (width or precision too long)");
  617. if (p-strfrmt+2 > MAX_FORMAT) /* +2 to include `%' and the specifier */
  618. luaL_error(L, "invalid format (too long)");
  619. form[0] = L_ESC;
  620. strncpy(form+1, strfrmt, p-strfrmt+1);
  621. form[p-strfrmt+2] = 0;
  622. return p;
  623. }
  624. static int str_format (lua_State *L) {
  625. int arg = 1;
  626. size_t sfl;
  627. const char *strfrmt = luaL_checklstring(L, arg, &sfl);
  628. const char *strfrmt_end = strfrmt+sfl;
  629. luaL_Buffer b;
  630. luaL_buffinit(L, &b);
  631. while (strfrmt < strfrmt_end) {
  632. if (*strfrmt != L_ESC)
  633. luaL_addchar(&b, *strfrmt++);
  634. else if (*++strfrmt == L_ESC)
  635. luaL_addchar(&b, *strfrmt++); /* %% */
  636. else { /* format item */
  637. char form[MAX_FORMAT]; /* to store the format (`%...') */
  638. char buff[MAX_ITEM]; /* to store the formatted item */
  639. int hasprecision = 0;
  640. arg++;
  641. strfrmt = scanformat(L, strfrmt, form, &hasprecision);
  642. switch (*strfrmt++) {
  643. case 'c': case 'd': case 'i': {
  644. sprintf(buff, form, luaL_checkint(L, arg));
  645. break;
  646. }
  647. case 'o': case 'u': case 'x': case 'X': {
  648. sprintf(buff, form, (unsigned int)(luaL_checknumber(L, arg)));
  649. break;
  650. }
  651. case 'e': case 'E': case 'f':
  652. case 'g': case 'G': {
  653. sprintf(buff, form, luaL_checknumber(L, arg));
  654. break;
  655. }
  656. case 'q': {
  657. addquoted(L, &b, arg);
  658. continue; /* skip the 'addsize' at the end */
  659. }
  660. case 's': {
  661. size_t l;
  662. const char *s = luaL_checklstring(L, arg, &l);
  663. if (!hasprecision && l >= 100) {
  664. /* no precision and string is too long to be formatted;
  665. keep original string */
  666. lua_pushvalue(L, arg);
  667. luaL_addvalue(&b);
  668. continue; /* skip the `addsize' at the end */
  669. }
  670. else {
  671. sprintf(buff, form, s);
  672. break;
  673. }
  674. }
  675. default: { /* also treat cases `pnLlh' */
  676. return luaL_error(L, "invalid option to " LUA_QL("format"));
  677. }
  678. }
  679. luaL_addlstring(&b, buff, strlen(buff));
  680. }
  681. }
  682. luaL_pushresult(&b);
  683. return 1;
  684. }
  685. static const luaL_Reg strlib[] = {
  686. {"byte", str_byte},
  687. {"char", str_char},
  688. {"dump", str_dump},
  689. {"find", str_find},
  690. {"format", str_format},
  691. {"gfind", gfind_nodef},
  692. {"gmatch", gmatch},
  693. {"gsub", str_gsub},
  694. {"len", str_len},
  695. {"lower", str_lower},
  696. {"match", str_match},
  697. {"rep", str_rep},
  698. {"reverse", str_reverse},
  699. {"sub", str_sub},
  700. {"upper", str_upper},
  701. {NULL, NULL}
  702. };
  703. static void createmetatable (lua_State *L) {
  704. lua_newtable(L); /* create metatable for strings */
  705. lua_pushliteral(L, ""); /* dummy string */
  706. lua_pushvalue(L, -2);
  707. lua_setmetatable(L, -2); /* set string metatable */
  708. lua_pop(L, 1); /* pop dummy string */
  709. lua_pushvalue(L, -2); /* string library... */
  710. lua_setfield(L, -2, "__index"); /* ...is the __index metamethod */
  711. lua_pop(L, 1); /* pop metatable */
  712. }
  713. /*
  714. ** Open string library
  715. */
  716. LUALIB_API int luaopen_string (lua_State *L) {
  717. luaL_register(L, LUA_STRLIBNAME, strlib);
  718. #if defined(LUA_COMPAT_GFIND)
  719. lua_getfield(L, -1, "gmatch");
  720. lua_setfield(L, -2, "gfind");
  721. #endif
  722. createmetatable(L);
  723. return 1;
  724. }