PageRenderTime 23ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 1ms

/ports/dingux/tags/v3-20101128/Source_Files/Lua/lstrlib.c

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