lstrlib.c 52 KB

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