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