Support more folding icon styles: arrows, +/- and no lines
[geany-mirror.git] / scintilla / RESearch.cxx
blob0c400450eb80f42216c11d07c2e5f611ad1006f3
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
21 * These routines are the PUBLIC DOMAIN equivalents of regex
22 * routines as found in 4.nBSD UN*X, with minor extensions.
24 * These routines are derived from various implementations found
25 * in software tools books, and Conroy's grep. They are NOT derived
26 * from licensed/restricted software.
27 * For more interesting/academic/complicated implementations,
28 * see Henry Spencer's regexp routines, or GNU Emacs pattern
29 * matching module.
31 * Modification history removed.
33 * Interfaces:
34 * RESearch::Compile: compile a regular expression into a NFA.
36 * const char *RESearch::Compile(const char *pattern, int length,
37 * bool caseSensitive, bool posix)
39 * Returns a short error string if they fail.
41 * RESearch::Execute: execute the NFA to match a pattern.
43 * int RESearch::Execute(characterIndexer &ci, int lp, int endp)
45 * RESearch::Substitute: substitute the matched portions in a new string.
47 * int RESearch::Substitute(CharacterIndexer &ci, char *src, char *dst)
49 * re_fail: failure routine for RESearch::Execute. (no longer used)
51 * void re_fail(char *msg, char op)
53 * Regular Expressions:
55 * [1] char matches itself, unless it is a special
56 * character (metachar): . \ [ ] * + ^ $
57 * and ( ) if posix option.
59 * [2] . matches any character.
61 * [3] \ matches the character following it, except:
62 * - \a, \b, \f, \n, \r, \t, \v match the corresponding C
63 * escape char, respectively BEL, BS, FF, LF, CR, TAB and VT;
64 * Note that \r and \n are never matched because Scintilla
65 * regex searches are made line per line
66 * (stripped of end-of-line chars).
67 * - if not in posix mode, when followed by a
68 * left or right round bracket (see [7]);
69 * - when followed by a digit 1 to 9 (see [8]);
70 * - when followed by a left or right angle bracket
71 * (see [9]);
72 * - when followed by d, D, s, S, w or W (see [10]);
73 * - when followed by x and two hexa digits (see [11].
74 * Backslash is used as an escape character for all
75 * other meta-characters, and itself.
77 * [4] [set] matches one of the characters in the set.
78 * If the first character in the set is "^",
79 * it matches the characters NOT in the set, i.e.
80 * complements the set. A shorthand S-E (start dash end)
81 * is used to specify a set of characters S up to
82 * E, inclusive. S and E must be characters, otherwise
83 * the dash is taken literally (eg. in expression [\d-a]).
84 * The special characters "]" and "-" have no special
85 * meaning if they appear as the first chars in the set.
86 * To include both, put - first: [-]A-Z]
87 * (or just backslash them).
88 * examples: match:
90 * [-]|] matches these 3 chars,
92 * []-|] matches from ] to | chars
94 * [a-z] any lowercase alpha
96 * [^-]] any char except - and ]
98 * [^A-Z] any char except uppercase
99 * alpha
101 * [a-zA-Z] any alpha
103 * [5] * any regular expression form [1] to [4]
104 * (except [7], [8] and [9] forms of [3]),
105 * followed by closure char (*)
106 * matches zero or more matches of that form.
108 * [6] + same as [5], except it matches one or more.
109 * Both [5] and [6] are greedy (they match as much as possible).
111 * [7] a regular expression in the form [1] to [12], enclosed
112 * as \(form\) (or (form) with posix flag) matches what
113 * form matches. The enclosure creates a set of tags,
114 * used for [8] and for pattern substitution.
115 * The tagged forms are numbered starting from 1.
117 * [8] a \ followed by a digit 1 to 9 matches whatever a
118 * previously tagged regular expression ([7]) matched.
120 * [9] \< a regular expression starting with a \< construct
121 * \> and/or ending with a \> construct, restricts the
122 * pattern matching to the beginning of a word, and/or
123 * the end of a word. A word is defined to be a character
124 * string beginning and/or ending with the characters
125 * A-Z a-z 0-9 and _. Scintilla extends this definition
126 * by user setting. The word must also be preceded and/or
127 * followed by any character outside those mentioned.
129 * [10] \l a backslash followed by d, D, s, S, w or W,
130 * becomes a character class (both inside and
131 * outside sets []).
132 * d: decimal digits
133 * D: any char except decimal digits
134 * s: whitespace (space, \t \n \r \f \v)
135 * S: any char except whitespace (see above)
136 * w: alphanumeric & underscore (changed by user setting)
137 * W: any char except alphanumeric & underscore (see above)
139 * [11] \xHH a backslash followed by x and two hexa digits,
140 * becomes the character whose Ascii code is equal
141 * to these digits. If not followed by two digits,
142 * it is 'x' char itself.
144 * [12] a composite regular expression xy where x and y
145 * are in the form [1] to [11] matches the longest
146 * match of x followed by a match for y.
148 * [13] ^ a regular expression starting with a ^ character
149 * $ and/or ending with a $ character, restricts the
150 * pattern matching to the beginning of the line,
151 * or the end of line. [anchors] Elsewhere in the
152 * pattern, ^ and $ are treated as ordinary characters.
155 * Acknowledgements:
157 * HCR's Hugh Redelmeier has been most helpful in various
158 * stages of development. He convinced me to include BOW
159 * and EOW constructs, originally invented by Rob Pike at
160 * the University of Toronto.
162 * References:
163 * Software tools Kernighan & Plauger
164 * Software tools in Pascal Kernighan & Plauger
165 * Grep [rsx-11 C dist] David Conroy
166 * ed - text editor Un*x Programmer's Manual
167 * Advanced editing on Un*x B. W. Kernighan
168 * RegExp routines Henry Spencer
170 * Notes:
172 * This implementation uses a bit-set representation for character
173 * classes for speed and compactness. Each character is represented
174 * by one bit in a 256-bit block. Thus, CCL always takes a
175 * constant 32 bytes in the internal nfa, and RESearch::Execute does a single
176 * bit comparison to locate the character in the set.
178 * Examples:
180 * pattern: foo*.*
181 * compile: CHR f CHR o CLO CHR o END CLO ANY END END
182 * matches: fo foo fooo foobar fobar foxx ...
184 * pattern: fo[ob]a[rz]
185 * compile: CHR f CHR o CCL bitset CHR a CCL bitset END
186 * matches: fobar fooar fobaz fooaz
188 * pattern: foo\\+
189 * compile: CHR f CHR o CHR o CHR \ CLO CHR \ END END
190 * matches: foo\ foo\\ foo\\\ ...
192 * pattern: \(foo\)[1-3]\1 (same as foo[1-3]foo)
193 * compile: BOT 1 CHR f CHR o CHR o EOT 1 CCL bitset REF 1 END
194 * matches: foo1foo foo2foo foo3foo
196 * pattern: \(fo.*\)-\1
197 * compile: BOT 1 CHR f CHR o CLO ANY END EOT 1 CHR - REF 1 END
198 * matches: foo-foo fo-fo fob-fob foobar-foobar ...
201 #include <stdlib.h>
203 #include "CharClassify.h"
204 #include "RESearch.h"
206 // Shut up annoying Visual C++ warnings:
207 #ifdef _MSC_VER
208 #pragma warning(disable: 4514)
209 #endif
211 #ifdef SCI_NAMESPACE
212 using namespace Scintilla;
213 #endif
215 #define OKP 1
216 #define NOP 0
218 #define CHR 1
219 #define ANY 2
220 #define CCL 3
221 #define BOL 4
222 #define EOL 5
223 #define BOT 6
224 #define EOT 7
225 #define BOW 8
226 #define EOW 9
227 #define REF 10
228 #define CLO 11
230 #define END 0
233 * The following defines are not meant to be changeable.
234 * They are for readability only.
236 #define BLKIND 0370
237 #define BITIND 07
239 const char bitarr[] = { 1, 2, 4, 8, 16, 32, 64, '\200' };
241 #define badpat(x) (*nfa = END, x)
244 * Character classification table for word boundary operators BOW
245 * and EOW is passed in by the creator of this object (Scintilla
246 * Document). The Document default state is that word chars are:
247 * 0-9, a-z, A-Z and _
250 RESearch::RESearch(CharClassify *charClassTable) {
251 charClass = charClassTable;
252 Init();
255 RESearch::~RESearch() {
256 Clear();
259 void RESearch::Init() {
260 sta = NOP; /* status of lastpat */
261 bol = 0;
262 for (int i = 0; i < MAXTAG; i++)
263 pat[i] = 0;
264 for (int j = 0; j < BITBLK; j++)
265 bittab[j] = 0;
268 void RESearch::Clear() {
269 for (int i = 0; i < MAXTAG; i++) {
270 delete []pat[i];
271 pat[i] = 0;
272 bopat[i] = NOTFOUND;
273 eopat[i] = NOTFOUND;
277 bool RESearch::GrabMatches(CharacterIndexer &ci) {
278 bool success = true;
279 for (unsigned int i = 0; i < MAXTAG; i++) {
280 if ((bopat[i] != NOTFOUND) && (eopat[i] != NOTFOUND)) {
281 unsigned int len = eopat[i] - bopat[i];
282 pat[i] = new char[len + 1];
283 if (pat[i]) {
284 for (unsigned int j = 0; j < len; j++)
285 pat[i][j] = ci.CharAt(bopat[i] + j);
286 pat[i][len] = '\0';
287 } else {
288 success = false;
292 return success;
295 void RESearch::ChSet(unsigned char c) {
296 bittab[((c) & BLKIND) >> 3] |= bitarr[(c) & BITIND];
299 void RESearch::ChSetWithCase(unsigned char c, bool caseSensitive) {
300 if (caseSensitive) {
301 ChSet(c);
302 } else {
303 if ((c >= 'a') && (c <= 'z')) {
304 ChSet(c);
305 ChSet(static_cast<unsigned char>(c - 'a' + 'A'));
306 } else if ((c >= 'A') && (c <= 'Z')) {
307 ChSet(c);
308 ChSet(static_cast<unsigned char>(c - 'A' + 'a'));
309 } else {
310 ChSet(c);
315 const unsigned char escapeValue(unsigned char ch) {
316 switch (ch) {
317 case 'a': return '\a';
318 case 'b': return '\b';
319 case 'f': return '\f';
320 case 'n': return '\n';
321 case 'r': return '\r';
322 case 't': return '\t';
323 case 'v': return '\v';
325 return 0;
328 static int GetHexaChar(unsigned char hd1, unsigned char hd2) {
329 int hexValue = 0;
330 if (hd1 >= '0' && hd1 <= '9') {
331 hexValue += 16 * (hd1 - '0');
332 } else if (hd1 >= 'A' && hd1 <= 'F') {
333 hexValue += 16 * (hd1 - 'A' + 10);
334 } else if (hd1 >= 'a' && hd1 <= 'f') {
335 hexValue += 16 * (hd1 - 'a' + 10);
336 } else
337 return -1;
338 if (hd2 >= '0' && hd2 <= '9') {
339 hexValue += hd2 - '0';
340 } else if (hd2 >= 'A' && hd2 <= 'F') {
341 hexValue += hd2 - 'A' + 10;
342 } else if (hd2 >= 'a' && hd2 <= 'f') {
343 hexValue += hd2 - 'a' + 10;
344 } else
345 return -1;
346 return hexValue;
350 * Called when the parser finds a backslash not followed
351 * by a valid expression (like \( in non-Posix mode).
352 * @param pattern: pointer on the char after the backslash.
353 * @param incr: (out) number of chars to skip after expression evaluation.
354 * @return the char if it resolves to a simple char,
355 * or -1 for a char class. In this case, bittab is changed.
357 int RESearch::GetBackslashExpression(
358 const char *pattern,
359 int &incr) {
360 // Since error reporting is primitive and messages are not used anyway,
361 // I choose to interpret unexpected syntax in a logical way instead
362 // of reporting errors. Otherwise, we can stick on, eg., PCRE behavior.
363 incr = 0; // Most of the time, will skip the char "naturally".
364 int c;
365 int result = -1;
366 unsigned char bsc = *pattern;
367 if (!bsc) {
368 // Avoid overrun
369 result = '\\'; // \ at end of pattern, take it literally
370 return result;
373 switch (bsc) {
374 case 'a':
375 case 'b':
376 case 'n':
377 case 'f':
378 case 'r':
379 case 't':
380 case 'v':
381 result = escapeValue(bsc);
382 break;
383 case 'x': {
384 unsigned char hd1 = *(pattern + 1);
385 unsigned char hd2 = *(pattern + 2);
386 int hexValue = GetHexaChar(hd1, hd2);
387 if (hexValue >= 0) {
388 result = hexValue;
389 incr = 2; // Must skip the digits
390 } else {
391 result = 'x'; // \x without 2 digits: see it as 'x'
394 break;
395 case 'd':
396 for (c = '0'; c <= '9'; c++) {
397 ChSet(static_cast<unsigned char>(c));
399 break;
400 case 'D':
401 for (c = 0; c < MAXCHR; c++) {
402 if (c < '0' || c > '9') {
403 ChSet(static_cast<unsigned char>(c));
406 break;
407 case 's':
408 ChSet(' ');
409 ChSet('\t');
410 ChSet('\n');
411 ChSet('\r');
412 ChSet('\f');
413 ChSet('\v');
414 break;
415 case 'S':
416 for (c = 0; c < MAXCHR; c++) {
417 if (c != ' ' && !(c >= 0x09 && c <= 0x0D)) {
418 ChSet(static_cast<unsigned char>(c));
421 break;
422 case 'w':
423 for (c = 0; c < MAXCHR; c++) {
424 if (iswordc(static_cast<unsigned char>(c))) {
425 ChSet(static_cast<unsigned char>(c));
428 break;
429 case 'W':
430 for (c = 0; c < MAXCHR; c++) {
431 if (!iswordc(static_cast<unsigned char>(c))) {
432 ChSet(static_cast<unsigned char>(c));
435 break;
436 default:
437 result = bsc;
439 return result;
442 const char *RESearch::Compile(const char *pattern, int length, bool caseSensitive, bool posix) {
443 char *mp=nfa; /* nfa pointer */
444 char *lp; /* saved pointer */
445 char *sp=nfa; /* another one */
446 char *mpMax = mp + MAXNFA - BITBLK - 10;
448 int tagi = 0; /* tag stack index */
449 int tagc = 1; /* actual tag count */
451 int n;
452 char mask; /* xor mask -CCL/NCL */
453 int c1, c2, prevChar;
455 if (!pattern || !length) {
456 if (sta)
457 return 0;
458 else
459 return badpat("No previous regular expression");
461 sta = NOP;
463 const char *p=pattern; /* pattern pointer */
464 for (int i=0; i<length; i++, p++) {
465 if (mp > mpMax)
466 return badpat("Pattern too long");
467 lp = mp;
468 switch (*p) {
470 case '.': /* match any char */
471 *mp++ = ANY;
472 break;
474 case '^': /* match beginning */
475 if (p == pattern)
476 *mp++ = BOL;
477 else {
478 *mp++ = CHR;
479 *mp++ = *p;
481 break;
483 case '$': /* match endofline */
484 if (!*(p+1))
485 *mp++ = EOL;
486 else {
487 *mp++ = CHR;
488 *mp++ = *p;
490 break;
492 case '[': /* match char class */
493 *mp++ = CCL;
494 prevChar = 0;
496 i++;
497 if (*++p == '^') {
498 mask = '\377';
499 i++;
500 p++;
501 } else
502 mask = 0;
504 if (*p == '-') { /* real dash */
505 i++;
506 prevChar = *p;
507 ChSet(*p++);
509 if (*p == ']') { /* real brace */
510 i++;
511 prevChar = *p;
512 ChSet(*p++);
514 while (*p && *p != ']') {
515 if (*p == '-') {
516 if (prevChar < 0) {
517 // Previous def. was a char class like \d, take dash literally
518 prevChar = *p;
519 ChSet(*p);
520 } else if (*(p+1)) {
521 if (*(p+1) != ']') {
522 c1 = prevChar + 1;
523 i++;
524 c2 = *++p;
525 if (c2 == '\\') {
526 if (!*(p+1)) // End of RE
527 return badpat("Missing ]");
528 else {
529 i++;
530 p++;
531 int incr;
532 c2 = GetBackslashExpression(p, incr);
533 i += incr;
534 p += incr;
535 if (c2 >= 0) {
536 // Convention: \c (c is any char) is case sensitive, whatever the option
537 ChSet(static_cast<unsigned char>(c2));
538 prevChar = c2;
539 } else {
540 // bittab is already changed
541 prevChar = -1;
545 if (prevChar < 0) {
546 // Char after dash is char class like \d, take dash literally
547 prevChar = '-';
548 ChSet('-');
549 } else {
550 // Put all chars between c1 and c2 included in the char set
551 while (c1 <= c2) {
552 ChSetWithCase(static_cast<unsigned char>(c1++), caseSensitive);
555 } else {
556 // Dash before the ], take it literally
557 prevChar = *p;
558 ChSet(*p);
560 } else {
561 return badpat("Missing ]");
563 } else if (*p == '\\' && *(p+1)) {
564 i++;
565 p++;
566 int incr;
567 int c = GetBackslashExpression(p, incr);
568 i += incr;
569 p += incr;
570 if (c >= 0) {
571 // Convention: \c (c is any char) is case sensitive, whatever the option
572 ChSet(static_cast<unsigned char>(c));
573 prevChar = c;
574 } else {
575 // bittab is already changed
576 prevChar = -1;
578 } else {
579 prevChar = *p;
580 ChSetWithCase(*p, caseSensitive);
582 i++;
583 p++;
585 if (!*p)
586 return badpat("Missing ]");
588 for (n = 0; n < BITBLK; bittab[n++] = 0)
589 *mp++ = static_cast<char>(mask ^ bittab[n]);
591 break;
593 case '*': /* match 0 or more... */
594 case '+': /* match 1 or more... */
595 if (p == pattern)
596 return badpat("Empty closure");
597 lp = sp; /* previous opcode */
598 if (*lp == CLO) /* equivalence... */
599 break;
600 switch (*lp) {
602 case BOL:
603 case BOT:
604 case EOT:
605 case BOW:
606 case EOW:
607 case REF:
608 return badpat("Illegal closure");
609 default:
610 break;
613 if (*p == '+')
614 for (sp = mp; lp < sp; lp++)
615 *mp++ = *lp;
617 *mp++ = END;
618 *mp++ = END;
619 sp = mp;
620 while (--mp > lp)
621 *mp = mp[-1];
622 *mp = CLO;
623 mp = sp;
624 break;
626 case '\\': /* tags, backrefs... */
627 i++;
628 switch (*++p) {
629 case '<':
630 *mp++ = BOW;
631 break;
632 case '>':
633 if (*sp == BOW)
634 return badpat("Null pattern inside \\<\\>");
635 *mp++ = EOW;
636 break;
637 case '1':
638 case '2':
639 case '3':
640 case '4':
641 case '5':
642 case '6':
643 case '7':
644 case '8':
645 case '9':
646 n = *p-'0';
647 if (tagi > 0 && tagstk[tagi] == n)
648 return badpat("Cyclical reference");
649 if (tagc > n) {
650 *mp++ = static_cast<char>(REF);
651 *mp++ = static_cast<char>(n);
652 } else
653 return badpat("Undetermined reference");
654 break;
655 default:
656 if (!posix && *p == '(') {
657 if (tagc < MAXTAG) {
658 tagstk[++tagi] = tagc;
659 *mp++ = BOT;
660 *mp++ = static_cast<char>(tagc++);
661 } else
662 return badpat("Too many \\(\\) pairs");
663 } else if (!posix && *p == ')') {
664 if (*sp == BOT)
665 return badpat("Null pattern inside \\(\\)");
666 if (tagi > 0) {
667 *mp++ = static_cast<char>(EOT);
668 *mp++ = static_cast<char>(tagstk[tagi--]);
669 } else
670 return badpat("Unmatched \\)");
671 } else {
672 int incr;
673 int c = GetBackslashExpression(p, incr);
674 i += incr;
675 p += incr;
676 if (c >= 0) {
677 *mp++ = CHR;
678 *mp++ = static_cast<unsigned char>(c);
679 } else {
680 *mp++ = CCL;
681 mask = 0;
682 for (n = 0; n < BITBLK; bittab[n++] = 0)
683 *mp++ = static_cast<char>(mask ^ bittab[n]);
687 break;
689 default : /* an ordinary char */
690 if (posix && *p == '(') {
691 if (tagc < MAXTAG) {
692 tagstk[++tagi] = tagc;
693 *mp++ = BOT;
694 *mp++ = static_cast<char>(tagc++);
695 } else
696 return badpat("Too many () pairs");
697 } else if (posix && *p == ')') {
698 if (*sp == BOT)
699 return badpat("Null pattern inside ()");
700 if (tagi > 0) {
701 *mp++ = static_cast<char>(EOT);
702 *mp++ = static_cast<char>(tagstk[tagi--]);
703 } else
704 return badpat("Unmatched )");
705 } else {
706 unsigned char c = *p;
707 if (!c) // End of RE
708 c = '\\'; // We take it as raw backslash
709 if (caseSensitive || !iswordc(c)) {
710 *mp++ = CHR;
711 *mp++ = c;
712 } else {
713 *mp++ = CCL;
714 mask = 0;
715 ChSetWithCase(c, false);
716 for (n = 0; n < BITBLK; bittab[n++] = 0)
717 *mp++ = static_cast<char>(mask ^ bittab[n]);
720 break;
722 sp = lp;
724 if (tagi > 0)
725 return badpat((posix ? "Unmatched (" : "Unmatched \\("));
726 *mp = END;
727 sta = OKP;
728 return 0;
732 * RESearch::Execute:
733 * execute nfa to find a match.
735 * special cases: (nfa[0])
736 * BOL
737 * Match only once, starting from the
738 * beginning.
739 * CHR
740 * First locate the character without
741 * calling PMatch, and if found, call
742 * PMatch for the remaining string.
743 * END
744 * RESearch::Compile failed, poor luser did not
745 * check for it. Fail fast.
747 * If a match is found, bopat[0] and eopat[0] are set
748 * to the beginning and the end of the matched fragment,
749 * respectively.
752 int RESearch::Execute(CharacterIndexer &ci, int lp, int endp) {
753 unsigned char c;
754 int ep = NOTFOUND;
755 char *ap = nfa;
757 bol = lp;
758 failure = 0;
760 Clear();
762 switch (*ap) {
764 case BOL: /* anchored: match from BOL only */
765 ep = PMatch(ci, lp, endp, ap);
766 break;
767 case EOL: /* just searching for end of line normal path doesn't work */
768 if (*(ap+1) == END) {
769 lp = endp;
770 ep = lp;
771 break;
772 } else {
773 return 0;
775 case CHR: /* ordinary char: locate it fast */
776 c = *(ap+1);
777 while ((lp < endp) && (ci.CharAt(lp) != c))
778 lp++;
779 if (lp >= endp) /* if EOS, fail, else fall thru. */
780 return 0;
781 default: /* regular matching all the way. */
782 while (lp < endp) {
783 ep = PMatch(ci, lp, endp, ap);
784 if (ep != NOTFOUND)
785 break;
786 lp++;
788 break;
789 case END: /* munged automaton. fail always */
790 return 0;
792 if (ep == NOTFOUND)
793 return 0;
795 bopat[0] = lp;
796 eopat[0] = ep;
797 return 1;
801 * PMatch: internal routine for the hard part
803 * This code is partly snarfed from an early grep written by
804 * David Conroy. The backref and tag stuff, and various other
805 * innovations are by oz.
807 * special case optimizations: (nfa[n], nfa[n+1])
808 * CLO ANY
809 * We KNOW .* will match everything upto the
810 * end of line. Thus, directly go to the end of
811 * line, without recursive PMatch calls. As in
812 * the other closure cases, the remaining pattern
813 * must be matched by moving backwards on the
814 * string recursively, to find a match for xy
815 * (x is ".*" and y is the remaining pattern)
816 * where the match satisfies the LONGEST match for
817 * x followed by a match for y.
818 * CLO CHR
819 * We can again scan the string forward for the
820 * single char and at the point of failure, we
821 * execute the remaining nfa recursively, same as
822 * above.
824 * At the end of a successful match, bopat[n] and eopat[n]
825 * are set to the beginning and end of subpatterns matched
826 * by tagged expressions (n = 1 to 9).
829 extern void re_fail(char *,char);
831 #define isinset(x,y) ((x)[((y)&BLKIND)>>3] & bitarr[(y)&BITIND])
834 * skip values for CLO XXX to skip past the closure
837 #define ANYSKIP 2 /* [CLO] ANY END */
838 #define CHRSKIP 3 /* [CLO] CHR chr END */
839 #define CCLSKIP 34 /* [CLO] CCL 32 bytes END */
841 int RESearch::PMatch(CharacterIndexer &ci, int lp, int endp, char *ap) {
842 int op, c, n;
843 int e; /* extra pointer for CLO */
844 int bp; /* beginning of subpat... */
845 int ep; /* ending of subpat... */
846 int are; /* to save the line ptr. */
848 while ((op = *ap++) != END)
849 switch (op) {
851 case CHR:
852 if (ci.CharAt(lp++) != *ap++)
853 return NOTFOUND;
854 break;
855 case ANY:
856 if (lp++ >= endp)
857 return NOTFOUND;
858 break;
859 case CCL:
860 if (lp >= endp)
861 return NOTFOUND;
862 c = ci.CharAt(lp++);
863 if (!isinset(ap,c))
864 return NOTFOUND;
865 ap += BITBLK;
866 break;
867 case BOL:
868 if (lp != bol)
869 return NOTFOUND;
870 break;
871 case EOL:
872 if (lp < endp)
873 return NOTFOUND;
874 break;
875 case BOT:
876 bopat[*ap++] = lp;
877 break;
878 case EOT:
879 eopat[*ap++] = lp;
880 break;
881 case BOW:
882 if ((lp!=bol && iswordc(ci.CharAt(lp-1))) || !iswordc(ci.CharAt(lp)))
883 return NOTFOUND;
884 break;
885 case EOW:
886 if (lp==bol || !iswordc(ci.CharAt(lp-1)) || iswordc(ci.CharAt(lp)))
887 return NOTFOUND;
888 break;
889 case REF:
890 n = *ap++;
891 bp = bopat[n];
892 ep = eopat[n];
893 while (bp < ep)
894 if (ci.CharAt(bp++) != ci.CharAt(lp++))
895 return NOTFOUND;
896 break;
897 case CLO:
898 are = lp;
899 switch (*ap) {
901 case ANY:
902 while (lp < endp)
903 lp++;
904 n = ANYSKIP;
905 break;
906 case CHR:
907 c = *(ap+1);
908 while ((lp < endp) && (c == ci.CharAt(lp)))
909 lp++;
910 n = CHRSKIP;
911 break;
912 case CCL:
913 while ((lp < endp) && isinset(ap+1,ci.CharAt(lp)))
914 lp++;
915 n = CCLSKIP;
916 break;
917 default:
918 failure = true;
919 //re_fail("closure: bad nfa.", *ap);
920 return NOTFOUND;
923 ap += n;
925 while (lp >= are) {
926 if ((e = PMatch(ci, lp, endp, ap)) != NOTFOUND)
927 return e;
928 --lp;
930 return NOTFOUND;
931 default:
932 //re_fail("RESearch::Execute: bad nfa.", static_cast<char>(op));
933 return NOTFOUND;
935 return lp;
939 * RESearch::Substitute:
940 * substitute the matched portions of the src in dst.
942 * & substitute the entire matched pattern.
944 * \digit substitute a subpattern, with the given tag number.
945 * Tags are numbered from 1 to 9. If the particular
946 * tagged subpattern does not exist, null is substituted.
948 int RESearch::Substitute(CharacterIndexer &ci, char *src, char *dst) {
949 unsigned char c;
950 int pin;
951 int bp;
952 int ep;
954 if (!*src || !bopat[0])
955 return 0;
957 while ((c = *src++) != 0) {
958 switch (c) {
960 case '&':
961 pin = 0;
962 break;
964 case '\\':
965 c = *src++;
966 if (c >= '0' && c <= '9') {
967 pin = c - '0';
968 break;
971 default:
972 *dst++ = c;
973 continue;
976 if ((bp = bopat[pin]) != 0 && (ep = eopat[pin]) != 0) {
977 while (ci.CharAt(bp) && bp < ep)
978 *dst++ = ci.CharAt(bp++);
979 if (bp < ep)
980 return 0;
983 *dst = '\0';
984 return 1;