lstrlib.c 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717
  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. static void push_onecapture (MatchState *ms, int i, const char *s,
  563. const char *e) {
  564. if (i >= ms->level) {
  565. if (i == 0) /* ms->level == 0, too */
  566. lua_pushlstring(ms->L, s, e - s); /* add whole match */
  567. else
  568. luaL_error(ms->L, "invalid capture index %%%d", i + 1);
  569. }
  570. else {
  571. ptrdiff_t l = ms->capture[i].len;
  572. if (l == CAP_UNFINISHED) luaL_error(ms->L, "unfinished capture");
  573. if (l == CAP_POSITION)
  574. lua_pushinteger(ms->L, (ms->capture[i].init - ms->src_init) + 1);
  575. else
  576. lua_pushlstring(ms->L, ms->capture[i].init, l);
  577. }
  578. }
  579. static int push_captures (MatchState *ms, const char *s, const char *e) {
  580. int i;
  581. int nlevels = (ms->level == 0 && s) ? 1 : ms->level;
  582. luaL_checkstack(ms->L, nlevels, "too many captures");
  583. for (i = 0; i < nlevels; i++)
  584. push_onecapture(ms, i, s, e);
  585. return nlevels; /* number of strings pushed */
  586. }
  587. /* check whether pattern has no special characters */
  588. static int nospecials (const char *p, size_t l) {
  589. size_t upto = 0;
  590. do {
  591. if (strpbrk(p + upto, SPECIALS))
  592. return 0; /* pattern has a special character */
  593. upto += strlen(p + upto) + 1; /* may have more after \0 */
  594. } while (upto <= l);
  595. return 1; /* no special chars found */
  596. }
  597. static void prepstate (MatchState *ms, lua_State *L,
  598. const char *s, size_t ls, const char *p, size_t lp) {
  599. ms->L = L;
  600. ms->matchdepth = MAXCCALLS;
  601. ms->src_init = s;
  602. ms->src_end = s + ls;
  603. ms->p_end = p + lp;
  604. }
  605. static void reprepstate (MatchState *ms) {
  606. ms->level = 0;
  607. lua_assert(ms->matchdepth == MAXCCALLS);
  608. }
  609. static int str_find_aux (lua_State *L, int find) {
  610. size_t ls, lp;
  611. const char *s = luaL_checklstring(L, 1, &ls);
  612. const char *p = luaL_checklstring(L, 2, &lp);
  613. size_t init = posrelatI(luaL_optinteger(L, 3, 1), ls) - 1;
  614. if (init > ls) { /* start after string's end? */
  615. lua_pushnil(L); /* cannot find anything */
  616. return 1;
  617. }
  618. /* explicit request or no special characters? */
  619. if (find && (lua_toboolean(L, 4) || nospecials(p, lp))) {
  620. /* do a plain search */
  621. const char *s2 = lmemfind(s + init, ls - init, p, lp);
  622. if (s2) {
  623. lua_pushinteger(L, (s2 - s) + 1);
  624. lua_pushinteger(L, (s2 - s) + lp);
  625. return 2;
  626. }
  627. }
  628. else {
  629. MatchState ms;
  630. const char *s1 = s + init;
  631. int anchor = (*p == '^');
  632. if (anchor) {
  633. p++; lp--; /* skip anchor character */
  634. }
  635. prepstate(&ms, L, s, ls, p, lp);
  636. do {
  637. const char *res;
  638. reprepstate(&ms);
  639. if ((res=match(&ms, s1, p)) != NULL) {
  640. if (find) {
  641. lua_pushinteger(L, (s1 - s) + 1); /* start */
  642. lua_pushinteger(L, res - s); /* end */
  643. return push_captures(&ms, NULL, 0) + 2;
  644. }
  645. else
  646. return push_captures(&ms, s1, res);
  647. }
  648. } while (s1++ < ms.src_end && !anchor);
  649. }
  650. lua_pushnil(L); /* not found */
  651. return 1;
  652. }
  653. static int str_find (lua_State *L) {
  654. return str_find_aux(L, 1);
  655. }
  656. static int str_match (lua_State *L) {
  657. return str_find_aux(L, 0);
  658. }
  659. /* state for 'gmatch' */
  660. typedef struct GMatchState {
  661. const char *src; /* current position */
  662. const char *p; /* pattern */
  663. const char *lastmatch; /* end of last match */
  664. MatchState ms; /* match state */
  665. } GMatchState;
  666. static int gmatch_aux (lua_State *L) {
  667. GMatchState *gm = (GMatchState *)lua_touserdata(L, lua_upvalueindex(3));
  668. const char *src;
  669. gm->ms.L = L;
  670. for (src = gm->src; src <= gm->ms.src_end; src++) {
  671. const char *e;
  672. reprepstate(&gm->ms);
  673. if ((e = match(&gm->ms, src, gm->p)) != NULL && e != gm->lastmatch) {
  674. gm->src = gm->lastmatch = e;
  675. return push_captures(&gm->ms, src, e);
  676. }
  677. }
  678. return 0; /* not found */
  679. }
  680. static int gmatch (lua_State *L) {
  681. size_t ls, lp;
  682. const char *s = luaL_checklstring(L, 1, &ls);
  683. const char *p = luaL_checklstring(L, 2, &lp);
  684. size_t init = posrelatI(luaL_optinteger(L, 3, 1), ls) - 1;
  685. GMatchState *gm;
  686. lua_settop(L, 2); /* keep strings on closure to avoid being collected */
  687. gm = (GMatchState *)lua_newuserdatauv(L, sizeof(GMatchState), 0);
  688. if (init > ls) /* start after string's end? */
  689. init = ls + 1; /* avoid overflows in 's + init' */
  690. prepstate(&gm->ms, L, s, ls, p, lp);
  691. gm->src = s + init; gm->p = p; gm->lastmatch = NULL;
  692. lua_pushcclosure(L, gmatch_aux, 3);
  693. return 1;
  694. }
  695. static void add_s (MatchState *ms, luaL_Buffer *b, const char *s,
  696. const char *e) {
  697. size_t l, i;
  698. lua_State *L = ms->L;
  699. const char *news = lua_tolstring(L, 3, &l);
  700. for (i = 0; i < l; i++) {
  701. if (news[i] != L_ESC)
  702. luaL_addchar(b, news[i]);
  703. else {
  704. i++; /* skip ESC */
  705. if (!isdigit(uchar(news[i]))) {
  706. if (news[i] != L_ESC)
  707. luaL_error(L, "invalid use of '%c' in replacement string", L_ESC);
  708. luaL_addchar(b, news[i]);
  709. }
  710. else if (news[i] == '0')
  711. luaL_addlstring(b, s, e - s);
  712. else {
  713. push_onecapture(ms, news[i] - '1', s, e);
  714. luaL_tolstring(L, -1, NULL); /* if number, convert it to string */
  715. lua_remove(L, -2); /* remove original value */
  716. luaL_addvalue(b); /* add capture to accumulated result */
  717. }
  718. }
  719. }
  720. }
  721. static void add_value (MatchState *ms, luaL_Buffer *b, const char *s,
  722. const char *e, int tr) {
  723. lua_State *L = ms->L;
  724. switch (tr) {
  725. case LUA_TFUNCTION: {
  726. int n;
  727. lua_pushvalue(L, 3);
  728. n = push_captures(ms, s, e);
  729. lua_call(L, n, 1);
  730. break;
  731. }
  732. case LUA_TTABLE: {
  733. push_onecapture(ms, 0, s, e);
  734. lua_gettable(L, 3);
  735. break;
  736. }
  737. default: { /* LUA_TNUMBER or LUA_TSTRING */
  738. add_s(ms, b, s, e);
  739. return;
  740. }
  741. }
  742. if (!lua_toboolean(L, -1)) { /* nil or false? */
  743. lua_pop(L, 1);
  744. lua_pushlstring(L, s, e - s); /* keep original text */
  745. }
  746. else if (!lua_isstring(L, -1))
  747. luaL_error(L, "invalid replacement value (a %s)", luaL_typename(L, -1));
  748. luaL_addvalue(b); /* add result to accumulator */
  749. }
  750. static int str_gsub (lua_State *L) {
  751. size_t srcl, lp;
  752. const char *src = luaL_checklstring(L, 1, &srcl); /* subject */
  753. const char *p = luaL_checklstring(L, 2, &lp); /* pattern */
  754. const char *lastmatch = NULL; /* end of last match */
  755. int tr = lua_type(L, 3); /* replacement type */
  756. lua_Integer max_s = luaL_optinteger(L, 4, srcl + 1); /* max replacements */
  757. int anchor = (*p == '^');
  758. lua_Integer n = 0; /* replacement count */
  759. MatchState ms;
  760. luaL_Buffer b;
  761. luaL_argexpected(L, tr == LUA_TNUMBER || tr == LUA_TSTRING ||
  762. tr == LUA_TFUNCTION || tr == LUA_TTABLE, 3,
  763. "string/function/table");
  764. luaL_buffinit(L, &b);
  765. if (anchor) {
  766. p++; lp--; /* skip anchor character */
  767. }
  768. prepstate(&ms, L, src, srcl, p, lp);
  769. while (n < max_s) {
  770. const char *e;
  771. reprepstate(&ms); /* (re)prepare state for new match */
  772. if ((e = match(&ms, src, p)) != NULL && e != lastmatch) { /* match? */
  773. n++;
  774. add_value(&ms, &b, src, e, tr); /* add replacement to buffer */
  775. src = lastmatch = e;
  776. }
  777. else if (src < ms.src_end) /* otherwise, skip one character */
  778. luaL_addchar(&b, *src++);
  779. else break; /* end of subject */
  780. if (anchor) break;
  781. }
  782. luaL_addlstring(&b, src, ms.src_end-src);
  783. luaL_pushresult(&b);
  784. lua_pushinteger(L, n); /* number of substitutions */
  785. return 2;
  786. }
  787. /* }====================================================== */
  788. /*
  789. ** {======================================================
  790. ** STRING FORMAT
  791. ** =======================================================
  792. */
  793. #if !defined(lua_number2strx) /* { */
  794. /*
  795. ** Hexadecimal floating-point formatter
  796. */
  797. #define SIZELENMOD (sizeof(LUA_NUMBER_FRMLEN)/sizeof(char))
  798. /*
  799. ** Number of bits that goes into the first digit. It can be any value
  800. ** between 1 and 4; the following definition tries to align the number
  801. ** to nibble boundaries by making what is left after that first digit a
  802. ** multiple of 4.
  803. */
  804. #define L_NBFD ((l_mathlim(MANT_DIG) - 1)%4 + 1)
  805. /*
  806. ** Add integer part of 'x' to buffer and return new 'x'
  807. */
  808. static lua_Number adddigit (char *buff, int n, lua_Number x) {
  809. lua_Number dd = l_mathop(floor)(x); /* get integer part from 'x' */
  810. int d = (int)dd;
  811. buff[n] = (d < 10 ? d + '0' : d - 10 + 'a'); /* add to buffer */
  812. return x - dd; /* return what is left */
  813. }
  814. static int num2straux (char *buff, int sz, lua_Number x) {
  815. /* if 'inf' or 'NaN', format it like '%g' */
  816. if (x != x || x == (lua_Number)HUGE_VAL || x == -(lua_Number)HUGE_VAL)
  817. return l_sprintf(buff, sz, LUA_NUMBER_FMT, (LUAI_UACNUMBER)x);
  818. else if (x == 0) { /* can be -0... */
  819. /* create "0" or "-0" followed by exponent */
  820. return l_sprintf(buff, sz, LUA_NUMBER_FMT "x0p+0", (LUAI_UACNUMBER)x);
  821. }
  822. else {
  823. int e;
  824. lua_Number m = l_mathop(frexp)(x, &e); /* 'x' fraction and exponent */
  825. int n = 0; /* character count */
  826. if (m < 0) { /* is number negative? */
  827. buff[n++] = '-'; /* add sign */
  828. m = -m; /* make it positive */
  829. }
  830. buff[n++] = '0'; buff[n++] = 'x'; /* add "0x" */
  831. m = adddigit(buff, n++, m * (1 << L_NBFD)); /* add first digit */
  832. e -= L_NBFD; /* this digit goes before the radix point */
  833. if (m > 0) { /* more digits? */
  834. buff[n++] = lua_getlocaledecpoint(); /* add radix point */
  835. do { /* add as many digits as needed */
  836. m = adddigit(buff, n++, m * 16);
  837. } while (m > 0);
  838. }
  839. n += l_sprintf(buff + n, sz - n, "p%+d", e); /* add exponent */
  840. lua_assert(n < sz);
  841. return n;
  842. }
  843. }
  844. static int lua_number2strx (lua_State *L, char *buff, int sz,
  845. const char *fmt, lua_Number x) {
  846. int n = num2straux(buff, sz, x);
  847. if (fmt[SIZELENMOD] == 'A') {
  848. int i;
  849. for (i = 0; i < n; i++)
  850. buff[i] = toupper(uchar(buff[i]));
  851. }
  852. else if (fmt[SIZELENMOD] != 'a')
  853. return luaL_error(L, "modifiers for format '%%a'/'%%A' not implemented");
  854. return n;
  855. }
  856. #endif /* } */
  857. /*
  858. ** Maximum size of each formatted item. This maximum size is produced
  859. ** by format('%.99f', -maxfloat), and is equal to 99 + 3 ('-', '.',
  860. ** and '\0') + number of decimal digits to represent maxfloat (which
  861. ** is maximum exponent + 1). (99+3+1 then rounded to 120 for "extra
  862. ** expenses", such as locale-dependent stuff)
  863. */
  864. #define MAX_ITEM (120 + l_mathlim(MAX_10_EXP))
  865. /* valid flags in a format specification */
  866. #define FLAGS "-+ #0"
  867. /*
  868. ** maximum size of each format specification (such as "%-099.99d")
  869. */
  870. #define MAX_FORMAT 32
  871. static void addquoted (luaL_Buffer *b, const char *s, size_t len) {
  872. luaL_addchar(b, '"');
  873. while (len--) {
  874. if (*s == '"' || *s == '\\' || *s == '\n') {
  875. luaL_addchar(b, '\\');
  876. luaL_addchar(b, *s);
  877. }
  878. else if (iscntrl(uchar(*s))) {
  879. char buff[10];
  880. if (!isdigit(uchar(*(s+1))))
  881. l_sprintf(buff, sizeof(buff), "\\%d", (int)uchar(*s));
  882. else
  883. l_sprintf(buff, sizeof(buff), "\\%03d", (int)uchar(*s));
  884. luaL_addstring(b, buff);
  885. }
  886. else
  887. luaL_addchar(b, *s);
  888. s++;
  889. }
  890. luaL_addchar(b, '"');
  891. }
  892. /*
  893. ** Serialize a floating-point number in such a way that it can be
  894. ** scanned back by Lua. Use hexadecimal format for "common" numbers
  895. ** (to preserve precision); inf, -inf, and NaN are handled separately.
  896. ** (NaN cannot be expressed as a numeral, so we write '(0/0)' for it.)
  897. */
  898. static int quotefloat (lua_State *L, char *buff, lua_Number n) {
  899. const char *s; /* for the fixed representations */
  900. if (n == (lua_Number)HUGE_VAL) /* inf? */
  901. s = "1e9999";
  902. else if (n == -(lua_Number)HUGE_VAL) /* -inf? */
  903. s = "-1e9999";
  904. else if (n != n) /* NaN? */
  905. s = "(0/0)";
  906. else { /* format number as hexadecimal */
  907. int nb = lua_number2strx(L, buff, MAX_ITEM,
  908. "%" LUA_NUMBER_FRMLEN "a", n);
  909. /* ensures that 'buff' string uses a dot as the radix character */
  910. if (memchr(buff, '.', nb) == NULL) { /* no dot? */
  911. char point = lua_getlocaledecpoint(); /* try locale point */
  912. char *ppoint = (char *)memchr(buff, point, nb);
  913. if (ppoint) *ppoint = '.'; /* change it to a dot */
  914. }
  915. return nb;
  916. }
  917. /* for the fixed representations */
  918. return l_sprintf(buff, MAX_ITEM, "%s", s);
  919. }
  920. static void addliteral (lua_State *L, luaL_Buffer *b, int arg) {
  921. switch (lua_type(L, arg)) {
  922. case LUA_TSTRING: {
  923. size_t len;
  924. const char *s = lua_tolstring(L, arg, &len);
  925. addquoted(b, s, len);
  926. break;
  927. }
  928. case LUA_TNUMBER: {
  929. char *buff = luaL_prepbuffsize(b, MAX_ITEM);
  930. int nb;
  931. if (!lua_isinteger(L, arg)) /* float? */
  932. nb = quotefloat(L, buff, lua_tonumber(L, arg));
  933. else { /* integers */
  934. lua_Integer n = lua_tointeger(L, arg);
  935. const char *format = (n == LUA_MININTEGER) /* corner case? */
  936. ? "0x%" LUA_INTEGER_FRMLEN "x" /* use hex */
  937. : LUA_INTEGER_FMT; /* else use default format */
  938. nb = l_sprintf(buff, MAX_ITEM, format, (LUAI_UACINT)n);
  939. }
  940. luaL_addsize(b, nb);
  941. break;
  942. }
  943. case LUA_TNIL: case LUA_TBOOLEAN: {
  944. luaL_tolstring(L, arg, NULL);
  945. luaL_addvalue(b);
  946. break;
  947. }
  948. default: {
  949. luaL_argerror(L, arg, "value has no literal form");
  950. }
  951. }
  952. }
  953. static const char *scanformat (lua_State *L, const char *strfrmt, char *form) {
  954. const char *p = strfrmt;
  955. while (*p != '\0' && strchr(FLAGS, *p) != NULL) p++; /* skip flags */
  956. if ((size_t)(p - strfrmt) >= sizeof(FLAGS)/sizeof(char))
  957. luaL_error(L, "invalid format (repeated flags)");
  958. if (isdigit(uchar(*p))) p++; /* skip width */
  959. if (isdigit(uchar(*p))) p++; /* (2 digits at most) */
  960. if (*p == '.') {
  961. p++;
  962. if (isdigit(uchar(*p))) p++; /* skip precision */
  963. if (isdigit(uchar(*p))) p++; /* (2 digits at most) */
  964. }
  965. if (isdigit(uchar(*p)))
  966. luaL_error(L, "invalid format (width or precision too long)");
  967. *(form++) = '%';
  968. memcpy(form, strfrmt, ((p - strfrmt) + 1) * sizeof(char));
  969. form += (p - strfrmt) + 1;
  970. *form = '\0';
  971. return p;
  972. }
  973. /*
  974. ** add length modifier into formats
  975. */
  976. static void addlenmod (char *form, const char *lenmod) {
  977. size_t l = strlen(form);
  978. size_t lm = strlen(lenmod);
  979. char spec = form[l - 1];
  980. strcpy(form + l - 1, lenmod);
  981. form[l + lm - 1] = spec;
  982. form[l + lm] = '\0';
  983. }
  984. static int str_format (lua_State *L) {
  985. int top = lua_gettop(L);
  986. int arg = 1;
  987. size_t sfl;
  988. const char *strfrmt = luaL_checklstring(L, arg, &sfl);
  989. const char *strfrmt_end = strfrmt+sfl;
  990. luaL_Buffer b;
  991. luaL_buffinit(L, &b);
  992. while (strfrmt < strfrmt_end) {
  993. if (*strfrmt != L_ESC)
  994. luaL_addchar(&b, *strfrmt++);
  995. else if (*++strfrmt == L_ESC)
  996. luaL_addchar(&b, *strfrmt++); /* %% */
  997. else { /* format item */
  998. char form[MAX_FORMAT]; /* to store the format ('%...') */
  999. char *buff = luaL_prepbuffsize(&b, MAX_ITEM); /* to put formatted item */
  1000. int nb = 0; /* number of bytes in added item */
  1001. if (++arg > top)
  1002. return luaL_argerror(L, arg, "no value");
  1003. strfrmt = scanformat(L, strfrmt, form);
  1004. switch (*strfrmt++) {
  1005. case 'c': {
  1006. nb = l_sprintf(buff, MAX_ITEM, form, (int)luaL_checkinteger(L, arg));
  1007. break;
  1008. }
  1009. case 'd': case 'i':
  1010. case 'o': case 'u': case 'x': case 'X': {
  1011. lua_Integer n = luaL_checkinteger(L, arg);
  1012. addlenmod(form, LUA_INTEGER_FRMLEN);
  1013. nb = l_sprintf(buff, MAX_ITEM, form, (LUAI_UACINT)n);
  1014. break;
  1015. }
  1016. case 'a': case 'A':
  1017. addlenmod(form, LUA_NUMBER_FRMLEN);
  1018. nb = lua_number2strx(L, buff, MAX_ITEM, form,
  1019. luaL_checknumber(L, arg));
  1020. break;
  1021. case 'e': case 'E': case 'f':
  1022. case 'g': case 'G': {
  1023. lua_Number n = luaL_checknumber(L, arg);
  1024. addlenmod(form, LUA_NUMBER_FRMLEN);
  1025. nb = l_sprintf(buff, MAX_ITEM, form, (LUAI_UACNUMBER)n);
  1026. break;
  1027. }
  1028. case 'p': {
  1029. const void *p = lua_topointer(L, arg);
  1030. nb = l_sprintf(buff, MAX_ITEM, form, p);
  1031. break;
  1032. }
  1033. case 'q': {
  1034. if (form[2] != '\0') /* modifiers? */
  1035. return luaL_error(L, "specifier '%%q' cannot have modifiers");
  1036. addliteral(L, &b, arg);
  1037. break;
  1038. }
  1039. case 's': {
  1040. size_t l;
  1041. const char *s = luaL_tolstring(L, arg, &l);
  1042. if (form[2] == '\0') /* no modifiers? */
  1043. luaL_addvalue(&b); /* keep entire string */
  1044. else {
  1045. luaL_argcheck(L, l == strlen(s), arg, "string contains zeros");
  1046. if (!strchr(form, '.') && l >= 100) {
  1047. /* no precision and string is too long to be formatted */
  1048. luaL_addvalue(&b); /* keep entire string */
  1049. }
  1050. else { /* format the string into 'buff' */
  1051. nb = l_sprintf(buff, MAX_ITEM, form, s);
  1052. lua_pop(L, 1); /* remove result from 'luaL_tolstring' */
  1053. }
  1054. }
  1055. break;
  1056. }
  1057. default: { /* also treat cases 'pnLlh' */
  1058. return luaL_error(L, "invalid conversion '%s' to 'format'", form);
  1059. }
  1060. }
  1061. lua_assert(nb < MAX_ITEM);
  1062. luaL_addsize(&b, nb);
  1063. }
  1064. }
  1065. luaL_pushresult(&b);
  1066. return 1;
  1067. }
  1068. /* }====================================================== */
  1069. /*
  1070. ** {======================================================
  1071. ** PACK/UNPACK
  1072. ** =======================================================
  1073. */
  1074. /* value used for padding */
  1075. #if !defined(LUAL_PACKPADBYTE)
  1076. #define LUAL_PACKPADBYTE 0x00
  1077. #endif
  1078. /* maximum size for the binary representation of an integer */
  1079. #define MAXINTSIZE 16
  1080. /* number of bits in a character */
  1081. #define NB CHAR_BIT
  1082. /* mask for one character (NB 1's) */
  1083. #define MC ((1 << NB) - 1)
  1084. /* size of a lua_Integer */
  1085. #define SZINT ((int)sizeof(lua_Integer))
  1086. /* dummy union to get native endianness */
  1087. static const union {
  1088. int dummy;
  1089. char little; /* true iff machine is little endian */
  1090. } nativeendian = {1};
  1091. /* dummy structure to get native alignment requirements */
  1092. struct cD {
  1093. char c;
  1094. union { double d; void *p; lua_Integer i; lua_Number n; } u;
  1095. };
  1096. #define MAXALIGN (offsetof(struct cD, u))
  1097. /*
  1098. ** Union for serializing floats
  1099. */
  1100. typedef union Ftypes {
  1101. float f;
  1102. double d;
  1103. lua_Number n;
  1104. char buff[5 * sizeof(lua_Number)]; /* enough for any float type */
  1105. } Ftypes;
  1106. /*
  1107. ** information to pack/unpack stuff
  1108. */
  1109. typedef struct Header {
  1110. lua_State *L;
  1111. int islittle;
  1112. int maxalign;
  1113. } Header;
  1114. /*
  1115. ** options for pack/unpack
  1116. */
  1117. typedef enum KOption {
  1118. Kint, /* signed integers */
  1119. Kuint, /* unsigned integers */
  1120. Kfloat, /* floating-point numbers */
  1121. Kchar, /* fixed-length strings */
  1122. Kstring, /* strings with prefixed length */
  1123. Kzstr, /* zero-terminated strings */
  1124. Kpadding, /* padding */
  1125. Kpaddalign, /* padding for alignment */
  1126. Knop /* no-op (configuration or spaces) */
  1127. } KOption;
  1128. /*
  1129. ** Read an integer numeral from string 'fmt' or return 'df' if
  1130. ** there is no numeral
  1131. */
  1132. static int digit (int c) { return '0' <= c && c <= '9'; }
  1133. static int getnum (const char **fmt, int df) {
  1134. if (!digit(**fmt)) /* no number? */
  1135. return df; /* return default value */
  1136. else {
  1137. int a = 0;
  1138. do {
  1139. a = a*10 + (*((*fmt)++) - '0');
  1140. } while (digit(**fmt) && a <= ((int)MAXSIZE - 9)/10);
  1141. return a;
  1142. }
  1143. }
  1144. /*
  1145. ** Read an integer numeral and raises an error if it is larger
  1146. ** than the maximum size for integers.
  1147. */
  1148. static int getnumlimit (Header *h, const char **fmt, int df) {
  1149. int sz = getnum(fmt, df);
  1150. if (sz > MAXINTSIZE || sz <= 0)
  1151. return luaL_error(h->L, "integral size (%d) out of limits [1,%d]",
  1152. sz, MAXINTSIZE);
  1153. return sz;
  1154. }
  1155. /*
  1156. ** Initialize Header
  1157. */
  1158. static void initheader (lua_State *L, Header *h) {
  1159. h->L = L;
  1160. h->islittle = nativeendian.little;
  1161. h->maxalign = 1;
  1162. }
  1163. /*
  1164. ** Read and classify next option. 'size' is filled with option's size.
  1165. */
  1166. static KOption getoption (Header *h, const char **fmt, int *size) {
  1167. int opt = *((*fmt)++);
  1168. *size = 0; /* default */
  1169. switch (opt) {
  1170. case 'b': *size = sizeof(char); return Kint;
  1171. case 'B': *size = sizeof(char); return Kuint;
  1172. case 'h': *size = sizeof(short); return Kint;
  1173. case 'H': *size = sizeof(short); return Kuint;
  1174. case 'l': *size = sizeof(long); return Kint;
  1175. case 'L': *size = sizeof(long); return Kuint;
  1176. case 'j': *size = sizeof(lua_Integer); return Kint;
  1177. case 'J': *size = sizeof(lua_Integer); return Kuint;
  1178. case 'T': *size = sizeof(size_t); return Kuint;
  1179. case 'f': *size = sizeof(float); return Kfloat;
  1180. case 'd': *size = sizeof(double); return Kfloat;
  1181. case 'n': *size = sizeof(lua_Number); return Kfloat;
  1182. case 'i': *size = getnumlimit(h, fmt, sizeof(int)); return Kint;
  1183. case 'I': *size = getnumlimit(h, fmt, sizeof(int)); return Kuint;
  1184. case 's': *size = getnumlimit(h, fmt, sizeof(size_t)); return Kstring;
  1185. case 'c':
  1186. *size = getnum(fmt, -1);
  1187. if (*size == -1)
  1188. luaL_error(h->L, "missing size for format option 'c'");
  1189. return Kchar;
  1190. case 'z': return Kzstr;
  1191. case 'x': *size = 1; return Kpadding;
  1192. case 'X': return Kpaddalign;
  1193. case ' ': break;
  1194. case '<': h->islittle = 1; break;
  1195. case '>': h->islittle = 0; break;
  1196. case '=': h->islittle = nativeendian.little; break;
  1197. case '!': h->maxalign = getnumlimit(h, fmt, MAXALIGN); break;
  1198. default: luaL_error(h->L, "invalid format option '%c'", opt);
  1199. }
  1200. return Knop;
  1201. }
  1202. /*
  1203. ** Read, classify, and fill other details about the next option.
  1204. ** 'psize' is filled with option's size, 'notoalign' with its
  1205. ** alignment requirements.
  1206. ** Local variable 'size' gets the size to be aligned. (Kpadal option
  1207. ** always gets its full alignment, other options are limited by
  1208. ** the maximum alignment ('maxalign'). Kchar option needs no alignment
  1209. ** despite its size.
  1210. */
  1211. static KOption getdetails (Header *h, size_t totalsize,
  1212. const char **fmt, int *psize, int *ntoalign) {
  1213. KOption opt = getoption(h, fmt, psize);
  1214. int align = *psize; /* usually, alignment follows size */
  1215. if (opt == Kpaddalign) { /* 'X' gets alignment from following option */
  1216. if (**fmt == '\0' || getoption(h, fmt, &align) == Kchar || align == 0)
  1217. luaL_argerror(h->L, 1, "invalid next option for option 'X'");
  1218. }
  1219. if (align <= 1 || opt == Kchar) /* need no alignment? */
  1220. *ntoalign = 0;
  1221. else {
  1222. if (align > h->maxalign) /* enforce maximum alignment */
  1223. align = h->maxalign;
  1224. if ((align & (align - 1)) != 0) /* is 'align' not a power of 2? */
  1225. luaL_argerror(h->L, 1, "format asks for alignment not power of 2");
  1226. *ntoalign = (align - (int)(totalsize & (align - 1))) & (align - 1);
  1227. }
  1228. return opt;
  1229. }
  1230. /*
  1231. ** Pack integer 'n' with 'size' bytes and 'islittle' endianness.
  1232. ** The final 'if' handles the case when 'size' is larger than
  1233. ** the size of a Lua integer, correcting the extra sign-extension
  1234. ** bytes if necessary (by default they would be zeros).
  1235. */
  1236. static void packint (luaL_Buffer *b, lua_Unsigned n,
  1237. int islittle, int size, int neg) {
  1238. char *buff = luaL_prepbuffsize(b, size);
  1239. int i;
  1240. buff[islittle ? 0 : size - 1] = (char)(n & MC); /* first byte */
  1241. for (i = 1; i < size; i++) {
  1242. n >>= NB;
  1243. buff[islittle ? i : size - 1 - i] = (char)(n & MC);
  1244. }
  1245. if (neg && size > SZINT) { /* negative number need sign extension? */
  1246. for (i = SZINT; i < size; i++) /* correct extra bytes */
  1247. buff[islittle ? i : size - 1 - i] = (char)MC;
  1248. }
  1249. luaL_addsize(b, size); /* add result to buffer */
  1250. }
  1251. /*
  1252. ** Copy 'size' bytes from 'src' to 'dest', correcting endianness if
  1253. ** given 'islittle' is different from native endianness.
  1254. */
  1255. static void copywithendian (volatile char *dest, volatile const char *src,
  1256. int size, int islittle) {
  1257. if (islittle == nativeendian.little) {
  1258. while (size-- != 0)
  1259. *(dest++) = *(src++);
  1260. }
  1261. else {
  1262. dest += size - 1;
  1263. while (size-- != 0)
  1264. *(dest--) = *(src++);
  1265. }
  1266. }
  1267. static int str_pack (lua_State *L) {
  1268. luaL_Buffer b;
  1269. Header h;
  1270. const char *fmt = luaL_checkstring(L, 1); /* format string */
  1271. int arg = 1; /* current argument to pack */
  1272. size_t totalsize = 0; /* accumulate total size of result */
  1273. initheader(L, &h);
  1274. lua_pushnil(L); /* mark to separate arguments from string buffer */
  1275. luaL_buffinit(L, &b);
  1276. while (*fmt != '\0') {
  1277. int size, ntoalign;
  1278. KOption opt = getdetails(&h, totalsize, &fmt, &size, &ntoalign);
  1279. totalsize += ntoalign + size;
  1280. while (ntoalign-- > 0)
  1281. luaL_addchar(&b, LUAL_PACKPADBYTE); /* fill alignment */
  1282. arg++;
  1283. switch (opt) {
  1284. case Kint: { /* signed integers */
  1285. lua_Integer n = luaL_checkinteger(L, arg);
  1286. if (size < SZINT) { /* need overflow check? */
  1287. lua_Integer lim = (lua_Integer)1 << ((size * NB) - 1);
  1288. luaL_argcheck(L, -lim <= n && n < lim, arg, "integer overflow");
  1289. }
  1290. packint(&b, (lua_Unsigned)n, h.islittle, size, (n < 0));
  1291. break;
  1292. }
  1293. case Kuint: { /* unsigned integers */
  1294. lua_Integer n = luaL_checkinteger(L, arg);
  1295. if (size < SZINT) /* need overflow check? */
  1296. luaL_argcheck(L, (lua_Unsigned)n < ((lua_Unsigned)1 << (size * NB)),
  1297. arg, "unsigned overflow");
  1298. packint(&b, (lua_Unsigned)n, h.islittle, size, 0);
  1299. break;
  1300. }
  1301. case Kfloat: { /* floating-point options */
  1302. volatile Ftypes u;
  1303. char *buff = luaL_prepbuffsize(&b, size);
  1304. lua_Number n = luaL_checknumber(L, arg); /* get argument */
  1305. if (size == sizeof(u.f)) u.f = (float)n; /* copy it into 'u' */
  1306. else if (size == sizeof(u.d)) u.d = (double)n;
  1307. else u.n = n;
  1308. /* move 'u' to final result, correcting endianness if needed */
  1309. copywithendian(buff, u.buff, size, h.islittle);
  1310. luaL_addsize(&b, size);
  1311. break;
  1312. }
  1313. case Kchar: { /* fixed-size string */
  1314. size_t len;
  1315. const char *s = luaL_checklstring(L, arg, &len);
  1316. luaL_argcheck(L, len <= (size_t)size, arg,
  1317. "string longer than given size");
  1318. luaL_addlstring(&b, s, len); /* add string */
  1319. while (len++ < (size_t)size) /* pad extra space */
  1320. luaL_addchar(&b, LUAL_PACKPADBYTE);
  1321. break;
  1322. }
  1323. case Kstring: { /* strings with length count */
  1324. size_t len;
  1325. const char *s = luaL_checklstring(L, arg, &len);
  1326. luaL_argcheck(L, size >= (int)sizeof(size_t) ||
  1327. len < ((size_t)1 << (size * NB)),
  1328. arg, "string length does not fit in given size");
  1329. packint(&b, (lua_Unsigned)len, h.islittle, size, 0); /* pack length */
  1330. luaL_addlstring(&b, s, len);
  1331. totalsize += len;
  1332. break;
  1333. }
  1334. case Kzstr: { /* zero-terminated string */
  1335. size_t len;
  1336. const char *s = luaL_checklstring(L, arg, &len);
  1337. luaL_argcheck(L, strlen(s) == len, arg, "string contains zeros");
  1338. luaL_addlstring(&b, s, len);
  1339. luaL_addchar(&b, '\0'); /* add zero at the end */
  1340. totalsize += len + 1;
  1341. break;
  1342. }
  1343. case Kpadding: luaL_addchar(&b, LUAL_PACKPADBYTE); /* FALLTHROUGH */
  1344. case Kpaddalign: case Knop:
  1345. arg--; /* undo increment */
  1346. break;
  1347. }
  1348. }
  1349. luaL_pushresult(&b);
  1350. return 1;
  1351. }
  1352. static int str_packsize (lua_State *L) {
  1353. Header h;
  1354. const char *fmt = luaL_checkstring(L, 1); /* format string */
  1355. size_t totalsize = 0; /* accumulate total size of result */
  1356. initheader(L, &h);
  1357. while (*fmt != '\0') {
  1358. int size, ntoalign;
  1359. KOption opt = getdetails(&h, totalsize, &fmt, &size, &ntoalign);
  1360. luaL_argcheck(L, opt != Kstring && opt != Kzstr, 1,
  1361. "variable-length format");
  1362. size += ntoalign; /* total space used by option */
  1363. luaL_argcheck(L, totalsize <= MAXSIZE - size, 1,
  1364. "format result too large");
  1365. totalsize += size;
  1366. }
  1367. lua_pushinteger(L, (lua_Integer)totalsize);
  1368. return 1;
  1369. }
  1370. /*
  1371. ** Unpack an integer with 'size' bytes and 'islittle' endianness.
  1372. ** If size is smaller than the size of a Lua integer and integer
  1373. ** is signed, must do sign extension (propagating the sign to the
  1374. ** higher bits); if size is larger than the size of a Lua integer,
  1375. ** it must check the unread bytes to see whether they do not cause an
  1376. ** overflow.
  1377. */
  1378. static lua_Integer unpackint (lua_State *L, const char *str,
  1379. int islittle, int size, int issigned) {
  1380. lua_Unsigned res = 0;
  1381. int i;
  1382. int limit = (size <= SZINT) ? size : SZINT;
  1383. for (i = limit - 1; i >= 0; i--) {
  1384. res <<= NB;
  1385. res |= (lua_Unsigned)(unsigned char)str[islittle ? i : size - 1 - i];
  1386. }
  1387. if (size < SZINT) { /* real size smaller than lua_Integer? */
  1388. if (issigned) { /* needs sign extension? */
  1389. lua_Unsigned mask = (lua_Unsigned)1 << (size*NB - 1);
  1390. res = ((res ^ mask) - mask); /* do sign extension */
  1391. }
  1392. }
  1393. else if (size > SZINT) { /* must check unread bytes */
  1394. int mask = (!issigned || (lua_Integer)res >= 0) ? 0 : MC;
  1395. for (i = limit; i < size; i++) {
  1396. if ((unsigned char)str[islittle ? i : size - 1 - i] != mask)
  1397. luaL_error(L, "%d-byte integer does not fit into Lua Integer", size);
  1398. }
  1399. }
  1400. return (lua_Integer)res;
  1401. }
  1402. static int str_unpack (lua_State *L) {
  1403. Header h;
  1404. const char *fmt = luaL_checkstring(L, 1);
  1405. size_t ld;
  1406. const char *data = luaL_checklstring(L, 2, &ld);
  1407. size_t pos = posrelatI(luaL_optinteger(L, 3, 1), ld) - 1;
  1408. int n = 0; /* number of results */
  1409. luaL_argcheck(L, pos <= ld, 3, "initial position out of string");
  1410. initheader(L, &h);
  1411. while (*fmt != '\0') {
  1412. int size, ntoalign;
  1413. KOption opt = getdetails(&h, pos, &fmt, &size, &ntoalign);
  1414. luaL_argcheck(L, (size_t)ntoalign + size <= ld - pos, 2,
  1415. "data string too short");
  1416. pos += ntoalign; /* skip alignment */
  1417. /* stack space for item + next position */
  1418. luaL_checkstack(L, 2, "too many results");
  1419. n++;
  1420. switch (opt) {
  1421. case Kint:
  1422. case Kuint: {
  1423. lua_Integer res = unpackint(L, data + pos, h.islittle, size,
  1424. (opt == Kint));
  1425. lua_pushinteger(L, res);
  1426. break;
  1427. }
  1428. case Kfloat: {
  1429. volatile Ftypes u;
  1430. lua_Number num;
  1431. copywithendian(u.buff, data + pos, size, h.islittle);
  1432. if (size == sizeof(u.f)) num = (lua_Number)u.f;
  1433. else if (size == sizeof(u.d)) num = (lua_Number)u.d;
  1434. else num = u.n;
  1435. lua_pushnumber(L, num);
  1436. break;
  1437. }
  1438. case Kchar: {
  1439. lua_pushlstring(L, data + pos, size);
  1440. break;
  1441. }
  1442. case Kstring: {
  1443. size_t len = (size_t)unpackint(L, data + pos, h.islittle, size, 0);
  1444. luaL_argcheck(L, len <= ld - pos - size, 2, "data string too short");
  1445. lua_pushlstring(L, data + pos + size, len);
  1446. pos += len; /* skip string */
  1447. break;
  1448. }
  1449. case Kzstr: {
  1450. size_t len = (int)strlen(data + pos);
  1451. luaL_argcheck(L, pos + len < ld, 2,
  1452. "unfinished string for format 'z'");
  1453. lua_pushlstring(L, data + pos, len);
  1454. pos += len + 1; /* skip string plus final '\0' */
  1455. break;
  1456. }
  1457. case Kpaddalign: case Kpadding: case Knop:
  1458. n--; /* undo increment */
  1459. break;
  1460. }
  1461. pos += size;
  1462. }
  1463. lua_pushinteger(L, pos + 1); /* next position */
  1464. return n + 1;
  1465. }
  1466. /* }====================================================== */
  1467. static const luaL_Reg strlib[] = {
  1468. {"byte", str_byte},
  1469. {"char", str_char},
  1470. {"dump", str_dump},
  1471. {"find", str_find},
  1472. {"format", str_format},
  1473. {"gmatch", gmatch},
  1474. {"gsub", str_gsub},
  1475. {"len", str_len},
  1476. {"lower", str_lower},
  1477. {"match", str_match},
  1478. {"rep", str_rep},
  1479. {"reverse", str_reverse},
  1480. {"sub", str_sub},
  1481. {"upper", str_upper},
  1482. {"pack", str_pack},
  1483. {"packsize", str_packsize},
  1484. {"unpack", str_unpack},
  1485. {NULL, NULL}
  1486. };
  1487. static void createmetatable (lua_State *L) {
  1488. /* table to be metatable for strings */
  1489. luaL_newlibtable(L, stringmetamethods);
  1490. luaL_setfuncs(L, stringmetamethods, 0);
  1491. lua_pushliteral(L, ""); /* dummy string */
  1492. lua_pushvalue(L, -2); /* copy table */
  1493. lua_setmetatable(L, -2); /* set table as metatable for strings */
  1494. lua_pop(L, 1); /* pop dummy string */
  1495. lua_pushvalue(L, -2); /* get string library */
  1496. lua_setfield(L, -2, "__index"); /* metatable.__index = string */
  1497. lua_pop(L, 1); /* pop metatable */
  1498. }
  1499. /*
  1500. ** Open string library
  1501. */
  1502. LUAMOD_API int luaopen_string (lua_State *L) {
  1503. luaL_newlib(L, strlib);
  1504. createmetatable(L);
  1505. return 1;
  1506. }