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