cmRegularExpression.cxx 32 KB

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