1 // Scintilla source code edit control
2 /** @file RESearch.cxx
3  ** Regular expression search library.
4  **/
5 
6 /*
7  * regex - Regular expression pattern matching and replacement
8  *
9  * By:  Ozan S. Yigit (oz)
10  *      Dept. of Computer Science
11  *      York University
12  *
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
21  *
22  * These routines are the PUBLIC DOMAIN equivalents of regex
23  * routines as found in 4.nBSD UN*X, with minor extensions.
24  *
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.
31  *
32  * Modification history removed.
33  *
34  * Interfaces:
35  *  RESearch::Compile:      compile a regular expression into a NFA.
36  *
37  *          const char *RESearch::Compile(const char *pattern, int length,
38  *                                        bool caseSensitive, bool posix)
39  *
40  * Returns a short error string if they fail.
41  *
42  *  RESearch::Execute:      execute the NFA to match a pattern.
43  *
44  *          int RESearch::Execute(characterIndexer &ci, int lp, int endp)
45  *
46  *  re_fail:                failure routine for RESearch::Execute. (no longer used)
47  *
48  *          void re_fail(char *msg, char op)
49  *
50  * Regular Expressions:
51  *
52  *      [1]     char    matches itself, unless it is a special
53  *                      character (metachar): . \ [ ] * + ? ^ $
54  *                      and ( ) if posix option.
55  *
56  *      [2]     .       matches any character.
57  *
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
68  *                      (see [10]);
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.
73  *
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).
85  *                      examples:        match:
86  *
87  *                              [-]|]    matches these 3 chars,
88  *
89  *                              []-|]    matches from ] to | chars
90  *
91  *                              [a-z]    any lowercase alpha
92  *
93  *                              [^-]]    any char except - and ]
94  *
95  *                              [^A-Z]   any char except uppercase
96  *                                       alpha
97  *
98  *                              [a-zA-Z] any alpha
99  *
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.
104  *
105  *      [6]     +       same as [5], except it matches one or more.
106  *
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
110  *
111  *      [7]     ?       same as [5] except it matches zero or one.
112  *
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.
118  *
119  *      [9]             a \ followed by a digit 1 to 9 matches whatever a
120  *                      previously tagged regular expression ([8]) matched.
121  *
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.
130  *
131  *      [11]    \l      a backslash followed by d, D, s, S, w or W,
132  *                      becomes a character class (both inside and
133  *                      outside sets []).
134  *                        d: decimal digits
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)
140  *
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.
145  *
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.
149  *
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.
155  *
156  *
157  * Acknowledgements:
158  *
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.
163  *
164  * References:
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
171  *
172  * Notes:
173  *
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.
179  *
180  * Examples:
181  *
182  *  pattern:    foo*.*
183  *  compile:    CHR f CHR o CLO CHR o END CLO ANY END END
184  *  matches:    fo foo fooo foobar fobar foxx ...
185  *
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
189  *
190  *  pattern:    foo\\+
191  *  compile:    CHR f CHR o CHR o CHR \ CLO CHR \ END END
192  *  matches:    foo\ foo\\ foo\\\  ...
193  *
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
197  *
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 ...
201  */
202 
203 #include <cstdlib>
204 
205 #include <stdexcept>
206 #include <string>
207 #include <algorithm>
208 
209 #include "Position.h"
210 #include "CharClassify.h"
211 #include "RESearch.h"
212 
213 #ifdef SCI_NAMESPACE
214 using namespace Scintilla;
215 #endif
216 
217 #define OKP     1
218 #define NOP     0
219 
220 #define CHR     1
221 #define ANY     2
222 #define CCL     3
223 #define BOL     4
224 #define EOL     5
225 #define BOT     6
226 #define EOT     7
227 #define BOW     8
228 #define EOW     9
229 #define REF     10
230 #define CLO     11
231 #define CLQ     12 /* 0 to 1 closure */
232 #define LCLO    13 /* lazy closure */
233 
234 #define END     0
235 
236 /*
237  * The following defines are not meant to be changeable.
238  * They are for readability only.
239  */
240 #define BLKIND  0370
241 #define BITIND  07
242 
243 const char bitarr[] = { 1, 2, 4, 8, 16, 32, 64, '\200' };
244 
245 #define badpat(x)	(*nfa = END, x)
246 
247 /*
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 _
252  */
253 
RESearch(CharClassify * charClassTable)254 RESearch::RESearch(CharClassify *charClassTable) {
255 	failure = 0;
256 	charClass = charClassTable;
257 	sta = NOP;                  /* status of lastpat */
258 	bol = 0;
259 	std::fill(bittab, bittab + BITBLK, static_cast<unsigned char>(0));
260 	std::fill(tagstk, tagstk + MAXTAG, 0);
261 	std::fill(nfa, nfa + MAXNFA, '\0');
262 	Clear();
263 }
264 
~RESearch()265 RESearch::~RESearch() {
266 	Clear();
267 }
268 
Clear()269 void RESearch::Clear() {
270 	for (int i = 0; i < MAXTAG; i++) {
271 		pat[i].clear();
272 		bopat[i] = NOTFOUND;
273 		eopat[i] = NOTFOUND;
274 	}
275 }
276 
GrabMatches(CharacterIndexer & ci)277 void RESearch::GrabMatches(CharacterIndexer &ci) {
278 	for (unsigned int i = 0; i < MAXTAG; i++) {
279 		if ((bopat[i] != NOTFOUND) && (eopat[i] != NOTFOUND)) {
280 			Sci::Position len = eopat[i] - bopat[i];
281 			pat[i].resize(len);
282 			for (Sci::Position j = 0; j < len; j++)
283 				pat[i][j] = ci.CharAt(bopat[i] + j);
284 		}
285 	}
286 }
287 
ChSet(unsigned char c)288 void RESearch::ChSet(unsigned char c) {
289 	bittab[((c) & BLKIND) >> 3] |= bitarr[(c) & BITIND];
290 }
291 
ChSetWithCase(unsigned char c,bool caseSensitive)292 void RESearch::ChSetWithCase(unsigned char c, bool caseSensitive) {
293 	if (caseSensitive) {
294 		ChSet(c);
295 	} else {
296 		if ((c >= 'a') && (c <= 'z')) {
297 			ChSet(c);
298 			ChSet(static_cast<unsigned char>(c - 'a' + 'A'));
299 		} else if ((c >= 'A') && (c <= 'Z')) {
300 			ChSet(c);
301 			ChSet(static_cast<unsigned char>(c - 'A' + 'a'));
302 		} else {
303 			ChSet(c);
304 		}
305 	}
306 }
307 
escapeValue(unsigned char ch)308 static unsigned char escapeValue(unsigned char ch) {
309 	switch (ch) {
310 	case 'a':	return '\a';
311 	case 'b':	return '\b';
312 	case 'f':	return '\f';
313 	case 'n':	return '\n';
314 	case 'r':	return '\r';
315 	case 't':	return '\t';
316 	case 'v':	return '\v';
317 	}
318 	return 0;
319 }
320 
GetHexaChar(unsigned char hd1,unsigned char hd2)321 static int GetHexaChar(unsigned char hd1, unsigned char hd2) {
322 	int hexValue = 0;
323 	if (hd1 >= '0' && hd1 <= '9') {
324 		hexValue += 16 * (hd1 - '0');
325 	} else if (hd1 >= 'A' && hd1 <= 'F') {
326 		hexValue += 16 * (hd1 - 'A' + 10);
327 	} else if (hd1 >= 'a' && hd1 <= 'f') {
328 		hexValue += 16 * (hd1 - 'a' + 10);
329 	} else {
330 		return -1;
331 	}
332 	if (hd2 >= '0' && hd2 <= '9') {
333 		hexValue += hd2 - '0';
334 	} else if (hd2 >= 'A' && hd2 <= 'F') {
335 		hexValue += hd2 - 'A' + 10;
336 	} else if (hd2 >= 'a' && hd2 <= 'f') {
337 		hexValue += hd2 - 'a' + 10;
338 	} else {
339 		return -1;
340 	}
341 	return hexValue;
342 }
343 
344 /**
345  * Called when the parser finds a backslash not followed
346  * by a valid expression (like \( in non-Posix mode).
347  * @param pattern : pointer on the char after the backslash.
348  * @param incr : (out) number of chars to skip after expression evaluation.
349  * @return the char if it resolves to a simple char,
350  * or -1 for a char class. In this case, bittab is changed.
351  */
GetBackslashExpression(const char * pattern,int & incr)352 int RESearch::GetBackslashExpression(
353     const char *pattern,
354     int &incr) {
355 	// Since error reporting is primitive and messages are not used anyway,
356 	// I choose to interpret unexpected syntax in a logical way instead
357 	// of reporting errors. Otherwise, we can stick on, eg., PCRE behavior.
358 	incr = 0;	// Most of the time, will skip the char "naturally".
359 	int c;
360 	int result = -1;
361 	const unsigned char bsc = *pattern;
362 	if (!bsc) {
363 		// Avoid overrun
364 		result = '\\';	// \ at end of pattern, take it literally
365 		return result;
366 	}
367 
368 	switch (bsc) {
369 	case 'a':
370 	case 'b':
371 	case 'n':
372 	case 'f':
373 	case 'r':
374 	case 't':
375 	case 'v':
376 		result = escapeValue(bsc);
377 		break;
378 	case 'x': {
379 			const unsigned char hd1 = *(pattern + 1);
380 			const unsigned char hd2 = *(pattern + 2);
381 			const int hexValue = GetHexaChar(hd1, hd2);
382 			if (hexValue >= 0) {
383 				result = hexValue;
384 				incr = 2;	// Must skip the digits
385 			} else {
386 				result = 'x';	// \x without 2 digits: see it as 'x'
387 			}
388 		}
389 		break;
390 	case 'd':
391 		for (c = '0'; c <= '9'; c++) {
392 			ChSet(static_cast<unsigned char>(c));
393 		}
394 		break;
395 	case 'D':
396 		for (c = 0; c < MAXCHR; c++) {
397 			if (c < '0' || c > '9') {
398 				ChSet(static_cast<unsigned char>(c));
399 			}
400 		}
401 		break;
402 	case 's':
403 		ChSet(' ');
404 		ChSet('\t');
405 		ChSet('\n');
406 		ChSet('\r');
407 		ChSet('\f');
408 		ChSet('\v');
409 		break;
410 	case 'S':
411 		for (c = 0; c < MAXCHR; c++) {
412 			if (c != ' ' && !(c >= 0x09 && c <= 0x0D)) {
413 				ChSet(static_cast<unsigned char>(c));
414 			}
415 		}
416 		break;
417 	case 'w':
418 		for (c = 0; c < MAXCHR; c++) {
419 			if (iswordc(static_cast<unsigned char>(c))) {
420 				ChSet(static_cast<unsigned char>(c));
421 			}
422 		}
423 		break;
424 	case 'W':
425 		for (c = 0; c < MAXCHR; c++) {
426 			if (!iswordc(static_cast<unsigned char>(c))) {
427 				ChSet(static_cast<unsigned char>(c));
428 			}
429 		}
430 		break;
431 	default:
432 		result = bsc;
433 	}
434 	return result;
435 }
436 
Compile(const char * pattern,Sci::Position length,bool caseSensitive,bool posix)437 const char *RESearch::Compile(const char *pattern, Sci::Position length, bool caseSensitive, bool posix) {
438 	char *mp=nfa;          /* nfa pointer       */
439 	char *lp;              /* saved pointer     */
440 	char *sp=nfa;          /* another one       */
441 	char *mpMax = mp + MAXNFA - BITBLK - 10;
442 
443 	int tagi = 0;          /* tag stack index   */
444 	int tagc = 1;          /* actual tag count  */
445 
446 	int n;
447 	char mask;             /* xor mask -CCL/NCL */
448 	int c1, c2, prevChar;
449 
450 	if (!pattern || !length) {
451 		if (sta)
452 			return 0;
453 		else
454 			return badpat("No previous regular expression");
455 	}
456 	sta = NOP;
457 
458 	const char *p=pattern;     /* pattern pointer   */
459 	for (int i=0; i<length; i++, p++) {
460 		if (mp > mpMax)
461 			return badpat("Pattern too long");
462 		lp = mp;
463 		switch (*p) {
464 
465 		case '.':               /* match any char  */
466 			*mp++ = ANY;
467 			break;
468 
469 		case '^':               /* match beginning */
470 			if (p == pattern) {
471 				*mp++ = BOL;
472 			} else {
473 				*mp++ = CHR;
474 				*mp++ = *p;
475 			}
476 			break;
477 
478 		case '$':               /* match endofline */
479 			if (!*(p+1)) {
480 				*mp++ = EOL;
481 			} else {
482 				*mp++ = CHR;
483 				*mp++ = *p;
484 			}
485 			break;
486 
487 		case '[':               /* match char class */
488 			*mp++ = CCL;
489 			prevChar = 0;
490 
491 			i++;
492 			if (*++p == '^') {
493 				mask = '\377';
494 				i++;
495 				p++;
496 			} else {
497 				mask = 0;
498 			}
499 
500 			if (*p == '-') {	/* real dash */
501 				i++;
502 				prevChar = *p;
503 				ChSet(*p++);
504 			}
505 			if (*p == ']') {	/* real brace */
506 				i++;
507 				prevChar = *p;
508 				ChSet(*p++);
509 			}
510 			while (*p && *p != ']') {
511 				if (*p == '-') {
512 					if (prevChar < 0) {
513 						// Previous def. was a char class like \d, take dash literally
514 						prevChar = *p;
515 						ChSet(*p);
516 					} else if (*(p+1)) {
517 						if (*(p+1) != ']') {
518 							c1 = prevChar + 1;
519 							i++;
520 							c2 = static_cast<unsigned char>(*++p);
521 							if (c2 == '\\') {
522 								if (!*(p+1)) {	// End of RE
523 									return badpat("Missing ]");
524 								} else {
525 									i++;
526 									p++;
527 									int incr;
528 									c2 = GetBackslashExpression(p, incr);
529 									i += incr;
530 									p += incr;
531 									if (c2 >= 0) {
532 										// Convention: \c (c is any char) is case sensitive, whatever the option
533 										ChSet(static_cast<unsigned char>(c2));
534 										prevChar = c2;
535 									} else {
536 										// bittab is already changed
537 										prevChar = -1;
538 									}
539 								}
540 							}
541 							if (prevChar < 0) {
542 								// Char after dash is char class like \d, take dash literally
543 								prevChar = '-';
544 								ChSet('-');
545 							} else {
546 								// Put all chars between c1 and c2 included in the char set
547 								while (c1 <= c2) {
548 									ChSetWithCase(static_cast<unsigned char>(c1++), caseSensitive);
549 								}
550 							}
551 						} else {
552 							// Dash before the ], take it literally
553 							prevChar = *p;
554 							ChSet(*p);
555 						}
556 					} else {
557 						return badpat("Missing ]");
558 					}
559 				} else if (*p == '\\' && *(p+1)) {
560 					i++;
561 					p++;
562 					int incr;
563 					int c = GetBackslashExpression(p, incr);
564 					i += incr;
565 					p += incr;
566 					if (c >= 0) {
567 						// Convention: \c (c is any char) is case sensitive, whatever the option
568 						ChSet(static_cast<unsigned char>(c));
569 						prevChar = c;
570 					} else {
571 						// bittab is already changed
572 						prevChar = -1;
573 					}
574 				} else {
575 					prevChar = static_cast<unsigned char>(*p);
576 					ChSetWithCase(*p, caseSensitive);
577 				}
578 				i++;
579 				p++;
580 			}
581 			if (!*p)
582 				return badpat("Missing ]");
583 
584 			for (n = 0; n < BITBLK; bittab[n++] = 0)
585 				*mp++ = static_cast<char>(mask ^ bittab[n]);
586 
587 			break;
588 
589 		case '*':               /* match 0 or more... */
590 		case '+':               /* match 1 or more... */
591 		case '?':
592 			if (p == pattern)
593 				return badpat("Empty closure");
594 			lp = sp;		/* previous opcode */
595 			if (*lp == CLO || *lp == LCLO)		/* equivalence... */
596 				break;
597 			switch (*lp) {
598 
599 			case BOL:
600 			case BOT:
601 			case EOT:
602 			case BOW:
603 			case EOW:
604 			case REF:
605 				return badpat("Illegal closure");
606 			default:
607 				break;
608 			}
609 
610 			if (*p == '+')
611 				for (sp = mp; lp < sp; lp++)
612 					*mp++ = *lp;
613 
614 			*mp++ = END;
615 			*mp++ = END;
616 			sp = mp;
617 
618 			while (--mp > lp)
619 				*mp = mp[-1];
620 			if (*p == '?')          *mp = CLQ;
621 			else if (*(p+1) == '?') *mp = LCLO;
622 			else                    *mp = CLO;
623 
624 			mp = sp;
625 			break;
626 
627 		case '\\':              /* tags, backrefs... */
628 			i++;
629 			switch (*++p) {
630 			case '<':
631 				*mp++ = BOW;
632 				break;
633 			case '>':
634 				if (*sp == BOW)
635 					return badpat("Null pattern inside \\<\\>");
636 				*mp++ = EOW;
637 				break;
638 			case '1':
639 			case '2':
640 			case '3':
641 			case '4':
642 			case '5':
643 			case '6':
644 			case '7':
645 			case '8':
646 			case '9':
647 				n = *p-'0';
648 				if (tagi > 0 && tagstk[tagi] == n)
649 					return badpat("Cyclical reference");
650 				if (tagc > n) {
651 					*mp++ = static_cast<char>(REF);
652 					*mp++ = static_cast<char>(n);
653 				} else {
654 					return badpat("Undetermined reference");
655 				}
656 				break;
657 			default:
658 				if (!posix && *p == '(') {
659 					if (tagc < MAXTAG) {
660 						tagstk[++tagi] = tagc;
661 						*mp++ = BOT;
662 						*mp++ = static_cast<char>(tagc++);
663 					} else {
664 						return badpat("Too many \\(\\) pairs");
665 					}
666 				} else if (!posix && *p == ')') {
667 					if (*sp == BOT)
668 						return badpat("Null pattern inside \\(\\)");
669 					if (tagi > 0) {
670 						*mp++ = static_cast<char>(EOT);
671 						*mp++ = static_cast<char>(tagstk[tagi--]);
672 					} else {
673 						return badpat("Unmatched \\)");
674 					}
675 				} else {
676 					int incr;
677 					int c = GetBackslashExpression(p, incr);
678 					i += incr;
679 					p += incr;
680 					if (c >= 0) {
681 						*mp++ = CHR;
682 						*mp++ = static_cast<unsigned char>(c);
683 					} else {
684 						*mp++ = CCL;
685 						mask = 0;
686 						for (n = 0; n < BITBLK; bittab[n++] = 0)
687 							*mp++ = static_cast<char>(mask ^ bittab[n]);
688 					}
689 				}
690 			}
691 			break;
692 
693 		default :               /* an ordinary char */
694 			if (posix && *p == '(') {
695 				if (tagc < MAXTAG) {
696 					tagstk[++tagi] = tagc;
697 					*mp++ = BOT;
698 					*mp++ = static_cast<char>(tagc++);
699 				} else {
700 					return badpat("Too many () pairs");
701 				}
702 			} else if (posix && *p == ')') {
703 				if (*sp == BOT)
704 					return badpat("Null pattern inside ()");
705 				if (tagi > 0) {
706 					*mp++ = static_cast<char>(EOT);
707 					*mp++ = static_cast<char>(tagstk[tagi--]);
708 				} else {
709 					return badpat("Unmatched )");
710 				}
711 			} else {
712 				unsigned char c = *p;
713 				if (!c)	// End of RE
714 					c = '\\';	// We take it as raw backslash
715 				if (caseSensitive || !iswordc(c)) {
716 					*mp++ = CHR;
717 					*mp++ = c;
718 				} else {
719 					*mp++ = CCL;
720 					mask = 0;
721 					ChSetWithCase(c, false);
722 					for (n = 0; n < BITBLK; bittab[n++] = 0)
723 						*mp++ = static_cast<char>(mask ^ bittab[n]);
724 				}
725 			}
726 			break;
727 		}
728 		sp = lp;
729 	}
730 	if (tagi > 0)
731 		return badpat((posix ? "Unmatched (" : "Unmatched \\("));
732 	*mp = END;
733 	sta = OKP;
734 	return 0;
735 }
736 
737 /*
738  * RESearch::Execute:
739  *   execute nfa to find a match.
740  *
741  *  special cases: (nfa[0])
742  *      BOL
743  *          Match only once, starting from the
744  *          beginning.
745  *      CHR
746  *          First locate the character without
747  *          calling PMatch, and if found, call
748  *          PMatch for the remaining string.
749  *      END
750  *          RESearch::Compile failed, poor luser did not
751  *          check for it. Fail fast.
752  *
753  *  If a match is found, bopat[0] and eopat[0] are set
754  *  to the beginning and the end of the matched fragment,
755  *  respectively.
756  *
757  */
Execute(CharacterIndexer & ci,Sci::Position lp,Sci::Position endp)758 int RESearch::Execute(CharacterIndexer &ci, Sci::Position lp, Sci::Position endp) {
759 	unsigned char c;
760 	Sci::Position ep = NOTFOUND;
761 	char *ap = nfa;
762 
763 	bol = lp;
764 	failure = 0;
765 
766 	Clear();
767 
768 	switch (*ap) {
769 
770 	case BOL:			/* anchored: match from BOL only */
771 		ep = PMatch(ci, lp, endp, ap);
772 		break;
773 	case EOL:			/* just searching for end of line normal path doesn't work */
774 		if (*(ap+1) == END) {
775 			lp = endp;
776 			ep = lp;
777 			break;
778 		} else {
779 			return 0;
780 		}
781 	case CHR:			/* ordinary char: locate it fast */
782 		c = *(ap+1);
783 		while ((lp < endp) && (static_cast<unsigned char>(ci.CharAt(lp)) != c))
784 			lp++;
785 		if (lp >= endp)	/* if EOS, fail, else fall through. */
786 			return 0;
787 	default:			/* regular matching all the way. */
788 		while (lp < endp) {
789 			ep = PMatch(ci, lp, endp, ap);
790 			if (ep != NOTFOUND)
791 				break;
792 			lp++;
793 		}
794 		break;
795 	case END:			/* munged automaton. fail always */
796 		return 0;
797 	}
798 	if (ep == NOTFOUND)
799 		return 0;
800 
801 	bopat[0] = lp;
802 	eopat[0] = ep;
803 	return 1;
804 }
805 
806 /*
807  * PMatch: internal routine for the hard part
808  *
809  *  This code is partly snarfed from an early grep written by
810  *  David Conroy. The backref and tag stuff, and various other
811  *  innovations are by oz.
812  *
813  *  special case optimizations: (nfa[n], nfa[n+1])
814  *      CLO ANY
815  *          We KNOW .* will match everything up to the
816  *          end of line. Thus, directly go to the end of
817  *          line, without recursive PMatch calls. As in
818  *          the other closure cases, the remaining pattern
819  *          must be matched by moving backwards on the
820  *          string recursively, to find a match for xy
821  *          (x is ".*" and y is the remaining pattern)
822  *          where the match satisfies the LONGEST match for
823  *          x followed by a match for y.
824  *      CLO CHR
825  *          We can again scan the string forward for the
826  *          single char and at the point of failure, we
827  *          execute the remaining nfa recursively, same as
828  *          above.
829  *
830  *  At the end of a successful match, bopat[n] and eopat[n]
831  *  are set to the beginning and end of subpatterns matched
832  *  by tagged expressions (n = 1 to 9).
833  */
834 
835 extern void re_fail(char *,char);
836 
837 #define isinset(x,y)	((x)[((y)&BLKIND)>>3] & bitarr[(y)&BITIND])
838 
839 /*
840  * skip values for CLO XXX to skip past the closure
841  */
842 
843 #define ANYSKIP 2 	/* [CLO] ANY END          */
844 #define CHRSKIP 3	/* [CLO] CHR chr END      */
845 #define CCLSKIP 34	/* [CLO] CCL 32 bytes END */
846 
PMatch(CharacterIndexer & ci,Sci::Position lp,Sci::Position endp,char * ap)847 Sci::Position RESearch::PMatch(CharacterIndexer &ci, Sci::Position lp, Sci::Position endp, char *ap) {
848 	int op, c, n;
849 	Sci::Position e;		/* extra pointer for CLO  */
850 	Sci::Position bp;		/* beginning of subpat... */
851 	Sci::Position ep;		/* ending of subpat...    */
852 	Sci::Position are;	/* to save the line ptr.  */
853 	Sci::Position llp;	/* lazy lp for LCLO       */
854 
855 	while ((op = *ap++) != END)
856 		switch (op) {
857 
858 		case CHR:
859 			if (ci.CharAt(lp++) != *ap++)
860 				return NOTFOUND;
861 			break;
862 		case ANY:
863 			if (lp++ >= endp)
864 				return NOTFOUND;
865 			break;
866 		case CCL:
867 			if (lp >= endp)
868 				return NOTFOUND;
869 			c = ci.CharAt(lp++);
870 			if (!isinset(ap,c))
871 				return NOTFOUND;
872 			ap += BITBLK;
873 			break;
874 		case BOL:
875 			if (lp != bol)
876 				return NOTFOUND;
877 			break;
878 		case EOL:
879 			if (lp < endp)
880 				return NOTFOUND;
881 			break;
882 		case BOT:
883 			bopat[static_cast<int>(*ap++)] = lp;
884 			break;
885 		case EOT:
886 			eopat[static_cast<int>(*ap++)] = lp;
887 			break;
888 		case BOW:
889 			if ((lp!=bol && iswordc(ci.CharAt(lp-1))) || !iswordc(ci.CharAt(lp)))
890 				return NOTFOUND;
891 			break;
892 		case EOW:
893 			if (lp==bol || !iswordc(ci.CharAt(lp-1)) || iswordc(ci.CharAt(lp)))
894 				return NOTFOUND;
895 			break;
896 		case REF:
897 			n = *ap++;
898 			bp = bopat[n];
899 			ep = eopat[n];
900 			while (bp < ep)
901 				if (ci.CharAt(bp++) != ci.CharAt(lp++))
902 					return NOTFOUND;
903 			break;
904 		case LCLO:
905 		case CLQ:
906 		case CLO:
907 			are = lp;
908 			switch (*ap) {
909 
910 			case ANY:
911 				if (op == CLO || op == LCLO)
912 					while (lp < endp)
913 						lp++;
914 				else if (lp < endp)
915 					lp++;
916 
917 				n = ANYSKIP;
918 				break;
919 			case CHR:
920 				c = *(ap+1);
921 				if (op == CLO || op == LCLO)
922 					while ((lp < endp) && (c == ci.CharAt(lp)))
923 						lp++;
924 				else if ((lp < endp) && (c == ci.CharAt(lp)))
925 					lp++;
926 				n = CHRSKIP;
927 				break;
928 			case CCL:
929 				while ((lp < endp) && isinset(ap+1,ci.CharAt(lp)))
930 					lp++;
931 				n = CCLSKIP;
932 				break;
933 			default:
934 				failure = true;
935 				//re_fail("closure: bad nfa.", *ap);
936 				return NOTFOUND;
937 			}
938 			ap += n;
939 
940 			llp = lp;
941 			e = NOTFOUND;
942 			while (llp >= are) {
943 				Sci::Position q;
944 				if ((q = PMatch(ci, llp, endp, ap)) != NOTFOUND) {
945 					e = q;
946 					lp = llp;
947 					if (op != LCLO) return e;
948 				}
949 				if (*ap == END) return e;
950 				--llp;
951 			}
952 			if (*ap == EOT)
953 				PMatch(ci, lp, endp, ap);
954 			return e;
955 		default:
956 			//re_fail("RESearch::Execute: bad nfa.", static_cast<char>(op));
957 			return NOTFOUND;
958 		}
959 	return lp;
960 }
961 
962 
963