2 * This code is derived from OpenBSD's libc/regex, original license follows:
4 * Copyright (c) 1992, 1993, 1994 Henry Spencer.
5 * Copyright (c) 1992, 1993, 1994
6 * The Regents of the University of California. All rights reserved.
8 * This code is derived from software contributed to Berkeley by
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 * 3. Neither the name of the University nor the names of its contributors
20 * may be used to endorse or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 * @(#)regcomp.c 8.5 (Berkeley) 3/20/94
38 #include <sys/types.h>
45 #include "regex_impl.h"
50 #include "llvm/Config/config.h"
51 #include "llvm/Support/Compiler.h"
53 /* character-class table */
54 static struct cclass
{
59 { "alnum", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\
61 { "alpha", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
63 { "blank", " \t", ""} ,
64 { "cntrl", "\007\b\t\n\v\f\r\1\2\3\4\5\6\16\17\20\21\22\23\24\
65 \25\26\27\30\31\32\33\34\35\36\37\177", ""} ,
66 { "digit", "0123456789", ""} ,
67 { "graph", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\
68 0123456789!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~",
70 { "lower", "abcdefghijklmnopqrstuvwxyz",
72 { "print", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\
73 0123456789!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~ ",
75 { "punct", "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~",
77 { "space", "\t\n\v\f\r ", ""} ,
78 { "upper", "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
80 { "xdigit", "0123456789ABCDEFabcdef",
85 /* character-name table */
100 { "backspace", '\b' },
106 { "vertical-tab", '\v' },
108 { "form-feed", '\f' },
110 { "carriage-return", '\r' },
134 { "exclamation-mark", '!' },
135 { "quotation-mark", '"' },
136 { "number-sign", '#' },
137 { "dollar-sign", '$' },
138 { "percent-sign", '%' },
139 { "ampersand", '&' },
140 { "apostrophe", '\'' },
141 { "left-parenthesis", '(' },
142 { "right-parenthesis", ')' },
144 { "plus-sign", '+' },
147 { "hyphen-minus", '-' },
149 { "full-stop", '.' },
163 { "semicolon", ';' },
164 { "less-than-sign", '<' },
165 { "equals-sign", '=' },
166 { "greater-than-sign", '>' },
167 { "question-mark", '?' },
168 { "commercial-at", '@' },
169 { "left-square-bracket", '[' },
170 { "backslash", '\\' },
171 { "reverse-solidus", '\\' },
172 { "right-square-bracket", ']' },
173 { "circumflex", '^' },
174 { "circumflex-accent", '^' },
175 { "underscore", '_' },
177 { "grave-accent", '`' },
178 { "left-brace", '{' },
179 { "left-curly-bracket", '{' },
180 { "vertical-line", '|' },
181 { "right-brace", '}' },
182 { "right-curly-bracket", '}' },
189 * parse structure, passed up and down to avoid global variables and
193 char *next
; /* next character in RE */
194 char *end
; /* end of string (-> NUL normally) */
195 int error
; /* has an error been seen? */
196 sop
*strip
; /* malloced strip */
197 sopno ssize
; /* malloced strip size (allocated) */
198 sopno slen
; /* malloced strip length (used) */
199 int ncsalloc
; /* number of csets allocated */
201 # define NPAREN 10 /* we need to remember () 1-9 for back refs */
202 sopno pbegin
[NPAREN
]; /* -> ( ([0] unused) */
203 sopno pend
[NPAREN
]; /* -> ) ([0] unused) */
206 static void p_ere(struct parse
*, int);
207 static void p_ere_exp(struct parse
*);
208 static void p_str(struct parse
*);
209 static void p_bre(struct parse
*, int, int);
210 static int p_simp_re(struct parse
*, int);
211 static int p_count(struct parse
*);
212 static void p_bracket(struct parse
*);
213 static void p_b_term(struct parse
*, cset
*);
214 static void p_b_cclass(struct parse
*, cset
*);
215 static void p_b_eclass(struct parse
*, cset
*);
216 static char p_b_symbol(struct parse
*);
217 static char p_b_coll_elem(struct parse
*, int);
218 static char othercase(int);
219 static void bothcases(struct parse
*, int);
220 static void ordinary(struct parse
*, int);
221 static void nonnewline(struct parse
*);
222 static void repeat(struct parse
*, sopno
, int, int);
223 static int seterr(struct parse
*, int);
224 static cset
*allocset(struct parse
*);
225 static void freeset(struct parse
*, cset
*);
226 static int freezeset(struct parse
*, cset
*);
227 static int firstch(struct parse
*, cset
*);
228 static int nch(struct parse
*, cset
*);
229 static void mcadd(struct parse
*, cset
*, const char *);
230 static void mcinvert(struct parse
*, cset
*);
231 static void mccase(struct parse
*, cset
*);
232 static int isinsets(struct re_guts
*, int);
233 static int samesets(struct re_guts
*, int, int);
234 static void categorize(struct parse
*, struct re_guts
*);
235 static sopno
dupl(struct parse
*, sopno
, sopno
);
236 static void doemit(struct parse
*, sop
, size_t);
237 static void doinsert(struct parse
*, sop
, size_t, sopno
);
238 static void dofwd(struct parse
*, sopno
, sop
);
239 static void enlarge(struct parse
*, sopno
);
240 static void stripsnug(struct parse
*, struct re_guts
*);
241 static void findmust(struct parse
*, struct re_guts
*);
242 static sopno
pluscount(struct parse
*, struct re_guts
*);
244 static char nuls
[10]; /* place to point scanner in event of error */
247 * macros for use with parse structure
248 * BEWARE: these know that the parse structure is named `p' !!!
250 #define PEEK() (*p->next)
251 #define PEEK2() (*(p->next+1))
252 #define MORE() (p->next < p->end)
253 #define MORE2() (p->next+1 < p->end)
254 #define SEE(c) (MORE() && PEEK() == (c))
255 #define SEETWO(a, b) (MORE() && MORE2() && PEEK() == (a) && PEEK2() == (b))
256 #define EAT(c) ((SEE(c)) ? (NEXT(), 1) : 0)
257 #define EATTWO(a, b) ((SEETWO(a, b)) ? (NEXT2(), 1) : 0)
258 #define NEXT() (p->next++)
259 #define NEXT2() (p->next += 2)
260 #define NEXTn(n) (p->next += (n))
261 #define GETNEXT() (*p->next++)
262 #define SETERROR(e) seterr(p, (e))
263 #define REQUIRE(co, e) (void)((co) || SETERROR(e))
264 #define MUSTSEE(c, e) (REQUIRE(MORE() && PEEK() == (c), e))
265 #define MUSTEAT(c, e) (REQUIRE(MORE() && GETNEXT() == (c), e))
266 #define MUSTNOTSEE(c, e) (REQUIRE(!MORE() || PEEK() != (c), e))
267 #define EMIT(op, sopnd) doemit(p, (sop)(op), (size_t)(sopnd))
268 #define INSERT(op, pos) doinsert(p, (sop)(op), HERE()-(pos)+1, pos)
269 #define AHEAD(pos) dofwd(p, pos, HERE()-(pos))
270 #define ASTERN(sop, pos) EMIT(sop, HERE()-pos)
271 #define HERE() (p->slen)
272 #define THERE() (p->slen - 1)
273 #define THERETHERE() (p->slen - 2)
274 #define DROP(n) (p->slen -= (n))
276 #ifdef _POSIX2_RE_DUP_MAX
277 #define DUPMAX _POSIX2_RE_DUP_MAX
281 #define INFINITY (DUPMAX + 1)
284 static int never
= 0; /* for use in asserts; shuts lint up */
286 #define never 0 /* some <assert.h>s have bugs too */
290 - llvm_regcomp - interface for parser and compilation
292 int /* 0 success, otherwise REG_something */
293 llvm_regcomp(llvm_regex_t
*preg
, const char *pattern
, int cflags
)
297 struct parse
*p
= &pa
;
301 # define GOODFLAGS(f) (f)
303 # define GOODFLAGS(f) ((f)&~REG_DUMP)
306 cflags
= GOODFLAGS(cflags
);
307 if ((cflags
®_EXTENDED
) && (cflags
®_NOSPEC
))
310 if (cflags
®_PEND
) {
311 if (preg
->re_endp
< pattern
)
313 len
= preg
->re_endp
- pattern
;
315 len
= strlen((const char *)pattern
);
317 /* do the mallocs early so failure handling is easy */
318 g
= (struct re_guts
*)malloc(sizeof(struct re_guts
) +
319 (NC
-1)*sizeof(cat_t
));
322 p
->ssize
= len
/(size_t)2*(size_t)3 + (size_t)1; /* ugh */
323 p
->strip
= (sop
*)calloc(p
->ssize
, sizeof(sop
));
325 if (p
->strip
== NULL
) {
332 p
->next
= (char *)pattern
; /* convenience; we do not modify it */
333 p
->end
= p
->next
+ len
;
336 for (i
= 0; i
< NPAREN
; i
++) {
351 g
->ncategories
= 1; /* category 0 is "everything else" */
352 g
->categories
= &g
->catspace
[-(CHAR_MIN
)];
353 (void) memset((char *)g
->catspace
, 0, NC
*sizeof(cat_t
));
358 g
->firststate
= THERE();
359 if (cflags
®_EXTENDED
)
361 else if (cflags
®_NOSPEC
)
366 g
->laststate
= THERE();
368 /* tidy up loose ends and fill things in */
372 g
->nplus
= pluscount(p
, g
);
374 preg
->re_nsub
= g
->nsub
;
376 preg
->re_magic
= MAGIC1
;
378 /* not debugging, so can't rely on the assert() in llvm_regexec() */
379 if (g
->iflags
®EX_BAD
)
380 SETERROR(REG_ASSERT
);
383 /* win or lose, we're done */
384 if (p
->error
!= 0) /* lose */
390 - p_ere - ERE parser top level, concatenation and alternation
393 p_ere(struct parse
*p
, int stop
) /* character this ERE should end at */
399 int first
= 1; /* is this the first alternative? */
402 /* do a bunch of concatenated expressions */
404 while (MORE() && (c
= PEEK()) != '|' && c
!= stop
)
406 REQUIRE(HERE() != conc
, REG_EMPTY
); /* require nonempty */
409 break; /* NOTE BREAK OUT */
412 INSERT(OCH_
, conc
); /* offset is wrong */
417 ASTERN(OOR1
, prevback
);
419 AHEAD(prevfwd
); /* fix previous offset */
421 EMIT(OOR2
, 0); /* offset is very wrong */
424 if (!first
) { /* tail-end fixups */
426 ASTERN(O_CH
, prevback
);
429 assert(!MORE() || SEE(stop
));
433 - p_ere_exp - parse one subERE, an atom possibly followed by a repetition op
436 p_ere_exp(struct parse
*p
)
446 assert(MORE()); /* caller should have ensured this */
452 REQUIRE(MORE(), REG_EPAREN
);
456 p
->pbegin
[subno
] = HERE();
457 EMIT(OLPAREN
, subno
);
460 if (subno
< NPAREN
) {
461 p
->pend
[subno
] = HERE();
462 assert(p
->pend
[subno
] != 0);
464 EMIT(ORPAREN
, subno
);
465 MUSTEAT(')', REG_EPAREN
);
467 #ifndef POSIX_MISTAKE
468 case ')': /* happens only if no current unmatched ( */
470 * You may ask, why the ifndef? Because I didn't notice
471 * this until slightly too late for 1003.2, and none of the
472 * other 1003.2 regular-expression reviewers noticed it at
473 * all. So an unmatched ) is legal POSIX, at least until
474 * we can get it fixed.
476 SETERROR(REG_EPAREN
);
481 p
->g
->iflags
|= USEBOL
;
487 p
->g
->iflags
|= USEEOL
;
496 SETERROR(REG_BADRPT
);
499 if (p
->g
->cflags
®_NEWLINE
)
508 REQUIRE(MORE(), REG_EESCAPE
);
510 if (c
>= '1' && c
<= '9') {
511 /* \[0-9] is taken to be a back-reference to a previously specified
512 * matching group. backrefnum will hold the number. The matching
513 * group must exist (i.e. if \4 is found there must have been at
514 * least 4 matching groups specified in the pattern previously).
516 backrefnum
= c
- '0';
517 if (p
->pend
[backrefnum
] == 0) {
518 SETERROR(REG_ESUBREG
);
522 /* Make sure everything checks out and emit the sequence
523 * that marks a back-reference to the parse structure.
525 assert(backrefnum
<= p
->g
->nsub
);
526 EMIT(OBACK_
, backrefnum
);
527 assert(p
->pbegin
[backrefnum
] != 0);
528 assert(OP(p
->strip
[p
->pbegin
[backrefnum
]]) != OLPAREN
);
529 assert(OP(p
->strip
[p
->pend
[backrefnum
]]) != ORPAREN
);
530 (void) dupl(p
, p
->pbegin
[backrefnum
]+1, p
->pend
[backrefnum
]);
531 EMIT(O_BACK
, backrefnum
);
534 /* Other chars are simply themselves when escaped with a backslash.
539 case '{': /* okay as ordinary except if digit follows */
540 REQUIRE(!MORE() || !isdigit((uch
)PEEK()), REG_BADRPT
);
550 /* we call { a repetition if followed by a digit */
551 if (!( c
== '*' || c
== '+' || c
== '?' ||
552 (c
== '{' && MORE2() && isdigit((uch
)PEEK2())) ))
553 return; /* no repetition, we're done */
556 REQUIRE(!wascaret
, REG_BADRPT
);
558 case '*': /* implemented as +? */
559 /* this case does not require the (y|) trick, noKLUDGE */
562 INSERT(OQUEST_
, pos
);
563 ASTERN(O_QUEST
, pos
);
570 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
571 INSERT(OCH_
, pos
); /* offset slightly wrong */
572 ASTERN(OOR1
, pos
); /* this one's right */
573 AHEAD(pos
); /* fix the OCH_ */
574 EMIT(OOR2
, 0); /* offset very wrong... */
575 AHEAD(THERE()); /* ...so fix it */
576 ASTERN(O_CH
, THERETHERE());
581 if (isdigit((uch
)PEEK())) {
583 REQUIRE(count
<= count2
, REG_BADBR
);
584 } else /* single number with comma */
586 } else /* just a single number */
588 repeat(p
, pos
, count
, count2
);
589 if (!EAT('}')) { /* error heuristics */
590 while (MORE() && PEEK() != '}')
592 REQUIRE(MORE(), REG_EBRACE
);
601 if (!( c
== '*' || c
== '+' || c
== '?' ||
602 (c
== '{' && MORE2() && isdigit((uch
)PEEK2())) ) )
604 SETERROR(REG_BADRPT
);
608 - p_str - string (no metacharacters) "parser"
611 p_str(struct parse
*p
)
613 REQUIRE(MORE(), REG_EMPTY
);
615 ordinary(p
, GETNEXT());
619 - p_bre - BRE parser top level, anchoring and concatenation
620 * Giving end1 as OUT essentially eliminates the end1/end2 check.
622 * This implementation is a bit of a kludge, in that a trailing $ is first
623 * taken as an ordinary character and then revised to be an anchor. The
624 * only undesirable side effect is that '$' gets included as a character
625 * category in such cases. This is fairly harmless; not worth fixing.
626 * The amount of lookahead needed to avoid this kludge is excessive.
629 p_bre(struct parse
*p
,
630 int end1
, /* first terminating character */
631 int end2
) /* second terminating character */
633 sopno start
= HERE();
634 int first
= 1; /* first subexpression? */
639 p
->g
->iflags
|= USEBOL
;
642 while (MORE() && !SEETWO(end1
, end2
)) {
643 wasdollar
= p_simp_re(p
, first
);
646 if (wasdollar
) { /* oops, that was a trailing anchor */
649 p
->g
->iflags
|= USEEOL
;
653 REQUIRE(HERE() != start
, REG_EMPTY
); /* require nonempty */
657 - p_simp_re - parse a simple RE, an atom possibly followed by a repetition
659 static int /* was the simple RE an unbackslashed $? */
660 p_simp_re(struct parse
*p
,
661 int starordinary
) /* is a leading * an ordinary character? */
669 # define BACKSL (1<<CHAR_BIT)
671 pos
= HERE(); /* repetition op, if any, covers from here */
673 assert(MORE()); /* caller should have ensured this */
676 REQUIRE(MORE(), REG_EESCAPE
);
677 c
= BACKSL
| GETNEXT();
681 if (p
->g
->cflags
®_NEWLINE
)
690 SETERROR(REG_BADRPT
);
696 p
->pbegin
[subno
] = HERE();
697 EMIT(OLPAREN
, subno
);
698 /* the MORE here is an error heuristic */
699 if (MORE() && !SEETWO('\\', ')'))
701 if (subno
< NPAREN
) {
702 p
->pend
[subno
] = HERE();
703 assert(p
->pend
[subno
] != 0);
705 EMIT(ORPAREN
, subno
);
706 REQUIRE(EATTWO('\\', ')'), REG_EPAREN
);
708 case BACKSL
|')': /* should not get here -- must be user */
710 SETERROR(REG_EPAREN
);
721 i
= (c
&~BACKSL
) - '0';
723 if (p
->pend
[i
] != 0) {
724 assert(i
<= p
->g
->nsub
);
726 assert(p
->pbegin
[i
] != 0);
727 assert(OP(p
->strip
[p
->pbegin
[i
]]) == OLPAREN
);
728 assert(OP(p
->strip
[p
->pend
[i
]]) == ORPAREN
);
729 (void) dupl(p
, p
->pbegin
[i
]+1, p
->pend
[i
]);
732 SETERROR(REG_ESUBREG
);
736 REQUIRE(starordinary
, REG_BADRPT
);
739 ordinary(p
, (char)c
);
743 if (EAT('*')) { /* implemented as +? */
744 /* this case does not require the (y|) trick, noKLUDGE */
747 INSERT(OQUEST_
, pos
);
748 ASTERN(O_QUEST
, pos
);
749 } else if (EATTWO('\\', '{')) {
752 if (MORE() && isdigit((uch
)PEEK())) {
754 REQUIRE(count
<= count2
, REG_BADBR
);
755 } else /* single number with comma */
757 } else /* just a single number */
759 repeat(p
, pos
, count
, count2
);
760 if (!EATTWO('\\', '}')) { /* error heuristics */
761 while (MORE() && !SEETWO('\\', '}'))
763 REQUIRE(MORE(), REG_EBRACE
);
766 } else if (c
== '$') /* $ (but not \$) ends it */
773 - p_count - parse a repetition count
775 static int /* the value */
776 p_count(struct parse
*p
)
781 while (MORE() && isdigit((uch
)PEEK()) && count
<= DUPMAX
) {
782 count
= count
*10 + (GETNEXT() - '0');
786 REQUIRE(ndigits
> 0 && count
<= DUPMAX
, REG_BADBR
);
791 - p_bracket - parse a bracketed character list
793 * Note a significant property of this code: if the allocset() did SETERROR,
794 * no set operations are done.
797 p_bracket(struct parse
*p
)
802 /* Dept of Truly Sickening Special-Case Kludges */
803 if (p
->next
+ 5 < p
->end
&& strncmp(p
->next
, "[:<:]]", 6) == 0) {
808 if (p
->next
+ 5 < p
->end
&& strncmp(p
->next
, "[:>:]]", 6) == 0) {
814 if ((cs
= allocset(p
)) == NULL
) {
815 /* allocset did set error status in p */
820 invert
++; /* make note to invert set at end */
825 while (MORE() && PEEK() != ']' && !SEETWO('-', ']'))
829 MUSTEAT(']', REG_EBRACK
);
831 if (p
->error
!= 0) { /* don't mess things up further */
836 if (p
->g
->cflags
®_ICASE
) {
840 for (i
= p
->g
->csetsize
- 1; i
>= 0; i
--)
841 if (CHIN(cs
, i
) && isalpha(i
)) {
846 if (cs
->multis
!= NULL
)
852 for (i
= p
->g
->csetsize
- 1; i
>= 0; i
--)
857 if (p
->g
->cflags
®_NEWLINE
)
859 if (cs
->multis
!= NULL
)
863 assert(cs
->multis
== NULL
); /* xxx */
865 if (nch(p
, cs
) == 1) { /* optimize singleton sets */
866 ordinary(p
, firstch(p
, cs
));
869 EMIT(OANYOF
, freezeset(p
, cs
));
873 - p_b_term - parse one term of a bracketed character list
876 p_b_term(struct parse
*p
, cset
*cs
)
882 /* classify what we've got */
883 switch ((MORE()) ? PEEK() : '\0') {
885 c
= (MORE2()) ? PEEK2() : '\0';
888 SETERROR(REG_ERANGE
);
889 return; /* NOTE RETURN */
897 case ':': /* character class */
899 REQUIRE(MORE(), REG_EBRACK
);
901 REQUIRE(c
!= '-' && c
!= ']', REG_ECTYPE
);
903 REQUIRE(MORE(), REG_EBRACK
);
904 REQUIRE(EATTWO(':', ']'), REG_ECTYPE
);
906 case '=': /* equivalence class */
908 REQUIRE(MORE(), REG_EBRACK
);
910 REQUIRE(c
!= '-' && c
!= ']', REG_ECOLLATE
);
912 REQUIRE(MORE(), REG_EBRACK
);
913 REQUIRE(EATTWO('=', ']'), REG_ECOLLATE
);
915 default: /* symbol, ordinary character, or range */
916 /* xxx revision needed for multichar stuff */
917 start
= p_b_symbol(p
);
918 if (SEE('-') && MORE2() && PEEK2() != ']') {
924 finish
= p_b_symbol(p
);
927 /* xxx what about signed chars here... */
928 REQUIRE(start
<= finish
, REG_ERANGE
);
929 for (i
= start
; i
<= finish
; i
++)
936 - p_b_cclass - parse a character-class name and deal with it
939 p_b_cclass(struct parse
*p
, cset
*cs
)
947 while (MORE() && isalpha((uch
)PEEK()))
950 for (cp
= cclasses
; cp
->name
!= NULL
; cp
++)
951 if (strncmp(cp
->name
, sp
, len
) == 0 && cp
->name
[len
] == '\0')
953 if (cp
->name
== NULL
) {
954 /* oops, didn't find it */
955 SETERROR(REG_ECTYPE
);
960 while ((c
= *u
++) != '\0')
962 for (u
= cp
->multis
; *u
!= '\0'; u
+= strlen(u
) + 1)
967 - p_b_eclass - parse an equivalence-class name and deal with it
969 * This implementation is incomplete. xxx
972 p_b_eclass(struct parse
*p
, cset
*cs
)
976 c
= p_b_coll_elem(p
, '=');
981 - p_b_symbol - parse a character or [..]ed multicharacter collating symbol
983 static char /* value of symbol */
984 p_b_symbol(struct parse
*p
)
988 REQUIRE(MORE(), REG_EBRACK
);
989 if (!EATTWO('[', '.'))
992 /* collating symbol */
993 value
= p_b_coll_elem(p
, '.');
994 REQUIRE(EATTWO('.', ']'), REG_ECOLLATE
);
999 - p_b_coll_elem - parse a collating-element name and look it up
1001 static char /* value of collating element */
1002 p_b_coll_elem(struct parse
*p
,
1003 int endc
) /* name ended by endc,']' */
1009 while (MORE() && !SEETWO(endc
, ']'))
1012 SETERROR(REG_EBRACK
);
1016 for (cp
= cnames
; cp
->name
!= NULL
; cp
++)
1017 if (strncmp(cp
->name
, sp
, len
) == 0 && strlen(cp
->name
) == len
)
1018 return(cp
->code
); /* known name */
1020 return(*sp
); /* single character */
1021 SETERROR(REG_ECOLLATE
); /* neither */
1026 - othercase - return the case counterpart of an alphabetic
1028 static char /* if no counterpart, return ch */
1032 assert(isalpha(ch
));
1034 return ((uch
)tolower(ch
));
1035 else if (islower(ch
))
1036 return ((uch
)toupper(ch
));
1037 else /* peculiar, but could happen */
1042 - bothcases - emit a dualcase version of a two-case character
1044 * Boy, is this implementation ever a kludge...
1047 bothcases(struct parse
*p
, int ch
)
1049 char *oldnext
= p
->next
;
1050 char *oldend
= p
->end
;
1054 assert(othercase(ch
) != ch
); /* p_bracket() would recurse */
1061 assert(p
->next
== bracket
+2);
1067 - ordinary - emit an ordinary character
1070 ordinary(struct parse
*p
, int ch
)
1072 cat_t
*cap
= p
->g
->categories
;
1074 if ((p
->g
->cflags
®_ICASE
) && isalpha((uch
)ch
) && othercase(ch
) != ch
)
1077 EMIT(OCHAR
, (uch
)ch
);
1079 cap
[ch
] = p
->g
->ncategories
++;
1084 - nonnewline - emit REG_NEWLINE version of OANY
1086 * Boy, is this implementation ever a kludge...
1089 nonnewline(struct parse
*p
)
1091 char *oldnext
= p
->next
;
1092 char *oldend
= p
->end
;
1102 assert(p
->next
== bracket
+3);
1108 - repeat - generate code for a bounded repetition, recursively if needed
1111 repeat(struct parse
*p
,
1112 sopno start
, /* operand from here to end of strip */
1113 int from
, /* repeated from this number */
1114 int to
) /* to this number of times (maybe INFINITY) */
1116 sopno finish
= HERE();
1119 # define REP(f, t) ((f)*8 + (t))
1120 # define MAP(n) (((n) <= 1) ? (n) : ((n) == INFINITY) ? INF : N)
1123 if (p
->error
!= 0) /* head off possible runaway recursion */
1128 switch (REP(MAP(from
), MAP(to
))) {
1129 case REP(0, 0): /* must be user doing this */
1130 DROP(finish
-start
); /* drop the operand */
1132 case REP(0, 1): /* as x{1,1}? */
1133 case REP(0, N
): /* as x{1,n}? */
1134 case REP(0, INF
): /* as x{1,}? */
1135 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
1136 INSERT(OCH_
, start
); /* offset is wrong... */
1137 repeat(p
, start
+1, 1, to
);
1138 ASTERN(OOR1
, start
);
1139 AHEAD(start
); /* ... fix it */
1142 ASTERN(O_CH
, THERETHERE());
1144 case REP(1, 1): /* trivial case */
1147 case REP(1, N
): /* as x?x{1,n-1} */
1148 /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */
1149 INSERT(OCH_
, start
);
1150 ASTERN(OOR1
, start
);
1152 EMIT(OOR2
, 0); /* offset very wrong... */
1153 AHEAD(THERE()); /* ...so fix it */
1154 ASTERN(O_CH
, THERETHERE());
1155 copy
= dupl(p
, start
+1, finish
+1);
1156 assert(copy
== finish
+4);
1157 repeat(p
, copy
, 1, to
-1);
1159 case REP(1, INF
): /* as x+ */
1160 INSERT(OPLUS_
, start
);
1161 ASTERN(O_PLUS
, start
);
1163 case REP(N
, N
): /* as xx{m-1,n-1} */
1164 copy
= dupl(p
, start
, finish
);
1165 repeat(p
, copy
, from
-1, to
-1);
1167 case REP(N
, INF
): /* as xx{n-1,INF} */
1168 copy
= dupl(p
, start
, finish
);
1169 repeat(p
, copy
, from
-1, to
);
1171 default: /* "can't happen" */
1172 SETERROR(REG_ASSERT
); /* just in case */
1178 - seterr - set an error condition
1180 static int /* useless but makes type checking happy */
1181 seterr(struct parse
*p
, int e
)
1183 if (p
->error
== 0) /* keep earliest error condition */
1185 p
->next
= nuls
; /* try to bring things to a halt */
1187 return(0); /* make the return value well-defined */
1191 - allocset - allocate a set of characters for []
1194 allocset(struct parse
*p
)
1196 int no
= p
->g
->ncsets
++;
1200 size_t css
= (size_t)p
->g
->csetsize
;
1203 if (no
>= p
->ncsalloc
) { /* need another column of space */
1206 p
->ncsalloc
+= CHAR_BIT
;
1208 if (nc
> SIZE_MAX
/ sizeof(cset
))
1210 assert(nc
% CHAR_BIT
== 0);
1211 nbytes
= nc
/ CHAR_BIT
* css
;
1213 ptr
= (cset
*)realloc((char *)p
->g
->sets
, nc
* sizeof(cset
));
1218 ptr
= (uch
*)realloc((char *)p
->g
->setbits
, nbytes
);
1221 p
->g
->setbits
= ptr
;
1223 for (i
= 0; i
< no
; i
++)
1224 p
->g
->sets
[i
].ptr
= p
->g
->setbits
+ css
*(i
/CHAR_BIT
);
1226 (void) memset((char *)p
->g
->setbits
+ (nbytes
- css
), 0, css
);
1228 /* XXX should not happen */
1229 if (p
->g
->sets
== NULL
|| p
->g
->setbits
== NULL
)
1232 cs
= &p
->g
->sets
[no
];
1233 cs
->ptr
= p
->g
->setbits
+ css
*((no
)/CHAR_BIT
);
1234 cs
->mask
= 1 << ((no
) % CHAR_BIT
);
1243 free(p
->g
->setbits
);
1244 p
->g
->setbits
= NULL
;
1246 SETERROR(REG_ESPACE
);
1247 /* caller's responsibility not to do set ops */
1252 - freeset - free a now-unused set
1255 freeset(struct parse
*p
, cset
*cs
)
1258 cset
*top
= &p
->g
->sets
[p
->g
->ncsets
];
1259 size_t css
= (size_t)p
->g
->csetsize
;
1261 for (i
= 0; i
< css
; i
++)
1263 if (cs
== top
-1) /* recover only the easy case */
1268 - freezeset - final processing on a set of characters
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 */
1277 freezeset(struct parse
*p
, cset
*cs
)
1281 cset
*top
= &p
->g
->sets
[p
->g
->ncsets
];
1283 size_t css
= (size_t)p
->g
->csetsize
;
1285 /* look for an earlier one which is the same */
1286 for (cs2
= &p
->g
->sets
[0]; cs2
< top
; cs2
++)
1287 if (cs2
->hash
== h
&& cs2
!= cs
) {
1289 for (i
= 0; i
< css
; i
++)
1290 if (!!CHIN(cs2
, i
) != !!CHIN(cs
, i
))
1296 if (cs2
< top
) { /* found one */
1301 return((int)(cs
- p
->g
->sets
));
1305 - firstch - return first character in a set (which must have at least one)
1307 static int /* character; there is no "none" value */
1308 firstch(struct parse
*p
, cset
*cs
)
1311 size_t css
= (size_t)p
->g
->csetsize
;
1313 for (i
= 0; i
< css
; i
++)
1317 return(0); /* arbitrary */
1321 - nch - number of characters in a set
1324 nch(struct parse
*p
, cset
*cs
)
1327 size_t css
= (size_t)p
->g
->csetsize
;
1330 for (i
= 0; i
< css
; i
++)
1337 - mcadd - add a collating element to a cset
1340 mcadd( struct parse
*p
, cset
*cs
, const char *cp
)
1342 size_t oldend
= cs
->smultis
;
1345 cs
->smultis
+= strlen(cp
) + 1;
1346 np
= realloc(cs
->multis
, cs
->smultis
);
1351 SETERROR(REG_ESPACE
);
1356 llvm_strlcpy(cs
->multis
+ oldend
- 1, cp
, cs
->smultis
- oldend
+ 1);
1360 - mcinvert - invert the list of collating elements in a cset
1362 * This would have to know the set of possibilities. Implementation
1367 mcinvert(struct parse
*p
, cset
*cs
)
1369 assert(cs
->multis
== NULL
); /* xxx */
1373 - mccase - add case counterparts of the list of collating elements in a cset
1375 * This would have to know the set of possibilities. Implementation
1380 mccase(struct parse
*p
, cset
*cs
)
1382 assert(cs
->multis
== NULL
); /* xxx */
1386 - isinsets - is this character in any sets?
1388 static int /* predicate */
1389 isinsets(struct re_guts
*g
, int c
)
1393 int ncols
= (g
->ncsets
+(CHAR_BIT
-1)) / CHAR_BIT
;
1394 unsigned uc
= (uch
)c
;
1396 for (i
= 0, col
= g
->setbits
; i
< ncols
; i
++, col
+= g
->csetsize
)
1403 - samesets - are these two characters in exactly the same sets?
1405 static int /* predicate */
1406 samesets(struct re_guts
*g
, int c1
, int c2
)
1410 int ncols
= (g
->ncsets
+(CHAR_BIT
-1)) / CHAR_BIT
;
1411 unsigned uc1
= (uch
)c1
;
1412 unsigned uc2
= (uch
)c2
;
1414 for (i
= 0, col
= g
->setbits
; i
< ncols
; i
++, col
+= g
->csetsize
)
1415 if (col
[uc1
] != col
[uc2
])
1421 - categorize - sort out character categories
1424 categorize(struct parse
*p
, struct re_guts
*g
)
1426 cat_t
*cats
= g
->categories
;
1431 /* avoid making error situations worse */
1435 for (c
= CHAR_MIN
; c
<= CHAR_MAX
; c
++)
1436 if (cats
[c
] == 0 && isinsets(g
, c
)) {
1437 cat
= g
->ncategories
++;
1439 for (c2
= c
+1; c2
<= CHAR_MAX
; c2
++)
1440 if (cats
[c2
] == 0 && samesets(g
, c
, c2
))
1446 - dupl - emit a duplicate of a bunch of sops
1448 static sopno
/* start of duplicate */
1449 dupl(struct parse
*p
,
1450 sopno start
, /* from here */
1451 sopno finish
) /* to this less one */
1454 sopno len
= finish
- start
;
1456 assert(finish
>= start
);
1459 enlarge(p
, p
->ssize
+ len
); /* this many unexpected additions */
1460 assert(p
->ssize
>= p
->slen
+ len
);
1461 (void) memmove((char *)(p
->strip
+ p
->slen
),
1462 (char *)(p
->strip
+ start
), (size_t)len
*sizeof(sop
));
1468 - doemit - emit a strip operator
1470 * It might seem better to implement this as a macro with a function as
1471 * hard-case backup, but it's just too big and messy unless there are
1472 * some changes to the data structures. Maybe later.
1475 doemit(struct parse
*p
, sop op
, size_t opnd
)
1477 /* avoid making error situations worse */
1481 /* deal with oversize operands ("can't happen", more or less) */
1482 assert(opnd
< 1<<OPSHIFT
);
1484 /* deal with undersized strip */
1485 if (p
->slen
>= p
->ssize
)
1486 enlarge(p
, (p
->ssize
+1) / 2 * 3); /* +50% */
1487 assert(p
->slen
< p
->ssize
);
1489 /* finally, it's all reduced to the easy case */
1490 p
->strip
[p
->slen
++] = SOP(op
, opnd
);
1494 - doinsert - insert a sop into the strip
1497 doinsert(struct parse
*p
, sop op
, size_t opnd
, sopno pos
)
1503 /* avoid making error situations worse */
1508 EMIT(op
, opnd
); /* do checks, ensure space */
1509 assert(HERE() == sn
+1);
1512 /* adjust paren pointers */
1514 for (i
= 1; i
< NPAREN
; i
++) {
1515 if (p
->pbegin
[i
] >= pos
) {
1518 if (p
->pend
[i
] >= pos
) {
1523 memmove((char *)&p
->strip
[pos
+1], (char *)&p
->strip
[pos
],
1524 (HERE()-pos
-1)*sizeof(sop
));
1529 - dofwd - complete a forward reference
1532 dofwd(struct parse
*p
, sopno pos
, sop value
)
1534 /* avoid making error situations worse */
1538 assert(value
< 1<<OPSHIFT
);
1539 p
->strip
[pos
] = OP(p
->strip
[pos
]) | value
;
1543 - enlarge - enlarge the strip
1546 enlarge(struct parse
*p
, sopno size
)
1550 if (p
->ssize
>= size
)
1553 if ((uintptr_t)size
> SIZE_MAX
/ sizeof(sop
)) {
1554 SETERROR(REG_ESPACE
);
1558 sp
= (sop
*)realloc(p
->strip
, size
*sizeof(sop
));
1560 SETERROR(REG_ESPACE
);
1568 - stripsnug - compact the strip
1571 stripsnug(struct parse
*p
, struct re_guts
*g
)
1573 g
->nstates
= p
->slen
;
1574 if ((uintptr_t)p
->slen
> SIZE_MAX
/ sizeof(sop
)) {
1575 g
->strip
= p
->strip
;
1576 SETERROR(REG_ESPACE
);
1580 g
->strip
= (sop
*)realloc((char *)p
->strip
, p
->slen
* sizeof(sop
));
1581 if (g
->strip
== NULL
) {
1582 SETERROR(REG_ESPACE
);
1583 g
->strip
= p
->strip
;
1588 - findmust - fill in must and mlen with longest mandatory literal string
1590 * This algorithm could do fancy things like analyzing the operands of |
1591 * for common subsequences. Someday. This code is simple and finds most
1592 * of the interesting cases.
1594 * Note that must and mlen got initialized during setup.
1597 findmust(struct parse
*p
, struct re_guts
*g
)
1600 sop
*start
= 0; /* start initialized in the default case, after that */
1601 sop
*newstart
= 0; /* newstart was initialized in the OCHAR case */
1607 /* avoid making error situations worse */
1611 /* find the longest OCHAR sequence in strip */
1613 scan
= g
->strip
+ 1;
1617 case OCHAR
: /* sequence member */
1618 if (newlen
== 0) /* new sequence */
1619 newstart
= scan
- 1;
1622 case OPLUS_
: /* things that don't break one */
1626 case OQUEST_
: /* things that must be skipped */
1632 /* assert() interferes w debug printouts */
1633 if (OP(s
) != O_QUEST
&& OP(s
) != O_CH
&&
1635 g
->iflags
|= REGEX_BAD
;
1638 } while (OP(s
) != O_QUEST
&& OP(s
) != O_CH
);
1640 default: /* things that break a sequence */
1641 if (newlen
> g
->mlen
) { /* ends one */
1648 } while (OP(s
) != OEND
);
1650 if (g
->mlen
== 0) /* there isn't one */
1653 /* turn it into a character string */
1654 g
->must
= malloc((size_t)g
->mlen
+ 1);
1655 if (g
->must
== NULL
) { /* argh; just forget it */
1661 for (i
= g
->mlen
; i
> 0; i
--) {
1662 while (OP(s
= *scan
++) != OCHAR
)
1664 assert(cp
< g
->must
+ g
->mlen
);
1665 *cp
++ = (char)OPND(s
);
1667 assert(cp
== g
->must
+ g
->mlen
);
1668 *cp
++ = '\0'; /* just on general principles */
1672 - pluscount - count + nesting
1674 static sopno
/* nesting depth */
1675 pluscount(struct parse
*p
, struct re_guts
*g
)
1683 return(0); /* there may not be an OEND */
1685 scan
= g
->strip
+ 1;
1693 if (plusnest
> maxnest
)
1698 } while (OP(s
) != OEND
);
1700 g
->iflags
|= REGEX_BAD
;