lstrlib.c 52 KB

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