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