home *** CD-ROM | disk | FTP | other *** search
/ Usenet 1994 October / usenetsourcesnewsgroupsinfomagicoctober1994disk2.iso / unix / volume9 / fastgrep / part02 < prev    next >
Text File  |  1987-06-15  |  56KB  |  2,242 lines

  1. Path: seismo!uunet!rs
  2. From: rs@uunet.UU.NET (Rich Salz)
  3. Newsgroups: comp.sources.unix
  4. Subject: v09i062:  Fastest grep around, Part02/02
  5. Message-ID: <366@uunet.UU.NET>
  6. Date: 16 Jun 87 23:37:04 GMT
  7. Organization: UUNET Communications Services, Arlington, VA
  8. Lines: 2231
  9. Approved: rs@uunet.uu.net
  10.  
  11. Submitted by: James A. Woods <ames!aurora!jaw>
  12. Mod.sources: Volume 9, Issue 62
  13. Archive-name: fastgrep/Part02
  14.  
  15. [  This was previously published in mod.sources, but was part of James's
  16.    distribution and contains a bugfix mailed to me by Henry Spencer.
  17.    (Giving proper credit, the bug was found by Jeff McCarrell at Berkeley.)
  18.     The bug was in the NEXT macro, line 116 of regexp.c --r$  ]
  19.  
  20. # To unbundle, sh this file
  21. echo README.regexp 1>&2
  22. cat > README.regexp <<'End of README.regexp'
  23. This is a nearly-public-domain reimplementation of the V8 regexp(3) package.
  24. It gives C programs the ability to use egrep-style regular expressions, and
  25. does it in a much cleaner fashion than the analogous routines in SysV.
  26.  
  27.     Copyright (c) 1986 by University of Toronto.
  28.     Written by Henry Spencer.  Not derived from licensed software.
  29.  
  30.     Permission is granted to anyone to use this software for any
  31.     purpose on any computer system, and to redistribute it freely,
  32.     subject to the following restrictions:
  33.  
  34.     1. The author is not responsible for the consequences of use of
  35.         this software, no matter how awful, even if they arise
  36.         from defects in it.
  37.  
  38.     2. The origin of this software must not be misrepresented, either
  39.         by explicit claim or by omission.
  40.  
  41.     3. Altered versions must be plainly marked as such, and must not
  42.         be misrepresented as being the original software.
  43.  
  44. Barring a couple of small items in the BUGS list, this implementation is
  45. believed 100% compatible with V8.  It should even be binary-compatible,
  46. sort of, since the only fields in a "struct regexp" that other people have
  47. any business touching are declared in exactly the same way at the same
  48. location in the struct (the beginning).
  49.  
  50. This implementation is *NOT* AT&T/Bell code, and is not derived from licensed
  51. software.  Even though U of T is a V8 licensee.  This software is based on
  52. a V8 manual page sent to me by Dennis Ritchie (the manual page enclosed
  53. here is a complete rewrite and hence is not covered by AT&T copyright).
  54. The software was nearly complete at the time of arrival of our V8 tape.
  55. I haven't even looked at V8 yet, although a friend elsewhere at U of T has
  56. been kind enough to run a few test programs using the V8 regexp(3) to resolve
  57. a few fine points.  I admit to some familiarity with regular-expression
  58. implementations of the past, but the only one that this code traces any
  59. ancestry to is the one published in Kernighan & Plauger (from which this
  60. one draws ideas but not code).
  61.  
  62. Simplistically:  put this stuff into a source directory, copy regexp.h into
  63. /usr/include, inspect Makefile for compilation options that need changing
  64. to suit your local environment, and then do "make r".  This compiles the
  65. regexp(3) functions, compiles a test program, and runs a large set of
  66. regression tests.  If there are no complaints, then put regexp.o, regsub.o,
  67. and regerror.o into your C library, and regexp.3 into your manual-pages
  68. directory.
  69.  
  70. Note that if you don't put regexp.h into /usr/include *before* compiling,
  71. you'll have to add "-I." to CFLAGS before compiling.
  72.  
  73. The files are:
  74.  
  75. Makefile    instructions to make everything
  76. regexp.3    manual page
  77. regexp.h    header file, for /usr/include
  78. regexp.c    source for regcomp() and regexec()
  79. regsub.c    source for regsub()
  80. regerror.c    source for default regerror()
  81. regmagic.h    internal header file
  82. try.c        source for test program
  83. timer.c        source for timing program
  84. tests        test list for try and timer
  85.  
  86. This implementation uses nondeterministic automata rather than the
  87. deterministic ones found in some other implementations, which makes it
  88. simpler, smaller, and faster at compiling regular expressions, but slower
  89. at executing them.  In theory, anyway.  This implementation does employ
  90. some special-case optimizations to make the simpler cases (which do make
  91. up the bulk of regular expressions actually used) run quickly.  In general,
  92. if you want blazing speed you're in the wrong place.  Replacing the insides
  93. of egrep with this stuff is probably a mistake; if you want your own egrep
  94. you're going to have to do a lot more work.  But if you want to use regular
  95. expressions a little bit in something else, you're in luck.  Note that many
  96. existing text editors use nondeterministic regular-expression implementations,
  97. so you're in good company.
  98.  
  99. This stuff should be pretty portable, given appropriate option settings.
  100. If your chars have less than 8 bits, you're going to have to change the
  101. internal representation of the automaton, although knowledge of the details
  102. of this is fairly localized.  There are no "reserved" char values except for
  103. NUL, and no special significance is attached to the top bit of chars.
  104. The string(3) functions are used a fair bit, on the grounds that they are
  105. probably faster than coding the operations in line.  Some attempts at code
  106. tuning have been made, but this is invariably a bit machine-specific.
  107. End of README.regexp
  108. echo Makefile.regexp 1>&2
  109. cat > Makefile.regexp <<'End of Makefile.regexp'
  110. # Things you might want to put in ENV and LENV:
  111. # -Dvoid=int        compilers that don't do void
  112. # -DCHARBITS=0377    compilers that don't do unsigned char
  113. # -DSTATIC=extern    compilers that don't like "static foo();" as forward decl
  114. # -DSTRCSPN        library does not have strcspn()
  115. # -Dstrchr=index    library does not have strchr()
  116. # -DERRAVAIL        have utzoo-compatible error() function and friends
  117. ENV= 
  118. LENV=
  119.  
  120. # Things you might want to put in TEST:
  121. # -DDEBUG        debugging hooks
  122. # -I.            regexp.h from current directory, not /usr/include
  123. TEST= -I.
  124.  
  125. # Things you might want to put in PROF:
  126. # -Dstatic='/* */'    make everything global so profiler can see it.
  127. # -p            profiler
  128. PROF=
  129.  
  130. CFLAGS=-O $(ENV) $(TEST) $(PROF)
  131. LINTFLAGS=$(LENV) $(TEST) -ha
  132. #LDFLAGS=-i        uncomment for pdp 11
  133.  
  134. OBJ=regexp.o regsub.o
  135. LSRC=regexp.c regsub.c regerror.c
  136. DTR=README.regexp dMakefile regexp.3 regexp.h regexp.c regsub.c regerror.c \
  137.     regmagic.h try.c timer.c tests
  138.  
  139. try:    try.o $(OBJ)
  140.     cc $(LDFLAGS) try.o $(OBJ) -o try
  141.  
  142. # Making timer will probably require putting stuff in $(PROF) and then
  143. # recompiling everything; the following is just the final stage.
  144. timer:    timer.o $(OBJ)
  145.     cc $(LDFLAGS) $(PROF) timer.o $(OBJ) -o timer
  146.  
  147. timer.o:    timer.c timer.t.h
  148.  
  149. timer.t.h:    tests
  150.     sed 's/    /","/g;s/\\/&&/g;s/.*/{"&"},/' tests >timer.t.h
  151.  
  152. # Regression test.
  153. r:    try tests
  154.     @echo 'No news is good news...'
  155.     try <tests
  156.  
  157. lint:    timer.t.h
  158.     @echo 'Complaints about multiply-declared regerror() are legit.'
  159.     lint $(LINTFLAGS) $(LSRC) try.c
  160.     lint $(LINTFLAGS) $(LSRC) timer.c
  161.  
  162. regexp.o:    regexp.c regexp.h regmagic.h
  163. regsub.o:    regsub.c regexp.h regmagic.h
  164.  
  165. clean:
  166.     rm -f *.o core mon.out timer.t.h dMakefile dtr try timer
  167.  
  168. dtr:    r makedtr $(DTR)
  169.     makedtr $(DTR) >dtr
  170.  
  171. dMakefile:    Makefile
  172.     sed '/^L*ENV=/s/ *-DERRAVAIL//' Makefile >dMakefile
  173. End of Makefile.regexp
  174. echo regexp.3 1>&2
  175. cat > regexp.3 <<'End of regexp.3'
  176. .TH REGEXP 3 local
  177. .DA 30 Nov 1985
  178. .SH NAME
  179. regcomp, regexec, regsub, regerror \- regular expression handler
  180. .SH SYNOPSIS
  181. .ft B
  182. .nf
  183. #include <regexp.h>
  184.  
  185. regexp *regcomp(exp)
  186. char *exp;
  187.  
  188. int regexec(prog, string)
  189. regexp *prog;
  190. char *string;
  191.  
  192. regsub(prog, source, dest)
  193. regexp *prog;
  194. char *source;
  195. char *dest;
  196.  
  197. regerror(msg)
  198. char *msg;
  199. .SH DESCRIPTION
  200. These functions implement
  201. .IR egrep (1)-style
  202. regular expressions and supporting facilities.
  203. .PP
  204. .I Regcomp
  205. compiles a regular expression into a structure of type
  206. .IR regexp ,
  207. and returns a pointer to it.
  208. The space has been allocated using
  209. .IR malloc (3)
  210. and may be released by
  211. .IR free .
  212. .PP
  213. .I Regexec
  214. matches a NUL-terminated \fIstring\fR against the compiled regular expression
  215. in \fIprog\fR.
  216. It returns 1 for success and 0 for failure, and adjusts the contents of
  217. \fIprog\fR's \fIstartp\fR and \fIendp\fR (see below) accordingly.
  218. .PP
  219. The members of a
  220. .I regexp
  221. structure include at least the following (not necessarily in order):
  222. .PP
  223. .RS
  224. char *startp[NSUBEXP];
  225. .br
  226. char *endp[NSUBEXP];
  227. .RE
  228. .PP
  229. where
  230. .I NSUBEXP
  231. is defined (as 10) in the header file.
  232. Once a successful \fIregexec\fR has been done using the \fIregexp\fR,
  233. each \fIstartp\fR-\fIendp\fR pair describes one substring
  234. within the \fIstring\fR,
  235. with the \fIstartp\fR pointing to the first character of the substring and
  236. the \fIendp\fR pointing to the first character following the substring.
  237. The 0th substring is the substring of \fIstring\fR that matched the whole
  238. regular expression.
  239. The others are those substrings that matched parenthesized expressions
  240. within the regular expression, with parenthesized expressions numbered
  241. in left-to-right order of their opening parentheses.
  242. .PP
  243. .I Regsub
  244. copies \fIsource\fR to \fIdest\fR, making substitutions according to the
  245. most recent \fIregexec\fR performed using \fIprog\fR.
  246. Each instance of `&' in \fIsource\fR is replaced by the substring
  247. indicated by \fIstartp\fR[\fI0\fR] and
  248. \fIendp\fR[\fI0\fR].
  249. Each instance of `\e\fIn\fR', where \fIn\fR is a digit, is replaced by
  250. the substring indicated by
  251. \fIstartp\fR[\fIn\fR] and
  252. \fIendp\fR[\fIn\fR].
  253. To get a literal `&' or `\e\fIn\fR' into \fIdest\fR, prefix it with `\e';
  254. to get a literal `\e' preceding `&' or `\e\fIn\fR', prefix it with
  255. another `\e'.
  256. .PP
  257. .I Regerror
  258. is called whenever an error is detected in \fIregcomp\fR, \fIregexec\fR,
  259. or \fIregsub\fR.
  260. The default \fIregerror\fR writes the string \fImsg\fR,
  261. with a suitable indicator of origin,
  262. on the standard
  263. error output
  264. and invokes \fIexit\fR(2).
  265. .I Regerror
  266. can be replaced by the user if other actions are desirable.
  267. .SH "REGULAR EXPRESSION SYNTAX"
  268. A regular expression is zero or more \fIbranches\fR, separated by `|'.
  269. It matches anything that matches one of the branches.
  270. .PP
  271. A branch is zero or more \fIpieces\fR, concatenated.
  272. It matches a match for the first, followed by a match for the second, etc.
  273. .PP
  274. A piece is an \fIatom\fR possibly followed by `*', `+', or `?'.
  275. An atom followed by `*' matches a sequence of 0 or more matches of the atom.
  276. An atom followed by `+' matches a sequence of 1 or more matches of the atom.
  277. An atom followed by `?' matches a match of the atom, or the null string.
  278. .PP
  279. An atom is a regular expression in parentheses (matching a match for the
  280. regular expression), a \fIrange\fR (see below), `.'
  281. (matching any single character), `^' (matching the null string at the
  282. beginning of the input string), `$' (matching the null string at the
  283. end of the input string), a `\e' followed by a single character (matching
  284. that character), or a single character with no other significance
  285. (matching that character).
  286. .PP
  287. A \fIrange\fR is a sequence of characters enclosed in `[]'.
  288. It normally matches any single character from the sequence.
  289. If the sequence begins with `^',
  290. it matches any single character \fInot\fR from the rest of the sequence.
  291. If two characters in the sequence are separated by `\-', this is shorthand
  292. for the full list of ASCII characters between them
  293. (e.g. `[0-9]' matches any decimal digit).
  294. To include a literal `]' in the sequence, make it the first character
  295. (following a possible `^').
  296. To include a literal `\-', make it the first or last character.
  297. .SH AMBIGUITY
  298. If a regular expression could match two different parts of the input string,
  299. it will match the one which begins earliest.
  300. If both begin in the same place    but match different lengths, or match
  301. the same length in different ways, life gets messier, as follows.
  302. .PP
  303. In general, the possibilities in a list of branches are considered in
  304. left-to-right order, the possibilities for `*', `+', and `?' are
  305. considered longest-first, nested constructs are considered from the
  306. outermost in, and concatenated constructs are considered leftmost-first.
  307. The match that will be chosen is the one that uses the earliest
  308. possibility in the first choice that has to be made.
  309. If there is more than one choice, the next will be made in the same manner
  310. (earliest possibility) subject to the decision on the first choice.
  311. And so forth.
  312. .PP
  313. For example, `(ab|a)b*c' could match `abc' in one of two ways.
  314. The first choice is between `ab' and `a'; since `ab' is earlier, and does
  315. lead to a successful overall match, it is chosen.
  316. Since the `b' is already spoken for,
  317. the `b*' must match its last possibility\(emthe empty string\(emsince
  318. it must respect the earlier choice.
  319. .PP
  320. In the particular case where no `|'s are present and there is only one
  321. `*', `+', or `?', the net effect is that the longest possible
  322. match will be chosen.
  323. So `ab*', presented with `xabbbby', will match `abbbb'.
  324. Note that if `ab*' is tried against `xabyabbbz', it
  325. will match `ab' just after `x', due to the begins-earliest rule.
  326. (In effect, the decision on where to start the match is the first choice
  327. to be made, hence subsequent choices must respect it even if this leads them
  328. to less-preferred alternatives.)
  329. .SH SEE ALSO
  330. egrep(1), expr(1)
  331. .SH DIAGNOSTICS
  332. \fIRegcomp\fR returns NULL for a failure
  333. (\fIregerror\fR permitting),
  334. where failures are syntax errors, exceeding implementation limits,
  335. or applying `+' or `*' to a possibly-null operand.
  336. .SH HISTORY
  337. Both code and manual page were
  338. written at U of T.
  339. They are intended to be compatible with the Bell V8 \fIregexp\fR(3),
  340. but are not derived from Bell code.
  341. .SH BUGS
  342. Empty branches and empty regular expressions are not portable to V8.
  343. .PP
  344. The restriction against
  345. applying `*' or `+' to a possibly-null operand is an artifact of the
  346. simplistic implementation.
  347. .PP
  348. Does not support \fIegrep\fR's newline-separated branches;
  349. neither does the V8 \fIregexp\fR(3), though.
  350. .PP
  351. Due to emphasis on
  352. compactness and simplicity,
  353. it's not strikingly fast.
  354. It does give special attention to handling simple cases quickly.
  355. End of regexp.3
  356. echo regexp.c 1>&2
  357. cat > regexp.c <<'End of regexp.c'
  358. /*
  359.  * regcomp and regexec -- regsub and regerror are elsewhere
  360.  *
  361.  *    Copyright (c) 1986 by University of Toronto.
  362.  *    Written by Henry Spencer.  Not derived from licensed software.
  363.  *
  364.  *    Permission is granted to anyone to use this software for any
  365.  *    purpose on any computer system, and to redistribute it freely,
  366.  *    subject to the following restrictions:
  367.  *
  368.  *    1. The author is not responsible for the consequences of use of
  369.  *        this software, no matter how awful, even if they arise
  370.  *        from defects in it.
  371.  *
  372.  *    2. The origin of this software must not be misrepresented, either
  373.  *        by explicit claim or by omission.
  374.  *
  375.  *    3. Altered versions must be plainly marked as such, and must not
  376.  *        be misrepresented as being the original software.
  377.  *
  378.  * Beware that some of this code is subtly aware of the way operator
  379.  * precedence is structured in regular expressions.  Serious changes in
  380.  * regular-expression syntax might require a total rethink.
  381.  */
  382. #include <stdio.h>
  383. #include <regexp.h>
  384. #include "regmagic.h"
  385.  
  386. /*
  387.  * The "internal use only" fields in regexp.h are present to pass info from
  388.  * compile to execute that permits the execute phase to run lots faster on
  389.  * simple cases.  They are:
  390.  *
  391.  * regstart    char that must begin a match; '\0' if none obvious
  392.  * reganch    is the match anchored (at beginning-of-line only)?
  393.  * regmust    string (pointer into program) that match must include, or NULL
  394.  * regmlen    length of regmust string
  395.  *
  396.  * Regstart and reganch permit very fast decisions on suitable starting points
  397.  * for a match, cutting down the work a lot.  Regmust permits fast rejection
  398.  * of lines that cannot possibly match.  The regmust tests are costly enough
  399.  * that regcomp() supplies a regmust only if the r.e. contains something
  400.  * potentially expensive (at present, the only such thing detected is * or +
  401.  * at the start of the r.e., which can involve a lot of backup).  Regmlen is
  402.  * supplied because the test in regexec() needs it and regcomp() is computing
  403.  * it anyway.
  404.  */
  405.  
  406. /*
  407.  * Structure for regexp "program".  This is essentially a linear encoding
  408.  * of a nondeterministic finite-state machine (aka syntax charts or
  409.  * "railroad normal form" in parsing technology).  Each node is an opcode
  410.  * plus a "next" pointer, possibly plus an operand.  "Next" pointers of
  411.  * all nodes except BRANCH implement concatenation; a "next" pointer with
  412.  * a BRANCH on both ends of it is connecting two alternatives.  (Here we
  413.  * have one of the subtle syntax dependencies:  an individual BRANCH (as
  414.  * opposed to a collection of them) is never concatenated with anything
  415.  * because of operator precedence.)  The operand of some types of node is
  416.  * a literal string; for others, it is a node leading into a sub-FSM.  In
  417.  * particular, the operand of a BRANCH node is the first node of the branch.
  418.  * (NB this is *not* a tree structure:  the tail of the branch connects
  419.  * to the thing following the set of BRANCHes.)  The opcodes are:
  420.  */
  421.  
  422. /* definition    number    opnd?    meaning */
  423. #define    END    0    /* no    End of program. */
  424. #define    BOL    1    /* no    Match "" at beginning of line. */
  425. #define    EOL    2    /* no    Match "" at end of line. */
  426. #define    ANY    3    /* no    Match any one character. */
  427. #define    ANYOF    4    /* str    Match any character in this string. */
  428. #define    ANYBUT    5    /* str    Match any character not in this string. */
  429. #define    BRANCH    6    /* node    Match this alternative, or the next... */
  430. #define    BACK    7    /* no    Match "", "next" ptr points backward. */
  431. #define    EXACTLY    8    /* str    Match this string. */
  432. #define    NOTHING    9    /* no    Match empty string. */
  433. #define    STAR    10    /* node    Match this (simple) thing 0 or more times. */
  434. #define    PLUS    11    /* node    Match this (simple) thing 1 or more times. */
  435. #define    OPEN    20    /* no    Mark this point in input as start of #n. */
  436.             /*    OPEN+1 is number 1, etc. */
  437. #define    CLOSE    30    /* no    Analogous to OPEN. */
  438.  
  439. /*
  440.  * Opcode notes:
  441.  *
  442.  * BRANCH    The set of branches constituting a single choice are hooked
  443.  *        together with their "next" pointers, since precedence prevents
  444.  *        anything being concatenated to any individual branch.  The
  445.  *        "next" pointer of the last BRANCH in a choice points to the
  446.  *        thing following the whole choice.  This is also where the
  447.  *        final "next" pointer of each individual branch points; each
  448.  *        branch starts with the operand node of a BRANCH node.
  449.  *
  450.  * BACK        Normal "next" pointers all implicitly point forward; BACK
  451.  *        exists to make loop structures possible.
  452.  *
  453.  * STAR,PLUS    '?', and complex '*' and '+', are implemented as circular
  454.  *        BRANCH structures using BACK.  Simple cases (one character
  455.  *        per match) are implemented with STAR and PLUS for speed
  456.  *        and to minimize recursive plunges.
  457.  *
  458.  * OPEN,CLOSE    ...are numbered at compile time.
  459.  */
  460.  
  461. /*
  462.  * A node is one char of opcode followed by two chars of "next" pointer.
  463.  * "Next" pointers are stored as two 8-bit pieces, high order first.  The
  464.  * value is a positive offset from the opcode of the node containing it.
  465.  * An operand, if any, simply follows the node.  (Note that much of the
  466.  * code generation knows about this implicit relationship.)
  467.  *
  468.  * Using two bytes for the "next" pointer is vast overkill for most things,
  469.  * but allows patterns to get big without disasters.
  470.  */
  471. #define    OP(p)    (*(p))
  472. #define    NEXT(p)    (((*((p)+1)&0377)<<8) + *((p)+2)&0377)
  473. #define    NEXT(p)    (((*((p)+1)&0377)<<8) + (*((p)+2)&0377))
  474. #define    OPERAND(p)    ((p) + 3)
  475.  
  476. /*
  477.  * See regmagic.h for one further detail of program structure.
  478.  */
  479.  
  480.  
  481. /*
  482.  * Utility definitions.
  483.  */
  484. #ifndef CHARBITS
  485. #define    UCHARAT(p)    ((int)*(unsigned char *)(p))
  486. #else
  487. #define    UCHARAT(p)    ((int)*(p)&CHARBITS)
  488. #endif
  489.  
  490. #define    FAIL(m)    { regerror(m); return(NULL); }
  491. #define    ISMULT(c)    ((c) == '*' || (c) == '+' || (c) == '?')
  492. #define    META    "^$.[()|?+*\\"
  493.  
  494. /*
  495.  * Flags to be passed up and down.
  496.  */
  497. #define    HASWIDTH    01    /* Known never to match null string. */
  498. #define    SIMPLE        02    /* Simple enough to be STAR/PLUS operand. */
  499. #define    SPSTART        04    /* Starts with * or +. */
  500. #define    WORST        0    /* Worst case. */
  501.  
  502. /*
  503.  * Global work variables for regcomp().
  504.  */
  505. static char *regparse;        /* Input-scan pointer. */
  506. static int regnpar;        /* () count. */
  507. static char regdummy;
  508. static char *regcode;        /* Code-emit pointer; ®dummy = don't. */
  509. static long regsize;        /* Code size. */
  510.  
  511. /*
  512.  * Forward declarations for regcomp()'s friends.
  513.  */
  514. #ifndef STATIC
  515. #define    STATIC    static
  516. #endif
  517. STATIC char *reg();
  518. STATIC char *regbranch();
  519. STATIC char *regpiece();
  520. STATIC char *regatom();
  521. STATIC char *regnode();
  522. STATIC char *regnext();
  523. STATIC void regc();
  524. STATIC void reginsert();
  525. STATIC void regtail();
  526. STATIC void regoptail();
  527. #ifdef STRCSPN
  528. STATIC int strcspn();
  529. #endif
  530.  
  531. /*
  532.  - regcomp - compile a regular expression into internal code
  533.  *
  534.  * We can't allocate space until we know how big the compiled form will be,
  535.  * but we can't compile it (and thus know how big it is) until we've got a
  536.  * place to put the code.  So we cheat:  we compile it twice, once with code
  537.  * generation turned off and size counting turned on, and once "for real".
  538.  * This also means that we don't allocate space until we are sure that the
  539.  * thing really will compile successfully, and we never have to move the
  540.  * code and thus invalidate pointers into it.  (Note that it has to be in
  541.  * one piece because free() must be able to free it all.)
  542.  *
  543.  * Beware that the optimization-preparation code in here knows about some
  544.  * of the structure of the compiled regexp.
  545.  */
  546. regexp *
  547. regcomp(exp)
  548. char *exp;
  549. {
  550.     register regexp *r;
  551.     register char *scan;
  552.     register char *longest;
  553.     register int len;
  554.     int flags;
  555.     extern char *malloc();
  556.  
  557.     if (exp == NULL)
  558.         FAIL("NULL argument");
  559.  
  560.     /* First pass: determine size, legality. */
  561.     regparse = exp;
  562.     regnpar = 1;
  563.     regsize = 0L;
  564.     regcode = ®dummy;
  565.     regc(MAGIC);
  566.     if (reg(0, &flags) == NULL)
  567.         return(NULL);
  568.  
  569.     /* Small enough for pointer-storage convention? */
  570.     if (regsize >= 32767L)        /* Probably could be 65535L. */
  571.         FAIL("regexp too big");
  572.  
  573.     /* Allocate space. */
  574.     r = (regexp *)malloc(sizeof(regexp) + (unsigned)regsize);
  575.     if (r == NULL)
  576.         FAIL("out of space");
  577.  
  578.     /* Second pass: emit code. */
  579.     regparse = exp;
  580.     regnpar = 1;
  581.     regcode = r->program;
  582.     regc(MAGIC);
  583.     if (reg(0, &flags) == NULL)
  584.         return(NULL);
  585.  
  586.     /* Dig out information for optimizations. */
  587.     r->regstart = '\0';    /* Worst-case defaults. */
  588.     r->reganch = 0;
  589.     r->regmust = NULL;
  590.     r->regmlen = 0;
  591.     scan = r->program+1;            /* First BRANCH. */
  592.     if (OP(regnext(scan)) == END) {        /* Only one top-level choice. */
  593.         scan = OPERAND(scan);
  594.  
  595.         /* Starting-point info. */
  596.         if (OP(scan) == EXACTLY)
  597.             r->regstart = *OPERAND(scan);
  598.         else if (OP(scan) == BOL)
  599.             r->reganch++;
  600.  
  601.         /*
  602.          * If there's something expensive in the r.e., find the
  603.          * longest literal string that must appear and make it the
  604.          * regmust.  Resolve ties in favor of later strings, since
  605.          * the regstart check works with the beginning of the r.e.
  606.          * and avoiding duplication strengthens checking.  Not a
  607.          * strong reason, but sufficient in the absence of others.
  608.          */
  609.         if (flags&SPSTART) {
  610.             longest = NULL;
  611.             len = 0;
  612.             for (; scan != NULL; scan = regnext(scan))
  613.                 if (OP(scan) == EXACTLY && strlen(OPERAND(scan)) >= len) {
  614.                     longest = OPERAND(scan);
  615.                     len = strlen(OPERAND(scan));
  616.                 }
  617.             r->regmust = longest;
  618.             r->regmlen = len;
  619.         }
  620.     }
  621.  
  622.     return(r);
  623. }
  624.  
  625. /*
  626.  - reg - regular expression, i.e. main body or parenthesized thing
  627.  *
  628.  * Caller must absorb opening parenthesis.
  629.  *
  630.  * Combining parenthesis handling with the base level of regular expression
  631.  * is a trifle forced, but the need to tie the tails of the branches to what
  632.  * follows makes it hard to avoid.
  633.  */
  634. static char *
  635. reg(paren, flagp)
  636. int paren;            /* Parenthesized? */
  637. int *flagp;
  638. {
  639.     register char *ret;
  640.     register char *br;
  641.     register char *ender;
  642.     register int parno;
  643.     int flags;
  644.  
  645.     *flagp = HASWIDTH;    /* Tentatively. */
  646.  
  647.     /* Make an OPEN node, if parenthesized. */
  648.     if (paren) {
  649.         if (regnpar >= NSUBEXP)
  650.             FAIL("too many ()");
  651.         parno = regnpar;
  652.         regnpar++;
  653.         ret = regnode(OPEN+parno);
  654.     } else
  655.         ret = NULL;
  656.  
  657.     /* Pick up the branches, linking them together. */
  658.     br = regbranch(&flags);
  659.     if (br == NULL)
  660.         return(NULL);
  661.     if (ret != NULL)
  662.         regtail(ret, br);    /* OPEN -> first. */
  663.     else
  664.         ret = br;
  665.     if (!(flags&HASWIDTH))
  666.         *flagp &= ~HASWIDTH;
  667.     *flagp |= flags&SPSTART;
  668.     while (*regparse == '|') {
  669.         regparse++;
  670.         br = regbranch(&flags);
  671.         if (br == NULL)
  672.             return(NULL);
  673.         regtail(ret, br);    /* BRANCH -> BRANCH. */
  674.         if (!(flags&HASWIDTH))
  675.             *flagp &= ~HASWIDTH;
  676.         *flagp |= flags&SPSTART;
  677.     }
  678.  
  679.     /* Make a closing node, and hook it on the end. */
  680.     ender = regnode((paren) ? CLOSE+parno : END);    
  681.     regtail(ret, ender);
  682.  
  683.     /* Hook the tails of the branches to the closing node. */
  684.     for (br = ret; br != NULL; br = regnext(br))
  685.         regoptail(br, ender);
  686.  
  687.     /* Check for proper termination. */
  688.     if (paren && *regparse++ != ')') {
  689.         FAIL("unmatched ()");
  690.     } else if (!paren && *regparse != '\0') {
  691.         if (*regparse == ')') {
  692.             FAIL("unmatched ()");
  693.         } else
  694.             FAIL("junk on end");    /* "Can't happen". */
  695.         /* NOTREACHED */
  696.     }
  697.  
  698.     return(ret);
  699. }
  700.  
  701. /*
  702.  - regbranch - one alternative of an | operator
  703.  *
  704.  * Implements the concatenation operator.
  705.  */
  706. static char *
  707. regbranch(flagp)
  708. int *flagp;
  709. {
  710.     register char *ret;
  711.     register char *chain;
  712.     register char *latest;
  713.     int flags;
  714.  
  715.     *flagp = WORST;        /* Tentatively. */
  716.  
  717.     ret = regnode(BRANCH);
  718.     chain = NULL;
  719.     while (*regparse != '\0' && *regparse != '|' && *regparse != ')') {
  720.         latest = regpiece(&flags);
  721.         if (latest == NULL)
  722.             return(NULL);
  723.         *flagp |= flags&HASWIDTH;
  724.         if (chain == NULL)    /* First piece. */
  725.             *flagp |= flags&SPSTART;
  726.         else
  727.             regtail(chain, latest);
  728.         chain = latest;
  729.     }
  730.     if (chain == NULL)    /* Loop ran zero times. */
  731.         (void) regnode(NOTHING);
  732.  
  733.     return(ret);
  734. }
  735.  
  736. /*
  737.  - regpiece - something followed by possible [*+?]
  738.  *
  739.  * Note that the branching code sequences used for ? and the general cases
  740.  * of * and + are somewhat optimized:  they use the same NOTHING node as
  741.  * both the endmarker for their branch list and the body of the last branch.
  742.  * It might seem that this node could be dispensed with entirely, but the
  743.  * endmarker role is not redundant.
  744.  */
  745. static char *
  746. regpiece(flagp)
  747. int *flagp;
  748. {
  749.     register char *ret;
  750.     register char op;
  751.     register char *next;
  752.     int flags;
  753.  
  754.     ret = regatom(&flags);
  755.     if (ret == NULL)
  756.         return(NULL);
  757.  
  758.     op = *regparse;
  759.     if (!ISMULT(op)) {
  760.         *flagp = flags;
  761.         return(ret);
  762.     }
  763.  
  764.     if (!(flags&HASWIDTH) && op != '?')
  765.         FAIL("*+ operand could be empty");
  766.     *flagp = (op != '+') ? (WORST|SPSTART) : (WORST|HASWIDTH);
  767.  
  768.     if (op == '*' && (flags&SIMPLE))
  769.         reginsert(STAR, ret);
  770.     else if (op == '*') {
  771.         /* Emit x* as (x&|), where & means "self". */
  772.         reginsert(BRANCH, ret);            /* Either x */
  773.         regoptail(ret, regnode(BACK));        /* and loop */
  774.         regoptail(ret, ret);            /* back */
  775.         regtail(ret, regnode(BRANCH));        /* or */
  776.         regtail(ret, regnode(NOTHING));        /* null. */
  777.     } else if (op == '+' && (flags&SIMPLE))
  778.         reginsert(PLUS, ret);
  779.     else if (op == '+') {
  780.         /* Emit x+ as x(&|), where & means "self". */
  781.         next = regnode(BRANCH);            /* Either */
  782.         regtail(ret, next);
  783.         regtail(regnode(BACK), ret);        /* loop back */
  784.         regtail(next, regnode(BRANCH));        /* or */
  785.         regtail(ret, regnode(NOTHING));        /* null. */
  786.     } else if (op == '?') {
  787.         /* Emit x? as (x|) */
  788.         reginsert(BRANCH, ret);            /* Either x */
  789.         regtail(ret, regnode(BRANCH));        /* or */
  790.         next = regnode(NOTHING);        /* null. */
  791.         regtail(ret, next);
  792.         regoptail(ret, next);
  793.     }
  794.     regparse++;
  795.     if (ISMULT(*regparse))
  796.         FAIL("nested *?+");
  797.  
  798.     return(ret);
  799. }
  800.  
  801. /*
  802.  - regatom - the lowest level
  803.  *
  804.  * Optimization:  gobbles an entire sequence of ordinary characters so that
  805.  * it can turn them into a single node, which is smaller to store and
  806.  * faster to run.  Backslashed characters are exceptions, each becoming a
  807.  * separate node; the code is simpler that way and it's not worth fixing.
  808.  */
  809. static char *
  810. regatom(flagp)
  811. int *flagp;
  812. {
  813.     register char *ret;
  814.     int flags;
  815.  
  816.     *flagp = WORST;        /* Tentatively. */
  817.  
  818.     switch (*regparse++) {
  819.     case '^':
  820.         ret = regnode(BOL);
  821.         break;
  822.     case '$':
  823.         ret = regnode(EOL);
  824.         break;
  825.     case '.':
  826.         ret = regnode(ANY);
  827.         *flagp |= HASWIDTH|SIMPLE;
  828.         break;
  829.     case '[': {
  830.             register int class;
  831.             register int classend;
  832.  
  833.             if (*regparse == '^') {    /* Complement of range. */
  834.                 ret = regnode(ANYBUT);
  835.                 regparse++;
  836.             } else
  837.                 ret = regnode(ANYOF);
  838.             if (*regparse == ']' || *regparse == '-')
  839.                 regc(*regparse++);
  840.             while (*regparse != '\0' && *regparse != ']') {
  841.                 if (*regparse == '-') {
  842.                     regparse++;
  843.                     if (*regparse == ']' || *regparse == '\0')
  844.                         regc('-');
  845.                     else {
  846.                         class = UCHARAT(regparse-2)+1;
  847.                         classend = UCHARAT(regparse);
  848.                         if (class > classend+1)
  849.                             FAIL("invalid [] range");
  850.                         for (; class <= classend; class++)
  851.                             regc(class);
  852.                         regparse++;
  853.                     }
  854.                 } else
  855.                     regc(*regparse++);
  856.             }
  857.             regc('\0');
  858.             if (*regparse != ']')
  859.                 FAIL("unmatched []");
  860.             regparse++;
  861.             *flagp |= HASWIDTH|SIMPLE;
  862.         }
  863.         break;
  864.     case '(':
  865.         ret = reg(1, &flags);
  866.         if (ret == NULL)
  867.             return(NULL);
  868.         *flagp |= flags&(HASWIDTH|SPSTART);
  869.         break;
  870.     case '\0':
  871.     case '|':
  872.     case ')':
  873.         FAIL("internal urp");    /* Supposed to be caught earlier. */
  874.         break;
  875.     case '?':
  876.     case '+':
  877.     case '*':
  878.         FAIL("?+* follows nothing");
  879.         break;
  880.     case '\\':
  881.         if (*regparse == '\0')
  882.             FAIL("trailing \\");
  883.         ret = regnode(EXACTLY);
  884.         regc(*regparse++);
  885.         regc('\0');
  886.         *flagp |= HASWIDTH|SIMPLE;
  887.         break;
  888.     default: {
  889.             register int len;
  890.             register char ender;
  891.  
  892.             regparse--;
  893.             len = strcspn(regparse, META);
  894.             if (len <= 0)
  895.                 FAIL("internal disaster");
  896.             ender = *(regparse+len);
  897.             if (len > 1 && ISMULT(ender))
  898.                 len--;        /* Back off clear of ?+* operand. */
  899.             *flagp |= HASWIDTH;
  900.             if (len == 1)
  901.                 *flagp |= SIMPLE;
  902.             ret = regnode(EXACTLY);
  903.             while (len > 0) {
  904.                 regc(*regparse++);
  905.                 len--;
  906.             }
  907.             regc('\0');
  908.         }
  909.         break;
  910.     }
  911.  
  912.     return(ret);
  913. }
  914.  
  915. /*
  916.  - regnode - emit a node
  917.  */
  918. static char *            /* Location. */
  919. regnode(op)
  920. char op;
  921. {
  922.     register char *ret;
  923.     register char *ptr;
  924.  
  925.     ret = regcode;
  926.     if (ret == ®dummy) {
  927.         regsize += 3;
  928.         return(ret);
  929.     }
  930.  
  931.     ptr = ret;
  932.     *ptr++ = op;
  933.     *ptr++ = '\0';        /* Null "next" pointer. */
  934.     *ptr++ = '\0';
  935.     regcode = ptr;
  936.  
  937.     return(ret);
  938. }
  939.  
  940. /*
  941.  - regc - emit (if appropriate) a byte of code
  942.  */
  943. static void
  944. regc(b)
  945. char b;
  946. {
  947.     if (regcode != ®dummy)
  948.         *regcode++ = b;
  949.     else
  950.         regsize++;
  951. }
  952.  
  953. /*
  954.  - reginsert - insert an operator in front of already-emitted operand
  955.  *
  956.  * Means relocating the operand.
  957.  */
  958. static void
  959. reginsert(op, opnd)
  960. char op;
  961. char *opnd;
  962. {
  963.     register char *src;
  964.     register char *dst;
  965.     register char *place;
  966.  
  967.     if (regcode == ®dummy) {
  968.         regsize += 3;
  969.         return;
  970.     }
  971.  
  972.     src = regcode;
  973.     regcode += 3;
  974.     dst = regcode;
  975.     while (src > opnd)
  976.         *--dst = *--src;
  977.  
  978.     place = opnd;        /* Op node, where operand used to be. */
  979.     *place++ = op;
  980.     *place++ = '\0';
  981.     *place++ = '\0';
  982. }
  983.  
  984. /*
  985.  - regtail - set the next-pointer at the end of a node chain
  986.  */
  987. static void
  988. regtail(p, val)
  989. char *p;
  990. char *val;
  991. {
  992.     register char *scan;
  993.     register char *temp;
  994.     register int offset;
  995.  
  996.     if (p == ®dummy)
  997.         return;
  998.  
  999.     /* Find last node. */
  1000.     scan = p;
  1001.     for (;;) {
  1002.         temp = regnext(scan);
  1003.         if (temp == NULL)
  1004.             break;
  1005.         scan = temp;
  1006.     }
  1007.  
  1008.     if (OP(scan) == BACK)
  1009.         offset = scan - val;
  1010.     else
  1011.         offset = val - scan;
  1012.     *(scan+1) = (offset>>8)&0377;
  1013.     *(scan+2) = offset&0377;
  1014. }
  1015.  
  1016. /*
  1017.  - regoptail - regtail on operand of first argument; nop if operandless
  1018.  */
  1019. static void
  1020. regoptail(p, val)
  1021. char *p;
  1022. char *val;
  1023. {
  1024.     /* "Operandless" and "op != BRANCH" are synonymous in practice. */
  1025.     if (p == NULL || p == ®dummy || OP(p) != BRANCH)
  1026.         return;
  1027.     regtail(OPERAND(p), val);
  1028. }
  1029.  
  1030. /*
  1031.  * regexec and friends
  1032.  */
  1033.  
  1034. /*
  1035.  * Global work variables for regexec().
  1036.  */
  1037. static char *reginput;        /* String-input pointer. */
  1038. static char *regbol;        /* Beginning of input, for ^ check. */
  1039. static char **regstartp;    /* Pointer to startp array. */
  1040. static char **regendp;        /* Ditto for endp. */
  1041.  
  1042. /*
  1043.  * Forwards.
  1044.  */
  1045. STATIC int regtry();
  1046. STATIC int regmatch();
  1047. STATIC int regrepeat();
  1048.  
  1049. #ifdef DEBUG
  1050. int regnarrate = 0;
  1051. void regdump();
  1052. STATIC char *regprop();
  1053. #endif
  1054.  
  1055. /*
  1056.  - regexec - match a regexp against a string
  1057.  */
  1058. int
  1059. regexec(prog, string)
  1060. register regexp *prog;
  1061. register char *string;
  1062. {
  1063.     register char *s;
  1064.     extern char *strchr();
  1065.  
  1066.     /* Be paranoid... */
  1067.     if (prog == NULL || string == NULL) {
  1068.         regerror("NULL parameter");
  1069.         return(0);
  1070.     }
  1071.  
  1072.     /* Check validity of program. */
  1073.     if (UCHARAT(prog->program) != MAGIC) {
  1074.         regerror("corrupted program");
  1075.         return(0);
  1076.     }
  1077.  
  1078.     /* If there is a "must appear" string, look for it. */
  1079.     if (prog->regmust != NULL) {
  1080.         s = string;
  1081.         while ((s = strchr(s, prog->regmust[0])) != NULL) {
  1082.             if (strncmp(s, prog->regmust, prog->regmlen) == 0)
  1083.                 break;    /* Found it. */
  1084.             s++;
  1085.         }
  1086.         if (s == NULL)    /* Not present. */
  1087.             return(0);
  1088.     }
  1089.  
  1090.     /* Mark beginning of line for ^ . */
  1091.     regbol = string;
  1092.  
  1093.     /* Simplest case:  anchored match need be tried only once. */
  1094.     if (prog->reganch)
  1095.         return(regtry(prog, string));
  1096.  
  1097.     /* Messy cases:  unanchored match. */
  1098.     s = string;
  1099.     if (prog->regstart != '\0')
  1100.         /* We know what char it must start with. */
  1101.         while ((s = strchr(s, prog->regstart)) != NULL) {
  1102.             if (regtry(prog, s))
  1103.                 return(1);
  1104.             s++;
  1105.         }
  1106.     else
  1107.         /* We don't -- general case. */
  1108.         do {
  1109.             if (regtry(prog, s))
  1110.                 return(1);
  1111.         } while (*s++ != '\0');
  1112.  
  1113.     /* Failure. */
  1114.     return(0);
  1115. }
  1116.  
  1117. /*
  1118.  - regtry - try match at specific point
  1119.  */
  1120. static int            /* 0 failure, 1 success */
  1121. regtry(prog, string)
  1122. regexp *prog;
  1123. char *string;
  1124. {
  1125.     register int i;
  1126.     register char **sp;
  1127.     register char **ep;
  1128.  
  1129.     reginput = string;
  1130.     regstartp = prog->startp;
  1131.     regendp = prog->endp;
  1132.  
  1133.     sp = prog->startp;
  1134.     ep = prog->endp;
  1135.     for (i = NSUBEXP; i > 0; i--) {
  1136.         *sp++ = NULL;
  1137.         *ep++ = NULL;
  1138.     }
  1139.     if (regmatch(prog->program + 1)) {
  1140.         prog->startp[0] = string;
  1141.         prog->endp[0] = reginput;
  1142.         return(1);
  1143.     } else
  1144.         return(0);
  1145. }
  1146.  
  1147. /*
  1148.  - regmatch - main matching routine
  1149.  *
  1150.  * Conceptually the strategy is simple:  check to see whether the current
  1151.  * node matches, call self recursively to see whether the rest matches,
  1152.  * and then act accordingly.  In practice we make some effort to avoid
  1153.  * recursion, in particular by going through "ordinary" nodes (that don't
  1154.  * need to know whether the rest of the match failed) by a loop instead of
  1155.  * by recursion.
  1156.  */
  1157. static int            /* 0 failure, 1 success */
  1158. regmatch(prog)
  1159. char *prog;
  1160. {
  1161.     register char *scan;    /* Current node. */
  1162.     char *next;        /* Next node. */
  1163.     extern char *strchr();
  1164.  
  1165.     scan = prog;
  1166. #ifdef DEBUG
  1167.     if (scan != NULL && regnarrate)
  1168.         fprintf(stderr, "%s(\n", regprop(scan));
  1169. #endif
  1170.     while (scan != NULL) {
  1171. #ifdef DEBUG
  1172.         if (regnarrate)
  1173.             fprintf(stderr, "%s...\n", regprop(scan));
  1174. #endif
  1175.         next = regnext(scan);
  1176.  
  1177.         switch (OP(scan)) {
  1178.         case BOL:
  1179.             if (reginput != regbol)
  1180.                 return(0);
  1181.             break;
  1182.         case EOL:
  1183.             if (*reginput != '\0')
  1184.                 return(0);
  1185.             break;
  1186.         case ANY:
  1187.             if (*reginput == '\0')
  1188.                 return(0);
  1189.             reginput++;
  1190.             break;
  1191.         case EXACTLY: {
  1192.                 register int len;
  1193.                 register char *opnd;
  1194.  
  1195.                 opnd = OPERAND(scan);
  1196.                 /* Inline the first character, for speed. */
  1197.                 if (*opnd != *reginput)
  1198.                     return(0);
  1199.                 len = strlen(opnd);
  1200.                 if (len > 1 && strncmp(opnd, reginput, len) != 0)
  1201.                     return(0);
  1202.                 reginput += len;
  1203.             }
  1204.             break;
  1205.         case ANYOF:
  1206.              if (*reginput == '\0' || strchr(OPERAND(scan), *reginput) == NULL)
  1207.                 return(0);
  1208.             reginput++;
  1209.             break;
  1210.         case ANYBUT:
  1211.              if (*reginput == '\0' || strchr(OPERAND(scan), *reginput) != NULL)
  1212.                 return(0);
  1213.             reginput++;
  1214.             break;
  1215.         case NOTHING:
  1216.             break;
  1217.         case BACK:
  1218.             break;
  1219.         case OPEN+1:
  1220.         case OPEN+2:
  1221.         case OPEN+3:
  1222.         case OPEN+4:
  1223.         case OPEN+5:
  1224.         case OPEN+6:
  1225.         case OPEN+7:
  1226.         case OPEN+8:
  1227.         case OPEN+9: {
  1228.                 register int no;
  1229.                 register char *save;
  1230.  
  1231.                 no = OP(scan) - OPEN;
  1232.                 save = reginput;
  1233.  
  1234.                 if (regmatch(next)) {
  1235.                     /*
  1236.                      * Don't set startp if some later
  1237.                      * invocation of the same parentheses
  1238.                      * already has.
  1239.                      */
  1240.                     if (regstartp[no] == NULL)
  1241.                         regstartp[no] = save;
  1242.                     return(1);
  1243.                 } else
  1244.                     return(0);
  1245.             }
  1246.             break;
  1247.         case CLOSE+1:
  1248.         case CLOSE+2:
  1249.         case CLOSE+3:
  1250.         case CLOSE+4:
  1251.         case CLOSE+5:
  1252.         case CLOSE+6:
  1253.         case CLOSE+7:
  1254.         case CLOSE+8:
  1255.         case CLOSE+9: {
  1256.                 register int no;
  1257.                 register char *save;
  1258.  
  1259.                 no = OP(scan) - CLOSE;
  1260.                 save = reginput;
  1261.  
  1262.                 if (regmatch(next)) {
  1263.                     /*
  1264.                      * Don't set endp if some later
  1265.                      * invocation of the same parentheses
  1266.                      * already has.
  1267.                      */
  1268.                     if (regendp[no] == NULL)
  1269.                         regendp[no] = save;
  1270.                     return(1);
  1271.                 } else
  1272.                     return(0);
  1273.             }
  1274.             break;
  1275.         case BRANCH: {
  1276.                 register char *save;
  1277.  
  1278.                 if (OP(next) != BRANCH)        /* No choice. */
  1279.                     next = OPERAND(scan);    /* Avoid recursion. */
  1280.                 else {
  1281.                     do {
  1282.                         save = reginput;
  1283.                         if (regmatch(OPERAND(scan)))
  1284.                             return(1);
  1285.                         reginput = save;
  1286.                         scan = regnext(scan);
  1287.                     } while (scan != NULL && OP(scan) == BRANCH);
  1288.                     return(0);
  1289.                     /* NOTREACHED */
  1290.                 }
  1291.             }
  1292.             break;
  1293.         case STAR:
  1294.         case PLUS: {
  1295.                 register char nextch;
  1296.                 register int no;
  1297.                 register char *save;
  1298.                 register int min;
  1299.  
  1300.                 /*
  1301.                  * Lookahead to avoid useless match attempts
  1302.                  * when we know what character comes next.
  1303.                  */
  1304.                 nextch = '\0';
  1305.                 if (OP(next) == EXACTLY)
  1306.                     nextch = *OPERAND(next);
  1307.                 min = (OP(scan) == STAR) ? 0 : 1;
  1308.                 save = reginput;
  1309.                 no = regrepeat(OPERAND(scan));
  1310.                 while (no >= min) {
  1311.                     /* If it could work, try it. */
  1312.                     if (nextch == '\0' || *reginput == nextch)
  1313.                         if (regmatch(next))
  1314.                             return(1);
  1315.                     /* Couldn't or didn't -- back up. */
  1316.                     no--;
  1317.                     reginput = save + no;
  1318.                 }
  1319.                 return(0);
  1320.             }
  1321.             break;
  1322.         case END:
  1323.             return(1);    /* Success! */
  1324.             break;
  1325.         default:
  1326.             regerror("memory corruption");
  1327.             return(0);
  1328.             break;
  1329.         }
  1330.  
  1331.         scan = next;
  1332.     }
  1333.  
  1334.     /*
  1335.      * We get here only if there's trouble -- normally "case END" is
  1336.      * the terminating point.
  1337.      */
  1338.     regerror("corrupted pointers");
  1339.     return(0);
  1340. }
  1341.  
  1342. /*
  1343.  - regrepeat - repeatedly match something simple, report how many
  1344.  */
  1345. static int
  1346. regrepeat(p)
  1347. char *p;
  1348. {
  1349.     register int count = 0;
  1350.     register char *scan;
  1351.     register char *opnd;
  1352.  
  1353.     scan = reginput;
  1354.     opnd = OPERAND(p);
  1355.     switch (OP(p)) {
  1356.     case ANY:
  1357.         count = strlen(scan);
  1358.         scan += count;
  1359.         break;
  1360.     case EXACTLY:
  1361.         while (*opnd == *scan) {
  1362.             count++;
  1363.             scan++;
  1364.         }
  1365.         break;
  1366.     case ANYOF:
  1367.         while (*scan != '\0' && strchr(opnd, *scan) != NULL) {
  1368.             count++;
  1369.             scan++;
  1370.         }
  1371.         break;
  1372.     case ANYBUT:
  1373.         while (*scan != '\0' && strchr(opnd, *scan) == NULL) {
  1374.             count++;
  1375.             scan++;
  1376.         }
  1377.         break;
  1378.     default:        /* Oh dear.  Called inappropriately. */
  1379.         regerror("internal foulup");
  1380.         count = 0;    /* Best compromise. */
  1381.         break;
  1382.     }
  1383.     reginput = scan;
  1384.  
  1385.     return(count);
  1386. }
  1387.  
  1388. /*
  1389.  - regnext - dig the "next" pointer out of a node
  1390.  */
  1391. static char *
  1392. regnext(p)
  1393. register char *p;
  1394. {
  1395.     register int offset;
  1396.  
  1397.     if (p == ®dummy)
  1398.         return(NULL);
  1399.  
  1400.     offset = NEXT(p);
  1401.     if (offset == 0)
  1402.         return(NULL);
  1403.  
  1404.     if (OP(p) == BACK)
  1405.         return(p-offset);
  1406.     else
  1407.         return(p+offset);
  1408. }
  1409.  
  1410. #ifdef DEBUG
  1411.  
  1412. STATIC char *regprop();
  1413.  
  1414. /*
  1415.  - regdump - dump a regexp onto stdout in vaguely comprehensible form
  1416.  */
  1417. void
  1418. regdump(r)
  1419. regexp *r;
  1420. {
  1421.     register char *s;
  1422.     register char op = EXACTLY;    /* Arbitrary non-END op. */
  1423.     register char *next;
  1424.     extern char *strchr();
  1425.  
  1426.  
  1427.     s = r->program + 1;
  1428.     while (op != END) {    /* While that wasn't END last time... */
  1429.         op = OP(s);
  1430.         printf("%2d%s", s-r->program, regprop(s));    /* Where, what. */
  1431.         next = regnext(s);
  1432.         if (next == NULL)        /* Next ptr. */
  1433.             printf("(0)");
  1434.         else 
  1435.             printf("(%d)", (s-r->program)+(next-s));
  1436.         s += 3;
  1437.         if (op == ANYOF || op == ANYBUT || op == EXACTLY) {
  1438.             /* Literal string, where present. */
  1439.             while (*s != '\0') {
  1440.                 putchar(*s);
  1441.                 s++;
  1442.             }
  1443.             s++;
  1444.         }
  1445.         putchar('\n');
  1446.     }
  1447.  
  1448.     /* Header fields of interest. */
  1449.     if (r->regstart != '\0')
  1450.         printf("start `%c' ", r->regstart);
  1451.     if (r->reganch)
  1452.         printf("anchored ");
  1453.     if (r->regmust != NULL)
  1454.         printf("must have \"%s\"", r->regmust);
  1455.     printf("\n");
  1456. }
  1457.  
  1458. /*
  1459.  - regprop - printable representation of opcode
  1460.  */
  1461. static char *
  1462. regprop(op)
  1463. char *op;
  1464. {
  1465.     register char *p;
  1466.     static char buf[50];
  1467.  
  1468.     (void) strcpy(buf, ":");
  1469.  
  1470.     switch (OP(op)) {
  1471.     case BOL:
  1472.         p = "BOL";
  1473.         break;
  1474.     case EOL:
  1475.         p = "EOL";
  1476.         break;
  1477.     case ANY:
  1478.         p = "ANY";
  1479.         break;
  1480.     case ANYOF:
  1481.         p = "ANYOF";
  1482.         break;
  1483.     case ANYBUT:
  1484.         p = "ANYBUT";
  1485.         break;
  1486.     case BRANCH:
  1487.         p = "BRANCH";
  1488.         break;
  1489.     case EXACTLY:
  1490.         p = "EXACTLY";
  1491.         break;
  1492.     case NOTHING:
  1493.         p = "NOTHING";
  1494.         break;
  1495.     case BACK:
  1496.         p = "BACK";
  1497.         break;
  1498.     case END:
  1499.         p = "END";
  1500.         break;
  1501.     case OPEN+1:
  1502.     case OPEN+2:
  1503.     case OPEN+3:
  1504.     case OPEN+4:
  1505.     case OPEN+5:
  1506.     case OPEN+6:
  1507.     case OPEN+7:
  1508.     case OPEN+8:
  1509.     case OPEN+9:
  1510.         sprintf(buf+strlen(buf), "OPEN%d", OP(op)-OPEN);
  1511.         p = NULL;
  1512.         break;
  1513.     case CLOSE+1:
  1514.     case CLOSE+2:
  1515.     case CLOSE+3:
  1516.     case CLOSE+4:
  1517.     case CLOSE+5:
  1518.     case CLOSE+6:
  1519.     case CLOSE+7:
  1520.     case CLOSE+8:
  1521.     case CLOSE+9:
  1522.         sprintf(buf+strlen(buf), "CLOSE%d", OP(op)-CLOSE);
  1523.         p = NULL;
  1524.         break;
  1525.     case STAR:
  1526.         p = "STAR";
  1527.         break;
  1528.     case PLUS:
  1529.         p = "PLUS";
  1530.         break;
  1531.     default:
  1532.         regerror("corrupted opcode");
  1533.         break;
  1534.     }
  1535.     if (p != NULL)
  1536.         (void) strcat(buf, p);
  1537.     return(buf);
  1538. }
  1539. #endif
  1540.  
  1541. /*
  1542.  * The following is provided for those people who do not have strcspn() in
  1543.  * their C libraries.  They should get off their butts and do something
  1544.  * about it; at least one public-domain implementation of those (highly
  1545.  * useful) string routines has been published on Usenet.
  1546.  */
  1547. #ifdef STRCSPN
  1548. /*
  1549.  * strcspn - find length of initial segment of s1 consisting entirely
  1550.  * of characters not from s2
  1551.  */
  1552.  
  1553. static int
  1554. strcspn(s1, s2)
  1555. char *s1;
  1556. char *s2;
  1557. {
  1558.     register char *scan1;
  1559.     register char *scan2;
  1560.     register int count;
  1561.  
  1562.     count = 0;
  1563.     for (scan1 = s1; *scan1 != '\0'; scan1++) {
  1564.         for (scan2 = s2; *scan2 != '\0';)    /* ++ moved down. */
  1565.             if (*scan1 == *scan2++)
  1566.                 return(count);
  1567.         count++;
  1568.     }
  1569.     return(count);
  1570. }
  1571. #endif
  1572. End of regexp.c
  1573. echo regexp.h 1>&2
  1574. cat > regexp.h <<'End of regexp.h'
  1575. /*
  1576.  * Definitions etc. for regexp(3) routines.
  1577.  *
  1578.  * Caveat:  this is V8 regexp(3) [actually, a reimplementation thereof],
  1579.  * not the System V one.
  1580.  */
  1581. #define NSUBEXP  10
  1582. typedef struct regexp {
  1583.     char *startp[NSUBEXP];
  1584.     char *endp[NSUBEXP];
  1585.     char regstart;        /* Internal use only. */
  1586.     char reganch;        /* Internal use only. */
  1587.     char *regmust;        /* Internal use only. */
  1588.     int regmlen;        /* Internal use only. */
  1589.     char program[1];    /* Unwarranted chumminess with compiler. */
  1590. } regexp;
  1591.  
  1592. extern regexp *regcomp();
  1593. extern int regexec();
  1594. extern void regsub();
  1595. extern void regerror();
  1596. End of regexp.h
  1597. echo regmagic.h 1>&2
  1598. cat > regmagic.h <<'End of regmagic.h'
  1599. /*
  1600.  * The first byte of the regexp internal "program" is actually this magic
  1601.  * number; the start node begins in the second byte.
  1602.  */
  1603. #define    MAGIC    0234
  1604. End of regmagic.h
  1605. echo regsub.c 1>&2
  1606. cat > regsub.c <<'End of regsub.c'
  1607. /*
  1608.  * regsub
  1609.  *
  1610.  *    Copyright (c) 1986 by University of Toronto.
  1611.  *    Written by Henry Spencer.  Not derived from licensed software.
  1612.  *
  1613.  *    Permission is granted to anyone to use this software for any
  1614.  *    purpose on any computer system, and to redistribute it freely,
  1615.  *    subject to the following restrictions:
  1616.  *
  1617.  *    1. The author is not responsible for the consequences of use of
  1618.  *        this software, no matter how awful, even if they arise
  1619.  *        from defects in it.
  1620.  *
  1621.  *    2. The origin of this software must not be misrepresented, either
  1622.  *        by explicit claim or by omission.
  1623.  *
  1624.  *    3. Altered versions must be plainly marked as such, and must not
  1625.  *        be misrepresented as being the original software.
  1626.  */
  1627. #include <stdio.h>
  1628. #include <regexp.h>
  1629. #include "regmagic.h"
  1630.  
  1631. #ifndef CHARBITS
  1632. #define    UCHARAT(p)    ((int)*(unsigned char *)(p))
  1633. #else
  1634. #define    UCHARAT(p)    ((int)*(p)&CHARBITS)
  1635. #endif
  1636.  
  1637. /*
  1638.  - regsub - perform substitutions after a regexp match
  1639.  */
  1640. void
  1641. regsub(prog, source, dest)
  1642. regexp *prog;
  1643. char *source;
  1644. char *dest;
  1645. {
  1646.     register char *src;
  1647.     register char *dst;
  1648.     register char c;
  1649.     register int no;
  1650.     register int len;
  1651.     extern char *strncpy();
  1652.  
  1653.     if (prog == NULL || source == NULL || dest == NULL) {
  1654.         regerror("NULL parm to regsub");
  1655.         return;
  1656.     }
  1657.     if (UCHARAT(prog->program) != MAGIC) {
  1658.         regerror("damaged regexp fed to regsub");
  1659.         return;
  1660.     }
  1661.  
  1662.     src = source;
  1663.     dst = dest;
  1664.     while ((c = *src++) != '\0') {
  1665.         if (c == '&')
  1666.             no = 0;
  1667.         else if (c == '\\' && '0' <= *src && *src <= '9')
  1668.             no = *src++ - '0';
  1669.         else
  1670.             no = -1;
  1671.          if (no < 0) {    /* Ordinary character. */
  1672.              if (c == '\\' && (*src == '\\' || *src == '&'))
  1673.                  c = *src++;
  1674.              *dst++ = c;
  1675.          } else if (prog->startp[no] != NULL && prog->endp[no] != NULL) {
  1676.             len = prog->endp[no] - prog->startp[no];
  1677.             (void) strncpy(dst, prog->startp[no], len);
  1678.             dst += len;
  1679.             if (len != 0 && *(dst-1) == '\0') {    /* strncpy hit NUL. */
  1680.                 regerror("damaged match string");
  1681.                 return;
  1682.             }
  1683.         }
  1684.     }
  1685.     *dst++ = '\0';
  1686. }
  1687. End of regsub.c
  1688. echo tests 1>&2
  1689. cat > tests <<'End of tests'
  1690. abc    abc    y    &    abc
  1691. abc    xbc    n    -    -
  1692. abc    axc    n    -    -
  1693. abc    abx    n    -    -
  1694. abc    xabcy    y    &    abc
  1695. abc    ababc    y    &    abc
  1696. ab*c    abc    y    &    abc
  1697. ab*bc    abc    y    &    abc
  1698. ab*bc    abbc    y    &    abbc
  1699. ab*bc    abbbbc    y    &    abbbbc
  1700. ab+bc    abbc    y    &    abbc
  1701. ab+bc    abc    n    -    -
  1702. ab+bc    abq    n    -    -
  1703. ab+bc    abbbbc    y    &    abbbbc
  1704. ab?bc    abbc    y    &    abbc
  1705. ab?bc    abc    y    &    abc
  1706. ab?bc    abbbbc    n    -    -
  1707. ab?c    abc    y    &    abc
  1708. ^abc$    abc    y    &    abc
  1709. ^abc$    abcc    n    -    -
  1710. ^abc    abcc    y    &    abc
  1711. ^abc$    aabc    n    -    -
  1712. abc$    aabc    y    &    abc
  1713. ^    abc    y    &    
  1714. $    abc    y    &    
  1715. a.c    abc    y    &    abc
  1716. a.c    axc    y    &    axc
  1717. a.*c    axyzc    y    &    axyzc
  1718. a.*c    axyzd    n    -    -
  1719. a[bc]d    abc    n    -    -
  1720. a[bc]d    abd    y    &    abd
  1721. a[b-d]e    abd    n    -    -
  1722. a[b-d]e    ace    y    &    ace
  1723. a[b-d]    aac    y    &    ac
  1724. a[-b]    a-    y    &    a-
  1725. a[b-]    a-    y    &    a-
  1726. a[b-a]    -    c    -    -
  1727. a[]b    -    c    -    -
  1728. a[    -    c    -    -
  1729. a]    a]    y    &    a]
  1730. a[]]b    a]b    y    &    a]b
  1731. a[^bc]d    aed    y    &    aed
  1732. a[^bc]d    abd    n    -    -
  1733. a[^-b]c    adc    y    &    adc
  1734. a[^-b]c    a-c    n    -    -
  1735. a[^]b]c    a]c    n    -    -
  1736. a[^]b]c    adc    y    &    adc
  1737. ab|cd    abc    y    &    ab
  1738. ab|cd    abcd    y    &    ab
  1739. ()ef    def    y    &-\1    ef-
  1740. ()*    -    c    -    -
  1741. *a    -    c    -    -
  1742. ^*    -    c    -    -
  1743. $*    -    c    -    -
  1744. (*)b    -    c    -    -
  1745. $b    b    n    -    -
  1746. a\    -    c    -    -
  1747. a\(b    a(b    y    &-\1    a(b-
  1748. a\(*b    ab    y    &    ab
  1749. a\(*b    a((b    y    &    a((b
  1750. a\\b    a\b    y    &    a\b
  1751. abc)    -    c    -    -
  1752. (abc    -    c    -    -
  1753. ((a))    abc    y    &-\1-\2    a-a-a
  1754. (a)b(c)    abc    y    &-\1-\2    abc-a-c
  1755. a+b+c    aabbabc    y    &    abc
  1756. a**    -    c    -    -
  1757. a*?    -    c    -    -
  1758. (a*)*    -    c    -    -
  1759. (a*)+    -    c    -    -
  1760. (a|)*    -    c    -    -
  1761. (a*|b)*    -    c    -    -
  1762. (a+|b)*    ab    y    &-\1    ab-b
  1763. (a+|b)+    ab    y    &-\1    ab-b
  1764. (a+|b)?    ab    y    &-\1    a-a
  1765. [^ab]*    cde    y    &    cde
  1766. (^)*    -    c    -    -
  1767. (ab|)*    -    c    -    -
  1768. )(    -    c    -    -
  1769.     abc    y    &    
  1770. abc        n    -    -
  1771. a*        y    &    
  1772. ([abc])*d    abbbcd    y    &-\1    abbbcd-c
  1773. ([abc])*bcd    abcd    y    &-\1    abcd-a
  1774. a|b|c|d|e    e    y    &    e
  1775. (a|b|c|d|e)f    ef    y    &-\1    ef-e
  1776. ((a*|b))*    -    c    -    -
  1777. abcd*efg    abcdefg    y    &    abcdefg
  1778. ab*    xabyabbbz    y    &    ab
  1779. ab*    xayabbbz    y    &    a
  1780. (ab|cd)e    abcde    y    &-\1    cde-cd
  1781. [abhgefdc]ij    hij    y    &    hij
  1782. ^(ab|cd)e    abcde    n    x\1y    xy
  1783. (abc|)ef    abcdef    y    &-\1    ef-
  1784. (a|b)c*d    abcd    y    &-\1    bcd-b
  1785. (ab|ab*)bc    abc    y    &-\1    abc-a
  1786. a([bc]*)c*    abc    y    &-\1    abc-bc
  1787. a([bc]*)(c*d)    abcd    y    &-\1-\2    abcd-bc-d
  1788. a([bc]+)(c*d)    abcd    y    &-\1-\2    abcd-bc-d
  1789. a([bc]*)(c+d)    abcd    y    &-\1-\2    abcd-b-cd
  1790. a[bcd]*dcdcde    adcdcde    y    &    adcdcde
  1791. a[bcd]+dcdcde    adcdcde    n    -    -
  1792. (ab|a)b*c    abc    y    &-\1    abc-ab
  1793. ((a)(b)c)(d)    abcd    y    \1-\2-\3-\4    abc-a-b-d
  1794. [a-zA-Z_][a-zA-Z0-9_]*    alpha    y    &    alpha
  1795. ^a(bc+|b[eh])g|.h$    abh    y    &-\1    bh-
  1796. (bc+d$|ef*g.|h?i(j|k))    effgz    y    &-\1-\2    effgz-effgz-
  1797. (bc+d$|ef*g.|h?i(j|k))    ij    y    &-\1-\2    ij-ij-j
  1798. (bc+d$|ef*g.|h?i(j|k))    effg    n    -    -
  1799. (bc+d$|ef*g.|h?i(j|k))    bcdd    n    -    -
  1800. (bc+d$|ef*g.|h?i(j|k))    reffgz    y    &-\1-\2    effgz-effgz-
  1801. ((((((((((a))))))))))    -    c    -    -
  1802. (((((((((a)))))))))    a    y    &    a
  1803. multiple words of text    uh-uh    n    -    -
  1804. multiple words    multiple words, yeah    y    &    multiple words
  1805. (.*)c(.*)    abcde    y    &-\1-\2    abcde-ab-de
  1806. \((.*), (.*)\)    (a, b)    y    (\2, \1)    (b, a)
  1807. [k]    ab    n    -    -
  1808. abcd    abcd    y    &-\&-\\&    abcd-&-\abcd
  1809. a(bc)d    abcd    y    \1-\\1-\\\1    bc-\1-\bc
  1810. a[-]?c    ac    y    &    ac
  1811. End of tests
  1812. echo timer.c 1>&2
  1813. cat > timer.c <<'End of timer.c'
  1814. /*
  1815.  * Simple timing program for regcomp().
  1816.  *
  1817.  *    Copyright (c) 1986 by University of Toronto.
  1818.  *    Written by Henry Spencer.  Not derived from licensed software.
  1819.  *
  1820.  *    Permission is granted to anyone to use this software for any
  1821.  *    purpose on any computer system, and to redistribute it freely,
  1822.  *    subject to the following restrictions:
  1823.  *
  1824.  *    1. The author is not responsible for the consequences of use of
  1825.  *        this software, no matter how awful, even if they arise
  1826.  *        from defects in it.
  1827.  *
  1828.  *    2. The origin of this software must not be misrepresented, either
  1829.  *        by explicit claim or by omission.
  1830.  *
  1831.  *    3. Altered versions must be plainly marked as such, and must not
  1832.  *        be misrepresented as being the original software.
  1833.  *
  1834.  * Usage: timer ncomp nexec nsub
  1835.  *    or
  1836.  *    timer ncomp nexec nsub regexp string [ answer [ sub ] ]
  1837.  *
  1838.  * The second form is for timing repetitions of a single test case.
  1839.  * The first form's test data is a compiled-in copy of the "tests" file.
  1840.  * Ncomp, nexec, nsub are how many times to do each regcomp, regexec,
  1841.  * and regsub.  The way to time an operation individually is to do something
  1842.  * like "timer 1 50 1".
  1843.  */
  1844. #include <stdio.h>
  1845.  
  1846. struct try {
  1847.     char *re, *str, *ans, *src, *dst;
  1848. } tests[] = {
  1849. #include "timer.t.h"
  1850. { NULL, NULL, NULL, NULL, NULL }
  1851. };
  1852.  
  1853. #include <regexp.h>
  1854.  
  1855. int errreport = 0;        /* Report errors via errseen? */
  1856. char *errseen = NULL;        /* Error message. */
  1857.  
  1858. char *progname;
  1859.  
  1860. /* ARGSUSED */
  1861. main(argc, argv)
  1862. int argc;
  1863. char *argv[];
  1864. {
  1865.     int ncomp, nexec, nsub;
  1866.     struct try one;
  1867.     char dummy[512];
  1868.  
  1869.     if (argc < 4) {
  1870.         ncomp = 1;
  1871.         nexec = 1;
  1872.         nsub = 1;
  1873.     } else {
  1874.         ncomp = atoi(argv[1]);
  1875.         nexec = atoi(argv[2]);
  1876.         nsub = atoi(argv[3]);
  1877.     }
  1878.     
  1879.     progname = argv[0];
  1880.     if (argc > 5) {
  1881.         one.re = argv[4];
  1882.         one.str = argv[5];
  1883.         if (argc > 6)
  1884.             one.ans = argv[6];
  1885.         else
  1886.             one.ans = "y";
  1887.         if (argc > 7) {    
  1888.             one.src = argv[7];
  1889.             one.dst = "xxx";
  1890.         } else {
  1891.             one.src = "x";
  1892.             one.dst = "x";
  1893.         }
  1894.         errreport = 1;
  1895.         try(one, ncomp, nexec, nsub);
  1896.     } else
  1897.         multiple(ncomp, nexec, nsub);
  1898.     exit(0);
  1899. }
  1900.  
  1901. void
  1902. regerror(s)
  1903. char *s;
  1904. {
  1905.     if (errreport)
  1906.         errseen = s;
  1907.     else
  1908.         error(s, "");
  1909. }
  1910.  
  1911. #ifndef ERRAVAIL
  1912. error(s1, s2)
  1913. char *s1;
  1914. char *s2;
  1915. {
  1916.     fprintf(stderr, "regexp: ");
  1917.     fprintf(stderr, s1, s2);
  1918.     fprintf(stderr, "\n");
  1919.     exit(1);
  1920. }
  1921. #endif
  1922.  
  1923. int lineno = 0;
  1924.  
  1925. multiple(ncomp, nexec, nsub)
  1926. int ncomp, nexec, nsub;
  1927. {
  1928.     register int i;
  1929.     extern char *strchr();
  1930.  
  1931.     errreport = 1;
  1932.     for (i = 0; tests[i].re != NULL; i++) {
  1933.         lineno++;
  1934.         try(tests[i], ncomp, nexec, nsub);
  1935.     }
  1936. }
  1937.  
  1938. try(fields, ncomp, nexec, nsub)
  1939. struct try fields;
  1940. int ncomp, nexec, nsub;
  1941. {
  1942.     regexp *r;
  1943.     char dbuf[BUFSIZ];
  1944.     register int i;
  1945.  
  1946.     errseen = NULL;
  1947.     r = regcomp(fields.re);
  1948.     if (r == NULL) {
  1949.         if (*fields.ans != 'c')
  1950.             complain("regcomp failure in `%s'", fields.re);
  1951.         return;
  1952.     }
  1953.     if (*fields.ans == 'c') {
  1954.         complain("unexpected regcomp success in `%s'", fields.re);
  1955.         free((char *)r);
  1956.         return;
  1957.     }
  1958.     for (i = ncomp-1; i > 0; i--) {
  1959.         free((char *)r);
  1960.         r = regcomp(fields.re);
  1961.     }
  1962.     if (!regexec(r, fields.str)) {
  1963.         if (*fields.ans != 'n')
  1964.             complain("regexec failure in `%s'", "");
  1965.         free((char *)r);
  1966.         return;
  1967.     }
  1968.     if (*fields.ans == 'n') {
  1969.         complain("unexpected regexec success", "");
  1970.         free((char *)r);
  1971.         return;
  1972.     }
  1973.     for (i = nexec-1; i > 0; i--)
  1974.         (void) regexec(r, fields.str);
  1975.     errseen = NULL;
  1976.     for (i = nsub; i > 0; i--)
  1977.         regsub(r, fields.src, dbuf);
  1978.     if (errseen != NULL) {    
  1979.         complain("regsub complaint", "");
  1980.         free((char *)r);
  1981.         return;
  1982.     }
  1983.     if (strcmp(dbuf, fields.dst) != 0)
  1984.         complain("regsub result `%s' wrong", dbuf);
  1985.     free((char *)r);
  1986. }
  1987.  
  1988. complain(s1, s2)
  1989. char *s1;
  1990. char *s2;
  1991. {
  1992.     fprintf(stderr, "try: %d: ", lineno);
  1993.     fprintf(stderr, s1, s2);
  1994.     fprintf(stderr, " (%s)\n", (errseen != NULL) ? errseen : "");
  1995. }
  1996. End of timer.c
  1997. echo try.c 1>&2
  1998. cat > try.c <<'End of try.c'
  1999. /*
  2000.  * Simple test program for regexp(3) stuff.  Knows about debugging hooks.
  2001.  *
  2002.  *    Copyright (c) 1986 by University of Toronto.
  2003.  *    Written by Henry Spencer.  Not derived from licensed software.
  2004.  *
  2005.  *    Permission is granted to anyone to use this software for any
  2006.  *    purpose on any computer system, and to redistribute it freely,
  2007.  *    subject to the following restrictions:
  2008.  *
  2009.  *    1. The author is not responsible for the consequences of use of
  2010.  *        this software, no matter how awful, even if they arise
  2011.  *        from defects in it.
  2012.  *
  2013.  *    2. The origin of this software must not be misrepresented, either
  2014.  *        by explicit claim or by omission.
  2015.  *
  2016.  *    3. Altered versions must be plainly marked as such, and must not
  2017.  *        be misrepresented as being the original software.
  2018.  *
  2019.  * Usage: try re [string [output [-]]]
  2020.  * The re is compiled and dumped, regexeced against the string, the result
  2021.  * is applied to output using regsub().  The - triggers a running narrative
  2022.  * from regexec().  Dumping and narrative don't happen unless DEBUG.
  2023.  *
  2024.  * If there are no arguments, stdin is assumed to be a stream of lines with
  2025.  * five fields:  a r.e., a string to match it against, a result code, a
  2026.  * source string for regsub, and the proper result.  Result codes are 'c'
  2027.  * for compile failure, 'y' for match success, 'n' for match failure.
  2028.  * Field separator is tab.
  2029.  */
  2030. #include <stdio.h>
  2031. #include <regexp.h>
  2032.  
  2033. #ifdef ERRAVAIL
  2034. char *progname;
  2035. extern char *mkprogname();
  2036. #endif
  2037.  
  2038. #ifdef DEBUG
  2039. extern int regnarrate;
  2040. #endif
  2041.  
  2042. char buf[BUFSIZ];
  2043.  
  2044. int errreport = 0;        /* Report errors via errseen? */
  2045. char *errseen = NULL;        /* Error message. */
  2046. int status = 0;            /* Exit status. */
  2047.  
  2048. /* ARGSUSED */
  2049. main(argc, argv)
  2050. int argc;
  2051. char *argv[];
  2052. {
  2053.     regexp *r;
  2054.     int i;
  2055.  
  2056. #ifdef ERRAVAIL
  2057.     progname = mkprogname(argv[0]);
  2058. #endif
  2059.  
  2060.     if (argc == 1) {
  2061.         multiple();
  2062.         exit(status);
  2063.     }
  2064.  
  2065.     r = regcomp(argv[1]);
  2066.     if (r == NULL)
  2067.         error("regcomp failure", "");
  2068. #ifdef DEBUG
  2069.     regdump(r);
  2070.     if (argc > 4)
  2071.         regnarrate++;
  2072. #endif
  2073.     if (argc > 2) {
  2074.         i = regexec(r, argv[2]);
  2075.         printf("%d", i);
  2076.         for (i = 1; i < NSUBEXP; i++)
  2077.             if (r->startp[i] != NULL && r->endp[i] != NULL)
  2078.                 printf(" \\%d", i);
  2079.         printf("\n");
  2080.     }
  2081.     if (argc > 3) {
  2082.         regsub(r, argv[3], buf);
  2083.         printf("%s\n", buf);
  2084.     }
  2085.     exit(status);
  2086. }
  2087.  
  2088. void
  2089. regerror(s)
  2090. char *s;
  2091. {
  2092.     if (errreport)
  2093.         errseen = s;
  2094.     else
  2095.         error(s, "");
  2096. }
  2097.  
  2098. #ifndef ERRAVAIL
  2099. error(s1, s2)
  2100. char *s1;
  2101. char *s2;
  2102. {
  2103.     fprintf(stderr, "regexp: ");
  2104.     fprintf(stderr, s1, s2);
  2105.     fprintf(stderr, "\n");
  2106.     exit(1);
  2107. }
  2108. #endif
  2109.  
  2110. int lineno;
  2111.  
  2112. regexp badregexp;        /* Implicit init to 0. */
  2113.  
  2114. multiple()
  2115. {
  2116.     char rbuf[BUFSIZ];
  2117.     char *field[5];
  2118.     char *scan;
  2119.     int i;
  2120.     regexp *r;
  2121.     extern char *strchr();
  2122.  
  2123.     errreport = 1;
  2124.     lineno = 0;
  2125.     while (fgets(rbuf, sizeof(rbuf), stdin) != NULL) {
  2126.         rbuf[strlen(rbuf)-1] = '\0';    /* Dispense with \n. */
  2127.         lineno++;
  2128.         scan = rbuf;
  2129.         for (i = 0; i < 5; i++) {
  2130.             field[i] = scan;
  2131.             if (field[i] == NULL) {
  2132.                 complain("bad testfile format", "");
  2133.                 exit(1);
  2134.             }
  2135.             scan = strchr(scan, '\t');
  2136.             if (scan != NULL)
  2137.                 *scan++ = '\0';
  2138.         }
  2139.         try(field);
  2140.     }
  2141.  
  2142.     /* And finish up with some internal testing... */
  2143.     lineno = 9990;
  2144.     errseen = NULL;
  2145.     if (regcomp((char *)NULL) != NULL || errseen == NULL)
  2146.         complain("regcomp(NULL) doesn't complain", "");
  2147.     lineno = 9991;
  2148.     errseen = NULL;
  2149.     if (regexec((regexp *)NULL, "foo") || errseen == NULL)
  2150.         complain("regexec(NULL, ...) doesn't complain", "");
  2151.     lineno = 9992;
  2152.     r = regcomp("foo");
  2153.     if (r == NULL) {
  2154.         complain("regcomp(\"foo\") fails", "");
  2155.         return;
  2156.     }
  2157.     lineno = 9993;
  2158.     errseen = NULL;
  2159.     if (regexec(r, (char *)NULL) || errseen == NULL)
  2160.         complain("regexec(..., NULL) doesn't complain", "");
  2161.     lineno = 9994;
  2162.     errseen = NULL;
  2163.     regsub((regexp *)NULL, "foo", rbuf);
  2164.     if (errseen == NULL)
  2165.         complain("regsub(NULL, ..., ...) doesn't complain", "");
  2166.     lineno = 9995;
  2167.     errseen = NULL;
  2168.     regsub(r, (char *)NULL, rbuf);
  2169.     if (errseen == NULL)
  2170.         complain("regsub(..., NULL, ...) doesn't complain", "");
  2171.     lineno = 9996;
  2172.     errseen = NULL;
  2173.     regsub(r, "foo", (char *)NULL);
  2174.     if (errseen == NULL)
  2175.         complain("regsub(..., ..., NULL) doesn't complain", "");
  2176.     lineno = 9997;
  2177.     errseen = NULL;
  2178.     if (regexec(&badregexp, "foo") || errseen == NULL)
  2179.         complain("regexec(nonsense, ...) doesn't complain", "");
  2180.     lineno = 9998;
  2181.     errseen = NULL;
  2182.     regsub(&badregexp, "foo", rbuf);
  2183.     if (errseen == NULL)
  2184.         complain("regsub(nonsense, ..., ...) doesn't complain", "");
  2185. }
  2186.  
  2187. try(fields)
  2188. char **fields;
  2189. {
  2190.     regexp *r;
  2191.     char dbuf[BUFSIZ];
  2192.  
  2193.     errseen = NULL;
  2194.     r = regcomp(fields[0]);
  2195.     if (r == NULL) {
  2196.         if (*fields[2] != 'c')
  2197.             complain("regcomp failure in `%s'", fields[0]);
  2198.         return;
  2199.     }
  2200.     if (*fields[2] == 'c') {
  2201.         complain("unexpected regcomp success in `%s'", fields[0]);
  2202.         free((char *)r);
  2203.         return;
  2204.     }
  2205.     if (!regexec(r, fields[1])) {
  2206.         if (*fields[2] != 'n')
  2207.             complain("regexec failure in `%s'", "");
  2208.         free((char *)r);
  2209.         return;
  2210.     }
  2211.     if (*fields[2] == 'n') {
  2212.         complain("unexpected regexec success", "");
  2213.         free((char *)r);
  2214.         return;
  2215.     }
  2216.     errseen = NULL;
  2217.     regsub(r, fields[3], dbuf);
  2218.     if (errseen != NULL) {
  2219.         complain("regsub complaint", "");
  2220.         free((char *)r);
  2221.         return;
  2222.     }
  2223.     if (strcmp(dbuf, fields[4]) != 0)
  2224.         complain("regsub result `%s' wrong", dbuf);
  2225.     free((char *)r);
  2226. }
  2227.  
  2228. complain(s1, s2)
  2229. char *s1;
  2230. char *s2;
  2231. {
  2232.     fprintf(stderr, "try: %d: ", lineno);
  2233.     fprintf(stderr, s1, s2);
  2234.     fprintf(stderr, " (%s)\n", (errseen != NULL) ? errseen : "");
  2235.     status = 1;
  2236. }
  2237. End of try.c
  2238.  
  2239. -- 
  2240. Rich $alz            rsalz@pineapple.bbn.com
  2241. Cronus Project, BBN Labs    "Anger is an energy"
  2242.