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