RegularExpression.cxx 38 KB

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