compiler/clib/regex: Switched to NetBSD version of the regex functions.
[AROS.git] / compiler / clib / regex / regcomp.c
blob85d4f29ee9f7b2df68b2febb30f6b29b725c0794
1 /* $NetBSD: regcomp.c,v 1.28 2007/02/09 23:44:18 junyoung Exp $ */
3 /*-
4 * Copyright (c) 1992, 1993, 1994
5 * The Regents of the University of California. All rights reserved.
7 * This code is derived from software contributed to Berkeley by
8 * Henry Spencer.
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.
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.
34 * @(#)regcomp.c 8.5 (Berkeley) 3/20/94
37 /*-
38 * Copyright (c) 1992, 1993, 1994 Henry Spencer.
40 * This code is derived from software contributed to Berkeley by
41 * Henry Spencer.
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.
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.
71 * @(#)regcomp.c 8.5 (Berkeley) 3/20/94
75 __RCSID("$NetBSD: regcomp.c,v 1.28 2007/02/09 23:44:18 junyoung Exp $");
78 #if defined(__AROS__)
79 #if !DEBUG
80 #define NDEBUG
81 #else
82 #define REDEBUG
83 #endif
84 #endif
86 #include <sys/types.h>
88 #include <assert.h>
89 #include <ctype.h>
90 #include <limits.h>
91 #include <stdio.h>
92 #include <stdlib.h>
93 #include <string.h>
94 #include <regex.h>
96 #ifdef __weak_alias
97 __weak_alias(regcomp,_regcomp)
98 #endif
100 #include "utils.h"
101 #include "regex2.h"
103 #include "cclass.h"
104 #include "cname.h"
107 * parse structure, passed up and down to avoid global variables and
108 * other clumsinesses
110 struct parse {
111 const char *next; /* next character in RE */
112 const char *end; /* end of string (-> NUL normally) */
113 int error; /* has an error been seen? */
114 sop *strip; /* malloced strip */
115 sopno ssize; /* malloced strip size (allocated) */
116 sopno slen; /* malloced strip length (used) */
117 int ncsalloc; /* number of csets allocated */
118 struct re_guts *g;
119 # define NPAREN 10 /* we need to remember () 1-9 for back refs */
120 sopno pbegin[NPAREN]; /* -> ( ([0] unused) */
121 sopno pend[NPAREN]; /* -> ) ([0] unused) */
124 /* ========= begin header generated by ./mkh ========= */
125 #ifdef __cplusplus
126 extern "C" {
127 #endif
129 /* === regcomp.c === */
130 static void p_ere(struct parse *p, int stop);
131 static void p_ere_exp(struct parse *p);
132 static void p_str(struct parse *p);
133 static void p_bre(struct parse *p, int end1, int end2);
134 static int p_simp_re(struct parse *p, int starordinary);
135 static int p_count(struct parse *p);
136 static void p_bracket(struct parse *p);
137 static void p_b_term(struct parse *p, cset *cs);
138 static void p_b_cclass(struct parse *p, cset *cs);
139 static void p_b_eclass(struct parse *p, cset *cs);
140 static char p_b_symbol(struct parse *p);
141 static char p_b_coll_elem(struct parse *p, int endc);
142 static int othercase(int ch);
143 static void bothcases(struct parse *p, int ch);
144 static void ordinary(struct parse *p, int ch);
145 static void nonnewline(struct parse *p);
146 static void repeat(struct parse *p, sopno start, int from, int to);
147 static int seterr(struct parse *p, int e);
148 static cset *allocset(struct parse *p);
149 static void freeset(struct parse *p, cset *cs);
150 static int freezeset(struct parse *p, cset *cs);
151 static int firstch(struct parse *p, cset *cs);
152 static int nch(struct parse *p, cset *cs);
153 static void mcadd(struct parse *p, cset *cs, const char *cp);
154 #if 0
155 static void mcsub(cset *cs, char *cp);
156 static int mcin(cset *cs, char *cp);
157 static char *mcfind(cset *cs, char *cp);
158 #endif
159 static void mcinvert(struct parse *p, cset *cs);
160 static void mccase(struct parse *p, cset *cs);
161 static int isinsets(struct re_guts *g, int c);
162 static int samesets(struct re_guts *g, int c1, int c2);
163 static void categorize(struct parse *p, struct re_guts *g);
164 static sopno dupl(struct parse *p, sopno start, sopno finish);
165 static void doemit(struct parse *p, sop op, sopno opnd);
166 static void doinsert(struct parse *p, sop op, sopno opnd, sopno pos);
167 static void dofwd(struct parse *p, sopno pos, sopno value);
168 static void enlarge(struct parse *p, sopno size);
169 static void stripsnug(struct parse *p, struct re_guts *g);
170 static void findmust(struct parse *p, struct re_guts *g);
171 static sopno pluscount(struct parse *p, struct re_guts *g);
173 #ifdef __cplusplus
175 #endif
176 /* ========= end header generated by ./mkh ========= */
178 static char nuls[10]; /* place to point scanner in event of error */
181 * macros for use with parse structure
182 * BEWARE: these know that the parse structure is named `p' !!!
184 #define PEEK() (*p->next)
185 #define PEEK2() (*(p->next+1))
186 #define MORE() (p->next < p->end)
187 #define MORE2() (p->next+1 < p->end)
188 #define SEE(c) (MORE() && PEEK() == (c))
189 #define SEETWO(a, b) (MORE() && MORE2() && PEEK() == (a) && PEEK2() == (b))
190 #define EAT(c) ((SEE(c)) ? (NEXT(), 1) : 0)
191 #define EATTWO(a, b) ((SEETWO(a, b)) ? (NEXT2(), 1) : 0)
192 #define NEXT() (p->next++)
193 #define NEXT2() (p->next += 2)
194 #define NEXTn(n) (p->next += (n))
195 #define GETNEXT() (*p->next++)
196 #define SETERROR(e) seterr(p, (e))
197 #define REQUIRE(co, e) (void) ((co) || SETERROR(e))
198 #define MUSTSEE(c, e) (REQUIRE(MORE() && PEEK() == (c), e))
199 #define MUSTEAT(c, e) (void) (REQUIRE(MORE() && GETNEXT() == (c), e))
200 #define MUSTNOTSEE(c, e) (REQUIRE(!MORE() || PEEK() != (c), e))
201 #define EMIT(op, sopnd) doemit(p, (sop)(op), sopnd)
202 #define INSERT(op, pos) doinsert(p, (sop)(op), HERE()-(pos)+1, pos)
203 #define AHEAD(pos) dofwd(p, pos, HERE()-(pos))
204 #define ASTERN(sop, pos) EMIT(sop, HERE()-pos)
205 #define HERE() (p->slen)
206 #define THERE() (p->slen - 1)
207 #define THERETHERE() (p->slen - 2)
208 #define DROP(n) (p->slen -= (n))
210 #ifndef NDEBUG
211 static int never = 0; /* for use in asserts; shuts lint up */
212 #else
213 #define never 0 /* some <assert.h>s have bugs too */
214 #endif
217 - regcomp - interface for parser and compilation
218 = extern int regcomp(regex_t *, const char *, int);
219 = #define REG_BASIC 0000
220 = #define REG_EXTENDED 0001
221 = #define REG_ICASE 0002
222 = #define REG_NOSUB 0004
223 = #define REG_NEWLINE 0010
224 = #define REG_NOSPEC 0020
225 = #define REG_PEND 0040
226 = #define REG_DUMP 0200
228 int /* 0 success, otherwise REG_something */
229 regcomp(
230 regex_t *preg,
231 const char *pattern,
232 int cflags)
234 struct parse pa;
235 struct re_guts *g;
236 struct parse *p = &pa;
237 int i;
238 size_t len;
239 #ifdef REDEBUG
240 # define GOODFLAGS(f) (f)
241 #else
242 # define GOODFLAGS(f) ((f)&~REG_DUMP)
243 #endif
245 assert(preg != NULL);
246 assert(pattern != NULL);
248 cflags = GOODFLAGS(cflags);
249 if ((cflags&REG_EXTENDED) && (cflags&REG_NOSPEC))
250 return(REG_INVARG);
252 if (cflags&REG_PEND) {
253 if (preg->re_endp < pattern)
254 return(REG_INVARG);
255 len = preg->re_endp - pattern;
256 } else
257 len = strlen(pattern);
259 /* do the mallocs early so failure handling is easy */
260 g = (struct re_guts *)malloc(sizeof(struct re_guts) +
261 (NC-1)*sizeof(cat_t));
262 if (g == NULL)
263 return(REG_ESPACE);
264 p->ssize = len/(size_t)2*(size_t)3 + (size_t)1; /* ugh */
265 p->strip = (sop *)malloc(p->ssize * sizeof(sop));
266 p->slen = 0;
267 if (p->strip == NULL) {
268 free(g);
269 return(REG_ESPACE);
272 /* set things up */
273 p->g = g;
274 p->next = pattern;
275 p->end = p->next + len;
276 p->error = 0;
277 p->ncsalloc = 0;
278 for (i = 0; i < NPAREN; i++) {
279 p->pbegin[i] = 0;
280 p->pend[i] = 0;
282 g->csetsize = NC;
283 g->sets = NULL;
284 g->setbits = NULL;
285 g->ncsets = 0;
286 g->cflags = cflags;
287 g->iflags = 0;
288 g->nbol = 0;
289 g->neol = 0;
290 g->must = NULL;
291 g->mlen = 0;
292 g->nsub = 0;
293 g->ncategories = 1; /* category 0 is "everything else" */
294 g->categories = &g->catspace[-(CHAR_MIN)];
295 (void) memset((char *)g->catspace, 0, NC*sizeof(cat_t));
296 g->backrefs = 0;
298 /* do it */
299 EMIT(OEND, 0);
300 g->firststate = THERE();
301 if (cflags&REG_EXTENDED)
302 p_ere(p, OUT);
303 else if (cflags&REG_NOSPEC)
304 p_str(p);
305 else
306 p_bre(p, OUT, OUT);
307 EMIT(OEND, 0);
308 g->laststate = THERE();
310 /* tidy up loose ends and fill things in */
311 categorize(p, g);
312 stripsnug(p, g);
313 findmust(p, g);
314 g->nplus = pluscount(p, g);
315 g->magic = MAGIC2;
316 preg->re_nsub = g->nsub;
317 preg->re_g = g;
318 preg->re_magic = MAGIC1;
319 #ifndef REDEBUG
320 /* not debugging, so can't rely on the assert() in regexec() */
321 if (g->iflags&BAD)
322 SETERROR(REG_ASSERT);
323 #endif
325 /* win or lose, we're done */
326 if (p->error != 0) /* lose */
327 regfree(preg);
328 return(p->error);
332 - p_ere - ERE parser top level, concatenation and alternation
333 == static void p_ere(struct parse *p, int stop);
335 static void
336 p_ere(
337 struct parse *p,
338 int stop) /* character this ERE should end at */
340 char c;
341 sopno prevback = 0; /* pacify gcc */
342 sopno prevfwd = 0; /* pacify gcc */
343 sopno conc;
344 int first = 1; /* is this the first alternative? */
346 assert(p != NULL);
348 for (;;) {
349 /* do a bunch of concatenated expressions */
350 conc = HERE();
351 while (MORE() && (c = PEEK()) != '|' && c != stop)
352 p_ere_exp(p);
353 REQUIRE(HERE() != conc, REG_EMPTY); /* require nonempty */
355 if (!EAT('|'))
356 break; /* NOTE BREAK OUT */
358 if (first) {
359 INSERT(OCH_, conc); /* offset is wrong */
360 prevfwd = conc;
361 prevback = conc;
362 first = 0;
364 ASTERN(OOR1, prevback);
365 prevback = THERE();
366 AHEAD(prevfwd); /* fix previous offset */
367 prevfwd = HERE();
368 EMIT(OOR2, 0); /* offset is very wrong */
371 if (!first) { /* tail-end fixups */
372 AHEAD(prevfwd);
373 ASTERN(O_CH, prevback);
376 assert(!MORE() || SEE(stop));
380 - p_ere_exp - parse one subERE, an atom possibly followed by a repetition op
381 == static void p_ere_exp(struct parse *p);
383 static void
384 p_ere_exp(
385 struct parse *p)
387 char c;
388 sopno pos;
389 int count;
390 int count2;
391 sopno subno;
392 int wascaret = 0;
394 assert(p != NULL);
396 assert(MORE()); /* caller should have ensured this */
397 c = GETNEXT();
399 pos = HERE();
400 switch (c) {
401 case '(':
402 REQUIRE(MORE(), REG_EPAREN);
403 p->g->nsub++;
404 subno = p->g->nsub;
405 if (subno < NPAREN)
406 p->pbegin[subno] = HERE();
407 EMIT(OLPAREN, subno);
408 if (!SEE(')'))
409 p_ere(p, ')');
410 if (subno < NPAREN) {
411 p->pend[subno] = HERE();
412 assert(p->pend[subno] != 0);
414 EMIT(ORPAREN, subno);
415 MUSTEAT(')', REG_EPAREN);
416 break;
417 #ifndef POSIX_MISTAKE
418 case ')': /* happens only if no current unmatched ( */
420 * You may ask, why the ifndef? Because I didn't notice
421 * this until slightly too late for 1003.2, and none of the
422 * other 1003.2 regular-expression reviewers noticed it at
423 * all. So an unmatched ) is legal POSIX, at least until
424 * we can get it fixed.
426 SETERROR(REG_EPAREN);
427 break;
428 #endif
429 case '^':
430 EMIT(OBOL, 0);
431 p->g->iflags |= USEBOL;
432 p->g->nbol++;
433 wascaret = 1;
434 break;
435 case '$':
436 EMIT(OEOL, 0);
437 p->g->iflags |= USEEOL;
438 p->g->neol++;
439 break;
440 case '|':
441 SETERROR(REG_EMPTY);
442 break;
443 case '*':
444 case '+':
445 case '?':
446 SETERROR(REG_BADRPT);
447 break;
448 case '.':
449 if (p->g->cflags&REG_NEWLINE)
450 nonnewline(p);
451 else
452 EMIT(OANY, 0);
453 break;
454 case '[':
455 p_bracket(p);
456 break;
457 case '\\':
458 REQUIRE(MORE(), REG_EESCAPE);
459 c = GETNEXT();
460 ordinary(p, c);
461 break;
462 case '{': /* okay as ordinary except if digit follows */
463 REQUIRE(!MORE() || !isdigit((unsigned char)PEEK()), REG_BADRPT);
464 /* FALLTHROUGH */
465 default:
466 ordinary(p, c);
467 break;
470 if (!MORE())
471 return;
472 c = PEEK();
473 /* we call { a repetition if followed by a digit */
474 if (!( c == '*' || c == '+' || c == '?' ||
475 (c == '{' && MORE2() && isdigit((unsigned char)PEEK2())) ))
476 return; /* no repetition, we're done */
477 NEXT();
479 REQUIRE(!wascaret, REG_BADRPT);
480 switch (c) {
481 case '*': /* implemented as +? */
482 /* this case does not require the (y|) trick, noKLUDGE */
483 INSERT(OPLUS_, pos);
484 ASTERN(O_PLUS, pos);
485 INSERT(OQUEST_, pos);
486 ASTERN(O_QUEST, pos);
487 break;
488 case '+':
489 INSERT(OPLUS_, pos);
490 ASTERN(O_PLUS, pos);
491 break;
492 case '?':
493 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
494 INSERT(OCH_, pos); /* offset slightly wrong */
495 ASTERN(OOR1, pos); /* this one's right */
496 AHEAD(pos); /* fix the OCH_ */
497 EMIT(OOR2, 0); /* offset very wrong... */
498 AHEAD(THERE()); /* ...so fix it */
499 ASTERN(O_CH, THERETHERE());
500 break;
501 case '{':
502 count = p_count(p);
503 if (EAT(',')) {
504 if (isdigit((unsigned char)PEEK())) {
505 count2 = p_count(p);
506 REQUIRE(count <= count2, REG_BADBR);
507 } else /* single number with comma */
508 count2 = INFINITY;
509 } else /* just a single number */
510 count2 = count;
511 repeat(p, pos, count, count2);
512 if (!EAT('}')) { /* error heuristics */
513 while (MORE() && PEEK() != '}')
514 NEXT();
515 REQUIRE(MORE(), REG_EBRACE);
516 SETERROR(REG_BADBR);
518 break;
521 if (!MORE())
522 return;
523 c = PEEK();
524 if (!( c == '*' || c == '+' || c == '?' ||
525 (c == '{' && MORE2() && isdigit((unsigned char)PEEK2())) ) )
526 return;
527 SETERROR(REG_BADRPT);
531 - p_str - string (no metacharacters) "parser"
532 == static void p_str(struct parse *p);
534 static void
535 p_str(
536 struct parse *p)
539 assert(p != NULL);
541 REQUIRE(MORE(), REG_EMPTY);
542 while (MORE())
543 ordinary(p, GETNEXT());
547 - p_bre - BRE parser top level, anchoring and concatenation
548 == static void p_bre(struct parse *p, int end1, \
549 == int end2);
550 * Giving end1 as OUT essentially eliminates the end1/end2 check.
552 * This implementation is a bit of a kludge, in that a trailing $ is first
553 * taken as an ordinary character and then revised to be an anchor. The
554 * only undesirable side effect is that '$' gets included as a character
555 * category in such cases. This is fairly harmless; not worth fixing.
556 * The amount of lookahead needed to avoid this kludge is excessive.
558 static void
559 p_bre(
560 struct parse *p,
561 int end1, /* first terminating character */
562 int end2) /* second terminating character */
564 sopno start;
565 int first = 1; /* first subexpression? */
566 int wasdollar = 0;
568 assert(p != NULL);
570 start = HERE();
572 if (EAT('^')) {
573 EMIT(OBOL, 0);
574 p->g->iflags |= USEBOL;
575 p->g->nbol++;
577 while (MORE() && !SEETWO(end1, end2)) {
578 wasdollar = p_simp_re(p, first);
579 first = 0;
581 if (wasdollar) { /* oops, that was a trailing anchor */
582 DROP(1);
583 EMIT(OEOL, 0);
584 p->g->iflags |= USEEOL;
585 p->g->neol++;
588 REQUIRE(HERE() != start, REG_EMPTY); /* require nonempty */
592 - p_simp_re - parse a simple RE, an atom possibly followed by a repetition
593 == static int p_simp_re(struct parse *p, int starordinary);
595 static int /* was the simple RE an unbackslashed $? */
596 p_simp_re(
597 struct parse *p,
598 int starordinary) /* is a leading * an ordinary character? */
600 int c;
601 int count;
602 int count2;
603 sopno pos;
604 int i;
605 sopno subno;
606 # define BACKSL (1<<CHAR_BIT)
608 assert(p != NULL);
610 pos = HERE(); /* repetion op, if any, covers from here */
612 assert(MORE()); /* caller should have ensured this */
613 c = GETNEXT();
614 if (c == '\\') {
615 REQUIRE(MORE(), REG_EESCAPE);
616 c = BACKSL | (unsigned char)GETNEXT();
618 switch (c) {
619 case '.':
620 if (p->g->cflags&REG_NEWLINE)
621 nonnewline(p);
622 else
623 EMIT(OANY, 0);
624 break;
625 case '[':
626 p_bracket(p);
627 break;
628 case BACKSL|'{':
629 SETERROR(REG_BADRPT);
630 break;
631 case BACKSL|'(':
632 p->g->nsub++;
633 subno = p->g->nsub;
634 if (subno < NPAREN)
635 p->pbegin[subno] = HERE();
636 EMIT(OLPAREN, subno);
637 /* the MORE here is an error heuristic */
638 if (MORE() && !SEETWO('\\', ')'))
639 p_bre(p, '\\', ')');
640 if (subno < NPAREN) {
641 p->pend[subno] = HERE();
642 assert(p->pend[subno] != 0);
644 EMIT(ORPAREN, subno);
645 REQUIRE(EATTWO('\\', ')'), REG_EPAREN);
646 break;
647 case BACKSL|')': /* should not get here -- must be user */
648 case BACKSL|'}':
649 SETERROR(REG_EPAREN);
650 break;
651 case BACKSL|'1':
652 case BACKSL|'2':
653 case BACKSL|'3':
654 case BACKSL|'4':
655 case BACKSL|'5':
656 case BACKSL|'6':
657 case BACKSL|'7':
658 case BACKSL|'8':
659 case BACKSL|'9':
660 i = (c&~BACKSL) - '0';
661 assert(i < NPAREN);
662 if (p->pend[i] != 0) {
663 assert(i <= p->g->nsub);
664 EMIT(OBACK_, i);
665 assert(p->pbegin[i] != 0);
666 assert(OP(p->strip[p->pbegin[i]]) == OLPAREN);
667 assert(OP(p->strip[p->pend[i]]) == ORPAREN);
668 (void) dupl(p, p->pbegin[i]+1, p->pend[i]);
669 EMIT(O_BACK, i);
670 } else
671 SETERROR(REG_ESUBREG);
672 p->g->backrefs = 1;
673 break;
674 case '*':
675 REQUIRE(starordinary, REG_BADRPT);
676 /* FALLTHROUGH */
677 default:
678 ordinary(p, c &~ BACKSL);
679 break;
682 if (EAT('*')) { /* implemented as +? */
683 /* this case does not require the (y|) trick, noKLUDGE */
684 INSERT(OPLUS_, pos);
685 ASTERN(O_PLUS, pos);
686 INSERT(OQUEST_, pos);
687 ASTERN(O_QUEST, pos);
688 } else if (EATTWO('\\', '{')) {
689 count = p_count(p);
690 if (EAT(',')) {
691 if (MORE() && isdigit((unsigned char)PEEK())) {
692 count2 = p_count(p);
693 REQUIRE(count <= count2, REG_BADBR);
694 } else /* single number with comma */
695 count2 = INFINITY;
696 } else /* just a single number */
697 count2 = count;
698 repeat(p, pos, count, count2);
699 if (!EATTWO('\\', '}')) { /* error heuristics */
700 while (MORE() && !SEETWO('\\', '}'))
701 NEXT();
702 REQUIRE(MORE(), REG_EBRACE);
703 SETERROR(REG_BADBR);
705 } else if (c == (unsigned char)'$') /* $ (but not \$) ends it */
706 return(1);
708 return(0);
712 - p_count - parse a repetition count
713 == static int p_count(struct parse *p);
715 static int /* the value */
716 p_count(
717 struct parse *p)
719 int count = 0;
720 int ndigits = 0;
722 assert(p != NULL);
724 while (MORE() && isdigit((unsigned char)PEEK()) && count <= DUPMAX) {
725 count = count*10 + (GETNEXT() - '0');
726 ndigits++;
729 REQUIRE(ndigits > 0 && count <= DUPMAX, REG_BADBR);
730 return(count);
734 - p_bracket - parse a bracketed character list
735 == static void p_bracket(struct parse *p);
737 * Note a significant property of this code: if the allocset() did SETERROR,
738 * no set operations are done.
740 static void
741 p_bracket(
742 struct parse *p)
744 cset *cs;
745 int invert = 0;
747 assert(p != NULL);
749 cs = allocset(p);
751 /* Dept of Truly Sickening Special-Case Kludges */
752 if (p->next + 5 < p->end && strncmp(p->next, "[:<:]]",
753 (size_t)6) == 0) {
754 EMIT(OBOW, 0);
755 NEXTn(6);
756 return;
758 if (p->next + 5 < p->end && strncmp(p->next, "[:>:]]",
759 (size_t)6) == 0) {
760 EMIT(OEOW, 0);
761 NEXTn(6);
762 return;
765 if (EAT('^'))
766 invert++; /* make note to invert set at end */
767 if (EAT(']'))
768 CHadd(cs, ']');
769 else if (EAT('-'))
770 CHadd(cs, '-');
771 while (MORE() && PEEK() != ']' && !SEETWO('-', ']'))
772 p_b_term(p, cs);
773 if (EAT('-'))
774 CHadd(cs, '-');
775 MUSTEAT(']', REG_EBRACK);
777 if (p->error != 0) /* don't mess things up further */
778 return;
780 if (p->g->cflags&REG_ICASE) {
781 int i;
782 int ci;
784 for (i = p->g->csetsize - 1; i >= 0; i--)
785 if (CHIN(cs, i) && isalpha(i)) {
786 ci = othercase(i);
787 if (ci != i)
788 CHadd(cs, ci);
790 if (cs->multis != NULL)
791 mccase(p, cs);
793 if (invert) {
794 int i;
796 for (i = p->g->csetsize - 1; i >= 0; i--)
797 if (CHIN(cs, i))
798 CHsub(cs, i);
799 else
800 CHadd(cs, i);
801 if (p->g->cflags&REG_NEWLINE)
802 CHsub(cs, '\n');
803 if (cs->multis != NULL)
804 mcinvert(p, cs);
807 assert(cs->multis == NULL); /* xxx */
809 if (nch(p, cs) == 1) { /* optimize singleton sets */
810 ordinary(p, firstch(p, cs));
811 freeset(p, cs);
812 } else
813 EMIT(OANYOF, freezeset(p, cs));
817 - p_b_term - parse one term of a bracketed character list
818 == static void p_b_term(struct parse *p, cset *cs);
820 static void
821 p_b_term(
822 struct parse *p,
823 cset *cs)
825 char c;
826 char start, finish;
827 int i;
829 assert(p != NULL);
830 assert(cs != NULL);
832 /* classify what we've got */
833 switch ((MORE()) ? PEEK() : '\0') {
834 case '[':
835 c = (MORE2()) ? PEEK2() : '\0';
836 break;
838 case '-':
839 SETERROR(REG_ERANGE);
840 return; /* NOTE RETURN */
842 default:
843 c = '\0';
844 break;
847 switch (c) {
848 case ':': /* character class */
849 NEXT2();
850 REQUIRE(MORE(), REG_EBRACK);
851 c = PEEK();
852 REQUIRE(c != '-' && c != ']', REG_ECTYPE);
853 p_b_cclass(p, cs);
854 REQUIRE(MORE(), REG_EBRACK);
855 REQUIRE(EATTWO(':', ']'), REG_ECTYPE);
856 break;
857 case '=': /* equivalence class */
858 NEXT2();
859 REQUIRE(MORE(), REG_EBRACK);
860 c = PEEK();
861 REQUIRE(c != '-' && c != ']', REG_ECOLLATE);
862 p_b_eclass(p, cs);
863 REQUIRE(MORE(), REG_EBRACK);
864 REQUIRE(EATTWO('=', ']'), REG_ECOLLATE);
865 break;
866 default: /* symbol, ordinary character, or range */
867 /* xxx revision needed for multichar stuff */
868 start = p_b_symbol(p);
869 if (SEE('-') && MORE2() && PEEK2() != ']') {
870 /* range */
871 NEXT();
872 if (EAT('-'))
873 finish = '-';
874 else
875 finish = p_b_symbol(p);
876 } else
877 finish = start;
878 /* xxx what about signed chars here... */
879 REQUIRE(start <= finish, REG_ERANGE);
880 for (i = start; i <= finish; i++)
881 CHadd(cs, i);
882 break;
887 - p_b_cclass - parse a character-class name and deal with it
888 == static void p_b_cclass(struct parse *p, cset *cs);
890 static void
891 p_b_cclass(
892 struct parse *p,
893 cset *cs)
895 const char *sp;
896 const struct cclass *cp;
897 size_t len;
898 const char *u;
899 char c;
901 assert(p != NULL);
902 assert(cs != NULL);
904 sp = p->next;
906 while (MORE() && isalpha((unsigned char)PEEK()))
907 NEXT();
908 len = p->next - sp;
909 for (cp = cclasses; cp->name != NULL; cp++)
910 if (strncmp(cp->name, sp, len) == 0 && cp->name[len] == '\0')
911 break;
912 if (cp->name == NULL) {
913 /* oops, didn't find it */
914 SETERROR(REG_ECTYPE);
915 return;
918 u = cp->chars;
919 while ((c = *u++) != '\0')
920 CHadd(cs, c);
921 for (u = cp->multis; *u != '\0'; u += strlen(u) + 1)
922 MCadd(p, cs, u);
926 - p_b_eclass - parse an equivalence-class name and deal with it
927 == static void p_b_eclass(struct parse *p, cset *cs);
929 * This implementation is incomplete. xxx
931 static void
932 p_b_eclass(
933 struct parse *p,
934 cset *cs)
936 char c;
938 assert(p != NULL);
939 assert(cs != NULL);
941 c = p_b_coll_elem(p, '=');
942 CHadd(cs, c);
946 - p_b_symbol - parse a character or [..]ed multicharacter collating symbol
947 == static char p_b_symbol(struct parse *p);
949 static char /* value of symbol */
950 p_b_symbol(
951 struct parse *p)
953 char value;
955 assert(p != NULL);
957 REQUIRE(MORE(), REG_EBRACK);
958 if (!EATTWO('[', '.'))
959 return(GETNEXT());
961 /* collating symbol */
962 value = p_b_coll_elem(p, '.');
963 REQUIRE(EATTWO('.', ']'), REG_ECOLLATE);
964 return(value);
968 - p_b_coll_elem - parse a collating-element name and look it up
969 == static char p_b_coll_elem(struct parse *p, int endc);
971 static char /* value of collating element */
972 p_b_coll_elem(
973 struct parse *p,
974 int endc) /* name ended by endc,']' */
976 const char *sp;
977 const struct cname *cp;
978 size_t len;
980 assert(p != NULL);
982 sp = p->next;
984 while (MORE() && !SEETWO(endc, ']'))
985 NEXT();
986 if (!MORE()) {
987 SETERROR(REG_EBRACK);
988 return(0);
990 len = p->next - sp;
991 for (cp = cnames; cp->name != NULL; cp++)
992 if (strncmp(cp->name, sp, len) == 0 && cp->name[len] == '\0')
993 return(cp->code); /* known name */
994 if (len == 1)
995 return(*sp); /* single character */
996 SETERROR(REG_ECOLLATE); /* neither */
997 return(0);
1001 - othercase - return the case counterpart of an alphabetic
1002 == static int othercase(int ch);
1004 static int /* if no counterpart, return ch */
1005 othercase(
1006 int ch)
1008 assert(isalpha(ch));
1009 if (isupper(ch))
1010 return(tolower(ch));
1011 else if (islower(ch))
1012 return(toupper(ch));
1013 else /* peculiar, but could happen */
1014 return(ch);
1018 - bothcases - emit a dualcase version of a two-case character
1019 == static void bothcases(struct parse *p, int ch);
1021 * Boy, is this implementation ever a kludge...
1023 static void
1024 bothcases(
1025 struct parse *p,
1026 int ch)
1028 const char *oldnext;
1029 const char *oldend;
1030 char bracket[3];
1032 assert(p != NULL);
1034 oldnext = p->next;
1035 oldend = p->end;
1037 assert(othercase(ch) != ch); /* p_bracket() would recurse */
1038 p->next = bracket;
1039 p->end = bracket+2;
1040 bracket[0] = ch;
1041 bracket[1] = ']';
1042 bracket[2] = '\0';
1043 p_bracket(p);
1044 assert(p->next == bracket+2);
1045 p->next = oldnext;
1046 p->end = oldend;
1050 - ordinary - emit an ordinary character
1051 == static void ordinary(struct parse *p, int ch);
1053 static void
1054 ordinary(
1055 struct parse *p,
1056 int ch)
1058 cat_t *cap;
1060 assert(p != NULL);
1062 cap = p->g->categories;
1063 if ((p->g->cflags&REG_ICASE) && isalpha((unsigned char) ch)
1064 && othercase((unsigned char) ch) != (unsigned char) ch)
1065 bothcases(p, (unsigned char) ch);
1066 else {
1067 EMIT(OCHAR, (unsigned char)ch);
1068 if (cap[ch] == 0)
1069 cap[ch] = p->g->ncategories++;
1074 - nonnewline - emit REG_NEWLINE version of OANY
1075 == static void nonnewline(struct parse *p);
1077 * Boy, is this implementation ever a kludge...
1079 static void
1080 nonnewline(
1081 struct parse *p)
1083 const char *oldnext;
1084 const char *oldend;
1085 char bracket[4];
1087 assert(p != NULL);
1089 oldnext = p->next;
1090 oldend = p->end;
1092 p->next = bracket;
1093 p->end = bracket+3;
1094 bracket[0] = '^';
1095 bracket[1] = '\n';
1096 bracket[2] = ']';
1097 bracket[3] = '\0';
1098 p_bracket(p);
1099 assert(p->next == bracket+3);
1100 p->next = oldnext;
1101 p->end = oldend;
1105 - repeat - generate code for a bounded repetition, recursively if needed
1106 == static void repeat(struct parse *p, sopno start, int from, int to);
1108 static void
1109 repeat(
1110 struct parse *p,
1111 sopno start, /* operand from here to end of strip */
1112 int from, /* repeated from this number */
1113 int to) /* to this number of times (maybe INFINITY) */
1115 sopno finish;
1116 # define N 2
1117 # define INF 3
1118 # define REP(f, t) ((f)*8 + (t))
1119 # define MAP(n) (((n) <= 1) ? (n) : ((n) == INFINITY) ? INF : N)
1120 sopno copy;
1122 assert(p != NULL);
1124 finish = HERE();
1126 if (p->error != 0) /* head off possible runaway recursion */
1127 return;
1129 assert(from <= to);
1131 switch (REP(MAP(from), MAP(to))) {
1132 case REP(0, 0): /* must be user doing this */
1133 DROP(finish-start); /* drop the operand */
1134 break;
1135 case REP(0, 1): /* as x{1,1}? */
1136 case REP(0, N): /* as x{1,n}? */
1137 case REP(0, INF): /* as x{1,}? */
1138 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
1139 INSERT(OCH_, start); /* offset is wrong... */
1140 repeat(p, start+1, 1, to);
1141 ASTERN(OOR1, start);
1142 AHEAD(start); /* ... fix it */
1143 EMIT(OOR2, 0);
1144 AHEAD(THERE());
1145 ASTERN(O_CH, THERETHERE());
1146 break;
1147 case REP(1, 1): /* trivial case */
1148 /* done */
1149 break;
1150 case REP(1, N): /* as x?x{1,n-1} */
1151 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
1152 INSERT(OCH_, start);
1153 ASTERN(OOR1, start);
1154 AHEAD(start);
1155 EMIT(OOR2, 0); /* offset very wrong... */
1156 AHEAD(THERE()); /* ...so fix it */
1157 ASTERN(O_CH, THERETHERE());
1158 copy = dupl(p, start+1, finish+1);
1159 assert(copy == finish+4);
1160 repeat(p, copy, 1, to-1);
1161 break;
1162 case REP(1, INF): /* as x+ */
1163 INSERT(OPLUS_, start);
1164 ASTERN(O_PLUS, start);
1165 break;
1166 case REP(N, N): /* as xx{m-1,n-1} */
1167 copy = dupl(p, start, finish);
1168 repeat(p, copy, from-1, to-1);
1169 break;
1170 case REP(N, INF): /* as xx{n-1,INF} */
1171 copy = dupl(p, start, finish);
1172 repeat(p, copy, from-1, to);
1173 break;
1174 default: /* "can't happen" */
1175 SETERROR(REG_ASSERT); /* just in case */
1176 break;
1181 - seterr - set an error condition
1182 == static int seterr(struct parse *p, int e);
1184 static int /* useless but makes type checking happy */
1185 seterr(
1186 struct parse *p,
1187 int e)
1190 assert(p != NULL);
1192 if (p->error == 0) /* keep earliest error condition */
1193 p->error = e;
1194 p->next = nuls; /* try to bring things to a halt */
1195 p->end = nuls;
1196 return(0); /* make the return value well-defined */
1200 - allocset - allocate a set of characters for []
1201 == static cset *allocset(struct parse *p);
1203 static cset *
1204 allocset(
1205 struct parse *p)
1207 int no;
1208 size_t nc;
1209 size_t nbytes;
1210 cset *cs;
1211 size_t css;
1212 int i;
1214 assert(p != NULL);
1216 no = p->g->ncsets++;
1217 css = (size_t)p->g->csetsize;
1218 if (no >= p->ncsalloc) { /* need another column of space */
1219 p->ncsalloc += CHAR_BIT;
1220 nc = p->ncsalloc;
1221 assert(nc % CHAR_BIT == 0);
1222 nbytes = nc / CHAR_BIT * css;
1223 if (p->g->sets == NULL)
1224 p->g->sets = malloc(nc * sizeof(cset));
1225 else
1226 p->g->sets = realloc(p->g->sets, nc * sizeof(cset));
1227 if (p->g->setbits == NULL)
1228 p->g->setbits = malloc(nbytes);
1229 else {
1230 p->g->setbits = realloc(p->g->setbits, nbytes);
1231 /* xxx this isn't right if setbits is now NULL */
1232 for (i = 0; i < no; i++)
1233 p->g->sets[i].ptr = p->g->setbits + css*(i/CHAR_BIT);
1235 if (p->g->sets != NULL && p->g->setbits != NULL)
1236 (void) memset((char *)p->g->setbits + (nbytes - css),
1237 0, css);
1238 else {
1239 no = 0;
1240 SETERROR(REG_ESPACE);
1241 /* caller's responsibility not to do set ops */
1245 assert(p->g->sets != NULL); /* xxx */
1246 cs = &p->g->sets[no];
1247 cs->ptr = p->g->setbits + css*((no)/CHAR_BIT);
1248 cs->mask = 1 << ((no) % CHAR_BIT);
1249 cs->hash = 0;
1250 cs->smultis = 0;
1251 cs->multis = NULL;
1253 return(cs);
1257 - freeset - free a now-unused set
1258 == static void freeset(struct parse *p, cset *cs);
1260 static void
1261 freeset(
1262 struct parse *p,
1263 cset *cs)
1265 int i;
1266 cset *top;
1267 size_t css;
1269 assert(p != NULL);
1270 assert(cs != NULL);
1272 top = &p->g->sets[p->g->ncsets];
1273 css = (size_t)p->g->csetsize;
1275 for (i = 0; i < css; i++)
1276 CHsub(cs, i);
1277 if (cs == top-1) /* recover only the easy case */
1278 p->g->ncsets--;
1282 - freezeset - final processing on a set of characters
1283 == static int freezeset(struct parse *p, cset *cs);
1285 * The main task here is merging identical sets. This is usually a waste
1286 * of time (although the hash code minimizes the overhead), but can win
1287 * big if REG_ICASE is being used. REG_ICASE, by the way, is why the hash
1288 * is done using addition rather than xor -- all ASCII [aA] sets xor to
1289 * the same value!
1291 static int /* set number */
1292 freezeset(
1293 struct parse *p,
1294 cset *cs)
1296 uch h;
1297 int i;
1298 cset *top;
1299 cset *cs2;
1300 size_t css;
1302 assert(p != NULL);
1303 assert(cs != NULL);
1305 h = cs->hash;
1306 top = &p->g->sets[p->g->ncsets];
1307 css = (size_t)p->g->csetsize;
1309 /* look for an earlier one which is the same */
1310 for (cs2 = &p->g->sets[0]; cs2 < top; cs2++)
1311 if (cs2->hash == h && cs2 != cs) {
1312 /* maybe */
1313 for (i = 0; i < css; i++)
1314 if (!!CHIN(cs2, i) != !!CHIN(cs, i))
1315 break; /* no */
1316 if (i == css)
1317 break; /* yes */
1320 if (cs2 < top) { /* found one */
1321 freeset(p, cs);
1322 cs = cs2;
1325 return((int)(cs - p->g->sets));
1329 - firstch - return first character in a set (which must have at least one)
1330 == static int firstch(struct parse *p, cset *cs);
1332 static int /* character; there is no "none" value */
1333 firstch(
1334 struct parse *p,
1335 cset *cs)
1337 int i;
1338 size_t css;
1340 assert(p != NULL);
1341 assert(cs != NULL);
1343 css = (size_t)p->g->csetsize;
1345 for (i = 0; i < css; i++)
1346 if (CHIN(cs, i))
1347 return((char)i);
1348 assert(never);
1349 return(0); /* arbitrary */
1353 - nch - number of characters in a set
1354 == static int nch(struct parse *p, cset *cs);
1356 static int
1357 nch(
1358 struct parse *p,
1359 cset *cs)
1361 int i;
1362 size_t css;
1363 int n = 0;
1365 assert(p != NULL);
1366 assert(cs != NULL);
1368 css = (size_t)p->g->csetsize;
1370 for (i = 0; i < css; i++)
1371 if (CHIN(cs, i))
1372 n++;
1373 return(n);
1377 - mcadd - add a collating element to a cset
1378 == static void mcadd(struct parse *p, cset *cs, \
1379 == char *cp);
1381 static void
1382 mcadd(
1383 struct parse *p,
1384 cset *cs,
1385 const char *cp)
1387 size_t oldend;
1389 assert(p != NULL);
1390 assert(cs != NULL);
1391 assert(cp != NULL);
1393 oldend = cs->smultis;
1395 cs->smultis += strlen(cp) + 1;
1396 if (cs->multis == NULL)
1397 cs->multis = malloc(cs->smultis);
1398 else
1399 cs->multis = realloc(cs->multis, cs->smultis);
1400 if (cs->multis == NULL) {
1401 SETERROR(REG_ESPACE);
1402 return;
1405 (void) strcpy(cs->multis + oldend - 1, cp);
1406 cs->multis[cs->smultis - 1] = '\0';
1409 #if 0
1411 - mcsub - subtract a collating element from a cset
1412 == static void mcsub(cset *cs, char *cp);
1414 static void
1415 mcsub(
1416 cset *cs,
1417 char *cp)
1419 char *fp;
1420 size_t len;
1422 assert(cs != NULL);
1423 assert(cp != NULL);
1425 fp = mcfind(cs, cp);
1426 len = strlen(fp);
1428 assert(fp != NULL);
1429 (void) memmove(fp, fp + len + 1,
1430 cs->smultis - (fp + len + 1 - cs->multis));
1431 cs->smultis -= len;
1433 if (cs->smultis == 0) {
1434 free(cs->multis);
1435 cs->multis = NULL;
1436 return;
1439 cs->multis = realloc(cs->multis, cs->smultis);
1440 assert(cs->multis != NULL);
1444 - mcin - is a collating element in a cset?
1445 == static int mcin(cset *cs, char *cp);
1447 static int
1448 mcin(
1449 cset *cs,
1450 char *cp)
1453 assert(cs != NULL);
1454 assert(cp != NULL);
1456 return(mcfind(cs, cp) != NULL);
1460 - mcfind - find a collating element in a cset
1461 == static char *mcfind(cset *cs, char *cp);
1463 static char *
1464 mcfind(
1465 cset *cs,
1466 char *cp)
1468 char *p;
1470 assert(cs != NULL);
1471 assert(cp != NULL);
1473 if (cs->multis == NULL)
1474 return(NULL);
1475 for (p = cs->multis; *p != '\0'; p += strlen(p) + 1)
1476 if (strcmp(cp, p) == 0)
1477 return(p);
1478 return(NULL);
1480 #endif
1483 - mcinvert - invert the list of collating elements in a cset
1484 == static void mcinvert(struct parse *p, cset *cs);
1486 * This would have to know the set of possibilities. Implementation
1487 * is deferred.
1489 /* ARGSUSED */
1490 static void
1491 mcinvert(
1492 struct parse *p,
1493 cset *cs)
1496 assert(p != NULL);
1497 assert(cs != NULL);
1499 assert(cs->multis == NULL); /* xxx */
1503 - mccase - add case counterparts of the list of collating elements in a cset
1504 == static void mccase(struct parse *p, cset *cs);
1506 * This would have to know the set of possibilities. Implementation
1507 * is deferred.
1509 /* ARGSUSED */
1510 static void
1511 mccase(
1512 struct parse *p,
1513 cset *cs)
1516 assert(p != NULL);
1517 assert(cs != NULL);
1519 assert(cs->multis == NULL); /* xxx */
1523 - isinsets - is this character in any sets?
1524 == static int isinsets(struct re_guts *g, int c);
1526 static int /* predicate */
1527 isinsets(
1528 struct re_guts *g,
1529 int c)
1531 uch *col;
1532 int i;
1533 int ncols;
1534 unsigned uc = (unsigned char)c;
1536 assert(g != NULL);
1538 ncols = (g->ncsets+(CHAR_BIT-1)) / CHAR_BIT;
1540 for (i = 0, col = g->setbits; i < ncols; i++, col += g->csetsize)
1541 if (col[uc] != 0)
1542 return(1);
1543 return(0);
1547 - samesets - are these two characters in exactly the same sets?
1548 == static int samesets(struct re_guts *g, int c1, int c2);
1550 static int /* predicate */
1551 samesets(
1552 struct re_guts *g,
1553 int c1,
1554 int c2)
1556 uch *col;
1557 int i;
1558 int ncols;
1559 unsigned uc1 = (unsigned char)c1;
1560 unsigned uc2 = (unsigned char)c2;
1562 assert(g != NULL);
1564 ncols = (g->ncsets+(CHAR_BIT-1)) / CHAR_BIT;
1566 for (i = 0, col = g->setbits; i < ncols; i++, col += g->csetsize)
1567 if (col[uc1] != col[uc2])
1568 return(0);
1569 return(1);
1573 - categorize - sort out character categories
1574 == static void categorize(struct parse *p, struct re_guts *g);
1576 static void
1577 categorize(
1578 struct parse *p,
1579 struct re_guts *g)
1581 cat_t *cats;
1582 int c;
1583 int c2;
1584 cat_t cat;
1586 assert(p != NULL);
1587 assert(g != NULL);
1589 cats = g->categories;
1591 /* avoid making error situations worse */
1592 if (p->error != 0)
1593 return;
1595 for (c = CHAR_MIN; c <= CHAR_MAX; c++)
1596 if (cats[c] == 0 && isinsets(g, c)) {
1597 cat = g->ncategories++;
1598 cats[c] = cat;
1599 for (c2 = c+1; c2 <= CHAR_MAX; c2++)
1600 if (cats[c2] == 0 && samesets(g, c, c2))
1601 cats[c2] = cat;
1606 - dupl - emit a duplicate of a bunch of sops
1607 == static sopno dupl(struct parse *p, sopno start, sopno finish);
1609 static sopno /* start of duplicate */
1610 dupl(
1611 struct parse *p,
1612 sopno start, /* from here */
1613 sopno finish) /* to this less one */
1615 sopno ret;
1616 sopno len = finish - start;
1618 assert(p != NULL);
1620 ret = HERE();
1622 assert(finish >= start);
1623 if (len == 0)
1624 return(ret);
1625 enlarge(p, p->ssize + len); /* this many unexpected additions */
1626 assert(p->ssize >= p->slen + len);
1627 (void)memcpy(p->strip + p->slen, p->strip + start,
1628 (size_t)len * sizeof(sop));
1629 p->slen += len;
1630 return(ret);
1634 - doemit - emit a strip operator
1635 == static void doemit(struct parse *p, sop op, size_t opnd);
1637 * It might seem better to implement this as a macro with a function as
1638 * hard-case backup, but it's just too big and messy unless there are
1639 * some changes to the data structures. Maybe later.
1641 static void
1642 doemit(
1643 struct parse *p,
1644 sop op,
1645 sopno opnd)
1648 assert(p != NULL);
1650 /* avoid making error situations worse */
1651 if (p->error != 0)
1652 return;
1654 /* deal with oversize operands ("can't happen", more or less) */
1655 assert(opnd < 1<<OPSHIFT);
1657 /* deal with undersized strip */
1658 if (p->slen >= p->ssize)
1659 enlarge(p, (p->ssize+1) / 2 * 3); /* +50% */
1660 assert(p->slen < p->ssize);
1662 /* finally, it's all reduced to the easy case */
1663 p->strip[p->slen++] = SOP(op, opnd);
1667 - doinsert - insert a sop into the strip
1668 == static void doinsert(struct parse *p, sop op, size_t opnd, sopno pos);
1670 static void
1671 doinsert(
1672 struct parse *p,
1673 sop op,
1674 sopno opnd,
1675 sopno pos)
1677 sopno sn;
1678 sop s;
1679 int i;
1681 assert(p != NULL);
1683 /* avoid making error situations worse */
1684 if (p->error != 0)
1685 return;
1687 sn = HERE();
1688 EMIT(op, opnd); /* do checks, ensure space */
1689 assert(HERE() == sn+1);
1690 s = p->strip[sn];
1692 /* adjust paren pointers */
1693 assert(pos > 0);
1694 for (i = 1; i < NPAREN; i++) {
1695 if (p->pbegin[i] >= pos) {
1696 p->pbegin[i]++;
1698 if (p->pend[i] >= pos) {
1699 p->pend[i]++;
1703 memmove(&p->strip[pos+1], &p->strip[pos], (HERE()-pos-1)*sizeof(sop));
1704 p->strip[pos] = s;
1708 - dofwd - complete a forward reference
1709 == static void dofwd(struct parse *p, sopno pos, sop value);
1711 static void
1712 dofwd(
1713 struct parse *p,
1714 sopno pos,
1715 sopno value)
1718 assert(p != NULL);
1720 /* avoid making error situations worse */
1721 if (p->error != 0)
1722 return;
1724 assert(value < 1<<OPSHIFT);
1725 p->strip[pos] = OP(p->strip[pos]) | value;
1729 - enlarge - enlarge the strip
1730 == static void enlarge(struct parse *p, sopno size);
1732 static void
1733 enlarge(
1734 struct parse *p,
1735 sopno size)
1737 sop *sp;
1739 assert(p != NULL);
1741 if (p->ssize >= size)
1742 return;
1744 sp = (sop *)realloc(p->strip, size*sizeof(sop));
1745 if (sp == NULL) {
1746 SETERROR(REG_ESPACE);
1747 return;
1749 p->strip = sp;
1750 p->ssize = size;
1754 - stripsnug - compact the strip
1755 == static void stripsnug(struct parse *p, struct re_guts *g);
1757 static void
1758 stripsnug(
1759 struct parse *p,
1760 struct re_guts *g)
1763 assert(p != NULL);
1764 assert(g != NULL);
1766 g->nstates = p->slen;
1767 g->strip = realloc(p->strip, p->slen * sizeof(sop));
1768 if (g->strip == NULL) {
1769 SETERROR(REG_ESPACE);
1770 g->strip = p->strip;
1775 - findmust - fill in must and mlen with longest mandatory literal string
1776 == static void findmust(struct parse *p, struct re_guts *g);
1778 * This algorithm could do fancy things like analyzing the operands of |
1779 * for common subsequences. Someday. This code is simple and finds most
1780 * of the interesting cases.
1782 * Note that must and mlen got initialized during setup.
1784 static void
1785 findmust(
1786 struct parse *p,
1787 struct re_guts *g)
1789 sop *scan;
1790 sop *start = NULL;
1791 sop *newstart = NULL;
1792 sopno newlen;
1793 sop s;
1794 char *cp;
1795 sopno i;
1797 assert(p != NULL);
1798 assert(g != NULL);
1800 /* avoid making error situations worse */
1801 if (p->error != 0)
1802 return;
1804 /* find the longest OCHAR sequence in strip */
1805 newlen = 0;
1806 scan = g->strip + 1;
1807 do {
1808 s = *scan++;
1809 switch (OP(s)) {
1810 case OCHAR: /* sequence member */
1811 if (newlen == 0) /* new sequence */
1812 newstart = scan - 1;
1813 newlen++;
1814 break;
1815 case OPLUS_: /* things that don't break one */
1816 case OLPAREN:
1817 case ORPAREN:
1818 break;
1819 case OQUEST_: /* things that must be skipped */
1820 case OCH_:
1821 scan--;
1822 do {
1823 scan += OPND(s);
1824 s = *scan;
1825 /* assert() interferes w debug printouts */
1826 if (OP(s) != O_QUEST && OP(s) != O_CH &&
1827 OP(s) != OOR2) {
1828 g->iflags |= BAD;
1829 return;
1831 } while (OP(s) != O_QUEST && OP(s) != O_CH);
1832 /* FALLTHROUGH */
1833 default: /* things that break a sequence */
1834 if (newlen > g->mlen) { /* ends one */
1835 start = newstart;
1836 g->mlen = newlen;
1838 newlen = 0;
1839 break;
1841 } while (OP(s) != OEND);
1843 if (start == NULL)
1844 g->mlen = 0;
1846 if (g->mlen == 0) /* there isn't one */
1847 return;
1849 /* turn it into a character string */
1850 g->must = malloc((size_t)g->mlen + 1);
1851 if (g->must == NULL) { /* argh; just forget it */
1852 g->mlen = 0;
1853 return;
1855 cp = g->must;
1856 scan = start;
1857 for (i = g->mlen; i > 0; i--) {
1858 while (OP(s = *scan++) != OCHAR)
1859 continue;
1860 assert(cp < g->must + g->mlen);
1861 *cp++ = (char)OPND(s);
1863 assert(cp == g->must + g->mlen);
1864 *cp++ = '\0'; /* just on general principles */
1868 - pluscount - count + nesting
1869 == static sopno pluscount(struct parse *p, struct re_guts *g);
1871 static sopno /* nesting depth */
1872 pluscount(
1873 struct parse *p,
1874 struct re_guts *g)
1876 sop *scan;
1877 sop s;
1878 sopno plusnest = 0;
1879 sopno maxnest = 0;
1881 assert(p != NULL);
1882 assert(g != NULL);
1884 if (p->error != 0)
1885 return(0); /* there may not be an OEND */
1887 scan = g->strip + 1;
1888 do {
1889 s = *scan++;
1890 switch (OP(s)) {
1891 case OPLUS_:
1892 plusnest++;
1893 break;
1894 case O_PLUS:
1895 if (plusnest > maxnest)
1896 maxnest = plusnest;
1897 plusnest--;
1898 break;
1900 } while (OP(s) != OEND);
1901 if (plusnest != 0)
1902 g->iflags |= BAD;
1903 return(maxnest);