1 // Scintilla source code edit control
3 ** Regular expression search library.
7 * regex - Regular expression pattern matching and replacement
9 * By: Ozan S. Yigit (oz)
10 * Dept. of Computer Science
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
32 * Modification history removed.
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
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).
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
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
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.
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.
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
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.
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
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 ...
209 #include "CharClassify.h"
210 #include "RESearch.h"
212 // Shut up annoying Visual C++ warnings:
214 #pragma warning(disable: 4514)
218 using namespace Scintilla
;
235 #define CLQ 12 /* 0 to 1 closure */
236 #define LCLO 13 /* lazy closure */
241 * The following defines are not meant to be changeable.
242 * They are for readability only.
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
) {
260 charClass
= charClassTable
;
264 RESearch::~RESearch() {
268 void RESearch::Init() {
269 sta
= NOP
; /* status of lastpat */
271 for (int i
= 0; i
< MAXTAG
; i
++)
273 for (int j
= 0; j
< BITBLK
; j
++)
277 void RESearch::Clear() {
278 for (int i
= 0; i
< MAXTAG
; i
++) {
286 bool RESearch::GrabMatches(CharacterIndexer
&ci
) {
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];
293 for (unsigned int j
= 0; j
< len
; j
++)
294 pat
[i
][j
] = ci
.CharAt(bopat
[i
] + j
);
304 void RESearch::ChSet(unsigned char c
) {
305 bittab
[((c
) & BLKIND
) >> 3] |= bitarr
[(c
) & BITIND
];
308 void RESearch::ChSetWithCase(unsigned char c
, bool caseSensitive
) {
312 if ((c
>= 'a') && (c
<= 'z')) {
314 ChSet(static_cast<unsigned char>(c
- 'a' + 'A'));
315 } else if ((c
>= 'A') && (c
<= 'Z')) {
317 ChSet(static_cast<unsigned char>(c
- 'A' + 'a'));
324 unsigned char escapeValue(unsigned char 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';
337 static int GetHexaChar(unsigned char hd1
, unsigned char hd2
) {
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);
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;
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(
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".
375 unsigned char bsc
= *pattern
;
378 result
= '\\'; // \ at end of pattern, take it literally
390 result
= escapeValue(bsc
);
393 unsigned char hd1
= *(pattern
+ 1);
394 unsigned char hd2
= *(pattern
+ 2);
395 int hexValue
= GetHexaChar(hd1
, hd2
);
398 incr
= 2; // Must skip the digits
400 result
= 'x'; // \x without 2 digits: see it as 'x'
405 for (c
= '0'; c
<= '9'; c
++) {
406 ChSet(static_cast<unsigned char>(c
));
410 for (c
= 0; c
< MAXCHR
; c
++) {
411 if (c
< '0' || c
> '9') {
412 ChSet(static_cast<unsigned char>(c
));
425 for (c
= 0; c
< MAXCHR
; c
++) {
426 if (c
!= ' ' && !(c
>= 0x09 && c
<= 0x0D)) {
427 ChSet(static_cast<unsigned char>(c
));
432 for (c
= 0; c
< MAXCHR
; c
++) {
433 if (iswordc(static_cast<unsigned char>(c
))) {
434 ChSet(static_cast<unsigned char>(c
));
439 for (c
= 0; c
< MAXCHR
; c
++) {
440 if (!iswordc(static_cast<unsigned char>(c
))) {
441 ChSet(static_cast<unsigned char>(c
));
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 */
461 char mask
; /* xor mask -CCL/NCL */
462 int c1
, c2
, prevChar
;
464 if (!pattern
|| !length
) {
468 return badpat("No previous regular expression");
472 const char *p
=pattern
; /* pattern pointer */
473 for (int i
=0; i
<length
; i
++, p
++) {
475 return badpat("Pattern too long");
479 case '.': /* match any char */
483 case '^': /* match beginning */
492 case '$': /* match endofline */
501 case '[': /* match char class */
513 if (*p
== '-') { /* real dash */
518 if (*p
== ']') { /* real brace */
523 while (*p
&& *p
!= ']') {
526 // Previous def. was a char class like \d, take dash literally
533 c2
= static_cast<unsigned char>(*++p
);
535 if (!*(p
+1)) // End of RE
536 return badpat("Missing ]");
541 c2
= GetBackslashExpression(p
, incr
);
545 // Convention: \c (c is any char) is case sensitive, whatever the option
546 ChSet(static_cast<unsigned char>(c2
));
549 // bittab is already changed
555 // Char after dash is char class like \d, take dash literally
559 // Put all chars between c1 and c2 included in the char set
561 ChSetWithCase(static_cast<unsigned char>(c1
++), caseSensitive
);
565 // Dash before the ], take it literally
570 return badpat("Missing ]");
572 } else if (*p
== '\\' && *(p
+1)) {
576 int c
= GetBackslashExpression(p
, incr
);
580 // Convention: \c (c is any char) is case sensitive, whatever the option
581 ChSet(static_cast<unsigned char>(c
));
584 // bittab is already changed
588 prevChar
= static_cast<unsigned char>(*p
);
589 ChSetWithCase(*p
, caseSensitive
);
595 return badpat("Missing ]");
597 for (n
= 0; n
< BITBLK
; bittab
[n
++] = 0)
598 *mp
++ = static_cast<char>(mask
^ bittab
[n
]);
602 case '*': /* match 0 or more... */
603 case '+': /* match 1 or more... */
606 return badpat("Empty closure");
607 lp
= sp
; /* previous opcode */
608 if (*lp
== CLO
|| *lp
== LCLO
) /* equivalence... */
618 return badpat("Illegal closure");
624 for (sp
= mp
; lp
< sp
; lp
++)
633 if (*p
== '?') *mp
= CLQ
;
634 else if (*(p
+1) == '?') *mp
= LCLO
;
640 case '\\': /* tags, backrefs... */
648 return badpat("Null pattern inside \\<\\>");
661 if (tagi
> 0 && tagstk
[tagi
] == n
)
662 return badpat("Cyclical reference");
664 *mp
++ = static_cast<char>(REF
);
665 *mp
++ = static_cast<char>(n
);
667 return badpat("Undetermined reference");
670 if (!posix
&& *p
== '(') {
672 tagstk
[++tagi
] = tagc
;
674 *mp
++ = static_cast<char>(tagc
++);
676 return badpat("Too many \\(\\) pairs");
677 } else if (!posix
&& *p
== ')') {
679 return badpat("Null pattern inside \\(\\)");
681 *mp
++ = static_cast<char>(EOT
);
682 *mp
++ = static_cast<char>(tagstk
[tagi
--]);
684 return badpat("Unmatched \\)");
687 int c
= GetBackslashExpression(p
, incr
);
692 *mp
++ = static_cast<unsigned char>(c
);
696 for (n
= 0; n
< BITBLK
; bittab
[n
++] = 0)
697 *mp
++ = static_cast<char>(mask
^ bittab
[n
]);
703 default : /* an ordinary char */
704 if (posix
&& *p
== '(') {
706 tagstk
[++tagi
] = tagc
;
708 *mp
++ = static_cast<char>(tagc
++);
710 return badpat("Too many () pairs");
711 } else if (posix
&& *p
== ')') {
713 return badpat("Null pattern inside ()");
715 *mp
++ = static_cast<char>(EOT
);
716 *mp
++ = static_cast<char>(tagstk
[tagi
--]);
718 return badpat("Unmatched )");
720 unsigned char c
= *p
;
722 c
= '\\'; // We take it as raw backslash
723 if (caseSensitive
|| !iswordc(c
)) {
729 ChSetWithCase(c
, false);
730 for (n
= 0; n
< BITBLK
; bittab
[n
++] = 0)
731 *mp
++ = static_cast<char>(mask
^ bittab
[n
]);
739 return badpat((posix
? "Unmatched (" : "Unmatched \\("));
747 * execute nfa to find a match.
749 * special cases: (nfa[0])
751 * Match only once, starting from the
754 * First locate the character without
755 * calling PMatch, and if found, call
756 * PMatch for the remaining string.
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,
766 int RESearch::Execute(CharacterIndexer
&ci
, int lp
, int endp
) {
778 case BOL
: /* anchored: match from BOL only */
779 ep
= PMatch(ci
, lp
, endp
, ap
);
781 case EOL
: /* just searching for end of line normal path doesn't work */
782 if (*(ap
+1) == END
) {
789 case CHR
: /* ordinary char: locate it fast */
791 while ((lp
< endp
) && (ci
.CharAt(lp
) != c
))
793 if (lp
>= endp
) /* if EOS, fail, else fall thru. */
795 default: /* regular matching all the way. */
797 ep
= PMatch(ci
, lp
, endp
, ap
);
803 case END
: /* munged automaton. fail always */
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])
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.
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
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
) {
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
)
867 if (ci
.CharAt(lp
++) != *ap
++)
891 bopat
[static_cast<int>(*ap
++)] = lp
;
894 eopat
[static_cast<int>(*ap
++)] = lp
;
897 if ((lp
!=bol
&& iswordc(ci
.CharAt(lp
-1))) || !iswordc(ci
.CharAt(lp
)))
901 if (lp
==bol
|| !iswordc(ci
.CharAt(lp
-1)) || iswordc(ci
.CharAt(lp
)))
909 if (ci
.CharAt(bp
++) != ci
.CharAt(lp
++))
919 if (op
== CLO
|| op
== LCLO
)
929 if (op
== CLO
|| op
== LCLO
)
930 while ((lp
< endp
) && (c
== ci
.CharAt(lp
)))
932 else if ((lp
< endp
) && (c
== ci
.CharAt(lp
)))
937 while ((lp
< endp
) && isinset(ap
+1,ci
.CharAt(lp
)))
943 //re_fail("closure: bad nfa.", *ap);
952 if ((q
= PMatch(ci
, llp
, endp
, ap
)) != NOTFOUND
) {
955 if (op
!= LCLO
) return e
;
957 if (*ap
== END
) return e
;
961 PMatch(ci
, lp
, endp
, ap
);
964 //re_fail("RESearch::Execute: bad nfa.", static_cast<char>(op));
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
) {
986 if (!*src
|| !bopat
[0])
989 while ((c
= *src
++) != 0) {
998 if (c
>= '0' && c
<= '9') {
1008 if ((bp
= bopat
[pin
]) != 0 && (ep
= eopat
[pin
]) != 0) {
1009 while (ci
.CharAt(bp
) && bp
< ep
)
1010 *dst
++ = ci
.CharAt(bp
++);