PageRenderTime 54ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/ExtLibs/wxWidgets/src/stc/scintilla/src/RESearch.cxx

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