scintilla: Update scintilla with changeset 3662:1d1c06df8a2f using gtk+3
[anjuta-extras.git] / plugins / scintilla / scintilla / RESearch.cxx
blobf26375fe50fdd1363ef048c464c09ada89106fed
1 // Scintilla source code edit control
2 /** @file RESearch.cxx
3 ** Regular expression search library.
4 **/
6 /*
7 * regex - Regular expression pattern matching and replacement
9 * By: Ozan S. Yigit (oz)
10 * Dept. of Computer Science
11 * York University
13 * Original code available from http://www.cs.yorku.ca/~oz/
14 * Translation to C++ by Neil Hodgson neilh@scintilla.org
15 * Removed all use of register.
16 * Converted to modern function prototypes.
17 * Put all global/static variables into an object so this code can be
18 * used from multiple threads, etc.
19 * Some extensions by Philippe Lhoste PhiLho(a)GMX.net
20 * '?' extensions by Michael Mullin masmullin@gmail.com
22 * These routines are the PUBLIC DOMAIN equivalents of regex
23 * routines as found in 4.nBSD UN*X, with minor extensions.
25 * These routines are derived from various implementations found
26 * in software tools books, and Conroy's grep. They are NOT derived
27 * from licensed/restricted software.
28 * For more interesting/academic/complicated implementations,
29 * see Henry Spencer's regexp routines, or GNU Emacs pattern
30 * matching module.
32 * Modification history removed.
34 * Interfaces:
35 * RESearch::Compile: compile a regular expression into a NFA.
37 * const char *RESearch::Compile(const char *pattern, int length,
38 * bool caseSensitive, bool posix)
40 * Returns a short error string if they fail.
42 * RESearch::Execute: execute the NFA to match a pattern.
44 * int RESearch::Execute(characterIndexer &ci, int lp, int endp)
46 * RESearch::Substitute: substitute the matched portions in a new string.
48 * int RESearch::Substitute(CharacterIndexer &ci, char *src, char *dst)
50 * re_fail: failure routine for RESearch::Execute. (no longer used)
52 * void re_fail(char *msg, char op)
54 * Regular Expressions:
56 * [1] char matches itself, unless it is a special
57 * character (metachar): . \ [ ] * + ? ^ $
58 * and ( ) if posix option.
60 * [2] . matches any character.
62 * [3] \ matches the character following it, except:
63 * - \a, \b, \f, \n, \r, \t, \v match the corresponding C
64 * escape char, respectively BEL, BS, FF, LF, CR, TAB and VT;
65 * Note that \r and \n are never matched because Scintilla
66 * regex searches are made line per line
67 * (stripped of end-of-line chars).
68 * - if not in posix mode, when followed by a
69 * left or right round bracket (see [8]);
70 * - when followed by a digit 1 to 9 (see [9]);
71 * - when followed by a left or right angle bracket
72 * (see [10]);
73 * - when followed by d, D, s, S, w or W (see [11]);
74 * - when followed by x and two hexa digits (see [12].
75 * Backslash is used as an escape character for all
76 * other meta-characters, and itself.
78 * [4] [set] matches one of the characters in the set.
79 * If the first character in the set is "^",
80 * it matches the characters NOT in the set, i.e.
81 * complements the set. A shorthand S-E (start dash end)
82 * is used to specify a set of characters S up to
83 * E, inclusive. S and E must be characters, otherwise
84 * the dash is taken literally (eg. in expression [\d-a]).
85 * The special characters "]" and "-" have no special
86 * meaning if they appear as the first chars in the set.
87 * To include both, put - first: [-]A-Z]
88 * (or just backslash them).
89 * examples: match:
91 * [-]|] matches these 3 chars,
93 * []-|] matches from ] to | chars
95 * [a-z] any lowercase alpha
97 * [^-]] any char except - and ]
99 * [^A-Z] any char except uppercase
100 * alpha
102 * [a-zA-Z] any alpha
104 * [5] * any regular expression form [1] to [4]
105 * (except [8], [9] and [10] forms of [3]),
106 * followed by closure char (*)
107 * matches zero or more matches of that form.
109 * [6] + same as [5], except it matches one or more.
111 * [5-6] Both [5] and [6] are greedy (they match as much as possible).
112 * Unless they are followed by the 'lazy' quantifier (?)
113 * In which case both [5] and [6] try to match as little as possible
115 * [7] ? same as [5] except it matches zero or one.
117 * [8] a regular expression in the form [1] to [13], enclosed
118 * as \(form\) (or (form) with posix flag) matches what
119 * form matches. The enclosure creates a set of tags,
120 * used for [9] and for pattern substitution.
121 * The tagged forms are numbered starting from 1.
123 * [9] a \ followed by a digit 1 to 9 matches whatever a
124 * previously tagged regular expression ([8]) matched.
126 * [10] \< a regular expression starting with a \< construct
127 * \> and/or ending with a \> construct, restricts the
128 * pattern matching to the beginning of a word, and/or
129 * the end of a word. A word is defined to be a character
130 * string beginning and/or ending with the characters
131 * A-Z a-z 0-9 and _. Scintilla extends this definition
132 * by user setting. The word must also be preceded and/or
133 * followed by any character outside those mentioned.
135 * [11] \l a backslash followed by d, D, s, S, w or W,
136 * becomes a character class (both inside and
137 * outside sets []).
138 * d: decimal digits
139 * D: any char except decimal digits
140 * s: whitespace (space, \t \n \r \f \v)
141 * S: any char except whitespace (see above)
142 * w: alphanumeric & underscore (changed by user setting)
143 * W: any char except alphanumeric & underscore (see above)
145 * [12] \xHH a backslash followed by x and two hexa digits,
146 * becomes the character whose Ascii code is equal
147 * to these digits. If not followed by two digits,
148 * it is 'x' char itself.
150 * [13] a composite regular expression xy where x and y
151 * are in the form [1] to [12] matches the longest
152 * match of x followed by a match for y.
154 * [14] ^ a regular expression starting with a ^ character
155 * $ and/or ending with a $ character, restricts the
156 * pattern matching to the beginning of the line,
157 * or the end of line. [anchors] Elsewhere in the
158 * pattern, ^ and $ are treated as ordinary characters.
161 * Acknowledgements:
163 * HCR's Hugh Redelmeier has been most helpful in various
164 * stages of development. He convinced me to include BOW
165 * and EOW constructs, originally invented by Rob Pike at
166 * the University of Toronto.
168 * References:
169 * Software tools Kernighan & Plauger
170 * Software tools in Pascal Kernighan & Plauger
171 * Grep [rsx-11 C dist] David Conroy
172 * ed - text editor Un*x Programmer's Manual
173 * Advanced editing on Un*x B. W. Kernighan
174 * RegExp routines Henry Spencer
176 * Notes:
178 * This implementation uses a bit-set representation for character
179 * classes for speed and compactness. Each character is represented
180 * by one bit in a 256-bit block. Thus, CCL always takes a
181 * constant 32 bytes in the internal nfa, and RESearch::Execute does a single
182 * bit comparison to locate the character in the set.
184 * Examples:
186 * pattern: foo*.*
187 * compile: CHR f CHR o CLO CHR o END CLO ANY END END
188 * matches: fo foo fooo foobar fobar foxx ...
190 * pattern: fo[ob]a[rz]
191 * compile: CHR f CHR o CCL bitset CHR a CCL bitset END
192 * matches: fobar fooar fobaz fooaz
194 * pattern: foo\\+
195 * compile: CHR f CHR o CHR o CHR \ CLO CHR \ END END
196 * matches: foo\ foo\\ foo\\\ ...
198 * pattern: \(foo\)[1-3]\1 (same as foo[1-3]foo)
199 * compile: BOT 1 CHR f CHR o CHR o EOT 1 CCL bitset REF 1 END
200 * matches: foo1foo foo2foo foo3foo
202 * pattern: \(fo.*\)-\1
203 * compile: BOT 1 CHR f CHR o CLO ANY END EOT 1 CHR - REF 1 END
204 * matches: foo-foo fo-fo fob-fob foobar-foobar ...
207 #include <stdlib.h>
209 #include "CharClassify.h"
210 #include "RESearch.h"
212 // Shut up annoying Visual C++ warnings:
213 #ifdef _MSC_VER
214 #pragma warning(disable: 4514)
215 #endif
217 #ifdef SCI_NAMESPACE
218 using namespace Scintilla;
219 #endif
221 #define OKP 1
222 #define NOP 0
224 #define CHR 1
225 #define ANY 2
226 #define CCL 3
227 #define BOL 4
228 #define EOL 5
229 #define BOT 6
230 #define EOT 7
231 #define BOW 8
232 #define EOW 9
233 #define REF 10
234 #define CLO 11
235 #define CLQ 12 /* 0 to 1 closure */
236 #define LCLO 13 /* lazy closure */
238 #define END 0
241 * The following defines are not meant to be changeable.
242 * They are for readability only.
244 #define BLKIND 0370
245 #define BITIND 07
247 const char bitarr[] = { 1, 2, 4, 8, 16, 32, 64, '\200' };
249 #define badpat(x) (*nfa = END, x)
252 * Character classification table for word boundary operators BOW
253 * and EOW is passed in by the creator of this object (Scintilla
254 * Document). The Document default state is that word chars are:
255 * 0-9, a-z, A-Z and _
258 RESearch::RESearch(CharClassify *charClassTable) {
259 failure = 0;
260 charClass = charClassTable;
261 Init();
264 RESearch::~RESearch() {
265 Clear();
268 void RESearch::Init() {
269 sta = NOP; /* status of lastpat */
270 bol = 0;
271 for (int i = 0; i < MAXTAG; i++)
272 pat[i] = 0;
273 for (int j = 0; j < BITBLK; j++)
274 bittab[j] = 0;
277 void RESearch::Clear() {
278 for (int i = 0; i < MAXTAG; i++) {
279 delete []pat[i];
280 pat[i] = 0;
281 bopat[i] = NOTFOUND;
282 eopat[i] = NOTFOUND;
286 bool RESearch::GrabMatches(CharacterIndexer &ci) {
287 bool success = true;
288 for (unsigned int i = 0; i < MAXTAG; i++) {
289 if ((bopat[i] != NOTFOUND) && (eopat[i] != NOTFOUND)) {
290 unsigned int len = eopat[i] - bopat[i];
291 pat[i] = new char[len + 1];
292 if (pat[i]) {
293 for (unsigned int j = 0; j < len; j++)
294 pat[i][j] = ci.CharAt(bopat[i] + j);
295 pat[i][len] = '\0';
296 } else {
297 success = false;
301 return success;
304 void RESearch::ChSet(unsigned char c) {
305 bittab[((c) & BLKIND) >> 3] |= bitarr[(c) & BITIND];
308 void RESearch::ChSetWithCase(unsigned char c, bool caseSensitive) {
309 if (caseSensitive) {
310 ChSet(c);
311 } else {
312 if ((c >= 'a') && (c <= 'z')) {
313 ChSet(c);
314 ChSet(static_cast<unsigned char>(c - 'a' + 'A'));
315 } else if ((c >= 'A') && (c <= 'Z')) {
316 ChSet(c);
317 ChSet(static_cast<unsigned char>(c - 'A' + 'a'));
318 } else {
319 ChSet(c);
324 const unsigned char escapeValue(unsigned char ch) {
325 switch (ch) {
326 case 'a': return '\a';
327 case 'b': return '\b';
328 case 'f': return '\f';
329 case 'n': return '\n';
330 case 'r': return '\r';
331 case 't': return '\t';
332 case 'v': return '\v';
334 return 0;
337 static int GetHexaChar(unsigned char hd1, unsigned char hd2) {
338 int hexValue = 0;
339 if (hd1 >= '0' && hd1 <= '9') {
340 hexValue += 16 * (hd1 - '0');
341 } else if (hd1 >= 'A' && hd1 <= 'F') {
342 hexValue += 16 * (hd1 - 'A' + 10);
343 } else if (hd1 >= 'a' && hd1 <= 'f') {
344 hexValue += 16 * (hd1 - 'a' + 10);
345 } else
346 return -1;
347 if (hd2 >= '0' && hd2 <= '9') {
348 hexValue += hd2 - '0';
349 } else if (hd2 >= 'A' && hd2 <= 'F') {
350 hexValue += hd2 - 'A' + 10;
351 } else if (hd2 >= 'a' && hd2 <= 'f') {
352 hexValue += hd2 - 'a' + 10;
353 } else
354 return -1;
355 return hexValue;
359 * Called when the parser finds a backslash not followed
360 * by a valid expression (like \( in non-Posix mode).
361 * @param pattern: pointer on the char after the backslash.
362 * @param incr: (out) number of chars to skip after expression evaluation.
363 * @return the char if it resolves to a simple char,
364 * or -1 for a char class. In this case, bittab is changed.
366 int RESearch::GetBackslashExpression(
367 const char *pattern,
368 int &incr) {
369 // Since error reporting is primitive and messages are not used anyway,
370 // I choose to interpret unexpected syntax in a logical way instead
371 // of reporting errors. Otherwise, we can stick on, eg., PCRE behavior.
372 incr = 0; // Most of the time, will skip the char "naturally".
373 int c;
374 int result = -1;
375 unsigned char bsc = *pattern;
376 if (!bsc) {
377 // Avoid overrun
378 result = '\\'; // \ at end of pattern, take it literally
379 return result;
382 switch (bsc) {
383 case 'a':
384 case 'b':
385 case 'n':
386 case 'f':
387 case 'r':
388 case 't':
389 case 'v':
390 result = escapeValue(bsc);
391 break;
392 case 'x': {
393 unsigned char hd1 = *(pattern + 1);
394 unsigned char hd2 = *(pattern + 2);
395 int hexValue = GetHexaChar(hd1, hd2);
396 if (hexValue >= 0) {
397 result = hexValue;
398 incr = 2; // Must skip the digits
399 } else {
400 result = 'x'; // \x without 2 digits: see it as 'x'
403 break;
404 case 'd':
405 for (c = '0'; c <= '9'; c++) {
406 ChSet(static_cast<unsigned char>(c));
408 break;
409 case 'D':
410 for (c = 0; c < MAXCHR; c++) {
411 if (c < '0' || c > '9') {
412 ChSet(static_cast<unsigned char>(c));
415 break;
416 case 's':
417 ChSet(' ');
418 ChSet('\t');
419 ChSet('\n');
420 ChSet('\r');
421 ChSet('\f');
422 ChSet('\v');
423 break;
424 case 'S':
425 for (c = 0; c < MAXCHR; c++) {
426 if (c != ' ' && !(c >= 0x09 && c <= 0x0D)) {
427 ChSet(static_cast<unsigned char>(c));
430 break;
431 case 'w':
432 for (c = 0; c < MAXCHR; c++) {
433 if (iswordc(static_cast<unsigned char>(c))) {
434 ChSet(static_cast<unsigned char>(c));
437 break;
438 case 'W':
439 for (c = 0; c < MAXCHR; c++) {
440 if (!iswordc(static_cast<unsigned char>(c))) {
441 ChSet(static_cast<unsigned char>(c));
444 break;
445 default:
446 result = bsc;
448 return result;
451 const char *RESearch::Compile(const char *pattern, int length, bool caseSensitive, bool posix) {
452 char *mp=nfa; /* nfa pointer */
453 char *lp; /* saved pointer */
454 char *sp=nfa; /* another one */
455 char *mpMax = mp + MAXNFA - BITBLK - 10;
457 int tagi = 0; /* tag stack index */
458 int tagc = 1; /* actual tag count */
460 int n;
461 char mask; /* xor mask -CCL/NCL */
462 int c1, c2, prevChar;
464 if (!pattern || !length) {
465 if (sta)
466 return 0;
467 else
468 return badpat("No previous regular expression");
470 sta = NOP;
472 const char *p=pattern; /* pattern pointer */
473 for (int i=0; i<length; i++, p++) {
474 if (mp > mpMax)
475 return badpat("Pattern too long");
476 lp = mp;
477 switch (*p) {
479 case '.': /* match any char */
480 *mp++ = ANY;
481 break;
483 case '^': /* match beginning */
484 if (p == pattern)
485 *mp++ = BOL;
486 else {
487 *mp++ = CHR;
488 *mp++ = *p;
490 break;
492 case '$': /* match endofline */
493 if (!*(p+1))
494 *mp++ = EOL;
495 else {
496 *mp++ = CHR;
497 *mp++ = *p;
499 break;
501 case '[': /* match char class */
502 *mp++ = CCL;
503 prevChar = 0;
505 i++;
506 if (*++p == '^') {
507 mask = '\377';
508 i++;
509 p++;
510 } else
511 mask = 0;
513 if (*p == '-') { /* real dash */
514 i++;
515 prevChar = *p;
516 ChSet(*p++);
518 if (*p == ']') { /* real brace */
519 i++;
520 prevChar = *p;
521 ChSet(*p++);
523 while (*p && *p != ']') {
524 if (*p == '-') {
525 if (prevChar < 0) {
526 // Previous def. was a char class like \d, take dash literally
527 prevChar = *p;
528 ChSet(*p);
529 } else if (*(p+1)) {
530 if (*(p+1) != ']') {
531 c1 = prevChar + 1;
532 i++;
533 c2 = static_cast<unsigned char>(*++p);
534 if (c2 == '\\') {
535 if (!*(p+1)) // End of RE
536 return badpat("Missing ]");
537 else {
538 i++;
539 p++;
540 int incr;
541 c2 = GetBackslashExpression(p, incr);
542 i += incr;
543 p += incr;
544 if (c2 >= 0) {
545 // Convention: \c (c is any char) is case sensitive, whatever the option
546 ChSet(static_cast<unsigned char>(c2));
547 prevChar = c2;
548 } else {
549 // bittab is already changed
550 prevChar = -1;
554 if (prevChar < 0) {
555 // Char after dash is char class like \d, take dash literally
556 prevChar = '-';
557 ChSet('-');
558 } else {
559 // Put all chars between c1 and c2 included in the char set
560 while (c1 <= c2) {
561 ChSetWithCase(static_cast<unsigned char>(c1++), caseSensitive);
564 } else {
565 // Dash before the ], take it literally
566 prevChar = *p;
567 ChSet(*p);
569 } else {
570 return badpat("Missing ]");
572 } else if (*p == '\\' && *(p+1)) {
573 i++;
574 p++;
575 int incr;
576 int c = GetBackslashExpression(p, incr);
577 i += incr;
578 p += incr;
579 if (c >= 0) {
580 // Convention: \c (c is any char) is case sensitive, whatever the option
581 ChSet(static_cast<unsigned char>(c));
582 prevChar = c;
583 } else {
584 // bittab is already changed
585 prevChar = -1;
587 } else {
588 prevChar = static_cast<unsigned char>(*p);
589 ChSetWithCase(*p, caseSensitive);
591 i++;
592 p++;
594 if (!*p)
595 return badpat("Missing ]");
597 for (n = 0; n < BITBLK; bittab[n++] = 0)
598 *mp++ = static_cast<char>(mask ^ bittab[n]);
600 break;
602 case '*': /* match 0 or more... */
603 case '+': /* match 1 or more... */
604 case '?':
605 if (p == pattern)
606 return badpat("Empty closure");
607 lp = sp; /* previous opcode */
608 if (*lp == CLO || *lp == LCLO) /* equivalence... */
609 break;
610 switch (*lp) {
612 case BOL:
613 case BOT:
614 case EOT:
615 case BOW:
616 case EOW:
617 case REF:
618 return badpat("Illegal closure");
619 default:
620 break;
623 if (*p == '+')
624 for (sp = mp; lp < sp; lp++)
625 *mp++ = *lp;
627 *mp++ = END;
628 *mp++ = END;
629 sp = mp;
631 while (--mp > lp)
632 *mp = mp[-1];
633 if (*p == '?') *mp = CLQ;
634 else if (*(p+1) == '?') *mp = LCLO;
635 else *mp = CLO;
637 mp = sp;
638 break;
640 case '\\': /* tags, backrefs... */
641 i++;
642 switch (*++p) {
643 case '<':
644 *mp++ = BOW;
645 break;
646 case '>':
647 if (*sp == BOW)
648 return badpat("Null pattern inside \\<\\>");
649 *mp++ = EOW;
650 break;
651 case '1':
652 case '2':
653 case '3':
654 case '4':
655 case '5':
656 case '6':
657 case '7':
658 case '8':
659 case '9':
660 n = *p-'0';
661 if (tagi > 0 && tagstk[tagi] == n)
662 return badpat("Cyclical reference");
663 if (tagc > n) {
664 *mp++ = static_cast<char>(REF);
665 *mp++ = static_cast<char>(n);
666 } else
667 return badpat("Undetermined reference");
668 break;
669 default:
670 if (!posix && *p == '(') {
671 if (tagc < MAXTAG) {
672 tagstk[++tagi] = tagc;
673 *mp++ = BOT;
674 *mp++ = static_cast<char>(tagc++);
675 } else
676 return badpat("Too many \\(\\) pairs");
677 } else if (!posix && *p == ')') {
678 if (*sp == BOT)
679 return badpat("Null pattern inside \\(\\)");
680 if (tagi > 0) {
681 *mp++ = static_cast<char>(EOT);
682 *mp++ = static_cast<char>(tagstk[tagi--]);
683 } else
684 return badpat("Unmatched \\)");
685 } else {
686 int incr;
687 int c = GetBackslashExpression(p, incr);
688 i += incr;
689 p += incr;
690 if (c >= 0) {
691 *mp++ = CHR;
692 *mp++ = static_cast<unsigned char>(c);
693 } else {
694 *mp++ = CCL;
695 mask = 0;
696 for (n = 0; n < BITBLK; bittab[n++] = 0)
697 *mp++ = static_cast<char>(mask ^ bittab[n]);
701 break;
703 default : /* an ordinary char */
704 if (posix && *p == '(') {
705 if (tagc < MAXTAG) {
706 tagstk[++tagi] = tagc;
707 *mp++ = BOT;
708 *mp++ = static_cast<char>(tagc++);
709 } else
710 return badpat("Too many () pairs");
711 } else if (posix && *p == ')') {
712 if (*sp == BOT)
713 return badpat("Null pattern inside ()");
714 if (tagi > 0) {
715 *mp++ = static_cast<char>(EOT);
716 *mp++ = static_cast<char>(tagstk[tagi--]);
717 } else
718 return badpat("Unmatched )");
719 } else {
720 unsigned char c = *p;
721 if (!c) // End of RE
722 c = '\\'; // We take it as raw backslash
723 if (caseSensitive || !iswordc(c)) {
724 *mp++ = CHR;
725 *mp++ = c;
726 } else {
727 *mp++ = CCL;
728 mask = 0;
729 ChSetWithCase(c, false);
730 for (n = 0; n < BITBLK; bittab[n++] = 0)
731 *mp++ = static_cast<char>(mask ^ bittab[n]);
734 break;
736 sp = lp;
738 if (tagi > 0)
739 return badpat((posix ? "Unmatched (" : "Unmatched \\("));
740 *mp = END;
741 sta = OKP;
742 return 0;
746 * RESearch::Execute:
747 * execute nfa to find a match.
749 * special cases: (nfa[0])
750 * BOL
751 * Match only once, starting from the
752 * beginning.
753 * CHR
754 * First locate the character without
755 * calling PMatch, and if found, call
756 * PMatch for the remaining string.
757 * END
758 * RESearch::Compile failed, poor luser did not
759 * check for it. Fail fast.
761 * If a match is found, bopat[0] and eopat[0] are set
762 * to the beginning and the end of the matched fragment,
763 * respectively.
766 int RESearch::Execute(CharacterIndexer &ci, int lp, int endp) {
767 unsigned char c;
768 int ep = NOTFOUND;
769 char *ap = nfa;
771 bol = lp;
772 failure = 0;
774 Clear();
776 switch (*ap) {
778 case BOL: /* anchored: match from BOL only */
779 ep = PMatch(ci, lp, endp, ap);
780 break;
781 case EOL: /* just searching for end of line normal path doesn't work */
782 if (*(ap+1) == END) {
783 lp = endp;
784 ep = lp;
785 break;
786 } else {
787 return 0;
789 case CHR: /* ordinary char: locate it fast */
790 c = *(ap+1);
791 while ((lp < endp) && (ci.CharAt(lp) != c))
792 lp++;
793 if (lp >= endp) /* if EOS, fail, else fall thru. */
794 return 0;
795 default: /* regular matching all the way. */
796 while (lp < endp) {
797 ep = PMatch(ci, lp, endp, ap);
798 if (ep != NOTFOUND)
799 break;
800 lp++;
802 break;
803 case END: /* munged automaton. fail always */
804 return 0;
806 if (ep == NOTFOUND)
807 return 0;
809 bopat[0] = lp;
810 eopat[0] = ep;
811 return 1;
815 * PMatch: internal routine for the hard part
817 * This code is partly snarfed from an early grep written by
818 * David Conroy. The backref and tag stuff, and various other
819 * innovations are by oz.
821 * special case optimizations: (nfa[n], nfa[n+1])
822 * CLO ANY
823 * We KNOW .* will match everything upto the
824 * end of line. Thus, directly go to the end of
825 * line, without recursive PMatch calls. As in
826 * the other closure cases, the remaining pattern
827 * must be matched by moving backwards on the
828 * string recursively, to find a match for xy
829 * (x is ".*" and y is the remaining pattern)
830 * where the match satisfies the LONGEST match for
831 * x followed by a match for y.
832 * CLO CHR
833 * We can again scan the string forward for the
834 * single char and at the point of failure, we
835 * execute the remaining nfa recursively, same as
836 * above.
838 * At the end of a successful match, bopat[n] and eopat[n]
839 * are set to the beginning and end of subpatterns matched
840 * by tagged expressions (n = 1 to 9).
843 extern void re_fail(char *,char);
845 #define isinset(x,y) ((x)[((y)&BLKIND)>>3] & bitarr[(y)&BITIND])
848 * skip values for CLO XXX to skip past the closure
851 #define ANYSKIP 2 /* [CLO] ANY END */
852 #define CHRSKIP 3 /* [CLO] CHR chr END */
853 #define CCLSKIP 34 /* [CLO] CCL 32 bytes END */
855 int RESearch::PMatch(CharacterIndexer &ci, int lp, int endp, char *ap) {
856 int op, c, n;
857 int e; /* extra pointer for CLO */
858 int bp; /* beginning of subpat... */
859 int ep; /* ending of subpat... */
860 int are; /* to save the line ptr. */
861 int llp; /* lazy lp for LCLO */
863 while ((op = *ap++) != END)
864 switch (op) {
866 case CHR:
867 if (ci.CharAt(lp++) != *ap++)
868 return NOTFOUND;
869 break;
870 case ANY:
871 if (lp++ >= endp)
872 return NOTFOUND;
873 break;
874 case CCL:
875 if (lp >= endp)
876 return NOTFOUND;
877 c = ci.CharAt(lp++);
878 if (!isinset(ap,c))
879 return NOTFOUND;
880 ap += BITBLK;
881 break;
882 case BOL:
883 if (lp != bol)
884 return NOTFOUND;
885 break;
886 case EOL:
887 if (lp < endp)
888 return NOTFOUND;
889 break;
890 case BOT:
891 bopat[*ap++] = lp;
892 break;
893 case EOT:
894 eopat[*ap++] = lp;
895 break;
896 case BOW:
897 if ((lp!=bol && iswordc(ci.CharAt(lp-1))) || !iswordc(ci.CharAt(lp)))
898 return NOTFOUND;
899 break;
900 case EOW:
901 if (lp==bol || !iswordc(ci.CharAt(lp-1)) || iswordc(ci.CharAt(lp)))
902 return NOTFOUND;
903 break;
904 case REF:
905 n = *ap++;
906 bp = bopat[n];
907 ep = eopat[n];
908 while (bp < ep)
909 if (ci.CharAt(bp++) != ci.CharAt(lp++))
910 return NOTFOUND;
911 break;
912 case LCLO:
913 case CLQ:
914 case CLO:
915 are = lp;
916 switch (*ap) {
918 case ANY:
919 if (op == CLO || op == LCLO)
920 while (lp < endp)
921 lp++;
922 else if (lp < endp)
923 lp++;
925 n = ANYSKIP;
926 break;
927 case CHR:
928 c = *(ap+1);
929 if (op == CLO || op == LCLO)
930 while ((lp < endp) && (c == ci.CharAt(lp)))
931 lp++;
932 else if ((lp < endp) && (c == ci.CharAt(lp)))
933 lp++;
934 n = CHRSKIP;
935 break;
936 case CCL:
937 while ((lp < endp) && isinset(ap+1,ci.CharAt(lp)))
938 lp++;
939 n = CCLSKIP;
940 break;
941 default:
942 failure = true;
943 //re_fail("closure: bad nfa.", *ap);
944 return NOTFOUND;
946 ap += n;
948 llp = lp;
949 e = NOTFOUND;
950 while (llp >= are) {
951 int q;
952 if ((q = PMatch(ci, llp, endp, ap)) != NOTFOUND) {
953 e = q;
954 lp = llp;
955 if (op != LCLO) return e;
957 if (*ap == END) return e;
958 --llp;
960 if (*ap == EOT)
961 PMatch(ci, lp, endp, ap);
962 return e;
963 default:
964 //re_fail("RESearch::Execute: bad nfa.", static_cast<char>(op));
965 return NOTFOUND;
967 return lp;
971 * RESearch::Substitute:
972 * substitute the matched portions of the src in dst.
974 * & substitute the entire matched pattern.
976 * \digit substitute a subpattern, with the given tag number.
977 * Tags are numbered from 1 to 9. If the particular
978 * tagged subpattern does not exist, null is substituted.
980 int RESearch::Substitute(CharacterIndexer &ci, char *src, char *dst) {
981 unsigned char c;
982 int pin;
983 int bp;
984 int ep;
986 if (!*src || !bopat[0])
987 return 0;
989 while ((c = *src++) != 0) {
990 switch (c) {
992 case '&':
993 pin = 0;
994 break;
996 case '\\':
997 c = *src++;
998 if (c >= '0' && c <= '9') {
999 pin = c - '0';
1000 break;
1003 default:
1004 *dst++ = c;
1005 continue;
1008 if ((bp = bopat[pin]) != 0 && (ep = eopat[pin]) != 0) {
1009 while (ci.CharAt(bp) && bp < ep)
1010 *dst++ = ci.CharAt(bp++);
1011 if (bp < ep)
1012 return 0;
1015 *dst = '\0';
1016 return 1;