1 /* $OpenBSD: regcomp.c,v 1.15 2005/08/05 13:03:00 espie Exp $ */
2 /*-
3 * Copyright © 2013
4 * Thorsten “mirabilos” Glaser <tg@mirbsd.org>
5 * Copyright (c) 1992, 1993, 1994 Henry Spencer.
6 * Copyright (c) 1992, 1993, 1994
7 * The Regents of the University of California. All rights reserved.
8 *
9 * This code is derived from software contributed to Berkeley by
10 * Henry Spencer.
11 *
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
14 * are met:
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in the
19 * documentation and/or other materials provided with the distribution.
20 * 3. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
23 *
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * SUCH DAMAGE.
35 *
36 * @(#)regcomp.c 8.5 (Berkeley) 3/20/94
37 */
38
39 #include <sys/types.h>
40 #include <stdio.h>
41 #include <string.h>
42 #include <ctype.h>
43 #include <limits.h>
44 #include <stdint.h>
45 #include <stdlib.h>
46 #include <regex.h>
47
48 #include "utils.h"
49 #include "regex2.h"
50
51 #include "cclass.h"
52 #include "cname.h"
53
54 __RCSID("$MirOS: src/lib/libc/regex/regcomp.c,v 1.5 2013/10/31 20:06:21 tg Exp $");
55
56 /*
57 * parse structure, passed up and down to avoid global variables and
58 * other clumsinesses
59 */
60 struct parse {
61 const char *next; /* next character in RE */
62 const char *end; /* end of string (-> NUL normally) */
63 int error; /* has an error been seen? */
64 sop *strip; /* malloced strip */
65 sopno ssize; /* malloced strip size (allocated) */
66 sopno slen; /* malloced strip length (used) */
67 int ncsalloc; /* number of csets allocated */
68 struct re_guts *g;
69 # define NPAREN 10 /* we need to remember () 1-9 for back refs */
70 sopno pbegin[NPAREN]; /* -> ( ([0] unused) */
71 sopno pend[NPAREN]; /* -> ) ([0] unused) */
72 };
73
74 static void p_ere(struct parse *, int);
75 static void p_ere_exp(struct parse *);
76 static void p_str(struct parse *);
77 static void p_bre(struct parse *, int, int);
78 static int p_simp_re(struct parse *, int);
79 static int p_count(struct parse *);
80 static void p_bracket(struct parse *);
81 static void p_b_term(struct parse *, cset *);
82 static void p_b_cclass(struct parse *, cset *);
83 static void p_b_eclass(struct parse *, cset *);
84 static char p_b_symbol(struct parse *);
85 static char p_b_coll_elem(struct parse *, int);
86 static char othercase(int);
87 static void bothcases(struct parse *, int);
88 static void ordinary(struct parse *, int);
89 static void nonnewline(struct parse *);
90 static void repeat(struct parse *, sopno, int, int);
91 static int seterr(struct parse *, int);
92 static cset *allocset(struct parse *);
93 static void freeset(struct parse *, cset *);
94 static int freezeset(struct parse *, cset *);
95 static int firstch(struct parse *, cset *);
96 static int nch(struct parse *, cset *);
97 static void mcadd(struct parse *, cset *, const char *);
98 static void mcinvert(struct parse *, cset *);
99 static void mccase(struct parse *, cset *);
100 static int isinsets(struct re_guts *, int);
101 static int samesets(struct re_guts *, int, int);
102 static void categorize(struct parse *, struct re_guts *);
103 static sopno dupl(struct parse *, sopno, sopno);
104 static void doemit(struct parse *, sop, size_t);
105 static void doinsert(struct parse *, sop, size_t, sopno);
106 static void dofwd(struct parse *, sopno, sop);
107 static void enlarge(struct parse *, sopno);
108 static void stripsnug(struct parse *, struct re_guts *);
109 static void findmust(struct parse *, struct re_guts *);
110 static sopno pluscount(struct parse *, struct re_guts *);
111
112 static char nuls[10]; /* place to point scanner in event of error */
113
114 /*
115 * macros for use with parse structure
116 * BEWARE: these know that the parse structure is named `p' !!!
117 */
118 #define PEEK() (*p->next)
119 #define PEEK2() (*(p->next+1))
120 #define MORE() (p->next < p->end)
121 #define MORE2() (p->next+1 < p->end)
122 #define SEE(c) (MORE() && PEEK() == (c))
123 #define SEETWO(a, b) (MORE() && MORE2() && PEEK() == (a) && PEEK2() == (b))
124 #define EAT(c) ((SEE(c)) ? (NEXT(), 1) : 0)
125 #define EATTWO(a, b) ((SEETWO(a, b)) ? (NEXT2(), 1) : 0)
126 #define NEXT() (p->next++)
127 #define NEXT2() (p->next += 2)
128 #define NEXTn(n) (p->next += (n))
129 #define GETNEXT() (*p->next++)
130 #define SETERROR(e) seterr(p, (e))
131 #define REQUIRE(co, e) ((co) || SETERROR(e))
132 #define MUSTSEE(c, e) (REQUIRE(MORE() && PEEK() == (c), e))
133 #define MUSTEAT(c, e) (REQUIRE(MORE() && GETNEXT() == (c), e))
134 #define MUSTNOTSEE(c, e) (REQUIRE(!MORE() || PEEK() != (c), e))
135 #define EMIT(op, sopnd) doemit(p, (sop)(op), (size_t)(sopnd))
136 #define INSERT(op, pos) doinsert(p, (sop)(op), HERE()-(pos)+1, pos)
137 #define AHEAD(pos) dofwd(p, pos, HERE()-(pos))
138 #define ASTERN(sop, pos) EMIT(sop, HERE()-pos)
139 #define HERE() (p->slen)
140 #define THERE() (p->slen - 1)
141 #define THERETHERE() (p->slen - 2)
142 #define DROP(n) (p->slen -= (n))
143
144 #ifndef NDEBUG
145 static int never = 0; /* for use in asserts; shuts lint up */
146 #else
147 #define never 0 /* some <assert.h>s have bugs too */
148 #endif
149
150 /*
151 - regcomp - interface for parser and compilation
152 */
153 int /* 0 success, otherwise REG_something */
regcomp(regex_t * preg,const char * pattern,int cflags)154 regcomp(regex_t *preg, const char *pattern, int cflags)
155 {
156 struct parse pa;
157 struct re_guts *g;
158 struct parse *p = &pa;
159 int i;
160 size_t len;
161 #ifdef REDEBUG
162 # define GOODFLAGS(f) (f)
163 #else
164 # define GOODFLAGS(f) ((f)&~REG_DUMP)
165 #endif
166
167 cflags = GOODFLAGS(cflags);
168 if ((cflags®_EXTENDED) && (cflags®_NOSPEC))
169 return(REG_INVARG);
170
171 if (cflags®_PEND) {
172 if (preg->re_endp < pattern)
173 return(REG_INVARG);
174 len = preg->re_endp - pattern;
175 } else
176 len = strlen(pattern);
177
178 /* do the mallocs early so failure handling is easy */
179 g = (struct re_guts *)malloc(sizeof(struct re_guts) +
180 (NC-1)*sizeof(cat_t));
181 if (g == NULL)
182 return(REG_ESPACE);
183 p->ssize = len/(size_t)2*(size_t)3 + (size_t)1; /* ugh */
184 p->strip = (sop *)malloc(p->ssize * sizeof(sop));
185 p->slen = 0;
186 if (p->strip == NULL) {
187 free((char *)g);
188 return(REG_ESPACE);
189 }
190
191 /* set things up */
192 p->g = g;
193 p->next = pattern;
194 p->end = p->next + len;
195 p->error = 0;
196 p->ncsalloc = 0;
197 for (i = 0; i < NPAREN; i++) {
198 p->pbegin[i] = 0;
199 p->pend[i] = 0;
200 }
201 g->csetsize = NC;
202 g->sets = NULL;
203 g->setbits = NULL;
204 g->ncsets = 0;
205 g->cflags = cflags;
206 g->iflags = 0;
207 g->nbol = 0;
208 g->neol = 0;
209 g->must = NULL;
210 g->mlen = 0;
211 g->nsub = 0;
212 g->ncategories = 1; /* category 0 is "everything else" */
213 g->categories = &g->catspace[-(CHAR_MIN)];
214 (void) memset((char *)g->catspace, 0, NC*sizeof(cat_t));
215 g->backrefs = 0;
216
217 /* do it */
218 EMIT(OEND, 0);
219 g->firststate = THERE();
220 if (cflags®_EXTENDED)
221 p_ere(p, OUT);
222 else if (cflags®_NOSPEC)
223 p_str(p);
224 else
225 p_bre(p, OUT, OUT);
226 EMIT(OEND, 0);
227 g->laststate = THERE();
228
229 /* tidy up loose ends and fill things in */
230 categorize(p, g);
231 stripsnug(p, g);
232 findmust(p, g);
233 g->nplus = pluscount(p, g);
234 g->magic = MAGIC2;
235 preg->re_nsub = g->nsub;
236 preg->re_g = g;
237 preg->re_magic = MAGIC1;
238 #ifndef REDEBUG
239 /* not debugging, so can't rely on the assert() in regexec() */
240 if (g->iflags&BAD)
241 SETERROR(REG_ASSERT);
242 #endif
243
244 /* win or lose, we're done */
245 if (p->error != 0) /* lose */
246 regfree(preg);
247 return(p->error);
248 }
249
250 /*
251 - p_ere - ERE parser top level, concatenation and alternation
252 */
253 static void
p_ere(struct parse * p,int stop)254 p_ere(struct parse *p, int stop) /* character this ERE should end at */
255 {
256 char c;
257 sopno prevback = 0;
258 sopno prevfwd = 0;
259 sopno conc;
260 int first = 1; /* is this the first alternative? */
261
262 for (;;) {
263 /* do a bunch of concatenated expressions */
264 conc = HERE();
265 while (MORE() && (c = PEEK()) != '|' && c != stop)
266 p_ere_exp(p);
267 REQUIRE(HERE() != conc, REG_EMPTY); /* require nonempty */
268
269 if (!EAT('|'))
270 break; /* NOTE BREAK OUT */
271
272 if (first) {
273 INSERT(OCH_, conc); /* offset is wrong */
274 prevfwd = conc;
275 prevback = conc;
276 first = 0;
277 }
278 ASTERN(OOR1, prevback);
279 prevback = THERE();
280 AHEAD(prevfwd); /* fix previous offset */
281 prevfwd = HERE();
282 EMIT(OOR2, 0); /* offset is very wrong */
283 }
284
285 if (!first) { /* tail-end fixups */
286 AHEAD(prevfwd);
287 ASTERN(O_CH, prevback);
288 }
289
290 assert(!MORE() || SEE(stop));
291 }
292
293 /*
294 - p_ere_exp - parse one subERE, an atom possibly followed by a repetition op
295 */
296 static void
p_ere_exp(struct parse * p)297 p_ere_exp(struct parse *p)
298 {
299 char c;
300 sopno pos;
301 int count;
302 int count2;
303 sopno subno;
304 int wascaret = 0;
305
306 assert(MORE()); /* caller should have ensured this */
307 c = GETNEXT();
308
309 pos = HERE();
310 switch (c) {
311 case '(':
312 REQUIRE(MORE(), REG_EPAREN);
313 p->g->nsub++;
314 subno = p->g->nsub;
315 if (subno < NPAREN)
316 p->pbegin[subno] = HERE();
317 EMIT(OLPAREN, subno);
318 if (!SEE(')'))
319 p_ere(p, ')');
320 if (subno < NPAREN) {
321 p->pend[subno] = HERE();
322 assert(p->pend[subno] != 0);
323 }
324 EMIT(ORPAREN, subno);
325 MUSTEAT(')', REG_EPAREN);
326 break;
327 #ifndef POSIX_MISTAKE
328 case ')': /* happens only if no current unmatched ( */
329 /*
330 * You may ask, why the ifndef? Because I didn't notice
331 * this until slightly too late for 1003.2, and none of the
332 * other 1003.2 regular-expression reviewers noticed it at
333 * all. So an unmatched ) is legal POSIX, at least until
334 * we can get it fixed.
335 */
336 SETERROR(REG_EPAREN);
337 break;
338 #endif
339 case '^':
340 EMIT(OBOL, 0);
341 p->g->iflags |= USEBOL;
342 p->g->nbol++;
343 wascaret = 1;
344 break;
345 case '$':
346 EMIT(OEOL, 0);
347 p->g->iflags |= USEEOL;
348 p->g->neol++;
349 break;
350 case '|':
351 SETERROR(REG_EMPTY);
352 break;
353 case '*':
354 case '+':
355 case '?':
356 SETERROR(REG_BADRPT);
357 break;
358 case '.':
359 if (p->g->cflags®_NEWLINE)
360 nonnewline(p);
361 else
362 EMIT(OANY, 0);
363 break;
364 case '[':
365 p_bracket(p);
366 break;
367 case '\\':
368 REQUIRE(MORE(), REG_EESCAPE);
369 c = GETNEXT();
370 ordinary(p, c);
371 break;
372 case '{': /* okay as ordinary except if digit follows */
373 REQUIRE(!MORE() || !isdigit((uch)PEEK()), REG_BADRPT);
374 /* FALLTHROUGH */
375 default:
376 ordinary(p, c);
377 break;
378 }
379
380 if (!MORE())
381 return;
382 c = PEEK();
383 /* we call { a repetition if followed by a digit */
384 if (!( c == '*' || c == '+' || c == '?' ||
385 (c == '{' && MORE2() && isdigit((uch)PEEK2())) ))
386 return; /* no repetition, we're done */
387 NEXT();
388
389 REQUIRE(!wascaret, REG_BADRPT);
390 switch (c) {
391 case '*': /* implemented as +? */
392 /* this case does not require the (y|) trick, noKLUDGE */
393 INSERT(OPLUS_, pos);
394 ASTERN(O_PLUS, pos);
395 INSERT(OQUEST_, pos);
396 ASTERN(O_QUEST, pos);
397 break;
398 case '+':
399 INSERT(OPLUS_, pos);
400 ASTERN(O_PLUS, pos);
401 break;
402 case '?':
403 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
404 INSERT(OCH_, pos); /* offset slightly wrong */
405 ASTERN(OOR1, pos); /* this one's right */
406 AHEAD(pos); /* fix the OCH_ */
407 EMIT(OOR2, 0); /* offset very wrong... */
408 AHEAD(THERE()); /* ...so fix it */
409 ASTERN(O_CH, THERETHERE());
410 break;
411 case '{':
412 count = p_count(p);
413 if (EAT(',')) {
414 if (isdigit((uch)PEEK())) {
415 count2 = p_count(p);
416 REQUIRE(count <= count2, REG_BADBR);
417 } else /* single number with comma */
418 count2 = INFINITY;
419 } else /* just a single number */
420 count2 = count;
421 repeat(p, pos, count, count2);
422 if (!EAT('}')) { /* error heuristics */
423 while (MORE() && PEEK() != '}')
424 NEXT();
425 REQUIRE(MORE(), REG_EBRACE);
426 SETERROR(REG_BADBR);
427 }
428 break;
429 }
430
431 if (!MORE())
432 return;
433 c = PEEK();
434 if (!( c == '*' || c == '+' || c == '?' ||
435 (c == '{' && MORE2() && isdigit((uch)PEEK2())) ) )
436 return;
437 SETERROR(REG_BADRPT);
438 }
439
440 /*
441 - p_str - string (no metacharacters) "parser"
442 */
443 static void
p_str(struct parse * p)444 p_str(struct parse *p)
445 {
446 REQUIRE(MORE(), REG_EMPTY);
447 while (MORE())
448 ordinary(p, GETNEXT());
449 }
450
451 /*
452 - p_bre - BRE parser top level, anchoring and concatenation
453 * Giving end1 as OUT essentially eliminates the end1/end2 check.
454 *
455 * This implementation is a bit of a kludge, in that a trailing $ is first
456 * taken as an ordinary character and then revised to be an anchor. The
457 * only undesirable side effect is that '$' gets included as a character
458 * category in such cases. This is fairly harmless; not worth fixing.
459 * The amount of lookahead needed to avoid this kludge is excessive.
460 */
461 static void
p_bre(struct parse * p,int end1,int end2)462 p_bre(struct parse *p,
463 int end1, /* first terminating character */
464 int end2) /* second terminating character */
465 {
466 sopno start = HERE();
467 int first = 1; /* first subexpression? */
468 int wasdollar = 0;
469
470 if (EAT('^')) {
471 EMIT(OBOL, 0);
472 p->g->iflags |= USEBOL;
473 p->g->nbol++;
474 }
475 while (MORE() && !SEETWO(end1, end2)) {
476 wasdollar = p_simp_re(p, first);
477 first = 0;
478 }
479 if (wasdollar) { /* oops, that was a trailing anchor */
480 DROP(1);
481 EMIT(OEOL, 0);
482 p->g->iflags |= USEEOL;
483 p->g->neol++;
484 }
485
486 REQUIRE(HERE() != start, REG_EMPTY); /* require nonempty */
487 }
488
489 /*
490 - p_simp_re - parse a simple RE, an atom possibly followed by a repetition
491 */
492 static int /* was the simple RE an unbackslashed $? */
p_simp_re(struct parse * p,int starordinary)493 p_simp_re(struct parse *p,
494 int starordinary) /* is a leading * an ordinary character? */
495 {
496 int c;
497 int count;
498 int count2;
499 sopno pos;
500 int i;
501 sopno subno;
502 # define BACKSL (1<<CHAR_BIT)
503
504 pos = HERE(); /* repetion op, if any, covers from here */
505
506 assert(MORE()); /* caller should have ensured this */
507 c = GETNEXT();
508 if (c == '\\') {
509 REQUIRE(MORE(), REG_EESCAPE);
510 c = BACKSL | GETNEXT();
511 }
512 switch (c) {
513 case '.':
514 if (p->g->cflags®_NEWLINE)
515 nonnewline(p);
516 else
517 EMIT(OANY, 0);
518 break;
519 case '[':
520 p_bracket(p);
521 break;
522 case BACKSL|'{':
523 SETERROR(REG_BADRPT);
524 break;
525 case BACKSL|'(':
526 p->g->nsub++;
527 subno = p->g->nsub;
528 if (subno < NPAREN)
529 p->pbegin[subno] = HERE();
530 EMIT(OLPAREN, subno);
531 /* the MORE here is an error heuristic */
532 if (MORE() && !SEETWO('\\', ')'))
533 p_bre(p, '\\', ')');
534 if (subno < NPAREN) {
535 p->pend[subno] = HERE();
536 assert(p->pend[subno] != 0);
537 }
538 EMIT(ORPAREN, subno);
539 REQUIRE(EATTWO('\\', ')'), REG_EPAREN);
540 break;
541 case BACKSL|')': /* should not get here -- must be user */
542 case BACKSL|'}':
543 SETERROR(REG_EPAREN);
544 break;
545 case BACKSL|'1':
546 case BACKSL|'2':
547 case BACKSL|'3':
548 case BACKSL|'4':
549 case BACKSL|'5':
550 case BACKSL|'6':
551 case BACKSL|'7':
552 case BACKSL|'8':
553 case BACKSL|'9':
554 i = (c&~BACKSL) - '0';
555 assert(i < NPAREN);
556 if (p->pend[i] != 0) {
557 assert(i <= p->g->nsub);
558 EMIT(OBACK_, i);
559 assert(p->pbegin[i] != 0);
560 assert(OP(p->strip[p->pbegin[i]]) == OLPAREN);
561 assert(OP(p->strip[p->pend[i]]) == ORPAREN);
562 (void) dupl(p, p->pbegin[i]+1, p->pend[i]);
563 EMIT(O_BACK, i);
564 } else
565 SETERROR(REG_ESUBREG);
566 p->g->backrefs = 1;
567 break;
568 case '*':
569 REQUIRE(starordinary, REG_BADRPT);
570 /* FALLTHROUGH */
571 default:
572 ordinary(p, (char)c);
573 break;
574 }
575
576 if (EAT('*')) { /* implemented as +? */
577 /* this case does not require the (y|) trick, noKLUDGE */
578 INSERT(OPLUS_, pos);
579 ASTERN(O_PLUS, pos);
580 INSERT(OQUEST_, pos);
581 ASTERN(O_QUEST, pos);
582 } else if (EATTWO('\\', '{')) {
583 count = p_count(p);
584 if (EAT(',')) {
585 if (MORE() && isdigit((uch)PEEK())) {
586 count2 = p_count(p);
587 REQUIRE(count <= count2, REG_BADBR);
588 } else /* single number with comma */
589 count2 = INFINITY;
590 } else /* just a single number */
591 count2 = count;
592 repeat(p, pos, count, count2);
593 if (!EATTWO('\\', '}')) { /* error heuristics */
594 while (MORE() && !SEETWO('\\', '}'))
595 NEXT();
596 REQUIRE(MORE(), REG_EBRACE);
597 SETERROR(REG_BADBR);
598 }
599 } else if (c == '$') /* $ (but not \$) ends it */
600 return(1);
601
602 return(0);
603 }
604
605 /*
606 - p_count - parse a repetition count
607 */
608 static int /* the value */
p_count(struct parse * p)609 p_count(struct parse *p)
610 {
611 int count = 0;
612 int ndigits = 0;
613
614 while (MORE() && isdigit((uch)PEEK()) && count <= DUPMAX) {
615 count = count*10 + (GETNEXT() - '0');
616 ndigits++;
617 }
618
619 REQUIRE(ndigits > 0 && count <= DUPMAX, REG_BADBR);
620 return(count);
621 }
622
623 /*
624 - p_bracket - parse a bracketed character list
625 *
626 * Note a significant property of this code: if the allocset() did SETERROR,
627 * no set operations are done.
628 */
629 static void
p_bracket(struct parse * p)630 p_bracket(struct parse *p)
631 {
632 cset *cs;
633 int invert = 0;
634
635 /* Dept of Truly Sickening Special-Case Kludges */
636 if (p->next + 5 < p->end && strncmp(p->next, "[:<:]]", 6) == 0) {
637 EMIT(OBOW, 0);
638 NEXTn(6);
639 return;
640 }
641 if (p->next + 5 < p->end && strncmp(p->next, "[:>:]]", 6) == 0) {
642 EMIT(OEOW, 0);
643 NEXTn(6);
644 return;
645 }
646
647 cs = allocset(p);
648
649 if (EAT('^'))
650 invert++; /* make note to invert set at end */
651 if (EAT(']'))
652 CHadd(cs, ']');
653 else if (EAT('-'))
654 CHadd(cs, '-');
655 while (MORE() && PEEK() != ']' && !SEETWO('-', ']'))
656 p_b_term(p, cs);
657 if (EAT('-'))
658 CHadd(cs, '-');
659 MUSTEAT(']', REG_EBRACK);
660
661 if (p->error != 0) { /* don't mess things up further */
662 freeset(p, cs);
663 return;
664 }
665
666 if (p->g->cflags®_ICASE) {
667 int i;
668 int ci;
669
670 for (i = p->g->csetsize - 1; i >= 0; i--)
671 if (CHIN(cs, i) && isalpha(i)) {
672 ci = othercase(i);
673 if (ci != i)
674 CHadd(cs, ci);
675 }
676 if (cs->multis != NULL)
677 mccase(p, cs);
678 }
679 if (invert) {
680 int i;
681
682 for (i = p->g->csetsize - 1; i >= 0; i--)
683 if (CHIN(cs, i))
684 CHsub(cs, i);
685 else
686 CHadd(cs, i);
687 if (p->g->cflags®_NEWLINE)
688 CHsub(cs, '\n');
689 if (cs->multis != NULL)
690 mcinvert(p, cs);
691 }
692
693 assert(cs->multis == NULL); /* xxx */
694
695 if (nch(p, cs) == 1) { /* optimize singleton sets */
696 ordinary(p, firstch(p, cs));
697 freeset(p, cs);
698 } else
699 EMIT(OANYOF, freezeset(p, cs));
700 }
701
702 /*
703 - p_b_term - parse one term of a bracketed character list
704 */
705 static void
p_b_term(struct parse * p,cset * cs)706 p_b_term(struct parse *p, cset *cs)
707 {
708 char c;
709 char start, finish;
710 int i;
711
712 /* classify what we've got */
713 switch ((MORE()) ? PEEK() : '\0') {
714 case '[':
715 c = (MORE2()) ? PEEK2() : '\0';
716 break;
717 case '-':
718 SETERROR(REG_ERANGE);
719 return; /* NOTE RETURN */
720 break;
721 default:
722 c = '\0';
723 break;
724 }
725
726 switch (c) {
727 case ':': /* character class */
728 NEXT2();
729 REQUIRE(MORE(), REG_EBRACK);
730 c = PEEK();
731 REQUIRE(c != '-' && c != ']', REG_ECTYPE);
732 p_b_cclass(p, cs);
733 REQUIRE(MORE(), REG_EBRACK);
734 REQUIRE(EATTWO(':', ']'), REG_ECTYPE);
735 break;
736 case '=': /* equivalence class */
737 NEXT2();
738 REQUIRE(MORE(), REG_EBRACK);
739 c = PEEK();
740 REQUIRE(c != '-' && c != ']', REG_ECOLLATE);
741 p_b_eclass(p, cs);
742 REQUIRE(MORE(), REG_EBRACK);
743 REQUIRE(EATTWO('=', ']'), REG_ECOLLATE);
744 break;
745 default: /* symbol, ordinary character, or range */
746 /* xxx revision needed for multichar stuff */
747 start = p_b_symbol(p);
748 if (SEE('-') && MORE2() && PEEK2() != ']') {
749 /* range */
750 NEXT();
751 if (EAT('-'))
752 finish = '-';
753 else
754 finish = p_b_symbol(p);
755 } else
756 finish = start;
757 /* xxx what about signed chars here... */
758 REQUIRE(start <= finish, REG_ERANGE);
759 for (i = start; i <= finish; i++)
760 CHadd(cs, i);
761 break;
762 }
763 }
764
765 /*
766 - p_b_cclass - parse a character-class name and deal with it
767 */
768 static void
p_b_cclass(struct parse * p,cset * cs)769 p_b_cclass(struct parse *p, cset *cs)
770 {
771 const char *sp = p->next;
772 struct cclass *cp;
773 size_t len;
774 const char *u;
775 char c;
776
777 while (MORE() && isalpha(PEEK()))
778 NEXT();
779 len = p->next - sp;
780 for (cp = cclasses; cp->name != NULL; cp++)
781 if (strncmp(cp->name, sp, len) == 0 && cp->name[len] == '\0')
782 break;
783 if (cp->name == NULL) {
784 /* oops, didn't find it */
785 SETERROR(REG_ECTYPE);
786 return;
787 }
788
789 u = cp->chars;
790 while ((c = *u++) != '\0')
791 CHadd(cs, c);
792 for (u = cp->multis; *u != '\0'; u += strlen(u) + 1)
793 MCadd(p, cs, u);
794 }
795
796 /*
797 - p_b_eclass - parse an equivalence-class name and deal with it
798 *
799 * This implementation is incomplete. xxx
800 */
801 static void
p_b_eclass(struct parse * p,cset * cs)802 p_b_eclass(struct parse *p, cset *cs)
803 {
804 char c;
805
806 c = p_b_coll_elem(p, '=');
807 CHadd(cs, c);
808 }
809
810 /*
811 - p_b_symbol - parse a character or [..]ed multicharacter collating symbol
812 */
813 static char /* value of symbol */
p_b_symbol(struct parse * p)814 p_b_symbol(struct parse *p)
815 {
816 char value;
817
818 REQUIRE(MORE(), REG_EBRACK);
819 if (!EATTWO('[', '.'))
820 return(GETNEXT());
821
822 /* collating symbol */
823 value = p_b_coll_elem(p, '.');
824 REQUIRE(EATTWO('.', ']'), REG_ECOLLATE);
825 return(value);
826 }
827
828 /*
829 - p_b_coll_elem - parse a collating-element name and look it up
830 */
831 static char /* value of collating element */
p_b_coll_elem(struct parse * p,int endc)832 p_b_coll_elem(struct parse *p,
833 int endc) /* name ended by endc,']' */
834 {
835 const char *sp = p->next;
836 struct cname *cp;
837 int len;
838
839 while (MORE() && !SEETWO(endc, ']'))
840 NEXT();
841 if (!MORE()) {
842 SETERROR(REG_EBRACK);
843 return(0);
844 }
845 len = p->next - sp;
846 for (cp = cnames; cp->name != NULL; cp++)
847 if (strncmp(cp->name, sp, len) == 0 && cp->name[len] == '\0')
848 return(cp->code); /* known name */
849 if (len == 1)
850 return(*sp); /* single character */
851 SETERROR(REG_ECOLLATE); /* neither */
852 return(0);
853 }
854
855 /*
856 - othercase - return the case counterpart of an alphabetic
857 */
858 static char /* if no counterpart, return ch */
othercase(int ch)859 othercase(int ch)
860 {
861 ch = (uch)ch;
862 assert(isalpha(ch));
863 if (isupper(ch))
864 return(tolower(ch));
865 else if (islower(ch))
866 return(toupper(ch));
867 else /* peculiar, but could happen */
868 return(ch);
869 }
870
871 /*
872 - bothcases - emit a dualcase version of a two-case character
873 *
874 * Boy, is this implementation ever a kludge...
875 */
876 static void
bothcases(struct parse * p,int ch)877 bothcases(struct parse *p, int ch)
878 {
879 const char *oldnext = p->next;
880 const char *oldend = p->end;
881 char bracket[3];
882
883 ch = (uch)ch;
884 assert(othercase(ch) != ch); /* p_bracket() would recurse */
885 p->next = bracket;
886 p->end = bracket+2;
887 bracket[0] = ch;
888 bracket[1] = ']';
889 bracket[2] = '\0';
890 p_bracket(p);
891 assert(p->next == bracket+2);
892 p->next = oldnext;
893 p->end = oldend;
894 }
895
896 /*
897 - ordinary - emit an ordinary character
898 */
899 static void
ordinary(struct parse * p,int ch)900 ordinary(struct parse *p, int ch)
901 {
902 cat_t *cap = p->g->categories;
903
904 if ((p->g->cflags®_ICASE) && isalpha((uch)ch) && othercase(ch) != ch)
905 bothcases(p, ch);
906 else {
907 EMIT(OCHAR, (uch)ch);
908 if (cap[ch] == 0)
909 cap[ch] = p->g->ncategories++;
910 }
911 }
912
913 /*
914 - nonnewline - emit REG_NEWLINE version of OANY
915 *
916 * Boy, is this implementation ever a kludge...
917 */
918 static void
nonnewline(struct parse * p)919 nonnewline(struct parse *p)
920 {
921 const char *oldnext = p->next;
922 const char *oldend = p->end;
923 char bracket[4];
924
925 p->next = bracket;
926 p->end = bracket+3;
927 bracket[0] = '^';
928 bracket[1] = '\n';
929 bracket[2] = ']';
930 bracket[3] = '\0';
931 p_bracket(p);
932 assert(p->next == bracket+3);
933 p->next = oldnext;
934 p->end = oldend;
935 }
936
937 /*
938 - repeat - generate code for a bounded repetition, recursively if needed
939 */
940 static void
repeat(struct parse * p,sopno start,int from,int to)941 repeat(struct parse *p,
942 sopno start, /* operand from here to end of strip */
943 int from, /* repeated from this number */
944 int to) /* to this number of times (maybe INFINITY) */
945 {
946 sopno finish = HERE();
947 # define N 2
948 # define INF 3
949 # define REP(f, t) ((f)*8 + (t))
950 # define MAP(n) (((n) <= 1) ? (n) : ((n) == INFINITY) ? INF : N)
951 sopno copy;
952
953 if (p->error != 0) /* head off possible runaway recursion */
954 return;
955
956 assert(from <= to);
957
958 switch (REP(MAP(from), MAP(to))) {
959 case REP(0, 0): /* must be user doing this */
960 DROP(finish-start); /* drop the operand */
961 break;
962 case REP(0, 1): /* as x{1,1}? */
963 case REP(0, N): /* as x{1,n}? */
964 case REP(0, INF): /* as x{1,}? */
965 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
966 INSERT(OCH_, start); /* offset is wrong... */
967 repeat(p, start+1, 1, to);
968 ASTERN(OOR1, start);
969 AHEAD(start); /* ... fix it */
970 EMIT(OOR2, 0);
971 AHEAD(THERE());
972 ASTERN(O_CH, THERETHERE());
973 break;
974 case REP(1, 1): /* trivial case */
975 /* done */
976 break;
977 case REP(1, N): /* as x?x{1,n-1} */
978 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
979 INSERT(OCH_, start);
980 ASTERN(OOR1, start);
981 AHEAD(start);
982 EMIT(OOR2, 0); /* offset very wrong... */
983 AHEAD(THERE()); /* ...so fix it */
984 ASTERN(O_CH, THERETHERE());
985 copy = dupl(p, start+1, finish+1);
986 assert(copy == finish+4);
987 repeat(p, copy, 1, to-1);
988 break;
989 case REP(1, INF): /* as x+ */
990 INSERT(OPLUS_, start);
991 ASTERN(O_PLUS, start);
992 break;
993 case REP(N, N): /* as xx{m-1,n-1} */
994 copy = dupl(p, start, finish);
995 repeat(p, copy, from-1, to-1);
996 break;
997 case REP(N, INF): /* as xx{n-1,INF} */
998 copy = dupl(p, start, finish);
999 repeat(p, copy, from-1, to);
1000 break;
1001 default: /* "can't happen" */
1002 SETERROR(REG_ASSERT); /* just in case */
1003 break;
1004 }
1005 }
1006
1007 /*
1008 - seterr - set an error condition
1009 */
1010 static int /* useless but makes type checking happy */
seterr(struct parse * p,int e)1011 seterr(struct parse *p, int e)
1012 {
1013 if (p->error == 0) /* keep earliest error condition */
1014 p->error = e;
1015 p->next = nuls; /* try to bring things to a halt */
1016 p->end = nuls;
1017 return(0); /* make the return value well-defined */
1018 }
1019
1020 /*
1021 - allocset - allocate a set of characters for []
1022 */
1023 static cset *
allocset(struct parse * p)1024 allocset(struct parse *p)
1025 {
1026 int no = p->g->ncsets++;
1027 size_t nc;
1028 size_t nbytes;
1029 cset *cs;
1030 size_t css = (size_t)p->g->csetsize;
1031 int i;
1032
1033 if (no >= p->ncsalloc) { /* need another column of space */
1034 p->ncsalloc += CHAR_BIT;
1035 nc = p->ncsalloc;
1036 assert(nc % CHAR_BIT == 0);
1037 nbytes = nc / CHAR_BIT * css;
1038 if (p->g->sets == NULL)
1039 p->g->sets = (cset *)malloc(nc * sizeof(cset));
1040 else {
1041 cset *ptr;
1042 ptr = (cset *)realloc((char *)p->g->sets,
1043 nc * sizeof(cset));
1044 if (ptr == NULL) {
1045 free(p->g->sets);
1046 p->g->sets = NULL;
1047 } else
1048 p->g->sets = ptr;
1049 }
1050 if (p->g->sets == NULL)
1051 goto nomem;
1052
1053 if (p->g->setbits == NULL)
1054 p->g->setbits = (uch *)malloc(nbytes);
1055 else {
1056 uch *ptr;
1057
1058 ptr = (uch *)realloc((char *)p->g->setbits, nbytes);
1059 if (ptr == NULL) {
1060 free(p->g->setbits);
1061 p->g->setbits = NULL;
1062 } else {
1063 p->g->setbits = ptr;
1064
1065 for (i = 0; i < no; i++)
1066 p->g->sets[i].ptr = p->g->setbits +
1067 css*(i/CHAR_BIT);
1068 }
1069 }
1070
1071 if (p->g->sets == NULL || p->g->setbits == NULL) {
1072 nomem:
1073 no = 0;
1074 SETERROR(REG_ESPACE);
1075 /* caller's responsibility not to do set ops */
1076 } else
1077 (void) memset((char *)p->g->setbits + (nbytes - css),
1078 0, css);
1079 }
1080
1081 #if defined(NDEBUG) && defined(__OpenBSD__)
1082 #define re_assert(e) ((e) ? (void)0 : \
1083 __assert2(__FILE__, __LINE__, __func__, #e))
1084 #else
1085 #define re_assert(e) assert(e)
1086 #endif
1087 re_assert(p->g->sets != NULL); /* xxx */
1088 #undef re_assert
1089 cs = &p->g->sets[no];
1090 cs->ptr = p->g->setbits + css*((no)/CHAR_BIT);
1091 cs->mask = 1 << ((no) % CHAR_BIT);
1092 cs->hash = 0;
1093 cs->smultis = 0;
1094 cs->multis = NULL;
1095
1096 return(cs);
1097 }
1098
1099 /*
1100 - freeset - free a now-unused set
1101 */
1102 static void
freeset(struct parse * p,cset * cs)1103 freeset(struct parse *p, cset *cs)
1104 {
1105 size_t i;
1106 cset *top = &p->g->sets[p->g->ncsets];
1107 size_t css = (size_t)p->g->csetsize;
1108
1109 for (i = 0; i < css; i++)
1110 CHsub(cs, i);
1111 if (cs == top-1) /* recover only the easy case */
1112 p->g->ncsets--;
1113 }
1114
1115 /*
1116 - freezeset - final processing on a set of characters
1117 *
1118 * The main task here is merging identical sets. This is usually a waste
1119 * of time (although the hash code minimizes the overhead), but can win
1120 * big if REG_ICASE is being used. REG_ICASE, by the way, is why the hash
1121 * is done using addition rather than xor -- all ASCII [aA] sets xor to
1122 * the same value!
1123 */
1124 static int /* set number */
freezeset(struct parse * p,cset * cs)1125 freezeset(struct parse *p, cset *cs)
1126 {
1127 uch h = cs->hash;
1128 size_t i;
1129 cset *top = &p->g->sets[p->g->ncsets];
1130 cset *cs2;
1131 size_t css = (size_t)p->g->csetsize;
1132
1133 /* look for an earlier one which is the same */
1134 for (cs2 = &p->g->sets[0]; cs2 < top; cs2++)
1135 if (cs2->hash == h && cs2 != cs) {
1136 /* maybe */
1137 for (i = 0; i < css; i++)
1138 if (!!CHIN(cs2, i) != !!CHIN(cs, i))
1139 break; /* no */
1140 if (i == css)
1141 break; /* yes */
1142 }
1143
1144 if (cs2 < top) { /* found one */
1145 freeset(p, cs);
1146 cs = cs2;
1147 }
1148
1149 return((int)(cs - p->g->sets));
1150 }
1151
1152 /*
1153 - firstch - return first character in a set (which must have at least one)
1154 */
1155 static int /* character; there is no "none" value */
firstch(struct parse * p,cset * cs)1156 firstch(struct parse *p, cset *cs)
1157 {
1158 size_t i, css = (size_t)p->g->csetsize;
1159
1160 for (i = 0; i < css; i++)
1161 if (CHIN(cs, i))
1162 return((char)i);
1163 assert(never);
1164 return(0); /* arbitrary */
1165 }
1166
1167 /*
1168 - nch - number of characters in a set
1169 */
1170 static int
nch(struct parse * p,cset * cs)1171 nch(struct parse *p, cset *cs)
1172 {
1173 size_t i, css = (size_t)p->g->csetsize;
1174 int n = 0;
1175
1176 for (i = 0; i < css; i++)
1177 if (CHIN(cs, i))
1178 n++;
1179 return(n);
1180 }
1181
1182 /*
1183 - mcadd - add a collating element to a cset
1184 */
1185 static void
mcadd(struct parse * p,cset * cs,const char * cp)1186 mcadd(struct parse *p, cset *cs, const char *cp)
1187 {
1188 size_t oldend = cs->smultis;
1189 void *np;
1190
1191 cs->smultis += strlen(cp) + 1;
1192 if (cs->multis == NULL)
1193 np = malloc(cs->smultis);
1194 else
1195 np = realloc(cs->multis, cs->smultis);
1196 if (np == NULL) {
1197 if (cs->multis)
1198 free(cs->multis);
1199 cs->multis = NULL;
1200 SETERROR(REG_ESPACE);
1201 return;
1202 }
1203 cs->multis = np;
1204
1205 strlcpy(cs->multis + oldend - 1, cp, cs->smultis - oldend + 1);
1206 }
1207
1208 /*
1209 - mcinvert - invert the list of collating elements in a cset
1210 *
1211 * This would have to know the set of possibilities. Implementation
1212 * is deferred.
1213 */
1214 /* ARGSUSED */
1215 static void
mcinvert(struct parse * p,cset * cs)1216 mcinvert(struct parse *p __attribute__((__unused__)),
1217 cset *cs __attribute__((__unused__)))
1218 {
1219 assert(cs->multis == NULL); /* xxx */
1220 }
1221
1222 /*
1223 - mccase - add case counterparts of the list of collating elements in a cset
1224 *
1225 * This would have to know the set of possibilities. Implementation
1226 * is deferred.
1227 */
1228 /* ARGSUSED */
1229 static void
mccase(struct parse * p,cset * cs)1230 mccase(struct parse *p __attribute__((__unused__)),
1231 cset *cs __attribute__((__unused__)))
1232 {
1233 assert(cs->multis == NULL); /* xxx */
1234 }
1235
1236 /*
1237 - isinsets - is this character in any sets?
1238 */
1239 static int /* predicate */
isinsets(struct re_guts * g,int c)1240 isinsets(struct re_guts *g, int c)
1241 {
1242 uch *col;
1243 int i;
1244 int ncols = (g->ncsets+(CHAR_BIT-1)) / CHAR_BIT;
1245 unsigned uc = (uch)c;
1246
1247 for (i = 0, col = g->setbits; i < ncols; i++, col += g->csetsize)
1248 if (col[uc] != 0)
1249 return(1);
1250 return(0);
1251 }
1252
1253 /*
1254 - samesets - are these two characters in exactly the same sets?
1255 */
1256 static int /* predicate */
samesets(struct re_guts * g,int c1,int c2)1257 samesets(struct re_guts *g, int c1, int c2)
1258 {
1259 uch *col;
1260 int i;
1261 int ncols = (g->ncsets+(CHAR_BIT-1)) / CHAR_BIT;
1262 unsigned uc1 = (uch)c1;
1263 unsigned uc2 = (uch)c2;
1264
1265 for (i = 0, col = g->setbits; i < ncols; i++, col += g->csetsize)
1266 if (col[uc1] != col[uc2])
1267 return(0);
1268 return(1);
1269 }
1270
1271 /*
1272 - categorize - sort out character categories
1273 */
1274 static void
categorize(struct parse * p,struct re_guts * g)1275 categorize(struct parse *p, struct re_guts *g)
1276 {
1277 cat_t *cats = g->categories;
1278 int c;
1279 int c2;
1280 cat_t cat;
1281
1282 /* avoid making error situations worse */
1283 if (p->error != 0)
1284 return;
1285
1286 for (c = CHAR_MIN; c <= CHAR_MAX; c++)
1287 if (cats[c] == 0 && isinsets(g, c)) {
1288 cat = g->ncategories++;
1289 cats[c] = cat;
1290 for (c2 = c+1; c2 <= CHAR_MAX; c2++)
1291 if (cats[c2] == 0 && samesets(g, c, c2))
1292 cats[c2] = cat;
1293 }
1294 }
1295
1296 /*
1297 - dupl - emit a duplicate of a bunch of sops
1298 */
1299 static sopno /* start of duplicate */
dupl(struct parse * p,sopno start,sopno finish)1300 dupl(struct parse *p,
1301 sopno start, /* from here */
1302 sopno finish) /* to this less one */
1303 {
1304 sopno ret = HERE();
1305 sopno len = finish - start;
1306
1307 assert(finish >= start);
1308 if (len == 0)
1309 return(ret);
1310 enlarge(p, p->ssize + len); /* this many unexpected additions */
1311 assert(p->ssize >= p->slen + len);
1312 (void) memcpy((char *)(p->strip + p->slen),
1313 (char *)(p->strip + start), (size_t)len*sizeof(sop));
1314 p->slen += len;
1315 return(ret);
1316 }
1317
1318 /*
1319 - doemit - emit a strip operator
1320 *
1321 * It might seem better to implement this as a macro with a function as
1322 * hard-case backup, but it's just too big and messy unless there are
1323 * some changes to the data structures. Maybe later.
1324 */
1325 static void
doemit(struct parse * p,sop op,size_t opnd)1326 doemit(struct parse *p, sop op, size_t opnd)
1327 {
1328 /* avoid making error situations worse */
1329 if (p->error != 0)
1330 return;
1331
1332 /* deal with oversize operands ("can't happen", more or less) */
1333 assert(opnd < 1<<OPSHIFT);
1334
1335 /* deal with undersized strip */
1336 if (p->slen >= p->ssize)
1337 enlarge(p, (p->ssize+1) / 2 * 3); /* +50% */
1338 assert(p->slen < p->ssize);
1339
1340 /* finally, it's all reduced to the easy case */
1341 p->strip[p->slen++] = SOP(op, opnd);
1342 }
1343
1344 /*
1345 - doinsert - insert a sop into the strip
1346 */
1347 static void
doinsert(struct parse * p,sop op,size_t opnd,sopno pos)1348 doinsert(struct parse *p, sop op, size_t opnd, sopno pos)
1349 {
1350 sopno sn;
1351 sop s;
1352 int i;
1353
1354 /* avoid making error situations worse */
1355 if (p->error != 0)
1356 return;
1357
1358 sn = HERE();
1359 EMIT(op, opnd); /* do checks, ensure space */
1360 assert(HERE() == sn+1);
1361 s = p->strip[sn];
1362
1363 /* adjust paren pointers */
1364 assert(pos > 0);
1365 for (i = 1; i < NPAREN; i++) {
1366 if (p->pbegin[i] >= pos) {
1367 p->pbegin[i]++;
1368 }
1369 if (p->pend[i] >= pos) {
1370 p->pend[i]++;
1371 }
1372 }
1373
1374 memmove((char *)&p->strip[pos+1], (char *)&p->strip[pos],
1375 (HERE()-pos-1)*sizeof(sop));
1376 p->strip[pos] = s;
1377 }
1378
1379 /*
1380 - dofwd - complete a forward reference
1381 */
1382 static void
dofwd(struct parse * p,sopno pos,sop value)1383 dofwd(struct parse *p, sopno pos, sop value)
1384 {
1385 /* avoid making error situations worse */
1386 if (p->error != 0)
1387 return;
1388
1389 assert(value < 1<<OPSHIFT);
1390 p->strip[pos] = OP(p->strip[pos]) | value;
1391 }
1392
1393 /*
1394 - enlarge - enlarge the strip
1395 */
1396 static void
enlarge(struct parse * p,sopno size)1397 enlarge(struct parse *p, sopno size)
1398 {
1399 sop *sp;
1400
1401 if (p->ssize >= size)
1402 return;
1403
1404 sp = (sop *)realloc(p->strip, size*sizeof(sop));
1405 if (sp == NULL) {
1406 SETERROR(REG_ESPACE);
1407 return;
1408 }
1409 p->strip = sp;
1410 p->ssize = size;
1411 }
1412
1413 /*
1414 - stripsnug - compact the strip
1415 */
1416 static void
stripsnug(struct parse * p,struct re_guts * g)1417 stripsnug(struct parse *p, struct re_guts *g)
1418 {
1419 g->nstates = p->slen;
1420 g->strip = (sop *)realloc((char *)p->strip, p->slen * sizeof(sop));
1421 if (g->strip == NULL) {
1422 SETERROR(REG_ESPACE);
1423 g->strip = p->strip;
1424 }
1425 }
1426
1427 /*
1428 - findmust - fill in must and mlen with longest mandatory literal string
1429 *
1430 * This algorithm could do fancy things like analyzing the operands of |
1431 * for common subsequences. Someday. This code is simple and finds most
1432 * of the interesting cases.
1433 *
1434 * Note that must and mlen got initialized during setup.
1435 */
1436 static void
findmust(struct parse * p,struct re_guts * g)1437 findmust(struct parse *p, struct re_guts *g)
1438 {
1439 sop *scan;
1440 sop *start = NULL;
1441 sop *newstart = NULL;
1442 sopno newlen = 0;
1443 sop s;
1444 char *cp;
1445 sopno i;
1446
1447 /* avoid making error situations worse */
1448 if (p->error != 0)
1449 return;
1450
1451 /* find the longest OCHAR sequence in strip */
1452 scan = g->strip + 1;
1453 do {
1454 s = *scan++;
1455 switch (OP(s)) {
1456 case OCHAR: /* sequence member */
1457 if (newlen == 0) /* new sequence */
1458 newstart = scan - 1;
1459 newlen++;
1460 break;
1461 case OPLUS_: /* things that don't break one */
1462 case OLPAREN:
1463 case ORPAREN:
1464 break;
1465 case OQUEST_: /* things that must be skipped */
1466 case OCH_:
1467 scan--;
1468 do {
1469 scan += OPND(s);
1470 s = *scan;
1471 /* assert() interferes w debug printouts */
1472 if (OP(s) != O_QUEST && OP(s) != O_CH &&
1473 OP(s) != OOR2) {
1474 g->iflags |= BAD;
1475 return;
1476 }
1477 } while (OP(s) != O_QUEST && OP(s) != O_CH);
1478 /* fallthrough */
1479 default: /* things that break a sequence */
1480 if (newlen > g->mlen) { /* ends one */
1481 start = newstart;
1482 g->mlen = newlen;
1483 }
1484 newlen = 0;
1485 break;
1486 }
1487 } while (OP(s) != OEND);
1488
1489 if (start == NULL) /* just in case */
1490 g->mlen = 0;
1491 if (g->mlen == 0) /* there isn't one */
1492 return;
1493
1494 /* turn it into a character string */
1495 g->must = malloc((size_t)g->mlen + 1);
1496 if (g->must == NULL) { /* argh; just forget it */
1497 g->mlen = 0;
1498 return;
1499 }
1500 cp = g->must;
1501 scan = start;
1502 for (i = g->mlen; i > 0; i--) {
1503 while (OP(s = *scan++) != OCHAR)
1504 continue;
1505 assert(cp < g->must + g->mlen);
1506 *cp++ = (char)OPND(s);
1507 }
1508 assert(cp == g->must + g->mlen);
1509 *cp++ = '\0'; /* just on general principles */
1510 }
1511
1512 /*
1513 - pluscount - count + nesting
1514 */
1515 static sopno /* nesting depth */
pluscount(struct parse * p,struct re_guts * g)1516 pluscount(struct parse *p, struct re_guts *g)
1517 {
1518 sop *scan;
1519 sop s;
1520 sopno plusnest = 0;
1521 sopno maxnest = 0;
1522
1523 if (p->error != 0)
1524 return(0); /* there may not be an OEND */
1525
1526 scan = g->strip + 1;
1527 do {
1528 s = *scan++;
1529 switch (OP(s)) {
1530 case OPLUS_:
1531 plusnest++;
1532 break;
1533 case O_PLUS:
1534 if (plusnest > maxnest)
1535 maxnest = plusnest;
1536 plusnest--;
1537 break;
1538 }
1539 } while (OP(s) != OEND);
1540 if (plusnest != 0)
1541 g->iflags |= BAD;
1542 return(maxnest);
1543 }
1544