RegularExpression.cxx 38 KB

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