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