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