]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - module/lua/lstrlib.c
Vendor import of openzfs master @ 184df27eef0abdc7ab2105b21257f753834b936b
[FreeBSD/FreeBSD.git] / module / lua / lstrlib.c
1 /* BEGIN CSTYLED */
2 /*
3 ** $Id: lstrlib.c,v 1.178.1.1 2013/04/12 18:48:47 roberto Exp $
4 ** Standard library for string operations and pattern-matching
5 ** See Copyright Notice in lua.h
6 */
7
8
9 #define lstrlib_c
10 #define LUA_LIB
11
12 #include <sys/lua/lua.h>
13
14 #include <sys/lua/lauxlib.h>
15 #include <sys/lua/lualib.h>
16
17
18 /*
19 ** maximum number of captures that a pattern can do during
20 ** pattern-matching. This limit is arbitrary.
21 */
22 #if !defined(LUA_MAXCAPTURES)
23 #define LUA_MAXCAPTURES         16
24 #endif
25
26
27 /* macro to `unsign' a character */
28 #define uchar(c)        ((unsigned char)(c))
29
30 /*
31  * The provided version of sprintf returns a char *, but str_format expects
32  * it to return the number of characters printed. This version has the expected
33  * behavior.
34  */
35 static size_t str_sprintf(char *buf, const char *fmt, ...) {
36   va_list args;
37   size_t len;
38
39   va_start(args, fmt);
40   len = vsnprintf(buf, INT_MAX, fmt, args);
41   va_end(args);
42
43   return len;
44 }
45
46
47 static int str_len (lua_State *L) {
48   size_t l;
49   luaL_checklstring(L, 1, &l);
50   lua_pushinteger(L, (lua_Integer)l);
51   return 1;
52 }
53
54
55 /* translate a relative string position: negative means back from end */
56 static size_t posrelat (ptrdiff_t pos, size_t len) {
57   if (pos >= 0) return (size_t)pos;
58   else if (0u - (size_t)pos > len) return 0;
59   else return len - ((size_t)-pos) + 1;
60 }
61
62
63 static int str_sub (lua_State *L) {
64   size_t l;
65   const char *s = luaL_checklstring(L, 1, &l);
66   size_t start = posrelat(luaL_checkinteger(L, 2), l);
67   size_t end = posrelat(luaL_optinteger(L, 3, -1), l);
68   if (start < 1) start = 1;
69   if (end > l) end = l;
70   if (start <= end)
71     lua_pushlstring(L, s + start - 1, end - start + 1);
72   else lua_pushliteral(L, "");
73   return 1;
74 }
75
76
77 static int str_reverse (lua_State *L) {
78   size_t l, i;
79   luaL_Buffer b;
80   const char *s = luaL_checklstring(L, 1, &l);
81   char *p = luaL_buffinitsize(L, &b, l);
82   for (i = 0; i < l; i++)
83     p[i] = s[l - i - 1];
84   luaL_pushresultsize(&b, l);
85   return 1;
86 }
87
88
89 static int str_lower (lua_State *L) {
90   size_t l;
91   size_t i;
92   luaL_Buffer b;
93   const char *s = luaL_checklstring(L, 1, &l);
94   char *p = luaL_buffinitsize(L, &b, l);
95   for (i=0; i<l; i++)
96     p[i] = tolower(uchar(s[i]));
97   luaL_pushresultsize(&b, l);
98   return 1;
99 }
100
101
102 static int str_upper (lua_State *L) {
103   size_t l;
104   size_t i;
105   luaL_Buffer b;
106   const char *s = luaL_checklstring(L, 1, &l);
107   char *p = luaL_buffinitsize(L, &b, l);
108   for (i=0; i<l; i++)
109     p[i] = toupper(uchar(s[i]));
110   luaL_pushresultsize(&b, l);
111   return 1;
112 }
113
114
115 /* reasonable limit to avoid arithmetic overflow */
116 #define MAXSIZE         ((~(size_t)0) >> 1)
117
118 static int str_rep (lua_State *L) {
119   size_t l, lsep;
120   const char *s = luaL_checklstring(L, 1, &l);
121   int n = luaL_checkint(L, 2);
122   const char *sep = luaL_optlstring(L, 3, "", &lsep);
123   if (n <= 0) lua_pushliteral(L, "");
124   else if (l + lsep < l || l + lsep >= MAXSIZE / n)  /* may overflow? */
125     return luaL_error(L, "resulting string too large");
126   else {
127     size_t totallen = n * l + (n - 1) * lsep;
128     luaL_Buffer b;
129     char *p = luaL_buffinitsize(L, &b, totallen);
130     while (n-- > 1) {  /* first n-1 copies (followed by separator) */
131       memcpy(p, s, l * sizeof(char)); p += l;
132       if (lsep > 0) {  /* avoid empty 'memcpy' (may be expensive) */
133         memcpy(p, sep, lsep * sizeof(char)); p += lsep;
134       }
135     }
136     memcpy(p, s, l * sizeof(char));  /* last copy (not followed by separator) */
137     luaL_pushresultsize(&b, totallen);
138   }
139   return 1;
140 }
141
142
143 static int str_byte (lua_State *L) {
144   size_t l;
145   const char *s = luaL_checklstring(L, 1, &l);
146   size_t posi = posrelat(luaL_optinteger(L, 2, 1), l);
147   size_t pose = posrelat(luaL_optinteger(L, 3, posi), l);
148   int n, i;
149   if (posi < 1) posi = 1;
150   if (pose > l) pose = l;
151   if (posi > pose) return 0;  /* empty interval; return no values */
152   n = (int)(pose -  posi + 1);
153   if (posi + n <= pose)  /* (size_t -> int) overflow? */
154     return luaL_error(L, "string slice too long");
155   luaL_checkstack(L, n, "string slice too long");
156   for (i=0; i<n; i++)
157     lua_pushinteger(L, uchar(s[posi+i-1]));
158   return n;
159 }
160
161
162 static int str_char (lua_State *L) {
163   int n = lua_gettop(L);  /* number of arguments */
164   int i;
165   luaL_Buffer b;
166   char *p = luaL_buffinitsize(L, &b, n);
167   for (i=1; i<=n; i++) {
168     int c = luaL_checkint(L, i);
169     luaL_argcheck(L, uchar(c) == c, i, "value out of range");
170     p[i - 1] = uchar(c);
171   }
172   luaL_pushresultsize(&b, n);
173   return 1;
174 }
175
176
177 #if defined(LUA_USE_DUMP)
178 static int writer (lua_State *L, const void* b, size_t size, void* B) {
179   (void)L;
180   luaL_addlstring((luaL_Buffer*) B, (const char *)b, size);
181   return 0;
182 }
183
184
185 static int str_dump (lua_State *L) {
186   luaL_Buffer b;
187   luaL_checktype(L, 1, LUA_TFUNCTION);
188   lua_settop(L, 1);
189   luaL_buffinit(L,&b);
190   if (lua_dump(L, writer, &b) != 0)
191     return luaL_error(L, "unable to dump given function");
192   luaL_pushresult(&b);
193   return 1;
194 }
195 #endif
196
197
198 /*
199 ** {======================================================
200 ** PATTERN MATCHING
201 ** =======================================================
202 */
203
204
205 #define CAP_UNFINISHED  (-1)
206 #define CAP_POSITION    (-2)
207
208
209 typedef struct MatchState {
210   int matchdepth;  /* control for recursive depth (to avoid C stack overflow) */
211   const char *src_init;  /* init of source string */
212   const char *src_end;  /* end ('\0') of source string */
213   const char *p_end;  /* end ('\0') of pattern */
214   lua_State *L;
215   int level;  /* total number of captures (finished or unfinished) */
216   struct {
217     const char *init;
218     ptrdiff_t len;
219   } capture[LUA_MAXCAPTURES];
220 } MatchState;
221
222
223 /* recursive function */
224 static const char *match (MatchState *ms, const char *s, const char *p);
225
226
227 /* maximum recursion depth for 'match' */
228 #if !defined(MAXCCALLS)
229 #define MAXCCALLS       200
230 #endif
231
232
233 #define L_ESC           '%'
234 #define SPECIALS        "^$*+?.([%-"
235
236
237 static int check_capture (MatchState *ms, int l) {
238   l -= '1';
239   if (l < 0 || l >= ms->level || ms->capture[l].len == CAP_UNFINISHED)
240     return luaL_error(ms->L, "invalid capture index %%%d", l + 1);
241   return l;
242 }
243
244
245 static int capture_to_close (MatchState *ms) {
246   int level = ms->level;
247   for (level--; level>=0; level--)
248     if (ms->capture[level].len == CAP_UNFINISHED) return level;
249   return luaL_error(ms->L, "invalid pattern capture");
250 }
251
252
253 static const char *classend (MatchState *ms, const char *p) {
254   switch (*p++) {
255     case L_ESC: {
256       if (p == ms->p_end)
257         luaL_error(ms->L, "malformed pattern (ends with " LUA_QL("%%") ")");
258       return p+1;
259     }
260     case '[': {
261       if (*p == '^') p++;
262       do {  /* look for a `]' */
263         if (p == ms->p_end)
264           luaL_error(ms->L, "malformed pattern (missing " LUA_QL("]") ")");
265         if (*(p++) == L_ESC && p < ms->p_end)
266           p++;  /* skip escapes (e.g. `%]') */
267       } while (*p != ']');
268       return p+1;
269     }
270     default: {
271       return p;
272     }
273   }
274 }
275
276
277 static int match_class (int c, int cl) {
278   int res;
279   switch (tolower(cl)) {
280     case 'a' : res = isalpha(c); break;
281     case 'c' : res = iscntrl(c); break;
282     case 'd' : res = isdigit(c); break;
283     case 'g' : res = isgraph(c); break;
284     case 'l' : res = islower(c); break;
285     case 'p' : res = ispunct(c); break;
286     case 's' : res = isspace(c); break;
287     case 'u' : res = isupper(c); break;
288     case 'w' : res = isalnum(c); break;
289     case 'x' : res = isxdigit(c); break;
290     case 'z' : res = (c == 0); break;  /* deprecated option */
291     default: return (cl == c);
292   }
293   return (islower(cl) ? res : !res);
294 }
295
296
297 static int matchbracketclass (int c, const char *p, const char *ec) {
298   int sig = 1;
299   if (*(p+1) == '^') {
300     sig = 0;
301     p++;  /* skip the `^' */
302   }
303   while (++p < ec) {
304     if (*p == L_ESC) {
305       p++;
306       if (match_class(c, uchar(*p)))
307         return sig;
308     }
309     else if ((*(p+1) == '-') && (p+2 < ec)) {
310       p+=2;
311       if (uchar(*(p-2)) <= c && c <= uchar(*p))
312         return sig;
313     }
314     else if (uchar(*p) == c) return sig;
315   }
316   return !sig;
317 }
318
319
320 static int singlematch (MatchState *ms, const char *s, const char *p,
321                         const char *ep) {
322   if (s >= ms->src_end)
323     return 0;
324   else {
325     int c = uchar(*s);
326     switch (*p) {
327       case '.': return 1;  /* matches any char */
328       case L_ESC: return match_class(c, uchar(*(p+1)));
329       case '[': return matchbracketclass(c, p, ep-1);
330       default:  return (uchar(*p) == c);
331     }
332   }
333 }
334
335
336 static const char *matchbalance (MatchState *ms, const char *s,
337                                    const char *p) {
338   if (p >= ms->p_end - 1)
339     luaL_error(ms->L, "malformed pattern "
340                       "(missing arguments to " LUA_QL("%%b") ")");
341   if (*s != *p) return NULL;
342   else {
343     int b = *p;
344     int e = *(p+1);
345     int cont = 1;
346     while (++s < ms->src_end) {
347       if (*s == e) {
348         if (--cont == 0) return s+1;
349       }
350       else if (*s == b) cont++;
351     }
352   }
353   return NULL;  /* string ends out of balance */
354 }
355
356
357 static const char *max_expand (MatchState *ms, const char *s,
358                                  const char *p, const char *ep) {
359   ptrdiff_t i = 0;  /* counts maximum expand for item */
360   while (singlematch(ms, s + i, p, ep))
361     i++;
362   /* keeps trying to match with the maximum repetitions */
363   while (i>=0) {
364     const char *res = match(ms, (s+i), ep+1);
365     if (res) return res;
366     i--;  /* else didn't match; reduce 1 repetition to try again */
367   }
368   return NULL;
369 }
370
371
372 static const char *min_expand (MatchState *ms, const char *s,
373                                  const char *p, const char *ep) {
374   for (;;) {
375     const char *res = match(ms, s, ep+1);
376     if (res != NULL)
377       return res;
378     else if (singlematch(ms, s, p, ep))
379       s++;  /* try with one more repetition */
380     else return NULL;
381   }
382 }
383
384
385 static const char *start_capture (MatchState *ms, const char *s,
386                                     const char *p, int what) {
387   const char *res;
388   int level = ms->level;
389   if (level >= LUA_MAXCAPTURES) luaL_error(ms->L, "too many captures");
390   ms->capture[level].init = s;
391   ms->capture[level].len = what;
392   ms->level = level+1;
393   if ((res=match(ms, s, p)) == NULL)  /* match failed? */
394     ms->level--;  /* undo capture */
395   return res;
396 }
397
398
399 static const char *end_capture (MatchState *ms, const char *s,
400                                   const char *p) {
401   int l = capture_to_close(ms);
402   const char *res;
403   ms->capture[l].len = s - ms->capture[l].init;  /* close capture */
404   if ((res = match(ms, s, p)) == NULL)  /* match failed? */
405     ms->capture[l].len = CAP_UNFINISHED;  /* undo capture */
406   return res;
407 }
408
409
410 static const char *match_capture (MatchState *ms, const char *s, int l) {
411   size_t len;
412   l = check_capture(ms, l);
413   len = ms->capture[l].len;
414   if ((size_t)(ms->src_end-s) >= len &&
415       memcmp(ms->capture[l].init, s, len) == 0)
416     return s+len;
417   else return NULL;
418 }
419
420
421 static const char *match (MatchState *ms, const char *s, const char *p) {
422   if (ms->matchdepth-- == 0)
423     luaL_error(ms->L, "pattern too complex");
424   init: /* using goto's to optimize tail recursion */
425   if (p != ms->p_end) {  /* end of pattern? */
426     switch (*p) {
427       case '(': {  /* start capture */
428         if (*(p + 1) == ')')  /* position capture? */
429           s = start_capture(ms, s, p + 2, CAP_POSITION);
430         else
431           s = start_capture(ms, s, p + 1, CAP_UNFINISHED);
432         break;
433       }
434       case ')': {  /* end capture */
435         s = end_capture(ms, s, p + 1);
436         break;
437       }
438       case '$': {
439         if ((p + 1) != ms->p_end)  /* is the `$' the last char in pattern? */
440           goto dflt;  /* no; go to default */
441         s = (s == ms->src_end) ? s : NULL;  /* check end of string */
442         break;
443       }
444       case L_ESC: {  /* escaped sequences not in the format class[*+?-]? */
445         switch (*(p + 1)) {
446           case 'b': {  /* balanced string? */
447             s = matchbalance(ms, s, p + 2);
448             if (s != NULL) {
449               p += 4; goto init;  /* return match(ms, s, p + 4); */
450             }  /* else fail (s == NULL) */
451             break;
452           }
453           case 'f': {  /* frontier? */
454             const char *ep; char previous;
455             p += 2;
456             if (*p != '[')
457               luaL_error(ms->L, "missing " LUA_QL("[") " after "
458                                  LUA_QL("%%f") " in pattern");
459             ep = classend(ms, p);  /* points to what is next */
460             previous = (s == ms->src_init) ? '\0' : *(s - 1);
461             if (!matchbracketclass(uchar(previous), p, ep - 1) &&
462                matchbracketclass(uchar(*s), p, ep - 1)) {
463               p = ep; goto init;  /* return match(ms, s, ep); */
464             }
465             s = NULL;  /* match failed */
466             break;
467           }
468           case '0': case '1': case '2': case '3':
469           case '4': case '5': case '6': case '7':
470           case '8': case '9': {  /* capture results (%0-%9)? */
471             s = match_capture(ms, s, uchar(*(p + 1)));
472             if (s != NULL) {
473               p += 2; goto init;  /* return match(ms, s, p + 2) */
474             }
475             break;
476           }
477           default: goto dflt;
478         }
479         break;
480       }
481       default: dflt: {  /* pattern class plus optional suffix */
482         const char *ep = classend(ms, p);  /* points to optional suffix */
483         /* does not match at least once? */
484         if (!singlematch(ms, s, p, ep)) {
485           if (*ep == '*' || *ep == '?' || *ep == '-') {  /* accept empty? */
486             p = ep + 1; goto init;  /* return match(ms, s, ep + 1); */
487           }
488           else  /* '+' or no suffix */
489             s = NULL;  /* fail */
490         }
491         else {  /* matched once */
492           switch (*ep) {  /* handle optional suffix */
493             case '?': {  /* optional */
494               const char *res;
495               if ((res = match(ms, s + 1, ep + 1)) != NULL)
496                 s = res;
497               else {
498                 p = ep + 1; goto init;  /* else return match(ms, s, ep + 1); */
499               }
500               break;
501             }
502             case '+':  /* 1 or more repetitions */
503               s++;  /* 1 match already done */
504               /* FALLTHROUGH */
505             case '*':  /* 0 or more repetitions */
506               s = max_expand(ms, s, p, ep);
507               break;
508             case '-':  /* 0 or more repetitions (minimum) */
509               s = min_expand(ms, s, p, ep);
510               break;
511             default:  /* no suffix */
512               s++; p = ep; goto init;  /* return match(ms, s + 1, ep); */
513           }
514         }
515         break;
516       }
517     }
518   }
519   ms->matchdepth++;
520   return s;
521 }
522
523
524
525 static const char *lmemfind (const char *s1, size_t l1,
526                                const char *s2, size_t l2) {
527   if (l2 == 0) return s1;  /* empty strings are everywhere */
528   else if (l2 > l1) return NULL;  /* avoids a negative `l1' */
529   else {
530     const char *init;  /* to search for a `*s2' inside `s1' */
531     l2--;  /* 1st char will be checked by `memchr' */
532     l1 = l1-l2;  /* `s2' cannot be found after that */
533     while (l1 > 0 && (init = (const char *)memchr(s1, *s2, l1)) != NULL) {
534       init++;   /* 1st char is already checked */
535       if (memcmp(init, s2+1, l2) == 0)
536         return init-1;
537       else {  /* correct `l1' and `s1' to try again */
538         l1 -= init-s1;
539         s1 = init;
540       }
541     }
542     return NULL;  /* not found */
543   }
544 }
545
546
547 static void push_onecapture (MatchState *ms, int i, const char *s,
548                                                     const char *e) {
549   if (i >= ms->level) {
550     if (i == 0)  /* ms->level == 0, too */
551       lua_pushlstring(ms->L, s, e - s);  /* add whole match */
552     else
553       luaL_error(ms->L, "invalid capture index");
554   }
555   else {
556     ptrdiff_t l = ms->capture[i].len;
557     if (l == CAP_UNFINISHED) luaL_error(ms->L, "unfinished capture");
558     if (l == CAP_POSITION)
559       lua_pushinteger(ms->L, ms->capture[i].init - ms->src_init + 1);
560     else
561       lua_pushlstring(ms->L, ms->capture[i].init, l);
562   }
563 }
564
565
566 static int push_captures (MatchState *ms, const char *s, const char *e) {
567   int i;
568   int nlevels = (ms->level == 0 && s) ? 1 : ms->level;
569   luaL_checkstack(ms->L, nlevels, "too many captures");
570   for (i = 0; i < nlevels; i++)
571     push_onecapture(ms, i, s, e);
572   return nlevels;  /* number of strings pushed */
573 }
574
575
576 /* check whether pattern has no special characters */
577 static int nospecials (const char *p, size_t l) {
578   size_t upto = 0;
579   do {
580     if (strpbrk(p + upto, SPECIALS))
581       return 0;  /* pattern has a special character */
582     upto += strlen(p + upto) + 1;  /* may have more after \0 */
583   } while (upto <= l);
584   return 1;  /* no special chars found */
585 }
586
587
588 static int str_find_aux (lua_State *L, int find) {
589   size_t ls, lp;
590   const char *s = luaL_checklstring(L, 1, &ls);
591   const char *p = luaL_checklstring(L, 2, &lp);
592   size_t init = posrelat(luaL_optinteger(L, 3, 1), ls);
593   if (init < 1) init = 1;
594   else if (init > ls + 1) {  /* start after string's end? */
595     lua_pushnil(L);  /* cannot find anything */
596     return 1;
597   }
598   /* explicit request or no special characters? */
599   if (find && (lua_toboolean(L, 4) || nospecials(p, lp))) {
600     /* do a plain search */
601     const char *s2 = lmemfind(s + init - 1, ls - init + 1, p, lp);
602     if (s2) {
603       lua_pushinteger(L, s2 - s + 1);
604       lua_pushinteger(L, s2 - s + lp);
605       return 2;
606     }
607   }
608   else {
609     MatchState ms;
610     const char *s1 = s + init - 1;
611     int anchor = (*p == '^');
612     if (anchor) {
613       p++; lp--;  /* skip anchor character */
614     }
615     ms.L = L;
616     ms.matchdepth = MAXCCALLS;
617     ms.src_init = s;
618     ms.src_end = s + ls;
619     ms.p_end = p + lp;
620     do {
621       const char *res;
622       ms.level = 0;
623       lua_assert(ms.matchdepth == MAXCCALLS);
624       if ((res=match(&ms, s1, p)) != NULL) {
625         if (find) {
626           lua_pushinteger(L, s1 - s + 1);  /* start */
627           lua_pushinteger(L, res - s);   /* end */
628           return push_captures(&ms, NULL, 0) + 2;
629         }
630         else
631           return push_captures(&ms, s1, res);
632       }
633     } while (s1++ < ms.src_end && !anchor);
634   }
635   lua_pushnil(L);  /* not found */
636   return 1;
637 }
638
639
640 static int str_find (lua_State *L) {
641   return str_find_aux(L, 1);
642 }
643
644
645 static int str_match (lua_State *L) {
646   return str_find_aux(L, 0);
647 }
648
649
650 static int gmatch_aux (lua_State *L) {
651   MatchState ms;
652   size_t ls, lp;
653   const char *s = lua_tolstring(L, lua_upvalueindex(1), &ls);
654   const char *p = lua_tolstring(L, lua_upvalueindex(2), &lp);
655   const char *src;
656   ms.L = L;
657   ms.matchdepth = MAXCCALLS;
658   ms.src_init = s;
659   ms.src_end = s+ls;
660   ms.p_end = p + lp;
661   for (src = s + (size_t)lua_tointeger(L, lua_upvalueindex(3));
662        src <= ms.src_end;
663        src++) {
664     const char *e;
665     ms.level = 0;
666     lua_assert(ms.matchdepth == MAXCCALLS);
667     if ((e = match(&ms, src, p)) != NULL) {
668       lua_Integer newstart = e-s;
669       if (e == src) newstart++;  /* empty match? go at least one position */
670       lua_pushinteger(L, newstart);
671       lua_replace(L, lua_upvalueindex(3));
672       return push_captures(&ms, src, e);
673     }
674   }
675   return 0;  /* not found */
676 }
677
678
679 static int str_gmatch (lua_State *L) {
680   luaL_checkstring(L, 1);
681   luaL_checkstring(L, 2);
682   lua_settop(L, 2);
683   lua_pushinteger(L, 0);
684   lua_pushcclosure(L, gmatch_aux, 3);
685   return 1;
686 }
687
688
689 static void add_s (MatchState *ms, luaL_Buffer *b, const char *s,
690                                                    const char *e) {
691   size_t l, i;
692   const char *news = lua_tolstring(ms->L, 3, &l);
693   for (i = 0; i < l; i++) {
694     if (news[i] != L_ESC)
695       luaL_addchar(b, news[i]);
696     else {
697       i++;  /* skip ESC */
698       if (!isdigit(uchar(news[i]))) {
699         if (news[i] != L_ESC)
700           luaL_error(ms->L, "invalid use of " LUA_QL("%c")
701                            " in replacement string", L_ESC);
702         luaL_addchar(b, news[i]);
703       }
704       else if (news[i] == '0')
705           luaL_addlstring(b, s, e - s);
706       else {
707         push_onecapture(ms, news[i] - '1', s, e);
708         luaL_addvalue(b);  /* add capture to accumulated result */
709       }
710     }
711   }
712 }
713
714
715 static void add_value (MatchState *ms, luaL_Buffer *b, const char *s,
716                                        const char *e, int tr) {
717   lua_State *L = ms->L;
718   switch (tr) {
719     case LUA_TFUNCTION: {
720       int n;
721       lua_pushvalue(L, 3);
722       n = push_captures(ms, s, e);
723       lua_call(L, n, 1);
724       break;
725     }
726     case LUA_TTABLE: {
727       push_onecapture(ms, 0, s, e);
728       lua_gettable(L, 3);
729       break;
730     }
731     default: {  /* LUA_TNUMBER or LUA_TSTRING */
732       add_s(ms, b, s, e);
733       return;
734     }
735   }
736   if (!lua_toboolean(L, -1)) {  /* nil or false? */
737     lua_pop(L, 1);
738     lua_pushlstring(L, s, e - s);  /* keep original text */
739   }
740   else if (!lua_isstring(L, -1))
741     luaL_error(L, "invalid replacement value (a %s)", luaL_typename(L, -1));
742   luaL_addvalue(b);  /* add result to accumulator */
743 }
744
745
746 static int str_gsub (lua_State *L) {
747   size_t srcl, lp;
748   const char *src = luaL_checklstring(L, 1, &srcl);
749   const char *p = luaL_checklstring(L, 2, &lp);
750   int tr = lua_type(L, 3);
751   size_t max_s = luaL_optinteger(L, 4, srcl+1);
752   int anchor = (*p == '^');
753   size_t n = 0;
754   MatchState ms;
755   luaL_Buffer b;
756   luaL_argcheck(L, tr == LUA_TNUMBER || tr == LUA_TSTRING ||
757                    tr == LUA_TFUNCTION || tr == LUA_TTABLE, 3,
758                       "string/function/table expected");
759   luaL_buffinit(L, &b);
760   if (anchor) {
761     p++; lp--;  /* skip anchor character */
762   }
763   ms.L = L;
764   ms.matchdepth = MAXCCALLS;
765   ms.src_init = src;
766   ms.src_end = src+srcl;
767   ms.p_end = p + lp;
768   while (n < max_s) {
769     const char *e;
770     ms.level = 0;
771     lua_assert(ms.matchdepth == MAXCCALLS);
772     e = match(&ms, src, p);
773     if (e) {
774       n++;
775       add_value(&ms, &b, src, e, tr);
776     }
777     if (e && e>src) /* non empty match? */
778       src = e;  /* skip it */
779     else if (src < ms.src_end)
780       luaL_addchar(&b, *src++);
781     else break;
782     if (anchor) break;
783   }
784   luaL_addlstring(&b, src, ms.src_end-src);
785   luaL_pushresult(&b);
786   lua_pushinteger(L, n);  /* number of substitutions */
787   return 2;
788 }
789
790 /* }====================================================== */
791
792
793
794 /*
795 ** {======================================================
796 ** STRING FORMAT
797 ** =======================================================
798 */
799
800 /*
801 ** LUA_INTFRMLEN is the length modifier for integer conversions in
802 ** 'string.format'; LUA_INTFRM_T is the integer type corresponding to
803 ** the previous length
804 */
805 #if !defined(LUA_INTFRMLEN)     /* { */
806 #if defined(LUA_USE_LONGLONG)
807
808 #define LUA_INTFRMLEN           "ll"
809 #define LUA_INTFRM_T            long long
810
811 #else
812
813 #define LUA_INTFRMLEN           "l"
814 #define LUA_INTFRM_T            long
815
816 #endif
817 #endif                          /* } */
818
819
820 /*
821 ** LUA_FLTFRMLEN is the length modifier for float conversions in
822 ** 'string.format'; LUA_FLTFRM_T is the float type corresponding to
823 ** the previous length
824 */
825 #if !defined(LUA_FLTFRMLEN)
826
827 #define LUA_FLTFRMLEN           ""
828 #define LUA_FLTFRM_T            double
829
830 #endif
831
832
833 /* maximum size of each formatted item (> len(format('%99.99f', -1e308))) */
834 #define MAX_ITEM        512
835 /* valid flags in a format specification */
836 #define FLAGS   "-+ #0"
837 /*
838 ** maximum size of each format specification (such as '%-099.99d')
839 ** (+10 accounts for %99.99x plus margin of error)
840 */
841 #define MAX_FORMAT      (sizeof(FLAGS) + sizeof(LUA_INTFRMLEN) + 10)
842
843
844 static void addquoted (lua_State *L, luaL_Buffer *b, int arg) {
845   size_t l;
846   const char *s = luaL_checklstring(L, arg, &l);
847   luaL_addchar(b, '"');
848   while (l--) {
849     if (*s == '"' || *s == '\\' || *s == '\n') {
850       luaL_addchar(b, '\\');
851       luaL_addchar(b, *s);
852     }
853     else if (*s == '\0' || iscntrl(uchar(*s))) {
854       char buff[10];
855       if (!isdigit(uchar(*(s+1))))
856         snprintf(buff, sizeof(buff), "\\%d", (int)uchar(*s));
857       else
858         snprintf(buff, sizeof(buff), "\\%03d", (int)uchar(*s));
859       luaL_addstring(b, buff);
860     }
861     else
862       luaL_addchar(b, *s);
863     s++;
864   }
865   luaL_addchar(b, '"');
866 }
867
868 static const char *scanformat (lua_State *L, const char *strfrmt, char *form) {
869   const char *p = strfrmt;
870   while (*p != '\0' && strchr(FLAGS, *p) != NULL) p++;  /* skip flags */
871   if ((size_t)(p - strfrmt) >= sizeof(FLAGS)/sizeof(char))
872     luaL_error(L, "invalid format (repeated flags)");
873   if (isdigit(uchar(*p))) p++;  /* skip width */
874   if (isdigit(uchar(*p))) p++;  /* (2 digits at most) */
875   if (*p == '.') {
876     p++;
877     if (isdigit(uchar(*p))) p++;  /* skip precision */
878     if (isdigit(uchar(*p))) p++;  /* (2 digits at most) */
879   }
880   if (isdigit(uchar(*p)))
881     luaL_error(L, "invalid format (width or precision too long)");
882   *(form++) = '%';
883   memcpy(form, strfrmt, (p - strfrmt + 1) * sizeof(char));
884   form += p - strfrmt + 1;
885   *form = '\0';
886   return p;
887 }
888
889
890 /*
891 ** add length modifier into formats
892 */
893 static void addlenmod (char *form, const char *lenmod, size_t size) {
894   size_t l = strlen(form);
895   size_t lm = strlen(lenmod);
896   char spec = form[l - 1];
897   strlcpy(form + l - 1, lenmod, size - (l - 1));
898   form[l + lm - 1] = spec;
899   form[l + lm] = '\0';
900 }
901
902
903 static int str_format (lua_State *L) {
904   int top = lua_gettop(L);
905   int arg = 1;
906   size_t sfl;
907   const char *strfrmt = luaL_checklstring(L, arg, &sfl);
908   const char *strfrmt_end = strfrmt+sfl;
909   luaL_Buffer b;
910   luaL_buffinit(L, &b);
911   while (strfrmt < strfrmt_end) {
912     if (*strfrmt != L_ESC)
913       luaL_addchar(&b, *strfrmt++);
914     else if (*++strfrmt == L_ESC)
915       luaL_addchar(&b, *strfrmt++);  /* %% */
916     else { /* format item */
917       char form[MAX_FORMAT];  /* to store the format (`%...') */
918       char *buff = luaL_prepbuffsize(&b, MAX_ITEM);  /* to put formatted item */
919       int nb = 0;  /* number of bytes in added item */
920       if (++arg > top)
921         luaL_argerror(L, arg, "no value");
922       strfrmt = scanformat(L, strfrmt, form);
923       switch (*strfrmt++) {
924         case 'c': {
925           nb = str_sprintf(buff, form, luaL_checkint(L, arg));
926           break;
927         }
928         case 'd': case 'i': {
929           lua_Number n = luaL_checknumber(L, arg);
930           LUA_INTFRM_T ni = (LUA_INTFRM_T)n;
931           lua_Number diff = n - (lua_Number)ni;
932           luaL_argcheck(L, -1 < diff && diff < 1, arg,
933                         "not a number in proper range");
934           addlenmod(form, LUA_INTFRMLEN, MAX_FORMAT);
935           nb = str_sprintf(buff, form, ni);
936           break;
937         }
938         case 'o': case 'u': case 'x': case 'X': {
939           lua_Number n = luaL_checknumber(L, arg);
940           unsigned LUA_INTFRM_T ni = (unsigned LUA_INTFRM_T)n;
941           lua_Number diff = n - (lua_Number)ni;
942           luaL_argcheck(L, -1 < diff && diff < 1, arg,
943                         "not a non-negative number in proper range");
944           addlenmod(form, LUA_INTFRMLEN, MAX_FORMAT);
945           nb = str_sprintf(buff, form, ni);
946           break;
947         }
948 #if defined(LUA_USE_FLOAT_FORMATS)
949         case 'e': case 'E': case 'f':
950 #if defined(LUA_USE_AFORMAT)
951         case 'a': case 'A':
952 #endif
953         case 'g': case 'G': {
954           addlenmod(form, LUA_FLTFRMLEN, MAX_FORMAT);
955           nb = str_sprintf(buff, form, (LUA_FLTFRM_T)luaL_checknumber(L, arg));
956           break;
957         }
958 #endif
959         case 'q': {
960           addquoted(L, &b, arg);
961           break;
962         }
963         case 's': {
964           size_t l;
965           const char *s = luaL_tolstring(L, arg, &l);
966           if (!strchr(form, '.') && l >= 100) {
967             /* no precision and string is too long to be formatted;
968                keep original string */
969             luaL_addvalue(&b);
970             break;
971           }
972           else {
973             nb = str_sprintf(buff, form, s);
974             lua_pop(L, 1);  /* remove result from 'luaL_tolstring' */
975             break;
976           }
977         }
978         default: {  /* also treat cases `pnLlh' */
979           return luaL_error(L, "invalid option " LUA_QL("%%%c") " to "
980                                LUA_QL("format"), *(strfrmt - 1));
981         }
982       }
983       luaL_addsize(&b, nb);
984     }
985   }
986   luaL_pushresult(&b);
987   return 1;
988 }
989
990 /* }====================================================== */
991
992
993 static const luaL_Reg strlib[] = {
994   {"byte", str_byte},
995   {"char", str_char},
996 #if defined(LUA_USE_DUMP)
997   {"dump", str_dump},
998 #endif
999   {"find", str_find},
1000   {"format", str_format},
1001   {"gmatch", str_gmatch},
1002   {"gsub", str_gsub},
1003   {"len", str_len},
1004   {"lower", str_lower},
1005   {"match", str_match},
1006   {"rep", str_rep},
1007   {"reverse", str_reverse},
1008   {"sub", str_sub},
1009   {"upper", str_upper},
1010   {NULL, NULL}
1011 };
1012
1013
1014 static void createmetatable (lua_State *L) {
1015   lua_createtable(L, 0, 1);  /* table to be metatable for strings */
1016   lua_pushliteral(L, "");  /* dummy string */
1017   lua_pushvalue(L, -2);  /* copy table */
1018   lua_setmetatable(L, -2);  /* set table as metatable for strings */
1019   lua_pop(L, 1);  /* pop dummy string */
1020   lua_pushvalue(L, -2);  /* get string library */
1021   lua_setfield(L, -2, "__index");  /* metatable.__index = string */
1022   lua_pop(L, 1);  /* pop metatable */
1023 }
1024
1025
1026 /*
1027 ** Open string library
1028 */
1029 LUAMOD_API int luaopen_string (lua_State *L) {
1030   luaL_newlib(L, strlib);
1031   createmetatable(L);
1032   return 1;
1033 }
1034
1035 #if defined(_KERNEL)
1036
1037 EXPORT_SYMBOL(luaopen_string);
1038
1039 #endif
1040 /* END CSTYLED */