RegularExpression.cxx 34 KB

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