lstrlib.c 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803
  1. /*
  2. ** $Id: lstrlib.c $
  3. ** Standard library for string operations and pattern-matching
  4. ** See Copyright Notice in lua.h
  5. */
  6. #define lstrlib_c
  7. #define LUA_LIB
  8. #include "lprefix.h"
  9. #include <ctype.h>
  10. #include <float.h>
  11. #include <limits.h>
  12. #include <locale.h>
  13. #include <math.h>
  14. #include <stddef.h>
  15. #include <stdio.h>
  16. #include <stdlib.h>
  17. #include <string.h>
  18. #include "lua.h"
  19. #include "lauxlib.h"
  20. #include "lualib.h"
  21. /*
  22. ** maximum number of captures that a pattern can do during
  23. ** pattern-matching. This limit is arbitrary, but must fit in
  24. ** an unsigned char.
  25. */
  26. #if !defined(LUA_MAXCAPTURES)
  27. #define LUA_MAXCAPTURES 32
  28. #endif
  29. /* macro to 'unsign' a character */
  30. #define uchar(c) ((unsigned char)(c))
  31. /*
  32. ** Some sizes are better limited to fit in 'int', but must also fit in
  33. ** 'size_t'. (We assume that 'lua_Integer' cannot be smaller than 'int'.)
  34. */
  35. #define MAX_SIZET ((size_t)(~(size_t)0))
  36. #define MAXSIZE \
  37. (sizeof(size_t) < sizeof(int) ? MAX_SIZET : (size_t)(INT_MAX))
  38. static int str_len (lua_State *L) {
  39. size_t l;
  40. luaL_checklstring(L, 1, &l);
  41. lua_pushinteger(L, (lua_Integer)l);
  42. return 1;
  43. }
  44. /*
  45. ** translate a relative initial string position
  46. ** (negative means back from end): clip result to [1, inf).
  47. ** The length of any string in Lua must fit in a lua_Integer,
  48. ** so there are no overflows in the casts.
  49. ** The inverted comparison avoids a possible overflow
  50. ** computing '-pos'.
  51. */
  52. static size_t posrelatI (lua_Integer pos, size_t len) {
  53. if (pos > 0)
  54. return (size_t)pos;
  55. else if (pos == 0)
  56. return 1;
  57. else if (pos < -(lua_Integer)len) /* inverted comparison */
  58. return 1; /* clip to 1 */
  59. else return len + (size_t)pos + 1;
  60. }
  61. /*
  62. ** Gets an optional ending string position from argument 'arg',
  63. ** with default value 'def'.
  64. ** Negative means back from end: clip result to [0, len]
  65. */
  66. static size_t getendpos (lua_State *L, int arg, lua_Integer def,
  67. size_t len) {
  68. lua_Integer pos = luaL_optinteger(L, arg, def);
  69. if (pos > (lua_Integer)len)
  70. return len;
  71. else if (pos >= 0)
  72. return (size_t)pos;
  73. else if (pos < -(lua_Integer)len)
  74. return 0;
  75. else return len + (size_t)pos + 1;
  76. }
  77. static int str_sub (lua_State *L) {
  78. size_t l;
  79. const char *s = luaL_checklstring(L, 1, &l);
  80. size_t start = posrelatI(luaL_checkinteger(L, 2), l);
  81. size_t end = getendpos(L, 3, -1, l);
  82. if (start <= end)
  83. lua_pushlstring(L, s + start - 1, (end - start) + 1);
  84. else lua_pushliteral(L, "");
  85. return 1;
  86. }
  87. static int str_reverse (lua_State *L) {
  88. size_t l, i;
  89. luaL_Buffer b;
  90. const char *s = luaL_checklstring(L, 1, &l);
  91. char *p = luaL_buffinitsize(L, &b, l);
  92. for (i = 0; i < l; i++)
  93. p[i] = s[l - i - 1];
  94. luaL_pushresultsize(&b, l);
  95. return 1;
  96. }
  97. static int str_lower (lua_State *L) {
  98. size_t l;
  99. size_t i;
  100. luaL_Buffer b;
  101. const char *s = luaL_checklstring(L, 1, &l);
  102. char *p = luaL_buffinitsize(L, &b, l);
  103. for (i=0; i<l; i++)
  104. p[i] = tolower(uchar(s[i]));
  105. luaL_pushresultsize(&b, l);
  106. return 1;
  107. }
  108. static int str_upper (lua_State *L) {
  109. size_t l;
  110. size_t i;
  111. luaL_Buffer b;
  112. const char *s = luaL_checklstring(L, 1, &l);
  113. char *p = luaL_buffinitsize(L, &b, l);
  114. for (i=0; i<l; i++)
  115. p[i] = toupper(uchar(s[i]));
  116. luaL_pushresultsize(&b, l);
  117. return 1;
  118. }
  119. static int str_rep (lua_State *L) {
  120. size_t l, lsep;
  121. const char *s = luaL_checklstring(L, 1, &l);
  122. lua_Integer n = luaL_checkinteger(L, 2);
  123. const char *sep = luaL_optlstring(L, 3, "", &lsep);
  124. if (n <= 0) lua_pushliteral(L, "");
  125. else if (l + lsep < l || l + lsep > MAXSIZE / n) /* may overflow? */
  126. return luaL_error(L, "resulting string too large");
  127. else {
  128. size_t totallen = (size_t)n * l + (size_t)(n - 1) * lsep;
  129. luaL_Buffer b;
  130. char *p = luaL_buffinitsize(L, &b, totallen);
  131. while (n-- > 1) { /* first n-1 copies (followed by separator) */
  132. memcpy(p, s, l * sizeof(char)); p += l;
  133. if (lsep > 0) { /* empty 'memcpy' is not that cheap */
  134. memcpy(p, sep, lsep * sizeof(char));
  135. p += lsep;
  136. }
  137. }
  138. memcpy(p, s, l * sizeof(char)); /* last copy (not followed by separator) */
  139. luaL_pushresultsize(&b, totallen);
  140. }
  141. return 1;
  142. }
  143. static int str_byte (lua_State *L) {
  144. size_t l;
  145. const char *s = luaL_checklstring(L, 1, &l);
  146. lua_Integer pi = luaL_optinteger(L, 2, 1);
  147. size_t posi = posrelatI(pi, l);
  148. size_t pose = getendpos(L, 3, pi, l);
  149. int n, i;
  150. if (posi > pose) return 0; /* empty interval; return no values */
  151. if (pose - posi >= (size_t)INT_MAX) /* arithmetic overflow? */
  152. return luaL_error(L, "string slice too long");
  153. n = (int)(pose - posi) + 1;
  154. luaL_checkstack(L, n, "string slice too long");
  155. for (i=0; i<n; i++)
  156. lua_pushinteger(L, uchar(s[posi+i-1]));
  157. return n;
  158. }
  159. static int str_char (lua_State *L) {
  160. int n = lua_gettop(L); /* number of arguments */
  161. int i;
  162. luaL_Buffer b;
  163. char *p = luaL_buffinitsize(L, &b, n);
  164. for (i=1; i<=n; i++) {
  165. lua_Unsigned c = (lua_Unsigned)luaL_checkinteger(L, i);
  166. luaL_argcheck(L, c <= (lua_Unsigned)UCHAR_MAX, i, "value out of range");
  167. p[i - 1] = uchar(c);
  168. }
  169. luaL_pushresultsize(&b, n);
  170. return 1;
  171. }
  172. /*
  173. ** Buffer to store the result of 'string.dump'. It must be initialized
  174. ** after the call to 'lua_dump', to ensure that the function is on the
  175. ** top of the stack when 'lua_dump' is called. ('luaL_buffinit' might
  176. ** push stuff.)
  177. */
  178. struct str_Writer {
  179. int init; /* true iff buffer has been initialized */
  180. luaL_Buffer B;
  181. };
  182. static int writer (lua_State *L, const void *b, size_t size, void *ud) {
  183. struct str_Writer *state = (struct str_Writer *)ud;
  184. if (!state->init) {
  185. state->init = 1;
  186. luaL_buffinit(L, &state->B);
  187. }
  188. luaL_addlstring(&state->B, (const char *)b, size);
  189. return 0;
  190. }
  191. static int str_dump (lua_State *L) {
  192. struct str_Writer state;
  193. int strip = lua_toboolean(L, 2);
  194. luaL_checktype(L, 1, LUA_TFUNCTION);
  195. lua_settop(L, 1); /* ensure function is on the top of the stack */
  196. state.init = 0;
  197. if (lua_dump(L, writer, &state, strip) != 0)
  198. return luaL_error(L, "unable to dump given function");
  199. luaL_pushresult(&state.B);
  200. return 1;
  201. }
  202. /*
  203. ** {======================================================
  204. ** METAMETHODS
  205. ** =======================================================
  206. */
  207. #if defined(LUA_NOCVTS2N) /* { */
  208. /* no coercion from strings to numbers */
  209. static const luaL_Reg stringmetamethods[] = {
  210. {"__index", NULL}, /* placeholder */
  211. {NULL, NULL}
  212. };
  213. #else /* }{ */
  214. static int tonum (lua_State *L, int arg) {
  215. if (lua_type(L, arg) == LUA_TNUMBER) { /* already a number? */
  216. lua_pushvalue(L, arg);
  217. return 1;
  218. }
  219. else { /* check whether it is a numerical string */
  220. size_t len;
  221. const char *s = lua_tolstring(L, arg, &len);
  222. return (s != NULL && lua_stringtonumber(L, s) == len + 1);
  223. }
  224. }
  225. static void trymt (lua_State *L, const char *mtname) {
  226. lua_settop(L, 2); /* back to the original arguments */
  227. if (lua_type(L, 2) == LUA_TSTRING || !luaL_getmetafield(L, 2, mtname))
  228. luaL_error(L, "attempt to %s a '%s' with a '%s'", mtname + 2,
  229. luaL_typename(L, -2), luaL_typename(L, -1));
  230. lua_insert(L, -3); /* put metamethod before arguments */
  231. lua_call(L, 2, 1); /* call metamethod */
  232. }
  233. static int arith (lua_State *L, int op, const char *mtname) {
  234. if (tonum(L, 1) && tonum(L, 2))
  235. lua_arith(L, op); /* result will be on the top */
  236. else
  237. trymt(L, mtname);
  238. return 1;
  239. }
  240. static int arith_add (lua_State *L) {
  241. return arith(L, LUA_OPADD, "__add");
  242. }
  243. static int arith_sub (lua_State *L) {
  244. return arith(L, LUA_OPSUB, "__sub");
  245. }
  246. static int arith_mul (lua_State *L) {
  247. return arith(L, LUA_OPMUL, "__mul");
  248. }
  249. static int arith_mod (lua_State *L) {
  250. return arith(L, LUA_OPMOD, "__mod");
  251. }
  252. static int arith_pow (lua_State *L) {
  253. return arith(L, LUA_OPPOW, "__pow");
  254. }
  255. static int arith_div (lua_State *L) {
  256. return arith(L, LUA_OPDIV, "__div");
  257. }
  258. static int arith_idiv (lua_State *L) {
  259. return arith(L, LUA_OPIDIV, "__idiv");
  260. }
  261. static int arith_unm (lua_State *L) {
  262. return arith(L, LUA_OPUNM, "__unm");
  263. }
  264. static const luaL_Reg stringmetamethods[] = {
  265. {"__add", arith_add},
  266. {"__sub", arith_sub},
  267. {"__mul", arith_mul},
  268. {"__mod", arith_mod},
  269. {"__pow", arith_pow},
  270. {"__div", arith_div},
  271. {"__idiv", arith_idiv},
  272. {"__unm", arith_unm},
  273. {"__index", NULL}, /* placeholder */
  274. {NULL, NULL}
  275. };
  276. #endif /* } */
  277. /* }====================================================== */
  278. /*
  279. ** {======================================================
  280. ** PATTERN MATCHING
  281. ** =======================================================
  282. */
  283. #define CAP_UNFINISHED (-1)
  284. #define CAP_POSITION (-2)
  285. typedef struct MatchState {
  286. const char *src_init; /* init of source string */
  287. const char *src_end; /* end ('\0') of source string */
  288. const char *p_end; /* end ('\0') of pattern */
  289. lua_State *L;
  290. int matchdepth; /* control for recursive depth (to avoid C stack overflow) */
  291. unsigned char level; /* total number of captures (finished or unfinished) */
  292. struct {
  293. const char *init;
  294. ptrdiff_t len;
  295. } capture[LUA_MAXCAPTURES];
  296. } MatchState;
  297. /* recursive function */
  298. static const char *match (MatchState *ms, const char *s, const char *p);
  299. /* maximum recursion depth for 'match' */
  300. #if !defined(MAXCCALLS)
  301. #define MAXCCALLS 200
  302. #endif
  303. #define L_ESC '%'
  304. #define SPECIALS "^$*+?.([%-"
  305. static int check_capture (MatchState *ms, int l) {
  306. l -= '1';
  307. if (l < 0 || l >= ms->level || ms->capture[l].len == CAP_UNFINISHED)
  308. return luaL_error(ms->L, "invalid capture index %%%d", l + 1);
  309. return l;
  310. }
  311. static int capture_to_close (MatchState *ms) {
  312. int level = ms->level;
  313. for (level--; level>=0; level--)
  314. if (ms->capture[level].len == CAP_UNFINISHED) return level;
  315. return luaL_error(ms->L, "invalid pattern capture");
  316. }
  317. static const char *classend (MatchState *ms, const char *p) {
  318. switch (*p++) {
  319. case L_ESC: {
  320. if (p == ms->p_end)
  321. luaL_error(ms->L, "malformed pattern (ends with '%%')");
  322. return p+1;
  323. }
  324. case '[': {
  325. if (*p == '^') p++;
  326. do { /* look for a ']' */
  327. if (p == ms->p_end)
  328. luaL_error(ms->L, "malformed pattern (missing ']')");
  329. if (*(p++) == L_ESC && p < ms->p_end)
  330. p++; /* skip escapes (e.g. '%]') */
  331. } while (*p != ']');
  332. return p+1;
  333. }
  334. default: {
  335. return p;
  336. }
  337. }
  338. }
  339. static int match_class (int c, int cl) {
  340. int res;
  341. switch (tolower(cl)) {
  342. case 'a' : res = isalpha(c); break;
  343. case 'c' : res = iscntrl(c); break;
  344. case 'd' : res = isdigit(c); break;
  345. case 'g' : res = isgraph(c); break;
  346. case 'l' : res = islower(c); break;
  347. case 'p' : res = ispunct(c); break;
  348. case 's' : res = isspace(c); break;
  349. case 'u' : res = isupper(c); break;
  350. case 'w' : res = isalnum(c); break;
  351. case 'x' : res = isxdigit(c); break;
  352. case 'z' : res = (c == 0); break; /* deprecated option */
  353. default: return (cl == c);
  354. }
  355. return (islower(cl) ? res : !res);
  356. }
  357. static int matchbracketclass (int c, const char *p, const char *ec) {
  358. int sig = 1;
  359. if (*(p+1) == '^') {
  360. sig = 0;
  361. p++; /* skip the '^' */
  362. }
  363. while (++p < ec) {
  364. if (*p == L_ESC) {
  365. p++;
  366. if (match_class(c, uchar(*p)))
  367. return sig;
  368. }
  369. else if ((*(p+1) == '-') && (p+2 < ec)) {
  370. p+=2;
  371. if (uchar(*(p-2)) <= c && c <= uchar(*p))
  372. return sig;
  373. }
  374. else if (uchar(*p) == c) return sig;
  375. }
  376. return !sig;
  377. }
  378. static int singlematch (MatchState *ms, const char *s, const char *p,
  379. const char *ep) {
  380. if (s >= ms->src_end)
  381. return 0;
  382. else {
  383. int c = uchar(*s);
  384. switch (*p) {
  385. case '.': return 1; /* matches any char */
  386. case L_ESC: return match_class(c, uchar(*(p+1)));
  387. case '[': return matchbracketclass(c, p, ep-1);
  388. default: return (uchar(*p) == c);
  389. }
  390. }
  391. }
  392. static const char *matchbalance (MatchState *ms, const char *s,
  393. const char *p) {
  394. if (p >= ms->p_end - 1)
  395. luaL_error(ms->L, "malformed pattern (missing arguments to '%%b')");
  396. if (*s != *p) return NULL;
  397. else {
  398. int b = *p;
  399. int e = *(p+1);
  400. int cont = 1;
  401. while (++s < ms->src_end) {
  402. if (*s == e) {
  403. if (--cont == 0) return s+1;
  404. }
  405. else if (*s == b) cont++;
  406. }
  407. }
  408. return NULL; /* string ends out of balance */
  409. }
  410. static const char *max_expand (MatchState *ms, const char *s,
  411. const char *p, const char *ep) {
  412. ptrdiff_t i = 0; /* counts maximum expand for item */
  413. while (singlematch(ms, s + i, p, ep))
  414. i++;
  415. /* keeps trying to match with the maximum repetitions */
  416. while (i>=0) {
  417. const char *res = match(ms, (s+i), ep+1);
  418. if (res) return res;
  419. i--; /* else didn't match; reduce 1 repetition to try again */
  420. }
  421. return NULL;
  422. }
  423. static const char *min_expand (MatchState *ms, const char *s,
  424. const char *p, const char *ep) {
  425. for (;;) {
  426. const char *res = match(ms, s, ep+1);
  427. if (res != NULL)
  428. return res;
  429. else if (singlematch(ms, s, p, ep))
  430. s++; /* try with one more repetition */
  431. else return NULL;
  432. }
  433. }
  434. static const char *start_capture (MatchState *ms, const char *s,
  435. const char *p, int what) {
  436. const char *res;
  437. int level = ms->level;
  438. if (level >= LUA_MAXCAPTURES) luaL_error(ms->L, "too many captures");
  439. ms->capture[level].init = s;
  440. ms->capture[level].len = what;
  441. ms->level = level+1;
  442. if ((res=match(ms, s, p)) == NULL) /* match failed? */
  443. ms->level--; /* undo capture */
  444. return res;
  445. }
  446. static const char *end_capture (MatchState *ms, const char *s,
  447. const char *p) {
  448. int l = capture_to_close(ms);
  449. const char *res;
  450. ms->capture[l].len = s - ms->capture[l].init; /* close capture */
  451. if ((res = match(ms, s, p)) == NULL) /* match failed? */
  452. ms->capture[l].len = CAP_UNFINISHED; /* undo capture */
  453. return res;
  454. }
  455. static const char *match_capture (MatchState *ms, const char *s, int l) {
  456. size_t len;
  457. l = check_capture(ms, l);
  458. len = ms->capture[l].len;
  459. if ((size_t)(ms->src_end-s) >= len &&
  460. memcmp(ms->capture[l].init, s, len) == 0)
  461. return s+len;
  462. else return NULL;
  463. }
  464. static const char *match (MatchState *ms, const char *s, const char *p) {
  465. if (ms->matchdepth-- == 0)
  466. luaL_error(ms->L, "pattern too complex");
  467. init: /* using goto's to optimize tail recursion */
  468. if (p != ms->p_end) { /* end of pattern? */
  469. switch (*p) {
  470. case '(': { /* start capture */
  471. if (*(p + 1) == ')') /* position capture? */
  472. s = start_capture(ms, s, p + 2, CAP_POSITION);
  473. else
  474. s = start_capture(ms, s, p + 1, CAP_UNFINISHED);
  475. break;
  476. }
  477. case ')': { /* end capture */
  478. s = end_capture(ms, s, p + 1);
  479. break;
  480. }
  481. case '$': {
  482. if ((p + 1) != ms->p_end) /* is the '$' the last char in pattern? */
  483. goto dflt; /* no; go to default */
  484. s = (s == ms->src_end) ? s : NULL; /* check end of string */
  485. break;
  486. }
  487. case L_ESC: { /* escaped sequences not in the format class[*+?-]? */
  488. switch (*(p + 1)) {
  489. case 'b': { /* balanced string? */
  490. s = matchbalance(ms, s, p + 2);
  491. if (s != NULL) {
  492. p += 4; goto init; /* return match(ms, s, p + 4); */
  493. } /* else fail (s == NULL) */
  494. break;
  495. }
  496. case 'f': { /* frontier? */
  497. const char *ep; char previous;
  498. p += 2;
  499. if (*p != '[')
  500. luaL_error(ms->L, "missing '[' after '%%f' in pattern");
  501. ep = classend(ms, p); /* points to what is next */
  502. previous = (s == ms->src_init) ? '\0' : *(s - 1);
  503. if (!matchbracketclass(uchar(previous), p, ep - 1) &&
  504. matchbracketclass(uchar(*s), p, ep - 1)) {
  505. p = ep; goto init; /* return match(ms, s, ep); */
  506. }
  507. s = NULL; /* match failed */
  508. break;
  509. }
  510. case '0': case '1': case '2': case '3':
  511. case '4': case '5': case '6': case '7':
  512. case '8': case '9': { /* capture results (%0-%9)? */
  513. s = match_capture(ms, s, uchar(*(p + 1)));
  514. if (s != NULL) {
  515. p += 2; goto init; /* return match(ms, s, p + 2) */
  516. }
  517. break;
  518. }
  519. default: goto dflt;
  520. }
  521. break;
  522. }
  523. default: dflt: { /* pattern class plus optional suffix */
  524. const char *ep = classend(ms, p); /* points to optional suffix */
  525. /* does not match at least once? */
  526. if (!singlematch(ms, s, p, ep)) {
  527. if (*ep == '*' || *ep == '?' || *ep == '-') { /* accept empty? */
  528. p = ep + 1; goto init; /* return match(ms, s, ep + 1); */
  529. }
  530. else /* '+' or no suffix */
  531. s = NULL; /* fail */
  532. }
  533. else { /* matched once */
  534. switch (*ep) { /* handle optional suffix */
  535. case '?': { /* optional */
  536. const char *res;
  537. if ((res = match(ms, s + 1, ep + 1)) != NULL)
  538. s = res;
  539. else {
  540. p = ep + 1; goto init; /* else return match(ms, s, ep + 1); */
  541. }
  542. break;
  543. }
  544. case '+': /* 1 or more repetitions */
  545. s++; /* 1 match already done */
  546. /* FALLTHROUGH */
  547. case '*': /* 0 or more repetitions */
  548. s = max_expand(ms, s, p, ep);
  549. break;
  550. case '-': /* 0 or more repetitions (minimum) */
  551. s = min_expand(ms, s, p, ep);
  552. break;
  553. default: /* no suffix */
  554. s++; p = ep; goto init; /* return match(ms, s + 1, ep); */
  555. }
  556. }
  557. break;
  558. }
  559. }
  560. }
  561. ms->matchdepth++;
  562. return s;
  563. }
  564. static const char *lmemfind (const char *s1, size_t l1,
  565. const char *s2, size_t l2) {
  566. if (l2 == 0) return s1; /* empty strings are everywhere */
  567. else if (l2 > l1) return NULL; /* avoids a negative 'l1' */
  568. else {
  569. const char *init; /* to search for a '*s2' inside 's1' */
  570. l2--; /* 1st char will be checked by 'memchr' */
  571. l1 = l1-l2; /* 's2' cannot be found after that */
  572. while (l1 > 0 && (init = (const char *)memchr(s1, *s2, l1)) != NULL) {
  573. init++; /* 1st char is already checked */
  574. if (memcmp(init, s2+1, l2) == 0)
  575. return init-1;
  576. else { /* correct 'l1' and 's1' to try again */
  577. l1 -= init-s1;
  578. s1 = init;
  579. }
  580. }
  581. return NULL; /* not found */
  582. }
  583. }
  584. /*
  585. ** get information about the i-th capture. If there are no captures
  586. ** and 'i==0', return information about the whole match, which
  587. ** is the range 's'..'e'. If the capture is a string, return
  588. ** its length and put its address in '*cap'. If it is an integer
  589. ** (a position), push it on the stack and return CAP_POSITION.
  590. */
  591. static size_t get_onecapture (MatchState *ms, int i, const char *s,
  592. const char *e, const char **cap) {
  593. if (i >= ms->level) {
  594. if (i != 0)
  595. luaL_error(ms->L, "invalid capture index %%%d", i + 1);
  596. *cap = s;
  597. return e - s;
  598. }
  599. else {
  600. ptrdiff_t capl = ms->capture[i].len;
  601. *cap = ms->capture[i].init;
  602. if (capl == CAP_UNFINISHED)
  603. luaL_error(ms->L, "unfinished capture");
  604. else if (capl == CAP_POSITION)
  605. lua_pushinteger(ms->L, (ms->capture[i].init - ms->src_init) + 1);
  606. return capl;
  607. }
  608. }
  609. /*
  610. ** Push the i-th capture on the stack.
  611. */
  612. static void push_onecapture (MatchState *ms, int i, const char *s,
  613. const char *e) {
  614. const char *cap;
  615. ptrdiff_t l = get_onecapture(ms, i, s, e, &cap);
  616. if (l != CAP_POSITION)
  617. lua_pushlstring(ms->L, cap, l);
  618. /* else position was already pushed */
  619. }
  620. static int push_captures (MatchState *ms, const char *s, const char *e) {
  621. int i;
  622. int nlevels = (ms->level == 0 && s) ? 1 : ms->level;
  623. luaL_checkstack(ms->L, nlevels, "too many captures");
  624. for (i = 0; i < nlevels; i++)
  625. push_onecapture(ms, i, s, e);
  626. return nlevels; /* number of strings pushed */
  627. }
  628. /* check whether pattern has no special characters */
  629. static int nospecials (const char *p, size_t l) {
  630. size_t upto = 0;
  631. do {
  632. if (strpbrk(p + upto, SPECIALS))
  633. return 0; /* pattern has a special character */
  634. upto += strlen(p + upto) + 1; /* may have more after \0 */
  635. } while (upto <= l);
  636. return 1; /* no special chars found */
  637. }
  638. static void prepstate (MatchState *ms, lua_State *L,
  639. const char *s, size_t ls, const char *p, size_t lp) {
  640. ms->L = L;
  641. ms->matchdepth = MAXCCALLS;
  642. ms->src_init = s;
  643. ms->src_end = s + ls;
  644. ms->p_end = p + lp;
  645. }
  646. static void reprepstate (MatchState *ms) {
  647. ms->level = 0;
  648. lua_assert(ms->matchdepth == MAXCCALLS);
  649. }
  650. static int str_find_aux (lua_State *L, int find) {
  651. size_t ls, lp;
  652. const char *s = luaL_checklstring(L, 1, &ls);
  653. const char *p = luaL_checklstring(L, 2, &lp);
  654. size_t init = posrelatI(luaL_optinteger(L, 3, 1), ls) - 1;
  655. if (init > ls) { /* start after string's end? */
  656. luaL_pushfail(L); /* cannot find anything */
  657. return 1;
  658. }
  659. /* explicit request or no special characters? */
  660. if (find && (lua_toboolean(L, 4) || nospecials(p, lp))) {
  661. /* do a plain search */
  662. const char *s2 = lmemfind(s + init, ls - init, p, lp);
  663. if (s2) {
  664. lua_pushinteger(L, (s2 - s) + 1);
  665. lua_pushinteger(L, (s2 - s) + lp);
  666. return 2;
  667. }
  668. }
  669. else {
  670. MatchState ms;
  671. const char *s1 = s + init;
  672. int anchor = (*p == '^');
  673. if (anchor) {
  674. p++; lp--; /* skip anchor character */
  675. }
  676. prepstate(&ms, L, s, ls, p, lp);
  677. do {
  678. const char *res;
  679. reprepstate(&ms);
  680. if ((res=match(&ms, s1, p)) != NULL) {
  681. if (find) {
  682. lua_pushinteger(L, (s1 - s) + 1); /* start */
  683. lua_pushinteger(L, res - s); /* end */
  684. return push_captures(&ms, NULL, 0) + 2;
  685. }
  686. else
  687. return push_captures(&ms, s1, res);
  688. }
  689. } while (s1++ < ms.src_end && !anchor);
  690. }
  691. luaL_pushfail(L); /* not found */
  692. return 1;
  693. }
  694. static int str_find (lua_State *L) {
  695. return str_find_aux(L, 1);
  696. }
  697. static int str_match (lua_State *L) {
  698. return str_find_aux(L, 0);
  699. }
  700. /* state for 'gmatch' */
  701. typedef struct GMatchState {
  702. const char *src; /* current position */
  703. const char *p; /* pattern */
  704. const char *lastmatch; /* end of last match */
  705. MatchState ms; /* match state */
  706. } GMatchState;
  707. static int gmatch_aux (lua_State *L) {
  708. GMatchState *gm = (GMatchState *)lua_touserdata(L, lua_upvalueindex(3));
  709. const char *src;
  710. gm->ms.L = L;
  711. for (src = gm->src; src <= gm->ms.src_end; src++) {
  712. const char *e;
  713. reprepstate(&gm->ms);
  714. if ((e = match(&gm->ms, src, gm->p)) != NULL && e != gm->lastmatch) {
  715. gm->src = gm->lastmatch = e;
  716. return push_captures(&gm->ms, src, e);
  717. }
  718. }
  719. return 0; /* not found */
  720. }
  721. static int gmatch (lua_State *L) {
  722. size_t ls, lp;
  723. const char *s = luaL_checklstring(L, 1, &ls);
  724. const char *p = luaL_checklstring(L, 2, &lp);
  725. size_t init = posrelatI(luaL_optinteger(L, 3, 1), ls) - 1;
  726. GMatchState *gm;
  727. lua_settop(L, 2); /* keep strings on closure to avoid being collected */
  728. gm = (GMatchState *)lua_newuserdatauv(L, sizeof(GMatchState), 0);
  729. if (init > ls) /* start after string's end? */
  730. init = ls + 1; /* avoid overflows in 's + init' */
  731. prepstate(&gm->ms, L, s, ls, p, lp);
  732. gm->src = s + init; gm->p = p; gm->lastmatch = NULL;
  733. lua_pushcclosure(L, gmatch_aux, 3);
  734. return 1;
  735. }
  736. static void add_s (MatchState *ms, luaL_Buffer *b, const char *s,
  737. const char *e) {
  738. size_t l;
  739. lua_State *L = ms->L;
  740. const char *news = lua_tolstring(L, 3, &l);
  741. const char *p;
  742. while ((p = (char *)memchr(news, L_ESC, l)) != NULL) {
  743. luaL_addlstring(b, news, p - news);
  744. p++; /* skip ESC */
  745. if (*p == L_ESC) /* '%%' */
  746. luaL_addchar(b, *p);
  747. else if (*p == '0') /* '%0' */
  748. luaL_addlstring(b, s, e - s);
  749. else if (isdigit(uchar(*p))) { /* '%n' */
  750. const char *cap;
  751. ptrdiff_t resl = get_onecapture(ms, *p - '1', s, e, &cap);
  752. if (resl == CAP_POSITION)
  753. luaL_addvalue(b); /* add position to accumulated result */
  754. else
  755. luaL_addlstring(b, cap, resl);
  756. }
  757. else
  758. luaL_error(L, "invalid use of '%c' in replacement string", L_ESC);
  759. l -= p + 1 - news;
  760. news = p + 1;
  761. }
  762. luaL_addlstring(b, news, l);
  763. }
  764. /*
  765. ** Add the replacement value to the string buffer 'b'.
  766. ** Return true if the original string was changed. (Function calls and
  767. ** table indexing resulting in nil or false do not change the subject.)
  768. */
  769. static int add_value (MatchState *ms, luaL_Buffer *b, const char *s,
  770. const char *e, int tr) {
  771. lua_State *L = ms->L;
  772. switch (tr) {
  773. case LUA_TFUNCTION: { /* call the function */
  774. int n;
  775. lua_pushvalue(L, 3); /* push the function */
  776. n = push_captures(ms, s, e); /* all captures as arguments */
  777. lua_call(L, n, 1); /* call it */
  778. break;
  779. }
  780. case LUA_TTABLE: { /* index the table */
  781. push_onecapture(ms, 0, s, e); /* first capture is the index */
  782. lua_gettable(L, 3);
  783. break;
  784. }
  785. default: { /* LUA_TNUMBER or LUA_TSTRING */
  786. add_s(ms, b, s, e); /* add value to the buffer */
  787. return 1; /* something changed */
  788. }
  789. }
  790. if (!lua_toboolean(L, -1)) { /* nil or false? */
  791. lua_pop(L, 1); /* remove value */
  792. luaL_addlstring(b, s, e - s); /* keep original text */
  793. return 0; /* no changes */
  794. }
  795. else if (!lua_isstring(L, -1))
  796. return luaL_error(L, "invalid replacement value (a %s)",
  797. luaL_typename(L, -1));
  798. else {
  799. luaL_addvalue(b); /* add result to accumulator */
  800. return 1; /* something changed */
  801. }
  802. }
  803. static int str_gsub (lua_State *L) {
  804. size_t srcl, lp;
  805. const char *src = luaL_checklstring(L, 1, &srcl); /* subject */
  806. const char *p = luaL_checklstring(L, 2, &lp); /* pattern */
  807. const char *lastmatch = NULL; /* end of last match */
  808. int tr = lua_type(L, 3); /* replacement type */
  809. lua_Integer max_s = luaL_optinteger(L, 4, srcl + 1); /* max replacements */
  810. int anchor = (*p == '^');
  811. lua_Integer n = 0; /* replacement count */
  812. int changed = 0; /* change flag */
  813. MatchState ms;
  814. luaL_Buffer b;
  815. luaL_argexpected(L, tr == LUA_TNUMBER || tr == LUA_TSTRING ||
  816. tr == LUA_TFUNCTION || tr == LUA_TTABLE, 3,
  817. "string/function/table");
  818. luaL_buffinit(L, &b);
  819. if (anchor) {
  820. p++; lp--; /* skip anchor character */
  821. }
  822. prepstate(&ms, L, src, srcl, p, lp);
  823. while (n < max_s) {
  824. const char *e;
  825. reprepstate(&ms); /* (re)prepare state for new match */
  826. if ((e = match(&ms, src, p)) != NULL && e != lastmatch) { /* match? */
  827. n++;
  828. changed = add_value(&ms, &b, src, e, tr) | changed;
  829. src = lastmatch = e;
  830. }
  831. else if (src < ms.src_end) /* otherwise, skip one character */
  832. luaL_addchar(&b, *src++);
  833. else break; /* end of subject */
  834. if (anchor) break;
  835. }
  836. if (!changed) /* no changes? */
  837. lua_pushvalue(L, 1); /* return original string */
  838. else { /* something changed */
  839. luaL_addlstring(&b, src, ms.src_end-src);
  840. luaL_pushresult(&b); /* create and return new string */
  841. }
  842. lua_pushinteger(L, n); /* number of substitutions */
  843. return 2;
  844. }
  845. /* }====================================================== */
  846. /*
  847. ** {======================================================
  848. ** STRING FORMAT
  849. ** =======================================================
  850. */
  851. #if !defined(lua_number2strx) /* { */
  852. /*
  853. ** Hexadecimal floating-point formatter
  854. */
  855. #define SIZELENMOD (sizeof(LUA_NUMBER_FRMLEN)/sizeof(char))
  856. /*
  857. ** Number of bits that goes into the first digit. It can be any value
  858. ** between 1 and 4; the following definition tries to align the number
  859. ** to nibble boundaries by making what is left after that first digit a
  860. ** multiple of 4.
  861. */
  862. #define L_NBFD ((l_floatatt(MANT_DIG) - 1)%4 + 1)
  863. /*
  864. ** Add integer part of 'x' to buffer and return new 'x'
  865. */
  866. static lua_Number adddigit (char *buff, int n, lua_Number x) {
  867. lua_Number dd = l_mathop(floor)(x); /* get integer part from 'x' */
  868. int d = (int)dd;
  869. buff[n] = (d < 10 ? d + '0' : d - 10 + 'a'); /* add to buffer */
  870. return x - dd; /* return what is left */
  871. }
  872. static int num2straux (char *buff, int sz, lua_Number x) {
  873. /* if 'inf' or 'NaN', format it like '%g' */
  874. if (x != x || x == (lua_Number)HUGE_VAL || x == -(lua_Number)HUGE_VAL)
  875. return l_sprintf(buff, sz, LUA_NUMBER_FMT, (LUAI_UACNUMBER)x);
  876. else if (x == 0) { /* can be -0... */
  877. /* create "0" or "-0" followed by exponent */
  878. return l_sprintf(buff, sz, LUA_NUMBER_FMT "x0p+0", (LUAI_UACNUMBER)x);
  879. }
  880. else {
  881. int e;
  882. lua_Number m = l_mathop(frexp)(x, &e); /* 'x' fraction and exponent */
  883. int n = 0; /* character count */
  884. if (m < 0) { /* is number negative? */
  885. buff[n++] = '-'; /* add sign */
  886. m = -m; /* make it positive */
  887. }
  888. buff[n++] = '0'; buff[n++] = 'x'; /* add "0x" */
  889. m = adddigit(buff, n++, m * (1 << L_NBFD)); /* add first digit */
  890. e -= L_NBFD; /* this digit goes before the radix point */
  891. if (m > 0) { /* more digits? */
  892. buff[n++] = lua_getlocaledecpoint(); /* add radix point */
  893. do { /* add as many digits as needed */
  894. m = adddigit(buff, n++, m * 16);
  895. } while (m > 0);
  896. }
  897. n += l_sprintf(buff + n, sz - n, "p%+d", e); /* add exponent */
  898. lua_assert(n < sz);
  899. return n;
  900. }
  901. }
  902. static int lua_number2strx (lua_State *L, char *buff, int sz,
  903. const char *fmt, lua_Number x) {
  904. int n = num2straux(buff, sz, x);
  905. if (fmt[SIZELENMOD] == 'A') {
  906. int i;
  907. for (i = 0; i < n; i++)
  908. buff[i] = toupper(uchar(buff[i]));
  909. }
  910. else if (fmt[SIZELENMOD] != 'a')
  911. return luaL_error(L, "modifiers for format '%%a'/'%%A' not implemented");
  912. return n;
  913. }
  914. #endif /* } */
  915. /*
  916. ** Maximum size for items formatted with '%f'. This size is produced
  917. ** by format('%.99f', -maxfloat), and is equal to 99 + 3 ('-', '.',
  918. ** and '\0') + number of decimal digits to represent maxfloat (which
  919. ** is maximum exponent + 1). (99+3+1, adding some extra, 110)
  920. */
  921. #define MAX_ITEMF (110 + l_floatatt(MAX_10_EXP))
  922. /*
  923. ** All formats except '%f' do not need that large limit. The other
  924. ** float formats use exponents, so that they fit in the 99 limit for
  925. ** significant digits; 's' for large strings and 'q' add items directly
  926. ** to the buffer; all integer formats also fit in the 99 limit. The
  927. ** worst case are floats: they may need 99 significant digits, plus
  928. ** '0x', '-', '.', 'e+XXXX', and '\0'. Adding some extra, 120.
  929. */
  930. #define MAX_ITEM 120
  931. /* valid flags in a format specification */
  932. #if !defined(L_FMTFLAGS)
  933. #define L_FMTFLAGS "-+ #0"
  934. #endif
  935. /*
  936. ** maximum size of each format specification (such as "%-099.99d")
  937. */
  938. #define MAX_FORMAT 32
  939. static void addquoted (luaL_Buffer *b, const char *s, size_t len) {
  940. luaL_addchar(b, '"');
  941. while (len--) {
  942. if (*s == '"' || *s == '\\' || *s == '\n') {
  943. luaL_addchar(b, '\\');
  944. luaL_addchar(b, *s);
  945. }
  946. else if (iscntrl(uchar(*s))) {
  947. char buff[10];
  948. if (!isdigit(uchar(*(s+1))))
  949. l_sprintf(buff, sizeof(buff), "\\%d", (int)uchar(*s));
  950. else
  951. l_sprintf(buff, sizeof(buff), "\\%03d", (int)uchar(*s));
  952. luaL_addstring(b, buff);
  953. }
  954. else
  955. luaL_addchar(b, *s);
  956. s++;
  957. }
  958. luaL_addchar(b, '"');
  959. }
  960. /*
  961. ** Serialize a floating-point number in such a way that it can be
  962. ** scanned back by Lua. Use hexadecimal format for "common" numbers
  963. ** (to preserve precision); inf, -inf, and NaN are handled separately.
  964. ** (NaN cannot be expressed as a numeral, so we write '(0/0)' for it.)
  965. */
  966. static int quotefloat (lua_State *L, char *buff, lua_Number n) {
  967. const char *s; /* for the fixed representations */
  968. if (n == (lua_Number)HUGE_VAL) /* inf? */
  969. s = "1e9999";
  970. else if (n == -(lua_Number)HUGE_VAL) /* -inf? */
  971. s = "-1e9999";
  972. else if (n != n) /* NaN? */
  973. s = "(0/0)";
  974. else { /* format number as hexadecimal */
  975. int nb = lua_number2strx(L, buff, MAX_ITEM,
  976. "%" LUA_NUMBER_FRMLEN "a", n);
  977. /* ensures that 'buff' string uses a dot as the radix character */
  978. if (memchr(buff, '.', nb) == NULL) { /* no dot? */
  979. char point = lua_getlocaledecpoint(); /* try locale point */
  980. char *ppoint = (char *)memchr(buff, point, nb);
  981. if (ppoint) *ppoint = '.'; /* change it to a dot */
  982. }
  983. return nb;
  984. }
  985. /* for the fixed representations */
  986. return l_sprintf(buff, MAX_ITEM, "%s", s);
  987. }
  988. static void addliteral (lua_State *L, luaL_Buffer *b, int arg) {
  989. switch (lua_type(L, arg)) {
  990. case LUA_TSTRING: {
  991. size_t len;
  992. const char *s = lua_tolstring(L, arg, &len);
  993. addquoted(b, s, len);
  994. break;
  995. }
  996. case LUA_TNUMBER: {
  997. char *buff = luaL_prepbuffsize(b, MAX_ITEM);
  998. int nb;
  999. if (!lua_isinteger(L, arg)) /* float? */
  1000. nb = quotefloat(L, buff, lua_tonumber(L, arg));
  1001. else { /* integers */
  1002. lua_Integer n = lua_tointeger(L, arg);
  1003. const char *format = (n == LUA_MININTEGER) /* corner case? */
  1004. ? "0x%" LUA_INTEGER_FRMLEN "x" /* use hex */
  1005. : LUA_INTEGER_FMT; /* else use default format */
  1006. nb = l_sprintf(buff, MAX_ITEM, format, (LUAI_UACINT)n);
  1007. }
  1008. luaL_addsize(b, nb);
  1009. break;
  1010. }
  1011. case LUA_TNIL: case LUA_TBOOLEAN: {
  1012. luaL_tolstring(L, arg, NULL);
  1013. luaL_addvalue(b);
  1014. break;
  1015. }
  1016. default: {
  1017. luaL_argerror(L, arg, "value has no literal form");
  1018. }
  1019. }
  1020. }
  1021. static const char *scanformat (lua_State *L, const char *strfrmt, char *form) {
  1022. const char *p = strfrmt;
  1023. while (*p != '\0' && strchr(L_FMTFLAGS, *p) != NULL) p++; /* skip flags */
  1024. if ((size_t)(p - strfrmt) >= sizeof(L_FMTFLAGS)/sizeof(char))
  1025. luaL_error(L, "invalid format (repeated flags)");
  1026. if (isdigit(uchar(*p))) p++; /* skip width */
  1027. if (isdigit(uchar(*p))) p++; /* (2 digits at most) */
  1028. if (*p == '.') {
  1029. p++;
  1030. if (isdigit(uchar(*p))) p++; /* skip precision */
  1031. if (isdigit(uchar(*p))) p++; /* (2 digits at most) */
  1032. }
  1033. if (isdigit(uchar(*p)))
  1034. luaL_error(L, "invalid format (width or precision too long)");
  1035. *(form++) = '%';
  1036. memcpy(form, strfrmt, ((p - strfrmt) + 1) * sizeof(char));
  1037. form += (p - strfrmt) + 1;
  1038. *form = '\0';
  1039. return p;
  1040. }
  1041. /*
  1042. ** add length modifier into formats
  1043. */
  1044. static void addlenmod (char *form, const char *lenmod) {
  1045. size_t l = strlen(form);
  1046. size_t lm = strlen(lenmod);
  1047. char spec = form[l - 1];
  1048. strcpy(form + l - 1, lenmod);
  1049. form[l + lm - 1] = spec;
  1050. form[l + lm] = '\0';
  1051. }
  1052. static int str_format (lua_State *L) {
  1053. int top = lua_gettop(L);
  1054. int arg = 1;
  1055. size_t sfl;
  1056. const char *strfrmt = luaL_checklstring(L, arg, &sfl);
  1057. const char *strfrmt_end = strfrmt+sfl;
  1058. luaL_Buffer b;
  1059. luaL_buffinit(L, &b);
  1060. while (strfrmt < strfrmt_end) {
  1061. if (*strfrmt != L_ESC)
  1062. luaL_addchar(&b, *strfrmt++);
  1063. else if (*++strfrmt == L_ESC)
  1064. luaL_addchar(&b, *strfrmt++); /* %% */
  1065. else { /* format item */
  1066. char form[MAX_FORMAT]; /* to store the format ('%...') */
  1067. int maxitem = MAX_ITEM;
  1068. char *buff = luaL_prepbuffsize(&b, maxitem); /* to put formatted item */
  1069. int nb = 0; /* number of bytes in added item */
  1070. if (++arg > top)
  1071. return luaL_argerror(L, arg, "no value");
  1072. strfrmt = scanformat(L, strfrmt, form);
  1073. switch (*strfrmt++) {
  1074. case 'c': {
  1075. nb = l_sprintf(buff, maxitem, form, (int)luaL_checkinteger(L, arg));
  1076. break;
  1077. }
  1078. case 'd': case 'i':
  1079. case 'o': case 'u': case 'x': case 'X': {
  1080. lua_Integer n = luaL_checkinteger(L, arg);
  1081. addlenmod(form, LUA_INTEGER_FRMLEN);
  1082. nb = l_sprintf(buff, maxitem, form, (LUAI_UACINT)n);
  1083. break;
  1084. }
  1085. case 'a': case 'A':
  1086. addlenmod(form, LUA_NUMBER_FRMLEN);
  1087. nb = lua_number2strx(L, buff, maxitem, form,
  1088. luaL_checknumber(L, arg));
  1089. break;
  1090. case 'f':
  1091. maxitem = MAX_ITEMF; /* extra space for '%f' */
  1092. buff = luaL_prepbuffsize(&b, maxitem);
  1093. /* FALLTHROUGH */
  1094. case 'e': case 'E': case 'g': case 'G': {
  1095. lua_Number n = luaL_checknumber(L, arg);
  1096. addlenmod(form, LUA_NUMBER_FRMLEN);
  1097. nb = snprintf(buff, maxitem, form, (LUAI_UACNUMBER)n);
  1098. break;
  1099. }
  1100. case 'p': {
  1101. const void *p = lua_topointer(L, arg);
  1102. if (p == NULL)
  1103. p = "(null)"; /* NULL not a valid parameter in ISO C 'printf' */
  1104. nb = l_sprintf(buff, maxitem, form, p);
  1105. break;
  1106. }
  1107. case 'q': {
  1108. if (form[2] != '\0') /* modifiers? */
  1109. return luaL_error(L, "specifier '%%q' cannot have modifiers");
  1110. addliteral(L, &b, arg);
  1111. break;
  1112. }
  1113. case 's': {
  1114. size_t l;
  1115. const char *s = luaL_tolstring(L, arg, &l);
  1116. if (form[2] == '\0') /* no modifiers? */
  1117. luaL_addvalue(&b); /* keep entire string */
  1118. else {
  1119. luaL_argcheck(L, l == strlen(s), arg, "string contains zeros");
  1120. if (!strchr(form, '.') && l >= 100) {
  1121. /* no precision and string is too long to be formatted */
  1122. luaL_addvalue(&b); /* keep entire string */
  1123. }
  1124. else { /* format the string into 'buff' */
  1125. nb = l_sprintf(buff, maxitem, form, s);
  1126. lua_pop(L, 1); /* remove result from 'luaL_tolstring' */
  1127. }
  1128. }
  1129. break;
  1130. }
  1131. default: { /* also treat cases 'pnLlh' */
  1132. return luaL_error(L, "invalid conversion '%s' to 'format'", form);
  1133. }
  1134. }
  1135. lua_assert(nb < maxitem);
  1136. luaL_addsize(&b, nb);
  1137. }
  1138. }
  1139. luaL_pushresult(&b);
  1140. return 1;
  1141. }
  1142. /* }====================================================== */
  1143. /*
  1144. ** {======================================================
  1145. ** PACK/UNPACK
  1146. ** =======================================================
  1147. */
  1148. /* value used for padding */
  1149. #if !defined(LUAL_PACKPADBYTE)
  1150. #define LUAL_PACKPADBYTE 0x00
  1151. #endif
  1152. /* maximum size for the binary representation of an integer */
  1153. #define MAXINTSIZE 16
  1154. /* number of bits in a character */
  1155. #define NB CHAR_BIT
  1156. /* mask for one character (NB 1's) */
  1157. #define MC ((1 << NB) - 1)
  1158. /* size of a lua_Integer */
  1159. #define SZINT ((int)sizeof(lua_Integer))
  1160. /* dummy union to get native endianness */
  1161. static const union {
  1162. int dummy;
  1163. char little; /* true iff machine is little endian */
  1164. } nativeendian = {1};
  1165. /* dummy structure to get native alignment requirements */
  1166. struct cD {
  1167. char c;
  1168. union { double d; void *p; lua_Integer i; lua_Number n; } u;
  1169. };
  1170. #define MAXALIGN (offsetof(struct cD, u))
  1171. /*
  1172. ** Union for serializing floats
  1173. */
  1174. typedef union Ftypes {
  1175. float f;
  1176. double d;
  1177. lua_Number n;
  1178. char buff[5 * sizeof(lua_Number)]; /* enough for any float type */
  1179. } Ftypes;
  1180. /*
  1181. ** information to pack/unpack stuff
  1182. */
  1183. typedef struct Header {
  1184. lua_State *L;
  1185. int islittle;
  1186. int maxalign;
  1187. } Header;
  1188. /*
  1189. ** options for pack/unpack
  1190. */
  1191. typedef enum KOption {
  1192. Kint, /* signed integers */
  1193. Kuint, /* unsigned integers */
  1194. Kfloat, /* floating-point numbers */
  1195. Kchar, /* fixed-length strings */
  1196. Kstring, /* strings with prefixed length */
  1197. Kzstr, /* zero-terminated strings */
  1198. Kpadding, /* padding */
  1199. Kpaddalign, /* padding for alignment */
  1200. Knop /* no-op (configuration or spaces) */
  1201. } KOption;
  1202. /*
  1203. ** Read an integer numeral from string 'fmt' or return 'df' if
  1204. ** there is no numeral
  1205. */
  1206. static int digit (int c) { return '0' <= c && c <= '9'; }
  1207. static int getnum (const char **fmt, int df) {
  1208. if (!digit(**fmt)) /* no number? */
  1209. return df; /* return default value */
  1210. else {
  1211. int a = 0;
  1212. do {
  1213. a = a*10 + (*((*fmt)++) - '0');
  1214. } while (digit(**fmt) && a <= ((int)MAXSIZE - 9)/10);
  1215. return a;
  1216. }
  1217. }
  1218. /*
  1219. ** Read an integer numeral and raises an error if it is larger
  1220. ** than the maximum size for integers.
  1221. */
  1222. static int getnumlimit (Header *h, const char **fmt, int df) {
  1223. int sz = getnum(fmt, df);
  1224. if (sz > MAXINTSIZE || sz <= 0)
  1225. return luaL_error(h->L, "integral size (%d) out of limits [1,%d]",
  1226. sz, MAXINTSIZE);
  1227. return sz;
  1228. }
  1229. /*
  1230. ** Initialize Header
  1231. */
  1232. static void initheader (lua_State *L, Header *h) {
  1233. h->L = L;
  1234. h->islittle = nativeendian.little;
  1235. h->maxalign = 1;
  1236. }
  1237. /*
  1238. ** Read and classify next option. 'size' is filled with option's size.
  1239. */
  1240. static KOption getoption (Header *h, const char **fmt, int *size) {
  1241. int opt = *((*fmt)++);
  1242. *size = 0; /* default */
  1243. switch (opt) {
  1244. case 'b': *size = sizeof(char); return Kint;
  1245. case 'B': *size = sizeof(char); return Kuint;
  1246. case 'h': *size = sizeof(short); return Kint;
  1247. case 'H': *size = sizeof(short); return Kuint;
  1248. case 'l': *size = sizeof(long); return Kint;
  1249. case 'L': *size = sizeof(long); return Kuint;
  1250. case 'j': *size = sizeof(lua_Integer); return Kint;
  1251. case 'J': *size = sizeof(lua_Integer); return Kuint;
  1252. case 'T': *size = sizeof(size_t); return Kuint;
  1253. case 'f': *size = sizeof(float); return Kfloat;
  1254. case 'd': *size = sizeof(double); return Kfloat;
  1255. case 'n': *size = sizeof(lua_Number); return Kfloat;
  1256. case 'i': *size = getnumlimit(h, fmt, sizeof(int)); return Kint;
  1257. case 'I': *size = getnumlimit(h, fmt, sizeof(int)); return Kuint;
  1258. case 's': *size = getnumlimit(h, fmt, sizeof(size_t)); return Kstring;
  1259. case 'c':
  1260. *size = getnum(fmt, -1);
  1261. if (*size == -1)
  1262. luaL_error(h->L, "missing size for format option 'c'");
  1263. return Kchar;
  1264. case 'z': return Kzstr;
  1265. case 'x': *size = 1; return Kpadding;
  1266. case 'X': return Kpaddalign;
  1267. case ' ': break;
  1268. case '<': h->islittle = 1; break;
  1269. case '>': h->islittle = 0; break;
  1270. case '=': h->islittle = nativeendian.little; break;
  1271. case '!': h->maxalign = getnumlimit(h, fmt, MAXALIGN); break;
  1272. default: luaL_error(h->L, "invalid format option '%c'", opt);
  1273. }
  1274. return Knop;
  1275. }
  1276. /*
  1277. ** Read, classify, and fill other details about the next option.
  1278. ** 'psize' is filled with option's size, 'notoalign' with its
  1279. ** alignment requirements.
  1280. ** Local variable 'size' gets the size to be aligned. (Kpadal option
  1281. ** always gets its full alignment, other options are limited by
  1282. ** the maximum alignment ('maxalign'). Kchar option needs no alignment
  1283. ** despite its size.
  1284. */
  1285. static KOption getdetails (Header *h, size_t totalsize,
  1286. const char **fmt, int *psize, int *ntoalign) {
  1287. KOption opt = getoption(h, fmt, psize);
  1288. int align = *psize; /* usually, alignment follows size */
  1289. if (opt == Kpaddalign) { /* 'X' gets alignment from following option */
  1290. if (**fmt == '\0' || getoption(h, fmt, &align) == Kchar || align == 0)
  1291. luaL_argerror(h->L, 1, "invalid next option for option 'X'");
  1292. }
  1293. if (align <= 1 || opt == Kchar) /* need no alignment? */
  1294. *ntoalign = 0;
  1295. else {
  1296. if (align > h->maxalign) /* enforce maximum alignment */
  1297. align = h->maxalign;
  1298. if ((align & (align - 1)) != 0) /* is 'align' not a power of 2? */
  1299. luaL_argerror(h->L, 1, "format asks for alignment not power of 2");
  1300. *ntoalign = (align - (int)(totalsize & (align - 1))) & (align - 1);
  1301. }
  1302. return opt;
  1303. }
  1304. /*
  1305. ** Pack integer 'n' with 'size' bytes and 'islittle' endianness.
  1306. ** The final 'if' handles the case when 'size' is larger than
  1307. ** the size of a Lua integer, correcting the extra sign-extension
  1308. ** bytes if necessary (by default they would be zeros).
  1309. */
  1310. static void packint (luaL_Buffer *b, lua_Unsigned n,
  1311. int islittle, int size, int neg) {
  1312. char *buff = luaL_prepbuffsize(b, size);
  1313. int i;
  1314. buff[islittle ? 0 : size - 1] = (char)(n & MC); /* first byte */
  1315. for (i = 1; i < size; i++) {
  1316. n >>= NB;
  1317. buff[islittle ? i : size - 1 - i] = (char)(n & MC);
  1318. }
  1319. if (neg && size > SZINT) { /* negative number need sign extension? */
  1320. for (i = SZINT; i < size; i++) /* correct extra bytes */
  1321. buff[islittle ? i : size - 1 - i] = (char)MC;
  1322. }
  1323. luaL_addsize(b, size); /* add result to buffer */
  1324. }
  1325. /*
  1326. ** Copy 'size' bytes from 'src' to 'dest', correcting endianness if
  1327. ** given 'islittle' is different from native endianness.
  1328. */
  1329. static void copywithendian (volatile char *dest, volatile const char *src,
  1330. int size, int islittle) {
  1331. if (islittle == nativeendian.little) {
  1332. while (size-- != 0)
  1333. *(dest++) = *(src++);
  1334. }
  1335. else {
  1336. dest += size - 1;
  1337. while (size-- != 0)
  1338. *(dest--) = *(src++);
  1339. }
  1340. }
  1341. static int str_pack (lua_State *L) {
  1342. luaL_Buffer b;
  1343. Header h;
  1344. const char *fmt = luaL_checkstring(L, 1); /* format string */
  1345. int arg = 1; /* current argument to pack */
  1346. size_t totalsize = 0; /* accumulate total size of result */
  1347. initheader(L, &h);
  1348. lua_pushnil(L); /* mark to separate arguments from string buffer */
  1349. luaL_buffinit(L, &b);
  1350. while (*fmt != '\0') {
  1351. int size, ntoalign;
  1352. KOption opt = getdetails(&h, totalsize, &fmt, &size, &ntoalign);
  1353. totalsize += ntoalign + size;
  1354. while (ntoalign-- > 0)
  1355. luaL_addchar(&b, LUAL_PACKPADBYTE); /* fill alignment */
  1356. arg++;
  1357. switch (opt) {
  1358. case Kint: { /* signed integers */
  1359. lua_Integer n = luaL_checkinteger(L, arg);
  1360. if (size < SZINT) { /* need overflow check? */
  1361. lua_Integer lim = (lua_Integer)1 << ((size * NB) - 1);
  1362. luaL_argcheck(L, -lim <= n && n < lim, arg, "integer overflow");
  1363. }
  1364. packint(&b, (lua_Unsigned)n, h.islittle, size, (n < 0));
  1365. break;
  1366. }
  1367. case Kuint: { /* unsigned integers */
  1368. lua_Integer n = luaL_checkinteger(L, arg);
  1369. if (size < SZINT) /* need overflow check? */
  1370. luaL_argcheck(L, (lua_Unsigned)n < ((lua_Unsigned)1 << (size * NB)),
  1371. arg, "unsigned overflow");
  1372. packint(&b, (lua_Unsigned)n, h.islittle, size, 0);
  1373. break;
  1374. }
  1375. case Kfloat: { /* floating-point options */
  1376. volatile Ftypes u;
  1377. char *buff = luaL_prepbuffsize(&b, size);
  1378. lua_Number n = luaL_checknumber(L, arg); /* get argument */
  1379. if (size == sizeof(u.f)) u.f = (float)n; /* copy it into 'u' */
  1380. else if (size == sizeof(u.d)) u.d = (double)n;
  1381. else u.n = n;
  1382. /* move 'u' to final result, correcting endianness if needed */
  1383. copywithendian(buff, u.buff, size, h.islittle);
  1384. luaL_addsize(&b, size);
  1385. break;
  1386. }
  1387. case Kchar: { /* fixed-size string */
  1388. size_t len;
  1389. const char *s = luaL_checklstring(L, arg, &len);
  1390. luaL_argcheck(L, len <= (size_t)size, arg,
  1391. "string longer than given size");
  1392. luaL_addlstring(&b, s, len); /* add string */
  1393. while (len++ < (size_t)size) /* pad extra space */
  1394. luaL_addchar(&b, LUAL_PACKPADBYTE);
  1395. break;
  1396. }
  1397. case Kstring: { /* strings with length count */
  1398. size_t len;
  1399. const char *s = luaL_checklstring(L, arg, &len);
  1400. luaL_argcheck(L, size >= (int)sizeof(size_t) ||
  1401. len < ((size_t)1 << (size * NB)),
  1402. arg, "string length does not fit in given size");
  1403. packint(&b, (lua_Unsigned)len, h.islittle, size, 0); /* pack length */
  1404. luaL_addlstring(&b, s, len);
  1405. totalsize += len;
  1406. break;
  1407. }
  1408. case Kzstr: { /* zero-terminated string */
  1409. size_t len;
  1410. const char *s = luaL_checklstring(L, arg, &len);
  1411. luaL_argcheck(L, strlen(s) == len, arg, "string contains zeros");
  1412. luaL_addlstring(&b, s, len);
  1413. luaL_addchar(&b, '\0'); /* add zero at the end */
  1414. totalsize += len + 1;
  1415. break;
  1416. }
  1417. case Kpadding: luaL_addchar(&b, LUAL_PACKPADBYTE); /* FALLTHROUGH */
  1418. case Kpaddalign: case Knop:
  1419. arg--; /* undo increment */
  1420. break;
  1421. }
  1422. }
  1423. luaL_pushresult(&b);
  1424. return 1;
  1425. }
  1426. static int str_packsize (lua_State *L) {
  1427. Header h;
  1428. const char *fmt = luaL_checkstring(L, 1); /* format string */
  1429. size_t totalsize = 0; /* accumulate total size of result */
  1430. initheader(L, &h);
  1431. while (*fmt != '\0') {
  1432. int size, ntoalign;
  1433. KOption opt = getdetails(&h, totalsize, &fmt, &size, &ntoalign);
  1434. luaL_argcheck(L, opt != Kstring && opt != Kzstr, 1,
  1435. "variable-length format");
  1436. size += ntoalign; /* total space used by option */
  1437. luaL_argcheck(L, totalsize <= MAXSIZE - size, 1,
  1438. "format result too large");
  1439. totalsize += size;
  1440. }
  1441. lua_pushinteger(L, (lua_Integer)totalsize);
  1442. return 1;
  1443. }
  1444. /*
  1445. ** Unpack an integer with 'size' bytes and 'islittle' endianness.
  1446. ** If size is smaller than the size of a Lua integer and integer
  1447. ** is signed, must do sign extension (propagating the sign to the
  1448. ** higher bits); if size is larger than the size of a Lua integer,
  1449. ** it must check the unread bytes to see whether they do not cause an
  1450. ** overflow.
  1451. */
  1452. static lua_Integer unpackint (lua_State *L, const char *str,
  1453. int islittle, int size, int issigned) {
  1454. lua_Unsigned res = 0;
  1455. int i;
  1456. int limit = (size <= SZINT) ? size : SZINT;
  1457. for (i = limit - 1; i >= 0; i--) {
  1458. res <<= NB;
  1459. res |= (lua_Unsigned)(unsigned char)str[islittle ? i : size - 1 - i];
  1460. }
  1461. if (size < SZINT) { /* real size smaller than lua_Integer? */
  1462. if (issigned) { /* needs sign extension? */
  1463. lua_Unsigned mask = (lua_Unsigned)1 << (size*NB - 1);
  1464. res = ((res ^ mask) - mask); /* do sign extension */
  1465. }
  1466. }
  1467. else if (size > SZINT) { /* must check unread bytes */
  1468. int mask = (!issigned || (lua_Integer)res >= 0) ? 0 : MC;
  1469. for (i = limit; i < size; i++) {
  1470. if ((unsigned char)str[islittle ? i : size - 1 - i] != mask)
  1471. luaL_error(L, "%d-byte integer does not fit into Lua Integer", size);
  1472. }
  1473. }
  1474. return (lua_Integer)res;
  1475. }
  1476. static int str_unpack (lua_State *L) {
  1477. Header h;
  1478. const char *fmt = luaL_checkstring(L, 1);
  1479. size_t ld;
  1480. const char *data = luaL_checklstring(L, 2, &ld);
  1481. size_t pos = posrelatI(luaL_optinteger(L, 3, 1), ld) - 1;
  1482. int n = 0; /* number of results */
  1483. luaL_argcheck(L, pos <= ld, 3, "initial position out of string");
  1484. initheader(L, &h);
  1485. while (*fmt != '\0') {
  1486. int size, ntoalign;
  1487. KOption opt = getdetails(&h, pos, &fmt, &size, &ntoalign);
  1488. luaL_argcheck(L, (size_t)ntoalign + size <= ld - pos, 2,
  1489. "data string too short");
  1490. pos += ntoalign; /* skip alignment */
  1491. /* stack space for item + next position */
  1492. luaL_checkstack(L, 2, "too many results");
  1493. n++;
  1494. switch (opt) {
  1495. case Kint:
  1496. case Kuint: {
  1497. lua_Integer res = unpackint(L, data + pos, h.islittle, size,
  1498. (opt == Kint));
  1499. lua_pushinteger(L, res);
  1500. break;
  1501. }
  1502. case Kfloat: {
  1503. volatile Ftypes u;
  1504. lua_Number num;
  1505. copywithendian(u.buff, data + pos, size, h.islittle);
  1506. if (size == sizeof(u.f)) num = (lua_Number)u.f;
  1507. else if (size == sizeof(u.d)) num = (lua_Number)u.d;
  1508. else num = u.n;
  1509. lua_pushnumber(L, num);
  1510. break;
  1511. }
  1512. case Kchar: {
  1513. lua_pushlstring(L, data + pos, size);
  1514. break;
  1515. }
  1516. case Kstring: {
  1517. size_t len = (size_t)unpackint(L, data + pos, h.islittle, size, 0);
  1518. luaL_argcheck(L, len <= ld - pos - size, 2, "data string too short");
  1519. lua_pushlstring(L, data + pos + size, len);
  1520. pos += len; /* skip string */
  1521. break;
  1522. }
  1523. case Kzstr: {
  1524. size_t len = (int)strlen(data + pos);
  1525. luaL_argcheck(L, pos + len < ld, 2,
  1526. "unfinished string for format 'z'");
  1527. lua_pushlstring(L, data + pos, len);
  1528. pos += len + 1; /* skip string plus final '\0' */
  1529. break;
  1530. }
  1531. case Kpaddalign: case Kpadding: case Knop:
  1532. n--; /* undo increment */
  1533. break;
  1534. }
  1535. pos += size;
  1536. }
  1537. lua_pushinteger(L, pos + 1); /* next position */
  1538. return n + 1;
  1539. }
  1540. /* }====================================================== */
  1541. static const luaL_Reg strlib[] = {
  1542. {"byte", str_byte},
  1543. {"char", str_char},
  1544. {"dump", str_dump},
  1545. {"find", str_find},
  1546. {"format", str_format},
  1547. {"gmatch", gmatch},
  1548. {"gsub", str_gsub},
  1549. {"len", str_len},
  1550. {"lower", str_lower},
  1551. {"match", str_match},
  1552. {"rep", str_rep},
  1553. {"reverse", str_reverse},
  1554. {"sub", str_sub},
  1555. {"upper", str_upper},
  1556. {"pack", str_pack},
  1557. {"packsize", str_packsize},
  1558. {"unpack", str_unpack},
  1559. {NULL, NULL}
  1560. };
  1561. static void createmetatable (lua_State *L) {
  1562. /* table to be metatable for strings */
  1563. luaL_newlibtable(L, stringmetamethods);
  1564. luaL_setfuncs(L, stringmetamethods, 0);
  1565. lua_pushliteral(L, ""); /* dummy string */
  1566. lua_pushvalue(L, -2); /* copy table */
  1567. lua_setmetatable(L, -2); /* set table as metatable for strings */
  1568. lua_pop(L, 1); /* pop dummy string */
  1569. lua_pushvalue(L, -2); /* get string library */
  1570. lua_setfield(L, -2, "__index"); /* metatable.__index = string */
  1571. lua_pop(L, 1); /* pop metatable */
  1572. }
  1573. /*
  1574. ** Open string library
  1575. */
  1576. LUAMOD_API int luaopen_string (lua_State *L) {
  1577. luaL_newlib(L, strlib);
  1578. createmetatable(L);
  1579. return 1;
  1580. }