Debian Codegraph @

src/regex/regexp.c

raw
1 /* This is an altered version. It was originally altered for use in
2 the Edinburgh Speech Tools by Richard Caley and others. It was
3 later altered for use in Flite by Alan W Black. It was then
4 further altered by David Huggins-Daines. Identifiers and
5 structures have been changed, but the basic structure of the code
6 is intact. */
7
8 /*
9 * regcomp and regexec -- regsub and regerror are elsewhere
10 *
11 * Copyright (c) 1986 by University of Toronto.
12 * Written by Henry Spencer. Not derived from licensed software.
13 *
14 * Permission is granted to anyone to use this software for any
15 * purpose on any computer system, and to redistribute it freely,
16 * subject to the following restrictions:
17 *
18 * 1. The author is not responsible for the consequences of use of
19 * this software, no matter how awful, even if they arise
20 * from defects in it.
21 *
22 * 2. The origin of this software must not be misrepresented, either
23 * by explicit claim or by omission.
24 *
25 * 3. Altered versions must be plainly marked as such, and must not
26 * be misrepresented as being the original software.
27 *** THIS IS AN ALTERED VERSION. It was altered by John Gilmore,
28 *** hoptoad!gnu, on 27 Dec 1986, to add \n as an alternative to |
29 *** to assist in implementing egrep.
30 *** THIS IS AN ALTERED VERSION. It was altered by John Gilmore,
31 *** hoptoad!gnu, on 27 Dec 1986, to add \< and \> for word-matching
32 *** as in BSD grep and ex.
33 *** THIS IS AN ALTERED VERSION. It was altered by John Gilmore,
34 *** hoptoad!gnu, on 28 Dec 1986, to optimize characters quoted with \.
35 *** THIS IS AN ALTERED VERSION. It was altered by James A. Woods,
36 *** ames!jaw, on 19 June 1987, to quash a regcomp() redundancy.
37 *
38 * Beware that some of this code is subtly aware of the way operator
39 * precedence is structured in regular expressions. Serious changes in
40 * regular-expression syntax might require a total rethink. */
41 #include <ctype.h>
42 #include "cst_alloc.h"
43 #include "cst_string.h"
44 #include "cst_file.h"
45 #include "cst_error.h"
46 #include "cst_regex.h"
47
48 /*
49 * The "internal use only" fields in regexp.h are present to pass info from
50 * compile to execute that permits the execute phase to run lots faster on
51 * simple cases. They are:
52 *
53 * regstart char that must begin a match; '\0' if none obvious
54 * reganch is the match anchored (at beginning-of-line only)?
55 * regmust string (pointer into program) that match must include, or NULL
56 * regmlen length of regmust string
57 *
58 * Regstart and reganch permit very fast decisions on suitable starting points
59 * for a match, cutting down the work a lot. Regmust permits fast rejection
60 * of lines that cannot possibly match. The regmust tests are costly enough
61 * that regcomp() supplies a regmust only if the r.e. contains something
62 * potentially expensive (at present, the only such thing detected is * or +
63 * at the start of the r.e., which can involve a lot of backup). Regmlen is
64 * supplied because the test in regexec() needs it and regcomp() is computing
65 * it anyway.
66 */
67
68 /*
69 * Structure for regexp "program". This is essentially a linear encoding
70 * of a nondeterministic finite-state machine (aka syntax charts or
71 * "railroad normal form" in parsing technology). Each node is an opcode
72 * plus a "next" pointer, possibly plus an operand. "Next" pointers of
73 * all nodes except BRANCH implement concatenation; a "next" pointer with
74 * a BRANCH on both ends of it is connecting two alternatives. (Here we
75 * have one of the subtle syntax dependencies: an individual BRANCH (as
76 * opposed to a collection of them) is never concatenated with anything
77 * because of operator precedence.) The operand of some types of node is
78 * a literal string; for others, it is a node leading into a sub-FSM. In
79 * particular, the operand of a BRANCH node is the first node of the branch.
80 * (NB this is *not* a tree structure: the tail of the branch connects
81 * to the thing following the set of BRANCHes.) The opcodes are:
82 */
83
84 /* definition number opnd? meaning */
85 #define END 0 /* no End of program. */
86 #define BOL 1 /* no Match "" at beginning of line. */
87 #define EOL 2 /* no Match "" at end of line. */
88 #define ANY 3 /* no Match any one character. */
89 #define ANYOF 4 /* str Match any character in this string. */
90 #define ANYBUT 5 /* str Match any character not in this string. */
91 #define BRANCH 6 /* node Match this alternative, or the next... */
92 #define BACK 7 /* no Match "", "next" ptr points backward. */
93 #define EXACTLY 8 /* str Match this string. */
94 #define NOTHING 9 /* no Match empty string. */
95 #define STAR 10 /* node Match this (simple) thing 0 or more times. */
96 #define PLUS 11 /* node Match this (simple) thing 1 or more times. */
97 #define WORDA 12 /* no Match "" at wordchar, where prev is nonword */
98 #define WORDZ 13 /* no Match "" at nonwordchar, where prev is word */
99 #define OPEN 20 /* no Mark this point in input as start of #n. */
100 /* OPEN+1 is number 1, etc. */
101 #define CLOSE 30 /* no Analogous to OPEN. */
102
103 /*
104 * Opcode notes:
105 *
106 * BRANCH The set of branches constituting a single choice are hooked
107 * together with their "next" pointers, since precedence prevents
108 * anything being concatenated to any individual branch. The
109 * "next" pointer of the last BRANCH in a choice points to the
110 * thing following the whole choice. This is also where the
111 * final "next" pointer of each individual branch points; each
112 * branch starts with the operand node of a BRANCH node.
113 *
114 * BACK Normal "next" pointers all implicitly point forward; BACK
115 * exists to make loop structures possible.
116 *
117 * STAR,PLUS '?', and complex '*' and '+', are implemented as circular
118 * BRANCH structures using BACK. Simple cases (one character
119 * per match) are implemented with STAR and PLUS for speed
120 * and to minimize recursive plunges.
121 *
122 * OPEN,CLOSE ...are numbered at compile time.
123 */
124
125 /*
126 * A node is one char of opcode followed by two chars of "next" pointer.
127 * "Next" pointers are stored as two 8-bit pieces, high order first. The
128 * value is a positive offset from the opcode of the node containing it.
129 * An operand, if any, simply follows the node. (Note that much of the
130 * code generation knows about this implicit relationship.)
131 *
132 * Using two bytes for the "next" pointer is vast overkill for most things,
133 * but allows patterns to get big without disasters.
134 */
135 #define OP(p) (*(p))
136 #define NEXT(p) (((*((p)+1)&0377)<<8) + (*((p)+2)&0377))
137 #define OPERAND(p) ((p) + 3)
138
139 /*
140 * See regmagic.h for one further detail of program structure.
141 */
142
143
144 /*
145 * Utility definitions.
146 */
147 #ifndef CHARBITS
148 #define UCHARAT(p) ((int)*(unsigned char *)(p))
149 #else
150 #define UCHARAT(p) ((int)*(p)&CHARBITS)
151 #endif
152
153 #define FAIL(m) { cst_errmsg("regexp failure: %s\n", m); cst_error(); }
154 #define ISMULT(c) ((c) == '*' || (c) == '+' || (c) == '?')
155
156 /*
157 * Flags to be passed up and down.
158 */
159 #define HASWIDTH 01 /* Known never to match null string. */
160 #define SIMPLE 02 /* Simple enough to be STAR/PLUS operand. */
161 #define SPSTART 04 /* Starts with * or +. */
162 #define WORST 0 /* Worst case. */
163
164 /*
165 * Global work variables for regcomp().
166 */
167 static const char *regparse; /* Input-scan pointer. */
168 static int regnpar; /* () count. */
169 static char regdummy;
170 static char *regcode; /* Code-emit pointer; &regdummy = don't. */
171 static long regsize; /* Code size. */
172
173 /*
174 * Forward declarations for regcomp()'s friends.
175 */
176 #ifndef STATIC
177 #define STATIC static
178 #endif
179 STATIC char *reg(int paren, int *flagp);
180 STATIC char *regbranch(int *flagp);
181 STATIC char *regpiece(int *flagp);
182 STATIC char *regatom(int *flagp);
183 STATIC char *regnode(char op);
184 STATIC char *regnext(register char *p);
185 STATIC void regc(char b);
186 STATIC void reginsert(char op, char *opnd);
187 STATIC void regtail(char *p, char *val);
188 STATIC void regoptail(char *p, char *val);
189 #ifdef STRCSPN
190 STATIC int strcspn();
191 #endif
192
193 /*
194 - regcomp - compile a regular expression into internal code
195 *
196 * We can't allocate space until we know how big the compiled form will be,
197 * but we can't compile it (and thus know how big it is) until we've got a
198 * place to put the code. So we cheat: we compile it twice, once with code
199 * generation turned off and size counting turned on, and once "for real".
200 * This also means that we don't allocate space until we are sure that the
201 * thing really will compile successfully, and we never have to move the
202 * code and thus invalidate pointers into it. (Note that it has to be in
203 * one piece because free() must be able to free it all.)
204 *
205 * Beware that the optimization-preparation code in here knows about some
206 * of the structure of the compiled regexp.
207 */
208 cst_regex *
209 hs_regcomp(const char *exp)
210 {
211 cst_regex *r;
212 char *scan;
213 char *longest;
214 unsigned int len;
215 int flags;
216 if (exp == NULL)
217 FAIL("NULL argument");
218
219 /* First pass: determine size, legality. */
220 #ifdef notdef
221 if (exp[0] == '.' && exp[1] == '*') exp += 2; /* aid grep */
222 #endif
223 regparse = exp;
224 regnpar = 1;
225 regsize = 0L;
226 regcode = &regdummy;
227 regc(CST_REGMAGIC);
228 if (reg(0, &flags) == NULL)
229 return(NULL);
230
231 /* Small enough for pointer-storage convention? */
232 if (regsize >= 32767L) /* Probably could be 65535L. */
233 FAIL("regexp too big");
234
235 /* Allocate space. */
236 r = cst_alloc(cst_regex,1);
237 r->regsize = regsize;
238 r->program = cst_alloc(char,regsize);
239 if (r == NULL)
240 FAIL("out of space");
241
242 /* Second pass: emit code. */
243 regparse = exp;
244 regnpar = 1;
245 regcode = r->program;
246 regc(CST_REGMAGIC);
247 if (reg(0, &flags) == NULL)
248 return(NULL);
249
250 /* Dig out information for optimizations. */
251 r->regstart = '\0'; /* Worst-case defaults. */
252 r->reganch = 0;
253 r->regmust = NULL;
254 r->regmlen = 0;
255 scan = r->program+1; /* First BRANCH. */
256
257 if (OP(regnext(scan)) == END) { /* Only one top-level choice. */
258 scan = OPERAND(scan);
259
260 /* Starting-point info. */
261 if (OP(scan) == EXACTLY)
262 r->regstart = *OPERAND(scan);
263 else if (OP(scan) == BOL)
264 r->reganch++;
265
266 /*
267 * If there's something expensive in the r.e., find the
268 * longest literal string that must appear and make it the
269 * regmust. Resolve ties in favor of later strings, since
270 * the regstart check works with the beginning of the r.e.
271 * and avoiding duplication strengthens checking. Not a
272 * strong reason, but sufficient in the absence of others.
273 */
274 if (flags&SPSTART) {
275 longest = NULL;
276 len = 0;
277 for (; scan != NULL; scan = regnext(scan))
278 if ((OP(scan) == EXACTLY) &&
279 (cst_strlen(OPERAND(scan)) >= len)) {
280 longest = OPERAND(scan);
281 len = cst_strlen(OPERAND(scan));
282 }
283 r->regmust = longest;
284 r->regmlen = len;
285 }
286 }
287 return(r);
288
289 }
290
291 void
292 hs_regdelete(cst_regex *r)
293 {
294 cst_free(r->program);
295 cst_free(r);
296 }
297
298 /*
299 - reg - regular expression, i.e. main body or parenthesized thing
300 *
301 * Caller must absorb opening parenthesis.
302 *
303 * Combining parenthesis handling with the base level of regular expression
304 * is a trifle forced, but the need to tie the tails of the branches to what
305 * follows makes it hard to avoid.
306 */
307 static char *
308 reg(int paren, int *flagp)
309 /* Parenthesized? */
310
311 {
312 char *ret;
313 char *br;
314 char *ender;
315 int parno=0;
316 int flags;
317
318 *flagp = HASWIDTH; /* Tentatively. */
319
320 /* Make an OPEN node, if parenthesized. */
321 if (paren) {
322 if (regnpar >= CST_NSUBEXP)
323 FAIL("too many ()");
324 parno = regnpar;
325 regnpar++;
326 ret = regnode(OPEN+parno);
327 } else
328 ret = NULL;
329
330 /* Pick up the branches, linking them together. */
331 br = regbranch(&flags);
332 if (br == NULL)
333 return(NULL);
334 if (ret != NULL)
335 regtail(ret, br); /* OPEN -> first. */
336 else
337 ret = br;
338 if (!(flags&HASWIDTH))
339 *flagp &= ~HASWIDTH;
340 *flagp |= flags&SPSTART;
341 while (*regparse == '|' || *regparse == '\n') {
342 regparse++;
343 br = regbranch(&flags);
344 if (br == NULL)
345 return(NULL);
346 regtail(ret, br); /* BRANCH -> BRANCH. */
347 if (!(flags&HASWIDTH))
348 *flagp &= ~HASWIDTH;
349 *flagp |= flags&SPSTART;
350 }
351
352 /* Make a closing node, and hook it on the end. */
353 ender = regnode((paren) ? CLOSE+parno : END);
354 regtail(ret, ender);
355
356 /* Hook the tails of the branches to the closing node. */
357 for (br = ret; br != NULL; br = regnext(br))
358 regoptail(br, ender);
359
360 /* Check for proper termination. */
361 if (paren && *regparse++ != ')') {
362 FAIL("unmatched ()");
363 } else if (!paren && *regparse != '\0') {
364 if (*regparse == ')') {
365 FAIL("unmatched ()");
366 } else
367 FAIL("junk on end"); /* "Can't happen". */
368 /* NOTREACHED */
369 }
370
371 return(ret);
372 }
373
374 /*
375 - regbranch - one alternative of an | operator
376 *
377 * Implements the concatenation operator.
378 */
379 static char *
380 regbranch(int *flagp)
381 {
382 char *ret;
383 char *chain;
384 char *latest;
385 int flags;
386
387 *flagp = WORST; /* Tentatively. */
388
389 ret = regnode(BRANCH);
390 chain = NULL;
391 while (*regparse != '\0' && *regparse != ')' &&
392 *regparse != '\n' && *regparse != '|') {
393 latest = regpiece(&flags);
394 if (latest == NULL)
395 return(NULL);
396 *flagp |= flags&HASWIDTH;
397 if (chain == NULL) /* First piece. */
398 *flagp |= flags&SPSTART;
399 else
400 regtail(chain, latest);
401 chain = latest;
402 }
403 if (chain == NULL) /* Loop ran zero times. */
404 (void) regnode(NOTHING);
405
406 return(ret);
407 }
408
409 /*
410 - regpiece - something followed by possible [*+?]
411 *
412 * Note that the branching code sequences used for ? and the general cases
413 * of * and + are somewhat optimized: they use the same NOTHING node as
414 * both the endmarker for their branch list and the body of the last branch.
415 * It might seem that this node could be dispensed with entirely, but the
416 * endmarker role is not redundant.
417 */
418 static char *
419 regpiece(int *flagp)
420 {
421 char *ret;
422 char op;
423 char *next;
424 int flags;
425
426 ret = regatom(&flags);
427 if (ret == NULL)
428 return(NULL);
429
430 op = *regparse;
431 if (!ISMULT(op)) {
432 *flagp = flags;
433 return(ret);
434 }
435
436 if (!(flags&HASWIDTH) && op != '?')
437 FAIL("*+ operand could be empty");
438 *flagp = (op != '+') ? (WORST|SPSTART) : (WORST|HASWIDTH);
439
440 if (op == '*' && (flags&SIMPLE))
441 reginsert(STAR, ret);
442 else if (op == '*') {
443 /* Emit x* as (x&|), where & means "self". */
444 reginsert(BRANCH, ret); /* Either x */
445 regoptail(ret, regnode(BACK)); /* and loop */
446 regoptail(ret, ret); /* back */
447 regtail(ret, regnode(BRANCH)); /* or */
448 regtail(ret, regnode(NOTHING)); /* null. */
449 } else if (op == '+' && (flags&SIMPLE))
450 reginsert(PLUS, ret);
451 else if (op == '+') {
452 /* Emit x+ as x(&|), where & means "self". */
453 next = regnode(BRANCH); /* Either */
454 regtail(ret, next);
455 regtail(regnode(BACK), ret); /* loop back */
456 regtail(next, regnode(BRANCH)); /* or */
457 regtail(ret, regnode(NOTHING)); /* null. */
458 } else if (op == '?') {
459 /* Emit x? as (x|) */
460 reginsert(BRANCH, ret); /* Either x */
461 regtail(ret, regnode(BRANCH)); /* or */
462 next = regnode(NOTHING); /* null. */
463 regtail(ret, next);
464 regoptail(ret, next);
465 }
466 regparse++;
467 if (ISMULT(*regparse))
468 FAIL("nested *?+");
469
470 return(ret);
471 }
472
473 /*
474 - regatom - the lowest level
475 *
476 * Optimization: gobbles an entire sequence of ordinary characters so that
477 * it can turn them into a single node, which is smaller to store and
478 * faster to run. Backslashed characters are exceptions, each becoming a
479 * separate node; the code is simpler that way and it's not worth fixing.
480 */
481 static char *
482 regatom(int *flagp)
483 {
484 char *ret = NULL;
485 int flags;
486
487 *flagp = WORST; /* Tentatively. */
488
489 switch (*regparse++) {
490 /* FIXME: these chars only have meaning at beg/end of pat? */
491 case '^':
492 ret = regnode(BOL);
493 break;
494 case '$':
495 ret = regnode(EOL);
496 break;
497 case '.':
498 ret = regnode(ANY);
499 *flagp |= HASWIDTH|SIMPLE;
500 break;
501 case '[': {
502 int class1;
503 int classend;
504
505 if (*regparse == '^') { /* Complement of range. */
506 ret = regnode(ANYBUT);
507 regparse++;
508 } else
509 ret = regnode(ANYOF);
510 if (*regparse == ']' || *regparse == '-')
511 regc(*regparse++);
512 while (*regparse != '\0' && *regparse != ']') {
513 if (*regparse == '-') {
514 regparse++;
515 if (*regparse == ']' || *regparse == '\0')
516 regc('-');
517 else {
518 class1 = UCHARAT(regparse-2)+1;
519 classend = UCHARAT(regparse);
520 if (class1 > classend+1)
521 FAIL("invalid [] range");
522 for (; class1 <= classend; class1++)
523 regc(class1);
524 regparse++;
525 }
526 } else
527 regc(*regparse++);
528 }
529 regc('\0');
530 if (*regparse != ']')
531 FAIL("unmatched []");
532 regparse++;
533 *flagp |= HASWIDTH|SIMPLE;
534 }
535 break;
536 case '(':
537 ret = reg(1, &flags);
538 if (ret == NULL)
539 return(NULL);
540 *flagp |= flags&(HASWIDTH|SPSTART);
541 break;
542 case '\0':
543 case '|':
544 case '\n':
545 case ')':
546 FAIL("internal urp"); /* Supposed to be caught earlier. */
547 break;
548 case '?':
549 case '+':
550 case '*':
551 FAIL("?+* follows nothing");
552 break;
553 case '\\':
554 switch (*regparse++) {
555 case '\0':
556 FAIL("trailing \\");
557 break;
558 case '<':
559 ret = regnode(WORDA);
560 break;
561 case '>':
562 ret = regnode(WORDZ);
563 break;
564 /* FIXME: Someday handle \1, \2, ... */
565 default:
566 /* Handle general quoted chars in exact-match routine */
567 goto de_fault;
568 }
569 break;
570 de_fault:
571 default:
572 /*
573 * Encode a string of characters to be matched exactly.
574 *
575 * This is a bit tricky due to quoted chars and due to
576 * '*', '+', and '?' taking the SINGLE char previous
577 * as their operand.
578 *
579 * On entry, the char at regparse[-1] is going to go
580 * into the string, no matter what it is. (It could be
581 * following a \ if we are entered from the '\' case.)
582 *
583 * Basic idea is to pick up a good char in ch and
584 * examine the next char. If it's *+? then we twiddle.
585 * If it's \ then we frozzle. If it's other magic char
586 * we push ch and terminate the string. If none of the
587 * above, we push ch on the string and go around again.
588 *
589 * regprev is used to remember where "the current char"
590 * starts in the string, if due to a *+? we need to back
591 * up and put the current char in a separate, 1-char, string.
592 * When regprev is NULL, ch is the only char in the
593 * string; this is used in *+? handling, and in setting
594 * flags |= SIMPLE at the end.
595 */
596 {
597 const char *regprev;
598 char ch = 0;
599
600 regparse--; /* Look at cur char */
601 ret = regnode(EXACTLY);
602 for ( regprev = 0 ; ; ) {
603 ch = *regparse++; /* Get current char */
604 switch (*regparse) { /* look at next one */
605
606 default:
607 regc(ch); /* Add cur to string */
608 break;
609
610 case '.': case '[': case '(':
611 case ')': case '|': case '\n':
612 case '$': case '^':
613 case '\0':
614 /* FIXME, $ and ^ should not always be magic */
615 magic:
616 regc(ch); /* dump cur char */
617 goto done; /* and we are done */
618
619 case '?': case '+': case '*':
620 if (!regprev) /* If just ch in str, */
621 goto magic; /* use it */
622 /* End mult-char string one early */
623 regparse = regprev; /* Back up parse */
624 goto done;
625
626 case '\\':
627 regc(ch); /* Cur char OK */
628 switch (regparse[1]){ /* Look after \ */
629 case '\0':
630 case '<':
631 case '>':
632 /* FIXME: Someday handle \1, \2, ... */
633 goto done; /* Not quoted */
634 default:
635 /* Backup point is \, scan * point is after it. */
636 regprev = regparse;
637 regparse++;
638 continue; /* NOT break; */
639 }
640 }
641 regprev = regparse; /* Set backup point */
642 }
643 done:
644 regc('\0');
645 *flagp |= HASWIDTH;
646 if (!regprev) /* One char? */
647 *flagp |= SIMPLE;
648 }
649 break;
650 }
651
652 return(ret);
653 }
654
655 /*
656 - regnode - emit a node
657 */
658 static char * /* Location. */
659 regnode(char op)
660 {
661 char *ret;
662 char *ptr;
663
664 ret = regcode;
665 if (ret == &regdummy) {
666 regsize += 3;
667 return(ret);
668 }
669
670 ptr = ret;
671 *ptr++ = op;
672 *ptr++ = '\0'; /* Null "next" pointer. */
673 *ptr++ = '\0';
674 regcode = ptr;
675
676 return(ret);
677 }
678
679 /*
680 - regc - emit (if appropriate) a byte of code
681 */
682 static void
683 regc(char b)
684 {
685 if (regcode != &regdummy)
686 *regcode++ = b;
687 else
688 regsize++;
689 }
690
691 /*
692 - reginsert - insert an operator in front of already-emitted operand
693 *
694 * Means relocating the operand.
695 */
696 static void
697 reginsert(char op, char *opnd)
698 {
699 char *src;
700 char *dst;
701 char *place;
702
703 if (regcode == &regdummy) {
704 regsize += 3;
705 return;
706 }
707
708 src = regcode;
709 regcode += 3;
710 dst = regcode;
711 while (src > opnd)
712 *--dst = *--src;
713
714 place = opnd; /* Op node, where operand used to be. */
715 *place++ = op;
716 *place++ = '\0';
717 *place++ = '\0';
718 }
719
720 /*
721 - regtail - set the next-pointer at the end of a node chain
722 */
723 static void
724 regtail(char *p, char *val)
725 {
726 char *scan;
727 char *temp;
728 int offset;
729
730 if (p == &regdummy)
731 return;
732
733 /* Find last node. */
734 scan = p;
735 for (;;) {
736 temp = regnext(scan);
737 if (temp == NULL)
738 break;
739 scan = temp;
740 }
741
742 if (OP(scan) == BACK)
743 offset = scan - val;
744 else
745 offset = val - scan;
746 *(scan+1) = (offset>>8)&0377;
747 *(scan+2) = offset&0377;
748 }
749
750 /*
751 - regoptail - regtail on operand of first argument; nop if operandless
752 */
753 static void
754 regoptail(char *p, char *val)
755 {
756 /* "Operandless" and "op != BRANCH" are synonymous in practice. */
757 if (p == NULL || p == &regdummy || OP(p) != BRANCH)
758 return;
759 regtail(OPERAND(p), val);
760 }
761
762 /*
763 * regexec and friends
764 */
765
766 /* [email protected] changed all this stuff to use a state structure
767 (and thus, be re-entrant) 2001-10-18 */
768
769 /*
770 * Forwards.
771 */
772 STATIC int regtry(cst_regstate *state, const char *string, char *prog);
773 STATIC int regmatch(cst_regstate *state, char *scan);
774 STATIC int regrepeat(cst_regstate *state, char *p);
775
776 #ifdef UNDER_CE
777 #undef DEBUG /* Just does not work on WinCE... */
778 #endif
779
780 #ifdef DEBUG
781 #define regnarrate stdout
782 void regdump();
783 STATIC char *regprop(char *scan);
784 #endif
785
786 /*
787 - regexec - match a regexp against a string
788 */
789 cst_regstate *
790 hs_regexec(const cst_regex *prog, const char *string)
791 {
792 cst_regstate *state;
793 char *s;
794
795 /* Be paranoid... */
796 if (prog == NULL || string == NULL) {
797 FAIL("NULL parameter");
798 return(0);
799 }
800
801 /* Check validity of program. */
802 if (UCHARAT(prog->program) != CST_REGMAGIC) {
803 FAIL("corrupted program");
804 return(0);
805 }
806
807 /* If there is a "must appear" string, look for it. */
808 if (prog->regmust != NULL) {
809 s = (char *)string;
810 while ((s = strchr(s, prog->regmust[0])) != NULL) {
811 if (strncmp(s, prog->regmust, prog->regmlen) == 0)
812 break; /* Found it. */
813 s++;
814 }
815 if (s == NULL) /* Not present. */
816 return(0);
817 }
818
819 state = cst_alloc(cst_regstate, 1);
820 /* Mark beginning of line for ^ . */
821 state->bol = string;
822
823 /* Simplest case: anchored match need be tried only once. */
824 if (prog->reganch) {
825 if (regtry(state, string, prog->program+1))
826 return state;
827 else {
828 cst_free(state);
829 return NULL;
830 }
831 }
832
833 /* Messy cases: unanchored match. */
834 s = (char *)string;
835 if (prog->regstart != '\0')
836 /* We know what char it must start with. */
837 while ((s = strchr(s, prog->regstart)) != NULL) {
838 if (regtry(state, s, prog->program+1))
839 return state;
840 s++;
841 }
842 else
843 /* We don't -- general case. */
844 do {
845 if (regtry(state, s, prog->program+1))
846 return state;
847 } while (*s++ != '\0');
848
849 cst_free(state);
850 return NULL;
851 }
852
853 /*
854 - regtry - try match at specific point
855 */
856 static int /* 0 failure, 1 success */
857 regtry(cst_regstate *state, const char *string, char *prog)
858 {
859 int i;
860 const char **sp;
861 const char **ep;
862
863 state->input = string;
864
865 sp = state->startp;
866 ep = state->endp;
867 for (i = CST_NSUBEXP; i > 0; i--) {
868 *sp++ = NULL;
869 *ep++ = NULL;
870 }
871 if (regmatch(state, prog)) {
872 state->startp[0] = (char *)string;
873 state->endp[0] = (char *)state->input;
874 return(1);
875 } else
876 return(0);
877 }
878
879 /*
880 - regmatch - main matching routine
881 *
882 * Conceptually the strategy is simple: check to see whether the current
883 * node matches, call self recursively to see whether the rest matches,
884 * and then act accordingly. In practice we make some effort to avoid
885 * recursion, in particular by going through "ordinary" nodes (that don't
886 * need to know whether the rest of the match failed) by a loop instead of
887 * by recursion.
888 */
889 static int /* 0 failure, 1 success */
890 regmatch(cst_regstate *state, char *scan)
891 {
892 char *next; /* Next node. */
893
894 #ifdef DEBUG
895 if (scan != NULL && regnarrate)
896 fprintf(regnarrate, "%s(\n", regprop(scan));
897 #endif
898 while (scan != NULL) {
899 #ifdef DEBUG
900 if (regnarrate)
901 fprintf(regnarrate, "%s...\n", regprop(scan));
902 #endif
903 next = regnext(scan);
904
905 switch (OP(scan)) {
906 case BOL:
907 if (state->input != state->bol)
908 return(0);
909 break;
910 case EOL:
911 if (*state->input != '\0')
912 return(0);
913 break;
914 case WORDA:
915 /* Must be looking at a letter, digit, or _ */
916 if ((!isalnum((int)*state->input)) && *state->input != '_')
917 return(0);
918 /* Prev must be BOL or nonword */
919 if (state->input > state->bol &&
920 (isalnum((int)state->input[-1]) || state->input[-1] == '_'))
921 return(0);
922 break;
923 case WORDZ:
924 /* Must be looking at non letter, digit, or _ */
925 if (isalnum((int)*state->input) || *state->input == '_')
926 return(0);
927 /* We don't care what the previous char was */
928 break;
929 case ANY:
930 if (*state->input == '\0')
931 return(0);
932 state->input++;
933 break;
934 case EXACTLY: {
935 int len;
936 char *opnd;
937
938 opnd = OPERAND(scan);
939 /* Inline the first character, for speed. */
940 if (*opnd != *state->input)
941 return(0);
942 len = cst_strlen(opnd);
943 if (len > 1 && strncmp(opnd, state->input, len) != 0)
944 return(0);
945 state->input += len;
946 }
947 break;
948 case ANYOF:
949 if (*state->input == '\0' || strchr(OPERAND(scan), *state->input) == NULL)
950 return(0);
951 state->input++;
952 break;
953 case ANYBUT:
954 if (*state->input == '\0' || strchr(OPERAND(scan), *state->input) != NULL)
955 return(0);
956 state->input++;
957 break;
958 case NOTHING:
959 break;
960 case BACK:
961 break;
962 case OPEN+1:
963 case OPEN+2:
964 case OPEN+3:
965 case OPEN+4:
966 case OPEN+5:
967 case OPEN+6:
968 case OPEN+7:
969 case OPEN+8:
970 case OPEN+9: {
971 int no;
972 const char *save;
973
974 no = OP(scan) - OPEN;
975 save = state->input;
976
977 if (regmatch(state, next)) {
978 /*
979 * Don't set startp if some later
980 * invocation of the same parentheses
981 * already has.
982 */
983 if (state->startp[no] == NULL)
984 state->startp[no] = save;
985 return(1);
986 } else
987 return(0);
988 }
989 break;
990 case CLOSE+1:
991 case CLOSE+2:
992 case CLOSE+3:
993 case CLOSE+4:
994 case CLOSE+5:
995 case CLOSE+6:
996 case CLOSE+7:
997 case CLOSE+8:
998 case CLOSE+9: {
999 int no;
1000 const char *save;
1001
1002 no = OP(scan) - CLOSE;
1003 save = state->input;
1004
1005 if (regmatch(state, next)) {
1006 /*
1007 * Don't set endp if some later
1008 * invocation of the same parentheses
1009 * already has.
1010 */
1011 if (state->endp[no] == NULL)
1012 state->endp[no] = save;
1013 return(1);
1014 } else
1015 return(0);
1016 }
1017 break;
1018 case BRANCH: {
1019 const char *save;
1020
1021 if (OP(next) != BRANCH) /* No choice. */
1022 next = OPERAND(scan); /* Avoid recursion. */
1023 else {
1024 do {
1025 save = state->input;
1026 if (regmatch(state, OPERAND(scan)))
1027 return(1);
1028 state->input = save;
1029 scan = regnext(scan);
1030 } while (scan != NULL && OP(scan) == BRANCH);
1031 return(0);
1032 /* NOTREACHED */
1033 }
1034 }
1035 break;
1036 case STAR:
1037 case PLUS: {
1038 char nextch;
1039 int no;
1040 const char *save;
1041 int min;
1042
1043 /*
1044 * Lookahead to avoid useless match attempts
1045 * when we know what character comes next.
1046 */
1047 nextch = '\0';
1048 if (OP(next) == EXACTLY)
1049 nextch = *OPERAND(next);
1050 min = (OP(scan) == STAR) ? 0 : 1;
1051 save = state->input;
1052
1053 no = regrepeat(state, OPERAND(scan));
1054 while (no >= min) {
1055 /* If it could work, try it. */
1056 if (nextch == '\0' || *state->input == nextch)
1057 {
1058 if (regmatch(state, next))
1059 return(1);
1060 }
1061 /* Couldn't or didn't -- back up. */
1062 no--;
1063 state->input = save + no;
1064 }
1065 return(0);
1066 }
1067 break;
1068 case END:
1069 return(1); /* Success! */
1070 break;
1071 default:
1072 FAIL("memory corruption");
1073 return(0);
1074 break;
1075 }
1076
1077 scan = next;
1078 }
1079
1080 /*
1081 * We get here only if there's trouble -- normally "case END" is
1082 * the terminating point.
1083 */
1084 FAIL("corrupted pointers");
1085 return(0);
1086 }
1087
1088 /*
1089 - regrepeat - repeatedly match something simple, report how many
1090 */
1091 static int
1092 regrepeat(cst_regstate *state, char *p)
1093 {
1094 int count = 0;
1095 const char *scan;
1096 char *opnd;
1097
1098 scan = state->input;
1099 opnd = OPERAND(p);
1100 switch (OP(p)) {
1101 case ANY:
1102 count = cst_strlen(scan);
1103 scan += count;
1104 break;
1105 case EXACTLY:
1106 while (*opnd == *scan) {
1107 count++;
1108 scan++;
1109 }
1110 break;
1111 case ANYOF:
1112 while (*scan != '\0' && strchr(opnd, *scan) != NULL) {
1113 count++;
1114 scan++;
1115 }
1116 break;
1117 case ANYBUT:
1118 while (*scan != '\0' && strchr(opnd, *scan) == NULL) {
1119 count++;
1120 scan++;
1121 }
1122 break;
1123 default: /* Oh dear. Called inappropriately. */
1124 FAIL("internal foulup");
1125 count = 0; /* Best compromise. */
1126 break;
1127 }
1128 state->input = scan;
1129
1130 return(count);
1131 }
1132
1133 /*
1134 - regnext - dig the "next" pointer out of a node
1135 */
1136 static char *
1137 regnext(char *p)
1138 {
1139 int offset;
1140
1141 if (p == &regdummy)
1142 return(NULL);
1143
1144 offset = NEXT(p);
1145 if (offset == 0)
1146 return(NULL);
1147
1148 if (OP(p) == BACK)
1149 return(p-offset);
1150 else
1151 return(p+offset);
1152 }
1153
1154 #ifdef DEBUG
1155
1156 STATIC char *regprop(char *scan);
1157
1158 /*
1159 - regdump - dump a regexp onto stdout in vaguely comprehensible form
1160 */
1161 void
1162 regdump(cst_regex *r)
1163 {
1164 char *s;
1165 char op = EXACTLY; /* Arbitrary non-END op. */
1166 char *next;
1167
1168
1169 s = r->program + 1;
1170 while (op != END) { /* While that wasn't END last time... */
1171 op = OP(s);
1172 printf("%2d%s", s-r->program, regprop(s)); /* Where, what. */
1173 next = regnext(s);
1174 if (next == NULL) /* Next ptr. */
1175 printf("(0)");
1176 else
1177 printf("(%d)", (s-r->program)+(next-s));
1178 s += 3;
1179 if (op == ANYOF || op == ANYBUT || op == EXACTLY) {
1180 /* Literal string, where present. */
1181 while (*s != '\0') {
1182 putchar(*s);
1183 s++;
1184 }
1185 s++;
1186 }
1187 putchar('\n');
1188 }
1189
1190 /* Header fields of interest. */
1191 if (r->regstart != '\0')
1192 printf("start `%c' ", r->regstart);
1193 if (r->reganch)
1194 printf("anchored ");
1195 if (r->regmust != NULL)
1196 printf("must have \"%s\"", r->regmust);
1197 printf("\n");
1198 }
1199
1200 /*
1201 - regprop - printable representation of opcode
1202 */
1203 static char *
1204 regprop(char *op)
1205 {
1206 char *p=NULL;
1207 static char buf[50];
1208
1209 (void) strcpy(buf, ":");
1210
1211 switch (OP(op)) {
1212 case BOL:
1213 p = "BOL";
1214 break;
1215 case EOL:
1216 p = "EOL";
1217 break;
1218 case ANY:
1219 p = "ANY";
1220 break;
1221 case ANYOF:
1222 p = "ANYOF";
1223 break;
1224 case ANYBUT:
1225 p = "ANYBUT";
1226 break;
1227 case BRANCH:
1228 p = "BRANCH";
1229 break;
1230 case EXACTLY:
1231 p = "EXACTLY";
1232 break;
1233 case NOTHING:
1234 p = "NOTHING";
1235 break;
1236 case BACK:
1237 p = "BACK";
1238 break;
1239 case END:
1240 p = "END";
1241 break;
1242 case OPEN+1:
1243 case OPEN+2:
1244 case OPEN+3:
1245 case OPEN+4:
1246 case OPEN+5:
1247 case OPEN+6:
1248 case OPEN+7:
1249 case OPEN+8:
1250 case OPEN+9:
1251 cst_sprintf(buf+cst_strlen(buf), "OPEN%d", OP(op)-OPEN);
1252 p = NULL;
1253 break;
1254 case CLOSE+1:
1255 case CLOSE+2:
1256 case CLOSE+3:
1257 case CLOSE+4:
1258 case CLOSE+5:
1259 case CLOSE+6:
1260 case CLOSE+7:
1261 case CLOSE+8:
1262 case CLOSE+9:
1263 cst_sprintf(buf+cst_strlen(buf), "CLOSE%d", OP(op)-CLOSE);
1264 p = NULL;
1265 break;
1266 case STAR:
1267 p = "STAR";
1268 break;
1269 case PLUS:
1270 p = "PLUS";
1271 break;
1272 case WORDA:
1273 p = "WORDA";
1274 break;
1275 case WORDZ:
1276 p = "WORDZ";
1277 break;
1278 default:
1279 FAIL("corrupted opcode");
1280 break;
1281 }
1282 if (p != NULL)
1283 (void) strcat(buf, p);
1284 return(buf);
1285 }
1286 #endif
1287
1288 /*
1289 * The following is provided for those people who do not have strcspn() in
1290 * their C libraries. They should get off their butts and do something
1291 * about it; at least one public-domain implementation of those (highly
1292 * useful) string routines has been published on Usenet.
1293 */
1294 #ifdef STRCSPN
1295 /*
1296 * strcspn - find length of initial segment of s1 consisting entirely
1297 * of characters not from s2
1298 */
1299
1300 static int
1301 strcspn(s1, s2)
1302 char *s1;
1303 char *s2;
1304 {
1305 char *scan1;
1306 char *scan2;
1307 int count;
1308
1309 count = 0;
1310 for (scan1 = s1; *scan1 != '\0'; scan1++) {
1311 for (scan2 = s2; *scan2 != '\0';) /* ++ moved down. */
1312 if (*scan1 == *scan2++)
1313 return(count);
1314 count++;
1315 }
1316 return(count);
1317 }
1318 #endif