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
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 * 4. Neither the name of the University nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * @(#)regcomp.c 8.5 (Berkeley) 3/20/94
38 #if defined(LIBC_SCCS) && !defined(lint)
39 static char sccsid
[] = "@(#)regcomp.c 8.5 (Berkeley) 3/20/94";
40 #endif /* LIBC_SCCS and not lint */
41 #include <sys/cdefs.h>
43 #include <sys/types.h>
60 * parse structure, passed up and down to avoid global variables and
64 char *next
; /* next character in RE */
65 char *end
; /* end of string (-> NUL normally) */
66 int error
; /* has an error been seen? */
67 sop
*strip
; /* malloced strip */
68 sopno ssize
; /* malloced strip size (allocated) */
69 sopno slen
; /* malloced strip length (used) */
70 int ncsalloc
; /* number of csets allocated */
72 # define NPAREN 10 /* we need to remember () 1-9 for back refs */
73 sopno pbegin
[NPAREN
]; /* -> ( ([0] unused) */
74 sopno pend
[NPAREN
]; /* -> ) ([0] unused) */
77 /* ========= begin header generated by ./mkh ========= */
82 /* === regcomp.c === */
83 static void p_ere(struct parse
*p
, int stop
);
84 static void p_ere_exp(struct parse
*p
);
85 static void p_str(struct parse
*p
);
86 static void p_bre(struct parse
*p
, int end1
, int end2
);
87 static int p_simp_re(struct parse
*p
, int starordinary
);
88 static int p_count(struct parse
*p
);
89 static void p_bracket(struct parse
*p
);
90 static void p_b_term(struct parse
*p
, cset
*cs
);
91 static void p_b_cclass(struct parse
*p
, cset
*cs
);
92 static void p_b_eclass(struct parse
*p
, cset
*cs
);
93 static char p_b_symbol(struct parse
*p
);
94 static char p_b_coll_elem(struct parse
*p
, int endc
);
95 static char othercase(int ch
);
96 static void bothcases(struct parse
*p
, int ch
);
97 static void ordinary(struct parse
*p
, int ch
);
98 static void nonnewline(struct parse
*p
);
99 static void repeat(struct parse
*p
, sopno start
, int from
, int to
);
100 static int seterr(struct parse
*p
, int e
);
101 static cset
*allocset(struct parse
*p
);
102 static void freeset(struct parse
*p
, cset
*cs
);
103 static int freezeset(struct parse
*p
, cset
*cs
);
104 static int firstch(struct parse
*p
, cset
*cs
);
105 static int nch(struct parse
*p
, cset
*cs
);
107 static void mcadd(struct parse
*p
, cset
*cs
, char *cp
);
108 static void mcsub(cset
*cs
, char *cp
);
109 static int mcin(cset
*cs
, char *cp
);
110 static char *mcfind(cset
*cs
, char *cp
);
112 static void mcinvert(struct parse
*p
, cset
*cs
);
113 static void mccase(struct parse
*p
, cset
*cs
);
114 static int isinsets(struct re_guts
*g
, int c
);
115 static int samesets(struct re_guts
*g
, int c1
, int c2
);
116 static void categorize(struct parse
*p
, struct re_guts
*g
);
117 static sopno
dupl(struct parse
*p
, sopno start
, sopno finish
);
118 static void doemit(struct parse
*p
, sop op
, size_t opnd
);
119 static void doinsert(struct parse
*p
, sop op
, size_t opnd
, sopno pos
);
120 static void dofwd(struct parse
*p
, sopno pos
, sop value
);
121 static void enlarge(struct parse
*p
, sopno size
);
122 static void stripsnug(struct parse
*p
, struct re_guts
*g
);
123 static void findmust(struct parse
*p
, struct re_guts
*g
);
124 static int altoffset(sop
*scan
, int offset
, int mccs
);
125 static void computejumps(struct parse
*p
, struct re_guts
*g
);
126 static void computematchjumps(struct parse
*p
, struct re_guts
*g
);
127 static sopno
pluscount(struct parse
*p
, struct re_guts
*g
);
132 /* ========= end header generated by ./mkh ========= */
134 static char nuls
[10]; /* place to point scanner in event of error */
137 * macros for use with parse structure
138 * BEWARE: these know that the parse structure is named `p' !!!
140 #define PEEK() (*p->next)
141 #define PEEK2() (*(p->next+1))
142 #define MORE() (p->next < p->end)
143 #define MORE2() (p->next+1 < p->end)
144 #define SEE(c) (MORE() && PEEK() == (c))
145 #define SEETWO(a, b) (MORE() && MORE2() && PEEK() == (a) && PEEK2() == (b))
146 #define EAT(c) ((SEE(c)) ? (NEXT(), 1) : 0)
147 #define EATTWO(a, b) ((SEETWO(a, b)) ? (NEXT2(), 1) : 0)
148 #define NEXT() (p->next++)
149 #define NEXT2() (p->next += 2)
150 #define NEXTn(n) (p->next += (n))
151 #define GETNEXT() (*p->next++)
152 #define SETERROR(e) seterr(p, (e))
153 #define REQUIRE(co, e) ((co) || SETERROR(e))
154 #define MUSTSEE(c, e) (REQUIRE(MORE() && PEEK() == (c), e))
155 #define MUSTEAT(c, e) (REQUIRE(MORE() && GETNEXT() == (c), e))
156 #define MUSTNOTSEE(c, e) (REQUIRE(!MORE() || PEEK() != (c), e))
157 #define EMIT(op, sopnd) doemit(p, (sop)(op), (size_t)(sopnd))
158 #define INSERT(op, pos) doinsert(p, (sop)(op), HERE()-(pos)+1, pos)
159 #define AHEAD(pos) dofwd(p, pos, HERE()-(pos))
160 #define ASTERN(sop, pos) EMIT(sop, HERE()-pos)
161 #define HERE() (p->slen)
162 #define THERE() (p->slen - 1)
163 #define THERETHERE() (p->slen - 2)
164 #define DROP(n) (p->slen -= (n))
167 static int never
= 0; /* for use in asserts; shuts lint up */
169 #define never 0 /* some <assert.h>s have bugs too */
172 /* Macro used by computejump()/computematchjump() */
173 #define MIN(a,b) ((a)<(b)?(a):(b))
176 - regcomp - interface for parser and compilation
177 = extern int regcomp(regex_t *__restrict, const char *__restrict, int);
178 = #define REG_BASIC 0000
179 = #define REG_EXTENDED 0001
180 = #define REG_ICASE 0002
181 = #define REG_NOSUB 0004
182 = #define REG_NEWLINE 0010
183 = #define REG_NOSPEC 0020
184 = #define REG_PEND 0040
185 = #define REG_DUMP 0200
187 int /* 0 success, otherwise REG_something */
188 regcomp(preg
, pattern
, cflags
)
189 regex_t
*__restrict preg
;
190 const char *__restrict pattern
;
195 struct parse
*p
= &pa
;
199 # define GOODFLAGS(f) (f)
201 # define GOODFLAGS(f) ((f)&~REG_DUMP)
204 cflags
= GOODFLAGS(cflags
);
205 if ((cflags
®_EXTENDED
) && (cflags
®_NOSPEC
))
208 if (cflags
®_PEND
) {
209 if (preg
->re_endp
< pattern
)
211 len
= preg
->re_endp
- pattern
;
213 len
= strlen((char *)pattern
);
215 /* do the mallocs early so failure handling is easy */
216 g
= (struct re_guts
*)malloc(sizeof(struct re_guts
) +
217 (NC
-1)*sizeof(cat_t
));
220 p
->ssize
= len
/(size_t)2*(size_t)3 + (size_t)1; /* ugh */
221 p
->strip
= (sop
*)malloc(p
->ssize
* sizeof(sop
));
223 if (p
->strip
== NULL
) {
230 p
->next
= (char *)pattern
; /* convenience; we do not modify it */
231 p
->end
= p
->next
+ len
;
234 for (i
= 0; i
< NPAREN
; i
++) {
252 g
->ncategories
= 1; /* category 0 is "everything else" */
253 g
->categories
= &g
->catspace
[-(CHAR_MIN
)];
254 (void) memset((char *)g
->catspace
, 0, NC
*sizeof(cat_t
));
259 g
->firststate
= THERE();
260 if (cflags
®_EXTENDED
)
262 else if (cflags
®_NOSPEC
)
267 g
->laststate
= THERE();
269 /* tidy up loose ends and fill things in */
273 /* only use Boyer-Moore algorithm if the pattern is bigger
274 * than three characters
278 computematchjumps(p
, g
);
279 if(g
->matchjump
== NULL
&& g
->charjump
!= NULL
) {
284 g
->nplus
= pluscount(p
, g
);
286 preg
->re_nsub
= g
->nsub
;
288 preg
->re_magic
= MAGIC1
;
290 /* not debugging, so can't rely on the assert() in regexec() */
292 SETERROR(REG_ASSERT
);
295 /* win or lose, we're done */
296 if (p
->error
!= 0) /* lose */
302 - p_ere - ERE parser top level, concatenation and alternation
303 == static void p_ere(struct parse *p, int stop);
308 int stop
/* character this ERE should end at */
315 int first
= 1; /* is this the first alternative? */
318 /* do a bunch of concatenated expressions */
320 while (MORE() && (c
= PEEK()) != '|' && c
!= stop
)
322 (void)REQUIRE(HERE() != conc
, REG_EMPTY
); /* require nonempty */
325 break; /* NOTE BREAK OUT */
328 INSERT(OCH_
, conc
); /* offset is wrong */
333 ASTERN(OOR1
, prevback
);
335 AHEAD(prevfwd
); /* fix previous offset */
337 EMIT(OOR2
, 0); /* offset is very wrong */
340 if (!first
) { /* tail-end fixups */
342 ASTERN(O_CH
, prevback
);
345 assert(!MORE() || SEE(stop
));
349 - p_ere_exp - parse one subERE, an atom possibly followed by a repetition op
350 == static void p_ere_exp(struct parse *p);
353 p_ere_exp(struct parse
*p
)
362 assert(MORE()); /* caller should have ensured this */
368 (void)REQUIRE(MORE(), REG_EPAREN
);
372 p
->pbegin
[subno
] = HERE();
373 EMIT(OLPAREN
, subno
);
376 if (subno
< NPAREN
) {
377 p
->pend
[subno
] = HERE();
378 assert(p
->pend
[subno
] != 0);
380 EMIT(ORPAREN
, subno
);
381 (void)MUSTEAT(')', REG_EPAREN
);
383 #ifndef POSIX_MISTAKE
384 case ')': /* happens only if no current unmatched ( */
386 * You may ask, why the ifndef? Because I didn't notice
387 * this until slightly too late for 1003.2, and none of the
388 * other 1003.2 regular-expression reviewers noticed it at
389 * all. So an unmatched ) is legal POSIX, at least until
390 * we can get it fixed.
392 SETERROR(REG_EPAREN
);
397 p
->g
->iflags
|= USEBOL
;
403 p
->g
->iflags
|= USEEOL
;
412 SETERROR(REG_BADRPT
);
415 if (p
->g
->cflags
®_NEWLINE
)
424 (void)REQUIRE(MORE(), REG_EESCAPE
);
428 case '{': /* okay as ordinary except if digit follows */
429 (void)REQUIRE(!MORE() || !isdigit((uch
)PEEK()), REG_BADRPT
);
439 /* we call { a repetition if followed by a digit */
440 if (!( c
== '*' || c
== '+' || c
== '?' ||
441 (c
== '{' && MORE2() && isdigit((uch
)PEEK2())) ))
442 return; /* no repetition, we're done */
445 (void)REQUIRE(!wascaret
, REG_BADRPT
);
447 case '*': /* implemented as +? */
448 /* this case does not require the (y|) trick, noKLUDGE */
451 INSERT(OQUEST_
, pos
);
452 ASTERN(O_QUEST
, pos
);
459 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
460 INSERT(OCH_
, pos
); /* offset slightly wrong */
461 ASTERN(OOR1
, pos
); /* this one's right */
462 AHEAD(pos
); /* fix the OCH_ */
463 EMIT(OOR2
, 0); /* offset very wrong... */
464 AHEAD(THERE()); /* ...so fix it */
465 ASTERN(O_CH
, THERETHERE());
470 if (isdigit((uch
)PEEK())) {
472 (void)REQUIRE(count
<= count2
, REG_BADBR
);
473 } else /* single number with comma */
475 } else /* just a single number */
477 repeat(p
, pos
, count
, count2
);
478 if (!EAT('}')) { /* error heuristics */
479 while (MORE() && PEEK() != '}')
481 (void)REQUIRE(MORE(), REG_EBRACE
);
490 if (!( c
== '*' || c
== '+' || c
== '?' ||
491 (c
== '{' && MORE2() && isdigit((uch
)PEEK2())) ) )
493 SETERROR(REG_BADRPT
);
497 - p_str - string (no metacharacters) "parser"
498 == static void p_str(struct parse *p);
501 p_str(struct parse
*p
)
503 (void)REQUIRE(MORE(), REG_EMPTY
);
505 ordinary(p
, GETNEXT());
509 - p_bre - BRE parser top level, anchoring and concatenation
510 == static void p_bre(struct parse *p, int end1, \
512 * Giving end1 as OUT essentially eliminates the end1/end2 check.
514 * This implementation is a bit of a kludge, in that a trailing $ is first
515 * taken as an ordinary character and then revised to be an anchor. The
516 * only undesirable side effect is that '$' gets included as a character
517 * category in such cases. This is fairly harmless; not worth fixing.
518 * The amount of lookahead needed to avoid this kludge is excessive.
523 int end1
, /* first terminating character */
524 int end2
/* second terminating character */
527 sopno start
= HERE();
528 int first
= 1; /* first subexpression? */
533 p
->g
->iflags
|= USEBOL
;
536 while (MORE() && !SEETWO(end1
, end2
)) {
537 wasdollar
= p_simp_re(p
, first
);
540 if (wasdollar
) { /* oops, that was a trailing anchor */
543 p
->g
->iflags
|= USEEOL
;
547 (void)REQUIRE(HERE() != start
, REG_EMPTY
); /* require nonempty */
551 - p_simp_re - parse a simple RE, an atom possibly followed by a repetition
552 == static int p_simp_re(struct parse *p, int starordinary);
554 static int /* was the simple RE an unbackslashed $? */
557 int starordinary
/* is a leading * an ordinary character? */
566 # define BACKSL (1<<CHAR_BIT)
568 pos
= HERE(); /* repetion op, if any, covers from here */
570 assert(MORE()); /* caller should have ensured this */
573 (void)REQUIRE(MORE(), REG_EESCAPE
);
574 c
= BACKSL
| GETNEXT();
578 if (p
->g
->cflags
®_NEWLINE
)
587 SETERROR(REG_BADRPT
);
593 p
->pbegin
[subno
] = HERE();
594 EMIT(OLPAREN
, subno
);
595 /* the MORE here is an error heuristic */
596 if (MORE() && !SEETWO('\\', ')'))
598 if (subno
< NPAREN
) {
599 p
->pend
[subno
] = HERE();
600 assert(p
->pend
[subno
] != 0);
602 EMIT(ORPAREN
, subno
);
603 (void)REQUIRE(EATTWO('\\', ')'), REG_EPAREN
);
605 case BACKSL
|')': /* should not get here -- must be user */
607 SETERROR(REG_EPAREN
);
618 i
= (c
&~BACKSL
) - '0';
620 if (p
->pend
[i
] != 0) {
621 assert(i
<= p
->g
->nsub
);
623 assert(p
->pbegin
[i
] != 0);
624 assert(OP(p
->strip
[p
->pbegin
[i
]]) == OLPAREN
);
625 assert(OP(p
->strip
[p
->pend
[i
]]) == ORPAREN
);
626 (void) dupl(p
, p
->pbegin
[i
]+1, p
->pend
[i
]);
629 SETERROR(REG_ESUBREG
);
633 (void)REQUIRE(starordinary
, REG_BADRPT
);
636 ordinary(p
, (char)c
);
640 if (EAT('*')) { /* implemented as +? */
641 /* this case does not require the (y|) trick, noKLUDGE */
644 INSERT(OQUEST_
, pos
);
645 ASTERN(O_QUEST
, pos
);
646 } else if (EATTWO('\\', '{')) {
649 if (MORE() && isdigit((uch
)PEEK())) {
651 (void)REQUIRE(count
<= count2
, REG_BADBR
);
652 } else /* single number with comma */
654 } else /* just a single number */
656 repeat(p
, pos
, count
, count2
);
657 if (!EATTWO('\\', '}')) { /* error heuristics */
658 while (MORE() && !SEETWO('\\', '}'))
660 (void)REQUIRE(MORE(), REG_EBRACE
);
663 } else if (c
== '$') /* $ (but not \$) ends it */
670 - p_count - parse a repetition count
671 == static int p_count(struct parse *p);
673 static int /* the value */
674 p_count(struct parse
*p
)
679 while (MORE() && isdigit((uch
)PEEK()) && count
<= DUPMAX
) {
680 count
= count
*10 + (GETNEXT() - '0');
684 (void)REQUIRE(ndigits
> 0 && count
<= DUPMAX
, REG_BADBR
);
689 - p_bracket - parse a bracketed character list
690 == static void p_bracket(struct parse *p);
692 * Note a significant property of this code: if the allocset() did SETERROR,
693 * no set operations are done.
696 p_bracket(struct parse
*p
)
698 cset
*cs
= allocset(p
);
701 /* Dept of Truly Sickening Special-Case Kludges */
702 if (p
->next
+ 5 < p
->end
&& strncmp(p
->next
, "[:<:]]", 6) == 0) {
707 if (p
->next
+ 5 < p
->end
&& strncmp(p
->next
, "[:>:]]", 6) == 0) {
714 invert
++; /* make note to invert set at end */
719 while (MORE() && PEEK() != ']' && !SEETWO('-', ']'))
723 (void)MUSTEAT(']', REG_EBRACK
);
725 if (p
->error
!= 0) /* don't mess things up further */
728 if (p
->g
->cflags
®_ICASE
) {
732 for (i
= p
->g
->csetsize
- 1; i
>= 0; i
--)
733 if (CHIN(cs
, i
) && isalpha(i
)) {
738 if (cs
->multis
!= NULL
)
744 for (i
= p
->g
->csetsize
- 1; i
>= 0; i
--)
749 if (p
->g
->cflags
®_NEWLINE
)
751 if (cs
->multis
!= NULL
)
755 assert(cs
->multis
== NULL
); /* xxx */
757 if (nch(p
, cs
) == 1) { /* optimize singleton sets */
758 ordinary(p
, firstch(p
, cs
));
761 EMIT(OANYOF
, freezeset(p
, cs
));
765 - p_b_term - parse one term of a bracketed character list
766 == static void p_b_term(struct parse *p, cset *cs);
778 /* classify what we've got */
779 switch ((MORE()) ? PEEK() : '\0') {
781 c
= (MORE2()) ? PEEK2() : '\0';
784 SETERROR(REG_ERANGE
);
785 return; /* NOTE RETURN */
793 case ':': /* character class */
795 (void)REQUIRE(MORE(), REG_EBRACK
);
797 (void)REQUIRE(c
!= '-' && c
!= ']', REG_ECTYPE
);
799 (void)REQUIRE(MORE(), REG_EBRACK
);
800 (void)REQUIRE(EATTWO(':', ']'), REG_ECTYPE
);
802 case '=': /* equivalence class */
804 (void)REQUIRE(MORE(), REG_EBRACK
);
806 (void)REQUIRE(c
!= '-' && c
!= ']', REG_ECOLLATE
);
808 (void)REQUIRE(MORE(), REG_EBRACK
);
809 (void)REQUIRE(EATTWO('=', ']'), REG_ECOLLATE
);
811 default: /* symbol, ordinary character, or range */
812 /* xxx revision needed for multichar stuff */
813 start
= p_b_symbol(p
);
814 if (SEE('-') && MORE2() && PEEK2() != ']') {
820 finish
= p_b_symbol(p
);
826 if (__collate_load_error
) {
827 (void)REQUIRE((uch
)start
<= (uch
)finish
, REG_ERANGE
);
828 for (i
= (uch
)start
; i
<= (uch
)finish
; i
++)
831 (void)REQUIRE(__collate_range_cmp(start
, finish
) <= 0, REG_ERANGE
);
832 for (i
= CHAR_MIN
; i
<= CHAR_MAX
; i
++) {
833 if ( __collate_range_cmp(start
, i
) <= 0
834 && __collate_range_cmp(i
, finish
) <= 0
845 - p_b_cclass - parse a character-class name and deal with it
846 == static void p_b_cclass(struct parse *p, cset *cs);
859 while (MORE() && isalpha((uch
)PEEK()))
862 for (cp
= cclasses
; cp
->name
!= NULL
; cp
++)
863 if (strncmp(cp
->name
, sp
, len
) == 0 && cp
->name
[len
] == '\0')
865 if (cp
->name
== NULL
) {
866 /* oops, didn't find it */
867 SETERROR(REG_ECTYPE
);
873 for (c
= CHAR_MIN
; c
<= CHAR_MAX
; c
++)
878 for (c
= CHAR_MIN
; c
<= CHAR_MAX
; c
++)
883 for (c
= CHAR_MIN
; c
<= CHAR_MAX
; c
++)
888 for (c
= CHAR_MIN
; c
<= CHAR_MAX
; c
++)
893 for (c
= CHAR_MIN
; c
<= CHAR_MAX
; c
++)
898 for (c
= CHAR_MIN
; c
<= CHAR_MAX
; c
++)
903 for (c
= CHAR_MIN
; c
<= CHAR_MAX
; c
++)
908 for (c
= CHAR_MIN
; c
<= CHAR_MAX
; c
++)
913 for (c
= CHAR_MIN
; c
<= CHAR_MAX
; c
++)
918 for (c
= CHAR_MIN
; c
<= CHAR_MAX
; c
++)
923 for (c
= CHAR_MIN
; c
<= CHAR_MAX
; c
++)
928 for (c
= CHAR_MIN
; c
<= CHAR_MAX
; c
++)
929 if (isxdigit((uch
)c
))
934 for (u
= cp
->multis
; *u
!= '\0'; u
+= strlen(u
) + 1)
940 - p_b_eclass - parse an equivalence-class name and deal with it
941 == static void p_b_eclass(struct parse *p, cset *cs);
943 * This implementation is incomplete. xxx
953 c
= p_b_coll_elem(p
, '=');
958 - p_b_symbol - parse a character or [..]ed multicharacter collating symbol
959 == static char p_b_symbol(struct parse *p);
961 static char /* value of symbol */
962 p_b_symbol(struct parse
*p
)
966 (void)REQUIRE(MORE(), REG_EBRACK
);
967 if (!EATTWO('[', '.'))
970 /* collating symbol */
971 value
= p_b_coll_elem(p
, '.');
972 (void)REQUIRE(EATTWO('.', ']'), REG_ECOLLATE
);
977 - p_b_coll_elem - parse a collating-element name and look it up
978 == static char p_b_coll_elem(struct parse *p, int endc);
980 static char /* value of collating element */
983 int endc
/* name ended by endc,']' */
990 while (MORE() && !SEETWO(endc
, ']'))
993 SETERROR(REG_EBRACK
);
997 for (cp
= cnames
; cp
->name
!= NULL
; cp
++)
998 if (strncmp(cp
->name
, sp
, len
) == 0 && cp
->name
[len
] == '\0')
999 return(cp
->code
); /* known name */
1001 return(*sp
); /* single character */
1002 SETERROR(REG_ECOLLATE
); /* neither */
1007 - othercase - return the case counterpart of an alphabetic
1008 == static char othercase(int ch);
1010 static char /* if no counterpart, return ch */
1016 assert(isalpha(ch
));
1018 return(tolower(ch
));
1019 else if (islower(ch
))
1020 return(toupper(ch
));
1021 else /* peculiar, but could happen */
1026 - bothcases - emit a dualcase version of a two-case character
1027 == static void bothcases(struct parse *p, int ch);
1029 * Boy, is this implementation ever a kludge...
1037 char *oldnext
= p
->next
;
1038 char *oldend
= p
->end
;
1042 assert(othercase(ch
) != ch
); /* p_bracket() would recurse */
1049 assert(p
->next
== bracket
+2);
1055 - ordinary - emit an ordinary character
1056 == static void ordinary(struct parse *p, int ch);
1064 cat_t
*cap
= p
->g
->categories
;
1066 if ((p
->g
->cflags
®_ICASE
) && isalpha((uch
)ch
) && othercase(ch
) != ch
)
1069 EMIT(OCHAR
, (uch
)ch
);
1071 cap
[ch
] = p
->g
->ncategories
++;
1076 - nonnewline - emit REG_NEWLINE version of OANY
1077 == static void nonnewline(struct parse *p);
1079 * Boy, is this implementation ever a kludge...
1086 char *oldnext
= p
->next
;
1087 char *oldend
= p
->end
;
1097 assert(p
->next
== bracket
+3);
1103 - repeat - generate code for a bounded repetition, recursively if needed
1104 == static void repeat(struct parse *p, sopno start, int from, int to);
1109 sopno start
, /* operand from here to end of strip */
1110 int from
, /* repeated from this number */
1111 int to
/* to this number of times (maybe INFINITY) */
1114 sopno finish
= HERE();
1117 # define REP(f, t) ((f)*8 + (t))
1118 # define MAP(n) (((n) <= 1) ? (n) : ((n) == INFINITY) ? INF : N)
1121 if (p
->error
!= 0) /* head off possible runaway recursion */
1126 switch (REP(MAP(from
), MAP(to
))) {
1127 case REP(0, 0): /* must be user doing this */
1128 DROP(finish
-start
); /* drop the operand */
1130 case REP(0, 1): /* as x{1,1}? */
1131 case REP(0, N
): /* as x{1,n}? */
1132 case REP(0, INF
): /* as x{1,}? */
1133 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
1134 INSERT(OCH_
, start
); /* offset is wrong... */
1135 repeat(p
, start
+1, 1, to
);
1136 ASTERN(OOR1
, start
);
1137 AHEAD(start
); /* ... fix it */
1140 ASTERN(O_CH
, THERETHERE());
1142 case REP(1, 1): /* trivial case */
1145 case REP(1, N
): /* as x?x{1,n-1} */
1146 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
1147 INSERT(OCH_
, start
);
1148 ASTERN(OOR1
, start
);
1150 EMIT(OOR2
, 0); /* offset very wrong... */
1151 AHEAD(THERE()); /* ...so fix it */
1152 ASTERN(O_CH
, THERETHERE());
1153 copy
= dupl(p
, start
+1, finish
+1);
1154 assert(copy
== finish
+4);
1155 repeat(p
, copy
, 1, to
-1);
1157 case REP(1, INF
): /* as x+ */
1158 INSERT(OPLUS_
, start
);
1159 ASTERN(O_PLUS
, start
);
1161 case REP(N
, N
): /* as xx{m-1,n-1} */
1162 copy
= dupl(p
, start
, finish
);
1163 repeat(p
, copy
, from
-1, to
-1);
1165 case REP(N
, INF
): /* as xx{n-1,INF} */
1166 copy
= dupl(p
, start
, finish
);
1167 repeat(p
, copy
, from
-1, to
);
1169 default: /* "can't happen" */
1170 SETERROR(REG_ASSERT
); /* just in case */
1176 - seterr - set an error condition
1177 == static int seterr(struct parse *p, int e);
1179 static int /* useless but makes type checking happy */
1185 if (p
->error
== 0) /* keep earliest error condition */
1187 p
->next
= nuls
; /* try to bring things to a halt */
1189 return(0); /* make the return value well-defined */
1193 - allocset - allocate a set of characters for []
1194 == static cset *allocset(struct parse *p);
1197 allocset(struct parse
*p
)
1199 int no
= p
->g
->ncsets
++;
1203 size_t css
= (size_t)p
->g
->csetsize
;
1206 if (no
>= p
->ncsalloc
) { /* need another column of space */
1207 p
->ncsalloc
+= CHAR_BIT
;
1209 assert(nc
% CHAR_BIT
== 0);
1210 nbytes
= nc
/ CHAR_BIT
* css
;
1211 if (p
->g
->sets
== NULL
)
1212 p
->g
->sets
= (cset
*)malloc(nc
* sizeof(cset
));
1214 p
->g
->sets
= (cset
*)reallocf((char *)p
->g
->sets
,
1216 if (p
->g
->setbits
== NULL
)
1217 p
->g
->setbits
= (uch
*)malloc(nbytes
);
1219 p
->g
->setbits
= (uch
*)reallocf((char *)p
->g
->setbits
,
1221 /* xxx this isn't right if setbits is now NULL */
1222 for (i
= 0; i
< no
; i
++)
1223 p
->g
->sets
[i
].ptr
= p
->g
->setbits
+ css
*(i
/CHAR_BIT
);
1225 if (p
->g
->sets
!= NULL
&& p
->g
->setbits
!= NULL
)
1226 (void) memset((char *)p
->g
->setbits
+ (nbytes
- css
),
1230 SETERROR(REG_ESPACE
);
1231 /* caller's responsibility not to do set ops */
1235 assert(p
->g
->sets
!= NULL
); /* xxx */
1236 cs
= &p
->g
->sets
[no
];
1237 cs
->ptr
= p
->g
->setbits
+ css
*((no
)/CHAR_BIT
);
1238 cs
->mask
= 1 << ((no
) % CHAR_BIT
);
1247 - freeset - free a now-unused set
1248 == static void freeset(struct parse *p, cset *cs);
1257 cset
*top
= &p
->g
->sets
[p
->g
->ncsets
];
1258 size_t css
= (size_t)p
->g
->csetsize
;
1260 for (i
= 0; i
< css
; i
++)
1262 if (cs
== top
-1) /* recover only the easy case */
1267 - freezeset - final processing on a set of characters
1268 == static int freezeset(struct parse *p, cset *cs);
1270 * The main task here is merging identical sets. This is usually a waste
1271 * of time (although the hash code minimizes the overhead), but can win
1272 * big if REG_ICASE is being used. REG_ICASE, by the way, is why the hash
1273 * is done using addition rather than xor -- all ASCII [aA] sets xor to
1276 static int /* set number */
1284 cset
*top
= &p
->g
->sets
[p
->g
->ncsets
];
1286 size_t css
= (size_t)p
->g
->csetsize
;
1288 /* look for an earlier one which is the same */
1289 for (cs2
= &p
->g
->sets
[0]; cs2
< top
; cs2
++)
1290 if (cs2
->hash
== h
&& cs2
!= cs
) {
1292 for (i
= 0; i
< css
; i
++)
1293 if (!!CHIN(cs2
, i
) != !!CHIN(cs
, i
))
1299 if (cs2
< top
) { /* found one */
1304 return((int)(cs
- p
->g
->sets
));
1308 - firstch - return first character in a set (which must have at least one)
1309 == static int firstch(struct parse *p, cset *cs);
1311 static int /* character; there is no "none" value */
1318 size_t css
= (size_t)p
->g
->csetsize
;
1320 for (i
= 0; i
< css
; i
++)
1324 return(0); /* arbitrary */
1328 - nch - number of characters in a set
1329 == static int nch(struct parse *p, cset *cs);
1338 size_t css
= (size_t)p
->g
->csetsize
;
1341 for (i
= 0; i
< css
; i
++)
1349 - mcadd - add a collating element to a cset
1350 == static void mcadd(struct parse *p, cset *cs, \
1359 size_t oldend
= cs
->smultis
;
1361 cs
->smultis
+= strlen(cp
) + 1;
1362 if (cs
->multis
== NULL
)
1363 cs
->multis
= malloc(cs
->smultis
);
1365 cs
->multis
= reallocf(cs
->multis
, cs
->smultis
);
1366 if (cs
->multis
== NULL
) {
1367 SETERROR(REG_ESPACE
);
1371 (void) strcpy(cs
->multis
+ oldend
- 1, cp
);
1372 cs
->multis
[cs
->smultis
- 1] = '\0';
1376 - mcsub - subtract a collating element from a cset
1377 == static void mcsub(cset *cs, char *cp);
1384 char *fp
= mcfind(cs
, cp
);
1385 size_t len
= strlen(fp
);
1388 (void) memmove(fp
, fp
+ len
+ 1,
1389 cs
->smultis
- (fp
+ len
+ 1 - cs
->multis
));
1392 if (cs
->smultis
== 0) {
1398 cs
->multis
= reallocf(cs
->multis
, cs
->smultis
);
1399 assert(cs
->multis
!= NULL
);
1403 - mcin - is a collating element in a cset?
1404 == static int mcin(cset *cs, char *cp);
1411 return(mcfind(cs
, cp
) != NULL
);
1415 - mcfind - find a collating element in a cset
1416 == static char *mcfind(cset *cs, char *cp);
1425 if (cs
->multis
== NULL
)
1427 for (p
= cs
->multis
; *p
!= '\0'; p
+= strlen(p
) + 1)
1428 if (strcmp(cp
, p
) == 0)
1435 - mcinvert - invert the list of collating elements in a cset
1436 == static void mcinvert(struct parse *p, cset *cs);
1438 * This would have to know the set of possibilities. Implementation
1447 assert(cs
->multis
== NULL
); /* xxx */
1451 - mccase - add case counterparts of the list of collating elements in a cset
1452 == static void mccase(struct parse *p, cset *cs);
1454 * This would have to know the set of possibilities. Implementation
1463 assert(cs
->multis
== NULL
); /* xxx */
1467 - isinsets - is this character in any sets?
1468 == static int isinsets(struct re_guts *g, int c);
1470 static int /* predicate */
1478 int ncols
= (g
->ncsets
+(CHAR_BIT
-1)) / CHAR_BIT
;
1479 unsigned uc
= (uch
)c
;
1481 for (i
= 0, col
= g
->setbits
; i
< ncols
; i
++, col
+= g
->csetsize
)
1488 - samesets - are these two characters in exactly the same sets?
1489 == static int samesets(struct re_guts *g, int c1, int c2);
1491 static int /* predicate */
1500 int ncols
= (g
->ncsets
+(CHAR_BIT
-1)) / CHAR_BIT
;
1501 unsigned uc1
= (uch
)c1
;
1502 unsigned uc2
= (uch
)c2
;
1504 for (i
= 0, col
= g
->setbits
; i
< ncols
; i
++, col
+= g
->csetsize
)
1505 if (col
[uc1
] != col
[uc2
])
1511 - categorize - sort out character categories
1512 == static void categorize(struct parse *p, struct re_guts *g);
1520 cat_t
*cats
= g
->categories
;
1525 /* avoid making error situations worse */
1529 for (c
= CHAR_MIN
; c
<= CHAR_MAX
; c
++)
1530 if (cats
[c
] == 0 && isinsets(g
, c
)) {
1531 cat
= g
->ncategories
++;
1533 for (c2
= c
+1; c2
<= CHAR_MAX
; c2
++)
1534 if (cats
[c2
] == 0 && samesets(g
, c
, c2
))
1540 - dupl - emit a duplicate of a bunch of sops
1541 == static sopno dupl(struct parse *p, sopno start, sopno finish);
1543 static sopno
/* start of duplicate */
1546 sopno start
, /* from here */
1547 sopno finish
/* to this less one */
1551 sopno len
= finish
- start
;
1553 assert(finish
>= start
);
1556 enlarge(p
, p
->ssize
+ len
); /* this many unexpected additions */
1557 assert(p
->ssize
>= p
->slen
+ len
);
1558 (void) memcpy((char *)(p
->strip
+ p
->slen
),
1559 (char *)(p
->strip
+ start
), (size_t)len
*sizeof(sop
));
1565 - doemit - emit a strip operator
1566 == static void doemit(struct parse *p, sop op, size_t opnd);
1568 * It might seem better to implement this as a macro with a function as
1569 * hard-case backup, but it's just too big and messy unless there are
1570 * some changes to the data structures. Maybe later.
1579 /* avoid making error situations worse */
1583 /* deal with oversize operands ("can't happen", more or less) */
1584 assert(opnd
< 1<<OPSHIFT
);
1586 /* deal with undersized strip */
1587 if (p
->slen
>= p
->ssize
)
1588 enlarge(p
, (p
->ssize
+1) / 2 * 3); /* +50% */
1589 assert(p
->slen
< p
->ssize
);
1591 /* finally, it's all reduced to the easy case */
1592 p
->strip
[p
->slen
++] = SOP(op
, opnd
);
1596 - doinsert - insert a sop into the strip
1597 == static void doinsert(struct parse *p, sop op, size_t opnd, sopno pos);
1611 /* avoid making error situations worse */
1616 EMIT(op
, opnd
); /* do checks, ensure space */
1617 assert(HERE() == sn
+1);
1620 /* adjust paren pointers */
1622 for (i
= 1; i
< NPAREN
; i
++) {
1623 if (p
->pbegin
[i
] >= pos
) {
1626 if (p
->pend
[i
] >= pos
) {
1631 memmove((char *)&p
->strip
[pos
+1], (char *)&p
->strip
[pos
],
1632 (HERE()-pos
-1)*sizeof(sop
));
1637 - dofwd - complete a forward reference
1638 == static void dofwd(struct parse *p, sopno pos, sop value);
1647 /* avoid making error situations worse */
1651 assert(value
< 1<<OPSHIFT
);
1652 p
->strip
[pos
] = OP(p
->strip
[pos
]) | value
;
1656 - enlarge - enlarge the strip
1657 == static void enlarge(struct parse *p, sopno size);
1667 if (p
->ssize
>= size
)
1670 sp
= (sop
*)realloc(p
->strip
, size
*sizeof(sop
));
1672 SETERROR(REG_ESPACE
);
1680 - stripsnug - compact the strip
1681 == static void stripsnug(struct parse *p, struct re_guts *g);
1689 g
->nstates
= p
->slen
;
1690 g
->strip
= (sop
*)realloc((char *)p
->strip
, p
->slen
* sizeof(sop
));
1691 if (g
->strip
== NULL
) {
1692 SETERROR(REG_ESPACE
);
1693 g
->strip
= p
->strip
;
1698 - findmust - fill in must and mlen with longest mandatory literal string
1699 == static void findmust(struct parse *p, struct re_guts *g);
1701 * This algorithm could do fancy things like analyzing the operands of |
1702 * for common subsequences. Someday. This code is simple and finds most
1703 * of the interesting cases.
1705 * Note that must and mlen got initialized during setup.
1715 sop
*newstart
= NULL
;
1723 /* avoid making error situations worse */
1727 /* Find out if we can handle OANYOF or not */
1729 for (cs
= 0; cs
< g
->ncsets
; cs
++)
1730 if (g
->sets
[cs
].multis
!= NULL
)
1733 /* find the longest OCHAR sequence in strip */
1737 scan
= g
->strip
+ 1;
1741 case OCHAR
: /* sequence member */
1742 if (newlen
== 0) /* new sequence */
1743 newstart
= scan
- 1;
1746 case OPLUS_
: /* things that don't break one */
1750 case OQUEST_
: /* things that must be skipped */
1752 offset
= altoffset(scan
, offset
, mccs
);
1757 /* assert() interferes w debug printouts */
1758 if (OP(s
) != O_QUEST
&& OP(s
) != O_CH
&&
1763 } while (OP(s
) != O_QUEST
&& OP(s
) != O_CH
);
1765 case OBOW
: /* things that break a sequence */
1772 if (newlen
> g
->mlen
) { /* ends one */
1776 g
->moffset
+= offset
;
1779 g
->moffset
= offset
;
1787 if (newlen
> g
->mlen
) { /* ends one */
1791 g
->moffset
+= offset
;
1794 g
->moffset
= offset
;
1803 case OANYOF
: /* may or may not invalidate offset */
1804 /* First, everything as OANY */
1805 if (newlen
> g
->mlen
) { /* ends one */
1809 g
->moffset
+= offset
;
1812 g
->moffset
= offset
;
1820 /* And, now, if we found out we can't deal with
1821 * it, make offset = -1.
1827 /* Anything here makes it impossible or too hard
1828 * to calculate the offset -- so we give up;
1829 * save the last known good offset, in case the
1830 * must sequence doesn't occur later.
1832 if (newlen
> g
->mlen
) { /* ends one */
1836 g
->moffset
+= offset
;
1838 g
->moffset
= offset
;
1844 } while (OP(s
) != OEND
);
1846 if (g
->mlen
== 0) { /* there isn't one */
1851 /* turn it into a character string */
1852 g
->must
= malloc((size_t)g
->mlen
+ 1);
1853 if (g
->must
== NULL
) { /* argh; just forget it */
1860 for (i
= g
->mlen
; i
> 0; i
--) {
1861 while (OP(s
= *scan
++) != OCHAR
)
1863 assert(cp
< g
->must
+ g
->mlen
);
1864 *cp
++ = (char)OPND(s
);
1866 assert(cp
== g
->must
+ g
->mlen
);
1867 *cp
++ = '\0'; /* just on general principles */
1871 - altoffset - choose biggest offset among multiple choices
1872 == static int altoffset(sop *scan, int offset, int mccs);
1874 * Compute, recursively if necessary, the largest offset among multiple
1888 /* If we gave up already on offsets, return */
1895 while (OP(s
) != O_QUEST
&& OP(s
) != O_CH
) {
1904 try = altoffset(scan
, try, mccs
);
1911 if (OP(s
) != O_QUEST
&& OP(s
) != O_CH
&&
1914 } while (OP(s
) != O_QUEST
&& OP(s
) != O_CH
);
1915 /* We must skip to the next position, or we'll
1916 * leave altoffset() too early.
1944 return largest
+offset
;
1948 - computejumps - compute char jumps for BM scan
1949 == static void computejumps(struct parse *p, struct re_guts *g);
1951 * This algorithm assumes g->must exists and is has size greater than
1952 * zero. It's based on the algorithm found on Computer Algorithms by
1955 * A char jump is the number of characters one needs to jump based on
1956 * the value of the character from the text that was mismatched.
1967 /* Avoid making errors worse */
1971 g
->charjump
= (int*) malloc((NC
+ 1) * sizeof(int));
1972 if (g
->charjump
== NULL
) /* Not a fatal error */
1974 /* Adjust for signed chars, if necessary */
1975 g
->charjump
= &g
->charjump
[-(CHAR_MIN
)];
1977 /* If the character does not exist in the pattern, the jump
1978 * is equal to the number of characters in the pattern.
1980 for (ch
= CHAR_MIN
; ch
< (CHAR_MAX
+ 1); ch
++)
1981 g
->charjump
[ch
] = g
->mlen
;
1983 /* If the character does exist, compute the jump that would
1984 * take us to the last character in the pattern equal to it
1985 * (notice that we match right to left, so that last character
1986 * is the first one that would be matched).
1988 for (mindex
= 0; mindex
< g
->mlen
; mindex
++)
1989 g
->charjump
[(unsigned char) g
->must
[mindex
]] = g
->mlen
- mindex
- 1;
1993 - computematchjumps - compute match jumps for BM scan
1994 == static void computematchjumps(struct parse *p, struct re_guts *g);
1996 * This algorithm assumes g->must exists and is has size greater than
1997 * zero. It's based on the algorithm found on Computer Algorithms by
2000 * A match jump is the number of characters one needs to advance based
2001 * on the already-matched suffix.
2002 * Notice that all values here are minus (g->mlen-1), because of the way
2003 * the search algorithm works.
2011 int mindex
; /* General "must" iterator */
2012 int suffix
; /* Keeps track of matching suffix */
2013 int ssuffix
; /* Keeps track of suffixes' suffix */
2014 int* pmatches
; /* pmatches[k] points to the next i
2015 * such that i+1...mlen is a substring
2016 * of k+1...k+mlen-i-1
2019 /* Avoid making errors worse */
2023 pmatches
= (int*) malloc(g
->mlen
* sizeof(unsigned int));
2024 if (pmatches
== NULL
) {
2025 g
->matchjump
= NULL
;
2029 g
->matchjump
= (int*) malloc(g
->mlen
* sizeof(unsigned int));
2030 if (g
->matchjump
== NULL
) { /* Not a fatal error */
2035 /* Set maximum possible jump for each character in the pattern */
2036 for (mindex
= 0; mindex
< g
->mlen
; mindex
++)
2037 g
->matchjump
[mindex
] = 2*g
->mlen
- mindex
- 1;
2039 /* Compute pmatches[] */
2040 for (mindex
= g
->mlen
- 1, suffix
= g
->mlen
; mindex
>= 0;
2041 mindex
--, suffix
--) {
2042 pmatches
[mindex
] = suffix
;
2044 /* If a mismatch is found, interrupting the substring,
2045 * compute the matchjump for that position. If no
2046 * mismatch is found, then a text substring mismatched
2047 * against the suffix will also mismatch against the
2050 while (suffix
< g
->mlen
2051 && g
->must
[mindex
] != g
->must
[suffix
]) {
2052 g
->matchjump
[suffix
] = MIN(g
->matchjump
[suffix
],
2053 g
->mlen
- mindex
- 1);
2054 suffix
= pmatches
[suffix
];
2058 /* Compute the matchjump up to the last substring found to jump
2059 * to the beginning of the largest must pattern prefix matching
2062 for (mindex
= 0; mindex
<= suffix
; mindex
++)
2063 g
->matchjump
[mindex
] = MIN(g
->matchjump
[mindex
],
2064 g
->mlen
+ suffix
- mindex
);
2066 ssuffix
= pmatches
[suffix
];
2067 while (suffix
< g
->mlen
) {
2068 while (suffix
<= ssuffix
&& suffix
< g
->mlen
) {
2069 g
->matchjump
[suffix
] = MIN(g
->matchjump
[suffix
],
2070 g
->mlen
+ ssuffix
- suffix
);
2073 if (suffix
< g
->mlen
)
2074 ssuffix
= pmatches
[ssuffix
];
2081 - pluscount - count + nesting
2082 == static sopno pluscount(struct parse *p, struct re_guts *g);
2084 static sopno
/* nesting depth */
2096 return(0); /* there may not be an OEND */
2098 scan
= g
->strip
+ 1;
2106 if (plusnest
> maxnest
)
2111 } while (OP(s
) != OEND
);
2117 #endif /* !_NO_REGEX */