lstrlib.c 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712
  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 'q': {
  1029. if (form[2] != '\0') /* modifiers? */
  1030. return luaL_error(L, "specifier '%%q' cannot have modifiers");
  1031. addliteral(L, &b, arg);
  1032. break;
  1033. }
  1034. case 's': {
  1035. size_t l;
  1036. const char *s = luaL_tolstring(L, arg, &l);
  1037. if (form[2] == '\0') /* no modifiers? */
  1038. luaL_addvalue(&b); /* keep entire string */
  1039. else {
  1040. luaL_argcheck(L, l == strlen(s), arg, "string contains zeros");
  1041. if (!strchr(form, '.') && l >= 100) {
  1042. /* no precision and string is too long to be formatted */
  1043. luaL_addvalue(&b); /* keep entire string */
  1044. }
  1045. else { /* format the string into 'buff' */
  1046. nb = l_sprintf(buff, MAX_ITEM, form, s);
  1047. lua_pop(L, 1); /* remove result from 'luaL_tolstring' */
  1048. }
  1049. }
  1050. break;
  1051. }
  1052. default: { /* also treat cases 'pnLlh' */
  1053. return luaL_error(L, "invalid conversion '%s' to 'format'", form);
  1054. }
  1055. }
  1056. lua_assert(nb < MAX_ITEM);
  1057. luaL_addsize(&b, nb);
  1058. }
  1059. }
  1060. luaL_pushresult(&b);
  1061. return 1;
  1062. }
  1063. /* }====================================================== */
  1064. /*
  1065. ** {======================================================
  1066. ** PACK/UNPACK
  1067. ** =======================================================
  1068. */
  1069. /* value used for padding */
  1070. #if !defined(LUAL_PACKPADBYTE)
  1071. #define LUAL_PACKPADBYTE 0x00
  1072. #endif
  1073. /* maximum size for the binary representation of an integer */
  1074. #define MAXINTSIZE 16
  1075. /* number of bits in a character */
  1076. #define NB CHAR_BIT
  1077. /* mask for one character (NB 1's) */
  1078. #define MC ((1 << NB) - 1)
  1079. /* size of a lua_Integer */
  1080. #define SZINT ((int)sizeof(lua_Integer))
  1081. /* dummy union to get native endianness */
  1082. static const union {
  1083. int dummy;
  1084. char little; /* true iff machine is little endian */
  1085. } nativeendian = {1};
  1086. /* dummy structure to get native alignment requirements */
  1087. struct cD {
  1088. char c;
  1089. union { double d; void *p; lua_Integer i; lua_Number n; } u;
  1090. };
  1091. #define MAXALIGN (offsetof(struct cD, u))
  1092. /*
  1093. ** Union for serializing floats
  1094. */
  1095. typedef union Ftypes {
  1096. float f;
  1097. double d;
  1098. lua_Number n;
  1099. char buff[5 * sizeof(lua_Number)]; /* enough for any float type */
  1100. } Ftypes;
  1101. /*
  1102. ** information to pack/unpack stuff
  1103. */
  1104. typedef struct Header {
  1105. lua_State *L;
  1106. int islittle;
  1107. int maxalign;
  1108. } Header;
  1109. /*
  1110. ** options for pack/unpack
  1111. */
  1112. typedef enum KOption {
  1113. Kint, /* signed integers */
  1114. Kuint, /* unsigned integers */
  1115. Kfloat, /* floating-point numbers */
  1116. Kchar, /* fixed-length strings */
  1117. Kstring, /* strings with prefixed length */
  1118. Kzstr, /* zero-terminated strings */
  1119. Kpadding, /* padding */
  1120. Kpaddalign, /* padding for alignment */
  1121. Knop /* no-op (configuration or spaces) */
  1122. } KOption;
  1123. /*
  1124. ** Read an integer numeral from string 'fmt' or return 'df' if
  1125. ** there is no numeral
  1126. */
  1127. static int digit (int c) { return '0' <= c && c <= '9'; }
  1128. static int getnum (const char **fmt, int df) {
  1129. if (!digit(**fmt)) /* no number? */
  1130. return df; /* return default value */
  1131. else {
  1132. int a = 0;
  1133. do {
  1134. a = a*10 + (*((*fmt)++) - '0');
  1135. } while (digit(**fmt) && a <= ((int)MAXSIZE - 9)/10);
  1136. return a;
  1137. }
  1138. }
  1139. /*
  1140. ** Read an integer numeral and raises an error if it is larger
  1141. ** than the maximum size for integers.
  1142. */
  1143. static int getnumlimit (Header *h, const char **fmt, int df) {
  1144. int sz = getnum(fmt, df);
  1145. if (sz > MAXINTSIZE || sz <= 0)
  1146. return luaL_error(h->L, "integral size (%d) out of limits [1,%d]",
  1147. sz, MAXINTSIZE);
  1148. return sz;
  1149. }
  1150. /*
  1151. ** Initialize Header
  1152. */
  1153. static void initheader (lua_State *L, Header *h) {
  1154. h->L = L;
  1155. h->islittle = nativeendian.little;
  1156. h->maxalign = 1;
  1157. }
  1158. /*
  1159. ** Read and classify next option. 'size' is filled with option's size.
  1160. */
  1161. static KOption getoption (Header *h, const char **fmt, int *size) {
  1162. int opt = *((*fmt)++);
  1163. *size = 0; /* default */
  1164. switch (opt) {
  1165. case 'b': *size = sizeof(char); return Kint;
  1166. case 'B': *size = sizeof(char); return Kuint;
  1167. case 'h': *size = sizeof(short); return Kint;
  1168. case 'H': *size = sizeof(short); return Kuint;
  1169. case 'l': *size = sizeof(long); return Kint;
  1170. case 'L': *size = sizeof(long); return Kuint;
  1171. case 'j': *size = sizeof(lua_Integer); return Kint;
  1172. case 'J': *size = sizeof(lua_Integer); return Kuint;
  1173. case 'T': *size = sizeof(size_t); return Kuint;
  1174. case 'f': *size = sizeof(float); return Kfloat;
  1175. case 'd': *size = sizeof(double); return Kfloat;
  1176. case 'n': *size = sizeof(lua_Number); return Kfloat;
  1177. case 'i': *size = getnumlimit(h, fmt, sizeof(int)); return Kint;
  1178. case 'I': *size = getnumlimit(h, fmt, sizeof(int)); return Kuint;
  1179. case 's': *size = getnumlimit(h, fmt, sizeof(size_t)); return Kstring;
  1180. case 'c':
  1181. *size = getnum(fmt, -1);
  1182. if (*size == -1)
  1183. luaL_error(h->L, "missing size for format option 'c'");
  1184. return Kchar;
  1185. case 'z': return Kzstr;
  1186. case 'x': *size = 1; return Kpadding;
  1187. case 'X': return Kpaddalign;
  1188. case ' ': break;
  1189. case '<': h->islittle = 1; break;
  1190. case '>': h->islittle = 0; break;
  1191. case '=': h->islittle = nativeendian.little; break;
  1192. case '!': h->maxalign = getnumlimit(h, fmt, MAXALIGN); break;
  1193. default: luaL_error(h->L, "invalid format option '%c'", opt);
  1194. }
  1195. return Knop;
  1196. }
  1197. /*
  1198. ** Read, classify, and fill other details about the next option.
  1199. ** 'psize' is filled with option's size, 'notoalign' with its
  1200. ** alignment requirements.
  1201. ** Local variable 'size' gets the size to be aligned. (Kpadal option
  1202. ** always gets its full alignment, other options are limited by
  1203. ** the maximum alignment ('maxalign'). Kchar option needs no alignment
  1204. ** despite its size.
  1205. */
  1206. static KOption getdetails (Header *h, size_t totalsize,
  1207. const char **fmt, int *psize, int *ntoalign) {
  1208. KOption opt = getoption(h, fmt, psize);
  1209. int align = *psize; /* usually, alignment follows size */
  1210. if (opt == Kpaddalign) { /* 'X' gets alignment from following option */
  1211. if (**fmt == '\0' || getoption(h, fmt, &align) == Kchar || align == 0)
  1212. luaL_argerror(h->L, 1, "invalid next option for option 'X'");
  1213. }
  1214. if (align <= 1 || opt == Kchar) /* need no alignment? */
  1215. *ntoalign = 0;
  1216. else {
  1217. if (align > h->maxalign) /* enforce maximum alignment */
  1218. align = h->maxalign;
  1219. if ((align & (align - 1)) != 0) /* is 'align' not a power of 2? */
  1220. luaL_argerror(h->L, 1, "format asks for alignment not power of 2");
  1221. *ntoalign = (align - (int)(totalsize & (align - 1))) & (align - 1);
  1222. }
  1223. return opt;
  1224. }
  1225. /*
  1226. ** Pack integer 'n' with 'size' bytes and 'islittle' endianness.
  1227. ** The final 'if' handles the case when 'size' is larger than
  1228. ** the size of a Lua integer, correcting the extra sign-extension
  1229. ** bytes if necessary (by default they would be zeros).
  1230. */
  1231. static void packint (luaL_Buffer *b, lua_Unsigned n,
  1232. int islittle, int size, int neg) {
  1233. char *buff = luaL_prepbuffsize(b, size);
  1234. int i;
  1235. buff[islittle ? 0 : size - 1] = (char)(n & MC); /* first byte */
  1236. for (i = 1; i < size; i++) {
  1237. n >>= NB;
  1238. buff[islittle ? i : size - 1 - i] = (char)(n & MC);
  1239. }
  1240. if (neg && size > SZINT) { /* negative number need sign extension? */
  1241. for (i = SZINT; i < size; i++) /* correct extra bytes */
  1242. buff[islittle ? i : size - 1 - i] = (char)MC;
  1243. }
  1244. luaL_addsize(b, size); /* add result to buffer */
  1245. }
  1246. /*
  1247. ** Copy 'size' bytes from 'src' to 'dest', correcting endianness if
  1248. ** given 'islittle' is different from native endianness.
  1249. */
  1250. static void copywithendian (volatile char *dest, volatile const char *src,
  1251. int size, int islittle) {
  1252. if (islittle == nativeendian.little) {
  1253. while (size-- != 0)
  1254. *(dest++) = *(src++);
  1255. }
  1256. else {
  1257. dest += size - 1;
  1258. while (size-- != 0)
  1259. *(dest--) = *(src++);
  1260. }
  1261. }
  1262. static int str_pack (lua_State *L) {
  1263. luaL_Buffer b;
  1264. Header h;
  1265. const char *fmt = luaL_checkstring(L, 1); /* format string */
  1266. int arg = 1; /* current argument to pack */
  1267. size_t totalsize = 0; /* accumulate total size of result */
  1268. initheader(L, &h);
  1269. lua_pushnil(L); /* mark to separate arguments from string buffer */
  1270. luaL_buffinit(L, &b);
  1271. while (*fmt != '\0') {
  1272. int size, ntoalign;
  1273. KOption opt = getdetails(&h, totalsize, &fmt, &size, &ntoalign);
  1274. totalsize += ntoalign + size;
  1275. while (ntoalign-- > 0)
  1276. luaL_addchar(&b, LUAL_PACKPADBYTE); /* fill alignment */
  1277. arg++;
  1278. switch (opt) {
  1279. case Kint: { /* signed integers */
  1280. lua_Integer n = luaL_checkinteger(L, arg);
  1281. if (size < SZINT) { /* need overflow check? */
  1282. lua_Integer lim = (lua_Integer)1 << ((size * NB) - 1);
  1283. luaL_argcheck(L, -lim <= n && n < lim, arg, "integer overflow");
  1284. }
  1285. packint(&b, (lua_Unsigned)n, h.islittle, size, (n < 0));
  1286. break;
  1287. }
  1288. case Kuint: { /* unsigned integers */
  1289. lua_Integer n = luaL_checkinteger(L, arg);
  1290. if (size < SZINT) /* need overflow check? */
  1291. luaL_argcheck(L, (lua_Unsigned)n < ((lua_Unsigned)1 << (size * NB)),
  1292. arg, "unsigned overflow");
  1293. packint(&b, (lua_Unsigned)n, h.islittle, size, 0);
  1294. break;
  1295. }
  1296. case Kfloat: { /* floating-point options */
  1297. volatile Ftypes u;
  1298. char *buff = luaL_prepbuffsize(&b, size);
  1299. lua_Number n = luaL_checknumber(L, arg); /* get argument */
  1300. if (size == sizeof(u.f)) u.f = (float)n; /* copy it into 'u' */
  1301. else if (size == sizeof(u.d)) u.d = (double)n;
  1302. else u.n = n;
  1303. /* move 'u' to final result, correcting endianness if needed */
  1304. copywithendian(buff, u.buff, size, h.islittle);
  1305. luaL_addsize(&b, size);
  1306. break;
  1307. }
  1308. case Kchar: { /* fixed-size string */
  1309. size_t len;
  1310. const char *s = luaL_checklstring(L, arg, &len);
  1311. luaL_argcheck(L, len <= (size_t)size, arg,
  1312. "string longer than given size");
  1313. luaL_addlstring(&b, s, len); /* add string */
  1314. while (len++ < (size_t)size) /* pad extra space */
  1315. luaL_addchar(&b, LUAL_PACKPADBYTE);
  1316. break;
  1317. }
  1318. case Kstring: { /* strings with length count */
  1319. size_t len;
  1320. const char *s = luaL_checklstring(L, arg, &len);
  1321. luaL_argcheck(L, size >= (int)sizeof(size_t) ||
  1322. len < ((size_t)1 << (size * NB)),
  1323. arg, "string length does not fit in given size");
  1324. packint(&b, (lua_Unsigned)len, h.islittle, size, 0); /* pack length */
  1325. luaL_addlstring(&b, s, len);
  1326. totalsize += len;
  1327. break;
  1328. }
  1329. case Kzstr: { /* zero-terminated string */
  1330. size_t len;
  1331. const char *s = luaL_checklstring(L, arg, &len);
  1332. luaL_argcheck(L, strlen(s) == len, arg, "string contains zeros");
  1333. luaL_addlstring(&b, s, len);
  1334. luaL_addchar(&b, '\0'); /* add zero at the end */
  1335. totalsize += len + 1;
  1336. break;
  1337. }
  1338. case Kpadding: luaL_addchar(&b, LUAL_PACKPADBYTE); /* FALLTHROUGH */
  1339. case Kpaddalign: case Knop:
  1340. arg--; /* undo increment */
  1341. break;
  1342. }
  1343. }
  1344. luaL_pushresult(&b);
  1345. return 1;
  1346. }
  1347. static int str_packsize (lua_State *L) {
  1348. Header h;
  1349. const char *fmt = luaL_checkstring(L, 1); /* format string */
  1350. size_t totalsize = 0; /* accumulate total size of result */
  1351. initheader(L, &h);
  1352. while (*fmt != '\0') {
  1353. int size, ntoalign;
  1354. KOption opt = getdetails(&h, totalsize, &fmt, &size, &ntoalign);
  1355. luaL_argcheck(L, opt != Kstring && opt != Kzstr, 1,
  1356. "variable-length format");
  1357. size += ntoalign; /* total space used by option */
  1358. luaL_argcheck(L, totalsize <= MAXSIZE - size, 1,
  1359. "format result too large");
  1360. totalsize += size;
  1361. }
  1362. lua_pushinteger(L, (lua_Integer)totalsize);
  1363. return 1;
  1364. }
  1365. /*
  1366. ** Unpack an integer with 'size' bytes and 'islittle' endianness.
  1367. ** If size is smaller than the size of a Lua integer and integer
  1368. ** is signed, must do sign extension (propagating the sign to the
  1369. ** higher bits); if size is larger than the size of a Lua integer,
  1370. ** it must check the unread bytes to see whether they do not cause an
  1371. ** overflow.
  1372. */
  1373. static lua_Integer unpackint (lua_State *L, const char *str,
  1374. int islittle, int size, int issigned) {
  1375. lua_Unsigned res = 0;
  1376. int i;
  1377. int limit = (size <= SZINT) ? size : SZINT;
  1378. for (i = limit - 1; i >= 0; i--) {
  1379. res <<= NB;
  1380. res |= (lua_Unsigned)(unsigned char)str[islittle ? i : size - 1 - i];
  1381. }
  1382. if (size < SZINT) { /* real size smaller than lua_Integer? */
  1383. if (issigned) { /* needs sign extension? */
  1384. lua_Unsigned mask = (lua_Unsigned)1 << (size*NB - 1);
  1385. res = ((res ^ mask) - mask); /* do sign extension */
  1386. }
  1387. }
  1388. else if (size > SZINT) { /* must check unread bytes */
  1389. int mask = (!issigned || (lua_Integer)res >= 0) ? 0 : MC;
  1390. for (i = limit; i < size; i++) {
  1391. if ((unsigned char)str[islittle ? i : size - 1 - i] != mask)
  1392. luaL_error(L, "%d-byte integer does not fit into Lua Integer", size);
  1393. }
  1394. }
  1395. return (lua_Integer)res;
  1396. }
  1397. static int str_unpack (lua_State *L) {
  1398. Header h;
  1399. const char *fmt = luaL_checkstring(L, 1);
  1400. size_t ld;
  1401. const char *data = luaL_checklstring(L, 2, &ld);
  1402. size_t pos = posrelatI(luaL_optinteger(L, 3, 1), ld) - 1;
  1403. int n = 0; /* number of results */
  1404. luaL_argcheck(L, pos <= ld, 3, "initial position out of string");
  1405. initheader(L, &h);
  1406. while (*fmt != '\0') {
  1407. int size, ntoalign;
  1408. KOption opt = getdetails(&h, pos, &fmt, &size, &ntoalign);
  1409. luaL_argcheck(L, (size_t)ntoalign + size <= ld - pos, 2,
  1410. "data string too short");
  1411. pos += ntoalign; /* skip alignment */
  1412. /* stack space for item + next position */
  1413. luaL_checkstack(L, 2, "too many results");
  1414. n++;
  1415. switch (opt) {
  1416. case Kint:
  1417. case Kuint: {
  1418. lua_Integer res = unpackint(L, data + pos, h.islittle, size,
  1419. (opt == Kint));
  1420. lua_pushinteger(L, res);
  1421. break;
  1422. }
  1423. case Kfloat: {
  1424. volatile Ftypes u;
  1425. lua_Number num;
  1426. copywithendian(u.buff, data + pos, size, h.islittle);
  1427. if (size == sizeof(u.f)) num = (lua_Number)u.f;
  1428. else if (size == sizeof(u.d)) num = (lua_Number)u.d;
  1429. else num = u.n;
  1430. lua_pushnumber(L, num);
  1431. break;
  1432. }
  1433. case Kchar: {
  1434. lua_pushlstring(L, data + pos, size);
  1435. break;
  1436. }
  1437. case Kstring: {
  1438. size_t len = (size_t)unpackint(L, data + pos, h.islittle, size, 0);
  1439. luaL_argcheck(L, len <= ld - pos - size, 2, "data string too short");
  1440. lua_pushlstring(L, data + pos + size, len);
  1441. pos += len; /* skip string */
  1442. break;
  1443. }
  1444. case Kzstr: {
  1445. size_t len = (int)strlen(data + pos);
  1446. luaL_argcheck(L, pos + len < ld, 2,
  1447. "unfinished string for format 'z'");
  1448. lua_pushlstring(L, data + pos, len);
  1449. pos += len + 1; /* skip string plus final '\0' */
  1450. break;
  1451. }
  1452. case Kpaddalign: case Kpadding: case Knop:
  1453. n--; /* undo increment */
  1454. break;
  1455. }
  1456. pos += size;
  1457. }
  1458. lua_pushinteger(L, pos + 1); /* next position */
  1459. return n + 1;
  1460. }
  1461. /* }====================================================== */
  1462. static const luaL_Reg strlib[] = {
  1463. {"byte", str_byte},
  1464. {"char", str_char},
  1465. {"dump", str_dump},
  1466. {"find", str_find},
  1467. {"format", str_format},
  1468. {"gmatch", gmatch},
  1469. {"gsub", str_gsub},
  1470. {"len", str_len},
  1471. {"lower", str_lower},
  1472. {"match", str_match},
  1473. {"rep", str_rep},
  1474. {"reverse", str_reverse},
  1475. {"sub", str_sub},
  1476. {"upper", str_upper},
  1477. {"pack", str_pack},
  1478. {"packsize", str_packsize},
  1479. {"unpack", str_unpack},
  1480. {NULL, NULL}
  1481. };
  1482. static void createmetatable (lua_State *L) {
  1483. /* table to be metatable for strings */
  1484. luaL_newlibtable(L, stringmetamethods);
  1485. luaL_setfuncs(L, stringmetamethods, 0);
  1486. lua_pushliteral(L, ""); /* dummy string */
  1487. lua_pushvalue(L, -2); /* copy table */
  1488. lua_setmetatable(L, -2); /* set table as metatable for strings */
  1489. lua_pop(L, 1); /* pop dummy string */
  1490. lua_pushvalue(L, -2); /* get string library */
  1491. lua_setfield(L, -2, "__index"); /* metatable.__index = string */
  1492. lua_pop(L, 1); /* pop metatable */
  1493. }
  1494. /*
  1495. ** Open string library
  1496. */
  1497. LUAMOD_API int luaopen_string (lua_State *L) {
  1498. luaL_newlib(L, strlib);
  1499. createmetatable(L);
  1500. return 1;
  1501. }