RegularExpression.cxx 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267
  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 <cstdio>
  29. #include <cstring>
  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 52 // 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 >= 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. delete[] this->program;
  336. // #endif
  337. this->program = new char[comp.regsize];
  338. this->progsize = static_cast<int>(comp.regsize);
  339. if (this->program == nullptr) {
  340. // RAISE Error, SYM(RegularExpression), SYM(Out_Of_Memory),
  341. printf("RegularExpression::compile(): Out of memory.\n");
  342. return false;
  343. }
  344. #ifdef __clang_analyzer__ /* Convince it that the program is initialized. */
  345. memset(this->program, 0, comp.regsize);
  346. #endif
  347. // Second pass: emit code.
  348. comp.regparse = exp;
  349. comp.regnpar = 1;
  350. comp.regcode = this->program;
  351. comp.regc(static_cast<char>(MAGIC));
  352. comp.reg(0, &flags);
  353. // Dig out information for optimizations.
  354. this->regstart = '\0'; // Worst-case defaults.
  355. this->reganch = 0;
  356. this->regmust = nullptr;
  357. this->regmlen = 0;
  358. scan = this->program + 1; // First BRANCH.
  359. if (OP(regnext(scan)) == END) { // Only one top-level choice.
  360. scan = OPERAND(scan);
  361. // Starting-point info.
  362. if (OP(scan) == EXACTLY)
  363. this->regstart = *OPERAND(scan);
  364. else if (OP(scan) == BOL)
  365. this->reganch++;
  366. //
  367. // If there's something expensive in the r.e., find the longest
  368. // literal string that must appear and make it the regmust. Resolve
  369. // ties in favor of later strings, since the regstart check works
  370. // with the beginning of the r.e. and avoiding duplication
  371. // strengthens checking. Not a strong reason, but sufficient in the
  372. // absence of others.
  373. //
  374. if (flags & SPSTART) {
  375. longest = nullptr;
  376. size_t len = 0;
  377. for (; scan != nullptr; scan = regnext(scan))
  378. if (OP(scan) == EXACTLY && strlen(OPERAND(scan)) >= len) {
  379. longest = OPERAND(scan);
  380. len = strlen(OPERAND(scan));
  381. }
  382. this->regmust = longest;
  383. this->regmlen = len;
  384. }
  385. }
  386. return true;
  387. }
  388. /*
  389. - reg - regular expression, i.e. main body or parenthesized thing
  390. *
  391. * Caller must absorb opening parenthesis.
  392. *
  393. * Combining parenthesis handling with the base level of regular expression
  394. * is a trifle forced, but the need to tie the tails of the branches to what
  395. * follows makes it hard to avoid.
  396. */
  397. char* RegExpCompile::reg(int paren, int* flagp)
  398. {
  399. char* ret;
  400. char* br;
  401. char* ender;
  402. int parno = 0;
  403. int flags;
  404. *flagp = HASWIDTH; // Tentatively.
  405. // Make an OPEN node, if parenthesized.
  406. if (paren) {
  407. if (regnpar >= RegularExpressionMatch::NSUBEXP) {
  408. // RAISE Error, SYM(RegularExpression), SYM(Too_Many_Parens),
  409. printf("RegularExpression::compile(): Too many parentheses.\n");
  410. return nullptr;
  411. }
  412. parno = regnpar;
  413. regnpar++;
  414. ret = regnode(static_cast<char>(OPEN + parno));
  415. } else
  416. ret = nullptr;
  417. // Pick up the branches, linking them together.
  418. br = regbranch(&flags);
  419. if (br == nullptr)
  420. return (nullptr);
  421. if (ret != nullptr)
  422. regtail(ret, br); // OPEN -> first.
  423. else
  424. ret = br;
  425. if (!(flags & HASWIDTH))
  426. *flagp &= ~HASWIDTH;
  427. *flagp |= flags & SPSTART;
  428. while (*regparse == '|') {
  429. regparse++;
  430. br = regbranch(&flags);
  431. if (br == nullptr)
  432. return (nullptr);
  433. regtail(ret, br); // BRANCH -> BRANCH.
  434. if (!(flags & HASWIDTH))
  435. *flagp &= ~HASWIDTH;
  436. *flagp |= flags & SPSTART;
  437. }
  438. // Make a closing node, and hook it on the end.
  439. ender = regnode(static_cast<char>((paren) ? CLOSE + parno : END));
  440. regtail(ret, ender);
  441. // Hook the tails of the branches to the closing node.
  442. for (br = ret; br != nullptr; br = regnext(br))
  443. regoptail(br, ender);
  444. // Check for proper termination.
  445. if (paren && *regparse++ != ')') {
  446. // RAISE Error, SYM(RegularExpression), SYM(Unmatched_Parens),
  447. printf("RegularExpression::compile(): Unmatched parentheses.\n");
  448. return nullptr;
  449. } else if (!paren && *regparse != '\0') {
  450. if (*regparse == ')') {
  451. // RAISE Error, SYM(RegularExpression), SYM(Unmatched_Parens),
  452. printf("RegularExpression::compile(): Unmatched parentheses.\n");
  453. return nullptr;
  454. } else {
  455. // RAISE Error, SYM(RegularExpression), SYM(Internal_Error),
  456. printf("RegularExpression::compile(): Internal error.\n");
  457. return nullptr;
  458. }
  459. // NOTREACHED
  460. }
  461. return (ret);
  462. }
  463. /*
  464. - regbranch - one alternative of an | operator
  465. *
  466. * Implements the concatenation operator.
  467. */
  468. char* RegExpCompile::regbranch(int* flagp)
  469. {
  470. char* ret;
  471. char* chain;
  472. char* latest;
  473. int flags;
  474. *flagp = WORST; // Tentatively.
  475. ret = regnode(BRANCH);
  476. chain = nullptr;
  477. while (*regparse != '\0' && *regparse != '|' && *regparse != ')') {
  478. latest = regpiece(&flags);
  479. if (latest == nullptr)
  480. return (nullptr);
  481. *flagp |= flags & HASWIDTH;
  482. if (chain == nullptr) // First piece.
  483. *flagp |= flags & SPSTART;
  484. else
  485. regtail(chain, latest);
  486. chain = latest;
  487. }
  488. if (chain == nullptr) // Loop ran zero times.
  489. regnode(NOTHING);
  490. return (ret);
  491. }
  492. /*
  493. - regpiece - something followed by possible [*+?]
  494. *
  495. * Note that the branching code sequences used for ? and the general cases
  496. * of * and + are somewhat optimized: they use the same NOTHING node as
  497. * both the endmarker for their branch list and the body of the last branch.
  498. * It might seem that this node could be dispensed with entirely, but the
  499. * endmarker role is not redundant.
  500. */
  501. char* RegExpCompile::regpiece(int* flagp)
  502. {
  503. char* ret;
  504. char op;
  505. char* next;
  506. int flags;
  507. ret = regatom(&flags);
  508. if (ret == nullptr)
  509. return (nullptr);
  510. op = *regparse;
  511. if (!ISMULT(op)) {
  512. *flagp = flags;
  513. return (ret);
  514. }
  515. if (!(flags & HASWIDTH) && op != '?') {
  516. // RAISE Error, SYM(RegularExpression), SYM(Empty_Operand),
  517. printf("RegularExpression::compile() : *+ operand could be empty.\n");
  518. return nullptr;
  519. }
  520. *flagp = (op != '+') ? (WORST | SPSTART) : (WORST | HASWIDTH);
  521. if (op == '*' && (flags & SIMPLE))
  522. reginsert(STAR, ret);
  523. else if (op == '*') {
  524. // Emit x* as (x&|), where & means "self".
  525. reginsert(BRANCH, ret); // Either x
  526. regoptail(ret, regnode(BACK)); // and loop
  527. regoptail(ret, ret); // back
  528. regtail(ret, regnode(BRANCH)); // or
  529. regtail(ret, regnode(NOTHING)); // null.
  530. } else if (op == '+' && (flags & SIMPLE))
  531. reginsert(PLUS, ret);
  532. else if (op == '+') {
  533. // Emit x+ as x(&|), where & means "self".
  534. next = regnode(BRANCH); // Either
  535. regtail(ret, next);
  536. regtail(regnode(BACK), ret); // loop back
  537. regtail(next, regnode(BRANCH)); // or
  538. regtail(ret, regnode(NOTHING)); // null.
  539. } else if (op == '?') {
  540. // Emit x? as (x|)
  541. reginsert(BRANCH, ret); // Either x
  542. regtail(ret, regnode(BRANCH)); // or
  543. next = regnode(NOTHING); // null.
  544. regtail(ret, next);
  545. regoptail(ret, next);
  546. }
  547. regparse++;
  548. if (ISMULT(*regparse)) {
  549. // RAISE Error, SYM(RegularExpression), SYM(Nested_Operand),
  550. printf("RegularExpression::compile(): Nested *?+.\n");
  551. return nullptr;
  552. }
  553. return (ret);
  554. }
  555. /*
  556. - regatom - the lowest level
  557. *
  558. * Optimization: gobbles an entire sequence of ordinary characters so that
  559. * it can turn them into a single node, which is smaller to store and
  560. * faster to run. Backslashed characters are exceptions, each becoming a
  561. * separate node; the code is simpler that way and it's not worth fixing.
  562. */
  563. char* RegExpCompile::regatom(int* flagp)
  564. {
  565. char* ret;
  566. int flags;
  567. *flagp = WORST; // Tentatively.
  568. switch (*regparse++) {
  569. case '^':
  570. ret = regnode(BOL);
  571. break;
  572. case '$':
  573. ret = regnode(EOL);
  574. break;
  575. case '.':
  576. ret = regnode(ANY);
  577. *flagp |= HASWIDTH | SIMPLE;
  578. break;
  579. case '[': {
  580. int rxpclass;
  581. int rxpclassend;
  582. if (*regparse == '^') { // Complement of range.
  583. ret = regnode(ANYBUT);
  584. regparse++;
  585. } else
  586. ret = regnode(ANYOF);
  587. if (*regparse == ']' || *regparse == '-')
  588. regc(*regparse++);
  589. while (*regparse != '\0' && *regparse != ']') {
  590. if (*regparse == '-') {
  591. regparse++;
  592. if (*regparse == ']' || *regparse == '\0')
  593. regc('-');
  594. else {
  595. rxpclass = UCHARAT(regparse - 2) + 1;
  596. rxpclassend = UCHARAT(regparse);
  597. if (rxpclass > rxpclassend + 1) {
  598. // RAISE Error, SYM(RegularExpression), SYM(Invalid_Range),
  599. printf("RegularExpression::compile(): Invalid range in [].\n");
  600. return nullptr;
  601. }
  602. for (; rxpclass <= rxpclassend; rxpclass++)
  603. regc(static_cast<char>(rxpclass));
  604. regparse++;
  605. }
  606. } else
  607. regc(*regparse++);
  608. }
  609. regc('\0');
  610. if (*regparse != ']') {
  611. // RAISE Error, SYM(RegularExpression), SYM(Unmatched_Bracket),
  612. printf("RegularExpression::compile(): Unmatched [].\n");
  613. return nullptr;
  614. }
  615. regparse++;
  616. *flagp |= HASWIDTH | SIMPLE;
  617. } break;
  618. case '(':
  619. ret = reg(1, &flags);
  620. if (ret == nullptr)
  621. return (nullptr);
  622. *flagp |= flags & (HASWIDTH | SPSTART);
  623. break;
  624. case '\0':
  625. case '|':
  626. case ')':
  627. // RAISE Error, SYM(RegularExpression), SYM(Internal_Error),
  628. printf("RegularExpression::compile(): Internal error.\n"); // Never here
  629. return nullptr;
  630. case '?':
  631. case '+':
  632. case '*':
  633. // RAISE Error, SYM(RegularExpression), SYM(No_Operand),
  634. printf("RegularExpression::compile(): ?+* follows nothing.\n");
  635. return nullptr;
  636. case '\\':
  637. if (*regparse == '\0') {
  638. // RAISE Error, SYM(RegularExpression), SYM(Trailing_Backslash),
  639. printf("RegularExpression::compile(): Trailing backslash.\n");
  640. return nullptr;
  641. }
  642. ret = regnode(EXACTLY);
  643. regc(*regparse++);
  644. regc('\0');
  645. *flagp |= HASWIDTH | SIMPLE;
  646. break;
  647. default: {
  648. int len;
  649. char ender;
  650. regparse--;
  651. len = int(strcspn(regparse, META));
  652. if (len <= 0) {
  653. // RAISE Error, SYM(RegularExpression), SYM(Internal_Error),
  654. printf("RegularExpression::compile(): Internal error.\n");
  655. return nullptr;
  656. }
  657. ender = *(regparse + len);
  658. if (len > 1 && ISMULT(ender))
  659. len--; // Back off clear of ?+* operand.
  660. *flagp |= HASWIDTH;
  661. if (len == 1)
  662. *flagp |= SIMPLE;
  663. ret = regnode(EXACTLY);
  664. while (len > 0) {
  665. regc(*regparse++);
  666. len--;
  667. }
  668. regc('\0');
  669. } break;
  670. }
  671. return (ret);
  672. }
  673. /*
  674. - regnode - emit a node
  675. Location.
  676. */
  677. char* RegExpCompile::regnode(char op)
  678. {
  679. char* ret;
  680. char* ptr;
  681. ret = regcode;
  682. if (ret == regdummyptr) {
  683. regsize += 3;
  684. return (ret);
  685. }
  686. ptr = ret;
  687. *ptr++ = op;
  688. *ptr++ = '\0'; // Null "next" pointer.
  689. *ptr++ = '\0';
  690. regcode = ptr;
  691. return (ret);
  692. }
  693. /*
  694. - regc - emit (if appropriate) a byte of code
  695. */
  696. void RegExpCompile::regc(char b)
  697. {
  698. if (regcode != regdummyptr)
  699. *regcode++ = b;
  700. else
  701. regsize++;
  702. }
  703. /*
  704. - reginsert - insert an operator in front of already-emitted operand
  705. *
  706. * Means relocating the operand.
  707. */
  708. void RegExpCompile::reginsert(char op, char* opnd)
  709. {
  710. char* src;
  711. char* dst;
  712. char* place;
  713. if (regcode == regdummyptr) {
  714. regsize += 3;
  715. return;
  716. }
  717. src = regcode;
  718. regcode += 3;
  719. dst = regcode;
  720. while (src > opnd)
  721. *--dst = *--src;
  722. place = opnd; // Op node, where operand used to be.
  723. *place++ = op;
  724. *place++ = '\0';
  725. *place = '\0';
  726. }
  727. /*
  728. - regtail - set the next-pointer at the end of a node chain
  729. */
  730. void RegExpCompile::regtail(char* p, const char* val)
  731. {
  732. char* scan;
  733. char* temp;
  734. int offset;
  735. if (p == regdummyptr)
  736. return;
  737. // Find last node.
  738. scan = p;
  739. for (;;) {
  740. temp = regnext(scan);
  741. if (temp == nullptr)
  742. break;
  743. scan = temp;
  744. }
  745. if (OP(scan) == BACK)
  746. offset = int(scan - val);
  747. else
  748. offset = int(val - scan);
  749. *(scan + 1) = static_cast<char>((offset >> 8) & 0377);
  750. *(scan + 2) = static_cast<char>(offset & 0377);
  751. }
  752. /*
  753. - regoptail - regtail on operand of first argument; nop if operandless
  754. */
  755. void RegExpCompile::regoptail(char* p, const char* val)
  756. {
  757. // "Operandless" and "op != BRANCH" are synonymous in practice.
  758. if (p == nullptr || p == regdummyptr || OP(p) != BRANCH)
  759. return;
  760. regtail(OPERAND(p), val);
  761. }
  762. ////////////////////////////////////////////////////////////////////////
  763. //
  764. // find and friends
  765. //
  766. ////////////////////////////////////////////////////////////////////////
  767. /*
  768. * Utility class for RegularExpression::find().
  769. */
  770. class RegExpFind
  771. {
  772. public:
  773. const char* reginput; // String-input pointer.
  774. const char* regbol; // Beginning of input, for ^ check.
  775. const char** regstartp; // Pointer to startp array.
  776. const char** regendp; // Ditto for endp.
  777. int regtry(const char*, const char**, const char**, const char*);
  778. int regmatch(const char*);
  779. int regrepeat(const char*);
  780. };
  781. // find -- Matches the regular expression to the given string.
  782. // Returns true if found, and sets start and end indexes accordingly.
  783. bool RegularExpression::find(char const* string,
  784. RegularExpressionMatch& rmatch) const
  785. {
  786. const char* s;
  787. rmatch.clear();
  788. rmatch.searchstring = string;
  789. if (!this->program) {
  790. return false;
  791. }
  792. // Check validity of program.
  793. if (UCHARAT(this->program) != MAGIC) {
  794. // RAISE Error, SYM(RegularExpression), SYM(Internal_Error),
  795. printf(
  796. "RegularExpression::find(): Compiled regular expression corrupted.\n");
  797. return false;
  798. }
  799. // If there is a "must appear" string, look for it.
  800. if (this->regmust != nullptr) {
  801. s = string;
  802. while ((s = strchr(s, this->regmust[0])) != nullptr) {
  803. if (strncmp(s, this->regmust, this->regmlen) == 0)
  804. break; // Found it.
  805. s++;
  806. }
  807. if (s == nullptr) // Not present.
  808. return false;
  809. }
  810. RegExpFind regFind;
  811. // Mark beginning of line for ^ .
  812. regFind.regbol = string;
  813. // Simplest case: anchored match need be tried only once.
  814. if (this->reganch)
  815. return (
  816. regFind.regtry(string, rmatch.startp, rmatch.endp, this->program) != 0);
  817. // Messy cases: unanchored match.
  818. s = string;
  819. if (this->regstart != '\0')
  820. // We know what char it must start with.
  821. while ((s = strchr(s, this->regstart)) != nullptr) {
  822. if (regFind.regtry(s, rmatch.startp, rmatch.endp, this->program))
  823. return true;
  824. s++;
  825. }
  826. else
  827. // We don't -- general case.
  828. do {
  829. if (regFind.regtry(s, rmatch.startp, rmatch.endp, this->program))
  830. return true;
  831. } while (*s++ != '\0');
  832. // Failure.
  833. return false;
  834. }
  835. /*
  836. - regtry - try match at specific point
  837. 0 failure, 1 success
  838. */
  839. int RegExpFind::regtry(const char* string, const char** start,
  840. const char** end, const char* prog)
  841. {
  842. int i;
  843. const char** sp1;
  844. const char** ep;
  845. reginput = string;
  846. regstartp = start;
  847. regendp = end;
  848. sp1 = start;
  849. ep = end;
  850. for (i = RegularExpressionMatch::NSUBEXP; i > 0; i--) {
  851. *sp1++ = nullptr;
  852. *ep++ = nullptr;
  853. }
  854. if (regmatch(prog + 1)) {
  855. start[0] = string;
  856. end[0] = reginput;
  857. return (1);
  858. } else
  859. return (0);
  860. }
  861. /*
  862. - regmatch - main matching routine
  863. *
  864. * Conceptually the strategy is simple: check to see whether the current
  865. * node matches, call self recursively to see whether the rest matches,
  866. * and then act accordingly. In practice we make some effort to avoid
  867. * recursion, in particular by going through "ordinary" nodes (that don't
  868. * need to know whether the rest of the match failed) by a loop instead of
  869. * by recursion.
  870. * 0 failure, 1 success
  871. */
  872. int RegExpFind::regmatch(const char* prog)
  873. {
  874. const char* scan; // Current node.
  875. const char* next; // Next node.
  876. scan = prog;
  877. while (scan != nullptr) {
  878. next = regnext(scan);
  879. switch (OP(scan)) {
  880. case BOL:
  881. if (reginput != regbol)
  882. return (0);
  883. break;
  884. case EOL:
  885. if (*reginput != '\0')
  886. return (0);
  887. break;
  888. case ANY:
  889. if (*reginput == '\0')
  890. return (0);
  891. reginput++;
  892. break;
  893. case EXACTLY: {
  894. size_t len;
  895. const char* opnd;
  896. opnd = OPERAND(scan);
  897. // Inline the first character, for speed.
  898. if (*opnd != *reginput)
  899. return (0);
  900. len = strlen(opnd);
  901. if (len > 1 && strncmp(opnd, reginput, len) != 0)
  902. return (0);
  903. reginput += len;
  904. } break;
  905. case ANYOF:
  906. if (*reginput == '\0' || strchr(OPERAND(scan), *reginput) == nullptr)
  907. return (0);
  908. reginput++;
  909. break;
  910. case ANYBUT:
  911. if (*reginput == '\0' || strchr(OPERAND(scan), *reginput) != nullptr)
  912. return (0);
  913. reginput++;
  914. break;
  915. case NOTHING:
  916. break;
  917. case BACK:
  918. break;
  919. case OPEN + 1:
  920. case OPEN + 2:
  921. case OPEN + 3:
  922. case OPEN + 4:
  923. case OPEN + 5:
  924. case OPEN + 6:
  925. case OPEN + 7:
  926. case OPEN + 8:
  927. case OPEN + 9:
  928. case OPEN + 10:
  929. case OPEN + 11:
  930. case OPEN + 12:
  931. case OPEN + 13:
  932. case OPEN + 14:
  933. case OPEN + 15:
  934. case OPEN + 16:
  935. case OPEN + 17:
  936. case OPEN + 18:
  937. case OPEN + 19:
  938. case OPEN + 20:
  939. case OPEN + 21:
  940. case OPEN + 22:
  941. case OPEN + 23:
  942. case OPEN + 24:
  943. case OPEN + 25:
  944. case OPEN + 26:
  945. case OPEN + 27:
  946. case OPEN + 28:
  947. case OPEN + 29:
  948. case OPEN + 30:
  949. case OPEN + 31:
  950. case OPEN + 32: {
  951. int no;
  952. const char* save;
  953. no = OP(scan) - OPEN;
  954. save = reginput;
  955. if (regmatch(next)) {
  956. //
  957. // Don't set startp if some later invocation of the
  958. // same parentheses already has.
  959. //
  960. if (regstartp[no] == nullptr)
  961. regstartp[no] = save;
  962. return (1);
  963. } else
  964. return (0);
  965. }
  966. // break;
  967. case CLOSE + 1:
  968. case CLOSE + 2:
  969. case CLOSE + 3:
  970. case CLOSE + 4:
  971. case CLOSE + 5:
  972. case CLOSE + 6:
  973. case CLOSE + 7:
  974. case CLOSE + 8:
  975. case CLOSE + 9:
  976. case CLOSE + 10:
  977. case CLOSE + 11:
  978. case CLOSE + 12:
  979. case CLOSE + 13:
  980. case CLOSE + 14:
  981. case CLOSE + 15:
  982. case CLOSE + 16:
  983. case CLOSE + 17:
  984. case CLOSE + 18:
  985. case CLOSE + 19:
  986. case CLOSE + 20:
  987. case CLOSE + 21:
  988. case CLOSE + 22:
  989. case CLOSE + 23:
  990. case CLOSE + 24:
  991. case CLOSE + 25:
  992. case CLOSE + 26:
  993. case CLOSE + 27:
  994. case CLOSE + 28:
  995. case CLOSE + 29:
  996. case CLOSE + 30:
  997. case CLOSE + 31:
  998. case CLOSE + 32: {
  999. int no;
  1000. const char* save;
  1001. no = OP(scan) - CLOSE;
  1002. save = reginput;
  1003. if (regmatch(next)) {
  1004. //
  1005. // Don't set endp if some later invocation of the
  1006. // same parentheses already has.
  1007. //
  1008. if (regendp[no] == nullptr)
  1009. regendp[no] = save;
  1010. return (1);
  1011. } else
  1012. return (0);
  1013. }
  1014. // break;
  1015. case BRANCH: {
  1016. const char* save;
  1017. if (OP(next) != BRANCH) // No choice.
  1018. next = OPERAND(scan); // Avoid recursion.
  1019. else {
  1020. do {
  1021. save = reginput;
  1022. if (regmatch(OPERAND(scan)))
  1023. return (1);
  1024. reginput = save;
  1025. scan = regnext(scan);
  1026. } while (scan != nullptr && OP(scan) == BRANCH);
  1027. return (0);
  1028. // NOTREACHED
  1029. }
  1030. } break;
  1031. case STAR:
  1032. case PLUS: {
  1033. char nextch;
  1034. int no;
  1035. const char* save;
  1036. int min_no;
  1037. //
  1038. // Lookahead to avoid useless match attempts when we know
  1039. // what character comes next.
  1040. //
  1041. nextch = '\0';
  1042. if (OP(next) == EXACTLY)
  1043. nextch = *OPERAND(next);
  1044. min_no = (OP(scan) == STAR) ? 0 : 1;
  1045. save = reginput;
  1046. no = regrepeat(OPERAND(scan));
  1047. while (no >= min_no) {
  1048. // If it could work, try it.
  1049. if (nextch == '\0' || *reginput == nextch)
  1050. if (regmatch(next))
  1051. return (1);
  1052. // Couldn't or didn't -- back up.
  1053. no--;
  1054. reginput = save + no;
  1055. }
  1056. return (0);
  1057. }
  1058. // break;
  1059. case END:
  1060. return (1); // Success!
  1061. default:
  1062. // RAISE Error, SYM(RegularExpression), SYM(Internal_Error),
  1063. printf(
  1064. "RegularExpression::find(): Internal error -- memory corrupted.\n");
  1065. return 0;
  1066. }
  1067. scan = next;
  1068. }
  1069. //
  1070. // We get here only if there's trouble -- normally "case END" is the
  1071. // terminating point.
  1072. //
  1073. // RAISE Error, SYM(RegularExpression), SYM(Internal_Error),
  1074. printf("RegularExpression::find(): Internal error -- corrupted pointers.\n");
  1075. return (0);
  1076. }
  1077. /*
  1078. - regrepeat - repeatedly match something simple, report how many
  1079. */
  1080. int RegExpFind::regrepeat(const char* p)
  1081. {
  1082. int count = 0;
  1083. const char* scan;
  1084. const char* opnd;
  1085. scan = reginput;
  1086. opnd = OPERAND(p);
  1087. switch (OP(p)) {
  1088. case ANY:
  1089. count = int(strlen(scan));
  1090. scan += count;
  1091. break;
  1092. case EXACTLY:
  1093. while (*opnd == *scan) {
  1094. count++;
  1095. scan++;
  1096. }
  1097. break;
  1098. case ANYOF:
  1099. while (*scan != '\0' && strchr(opnd, *scan) != nullptr) {
  1100. count++;
  1101. scan++;
  1102. }
  1103. break;
  1104. case ANYBUT:
  1105. while (*scan != '\0' && strchr(opnd, *scan) == nullptr) {
  1106. count++;
  1107. scan++;
  1108. }
  1109. break;
  1110. default: // Oh dear. Called inappropriately.
  1111. // RAISE Error, SYM(RegularExpression), SYM(Internal_Error),
  1112. printf("cm RegularExpression::find(): Internal error.\n");
  1113. return 0;
  1114. }
  1115. reginput = scan;
  1116. return (count);
  1117. }
  1118. /*
  1119. - regnext - dig the "next" pointer out of a node
  1120. */
  1121. static const char* regnext(const char* p)
  1122. {
  1123. int offset;
  1124. if (p == regdummyptr)
  1125. return (nullptr);
  1126. offset = NEXT(p);
  1127. if (offset == 0)
  1128. return (nullptr);
  1129. if (OP(p) == BACK)
  1130. return (p - offset);
  1131. else
  1132. return (p + offset);
  1133. }
  1134. static char* regnext(char* p)
  1135. {
  1136. int offset;
  1137. if (p == regdummyptr)
  1138. return (nullptr);
  1139. offset = NEXT(p);
  1140. if (offset == 0)
  1141. return (nullptr);
  1142. if (OP(p) == BACK)
  1143. return (p - offset);
  1144. else
  1145. return (p + offset);
  1146. }
  1147. } // namespace KWSYS_NAMESPACE