RegularExpression.cxx 38 KB

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