cmRegularExpression.cxx 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207
  1. /*=========================================================================
  2. Program: CMake - Cross-Platform Makefile Generator
  3. Module: $RCSfile$
  4. Language: C++
  5. Date: $Date$
  6. Version: $Revision$
  7. Copyright (c) 2002 Kitware, Inc., Insight Consortium. All rights reserved.
  8. See Copyright.txt or http://www.cmake.org/HTML/Copyright.html for details.
  9. This software is distributed WITHOUT ANY WARRANTY; without even
  10. the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
  11. PURPOSE. See the above copyright notices for more information.
  12. =========================================================================*/
  13. //
  14. // Copyright (C) 1991 Texas Instruments Incorporated.
  15. //
  16. // Permission is granted to any individual or institution to use, copy, modify,
  17. // and distribute this software, provided that this complete copyright and
  18. // permission notice is maintained, intact, in all copies and supporting
  19. // documentation.
  20. //
  21. // Texas Instruments Incorporated provides this software "as is" without
  22. // express or implied warranty.
  23. //
  24. //
  25. // Created: MNF 06/13/89 Initial Design and Implementation
  26. // Updated: LGO 08/09/89 Inherit from Generic
  27. // Updated: MBN 09/07/89 Added conditional exception handling
  28. // Updated: MBN 12/15/89 Sprinkled "const" qualifiers all over the place!
  29. // Updated: DLS 03/22/91 New lite version
  30. //
  31. #include "cmRegularExpression.h" // Include class specification
  32. #include "cmStandardIncludes.h"
  33. #include <stdio.h>
  34. // cmRegularExpression -- Copies the given regular expression.
  35. cmRegularExpression::cmRegularExpression (const cmRegularExpression& rxp) {
  36. if ( !rxp.program )
  37. {
  38. this->program = 0;
  39. return;
  40. }
  41. int ind;
  42. this->progsize = rxp.progsize; // Copy regular expression size
  43. this->program = new char[this->progsize]; // Allocate storage
  44. for(ind=this->progsize; ind-- != 0;) // Copy regular expresion
  45. this->program[ind] = rxp.program[ind];
  46. this->startp[0] = rxp.startp[0]; // Copy pointers into last
  47. this->endp[0] = rxp.endp[0]; // Successful "find" operation
  48. this->regmust = rxp.regmust; // Copy field
  49. if (rxp.regmust != 0) {
  50. char* dum = rxp.program;
  51. ind = 0;
  52. while (dum != rxp.regmust) {
  53. ++dum;
  54. ++ind;
  55. }
  56. this->regmust = this->program + ind;
  57. }
  58. this->regstart = rxp.regstart; // Copy starting index
  59. this->reganch = rxp.reganch; // Copy remaining private data
  60. this->regmlen = rxp.regmlen; // Copy remaining private data
  61. }
  62. // operator== -- Returns true if two regular expressions have the same
  63. // compiled program for pattern matching.
  64. bool cmRegularExpression::operator== (const cmRegularExpression& rxp) const {
  65. if (this != &rxp) { // Same address?
  66. int ind = this->progsize; // Get regular expression size
  67. if (ind != rxp.progsize) // If different size regexp
  68. return false; // Return failure
  69. while(ind-- != 0) // Else while still characters
  70. if(this->program[ind] != rxp.program[ind]) // If regexp are different
  71. return false; // Return failure
  72. }
  73. return true; // Else same, return success
  74. }
  75. // deep_equal -- Returns true if have the same compiled regular expressions
  76. // and the same start and end pointers.
  77. bool cmRegularExpression::deep_equal (const cmRegularExpression& rxp) const {
  78. int ind = this->progsize; // Get regular expression size
  79. if (ind != rxp.progsize) // If different size regexp
  80. return false; // Return failure
  81. while(ind-- != 0) // Else while still characters
  82. if(this->program[ind] != rxp.program[ind]) // If regexp are different
  83. return false; // Return failure
  84. return (this->startp[0] == rxp.startp[0] && // Else if same start/end ptrs,
  85. this->endp[0] == rxp.endp[0]); // Return true
  86. }
  87. // The remaining code in this file is derived from the regular expression code
  88. // whose copyright statement appears below. It has been changed to work
  89. // with the class concepts of C++ and COOL.
  90. /*
  91. * compile and find
  92. *
  93. * Copyright (c) 1986 by University of Toronto.
  94. * Written by Henry Spencer. Not derived from licensed software.
  95. *
  96. * Permission is granted to anyone to use this software for any
  97. * purpose on any computer system, and to redistribute it freely,
  98. * subject to the following restrictions:
  99. *
  100. * 1. The author is not responsible for the consequences of use of
  101. * this software, no matter how awful, even if they arise
  102. * from defects in it.
  103. *
  104. * 2. The origin of this software must not be misrepresented, either
  105. * by explicit claim or by omission.
  106. *
  107. * 3. Altered versions must be plainly marked as such, and must not
  108. * be misrepresented as being the original software.
  109. *
  110. * Beware that some of this code is subtly aware of the way operator
  111. * precedence is structured in regular expressions. Serious changes in
  112. * regular-expression syntax might require a total rethink.
  113. */
  114. /*
  115. * The "internal use only" fields in regexp.h are present to pass info from
  116. * compile to execute that permits the execute phase to run lots faster on
  117. * simple cases. They are:
  118. *
  119. * regstart char that must begin a match; '\0' if none obvious
  120. * reganch is the match anchored (at beginning-of-line only)?
  121. * regmust string (pointer into program) that match must include, or NULL
  122. * regmlen length of regmust string
  123. *
  124. * Regstart and reganch permit very fast decisions on suitable starting points
  125. * for a match, cutting down the work a lot. Regmust permits fast rejection
  126. * of lines that cannot possibly match. The regmust tests are costly enough
  127. * that compile() supplies a regmust only if the r.e. contains something
  128. * potentially expensive (at present, the only such thing detected is * or +
  129. * at the start of the r.e., which can involve a lot of backup). Regmlen is
  130. * supplied because the test in find() needs it and compile() is computing
  131. * it anyway.
  132. */
  133. /*
  134. * Structure for regexp "program". This is essentially a linear encoding
  135. * of a nondeterministic finite-state machine (aka syntax charts or
  136. * "railroad normal form" in parsing technology). Each node is an opcode
  137. * plus a "next" pointer, possibly plus an operand. "Next" pointers of
  138. * all nodes except BRANCH implement concatenation; a "next" pointer with
  139. * a BRANCH on both ends of it is connecting two alternatives. (Here we
  140. * have one of the subtle syntax dependencies: an individual BRANCH (as
  141. * opposed to a collection of them) is never concatenated with anything
  142. * because of operator precedence.) The operand of some types of node is
  143. * a literal string; for others, it is a node leading into a sub-FSM. In
  144. * particular, the operand of a BRANCH node is the first node of the branch.
  145. * (NB this is *not* a tree structure: the tail of the branch connects
  146. * to the thing following the set of BRANCHes.) The opcodes are:
  147. */
  148. // definition number opnd? meaning
  149. #define END 0 // no End of program.
  150. #define BOL 1 // no Match "" at beginning of line.
  151. #define EOL 2 // no Match "" at end of line.
  152. #define ANY 3 // no Match any one character.
  153. #define ANYOF 4 // str Match any character in this string.
  154. #define ANYBUT 5 // str Match any character not in this
  155. // string.
  156. #define BRANCH 6 // node Match this alternative, or the
  157. // next...
  158. #define BACK 7 // no Match "", "next" ptr points backward.
  159. #define EXACTLY 8 // str Match this string.
  160. #define NOTHING 9 // no Match empty string.
  161. #define STAR 10 // node Match this (simple) thing 0 or more
  162. // times.
  163. #define PLUS 11 // node Match this (simple) thing 1 or more
  164. // times.
  165. #define OPEN 20 // no Mark this point in input as start of
  166. // #n.
  167. // OPEN+1 is number 1, etc.
  168. #define CLOSE 30 // no Analogous to OPEN.
  169. /*
  170. * Opcode notes:
  171. *
  172. * BRANCH The set of branches constituting a single choice are hooked
  173. * together with their "next" pointers, since precedence prevents
  174. * anything being concatenated to any individual branch. The
  175. * "next" pointer of the last BRANCH in a choice points to the
  176. * thing following the whole choice. This is also where the
  177. * final "next" pointer of each individual branch points; each
  178. * branch starts with the operand node of a BRANCH node.
  179. *
  180. * BACK Normal "next" pointers all implicitly point forward; BACK
  181. * exists to make loop structures possible.
  182. *
  183. * STAR,PLUS '?', and complex '*' and '+', are implemented as circular
  184. * BRANCH structures using BACK. Simple cases (one character
  185. * per match) are implemented with STAR and PLUS for speed
  186. * and to minimize recursive plunges.
  187. *
  188. * OPEN,CLOSE ...are numbered at compile time.
  189. */
  190. /*
  191. * A node is one char of opcode followed by two chars of "next" pointer.
  192. * "Next" pointers are stored as two 8-bit pieces, high order first. The
  193. * value is a positive offset from the opcode of the node containing it.
  194. * An operand, if any, simply follows the node. (Note that much of the
  195. * code generation knows about this implicit relationship.)
  196. *
  197. * Using two bytes for the "next" pointer is vast overkill for most things,
  198. * but allows patterns to get big without disasters.
  199. */
  200. #define OP(p) (*(p))
  201. #define NEXT(p) (((*((p)+1)&0377)<<8) + (*((p)+2)&0377))
  202. #define OPERAND(p) ((p) + 3)
  203. const unsigned char MAGIC = 0234;
  204. /*
  205. * Utility definitions.
  206. */
  207. #define UCHARAT(p) ((const unsigned char*)(p))[0]
  208. #define FAIL(m) { regerror(m); return(0); }
  209. #define ISMULT(c) ((c) == '*' || (c) == '+' || (c) == '?')
  210. #define META "^$.[()|?+*\\"
  211. /*
  212. * Flags to be passed up and down.
  213. */
  214. #define HASWIDTH 01 // Known never to match null string.
  215. #define SIMPLE 02 // Simple enough to be STAR/PLUS operand.
  216. #define SPSTART 04 // Starts with * or +.
  217. #define WORST 0 // Worst case.
  218. /////////////////////////////////////////////////////////////////////////
  219. //
  220. // COMPILE AND ASSOCIATED FUNCTIONS
  221. //
  222. /////////////////////////////////////////////////////////////////////////
  223. /*
  224. * Global work variables for compile().
  225. */
  226. static const char* regparse; // Input-scan pointer.
  227. static int regnpar; // () count.
  228. static char regdummy;
  229. static char* regcode; // Code-emit pointer; &regdummy = don't.
  230. static long regsize; // Code size.
  231. /*
  232. * Forward declarations for compile()'s friends.
  233. */
  234. // #ifndef static
  235. // #define static static
  236. // #endif
  237. static char* reg (int, int*);
  238. static char* regbranch (int*);
  239. static char* regpiece (int*);
  240. static char* regatom (int*);
  241. static char* regnode (char);
  242. static const char* regnext (register const char*);
  243. static char* regnext (register char*);
  244. static void regc (unsigned char);
  245. static void reginsert (char, char*);
  246. static void regtail (char*, const char*);
  247. static void regoptail (char*, const char*);
  248. #ifdef STRCSPN
  249. static int strcspn ();
  250. #endif
  251. /*
  252. * We can't allocate space until we know how big the compiled form will be,
  253. * but we can't compile it (and thus know how big it is) until we've got a
  254. * place to put the code. So we cheat: we compile it twice, once with code
  255. * generation turned off and size counting turned on, and once "for real".
  256. * This also means that we don't allocate space until we are sure that the
  257. * thing really will compile successfully, and we never have to move the
  258. * code and thus invalidate pointers into it. (Note that it has to be in
  259. * one piece because free() must be able to free it all.)
  260. *
  261. * Beware that the optimization-preparation code in here knows about some
  262. * of the structure of the compiled regexp.
  263. */
  264. // compile -- compile a regular expression into internal code
  265. // for later pattern matching.
  266. bool cmRegularExpression::compile (const char* exp) {
  267. register const char* scan;
  268. register const char* longest;
  269. register unsigned long len;
  270. int flags;
  271. if (exp == 0) {
  272. //RAISE Error, SYM(cmRegularExpression), SYM(No_Expr),
  273. printf ("cmRegularExpression::compile(): No expression supplied.\n");
  274. return false;
  275. }
  276. // First pass: determine size, legality.
  277. regparse = exp;
  278. regnpar = 1;
  279. regsize = 0L;
  280. regcode = &regdummy;
  281. regc(MAGIC);
  282. if(!reg(0, &flags))
  283. {
  284. printf ("cmRegularExpression::compile(): Error in compile.\n");
  285. return false;
  286. }
  287. this->startp[0] = this->endp[0] = this->searchstring = 0;
  288. // Small enough for pointer-storage convention?
  289. if (regsize >= 32767L) { // Probably could be 65535L.
  290. //RAISE Error, SYM(cmRegularExpression), SYM(Expr_Too_Big),
  291. printf ("cmRegularExpression::compile(): Expression too big.\n");
  292. return false;
  293. }
  294. // Allocate space.
  295. //#ifndef WIN32
  296. if (this->program != 0) delete [] this->program;
  297. //#endif
  298. this->program = new char[regsize];
  299. this->progsize = (int) regsize;
  300. if (this->program == 0) {
  301. //RAISE Error, SYM(cmRegularExpression), SYM(Out_Of_Memory),
  302. printf ("cmRegularExpression::compile(): Out of memory.\n");
  303. return false;
  304. }
  305. // Second pass: emit code.
  306. regparse = exp;
  307. regnpar = 1;
  308. regcode = this->program;
  309. regc(MAGIC);
  310. reg(0, &flags);
  311. // Dig out information for optimizations.
  312. this->regstart = '\0'; // Worst-case defaults.
  313. this->reganch = 0;
  314. this->regmust = 0;
  315. this->regmlen = 0;
  316. scan = this->program + 1; // First BRANCH.
  317. if (OP(regnext(scan)) == END) { // Only one top-level choice.
  318. scan = OPERAND(scan);
  319. // Starting-point info.
  320. if (OP(scan) == EXACTLY)
  321. this->regstart = *OPERAND(scan);
  322. else if (OP(scan) == BOL)
  323. this->reganch++;
  324. //
  325. // If there's something expensive in the r.e., find the longest
  326. // literal string that must appear and make it the regmust. Resolve
  327. // ties in favor of later strings, since the regstart check works
  328. // with the beginning of the r.e. and avoiding duplication
  329. // strengthens checking. Not a strong reason, but sufficient in the
  330. // absence of others.
  331. //
  332. if (flags & SPSTART) {
  333. longest = 0;
  334. len = 0;
  335. for (; scan != 0; scan = regnext(scan))
  336. if (OP(scan) == EXACTLY && strlen(OPERAND(scan)) >= len) {
  337. longest = OPERAND(scan);
  338. len = int(strlen(OPERAND(scan)));
  339. }
  340. this->regmust = longest;
  341. this->regmlen = len;
  342. }
  343. }
  344. return true;
  345. }
  346. /*
  347. - reg - regular expression, i.e. main body or parenthesized thing
  348. *
  349. * Caller must absorb opening parenthesis.
  350. *
  351. * Combining parenthesis handling with the base level of regular expression
  352. * is a trifle forced, but the need to tie the tails of the branches to what
  353. * follows makes it hard to avoid.
  354. */
  355. static char* reg (int paren, int *flagp) {
  356. register char* ret;
  357. register char* br;
  358. register char* ender;
  359. register int parno =0;
  360. int flags;
  361. *flagp = HASWIDTH; // Tentatively.
  362. // Make an OPEN node, if parenthesized.
  363. if (paren) {
  364. if (regnpar >= NSUBEXP) {
  365. //RAISE Error, SYM(cmRegularExpression), SYM(Too_Many_Parens),
  366. printf ("cmRegularExpression::compile(): Too many parentheses.\n");
  367. return 0;
  368. }
  369. parno = regnpar;
  370. regnpar++;
  371. ret = regnode(OPEN + parno);
  372. }
  373. else
  374. ret = 0;
  375. // Pick up the branches, linking them together.
  376. br = regbranch(&flags);
  377. if (br == 0)
  378. return (0);
  379. if (ret != 0)
  380. regtail(ret, br); // OPEN -> first.
  381. else
  382. ret = br;
  383. if (!(flags & HASWIDTH))
  384. *flagp &= ~HASWIDTH;
  385. *flagp |= flags & SPSTART;
  386. while (*regparse == '|') {
  387. regparse++;
  388. br = regbranch(&flags);
  389. if (br == 0)
  390. return (0);
  391. regtail(ret, br); // BRANCH -> BRANCH.
  392. if (!(flags & HASWIDTH))
  393. *flagp &= ~HASWIDTH;
  394. *flagp |= flags & SPSTART;
  395. }
  396. // Make a closing node, and hook it on the end.
  397. ender = regnode((paren) ? CLOSE + parno : END);
  398. regtail(ret, ender);
  399. // Hook the tails of the branches to the closing node.
  400. for (br = ret; br != 0; br = regnext(br))
  401. regoptail(br, ender);
  402. // Check for proper termination.
  403. if (paren && *regparse++ != ')') {
  404. //RAISE Error, SYM(cmRegularExpression), SYM(Unmatched_Parens),
  405. printf ("cmRegularExpression::compile(): Unmatched parentheses.\n");
  406. return 0;
  407. }
  408. else if (!paren && *regparse != '\0') {
  409. if (*regparse == ')') {
  410. //RAISE Error, SYM(cmRegularExpression), SYM(Unmatched_Parens),
  411. printf ("cmRegularExpression::compile(): Unmatched parentheses.\n");
  412. return 0;
  413. }
  414. else {
  415. //RAISE Error, SYM(cmRegularExpression), SYM(Internal_Error),
  416. printf ("cmRegularExpression::compile(): Internal error.\n");
  417. return 0;
  418. }
  419. // NOTREACHED
  420. }
  421. return (ret);
  422. }
  423. /*
  424. - regbranch - one alternative of an | operator
  425. *
  426. * Implements the concatenation operator.
  427. */
  428. static char* regbranch (int *flagp) {
  429. register char* ret;
  430. register char* chain;
  431. register char* latest;
  432. int flags;
  433. *flagp = WORST; // Tentatively.
  434. ret = regnode(BRANCH);
  435. chain = 0;
  436. while (*regparse != '\0' && *regparse != '|' && *regparse != ')') {
  437. latest = regpiece(&flags);
  438. if (latest == 0)
  439. return (0);
  440. *flagp |= flags & HASWIDTH;
  441. if (chain == 0) // First piece.
  442. *flagp |= flags & SPSTART;
  443. else
  444. regtail(chain, latest);
  445. chain = latest;
  446. }
  447. if (chain == 0) // Loop ran zero times.
  448. regnode(NOTHING);
  449. return (ret);
  450. }
  451. /*
  452. - regpiece - something followed by possible [*+?]
  453. *
  454. * Note that the branching code sequences used for ? and the general cases
  455. * of * and + are somewhat optimized: they use the same NOTHING node as
  456. * both the endmarker for their branch list and the body of the last branch.
  457. * It might seem that this node could be dispensed with entirely, but the
  458. * endmarker role is not redundant.
  459. */
  460. static char* regpiece (int *flagp) {
  461. register char* ret;
  462. register char op;
  463. register char* next;
  464. int flags;
  465. ret = regatom(&flags);
  466. if (ret == 0)
  467. return (0);
  468. op = *regparse;
  469. if (!ISMULT(op)) {
  470. *flagp = flags;
  471. return (ret);
  472. }
  473. if (!(flags & HASWIDTH) && op != '?') {
  474. //RAISE Error, SYM(cmRegularExpression), SYM(Empty_Operand),
  475. printf ("cmRegularExpression::compile() : *+ operand could be empty.\n");
  476. return 0;
  477. }
  478. *flagp = (op != '+') ? (WORST | SPSTART) : (WORST | HASWIDTH);
  479. if (op == '*' && (flags & SIMPLE))
  480. reginsert(STAR, ret);
  481. else if (op == '*') {
  482. // Emit x* as (x&|), where & means "self".
  483. reginsert(BRANCH, ret); // Either x
  484. regoptail(ret, regnode(BACK)); // and loop
  485. regoptail(ret, ret); // back
  486. regtail(ret, regnode(BRANCH)); // or
  487. regtail(ret, regnode(NOTHING)); // null.
  488. }
  489. else if (op == '+' && (flags & SIMPLE))
  490. reginsert(PLUS, ret);
  491. else if (op == '+') {
  492. // Emit x+ as x(&|), where & means "self".
  493. next = regnode(BRANCH); // Either
  494. regtail(ret, next);
  495. regtail(regnode(BACK), ret); // loop back
  496. regtail(next, regnode(BRANCH)); // or
  497. regtail(ret, regnode(NOTHING)); // null.
  498. }
  499. else if (op == '?') {
  500. // Emit x? as (x|)
  501. reginsert(BRANCH, ret); // Either x
  502. regtail(ret, regnode(BRANCH)); // or
  503. next = regnode(NOTHING);// null.
  504. regtail(ret, next);
  505. regoptail(ret, next);
  506. }
  507. regparse++;
  508. if (ISMULT(*regparse)) {
  509. //RAISE Error, SYM(cmRegularExpression), SYM(Nested_Operand),
  510. printf ("cmRegularExpression::compile(): Nested *?+.\n");
  511. return 0;
  512. }
  513. return (ret);
  514. }
  515. /*
  516. - regatom - the lowest level
  517. *
  518. * Optimization: gobbles an entire sequence of ordinary characters so that
  519. * it can turn them into a single node, which is smaller to store and
  520. * faster to run. Backslashed characters are exceptions, each becoming a
  521. * separate node; the code is simpler that way and it's not worth fixing.
  522. */
  523. static char* regatom (int *flagp) {
  524. register char* ret;
  525. int flags;
  526. *flagp = WORST; // Tentatively.
  527. switch (*regparse++) {
  528. case '^':
  529. ret = regnode(BOL);
  530. break;
  531. case '$':
  532. ret = regnode(EOL);
  533. break;
  534. case '.':
  535. ret = regnode(ANY);
  536. *flagp |= HASWIDTH | SIMPLE;
  537. break;
  538. case '[':{
  539. register int rxpclass;
  540. register int rxpclassend;
  541. if (*regparse == '^') { // Complement of range.
  542. ret = regnode(ANYBUT);
  543. regparse++;
  544. }
  545. else
  546. ret = regnode(ANYOF);
  547. if (*regparse == ']' || *regparse == '-')
  548. regc(*regparse++);
  549. while (*regparse != '\0' && *regparse != ']') {
  550. if (*regparse == '-') {
  551. regparse++;
  552. if (*regparse == ']' || *regparse == '\0')
  553. regc('-');
  554. else {
  555. rxpclass = UCHARAT(regparse - 2) + 1;
  556. rxpclassend = UCHARAT(regparse);
  557. if (rxpclass > rxpclassend + 1) {
  558. //RAISE Error, SYM(cmRegularExpression), SYM(Invalid_Range),
  559. printf ("cmRegularExpression::compile(): Invalid range in [].\n");
  560. return 0;
  561. }
  562. for (; rxpclass <= rxpclassend; rxpclass++)
  563. regc(rxpclass);
  564. regparse++;
  565. }
  566. }
  567. else
  568. regc(*regparse++);
  569. }
  570. regc('\0');
  571. if (*regparse != ']') {
  572. //RAISE Error, SYM(cmRegularExpression), SYM(Unmatched_Bracket),
  573. printf ("cmRegularExpression::compile(): Unmatched [].\n");
  574. return 0;
  575. }
  576. regparse++;
  577. *flagp |= HASWIDTH | SIMPLE;
  578. }
  579. break;
  580. case '(':
  581. ret = reg(1, &flags);
  582. if (ret == 0)
  583. return (0);
  584. *flagp |= flags & (HASWIDTH | SPSTART);
  585. break;
  586. case '\0':
  587. case '|':
  588. case ')':
  589. //RAISE Error, SYM(cmRegularExpression), SYM(Internal_Error),
  590. printf ("cmRegularExpression::compile(): Internal error.\n"); // Never here
  591. return 0;
  592. case '?':
  593. case '+':
  594. case '*':
  595. //RAISE Error, SYM(cmRegularExpression), SYM(No_Operand),
  596. printf ("cmRegularExpression::compile(): ?+* follows nothing.\n");
  597. return 0;
  598. case '\\':
  599. if (*regparse == '\0') {
  600. //RAISE Error, SYM(cmRegularExpression), SYM(Trailing_Backslash),
  601. printf ("cmRegularExpression::compile(): Trailing backslash.\n");
  602. return 0;
  603. }
  604. ret = regnode(EXACTLY);
  605. regc(*regparse++);
  606. regc('\0');
  607. *flagp |= HASWIDTH | SIMPLE;
  608. break;
  609. default:{
  610. register int len;
  611. register char ender;
  612. regparse--;
  613. len = int(strcspn(regparse, META));
  614. if (len <= 0) {
  615. //RAISE Error, SYM(cmRegularExpression), SYM(Internal_Error),
  616. printf ("cmRegularExpression::compile(): Internal error.\n");
  617. return 0;
  618. }
  619. ender = *(regparse + len);
  620. if (len > 1 && ISMULT(ender))
  621. len--; // Back off clear of ?+* operand.
  622. *flagp |= HASWIDTH;
  623. if (len == 1)
  624. *flagp |= SIMPLE;
  625. ret = regnode(EXACTLY);
  626. while (len > 0) {
  627. regc(*regparse++);
  628. len--;
  629. }
  630. regc('\0');
  631. }
  632. break;
  633. }
  634. return (ret);
  635. }
  636. /*
  637. - regnode - emit a node
  638. Location.
  639. */
  640. static char* regnode (char op) {
  641. register char* ret;
  642. register char* ptr;
  643. ret = regcode;
  644. if (ret == &regdummy) {
  645. regsize += 3;
  646. return (ret);
  647. }
  648. ptr = ret;
  649. *ptr++ = op;
  650. *ptr++ = '\0'; // Null "next" pointer.
  651. *ptr++ = '\0';
  652. regcode = ptr;
  653. return (ret);
  654. }
  655. /*
  656. - regc - emit (if appropriate) a byte of code
  657. */
  658. static void regc (unsigned char b) {
  659. if (regcode != &regdummy)
  660. *regcode++ = b;
  661. else
  662. regsize++;
  663. }
  664. /*
  665. - reginsert - insert an operator in front of already-emitted operand
  666. *
  667. * Means relocating the operand.
  668. */
  669. static void reginsert (char op, char* opnd) {
  670. register char* src;
  671. register char* dst;
  672. register char* place;
  673. if (regcode == &regdummy) {
  674. regsize += 3;
  675. return;
  676. }
  677. src = regcode;
  678. regcode += 3;
  679. dst = regcode;
  680. while (src > opnd)
  681. *--dst = *--src;
  682. place = opnd; // Op node, where operand used to be.
  683. *place++ = op;
  684. *place++ = '\0';
  685. *place++ = '\0';
  686. }
  687. /*
  688. - regtail - set the next-pointer at the end of a node chain
  689. */
  690. static void regtail (char* p, const char* val) {
  691. register char* scan;
  692. register char* temp;
  693. register int offset;
  694. if (p == &regdummy)
  695. return;
  696. // Find last node.
  697. scan = p;
  698. for (;;) {
  699. temp = regnext(scan);
  700. if (temp == 0)
  701. break;
  702. scan = temp;
  703. }
  704. if (OP(scan) == BACK)
  705. offset = int(scan - val);
  706. else
  707. offset = int(val - scan);
  708. *(scan + 1) = (offset >> 8) & 0377;
  709. *(scan + 2) = offset & 0377;
  710. }
  711. /*
  712. - regoptail - regtail on operand of first argument; nop if operandless
  713. */
  714. static void regoptail (char* p, const char* val) {
  715. // "Operandless" and "op != BRANCH" are synonymous in practice.
  716. if (p == 0 || p == &regdummy || OP(p) != BRANCH)
  717. return;
  718. regtail(OPERAND(p), val);
  719. }
  720. ////////////////////////////////////////////////////////////////////////
  721. //
  722. // find and friends
  723. //
  724. ////////////////////////////////////////////////////////////////////////
  725. /*
  726. * Global work variables for find().
  727. */
  728. static const char* reginput; // String-input pointer.
  729. static const char* regbol; // Beginning of input, for ^ check.
  730. static const char* *regstartp; // Pointer to startp array.
  731. static const char* *regendp; // Ditto for endp.
  732. /*
  733. * Forwards.
  734. */
  735. static int regtry (const char*, const char* *,
  736. const char* *, const char*);
  737. static int regmatch (const char*);
  738. static int regrepeat (const char*);
  739. #ifdef DEBUG
  740. int regnarrate = 0;
  741. void regdump ();
  742. static char* regprop ();
  743. #endif
  744. bool cmRegularExpression::find (std::string const& s)
  745. {
  746. return find(s.c_str());
  747. }
  748. // find -- Matches the regular expression to the given string.
  749. // Returns true if found, and sets start and end indexes accordingly.
  750. bool cmRegularExpression::find (const char* string) {
  751. register const char* s;
  752. this->searchstring = string;
  753. if (!this->program)
  754. {
  755. return false;
  756. }
  757. // Check validity of program.
  758. if (UCHARAT(this->program) != MAGIC) {
  759. //RAISE Error, SYM(cmRegularExpression), SYM(Internal_Error),
  760. printf ("cmRegularExpression::find(): Compiled regular expression corrupted.\n");
  761. return 0;
  762. }
  763. // If there is a "must appear" string, look for it.
  764. if (this->regmust != 0) {
  765. s = string;
  766. while ((s = strchr(s, this->regmust[0])) != 0) {
  767. if (strncmp(s, this->regmust, this->regmlen) == 0)
  768. break; // Found it.
  769. s++;
  770. }
  771. if (s == 0) // Not present.
  772. return (0);
  773. }
  774. // Mark beginning of line for ^ .
  775. regbol = string;
  776. // Simplest case: anchored match need be tried only once.
  777. if (this->reganch)
  778. return (regtry(string, this->startp, this->endp, this->program) != 0);
  779. // Messy cases: unanchored match.
  780. s = string;
  781. if (this->regstart != '\0')
  782. // We know what char it must start with.
  783. while ((s = strchr(s, this->regstart)) != 0) {
  784. if (regtry(s, this->startp, this->endp, this->program))
  785. return (1);
  786. s++;
  787. }
  788. else
  789. // We don't -- general case.
  790. do {
  791. if (regtry(s, this->startp, this->endp, this->program))
  792. return (1);
  793. } while (*s++ != '\0');
  794. // Failure.
  795. return (0);
  796. }
  797. /*
  798. - regtry - try match at specific point
  799. 0 failure, 1 success
  800. */
  801. static int regtry (const char* string, const char* *start,
  802. const char* *end, const char* prog) {
  803. register int i;
  804. register const char* *sp1;
  805. register const char* *ep;
  806. reginput = string;
  807. regstartp = start;
  808. regendp = end;
  809. sp1 = start;
  810. ep = end;
  811. for (i = NSUBEXP; i > 0; i--) {
  812. *sp1++ = 0;
  813. *ep++ = 0;
  814. }
  815. if (regmatch(prog + 1)) {
  816. start[0] = string;
  817. end[0] = reginput;
  818. return (1);
  819. }
  820. else
  821. return (0);
  822. }
  823. /*
  824. - regmatch - main matching routine
  825. *
  826. * Conceptually the strategy is simple: check to see whether the current
  827. * node matches, call self recursively to see whether the rest matches,
  828. * and then act accordingly. In practice we make some effort to avoid
  829. * recursion, in particular by going through "ordinary" nodes (that don't
  830. * need to know whether the rest of the match failed) by a loop instead of
  831. * by recursion.
  832. * 0 failure, 1 success
  833. */
  834. static int regmatch (const char* prog) {
  835. register const char* scan; // Current node.
  836. const char* next; // Next node.
  837. scan = prog;
  838. while (scan != 0) {
  839. next = regnext(scan);
  840. switch (OP(scan)) {
  841. case BOL:
  842. if (reginput != regbol)
  843. return (0);
  844. break;
  845. case EOL:
  846. if (*reginput != '\0')
  847. return (0);
  848. break;
  849. case ANY:
  850. if (*reginput == '\0')
  851. return (0);
  852. reginput++;
  853. break;
  854. case EXACTLY:{
  855. register int len;
  856. register const char* opnd;
  857. opnd = OPERAND(scan);
  858. // Inline the first character, for speed.
  859. if (*opnd != *reginput)
  860. return (0);
  861. len = int(strlen(opnd));
  862. if (len > 1 && strncmp(opnd, reginput, len) != 0)
  863. return (0);
  864. reginput += len;
  865. }
  866. break;
  867. case ANYOF:
  868. if (*reginput == '\0' || strchr(OPERAND(scan), *reginput) == 0)
  869. return (0);
  870. reginput++;
  871. break;
  872. case ANYBUT:
  873. if (*reginput == '\0' || strchr(OPERAND(scan), *reginput) != 0)
  874. return (0);
  875. reginput++;
  876. break;
  877. case NOTHING:
  878. break;
  879. case BACK:
  880. break;
  881. case OPEN + 1:
  882. case OPEN + 2:
  883. case OPEN + 3:
  884. case OPEN + 4:
  885. case OPEN + 5:
  886. case OPEN + 6:
  887. case OPEN + 7:
  888. case OPEN + 8:
  889. case OPEN + 9:{
  890. register int no;
  891. register const char* save;
  892. no = OP(scan) - OPEN;
  893. save = reginput;
  894. if (regmatch(next)) {
  895. //
  896. // Don't set startp if some later invocation of the
  897. // same parentheses already has.
  898. //
  899. if (regstartp[no] == 0)
  900. regstartp[no] = save;
  901. return (1);
  902. }
  903. else
  904. return (0);
  905. }
  906. // break;
  907. case CLOSE + 1:
  908. case CLOSE + 2:
  909. case CLOSE + 3:
  910. case CLOSE + 4:
  911. case CLOSE + 5:
  912. case CLOSE + 6:
  913. case CLOSE + 7:
  914. case CLOSE + 8:
  915. case CLOSE + 9:{
  916. register int no;
  917. register const char* save;
  918. no = OP(scan) - CLOSE;
  919. save = reginput;
  920. if (regmatch(next)) {
  921. //
  922. // Don't set endp if some later invocation of the
  923. // same parentheses already has.
  924. //
  925. if (regendp[no] == 0)
  926. regendp[no] = save;
  927. return (1);
  928. }
  929. else
  930. return (0);
  931. }
  932. // break;
  933. case BRANCH:{
  934. register const char* save;
  935. if (OP(next) != BRANCH) // No choice.
  936. next = OPERAND(scan); // Avoid recursion.
  937. else {
  938. do {
  939. save = reginput;
  940. if (regmatch(OPERAND(scan)))
  941. return (1);
  942. reginput = save;
  943. scan = regnext(scan);
  944. } while (scan != 0 && OP(scan) == BRANCH);
  945. return (0);
  946. // NOTREACHED
  947. }
  948. }
  949. break;
  950. case STAR:
  951. case PLUS:{
  952. register char nextch;
  953. register int no;
  954. register const char* save;
  955. register int min_no;
  956. //
  957. // Lookahead to avoid useless match attempts when we know
  958. // what character comes next.
  959. //
  960. nextch = '\0';
  961. if (OP(next) == EXACTLY)
  962. nextch = *OPERAND(next);
  963. min_no = (OP(scan) == STAR) ? 0 : 1;
  964. save = reginput;
  965. no = regrepeat(OPERAND(scan));
  966. while (no >= min_no) {
  967. // If it could work, try it.
  968. if (nextch == '\0' || *reginput == nextch)
  969. if (regmatch(next))
  970. return (1);
  971. // Couldn't or didn't -- back up.
  972. no--;
  973. reginput = save + no;
  974. }
  975. return (0);
  976. }
  977. // break;
  978. case END:
  979. return (1); // Success!
  980. default:
  981. //RAISE Error, SYM(cmRegularExpression), SYM(Internal_Error),
  982. printf ("cmRegularExpression::find(): Internal error -- memory corrupted.\n");
  983. return 0;
  984. }
  985. scan = next;
  986. }
  987. //
  988. // We get here only if there's trouble -- normally "case END" is the
  989. // terminating point.
  990. //
  991. //RAISE Error, SYM(cmRegularExpression), SYM(Internal_Error),
  992. printf ("cmRegularExpression::find(): Internal error -- corrupted pointers.\n");
  993. return (0);
  994. }
  995. /*
  996. - regrepeat - repeatedly match something simple, report how many
  997. */
  998. static int regrepeat (const char* p) {
  999. register int count = 0;
  1000. register const char* scan;
  1001. register const char* opnd;
  1002. scan = reginput;
  1003. opnd = OPERAND(p);
  1004. switch (OP(p)) {
  1005. case ANY:
  1006. count = int(strlen(scan));
  1007. scan += count;
  1008. break;
  1009. case EXACTLY:
  1010. while (*opnd == *scan) {
  1011. count++;
  1012. scan++;
  1013. }
  1014. break;
  1015. case ANYOF:
  1016. while (*scan != '\0' && strchr(opnd, *scan) != 0) {
  1017. count++;
  1018. scan++;
  1019. }
  1020. break;
  1021. case ANYBUT:
  1022. while (*scan != '\0' && strchr(opnd, *scan) == 0) {
  1023. count++;
  1024. scan++;
  1025. }
  1026. break;
  1027. default: // Oh dear. Called inappropriately.
  1028. //RAISE Error, SYM(cmRegularExpression), SYM(Internal_Error),
  1029. printf ("cm RegularExpression::find(): Internal error.\n");
  1030. return 0;
  1031. }
  1032. reginput = scan;
  1033. return (count);
  1034. }
  1035. /*
  1036. - regnext - dig the "next" pointer out of a node
  1037. */
  1038. static const char* regnext (register const char* p) {
  1039. register int offset;
  1040. if (p == &regdummy)
  1041. return (0);
  1042. offset = NEXT(p);
  1043. if (offset == 0)
  1044. return (0);
  1045. if (OP(p) == BACK)
  1046. return (p - offset);
  1047. else
  1048. return (p + offset);
  1049. }
  1050. static char* regnext (register char* p) {
  1051. register int offset;
  1052. if (p == &regdummy)
  1053. return (0);
  1054. offset = NEXT(p);
  1055. if (offset == 0)
  1056. return (0);
  1057. if (OP(p) == BACK)
  1058. return (p - offset);
  1059. else
  1060. return (p + offset);
  1061. }