Cygwin: mmap: allow remapping part of an existing anonymous mapping
[newlib-cygwin.git] / newlib / libc / posix / regcomp.c
blobc8398094684f84114e862d435c2b5885c521f086
1 /*-
2 * Copyright (c) 1992, 1993, 1994 Henry Spencer.
3 * Copyright (c) 1992, 1993, 1994
4 * The Regents of the University of California. All rights reserved.
6 * This code is derived from software contributed to Berkeley by
7 * Henry Spencer.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 * 4. Neither the name of the University nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
33 * @(#)regcomp.c 8.5 (Berkeley) 3/20/94
36 #ifndef _NO_REGEX
38 #if defined(LIBC_SCCS) && !defined(lint)
39 static char sccsid[] = "@(#)regcomp.c 8.5 (Berkeley) 3/20/94";
40 #endif /* LIBC_SCCS and not lint */
41 #include <sys/cdefs.h>
43 #include <sys/types.h>
44 #include <stdio.h>
45 #include <string.h>
46 #include <ctype.h>
47 #include <limits.h>
48 #include <stdlib.h>
49 #include <regex.h>
51 #include "collate.h"
53 #include "utils.h"
54 #include "regex2.h"
56 #include "cclass.h"
57 #include "cname.h"
60 * parse structure, passed up and down to avoid global variables and
61 * other clumsinesses
63 struct parse {
64 char *next; /* next character in RE */
65 char *end; /* end of string (-> NUL normally) */
66 int error; /* has an error been seen? */
67 sop *strip; /* malloced strip */
68 sopno ssize; /* malloced strip size (allocated) */
69 sopno slen; /* malloced strip length (used) */
70 int ncsalloc; /* number of csets allocated */
71 struct re_guts *g;
72 # define NPAREN 10 /* we need to remember () 1-9 for back refs */
73 sopno pbegin[NPAREN]; /* -> ( ([0] unused) */
74 sopno pend[NPAREN]; /* -> ) ([0] unused) */
77 /* ========= begin header generated by ./mkh ========= */
78 #ifdef __cplusplus
79 extern "C" {
80 #endif
82 /* === regcomp.c === */
83 static void p_ere(struct parse *p, int stop);
84 static void p_ere_exp(struct parse *p);
85 static void p_str(struct parse *p);
86 static void p_bre(struct parse *p, int end1, int end2);
87 static int p_simp_re(struct parse *p, int starordinary);
88 static int p_count(struct parse *p);
89 static void p_bracket(struct parse *p);
90 static void p_b_term(struct parse *p, cset *cs);
91 static void p_b_cclass(struct parse *p, cset *cs);
92 static void p_b_eclass(struct parse *p, cset *cs);
93 static char p_b_symbol(struct parse *p);
94 static char p_b_coll_elem(struct parse *p, int endc);
95 static char othercase(int ch);
96 static void bothcases(struct parse *p, int ch);
97 static void ordinary(struct parse *p, int ch);
98 static void nonnewline(struct parse *p);
99 static void repeat(struct parse *p, sopno start, int from, int to);
100 static int seterr(struct parse *p, int e);
101 static cset *allocset(struct parse *p);
102 static void freeset(struct parse *p, cset *cs);
103 static int freezeset(struct parse *p, cset *cs);
104 static int firstch(struct parse *p, cset *cs);
105 static int nch(struct parse *p, cset *cs);
106 #if used
107 static void mcadd(struct parse *p, cset *cs, char *cp);
108 static void mcsub(cset *cs, char *cp);
109 static int mcin(cset *cs, char *cp);
110 static char *mcfind(cset *cs, char *cp);
111 #endif
112 static void mcinvert(struct parse *p, cset *cs);
113 static void mccase(struct parse *p, cset *cs);
114 static int isinsets(struct re_guts *g, int c);
115 static int samesets(struct re_guts *g, int c1, int c2);
116 static void categorize(struct parse *p, struct re_guts *g);
117 static sopno dupl(struct parse *p, sopno start, sopno finish);
118 static void doemit(struct parse *p, sop op, size_t opnd);
119 static void doinsert(struct parse *p, sop op, size_t opnd, sopno pos);
120 static void dofwd(struct parse *p, sopno pos, sop value);
121 static void enlarge(struct parse *p, sopno size);
122 static void stripsnug(struct parse *p, struct re_guts *g);
123 static void findmust(struct parse *p, struct re_guts *g);
124 static int altoffset(sop *scan, int offset, int mccs);
125 static void computejumps(struct parse *p, struct re_guts *g);
126 static void computematchjumps(struct parse *p, struct re_guts *g);
127 static sopno pluscount(struct parse *p, struct re_guts *g);
129 #ifdef __cplusplus
131 #endif
132 /* ========= end header generated by ./mkh ========= */
134 static char nuls[10]; /* place to point scanner in event of error */
137 * macros for use with parse structure
138 * BEWARE: these know that the parse structure is named `p' !!!
140 #define PEEK() (*p->next)
141 #define PEEK2() (*(p->next+1))
142 #define MORE() (p->next < p->end)
143 #define MORE2() (p->next+1 < p->end)
144 #define SEE(c) (MORE() && PEEK() == (c))
145 #define SEETWO(a, b) (MORE() && MORE2() && PEEK() == (a) && PEEK2() == (b))
146 #define EAT(c) ((SEE(c)) ? (NEXT(), 1) : 0)
147 #define EATTWO(a, b) ((SEETWO(a, b)) ? (NEXT2(), 1) : 0)
148 #define NEXT() (p->next++)
149 #define NEXT2() (p->next += 2)
150 #define NEXTn(n) (p->next += (n))
151 #define GETNEXT() (*p->next++)
152 #define SETERROR(e) seterr(p, (e))
153 #define REQUIRE(co, e) ((co) || SETERROR(e))
154 #define MUSTSEE(c, e) (REQUIRE(MORE() && PEEK() == (c), e))
155 #define MUSTEAT(c, e) (REQUIRE(MORE() && GETNEXT() == (c), e))
156 #define MUSTNOTSEE(c, e) (REQUIRE(!MORE() || PEEK() != (c), e))
157 #define EMIT(op, sopnd) doemit(p, (sop)(op), (size_t)(sopnd))
158 #define INSERT(op, pos) doinsert(p, (sop)(op), HERE()-(pos)+1, pos)
159 #define AHEAD(pos) dofwd(p, pos, HERE()-(pos))
160 #define ASTERN(sop, pos) EMIT(sop, HERE()-pos)
161 #define HERE() (p->slen)
162 #define THERE() (p->slen - 1)
163 #define THERETHERE() (p->slen - 2)
164 #define DROP(n) (p->slen -= (n))
166 #ifndef NDEBUG
167 static int never = 0; /* for use in asserts; shuts lint up */
168 #else
169 #define never 0 /* some <assert.h>s have bugs too */
170 #endif
172 /* Macro used by computejump()/computematchjump() */
173 #define MIN(a,b) ((a)<(b)?(a):(b))
176 - regcomp - interface for parser and compilation
177 = extern int regcomp(regex_t *__restrict, const char *__restrict, int);
178 = #define REG_BASIC 0000
179 = #define REG_EXTENDED 0001
180 = #define REG_ICASE 0002
181 = #define REG_NOSUB 0004
182 = #define REG_NEWLINE 0010
183 = #define REG_NOSPEC 0020
184 = #define REG_PEND 0040
185 = #define REG_DUMP 0200
187 int /* 0 success, otherwise REG_something */
188 regcomp(preg, pattern, cflags)
189 regex_t *__restrict preg;
190 const char *__restrict pattern;
191 int cflags;
193 struct parse pa;
194 struct re_guts *g;
195 struct parse *p = &pa;
196 int i;
197 size_t len;
198 #ifdef REDEBUG
199 # define GOODFLAGS(f) (f)
200 #else
201 # define GOODFLAGS(f) ((f)&~REG_DUMP)
202 #endif
204 cflags = GOODFLAGS(cflags);
205 if ((cflags&REG_EXTENDED) && (cflags&REG_NOSPEC))
206 return(REG_INVARG);
208 if (cflags&REG_PEND) {
209 if (preg->re_endp < pattern)
210 return(REG_INVARG);
211 len = preg->re_endp - pattern;
212 } else
213 len = strlen((char *)pattern);
215 /* do the mallocs early so failure handling is easy */
216 g = (struct re_guts *)malloc(sizeof(struct re_guts) +
217 (NC-1)*sizeof(cat_t));
218 if (g == NULL)
219 return(REG_ESPACE);
220 p->ssize = len/(size_t)2*(size_t)3 + (size_t)1; /* ugh */
221 p->strip = (sop *)malloc(p->ssize * sizeof(sop));
222 p->slen = 0;
223 if (p->strip == NULL) {
224 free((char *)g);
225 return(REG_ESPACE);
228 /* set things up */
229 p->g = g;
230 p->next = (char *)pattern; /* convenience; we do not modify it */
231 p->end = p->next + len;
232 p->error = 0;
233 p->ncsalloc = 0;
234 for (i = 0; i < NPAREN; i++) {
235 p->pbegin[i] = 0;
236 p->pend[i] = 0;
238 g->csetsize = NC;
239 g->sets = NULL;
240 g->setbits = NULL;
241 g->ncsets = 0;
242 g->cflags = cflags;
243 g->iflags = 0;
244 g->nbol = 0;
245 g->neol = 0;
246 g->must = NULL;
247 g->moffset = -1;
248 g->charjump = NULL;
249 g->matchjump = NULL;
250 g->mlen = 0;
251 g->nsub = 0;
252 g->ncategories = 1; /* category 0 is "everything else" */
253 g->categories = &g->catspace[-(CHAR_MIN)];
254 (void) memset((char *)g->catspace, 0, NC*sizeof(cat_t));
255 g->backrefs = 0;
257 /* do it */
258 EMIT(OEND, 0);
259 g->firststate = THERE();
260 if (cflags&REG_EXTENDED)
261 p_ere(p, OUT);
262 else if (cflags&REG_NOSPEC)
263 p_str(p);
264 else
265 p_bre(p, OUT, OUT);
266 EMIT(OEND, 0);
267 g->laststate = THERE();
269 /* tidy up loose ends and fill things in */
270 categorize(p, g);
271 stripsnug(p, g);
272 findmust(p, g);
273 /* only use Boyer-Moore algorithm if the pattern is bigger
274 * than three characters
276 if(g->mlen > 3) {
277 computejumps(p, g);
278 computematchjumps(p, g);
279 if(g->matchjump == NULL && g->charjump != NULL) {
280 free(g->charjump);
281 g->charjump = NULL;
284 g->nplus = pluscount(p, g);
285 g->magic = MAGIC2;
286 preg->re_nsub = g->nsub;
287 preg->re_g = g;
288 preg->re_magic = MAGIC1;
289 #ifndef REDEBUG
290 /* not debugging, so can't rely on the assert() in regexec() */
291 if (g->iflags&BAD)
292 SETERROR(REG_ASSERT);
293 #endif
295 /* win or lose, we're done */
296 if (p->error != 0) /* lose */
297 regfree(preg);
298 return(p->error);
302 - p_ere - ERE parser top level, concatenation and alternation
303 == static void p_ere(struct parse *p, int stop);
305 static void
306 p_ere(
307 struct parse *p,
308 int stop /* character this ERE should end at */
311 char c;
312 sopno prevback = 0;
313 sopno prevfwd = 0;
314 sopno conc;
315 int first = 1; /* is this the first alternative? */
317 for (;;) {
318 /* do a bunch of concatenated expressions */
319 conc = HERE();
320 while (MORE() && (c = PEEK()) != '|' && c != stop)
321 p_ere_exp(p);
322 (void)REQUIRE(HERE() != conc, REG_EMPTY); /* require nonempty */
324 if (!EAT('|'))
325 break; /* NOTE BREAK OUT */
327 if (first) {
328 INSERT(OCH_, conc); /* offset is wrong */
329 prevfwd = conc;
330 prevback = conc;
331 first = 0;
333 ASTERN(OOR1, prevback);
334 prevback = THERE();
335 AHEAD(prevfwd); /* fix previous offset */
336 prevfwd = HERE();
337 EMIT(OOR2, 0); /* offset is very wrong */
340 if (!first) { /* tail-end fixups */
341 AHEAD(prevfwd);
342 ASTERN(O_CH, prevback);
345 assert(!MORE() || SEE(stop));
349 - p_ere_exp - parse one subERE, an atom possibly followed by a repetition op
350 == static void p_ere_exp(struct parse *p);
352 static void
353 p_ere_exp(struct parse *p)
355 char c;
356 sopno pos;
357 int count;
358 int count2;
359 sopno subno;
360 int wascaret = 0;
362 assert(MORE()); /* caller should have ensured this */
363 c = GETNEXT();
365 pos = HERE();
366 switch (c) {
367 case '(':
368 (void)REQUIRE(MORE(), REG_EPAREN);
369 p->g->nsub++;
370 subno = p->g->nsub;
371 if (subno < NPAREN)
372 p->pbegin[subno] = HERE();
373 EMIT(OLPAREN, subno);
374 if (!SEE(')'))
375 p_ere(p, ')');
376 if (subno < NPAREN) {
377 p->pend[subno] = HERE();
378 assert(p->pend[subno] != 0);
380 EMIT(ORPAREN, subno);
381 (void)MUSTEAT(')', REG_EPAREN);
382 break;
383 #ifndef POSIX_MISTAKE
384 case ')': /* happens only if no current unmatched ( */
386 * You may ask, why the ifndef? Because I didn't notice
387 * this until slightly too late for 1003.2, and none of the
388 * other 1003.2 regular-expression reviewers noticed it at
389 * all. So an unmatched ) is legal POSIX, at least until
390 * we can get it fixed.
392 SETERROR(REG_EPAREN);
393 break;
394 #endif
395 case '^':
396 EMIT(OBOL, 0);
397 p->g->iflags |= USEBOL;
398 p->g->nbol++;
399 wascaret = 1;
400 break;
401 case '$':
402 EMIT(OEOL, 0);
403 p->g->iflags |= USEEOL;
404 p->g->neol++;
405 break;
406 case '|':
407 SETERROR(REG_EMPTY);
408 break;
409 case '*':
410 case '+':
411 case '?':
412 SETERROR(REG_BADRPT);
413 break;
414 case '.':
415 if (p->g->cflags&REG_NEWLINE)
416 nonnewline(p);
417 else
418 EMIT(OANY, 0);
419 break;
420 case '[':
421 p_bracket(p);
422 break;
423 case '\\':
424 (void)REQUIRE(MORE(), REG_EESCAPE);
425 c = GETNEXT();
426 ordinary(p, c);
427 break;
428 case '{': /* okay as ordinary except if digit follows */
429 (void)REQUIRE(!MORE() || !isdigit((uch)PEEK()), REG_BADRPT);
430 /* FALLTHROUGH */
431 default:
432 ordinary(p, c);
433 break;
436 if (!MORE())
437 return;
438 c = PEEK();
439 /* we call { a repetition if followed by a digit */
440 if (!( c == '*' || c == '+' || c == '?' ||
441 (c == '{' && MORE2() && isdigit((uch)PEEK2())) ))
442 return; /* no repetition, we're done */
443 NEXT();
445 (void)REQUIRE(!wascaret, REG_BADRPT);
446 switch (c) {
447 case '*': /* implemented as +? */
448 /* this case does not require the (y|) trick, noKLUDGE */
449 INSERT(OPLUS_, pos);
450 ASTERN(O_PLUS, pos);
451 INSERT(OQUEST_, pos);
452 ASTERN(O_QUEST, pos);
453 break;
454 case '+':
455 INSERT(OPLUS_, pos);
456 ASTERN(O_PLUS, pos);
457 break;
458 case '?':
459 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
460 INSERT(OCH_, pos); /* offset slightly wrong */
461 ASTERN(OOR1, pos); /* this one's right */
462 AHEAD(pos); /* fix the OCH_ */
463 EMIT(OOR2, 0); /* offset very wrong... */
464 AHEAD(THERE()); /* ...so fix it */
465 ASTERN(O_CH, THERETHERE());
466 break;
467 case '{':
468 count = p_count(p);
469 if (EAT(',')) {
470 if (isdigit((uch)PEEK())) {
471 count2 = p_count(p);
472 (void)REQUIRE(count <= count2, REG_BADBR);
473 } else /* single number with comma */
474 count2 = INFINITY;
475 } else /* just a single number */
476 count2 = count;
477 repeat(p, pos, count, count2);
478 if (!EAT('}')) { /* error heuristics */
479 while (MORE() && PEEK() != '}')
480 NEXT();
481 (void)REQUIRE(MORE(), REG_EBRACE);
482 SETERROR(REG_BADBR);
484 break;
487 if (!MORE())
488 return;
489 c = PEEK();
490 if (!( c == '*' || c == '+' || c == '?' ||
491 (c == '{' && MORE2() && isdigit((uch)PEEK2())) ) )
492 return;
493 SETERROR(REG_BADRPT);
497 - p_str - string (no metacharacters) "parser"
498 == static void p_str(struct parse *p);
500 static void
501 p_str(struct parse *p)
503 (void)REQUIRE(MORE(), REG_EMPTY);
504 while (MORE())
505 ordinary(p, GETNEXT());
509 - p_bre - BRE parser top level, anchoring and concatenation
510 == static void p_bre(struct parse *p, int end1, \
511 == int end2);
512 * Giving end1 as OUT essentially eliminates the end1/end2 check.
514 * This implementation is a bit of a kludge, in that a trailing $ is first
515 * taken as an ordinary character and then revised to be an anchor. The
516 * only undesirable side effect is that '$' gets included as a character
517 * category in such cases. This is fairly harmless; not worth fixing.
518 * The amount of lookahead needed to avoid this kludge is excessive.
520 static void
521 p_bre(
522 struct parse *p,
523 int end1, /* first terminating character */
524 int end2 /* second terminating character */
527 sopno start = HERE();
528 int first = 1; /* first subexpression? */
529 int wasdollar = 0;
531 if (EAT('^')) {
532 EMIT(OBOL, 0);
533 p->g->iflags |= USEBOL;
534 p->g->nbol++;
536 while (MORE() && !SEETWO(end1, end2)) {
537 wasdollar = p_simp_re(p, first);
538 first = 0;
540 if (wasdollar) { /* oops, that was a trailing anchor */
541 DROP(1);
542 EMIT(OEOL, 0);
543 p->g->iflags |= USEEOL;
544 p->g->neol++;
547 (void)REQUIRE(HERE() != start, REG_EMPTY); /* require nonempty */
551 - p_simp_re - parse a simple RE, an atom possibly followed by a repetition
552 == static int p_simp_re(struct parse *p, int starordinary);
554 static int /* was the simple RE an unbackslashed $? */
555 p_simp_re(
556 struct parse *p,
557 int starordinary /* is a leading * an ordinary character? */
560 int c;
561 int count;
562 int count2;
563 sopno pos;
564 int i;
565 sopno subno;
566 # define BACKSL (1<<CHAR_BIT)
568 pos = HERE(); /* repetion op, if any, covers from here */
570 assert(MORE()); /* caller should have ensured this */
571 c = GETNEXT();
572 if (c == '\\') {
573 (void)REQUIRE(MORE(), REG_EESCAPE);
574 c = BACKSL | GETNEXT();
576 switch (c) {
577 case '.':
578 if (p->g->cflags&REG_NEWLINE)
579 nonnewline(p);
580 else
581 EMIT(OANY, 0);
582 break;
583 case '[':
584 p_bracket(p);
585 break;
586 case BACKSL|'{':
587 SETERROR(REG_BADRPT);
588 break;
589 case BACKSL|'(':
590 p->g->nsub++;
591 subno = p->g->nsub;
592 if (subno < NPAREN)
593 p->pbegin[subno] = HERE();
594 EMIT(OLPAREN, subno);
595 /* the MORE here is an error heuristic */
596 if (MORE() && !SEETWO('\\', ')'))
597 p_bre(p, '\\', ')');
598 if (subno < NPAREN) {
599 p->pend[subno] = HERE();
600 assert(p->pend[subno] != 0);
602 EMIT(ORPAREN, subno);
603 (void)REQUIRE(EATTWO('\\', ')'), REG_EPAREN);
604 break;
605 case BACKSL|')': /* should not get here -- must be user */
606 case BACKSL|'}':
607 SETERROR(REG_EPAREN);
608 break;
609 case BACKSL|'1':
610 case BACKSL|'2':
611 case BACKSL|'3':
612 case BACKSL|'4':
613 case BACKSL|'5':
614 case BACKSL|'6':
615 case BACKSL|'7':
616 case BACKSL|'8':
617 case BACKSL|'9':
618 i = (c&~BACKSL) - '0';
619 assert(i < NPAREN);
620 if (p->pend[i] != 0) {
621 assert(i <= p->g->nsub);
622 EMIT(OBACK_, i);
623 assert(p->pbegin[i] != 0);
624 assert(OP(p->strip[p->pbegin[i]]) == OLPAREN);
625 assert(OP(p->strip[p->pend[i]]) == ORPAREN);
626 (void) dupl(p, p->pbegin[i]+1, p->pend[i]);
627 EMIT(O_BACK, i);
628 } else
629 SETERROR(REG_ESUBREG);
630 p->g->backrefs = 1;
631 break;
632 case '*':
633 (void)REQUIRE(starordinary, REG_BADRPT);
634 /* FALLTHROUGH */
635 default:
636 ordinary(p, (char)c);
637 break;
640 if (EAT('*')) { /* implemented as +? */
641 /* this case does not require the (y|) trick, noKLUDGE */
642 INSERT(OPLUS_, pos);
643 ASTERN(O_PLUS, pos);
644 INSERT(OQUEST_, pos);
645 ASTERN(O_QUEST, pos);
646 } else if (EATTWO('\\', '{')) {
647 count = p_count(p);
648 if (EAT(',')) {
649 if (MORE() && isdigit((uch)PEEK())) {
650 count2 = p_count(p);
651 (void)REQUIRE(count <= count2, REG_BADBR);
652 } else /* single number with comma */
653 count2 = INFINITY;
654 } else /* just a single number */
655 count2 = count;
656 repeat(p, pos, count, count2);
657 if (!EATTWO('\\', '}')) { /* error heuristics */
658 while (MORE() && !SEETWO('\\', '}'))
659 NEXT();
660 (void)REQUIRE(MORE(), REG_EBRACE);
661 SETERROR(REG_BADBR);
663 } else if (c == '$') /* $ (but not \$) ends it */
664 return(1);
666 return(0);
670 - p_count - parse a repetition count
671 == static int p_count(struct parse *p);
673 static int /* the value */
674 p_count(struct parse *p)
676 int count = 0;
677 int ndigits = 0;
679 while (MORE() && isdigit((uch)PEEK()) && count <= DUPMAX) {
680 count = count*10 + (GETNEXT() - '0');
681 ndigits++;
684 (void)REQUIRE(ndigits > 0 && count <= DUPMAX, REG_BADBR);
685 return(count);
689 - p_bracket - parse a bracketed character list
690 == static void p_bracket(struct parse *p);
692 * Note a significant property of this code: if the allocset() did SETERROR,
693 * no set operations are done.
695 static void
696 p_bracket(struct parse *p)
698 cset *cs = allocset(p);
699 int invert = 0;
701 /* Dept of Truly Sickening Special-Case Kludges */
702 if (p->next + 5 < p->end && strncmp(p->next, "[:<:]]", 6) == 0) {
703 EMIT(OBOW, 0);
704 NEXTn(6);
705 return;
707 if (p->next + 5 < p->end && strncmp(p->next, "[:>:]]", 6) == 0) {
708 EMIT(OEOW, 0);
709 NEXTn(6);
710 return;
713 if (EAT('^'))
714 invert++; /* make note to invert set at end */
715 if (EAT(']'))
716 CHadd(cs, ']');
717 else if (EAT('-'))
718 CHadd(cs, '-');
719 while (MORE() && PEEK() != ']' && !SEETWO('-', ']'))
720 p_b_term(p, cs);
721 if (EAT('-'))
722 CHadd(cs, '-');
723 (void)MUSTEAT(']', REG_EBRACK);
725 if (p->error != 0) /* don't mess things up further */
726 return;
728 if (p->g->cflags&REG_ICASE) {
729 int i;
730 int ci;
732 for (i = p->g->csetsize - 1; i >= 0; i--)
733 if (CHIN(cs, i) && isalpha(i)) {
734 ci = othercase(i);
735 if (ci != i)
736 CHadd(cs, ci);
738 if (cs->multis != NULL)
739 mccase(p, cs);
741 if (invert) {
742 int i;
744 for (i = p->g->csetsize - 1; i >= 0; i--)
745 if (CHIN(cs, i))
746 CHsub(cs, i);
747 else
748 CHadd(cs, i);
749 if (p->g->cflags&REG_NEWLINE)
750 CHsub(cs, '\n');
751 if (cs->multis != NULL)
752 mcinvert(p, cs);
755 assert(cs->multis == NULL); /* xxx */
757 if (nch(p, cs) == 1) { /* optimize singleton sets */
758 ordinary(p, firstch(p, cs));
759 freeset(p, cs);
760 } else
761 EMIT(OANYOF, freezeset(p, cs));
765 - p_b_term - parse one term of a bracketed character list
766 == static void p_b_term(struct parse *p, cset *cs);
768 static void
769 p_b_term(
770 struct parse *p,
771 cset *cs
774 char c;
775 char start, finish;
776 int i;
778 /* classify what we've got */
779 switch ((MORE()) ? PEEK() : '\0') {
780 case '[':
781 c = (MORE2()) ? PEEK2() : '\0';
782 break;
783 case '-':
784 SETERROR(REG_ERANGE);
785 return; /* NOTE RETURN */
786 break;
787 default:
788 c = '\0';
789 break;
792 switch (c) {
793 case ':': /* character class */
794 NEXT2();
795 (void)REQUIRE(MORE(), REG_EBRACK);
796 c = PEEK();
797 (void)REQUIRE(c != '-' && c != ']', REG_ECTYPE);
798 p_b_cclass(p, cs);
799 (void)REQUIRE(MORE(), REG_EBRACK);
800 (void)REQUIRE(EATTWO(':', ']'), REG_ECTYPE);
801 break;
802 case '=': /* equivalence class */
803 NEXT2();
804 (void)REQUIRE(MORE(), REG_EBRACK);
805 c = PEEK();
806 (void)REQUIRE(c != '-' && c != ']', REG_ECOLLATE);
807 p_b_eclass(p, cs);
808 (void)REQUIRE(MORE(), REG_EBRACK);
809 (void)REQUIRE(EATTWO('=', ']'), REG_ECOLLATE);
810 break;
811 default: /* symbol, ordinary character, or range */
812 /* xxx revision needed for multichar stuff */
813 start = p_b_symbol(p);
814 if (SEE('-') && MORE2() && PEEK2() != ']') {
815 /* range */
816 NEXT();
817 if (EAT('-'))
818 finish = '-';
819 else
820 finish = p_b_symbol(p);
821 } else
822 finish = start;
823 if (start == finish)
824 CHadd(cs, start);
825 else {
826 if (__collate_load_error) {
827 (void)REQUIRE((uch)start <= (uch)finish, REG_ERANGE);
828 for (i = (uch)start; i <= (uch)finish; i++)
829 CHadd(cs, i);
830 } else {
831 (void)REQUIRE(__collate_range_cmp(start, finish) <= 0, REG_ERANGE);
832 for (i = CHAR_MIN; i <= CHAR_MAX; i++) {
833 if ( __collate_range_cmp(start, i) <= 0
834 && __collate_range_cmp(i, finish) <= 0
836 CHadd(cs, i);
840 break;
845 - p_b_cclass - parse a character-class name and deal with it
846 == static void p_b_cclass(struct parse *p, cset *cs);
848 static void
849 p_b_cclass(
850 struct parse *p,
851 cset *cs
854 int c;
855 char *sp = p->next;
856 struct cclass *cp;
857 size_t len;
859 while (MORE() && isalpha((uch)PEEK()))
860 NEXT();
861 len = p->next - sp;
862 for (cp = cclasses; cp->name != NULL; cp++)
863 if (strncmp(cp->name, sp, len) == 0 && cp->name[len] == '\0')
864 break;
865 if (cp->name == NULL) {
866 /* oops, didn't find it */
867 SETERROR(REG_ECTYPE);
868 return;
871 switch (cp->fidx) {
872 case CALNUM:
873 for (c = CHAR_MIN; c <= CHAR_MAX; c++)
874 if (isalnum((uch)c))
875 CHadd(cs, c);
876 break;
877 case CALPHA:
878 for (c = CHAR_MIN; c <= CHAR_MAX; c++)
879 if (isalpha((uch)c))
880 CHadd(cs, c);
881 break;
882 case CBLANK:
883 for (c = CHAR_MIN; c <= CHAR_MAX; c++)
884 if (isblank((uch)c))
885 CHadd(cs, c);
886 break;
887 case CCNTRL:
888 for (c = CHAR_MIN; c <= CHAR_MAX; c++)
889 if (iscntrl((uch)c))
890 CHadd(cs, c);
891 break;
892 case CDIGIT:
893 for (c = CHAR_MIN; c <= CHAR_MAX; c++)
894 if (isdigit((uch)c))
895 CHadd(cs, c);
896 break;
897 case CGRAPH:
898 for (c = CHAR_MIN; c <= CHAR_MAX; c++)
899 if (isgraph((uch)c))
900 CHadd(cs, c);
901 break;
902 case CLOWER:
903 for (c = CHAR_MIN; c <= CHAR_MAX; c++)
904 if (islower((uch)c))
905 CHadd(cs, c);
906 break;
907 case CPRINT:
908 for (c = CHAR_MIN; c <= CHAR_MAX; c++)
909 if (isprint((uch)c))
910 CHadd(cs, c);
911 break;
912 case CPUNCT:
913 for (c = CHAR_MIN; c <= CHAR_MAX; c++)
914 if (ispunct((uch)c))
915 CHadd(cs, c);
916 break;
917 case CSPACE:
918 for (c = CHAR_MIN; c <= CHAR_MAX; c++)
919 if (isspace((uch)c))
920 CHadd(cs, c);
921 break;
922 case CUPPER:
923 for (c = CHAR_MIN; c <= CHAR_MAX; c++)
924 if (isupper((uch)c))
925 CHadd(cs, c);
926 break;
927 case CXDIGIT:
928 for (c = CHAR_MIN; c <= CHAR_MAX; c++)
929 if (isxdigit((uch)c))
930 CHadd(cs, c);
931 break;
933 #if 0
934 for (u = cp->multis; *u != '\0'; u += strlen(u) + 1)
935 MCadd(p, cs, u);
936 #endif
940 - p_b_eclass - parse an equivalence-class name and deal with it
941 == static void p_b_eclass(struct parse *p, cset *cs);
943 * This implementation is incomplete. xxx
945 static void
946 p_b_eclass(
947 struct parse *p,
948 cset *cs
951 char c;
953 c = p_b_coll_elem(p, '=');
954 CHadd(cs, c);
958 - p_b_symbol - parse a character or [..]ed multicharacter collating symbol
959 == static char p_b_symbol(struct parse *p);
961 static char /* value of symbol */
962 p_b_symbol(struct parse *p)
964 char value;
966 (void)REQUIRE(MORE(), REG_EBRACK);
967 if (!EATTWO('[', '.'))
968 return(GETNEXT());
970 /* collating symbol */
971 value = p_b_coll_elem(p, '.');
972 (void)REQUIRE(EATTWO('.', ']'), REG_ECOLLATE);
973 return(value);
977 - p_b_coll_elem - parse a collating-element name and look it up
978 == static char p_b_coll_elem(struct parse *p, int endc);
980 static char /* value of collating element */
981 p_b_coll_elem(
982 struct parse *p,
983 int endc /* name ended by endc,']' */
986 char *sp = p->next;
987 struct cname *cp;
988 int len;
990 while (MORE() && !SEETWO(endc, ']'))
991 NEXT();
992 if (!MORE()) {
993 SETERROR(REG_EBRACK);
994 return(0);
996 len = p->next - sp;
997 for (cp = cnames; cp->name != NULL; cp++)
998 if (strncmp(cp->name, sp, len) == 0 && cp->name[len] == '\0')
999 return(cp->code); /* known name */
1000 if (len == 1)
1001 return(*sp); /* single character */
1002 SETERROR(REG_ECOLLATE); /* neither */
1003 return(0);
1007 - othercase - return the case counterpart of an alphabetic
1008 == static char othercase(int ch);
1010 static char /* if no counterpart, return ch */
1011 othercase(
1012 int ch
1015 ch = (uch)ch;
1016 assert(isalpha(ch));
1017 if (isupper(ch))
1018 return(tolower(ch));
1019 else if (islower(ch))
1020 return(toupper(ch));
1021 else /* peculiar, but could happen */
1022 return(ch);
1026 - bothcases - emit a dualcase version of a two-case character
1027 == static void bothcases(struct parse *p, int ch);
1029 * Boy, is this implementation ever a kludge...
1031 static void
1032 bothcases(
1033 struct parse *p,
1034 int ch
1037 char *oldnext = p->next;
1038 char *oldend = p->end;
1039 char bracket[3];
1041 ch = (uch)ch;
1042 assert(othercase(ch) != ch); /* p_bracket() would recurse */
1043 p->next = bracket;
1044 p->end = bracket+2;
1045 bracket[0] = ch;
1046 bracket[1] = ']';
1047 bracket[2] = '\0';
1048 p_bracket(p);
1049 assert(p->next == bracket+2);
1050 p->next = oldnext;
1051 p->end = oldend;
1055 - ordinary - emit an ordinary character
1056 == static void ordinary(struct parse *p, int ch);
1058 static void
1059 ordinary(
1060 struct parse *p,
1061 int ch
1064 cat_t *cap = p->g->categories;
1066 if ((p->g->cflags&REG_ICASE) && isalpha((uch)ch) && othercase(ch) != ch)
1067 bothcases(p, ch);
1068 else {
1069 EMIT(OCHAR, (uch)ch);
1070 if (cap[ch] == 0)
1071 cap[ch] = p->g->ncategories++;
1076 - nonnewline - emit REG_NEWLINE version of OANY
1077 == static void nonnewline(struct parse *p);
1079 * Boy, is this implementation ever a kludge...
1081 static void
1082 nonnewline(
1083 struct parse *p
1086 char *oldnext = p->next;
1087 char *oldend = p->end;
1088 char bracket[4];
1090 p->next = bracket;
1091 p->end = bracket+3;
1092 bracket[0] = '^';
1093 bracket[1] = '\n';
1094 bracket[2] = ']';
1095 bracket[3] = '\0';
1096 p_bracket(p);
1097 assert(p->next == bracket+3);
1098 p->next = oldnext;
1099 p->end = oldend;
1103 - repeat - generate code for a bounded repetition, recursively if needed
1104 == static void repeat(struct parse *p, sopno start, int from, int to);
1106 static void
1107 repeat(
1108 struct parse *p,
1109 sopno start, /* operand from here to end of strip */
1110 int from, /* repeated from this number */
1111 int to /* to this number of times (maybe INFINITY) */
1114 sopno finish = HERE();
1115 # define N 2
1116 # define INF 3
1117 # define REP(f, t) ((f)*8 + (t))
1118 # define MAP(n) (((n) <= 1) ? (n) : ((n) == INFINITY) ? INF : N)
1119 sopno copy;
1121 if (p->error != 0) /* head off possible runaway recursion */
1122 return;
1124 assert(from <= to);
1126 switch (REP(MAP(from), MAP(to))) {
1127 case REP(0, 0): /* must be user doing this */
1128 DROP(finish-start); /* drop the operand */
1129 break;
1130 case REP(0, 1): /* as x{1,1}? */
1131 case REP(0, N): /* as x{1,n}? */
1132 case REP(0, INF): /* as x{1,}? */
1133 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
1134 INSERT(OCH_, start); /* offset is wrong... */
1135 repeat(p, start+1, 1, to);
1136 ASTERN(OOR1, start);
1137 AHEAD(start); /* ... fix it */
1138 EMIT(OOR2, 0);
1139 AHEAD(THERE());
1140 ASTERN(O_CH, THERETHERE());
1141 break;
1142 case REP(1, 1): /* trivial case */
1143 /* done */
1144 break;
1145 case REP(1, N): /* as x?x{1,n-1} */
1146 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
1147 INSERT(OCH_, start);
1148 ASTERN(OOR1, start);
1149 AHEAD(start);
1150 EMIT(OOR2, 0); /* offset very wrong... */
1151 AHEAD(THERE()); /* ...so fix it */
1152 ASTERN(O_CH, THERETHERE());
1153 copy = dupl(p, start+1, finish+1);
1154 assert(copy == finish+4);
1155 repeat(p, copy, 1, to-1);
1156 break;
1157 case REP(1, INF): /* as x+ */
1158 INSERT(OPLUS_, start);
1159 ASTERN(O_PLUS, start);
1160 break;
1161 case REP(N, N): /* as xx{m-1,n-1} */
1162 copy = dupl(p, start, finish);
1163 repeat(p, copy, from-1, to-1);
1164 break;
1165 case REP(N, INF): /* as xx{n-1,INF} */
1166 copy = dupl(p, start, finish);
1167 repeat(p, copy, from-1, to);
1168 break;
1169 default: /* "can't happen" */
1170 SETERROR(REG_ASSERT); /* just in case */
1171 break;
1176 - seterr - set an error condition
1177 == static int seterr(struct parse *p, int e);
1179 static int /* useless but makes type checking happy */
1180 seterr(
1181 struct parse *p,
1182 int e
1185 if (p->error == 0) /* keep earliest error condition */
1186 p->error = e;
1187 p->next = nuls; /* try to bring things to a halt */
1188 p->end = nuls;
1189 return(0); /* make the return value well-defined */
1193 - allocset - allocate a set of characters for []
1194 == static cset *allocset(struct parse *p);
1196 static cset *
1197 allocset(struct parse *p)
1199 int no = p->g->ncsets++;
1200 size_t nc;
1201 size_t nbytes;
1202 cset *cs;
1203 size_t css = (size_t)p->g->csetsize;
1204 int i;
1206 if (no >= p->ncsalloc) { /* need another column of space */
1207 p->ncsalloc += CHAR_BIT;
1208 nc = p->ncsalloc;
1209 assert(nc % CHAR_BIT == 0);
1210 nbytes = nc / CHAR_BIT * css;
1211 if (p->g->sets == NULL)
1212 p->g->sets = (cset *)malloc(nc * sizeof(cset));
1213 else
1214 p->g->sets = (cset *)reallocf((char *)p->g->sets,
1215 nc * sizeof(cset));
1216 if (p->g->setbits == NULL)
1217 p->g->setbits = (uch *)malloc(nbytes);
1218 else {
1219 p->g->setbits = (uch *)reallocf((char *)p->g->setbits,
1220 nbytes);
1221 /* xxx this isn't right if setbits is now NULL */
1222 for (i = 0; i < no; i++)
1223 p->g->sets[i].ptr = p->g->setbits + css*(i/CHAR_BIT);
1225 if (p->g->sets != NULL && p->g->setbits != NULL)
1226 (void) memset((char *)p->g->setbits + (nbytes - css),
1227 0, css);
1228 else {
1229 no = 0;
1230 SETERROR(REG_ESPACE);
1231 /* caller's responsibility not to do set ops */
1235 assert(p->g->sets != NULL); /* xxx */
1236 cs = &p->g->sets[no];
1237 cs->ptr = p->g->setbits + css*((no)/CHAR_BIT);
1238 cs->mask = 1 << ((no) % CHAR_BIT);
1239 cs->hash = 0;
1240 cs->smultis = 0;
1241 cs->multis = NULL;
1243 return(cs);
1247 - freeset - free a now-unused set
1248 == static void freeset(struct parse *p, cset *cs);
1250 static void
1251 freeset(
1252 struct parse *p,
1253 cset *cs
1256 int i;
1257 cset *top = &p->g->sets[p->g->ncsets];
1258 size_t css = (size_t)p->g->csetsize;
1260 for (i = 0; i < css; i++)
1261 CHsub(cs, i);
1262 if (cs == top-1) /* recover only the easy case */
1263 p->g->ncsets--;
1267 - freezeset - final processing on a set of characters
1268 == static int freezeset(struct parse *p, cset *cs);
1270 * The main task here is merging identical sets. This is usually a waste
1271 * of time (although the hash code minimizes the overhead), but can win
1272 * big if REG_ICASE is being used. REG_ICASE, by the way, is why the hash
1273 * is done using addition rather than xor -- all ASCII [aA] sets xor to
1274 * the same value!
1276 static int /* set number */
1277 freezeset(
1278 struct parse *p,
1279 cset *cs
1282 short h = cs->hash;
1283 int i;
1284 cset *top = &p->g->sets[p->g->ncsets];
1285 cset *cs2;
1286 size_t css = (size_t)p->g->csetsize;
1288 /* look for an earlier one which is the same */
1289 for (cs2 = &p->g->sets[0]; cs2 < top; cs2++)
1290 if (cs2->hash == h && cs2 != cs) {
1291 /* maybe */
1292 for (i = 0; i < css; i++)
1293 if (!!CHIN(cs2, i) != !!CHIN(cs, i))
1294 break; /* no */
1295 if (i == css)
1296 break; /* yes */
1299 if (cs2 < top) { /* found one */
1300 freeset(p, cs);
1301 cs = cs2;
1304 return((int)(cs - p->g->sets));
1308 - firstch - return first character in a set (which must have at least one)
1309 == static int firstch(struct parse *p, cset *cs);
1311 static int /* character; there is no "none" value */
1312 firstch(
1313 struct parse *p,
1314 cset *cs
1317 int i;
1318 size_t css = (size_t)p->g->csetsize;
1320 for (i = 0; i < css; i++)
1321 if (CHIN(cs, i))
1322 return((char)i);
1323 assert(never);
1324 return(0); /* arbitrary */
1328 - nch - number of characters in a set
1329 == static int nch(struct parse *p, cset *cs);
1331 static int
1332 nch(
1333 struct parse *p,
1334 cset *cs
1337 int i;
1338 size_t css = (size_t)p->g->csetsize;
1339 int n = 0;
1341 for (i = 0; i < css; i++)
1342 if (CHIN(cs, i))
1343 n++;
1344 return(n);
1347 #if used
1349 - mcadd - add a collating element to a cset
1350 == static void mcadd(struct parse *p, cset *cs, \
1351 == char *cp);
1353 static void
1354 mcadd(p, cs, cp)
1355 struct parse *p;
1356 cset *cs;
1357 char *cp;
1359 size_t oldend = cs->smultis;
1361 cs->smultis += strlen(cp) + 1;
1362 if (cs->multis == NULL)
1363 cs->multis = malloc(cs->smultis);
1364 else
1365 cs->multis = reallocf(cs->multis, cs->smultis);
1366 if (cs->multis == NULL) {
1367 SETERROR(REG_ESPACE);
1368 return;
1371 (void) strcpy(cs->multis + oldend - 1, cp);
1372 cs->multis[cs->smultis - 1] = '\0';
1376 - mcsub - subtract a collating element from a cset
1377 == static void mcsub(cset *cs, char *cp);
1379 static void
1380 mcsub(cs, cp)
1381 cset *cs;
1382 char *cp;
1384 char *fp = mcfind(cs, cp);
1385 size_t len = strlen(fp);
1387 assert(fp != NULL);
1388 (void) memmove(fp, fp + len + 1,
1389 cs->smultis - (fp + len + 1 - cs->multis));
1390 cs->smultis -= len;
1392 if (cs->smultis == 0) {
1393 free(cs->multis);
1394 cs->multis = NULL;
1395 return;
1398 cs->multis = reallocf(cs->multis, cs->smultis);
1399 assert(cs->multis != NULL);
1403 - mcin - is a collating element in a cset?
1404 == static int mcin(cset *cs, char *cp);
1406 static int
1407 mcin(cs, cp)
1408 cset *cs;
1409 char *cp;
1411 return(mcfind(cs, cp) != NULL);
1415 - mcfind - find a collating element in a cset
1416 == static char *mcfind(cset *cs, char *cp);
1418 static char *
1419 mcfind(cs, cp)
1420 cset *cs;
1421 char *cp;
1423 char *p;
1425 if (cs->multis == NULL)
1426 return(NULL);
1427 for (p = cs->multis; *p != '\0'; p += strlen(p) + 1)
1428 if (strcmp(cp, p) == 0)
1429 return(p);
1430 return(NULL);
1432 #endif
1435 - mcinvert - invert the list of collating elements in a cset
1436 == static void mcinvert(struct parse *p, cset *cs);
1438 * This would have to know the set of possibilities. Implementation
1439 * is deferred.
1441 static void
1442 mcinvert(
1443 struct parse *p,
1444 cset *cs
1447 assert(cs->multis == NULL); /* xxx */
1451 - mccase - add case counterparts of the list of collating elements in a cset
1452 == static void mccase(struct parse *p, cset *cs);
1454 * This would have to know the set of possibilities. Implementation
1455 * is deferred.
1457 static void
1458 mccase(
1459 struct parse *p,
1460 cset *cs
1463 assert(cs->multis == NULL); /* xxx */
1467 - isinsets - is this character in any sets?
1468 == static int isinsets(struct re_guts *g, int c);
1470 static int /* predicate */
1471 isinsets(
1472 struct re_guts *g,
1473 int c
1476 uch *col;
1477 int i;
1478 int ncols = (g->ncsets+(CHAR_BIT-1)) / CHAR_BIT;
1479 unsigned uc = (uch)c;
1481 for (i = 0, col = g->setbits; i < ncols; i++, col += g->csetsize)
1482 if (col[uc] != 0)
1483 return(1);
1484 return(0);
1488 - samesets - are these two characters in exactly the same sets?
1489 == static int samesets(struct re_guts *g, int c1, int c2);
1491 static int /* predicate */
1492 samesets(
1493 struct re_guts *g,
1494 int c1,
1495 int c2
1498 uch *col;
1499 int i;
1500 int ncols = (g->ncsets+(CHAR_BIT-1)) / CHAR_BIT;
1501 unsigned uc1 = (uch)c1;
1502 unsigned uc2 = (uch)c2;
1504 for (i = 0, col = g->setbits; i < ncols; i++, col += g->csetsize)
1505 if (col[uc1] != col[uc2])
1506 return(0);
1507 return(1);
1511 - categorize - sort out character categories
1512 == static void categorize(struct parse *p, struct re_guts *g);
1514 static void
1515 categorize(
1516 struct parse *p,
1517 struct re_guts *g
1520 cat_t *cats = g->categories;
1521 int c;
1522 int c2;
1523 cat_t cat;
1525 /* avoid making error situations worse */
1526 if (p->error != 0)
1527 return;
1529 for (c = CHAR_MIN; c <= CHAR_MAX; c++)
1530 if (cats[c] == 0 && isinsets(g, c)) {
1531 cat = g->ncategories++;
1532 cats[c] = cat;
1533 for (c2 = c+1; c2 <= CHAR_MAX; c2++)
1534 if (cats[c2] == 0 && samesets(g, c, c2))
1535 cats[c2] = cat;
1540 - dupl - emit a duplicate of a bunch of sops
1541 == static sopno dupl(struct parse *p, sopno start, sopno finish);
1543 static sopno /* start of duplicate */
1544 dupl(
1545 struct parse *p,
1546 sopno start, /* from here */
1547 sopno finish /* to this less one */
1550 sopno ret = HERE();
1551 sopno len = finish - start;
1553 assert(finish >= start);
1554 if (len == 0)
1555 return(ret);
1556 enlarge(p, p->ssize + len); /* this many unexpected additions */
1557 assert(p->ssize >= p->slen + len);
1558 (void) memcpy((char *)(p->strip + p->slen),
1559 (char *)(p->strip + start), (size_t)len*sizeof(sop));
1560 p->slen += len;
1561 return(ret);
1565 - doemit - emit a strip operator
1566 == static void doemit(struct parse *p, sop op, size_t opnd);
1568 * It might seem better to implement this as a macro with a function as
1569 * hard-case backup, but it's just too big and messy unless there are
1570 * some changes to the data structures. Maybe later.
1572 static void
1573 doemit(
1574 struct parse *p,
1575 sop op,
1576 size_t opnd
1579 /* avoid making error situations worse */
1580 if (p->error != 0)
1581 return;
1583 /* deal with oversize operands ("can't happen", more or less) */
1584 assert(opnd < 1<<OPSHIFT);
1586 /* deal with undersized strip */
1587 if (p->slen >= p->ssize)
1588 enlarge(p, (p->ssize+1) / 2 * 3); /* +50% */
1589 assert(p->slen < p->ssize);
1591 /* finally, it's all reduced to the easy case */
1592 p->strip[p->slen++] = SOP(op, opnd);
1596 - doinsert - insert a sop into the strip
1597 == static void doinsert(struct parse *p, sop op, size_t opnd, sopno pos);
1599 static void
1600 doinsert(
1601 struct parse *p,
1602 sop op,
1603 size_t opnd,
1604 sopno pos
1607 sopno sn;
1608 sop s;
1609 int i;
1611 /* avoid making error situations worse */
1612 if (p->error != 0)
1613 return;
1615 sn = HERE();
1616 EMIT(op, opnd); /* do checks, ensure space */
1617 assert(HERE() == sn+1);
1618 s = p->strip[sn];
1620 /* adjust paren pointers */
1621 assert(pos > 0);
1622 for (i = 1; i < NPAREN; i++) {
1623 if (p->pbegin[i] >= pos) {
1624 p->pbegin[i]++;
1626 if (p->pend[i] >= pos) {
1627 p->pend[i]++;
1631 memmove((char *)&p->strip[pos+1], (char *)&p->strip[pos],
1632 (HERE()-pos-1)*sizeof(sop));
1633 p->strip[pos] = s;
1637 - dofwd - complete a forward reference
1638 == static void dofwd(struct parse *p, sopno pos, sop value);
1640 static void
1641 dofwd(
1642 struct parse *p,
1643 sopno pos,
1644 sop value
1647 /* avoid making error situations worse */
1648 if (p->error != 0)
1649 return;
1651 assert(value < 1<<OPSHIFT);
1652 p->strip[pos] = OP(p->strip[pos]) | value;
1656 - enlarge - enlarge the strip
1657 == static void enlarge(struct parse *p, sopno size);
1659 static void
1660 enlarge(
1661 struct parse *p,
1662 sopno size
1665 sop *sp;
1667 if (p->ssize >= size)
1668 return;
1670 sp = (sop *)realloc(p->strip, size*sizeof(sop));
1671 if (sp == NULL) {
1672 SETERROR(REG_ESPACE);
1673 return;
1675 p->strip = sp;
1676 p->ssize = size;
1680 - stripsnug - compact the strip
1681 == static void stripsnug(struct parse *p, struct re_guts *g);
1683 static void
1684 stripsnug(
1685 struct parse *p,
1686 struct re_guts *g
1689 g->nstates = p->slen;
1690 g->strip = (sop *)realloc((char *)p->strip, p->slen * sizeof(sop));
1691 if (g->strip == NULL) {
1692 SETERROR(REG_ESPACE);
1693 g->strip = p->strip;
1698 - findmust - fill in must and mlen with longest mandatory literal string
1699 == static void findmust(struct parse *p, struct re_guts *g);
1701 * This algorithm could do fancy things like analyzing the operands of |
1702 * for common subsequences. Someday. This code is simple and finds most
1703 * of the interesting cases.
1705 * Note that must and mlen got initialized during setup.
1707 static void
1708 findmust(
1709 struct parse *p,
1710 struct re_guts *g
1713 sop *scan;
1714 sop *start = NULL;
1715 sop *newstart = NULL;
1716 sopno newlen;
1717 sop s;
1718 char *cp;
1719 sopno i;
1720 int offset;
1721 int cs, mccs;
1723 /* avoid making error situations worse */
1724 if (p->error != 0)
1725 return;
1727 /* Find out if we can handle OANYOF or not */
1728 mccs = 0;
1729 for (cs = 0; cs < g->ncsets; cs++)
1730 if (g->sets[cs].multis != NULL)
1731 mccs = 1;
1733 /* find the longest OCHAR sequence in strip */
1734 newlen = 0;
1735 offset = 0;
1736 g->moffset = 0;
1737 scan = g->strip + 1;
1738 do {
1739 s = *scan++;
1740 switch (OP(s)) {
1741 case OCHAR: /* sequence member */
1742 if (newlen == 0) /* new sequence */
1743 newstart = scan - 1;
1744 newlen++;
1745 break;
1746 case OPLUS_: /* things that don't break one */
1747 case OLPAREN:
1748 case ORPAREN:
1749 break;
1750 case OQUEST_: /* things that must be skipped */
1751 case OCH_:
1752 offset = altoffset(scan, offset, mccs);
1753 scan--;
1754 do {
1755 scan += OPND(s);
1756 s = *scan;
1757 /* assert() interferes w debug printouts */
1758 if (OP(s) != O_QUEST && OP(s) != O_CH &&
1759 OP(s) != OOR2) {
1760 g->iflags |= BAD;
1761 return;
1763 } while (OP(s) != O_QUEST && OP(s) != O_CH);
1764 /* fallthrough */
1765 case OBOW: /* things that break a sequence */
1766 case OEOW:
1767 case OBOL:
1768 case OEOL:
1769 case O_QUEST:
1770 case O_CH:
1771 case OEND:
1772 if (newlen > g->mlen) { /* ends one */
1773 start = newstart;
1774 g->mlen = newlen;
1775 if (offset > -1) {
1776 g->moffset += offset;
1777 offset = newlen;
1778 } else
1779 g->moffset = offset;
1780 } else {
1781 if (offset > -1)
1782 offset += newlen;
1784 newlen = 0;
1785 break;
1786 case OANY:
1787 if (newlen > g->mlen) { /* ends one */
1788 start = newstart;
1789 g->mlen = newlen;
1790 if (offset > -1) {
1791 g->moffset += offset;
1792 offset = newlen;
1793 } else
1794 g->moffset = offset;
1795 } else {
1796 if (offset > -1)
1797 offset += newlen;
1799 if (offset > -1)
1800 offset++;
1801 newlen = 0;
1802 break;
1803 case OANYOF: /* may or may not invalidate offset */
1804 /* First, everything as OANY */
1805 if (newlen > g->mlen) { /* ends one */
1806 start = newstart;
1807 g->mlen = newlen;
1808 if (offset > -1) {
1809 g->moffset += offset;
1810 offset = newlen;
1811 } else
1812 g->moffset = offset;
1813 } else {
1814 if (offset > -1)
1815 offset += newlen;
1817 if (offset > -1)
1818 offset++;
1819 newlen = 0;
1820 /* And, now, if we found out we can't deal with
1821 * it, make offset = -1.
1823 if (mccs)
1824 offset = -1;
1825 break;
1826 default:
1827 /* Anything here makes it impossible or too hard
1828 * to calculate the offset -- so we give up;
1829 * save the last known good offset, in case the
1830 * must sequence doesn't occur later.
1832 if (newlen > g->mlen) { /* ends one */
1833 start = newstart;
1834 g->mlen = newlen;
1835 if (offset > -1)
1836 g->moffset += offset;
1837 else
1838 g->moffset = offset;
1840 offset = -1;
1841 newlen = 0;
1842 break;
1844 } while (OP(s) != OEND);
1846 if (g->mlen == 0) { /* there isn't one */
1847 g->moffset = -1;
1848 return;
1851 /* turn it into a character string */
1852 g->must = malloc((size_t)g->mlen + 1);
1853 if (g->must == NULL) { /* argh; just forget it */
1854 g->mlen = 0;
1855 g->moffset = -1;
1856 return;
1858 cp = g->must;
1859 scan = start;
1860 for (i = g->mlen; i > 0; i--) {
1861 while (OP(s = *scan++) != OCHAR)
1862 continue;
1863 assert(cp < g->must + g->mlen);
1864 *cp++ = (char)OPND(s);
1866 assert(cp == g->must + g->mlen);
1867 *cp++ = '\0'; /* just on general principles */
1871 - altoffset - choose biggest offset among multiple choices
1872 == static int altoffset(sop *scan, int offset, int mccs);
1874 * Compute, recursively if necessary, the largest offset among multiple
1875 * re paths.
1877 static int
1878 altoffset(
1879 sop *scan,
1880 int offset,
1881 int mccs
1884 int largest;
1885 int try;
1886 sop s;
1888 /* If we gave up already on offsets, return */
1889 if (offset == -1)
1890 return -1;
1892 largest = 0;
1893 try = 0;
1894 s = *scan++;
1895 while (OP(s) != O_QUEST && OP(s) != O_CH) {
1896 switch (OP(s)) {
1897 case OOR1:
1898 if (try > largest)
1899 largest = try;
1900 try = 0;
1901 break;
1902 case OQUEST_:
1903 case OCH_:
1904 try = altoffset(scan, try, mccs);
1905 if (try == -1)
1906 return -1;
1907 scan--;
1908 do {
1909 scan += OPND(s);
1910 s = *scan;
1911 if (OP(s) != O_QUEST && OP(s) != O_CH &&
1912 OP(s) != OOR2)
1913 return -1;
1914 } while (OP(s) != O_QUEST && OP(s) != O_CH);
1915 /* We must skip to the next position, or we'll
1916 * leave altoffset() too early.
1918 scan++;
1919 break;
1920 case OANYOF:
1921 if (mccs)
1922 return -1;
1923 case OCHAR:
1924 case OANY:
1925 try++;
1926 case OBOW:
1927 case OEOW:
1928 case OLPAREN:
1929 case ORPAREN:
1930 case OOR2:
1931 break;
1932 default:
1933 try = -1;
1934 break;
1936 if (try == -1)
1937 return -1;
1938 s = *scan++;
1941 if (try > largest)
1942 largest = try;
1944 return largest+offset;
1948 - computejumps - compute char jumps for BM scan
1949 == static void computejumps(struct parse *p, struct re_guts *g);
1951 * This algorithm assumes g->must exists and is has size greater than
1952 * zero. It's based on the algorithm found on Computer Algorithms by
1953 * Sara Baase.
1955 * A char jump is the number of characters one needs to jump based on
1956 * the value of the character from the text that was mismatched.
1958 static void
1959 computejumps(
1960 struct parse *p,
1961 struct re_guts *g
1964 int ch;
1965 int mindex;
1967 /* Avoid making errors worse */
1968 if (p->error != 0)
1969 return;
1971 g->charjump = (int*) malloc((NC + 1) * sizeof(int));
1972 if (g->charjump == NULL) /* Not a fatal error */
1973 return;
1974 /* Adjust for signed chars, if necessary */
1975 g->charjump = &g->charjump[-(CHAR_MIN)];
1977 /* If the character does not exist in the pattern, the jump
1978 * is equal to the number of characters in the pattern.
1980 for (ch = CHAR_MIN; ch < (CHAR_MAX + 1); ch++)
1981 g->charjump[ch] = g->mlen;
1983 /* If the character does exist, compute the jump that would
1984 * take us to the last character in the pattern equal to it
1985 * (notice that we match right to left, so that last character
1986 * is the first one that would be matched).
1988 for (mindex = 0; mindex < g->mlen; mindex++)
1989 g->charjump[(unsigned char) g->must[mindex]] = g->mlen - mindex - 1;
1993 - computematchjumps - compute match jumps for BM scan
1994 == static void computematchjumps(struct parse *p, struct re_guts *g);
1996 * This algorithm assumes g->must exists and is has size greater than
1997 * zero. It's based on the algorithm found on Computer Algorithms by
1998 * Sara Baase.
2000 * A match jump is the number of characters one needs to advance based
2001 * on the already-matched suffix.
2002 * Notice that all values here are minus (g->mlen-1), because of the way
2003 * the search algorithm works.
2005 static void
2006 computematchjumps(
2007 struct parse *p,
2008 struct re_guts *g
2011 int mindex; /* General "must" iterator */
2012 int suffix; /* Keeps track of matching suffix */
2013 int ssuffix; /* Keeps track of suffixes' suffix */
2014 int* pmatches; /* pmatches[k] points to the next i
2015 * such that i+1...mlen is a substring
2016 * of k+1...k+mlen-i-1
2019 /* Avoid making errors worse */
2020 if (p->error != 0)
2021 return;
2023 pmatches = (int*) malloc(g->mlen * sizeof(unsigned int));
2024 if (pmatches == NULL) {
2025 g->matchjump = NULL;
2026 return;
2029 g->matchjump = (int*) malloc(g->mlen * sizeof(unsigned int));
2030 if (g->matchjump == NULL) { /* Not a fatal error */
2031 free(pmatches);
2032 return;
2035 /* Set maximum possible jump for each character in the pattern */
2036 for (mindex = 0; mindex < g->mlen; mindex++)
2037 g->matchjump[mindex] = 2*g->mlen - mindex - 1;
2039 /* Compute pmatches[] */
2040 for (mindex = g->mlen - 1, suffix = g->mlen; mindex >= 0;
2041 mindex--, suffix--) {
2042 pmatches[mindex] = suffix;
2044 /* If a mismatch is found, interrupting the substring,
2045 * compute the matchjump for that position. If no
2046 * mismatch is found, then a text substring mismatched
2047 * against the suffix will also mismatch against the
2048 * substring.
2050 while (suffix < g->mlen
2051 && g->must[mindex] != g->must[suffix]) {
2052 g->matchjump[suffix] = MIN(g->matchjump[suffix],
2053 g->mlen - mindex - 1);
2054 suffix = pmatches[suffix];
2058 /* Compute the matchjump up to the last substring found to jump
2059 * to the beginning of the largest must pattern prefix matching
2060 * it's own suffix.
2062 for (mindex = 0; mindex <= suffix; mindex++)
2063 g->matchjump[mindex] = MIN(g->matchjump[mindex],
2064 g->mlen + suffix - mindex);
2066 ssuffix = pmatches[suffix];
2067 while (suffix < g->mlen) {
2068 while (suffix <= ssuffix && suffix < g->mlen) {
2069 g->matchjump[suffix] = MIN(g->matchjump[suffix],
2070 g->mlen + ssuffix - suffix);
2071 suffix++;
2073 if (suffix < g->mlen)
2074 ssuffix = pmatches[ssuffix];
2077 free(pmatches);
2081 - pluscount - count + nesting
2082 == static sopno pluscount(struct parse *p, struct re_guts *g);
2084 static sopno /* nesting depth */
2085 pluscount(
2086 struct parse *p,
2087 struct re_guts *g
2090 sop *scan;
2091 sop s;
2092 sopno plusnest = 0;
2093 sopno maxnest = 0;
2095 if (p->error != 0)
2096 return(0); /* there may not be an OEND */
2098 scan = g->strip + 1;
2099 do {
2100 s = *scan++;
2101 switch (OP(s)) {
2102 case OPLUS_:
2103 plusnest++;
2104 break;
2105 case O_PLUS:
2106 if (plusnest > maxnest)
2107 maxnest = plusnest;
2108 plusnest--;
2109 break;
2111 } while (OP(s) != OEND);
2112 if (plusnest != 0)
2113 g->iflags |= BAD;
2114 return(maxnest);
2117 #endif /* !_NO_REGEX */