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 * re_fail: failure routine for RESearch::Execute. (no longer used)
48 * void re_fail(char *msg, char op)
50 * Regular Expressions:
52 * [1] char matches itself, unless it is a special
53 * character (metachar): . \ [ ] * + ? ^ $
54 * and ( ) if posix option.
56 * [2] . matches any character.
58 * [3] \ matches the character following it, except:
59 * - \a, \b, \f, \n, \r, \t, \v match the corresponding C
60 * escape char, respectively BEL, BS, FF, LF, CR, TAB and VT;
61 * Note that \r and \n are never matched because Scintilla
62 * regex searches are made line per line
63 * (stripped of end-of-line chars).
64 * - if not in posix mode, when followed by a
65 * left or right round bracket (see [8]);
66 * - when followed by a digit 1 to 9 (see [9]);
67 * - when followed by a left or right angle bracket
69 * - when followed by d, D, s, S, w or W (see [11]);
70 * - when followed by x and two hexa digits (see [12].
71 * Backslash is used as an escape character for all
72 * other meta-characters, and itself.
74 * [4] [set] matches one of the characters in the set.
75 * If the first character in the set is "^",
76 * it matches the characters NOT in the set, i.e.
77 * complements the set. A shorthand S-E (start dash end)
78 * is used to specify a set of characters S up to
79 * E, inclusive. S and E must be characters, otherwise
80 * the dash is taken literally (eg. in expression [\d-a]).
81 * The special characters "]" and "-" have no special
82 * meaning if they appear as the first chars in the set.
83 * To include both, put - first: [-]A-Z]
84 * (or just backslash them).
87 * [-]|] matches these 3 chars,
89 * []-|] matches from ] to | chars
91 * [a-z] any lowercase alpha
93 * [^-]] any char except - and ]
95 * [^A-Z] any char except uppercase
100 * [5] * any regular expression form [1] to [4]
101 * (except [8], [9] and [10] forms of [3]),
102 * followed by closure char (*)
103 * matches zero or more matches of that form.
105 * [6] + same as [5], except it matches one or more.
107 * [5-6] Both [5] and [6] are greedy (they match as much as possible).
108 * Unless they are followed by the 'lazy' quantifier (?)
109 * In which case both [5] and [6] try to match as little as possible
111 * [7] ? same as [5] except it matches zero or one.
113 * [8] a regular expression in the form [1] to [13], enclosed
114 * as \(form\) (or (form) with posix flag) matches what
115 * form matches. The enclosure creates a set of tags,
116 * used for [9] and for pattern substitution.
117 * The tagged forms are numbered starting from 1.
119 * [9] a \ followed by a digit 1 to 9 matches whatever a
120 * previously tagged regular expression ([8]) matched.
122 * [10] \< a regular expression starting with a \< construct
123 * \> and/or ending with a \> construct, restricts the
124 * pattern matching to the beginning of a word, and/or
125 * the end of a word. A word is defined to be a character
126 * string beginning and/or ending with the characters
127 * A-Z a-z 0-9 and _. Scintilla extends this definition
128 * by user setting. The word must also be preceded and/or
129 * followed by any character outside those mentioned.
131 * [11] \l a backslash followed by d, D, s, S, w or W,
132 * becomes a character class (both inside and
135 * D: any char except decimal digits
136 * s: whitespace (space, \t \n \r \f \v)
137 * S: any char except whitespace (see above)
138 * w: alphanumeric & underscore (changed by user setting)
139 * W: any char except alphanumeric & underscore (see above)
141 * [12] \xHH a backslash followed by x and two hexa digits,
142 * becomes the character whose ASCII code is equal
143 * to these digits. If not followed by two digits,
144 * it is 'x' char itself.
146 * [13] a composite regular expression xy where x and y
147 * are in the form [1] to [12] matches the longest
148 * match of x followed by a match for y.
150 * [14] ^ a regular expression starting with a ^ character
151 * $ and/or ending with a $ character, restricts the
152 * pattern matching to the beginning of the line,
153 * or the end of line. [anchors] Elsewhere in the
154 * pattern, ^ and $ are treated as ordinary characters.
159 * HCR's Hugh Redelmeier has been most helpful in various
160 * stages of development. He convinced me to include BOW
161 * and EOW constructs, originally invented by Rob Pike at
162 * the University of Toronto.
165 * Software tools Kernighan & Plauger
166 * Software tools in Pascal Kernighan & Plauger
167 * Grep [rsx-11 C dist] David Conroy
168 * ed - text editor Un*x Programmer's Manual
169 * Advanced editing on Un*x B. W. Kernighan
170 * RegExp routines Henry Spencer
174 * This implementation uses a bit-set representation for character
175 * classes for speed and compactness. Each character is represented
176 * by one bit in a 256-bit block. Thus, CCL always takes a
177 * constant 32 bytes in the internal nfa, and RESearch::Execute does a single
178 * bit comparison to locate the character in the set.
183 * compile: CHR f CHR o CLO CHR o END CLO ANY END END
184 * matches: fo foo fooo foobar fobar foxx ...
186 * pattern: fo[ob]a[rz]
187 * compile: CHR f CHR o CCL bitset CHR a CCL bitset END
188 * matches: fobar fooar fobaz fooaz
191 * compile: CHR f CHR o CHR o CHR \ CLO CHR \ END END
192 * matches: foo\ foo\\ foo\\\ ...
194 * pattern: \(foo\)[1-3]\1 (same as foo[1-3]foo)
195 * compile: BOT 1 CHR f CHR o CHR o EOT 1 CCL bitset REF 1 END
196 * matches: foo1foo foo2foo foo3foo
198 * pattern: \(fo.*\)-\1
199 * compile: BOT 1 CHR f CHR o CLO ANY END EOT 1 CHR - REF 1 END
200 * matches: foo-foo fo-fo fob-fob foobar-foobar ...
211 #include "Position.h"
212 #include "CharClassify.h"
213 #include "RESearch.h"
215 using namespace Scintilla
;
231 #define CLQ 12 /* 0 to 1 closure */
232 #define LCLO 13 /* lazy closure */
237 * The following defines are not meant to be changeable.
238 * They are for readability only.
243 static const char bitarr
[] = { 1, 2, 4, 8, 16, 32, 64, '\200' };
245 #define badpat(x) (*nfa = END, x)
248 * Character classification table for word boundary operators BOW
249 * and EOW is passed in by the creator of this object (Scintilla
250 * Document). The Document default state is that word chars are:
251 * 0-9, a-z, A-Z and _
254 RESearch::RESearch(CharClassify
*charClassTable
) {
256 charClass
= charClassTable
;
257 sta
= NOP
; /* status of lastpat */
259 constexpr unsigned char nul
= 0;
260 std::fill(bittab
, std::end(bittab
), nul
);
261 std::fill(tagstk
, std::end(tagstk
), 0);
262 std::fill(nfa
, std::end(nfa
), '\0');
266 RESearch::~RESearch() {
270 void RESearch::Clear() noexcept
{
271 for (int i
= 0; i
< MAXTAG
; i
++) {
278 void RESearch::GrabMatches(const CharacterIndexer
&ci
) {
279 for (unsigned int i
= 0; i
< MAXTAG
; i
++) {
280 if ((bopat
[i
] != NOTFOUND
) && (eopat
[i
] != NOTFOUND
)) {
281 const Sci::Position len
= eopat
[i
] - bopat
[i
];
283 for (Sci::Position j
= 0; j
< len
; j
++)
284 pat
[i
][j
] = ci
.CharAt(bopat
[i
] + j
);
289 void RESearch::ChSet(unsigned char c
) noexcept
{
290 bittab
[((c
) & BLKIND
) >> 3] |= bitarr
[(c
) & BITIND
];
293 void RESearch::ChSetWithCase(unsigned char c
, bool caseSensitive
) noexcept
{
295 if (!caseSensitive
) {
296 if ((c
>= 'a') && (c
<= 'z')) {
297 ChSet(c
- 'a' + 'A');
298 } else if ((c
>= 'A') && (c
<= 'Z')) {
299 ChSet(c
- 'A' + 'a');
304 static unsigned char escapeValue(unsigned char ch
) noexcept
{
306 case 'a': return '\a';
307 case 'b': return '\b';
308 case 'f': return '\f';
309 case 'n': return '\n';
310 case 'r': return '\r';
311 case 't': return '\t';
312 case 'v': return '\v';
317 static int GetHexaChar(unsigned char hd1
, unsigned char hd2
) noexcept
{
319 if (hd1
>= '0' && hd1
<= '9') {
320 hexValue
+= 16 * (hd1
- '0');
321 } else if (hd1
>= 'A' && hd1
<= 'F') {
322 hexValue
+= 16 * (hd1
- 'A' + 10);
323 } else if (hd1
>= 'a' && hd1
<= 'f') {
324 hexValue
+= 16 * (hd1
- 'a' + 10);
328 if (hd2
>= '0' && hd2
<= '9') {
329 hexValue
+= hd2
- '0';
330 } else if (hd2
>= 'A' && hd2
<= 'F') {
331 hexValue
+= hd2
- 'A' + 10;
332 } else if (hd2
>= 'a' && hd2
<= 'f') {
333 hexValue
+= hd2
- 'a' + 10;
341 * Called when the parser finds a backslash not followed
342 * by a valid expression (like \( in non-Posix mode).
343 * @param pattern : pointer on the char after the backslash.
344 * @param incr : (out) number of chars to skip after expression evaluation.
345 * @return the char if it resolves to a simple char,
346 * or -1 for a char class. In this case, bittab is changed.
348 int RESearch::GetBackslashExpression(
350 int &incr
) noexcept
{
351 // Since error reporting is primitive and messages are not used anyway,
352 // I choose to interpret unexpected syntax in a logical way instead
353 // of reporting errors. Otherwise, we can stick on, eg., PCRE behaviour.
354 incr
= 0; // Most of the time, will skip the char "naturally".
357 const unsigned char bsc
= *pattern
;
360 result
= '\\'; // \ at end of pattern, take it literally
372 result
= escapeValue(bsc
);
375 const unsigned char hd1
= *(pattern
+ 1);
376 const unsigned char hd2
= *(pattern
+ 2);
377 const int hexValue
= GetHexaChar(hd1
, hd2
);
380 incr
= 2; // Must skip the digits
382 result
= 'x'; // \x without 2 digits: see it as 'x'
387 for (c
= '0'; c
<= '9'; c
++) {
388 ChSet(static_cast<unsigned char>(c
));
392 for (c
= 0; c
< MAXCHR
; c
++) {
393 if (c
< '0' || c
> '9') {
394 ChSet(static_cast<unsigned char>(c
));
407 for (c
= 0; c
< MAXCHR
; c
++) {
408 if (c
!= ' ' && !(c
>= 0x09 && c
<= 0x0D)) {
409 ChSet(static_cast<unsigned char>(c
));
414 for (c
= 0; c
< MAXCHR
; c
++) {
415 if (iswordc(static_cast<unsigned char>(c
))) {
416 ChSet(static_cast<unsigned char>(c
));
421 for (c
= 0; c
< MAXCHR
; c
++) {
422 if (!iswordc(static_cast<unsigned char>(c
))) {
423 ChSet(static_cast<unsigned char>(c
));
433 const char *RESearch::Compile(const char *pattern
, Sci::Position length
, bool caseSensitive
, bool posix
) noexcept
{
434 char *mp
=nfa
; /* nfa pointer */
435 char *lp
; /* saved pointer */
436 char *sp
=nfa
; /* another one */
437 char *mpMax
= mp
+ MAXNFA
- BITBLK
- 10;
439 int tagi
= 0; /* tag stack index */
440 int tagc
= 1; /* actual tag count */
443 char mask
; /* xor mask -CCL/NCL */
444 int c1
, c2
, prevChar
;
446 if (!pattern
|| !length
) {
450 return badpat("No previous regular expression");
454 const char *p
=pattern
; /* pattern pointer */
455 for (int i
=0; i
<length
; i
++, p
++) {
457 return badpat("Pattern too long");
461 case '.': /* match any char */
465 case '^': /* match beginning */
474 case '$': /* match endofline */
483 case '[': /* match char class */
496 if (*p
== '-') { /* real dash */
501 if (*p
== ']') { /* real brace */
506 while (*p
&& *p
!= ']') {
509 // Previous def. was a char class like \d, take dash literally
516 c2
= static_cast<unsigned char>(*++p
);
518 if (!*(p
+1)) { // End of RE
519 return badpat("Missing ]");
524 c2
= GetBackslashExpression(p
, incr
);
528 // Convention: \c (c is any char) is case sensitive, whatever the option
529 ChSet(static_cast<unsigned char>(c2
));
532 // bittab is already changed
538 // Char after dash is char class like \d, take dash literally
542 // Put all chars between c1 and c2 included in the char set
544 ChSetWithCase(static_cast<unsigned char>(c1
++), caseSensitive
);
548 // Dash before the ], take it literally
553 return badpat("Missing ]");
555 } else if (*p
== '\\' && *(p
+1)) {
559 const int c
= GetBackslashExpression(p
, incr
);
563 // Convention: \c (c is any char) is case sensitive, whatever the option
564 ChSet(static_cast<unsigned char>(c
));
567 // bittab is already changed
571 prevChar
= static_cast<unsigned char>(*p
);
572 ChSetWithCase(*p
, caseSensitive
);
578 return badpat("Missing ]");
580 for (n
= 0; n
< BITBLK
; bittab
[n
++] = 0)
581 *mp
++ = static_cast<char>(mask
^ bittab
[n
]);
585 case '*': /* match 0 or more... */
586 case '+': /* match 1 or more... */
589 return badpat("Empty closure");
590 lp
= sp
; /* previous opcode */
591 if (*lp
== CLO
|| *lp
== LCLO
) /* equivalence... */
601 return badpat("Illegal closure");
607 for (sp
= mp
; lp
< sp
; lp
++)
616 if (*p
== '?') *mp
= CLQ
;
617 else if (*(p
+1) == '?') *mp
= LCLO
;
623 case '\\': /* tags, backrefs... */
631 return badpat("Null pattern inside \\<\\>");
644 if (tagi
> 0 && tagstk
[tagi
] == n
)
645 return badpat("Cyclical reference");
648 *mp
++ = static_cast<char>(n
);
650 return badpat("Undetermined reference");
654 if (!posix
&& *p
== '(') {
656 tagstk
[++tagi
] = tagc
;
658 *mp
++ = static_cast<char>(tagc
++);
660 return badpat("Too many \\(\\) pairs");
662 } else if (!posix
&& *p
== ')') {
664 return badpat("Null pattern inside \\(\\)");
667 *mp
++ = static_cast<char>(tagstk
[tagi
--]);
669 return badpat("Unmatched \\)");
673 int c
= GetBackslashExpression(p
, incr
);
678 *mp
++ = static_cast<unsigned char>(c
);
682 for (n
= 0; n
< BITBLK
; bittab
[n
++] = 0)
683 *mp
++ = static_cast<char>(mask
^ bittab
[n
]);
689 default : /* an ordinary char */
690 if (posix
&& *p
== '(') {
692 tagstk
[++tagi
] = tagc
;
694 *mp
++ = static_cast<char>(tagc
++);
696 return badpat("Too many () pairs");
698 } else if (posix
&& *p
== ')') {
700 return badpat("Null pattern inside ()");
703 *mp
++ = static_cast<char>(tagstk
[tagi
--]);
705 return badpat("Unmatched )");
708 unsigned char c
= *p
;
710 c
= '\\'; // We take it as raw backslash
711 if (caseSensitive
|| !iswordc(c
)) {
717 ChSetWithCase(c
, false);
718 for (n
= 0; n
< BITBLK
; bittab
[n
++] = 0)
719 *mp
++ = static_cast<char>(mask
^ bittab
[n
]);
727 return badpat((posix
? "Unmatched (" : "Unmatched \\("));
735 * execute nfa to find a match.
737 * special cases: (nfa[0])
739 * Match only once, starting from the
742 * First locate the character without
743 * calling PMatch, and if found, call
744 * PMatch for the remaining string.
746 * RESearch::Compile failed, poor luser did not
747 * check for it. Fail fast.
749 * If a match is found, bopat[0] and eopat[0] are set
750 * to the beginning and the end of the matched fragment,
754 int RESearch::Execute(const CharacterIndexer
&ci
, Sci::Position lp
, Sci::Position endp
) {
756 Sci::Position ep
= NOTFOUND
;
766 case BOL
: /* anchored: match from BOL only */
767 ep
= PMatch(ci
, lp
, endp
, ap
);
769 case EOL
: /* just searching for end of line normal path doesn't work */
770 if (*(ap
+1) == END
) {
777 case CHR
: /* ordinary char: locate it fast */
779 while ((lp
< endp
) && (static_cast<unsigned char>(ci
.CharAt(lp
)) != c
))
781 if (lp
>= endp
) /* if EOS, fail, else fall through. */
784 default: /* regular matching all the way. */
786 ep
= PMatch(ci
, lp
, endp
, ap
);
792 case END
: /* munged automaton. fail always */
804 * PMatch: internal routine for the hard part
806 * This code is partly snarfed from an early grep written by
807 * David Conroy. The backref and tag stuff, and various other
808 * innovations are by oz.
810 * special case optimizations: (nfa[n], nfa[n+1])
812 * We KNOW .* will match everything up to the
813 * end of line. Thus, directly go to the end of
814 * line, without recursive PMatch calls. As in
815 * the other closure cases, the remaining pattern
816 * must be matched by moving backwards on the
817 * string recursively, to find a match for xy
818 * (x is ".*" and y is the remaining pattern)
819 * where the match satisfies the LONGEST match for
820 * x followed by a match for y.
822 * We can again scan the string forward for the
823 * single char and at the point of failure, we
824 * execute the remaining nfa recursively, same as
827 * At the end of a successful match, bopat[n] and eopat[n]
828 * are set to the beginning and end of subpatterns matched
829 * by tagged expressions (n = 1 to 9).
832 extern void re_fail(char *,char);
834 static inline int isinset(const char *ap
, unsigned char c
) noexcept
{
835 return ap
[(c
& BLKIND
) >> 3] & bitarr
[c
& BITIND
];
839 * skip values for CLO XXX to skip past the closure
842 #define ANYSKIP 2 /* [CLO] ANY END */
843 #define CHRSKIP 3 /* [CLO] CHR chr END */
844 #define CCLSKIP 34 /* [CLO] CCL 32 bytes END */
846 Sci::Position
RESearch::PMatch(const CharacterIndexer
&ci
, Sci::Position lp
, Sci::Position endp
, char *ap
) {
848 Sci::Position e
; /* extra pointer for CLO */
849 Sci::Position bp
; /* beginning of subpat... */
850 Sci::Position ep
; /* ending of subpat... */
851 Sci::Position are
; /* to save the line ptr. */
852 Sci::Position llp
; /* lazy lp for LCLO */
854 while ((op
= *ap
++) != END
)
858 if (ci
.CharAt(lp
++) != *ap
++)
868 if (!isinset(ap
, ci
.CharAt(lp
++)))
881 bopat
[static_cast<int>(*ap
++)] = lp
;
884 eopat
[static_cast<int>(*ap
++)] = lp
;
887 if ((lp
!=bol
&& iswordc(ci
.CharAt(lp
-1))) || !iswordc(ci
.CharAt(lp
)))
891 if (lp
==bol
|| !iswordc(ci
.CharAt(lp
-1)) || iswordc(ci
.CharAt(lp
)))
899 if (ci
.CharAt(bp
++) != ci
.CharAt(lp
++))
909 if (op
== CLO
|| op
== LCLO
)
919 if (op
== CLO
|| op
== LCLO
)
920 while ((lp
< endp
) && (c
== ci
.CharAt(lp
)))
922 else if ((lp
< endp
) && (c
== ci
.CharAt(lp
)))
927 while ((lp
< endp
) && isinset(ap
+1, ci
.CharAt(lp
)))
933 //re_fail("closure: bad nfa.", *ap);
942 if ((q
= PMatch(ci
, llp
, endp
, ap
)) != NOTFOUND
) {
945 if (op
!= LCLO
) return e
;
947 if (*ap
== END
) return e
;
951 PMatch(ci
, lp
, endp
, ap
);
954 //re_fail("RESearch::Execute: bad nfa.", static_cast<char>(op));