lstrlib.c 50 KB

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