lstrlib.c 22 KB

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