regexp.c 30 KB

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