2 * Copyright (c) 1992, 1993, 1994 Henry Spencer.
3 * Copyright (c) 1992, 1993, 1994
4 * The Regents of the University of California. All rights reserved.
6 * This code is derived from software contributed to Berkeley by
7 * Henry Spencer of the University of Toronto.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 * 3. All advertising materials mentioning features or use of this software
18 * must display the following acknowledgement:
19 * This product includes software developed by the University of
20 * California, Berkeley and its contributors.
21 * 4. Neither the name of the University nor the names of its contributors
22 * may be used to endorse or promote products derived from this software
23 * without specific prior written permission.
25 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
37 * @(#)regcomp.c 8.4 (Berkeley) 3/19/94
40 #if defined(LIBC_SCCS) && !defined(lint)
41 static char sccsid
[] = "@(#)regcomp.c 8.4 (Berkeley) 3/19/94";
42 #endif /* LIBC_SCCS and not lint */
44 #include <sys/types.h>
59 * parse structure, passed up and down to avoid global variables and
63 char *next
; /* next character in RE */
64 char *end
; /* end of string (-> NUL normally) */
65 int error
; /* has an error been seen? */
66 sop
*strip
; /* malloced strip */
67 sopno ssize
; /* malloced strip size (allocated) */
68 sopno slen
; /* malloced strip length (used) */
69 int ncsalloc
; /* number of csets allocated */
71 # define NPAREN 10 /* we need to remember () 1-9 for back refs */
72 sopno pbegin
[NPAREN
]; /* -> ( ([0] unused) */
73 sopno pend
[NPAREN
]; /* -> ) ([0] unused) */
76 /* ========= begin header generated by ./mkh ========= */
81 /* === regcomp.c === */
82 static void p_ere
__P((struct parse
*p
, int stop
));
83 static void p_ere_exp
__P((struct parse
*p
));
84 static void p_str
__P((struct parse
*p
));
85 static void p_bre
__P((struct parse
*p
, int end1
, int end2
));
86 static int p_simp_re
__P((struct parse
*p
, int starordinary
));
87 static int p_count
__P((struct parse
*p
));
88 static void p_bracket
__P((struct parse
*p
));
89 static void p_b_term
__P((struct parse
*p
, cset
*cs
));
90 static void p_b_cclass
__P((struct parse
*p
, cset
*cs
));
91 static void p_b_eclass
__P((struct parse
*p
, cset
*cs
));
92 static char p_b_symbol
__P((struct parse
*p
));
93 static char p_b_coll_elem
__P((struct parse
*p
, int endc
));
94 static char othercase
__P((int ch
));
95 static void bothcases
__P((struct parse
*p
, int ch
));
96 static void ordinary
__P((struct parse
*p
, int ch
));
97 static void nonnewline
__P((struct parse
*p
));
98 static void repeat
__P((struct parse
*p
, sopno start
, int from
, int to
));
99 static int seterr
__P((struct parse
*p
, int e
));
100 static cset
*allocset
__P((struct parse
*p
));
101 static void freeset
__P((struct parse
*p
, cset
*cs
));
102 static int freezeset
__P((struct parse
*p
, cset
*cs
));
103 static int firstch
__P((struct parse
*p
, cset
*cs
));
104 static int nch
__P((struct parse
*p
, cset
*cs
));
105 static void mcadd
__P((struct parse
*p
, cset
*cs
, char *cp
));
106 static void mcsub
__P((cset
*cs
, char *cp
));
107 static int mcin
__P((cset
*cs
, char *cp
));
108 static char *mcfind
__P((cset
*cs
, char *cp
));
109 static void mcinvert
__P((struct parse
*p
, cset
*cs
));
110 static void mccase
__P((struct parse
*p
, cset
*cs
));
111 static int isinsets
__P((struct re_guts
*g
, int c
));
112 static int samesets
__P((struct re_guts
*g
, int c1
, int c2
));
113 static void categorize
__P((struct parse
*p
, struct re_guts
*g
));
114 static sopno dupl
__P((struct parse
*p
, sopno start
, sopno finish
));
115 static void doemit
__P((struct parse
*p
, sop op
, size_t opnd
));
116 static void doinsert
__P((struct parse
*p
, sop op
, size_t opnd
, sopno pos
));
117 static void dofwd
__P((struct parse
*p
, sopno pos
, sop value
));
118 static void enlarge
__P((struct parse
*p
, sopno size
));
119 static void stripsnug
__P((struct parse
*p
, struct re_guts
*g
));
120 static void findmust
__P((struct parse
*p
, struct re_guts
*g
));
121 static sopno pluscount
__P((struct parse
*p
, struct re_guts
*g
));
126 /* ========= end header generated by ./mkh ========= */
128 static char nuls
[10]; /* place to point scanner in event of error */
131 * macros for use with parse structure
132 * BEWARE: these know that the parse structure is named `p' !!!
134 #define PEEK() (*p->next)
135 #define PEEK2() (*(p->next+1))
136 #define MORE() (p->next < p->end)
137 #define MORE2() (p->next+1 < p->end)
138 #define SEE(c) (MORE() && PEEK() == (c))
139 #define SEETWO(a, b) (MORE() && MORE2() && PEEK() == (a) && PEEK2() == (b))
140 #define EAT(c) ((SEE(c)) ? (NEXT(), 1) : 0)
141 #define EATTWO(a, b) ((SEETWO(a, b)) ? (NEXT2(), 1) : 0)
142 #define NEXT() (p->next++)
143 #define NEXT2() (p->next += 2)
144 #define NEXTn(n) (p->next += (n))
145 #define GETNEXT() (*p->next++)
146 #define SETERROR(e) seterr(p, (e))
147 #define REQUIRE(co, e) ((co) || SETERROR(e))
148 #define MUSTSEE(c, e) (REQUIRE(MORE() && PEEK() == (c), e))
149 #define MUSTEAT(c, e) (REQUIRE(MORE() && GETNEXT() == (c), e))
150 #define MUSTNOTSEE(c, e) (REQUIRE(!MORE() || PEEK() != (c), e))
151 #define EMIT(op, sopnd) doemit(p, (sop)(op), (size_t)(sopnd))
152 #define INSERT(op, pos) doinsert(p, (sop)(op), HERE()-(pos)+1, pos)
153 #define AHEAD(pos) dofwd(p, pos, HERE()-(pos))
154 #define ASTERN(sop, pos) EMIT(sop, HERE()-pos)
155 #define HERE() (p->slen)
156 #define THERE() (p->slen - 1)
157 #define THERETHERE() (p->slen - 2)
158 #define DROP(n) (p->slen -= (n))
161 static int never
= 0; /* for use in asserts; shuts lint up */
163 #define never 0 /* some <assert.h>s have bugs too */
167 - regcomp - interface for parser and compilation
168 = extern int regcomp(regex_t *, const char *, int);
169 = #define REG_BASIC 0000
170 = #define REG_EXTENDED 0001
171 = #define REG_ICASE 0002
172 = #define REG_NOSUB 0004
173 = #define REG_NEWLINE 0010
174 = #define REG_NOSPEC 0020
175 = #define REG_PEND 0040
176 = #define REG_DUMP 0200
178 int /* 0 success, otherwise REG_something */
179 regcomp(preg
, pattern
, cflags
)
185 register struct re_guts
*g
;
186 register struct parse
*p
= &pa
;
190 # define GOODFLAGS(f) (f)
192 # define GOODFLAGS(f) ((f)&~REG_DUMP)
195 cflags
= GOODFLAGS(cflags
);
196 if ((cflags
®_EXTENDED
) && (cflags
®_NOSPEC
))
199 if (cflags
®_PEND
) {
200 if (preg
->re_endp
< pattern
)
202 len
= preg
->re_endp
- pattern
;
204 len
= strlen((char *)pattern
);
206 /* do the mallocs early so failure handling is easy */
207 g
= (struct re_guts
*)malloc(sizeof(struct re_guts
) +
208 (NC
-1)*sizeof(cat_t
));
211 p
->ssize
= len
/(size_t)2*(size_t)3 + (size_t)1; /* ugh */
212 p
->strip
= (sop
*)malloc(p
->ssize
* sizeof(sop
));
214 if (p
->strip
== NULL
) {
221 p
->next
= (char *)pattern
; /* convenience; we do not modify it */
222 p
->end
= p
->next
+ len
;
225 for (i
= 0; i
< NPAREN
; i
++) {
240 g
->ncategories
= 1; /* category 0 is "everything else" */
241 g
->categories
= &g
->catspace
[-(CHAR_MIN
)];
242 (void) memset((char *)g
->catspace
, 0, NC
*sizeof(cat_t
));
247 g
->firststate
= THERE();
248 if (cflags
®_EXTENDED
)
250 else if (cflags
®_NOSPEC
)
255 g
->laststate
= THERE();
257 /* tidy up loose ends and fill things in */
261 g
->nplus
= pluscount(p
, g
);
263 preg
->re_nsub
= g
->nsub
;
265 preg
->re_magic
= MAGIC1
;
267 /* not debugging, so can't rely on the assert() in regexec() */
269 SETERROR(REG_ASSERT
);
272 /* win or lose, we're done */
273 if (p
->error
!= 0) /* lose */
279 - p_ere - ERE parser top level, concatenation and alternation
280 == static void p_ere(register struct parse *p, int stop);
284 register struct parse
*p
;
285 int stop
; /* character this ERE should end at */
288 register sopno prevback
;
289 register sopno prevfwd
;
291 register int first
= 1; /* is this the first alternative? */
294 /* do a bunch of concatenated expressions */
296 while (MORE() && (c
= PEEK()) != '|' && c
!= stop
)
298 REQUIRE(HERE() != conc
, REG_EMPTY
); /* require nonempty */
301 break; /* NOTE BREAK OUT */
304 INSERT(OCH_
, conc
); /* offset is wrong */
309 ASTERN(OOR1
, prevback
);
311 AHEAD(prevfwd
); /* fix previous offset */
313 EMIT(OOR2
, 0); /* offset is very wrong */
316 if (!first
) { /* tail-end fixups */
318 ASTERN(O_CH
, prevback
);
321 assert(!MORE() || SEE(stop
));
325 - p_ere_exp - parse one subERE, an atom possibly followed by a repetition op
326 == static void p_ere_exp(register struct parse *p);
330 register struct parse
*p
;
336 register sopno subno
;
339 assert(MORE()); /* caller should have ensured this */
345 REQUIRE(MORE(), REG_EPAREN
);
349 p
->pbegin
[subno
] = HERE();
350 EMIT(OLPAREN
, subno
);
353 if (subno
< NPAREN
) {
354 p
->pend
[subno
] = HERE();
355 assert(p
->pend
[subno
] != 0);
357 EMIT(ORPAREN
, subno
);
358 MUSTEAT(')', REG_EPAREN
);
360 #ifndef POSIX_MISTAKE
361 case ')': /* happens only if no current unmatched ( */
363 * You may ask, why the ifndef? Because I didn't notice
364 * this until slightly too late for 1003.2, and none of the
365 * other 1003.2 regular-expression reviewers noticed it at
366 * all. So an unmatched ) is legal POSIX, at least until
367 * we can get it fixed.
369 SETERROR(REG_EPAREN
);
374 p
->g
->iflags
|= USEBOL
;
380 p
->g
->iflags
|= USEEOL
;
389 SETERROR(REG_BADRPT
);
392 if (p
->g
->cflags
®_NEWLINE
)
401 REQUIRE(MORE(), REG_EESCAPE
);
405 case '{': /* okay as ordinary except if digit follows */
406 REQUIRE(!MORE() || !isdigit(PEEK()), REG_BADRPT
);
416 /* we call { a repetition if followed by a digit */
417 if (!( c
== '*' || c
== '+' || c
== '?' ||
418 (c
== '{' && MORE2() && isdigit(PEEK2())) ))
419 return; /* no repetition, we're done */
422 REQUIRE(!wascaret
, REG_BADRPT
);
424 case '*': /* implemented as +? */
425 /* this case does not require the (y|) trick, noKLUDGE */
428 INSERT(OQUEST_
, pos
);
429 ASTERN(O_QUEST
, pos
);
436 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
437 INSERT(OCH_
, pos
); /* offset slightly wrong */
438 ASTERN(OOR1
, pos
); /* this one's right */
439 AHEAD(pos
); /* fix the OCH_ */
440 EMIT(OOR2
, 0); /* offset very wrong... */
441 AHEAD(THERE()); /* ...so fix it */
442 ASTERN(O_CH
, THERETHERE());
447 if (isdigit(PEEK())) {
449 REQUIRE(count
<= count2
, REG_BADBR
);
450 } else /* single number with comma */
452 } else /* just a single number */
454 repeat(p
, pos
, count
, count2
);
455 if (!EAT('}')) { /* error heuristics */
456 while (MORE() && PEEK() != '}')
458 REQUIRE(MORE(), REG_EBRACE
);
467 if (!( c
== '*' || c
== '+' || c
== '?' ||
468 (c
== '{' && MORE2() && isdigit(PEEK2())) ) )
470 SETERROR(REG_BADRPT
);
474 - p_str - string (no metacharacters) "parser"
475 == static void p_str(register struct parse *p);
479 register struct parse
*p
;
481 REQUIRE(MORE(), REG_EMPTY
);
483 ordinary(p
, GETNEXT());
487 - p_bre - BRE parser top level, anchoring and concatenation
488 == static void p_bre(register struct parse *p, register int end1, \
489 == register int end2);
490 * Giving end1 as OUT essentially eliminates the end1/end2 check.
492 * This implementation is a bit of a kludge, in that a trailing $ is first
493 * taken as an ordinary character and then revised to be an anchor. The
494 * only undesirable side effect is that '$' gets included as a character
495 * category in such cases. This is fairly harmless; not worth fixing.
496 * The amount of lookahead needed to avoid this kludge is excessive.
500 register struct parse
*p
;
501 register int end1
; /* first terminating character */
502 register int end2
; /* second terminating character */
504 register sopno start
= HERE();
505 register int first
= 1; /* first subexpression? */
506 register int wasdollar
= 0;
510 p
->g
->iflags
|= USEBOL
;
513 while (MORE() && !SEETWO(end1
, end2
)) {
514 wasdollar
= p_simp_re(p
, first
);
517 if (wasdollar
) { /* oops, that was a trailing anchor */
520 p
->g
->iflags
|= USEEOL
;
524 REQUIRE(HERE() != start
, REG_EMPTY
); /* require nonempty */
528 - p_simp_re - parse a simple RE, an atom possibly followed by a repetition
529 == static int p_simp_re(register struct parse *p, int starordinary);
531 static int /* was the simple RE an unbackslashed $? */
532 p_simp_re(p
, starordinary
)
533 register struct parse
*p
;
534 int starordinary
; /* is a leading * an ordinary character? */
541 register sopno subno
;
542 # define BACKSL (1<<CHAR_BIT)
544 pos
= HERE(); /* repetion op, if any, covers from here */
546 assert(MORE()); /* caller should have ensured this */
549 REQUIRE(MORE(), REG_EESCAPE
);
550 c
= BACKSL
| (unsigned char)GETNEXT();
554 if (p
->g
->cflags
®_NEWLINE
)
563 SETERROR(REG_BADRPT
);
569 p
->pbegin
[subno
] = HERE();
570 EMIT(OLPAREN
, subno
);
571 /* the MORE here is an error heuristic */
572 if (MORE() && !SEETWO('\\', ')'))
574 if (subno
< NPAREN
) {
575 p
->pend
[subno
] = HERE();
576 assert(p
->pend
[subno
] != 0);
578 EMIT(ORPAREN
, subno
);
579 REQUIRE(EATTWO('\\', ')'), REG_EPAREN
);
581 case BACKSL
|')': /* should not get here -- must be user */
583 SETERROR(REG_EPAREN
);
594 i
= (c
&~BACKSL
) - '0';
596 if (p
->pend
[i
] != 0) {
597 assert(i
<= p
->g
->nsub
);
599 assert(p
->pbegin
[i
] != 0);
600 assert(OP(p
->strip
[p
->pbegin
[i
]]) == OLPAREN
);
601 assert(OP(p
->strip
[p
->pend
[i
]]) == ORPAREN
);
602 (void) dupl(p
, p
->pbegin
[i
]+1, p
->pend
[i
]);
605 SETERROR(REG_ESUBREG
);
609 REQUIRE(starordinary
, REG_BADRPT
);
612 ordinary(p
, c
&~ BACKSL
);
616 if (EAT('*')) { /* implemented as +? */
617 /* this case does not require the (y|) trick, noKLUDGE */
620 INSERT(OQUEST_
, pos
);
621 ASTERN(O_QUEST
, pos
);
622 } else if (EATTWO('\\', '{')) {
625 if (MORE() && isdigit(PEEK())) {
627 REQUIRE(count
<= count2
, REG_BADBR
);
628 } else /* single number with comma */
630 } else /* just a single number */
632 repeat(p
, pos
, count
, count2
);
633 if (!EATTWO('\\', '}')) { /* error heuristics */
634 while (MORE() && !SEETWO('\\', '}'))
636 REQUIRE(MORE(), REG_EBRACE
);
639 } else if (c
== (unsigned char)'$') /* $ (but not \$) ends it */
646 - p_count - parse a repetition count
647 == static int p_count(register struct parse *p);
649 static int /* the value */
651 register struct parse
*p
;
653 register int count
= 0;
654 register int ndigits
= 0;
656 while (MORE() && isdigit(PEEK()) && count
<= DUPMAX
) {
657 count
= count
*10 + (GETNEXT() - '0');
661 REQUIRE(ndigits
> 0 && count
<= DUPMAX
, REG_BADBR
);
666 - p_bracket - parse a bracketed character list
667 == static void p_bracket(register struct parse *p);
669 * Note a significant property of this code: if the allocset() did SETERROR,
670 * no set operations are done.
674 register struct parse
*p
;
677 register cset
*cs
= allocset(p
);
678 register int invert
= 0;
680 /* Dept of Truly Sickening Special-Case Kludges */
681 if (p
->next
+ 5 < p
->end
&& strncmp(p
->next
, "[:<:]]", 6) == 0) {
686 if (p
->next
+ 5 < p
->end
&& strncmp(p
->next
, "[:>:]]", 6) == 0) {
693 invert
++; /* make note to invert set at end */
698 while (MORE() && PEEK() != ']' && !SEETWO('-', ']'))
702 MUSTEAT(']', REG_EBRACK
);
704 if (p
->error
!= 0) /* don't mess things up further */
707 if (p
->g
->cflags
®_ICASE
) {
711 for (i
= p
->g
->csetsize
- 1; i
>= 0; i
--)
712 if (CHIN(cs
, i
) && isalpha(i
)) {
717 if (cs
->multis
!= NULL
)
723 for (i
= p
->g
->csetsize
- 1; i
>= 0; i
--)
728 if (p
->g
->cflags
®_NEWLINE
)
730 if (cs
->multis
!= NULL
)
734 assert(cs
->multis
== NULL
); /* xxx */
736 if (nch(p
, cs
) == 1) { /* optimize singleton sets */
737 ordinary(p
, firstch(p
, cs
));
740 EMIT(OANYOF
, freezeset(p
, cs
));
744 - p_b_term - parse one term of a bracketed character list
745 == static void p_b_term(register struct parse *p, register cset *cs);
749 register struct parse
*p
;
753 register char start
, finish
;
756 /* classify what we've got */
757 switch ((MORE()) ? PEEK() : '\0') {
759 c
= (MORE2()) ? PEEK2() : '\0';
762 SETERROR(REG_ERANGE
);
763 return; /* NOTE RETURN */
771 case ':': /* character class */
773 REQUIRE(MORE(), REG_EBRACK
);
775 REQUIRE(c
!= '-' && c
!= ']', REG_ECTYPE
);
777 REQUIRE(MORE(), REG_EBRACK
);
778 REQUIRE(EATTWO(':', ']'), REG_ECTYPE
);
780 case '=': /* equivalence class */
782 REQUIRE(MORE(), REG_EBRACK
);
784 REQUIRE(c
!= '-' && c
!= ']', REG_ECOLLATE
);
786 REQUIRE(MORE(), REG_EBRACK
);
787 REQUIRE(EATTWO('=', ']'), REG_ECOLLATE
);
789 default: /* symbol, ordinary character, or range */
790 /* xxx revision needed for multichar stuff */
791 start
= p_b_symbol(p
);
792 if (SEE('-') && MORE2() && PEEK2() != ']') {
798 finish
= p_b_symbol(p
);
801 /* xxx what about signed chars here... */
802 REQUIRE(start
<= finish
, REG_ERANGE
);
803 for (i
= start
; i
<= finish
; i
++)
810 - p_b_cclass - parse a character-class name and deal with it
811 == static void p_b_cclass(register struct parse *p, register cset *cs);
815 register struct parse
*p
;
818 register char *sp
= p
->next
;
819 register struct cclass
*cp
;
824 while (MORE() && isalpha(PEEK()))
827 for (cp
= cclasses
; cp
->name
!= NULL
; cp
++)
828 if (strncmp(cp
->name
, sp
, len
) == 0 && cp
->name
[len
] == '\0')
830 if (cp
->name
== NULL
) {
831 /* oops, didn't find it */
832 SETERROR(REG_ECTYPE
);
837 while ((c
= *u
++) != '\0')
839 for (u
= cp
->multis
; *u
!= '\0'; u
+= strlen(u
) + 1)
844 - p_b_eclass - parse an equivalence-class name and deal with it
845 == static void p_b_eclass(register struct parse *p, register cset *cs);
847 * This implementation is incomplete. xxx
851 register struct parse
*p
;
856 c
= p_b_coll_elem(p
, '=');
861 - p_b_symbol - parse a character or [..]ed multicharacter collating symbol
862 == static char p_b_symbol(register struct parse *p);
864 static char /* value of symbol */
866 register struct parse
*p
;
870 REQUIRE(MORE(), REG_EBRACK
);
871 if (!EATTWO('[', '.'))
874 /* collating symbol */
875 value
= p_b_coll_elem(p
, '.');
876 REQUIRE(EATTWO('.', ']'), REG_ECOLLATE
);
881 - p_b_coll_elem - parse a collating-element name and look it up
882 == static char p_b_coll_elem(register struct parse *p, int endc);
884 static char /* value of collating element */
885 p_b_coll_elem(p
, endc
)
886 register struct parse
*p
;
887 int endc
; /* name ended by endc,']' */
889 register char *sp
= p
->next
;
890 register struct cname
*cp
;
894 while (MORE() && !SEETWO(endc
, ']'))
897 SETERROR(REG_EBRACK
);
901 for (cp
= cnames
; cp
->name
!= NULL
; cp
++)
902 if (strncmp(cp
->name
, sp
, len
) == 0 && cp
->name
[len
] == '\0')
903 return(cp
->code
); /* known name */
905 return(*sp
); /* single character */
906 SETERROR(REG_ECOLLATE
); /* neither */
911 - othercase - return the case counterpart of an alphabetic
912 == static char othercase(int ch);
914 static char /* if no counterpart, return ch */
921 else if (islower(ch
))
923 else /* peculiar, but could happen */
928 - bothcases - emit a dualcase version of a two-case character
929 == static void bothcases(register struct parse *p, int ch);
931 * Boy, is this implementation ever a kludge...
935 register struct parse
*p
;
938 register char *oldnext
= p
->next
;
939 register char *oldend
= p
->end
;
942 assert(othercase(ch
) != ch
); /* p_bracket() would recurse */
949 assert(p
->next
== bracket
+2);
955 - ordinary - emit an ordinary character
956 == static void ordinary(register struct parse *p, register int ch);
960 register struct parse
*p
;
963 register cat_t
*cap
= p
->g
->categories
;
965 if ((p
->g
->cflags
®_ICASE
) && isalpha(ch
) && othercase(ch
) != ch
)
968 EMIT(OCHAR
, (unsigned char)ch
);
970 cap
[ch
] = p
->g
->ncategories
++;
975 - nonnewline - emit REG_NEWLINE version of OANY
976 == static void nonnewline(register struct parse *p);
978 * Boy, is this implementation ever a kludge...
982 register struct parse
*p
;
984 register char *oldnext
= p
->next
;
985 register char *oldend
= p
->end
;
995 assert(p
->next
== bracket
+3);
1001 - repeat - generate code for a bounded repetition, recursively if needed
1002 == static void repeat(register struct parse *p, sopno start, int from, int to);
1005 repeat(p
, start
, from
, to
)
1006 register struct parse
*p
;
1007 sopno start
; /* operand from here to end of strip */
1008 int from
; /* repeated from this number */
1009 int to
; /* to this number of times (maybe INFINITY) */
1011 register sopno finish
= HERE();
1014 # define REP(f, t) ((f)*8 + (t))
1015 # define MAP(n) (((n) <= 1) ? (n) : ((n) == INFINITY) ? INF : N)
1016 register sopno copy
;
1018 if (p
->error
!= 0) /* head off possible runaway recursion */
1023 switch (REP(MAP(from
), MAP(to
))) {
1024 case REP(0, 0): /* must be user doing this */
1025 DROP(finish
-start
); /* drop the operand */
1027 case REP(0, 1): /* as x{1,1}? */
1028 case REP(0, N
): /* as x{1,n}? */
1029 case REP(0, INF
): /* as x{1,}? */
1030 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
1031 INSERT(OCH_
, start
); /* offset is wrong... */
1032 repeat(p
, start
+1, 1, to
);
1033 ASTERN(OOR1
, start
);
1034 AHEAD(start
); /* ... fix it */
1037 ASTERN(O_CH
, THERETHERE());
1039 case REP(1, 1): /* trivial case */
1042 case REP(1, N
): /* as x?x{1,n-1} */
1043 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
1044 INSERT(OCH_
, start
);
1045 ASTERN(OOR1
, start
);
1047 EMIT(OOR2
, 0); /* offset very wrong... */
1048 AHEAD(THERE()); /* ...so fix it */
1049 ASTERN(O_CH
, THERETHERE());
1050 copy
= dupl(p
, start
+1, finish
+1);
1051 assert(copy
== finish
+4);
1052 repeat(p
, copy
, 1, to
-1);
1054 case REP(1, INF
): /* as x+ */
1055 INSERT(OPLUS_
, start
);
1056 ASTERN(O_PLUS
, start
);
1058 case REP(N
, N
): /* as xx{m-1,n-1} */
1059 copy
= dupl(p
, start
, finish
);
1060 repeat(p
, copy
, from
-1, to
-1);
1062 case REP(N
, INF
): /* as xx{n-1,INF} */
1063 copy
= dupl(p
, start
, finish
);
1064 repeat(p
, copy
, from
-1, to
);
1066 default: /* "can't happen" */
1067 SETERROR(REG_ASSERT
); /* just in case */
1073 - seterr - set an error condition
1074 == static int seterr(register struct parse *p, int e);
1076 static int /* useless but makes type checking happy */
1078 register struct parse
*p
;
1081 if (p
->error
== 0) /* keep earliest error condition */
1083 p
->next
= nuls
; /* try to bring things to a halt */
1085 return(0); /* make the return value well-defined */
1089 - allocset - allocate a set of characters for []
1090 == static cset *allocset(register struct parse *p);
1094 register struct parse
*p
;
1096 register int no
= p
->g
->ncsets
++;
1098 register size_t nbytes
;
1100 register size_t css
= (size_t)p
->g
->csetsize
;
1103 if (no
>= p
->ncsalloc
) { /* need another column of space */
1104 p
->ncsalloc
+= CHAR_BIT
;
1106 assert(nc
% CHAR_BIT
== 0);
1107 nbytes
= nc
/ CHAR_BIT
* css
;
1108 if (p
->g
->sets
== NULL
)
1109 p
->g
->sets
= (cset
*)malloc(nc
* sizeof(cset
));
1111 p
->g
->sets
= (cset
*)realloc((char *)p
->g
->sets
,
1113 if (p
->g
->setbits
== NULL
)
1114 p
->g
->setbits
= (uch
*)malloc(nbytes
);
1116 p
->g
->setbits
= (uch
*)realloc((char *)p
->g
->setbits
,
1118 /* xxx this isn't right if setbits is now NULL */
1119 for (i
= 0; i
< no
; i
++)
1120 p
->g
->sets
[i
].ptr
= p
->g
->setbits
+ css
*(i
/CHAR_BIT
);
1122 if (p
->g
->sets
!= NULL
&& p
->g
->setbits
!= NULL
)
1123 (void) memset((char *)p
->g
->setbits
+ (nbytes
- css
),
1127 SETERROR(REG_ESPACE
);
1128 /* caller's responsibility not to do set ops */
1132 assert(p
->g
->sets
!= NULL
); /* xxx */
1133 cs
= &p
->g
->sets
[no
];
1134 cs
->ptr
= p
->g
->setbits
+ css
*((no
)/CHAR_BIT
);
1135 cs
->mask
= 1 << ((no
) % CHAR_BIT
);
1144 - freeset - free a now-unused set
1145 == static void freeset(register struct parse *p, register cset *cs);
1149 register struct parse
*p
;
1153 register cset
*top
= &p
->g
->sets
[p
->g
->ncsets
];
1154 register size_t css
= (size_t)p
->g
->csetsize
;
1156 for (i
= 0; i
< css
; i
++)
1158 if (cs
== top
-1) /* recover only the easy case */
1163 - freezeset - final processing on a set of characters
1164 == static int freezeset(register struct parse *p, register cset *cs);
1166 * The main task here is merging identical sets. This is usually a waste
1167 * of time (although the hash code minimizes the overhead), but can win
1168 * big if REG_ICASE is being used. REG_ICASE, by the way, is why the hash
1169 * is done using addition rather than xor -- all ASCII [aA] sets xor to
1172 static int /* set number */
1174 register struct parse
*p
;
1177 register uch h
= cs
->hash
;
1179 register cset
*top
= &p
->g
->sets
[p
->g
->ncsets
];
1181 register size_t css
= (size_t)p
->g
->csetsize
;
1183 /* look for an earlier one which is the same */
1184 for (cs2
= &p
->g
->sets
[0]; cs2
< top
; cs2
++)
1185 if (cs2
->hash
== h
&& cs2
!= cs
) {
1187 for (i
= 0; i
< css
; i
++)
1188 if (!!CHIN(cs2
, i
) != !!CHIN(cs
, i
))
1194 if (cs2
< top
) { /* found one */
1199 return((int)(cs
- p
->g
->sets
));
1203 - firstch - return first character in a set (which must have at least one)
1204 == static int firstch(register struct parse *p, register cset *cs);
1206 static int /* character; there is no "none" value */
1208 register struct parse
*p
;
1212 register size_t css
= (size_t)p
->g
->csetsize
;
1214 for (i
= 0; i
< css
; i
++)
1218 return(0); /* arbitrary */
1222 - nch - number of characters in a set
1223 == static int nch(register struct parse *p, register cset *cs);
1227 register struct parse
*p
;
1231 register size_t css
= (size_t)p
->g
->csetsize
;
1234 for (i
= 0; i
< css
; i
++)
1241 - mcadd - add a collating element to a cset
1242 == static void mcadd(register struct parse *p, register cset *cs, \
1243 == register char *cp);
1247 register struct parse
*p
;
1251 register size_t oldend
= cs
->smultis
;
1253 cs
->smultis
+= strlen(cp
) + 1;
1254 if (cs
->multis
== NULL
)
1255 cs
->multis
= malloc(cs
->smultis
);
1257 cs
->multis
= realloc(cs
->multis
, cs
->smultis
);
1258 if (cs
->multis
== NULL
) {
1259 SETERROR(REG_ESPACE
);
1263 (void) strcpy(cs
->multis
+ oldend
- 1, cp
);
1264 cs
->multis
[cs
->smultis
- 1] = '\0';
1268 - mcsub - subtract a collating element from a cset
1269 == static void mcsub(register cset *cs, register char *cp);
1276 register char *fp
= mcfind(cs
, cp
);
1277 register size_t len
= strlen(fp
);
1280 (void) memmove(fp
, fp
+ len
+ 1,
1281 cs
->smultis
- (fp
+ len
+ 1 - cs
->multis
));
1284 if (cs
->smultis
== 0) {
1290 cs
->multis
= realloc(cs
->multis
, cs
->smultis
);
1291 assert(cs
->multis
!= NULL
);
1295 - mcin - is a collating element in a cset?
1296 == static int mcin(register cset *cs, register char *cp);
1303 return(mcfind(cs
, cp
) != NULL
);
1307 - mcfind - find a collating element in a cset
1308 == static char *mcfind(register cset *cs, register char *cp);
1317 if (cs
->multis
== NULL
)
1319 for (p
= cs
->multis
; *p
!= '\0'; p
+= strlen(p
) + 1)
1320 if (strcmp(cp
, p
) == 0)
1326 - mcinvert - invert the list of collating elements in a cset
1327 == static void mcinvert(register struct parse *p, register cset *cs);
1329 * This would have to know the set of possibilities. Implementation
1334 register struct parse
*p
;
1337 assert(cs
->multis
== NULL
); /* xxx */
1341 - mccase - add case counterparts of the list of collating elements in a cset
1342 == static void mccase(register struct parse *p, register cset *cs);
1344 * This would have to know the set of possibilities. Implementation
1349 register struct parse
*p
;
1352 assert(cs
->multis
== NULL
); /* xxx */
1356 - isinsets - is this character in any sets?
1357 == static int isinsets(register struct re_guts *g, int c);
1359 static int /* predicate */
1361 register struct re_guts
*g
;
1366 register int ncols
= (g
->ncsets
+(CHAR_BIT
-1)) / CHAR_BIT
;
1367 register unsigned uc
= (unsigned char)c
;
1369 for (i
= 0, col
= g
->setbits
; i
< ncols
; i
++, col
+= g
->csetsize
)
1376 - samesets - are these two characters in exactly the same sets?
1377 == static int samesets(register struct re_guts *g, int c1, int c2);
1379 static int /* predicate */
1381 register struct re_guts
*g
;
1387 register int ncols
= (g
->ncsets
+(CHAR_BIT
-1)) / CHAR_BIT
;
1388 register unsigned uc1
= (unsigned char)c1
;
1389 register unsigned uc2
= (unsigned char)c2
;
1391 for (i
= 0, col
= g
->setbits
; i
< ncols
; i
++, col
+= g
->csetsize
)
1392 if (col
[uc1
] != col
[uc2
])
1398 - categorize - sort out character categories
1399 == static void categorize(struct parse *p, register struct re_guts *g);
1404 register struct re_guts
*g
;
1406 register cat_t
*cats
= g
->categories
;
1411 /* avoid making error situations worse */
1415 for (c
= CHAR_MIN
; c
<= CHAR_MAX
; c
++)
1416 if (cats
[c
] == 0 && isinsets(g
, c
)) {
1417 cat
= g
->ncategories
++;
1419 for (c2
= c
+1; c2
<= CHAR_MAX
; c2
++)
1420 if (cats
[c2
] == 0 && samesets(g
, c
, c2
))
1426 - dupl - emit a duplicate of a bunch of sops
1427 == static sopno dupl(register struct parse *p, sopno start, sopno finish);
1429 static sopno
/* start of duplicate */
1430 dupl(p
, start
, finish
)
1431 register struct parse
*p
;
1432 sopno start
; /* from here */
1433 sopno finish
; /* to this less one */
1435 register sopno ret
= HERE();
1436 register sopno len
= finish
- start
;
1438 assert(finish
>= start
);
1441 enlarge(p
, p
->ssize
+ len
); /* this many unexpected additions */
1442 assert(p
->ssize
>= p
->slen
+ len
);
1443 (void) memcpy((char *)(p
->strip
+ p
->slen
),
1444 (char *)(p
->strip
+ start
), (size_t)len
*sizeof(sop
));
1450 - doemit - emit a strip operator
1451 == static void doemit(register struct parse *p, sop op, size_t opnd);
1453 * It might seem better to implement this as a macro with a function as
1454 * hard-case backup, but it's just too big and messy unless there are
1455 * some changes to the data structures. Maybe later.
1459 register struct parse
*p
;
1463 /* avoid making error situations worse */
1467 /* deal with oversize operands ("can't happen", more or less) */
1468 assert(opnd
< 1<<OPSHIFT
);
1470 /* deal with undersized strip */
1471 if (p
->slen
>= p
->ssize
)
1472 enlarge(p
, (p
->ssize
+1) / 2 * 3); /* +50% */
1473 assert(p
->slen
< p
->ssize
);
1475 /* finally, it's all reduced to the easy case */
1476 p
->strip
[p
->slen
++] = SOP(op
, opnd
);
1480 - doinsert - insert a sop into the strip
1481 == static void doinsert(register struct parse *p, sop op, size_t opnd, sopno pos);
1484 doinsert(p
, op
, opnd
, pos
)
1485 register struct parse
*p
;
1494 /* avoid making error situations worse */
1499 EMIT(op
, opnd
); /* do checks, ensure space */
1500 assert(HERE() == sn
+1);
1503 /* adjust paren pointers */
1505 for (i
= 1; i
< NPAREN
; i
++) {
1506 if (p
->pbegin
[i
] >= pos
) {
1509 if (p
->pend
[i
] >= pos
) {
1514 memmove((char *)&p
->strip
[pos
+1], (char *)&p
->strip
[pos
],
1515 (HERE()-pos
-1)*sizeof(sop
));
1520 - dofwd - complete a forward reference
1521 == static void dofwd(register struct parse *p, sopno pos, sop value);
1524 dofwd(p
, pos
, value
)
1525 register struct parse
*p
;
1529 /* avoid making error situations worse */
1533 assert(value
< 1<<OPSHIFT
);
1534 p
->strip
[pos
] = OP(p
->strip
[pos
]) | value
;
1538 - enlarge - enlarge the strip
1539 == static void enlarge(register struct parse *p, sopno size);
1543 register struct parse
*p
;
1544 register sopno size
;
1548 if (p
->ssize
>= size
)
1551 sp
= (sop
*)realloc(p
->strip
, size
*sizeof(sop
));
1553 SETERROR(REG_ESPACE
);
1561 - stripsnug - compact the strip
1562 == static void stripsnug(register struct parse *p, register struct re_guts *g);
1566 register struct parse
*p
;
1567 register struct re_guts
*g
;
1569 g
->nstates
= p
->slen
;
1570 g
->strip
= (sop
*)realloc((char *)p
->strip
, p
->slen
* sizeof(sop
));
1571 if (g
->strip
== NULL
) {
1572 SETERROR(REG_ESPACE
);
1573 g
->strip
= p
->strip
;
1578 - findmust - fill in must and mlen with longest mandatory literal string
1579 == static void findmust(register struct parse *p, register struct re_guts *g);
1581 * This algorithm could do fancy things like analyzing the operands of |
1582 * for common subsequences. Someday. This code is simple and finds most
1583 * of the interesting cases.
1585 * Note that must and mlen got initialized during setup.
1590 register struct re_guts
*g
;
1594 register sop
*newstart
;
1595 register sopno newlen
;
1600 /* avoid making error situations worse */
1604 /* find the longest OCHAR sequence in strip */
1606 scan
= g
->strip
+ 1;
1610 case OCHAR
: /* sequence member */
1611 if (newlen
== 0) /* new sequence */
1612 newstart
= scan
- 1;
1615 case OPLUS_
: /* things that don't break one */
1619 case OQUEST_
: /* things that must be skipped */
1625 /* assert() interferes w debug printouts */
1626 if (OP(s
) != O_QUEST
&& OP(s
) != O_CH
&&
1631 } while (OP(s
) != O_QUEST
&& OP(s
) != O_CH
);
1633 default: /* things that break a sequence */
1634 if (newlen
> g
->mlen
) { /* ends one */
1641 } while (OP(s
) != OEND
);
1643 if (g
->mlen
== 0) /* there isn't one */
1646 /* turn it into a character string */
1647 g
->must
= malloc((size_t)g
->mlen
+ 1);
1648 if (g
->must
== NULL
) { /* argh; just forget it */
1654 for (i
= g
->mlen
; i
> 0; i
--) {
1655 while (OP(s
= *scan
++) != OCHAR
)
1657 assert(cp
< g
->must
+ g
->mlen
);
1658 *cp
++ = (char)OPND(s
);
1660 assert(cp
== g
->must
+ g
->mlen
);
1661 *cp
++ = '\0'; /* just on general principles */
1665 - pluscount - count + nesting
1666 == static sopno pluscount(register struct parse *p, register struct re_guts *g);
1668 static sopno
/* nesting depth */
1671 register struct re_guts
*g
;
1675 register sopno plusnest
= 0;
1676 register sopno maxnest
= 0;
1679 return(0); /* there may not be an OEND */
1681 scan
= g
->strip
+ 1;
1689 if (plusnest
> maxnest
)
1694 } while (OP(s
) != OEND
);