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