Debian Codegraph @

easel/esl_regexp.c

raw symbols SCIP
1 /* esl_regexp.c: regular expression matching on strings.
2 *
3 * This is a wrapper around a modified version of Henry Spencer's
4 * regex library. Spencer's copyright notice appears below, after my
5 * wrappers, prefacing the section that includes his code. I believe
6 * you can obtain the original code from:
7 * ftp://ftp.zoo.toronto.edu/pub/bookregex.tar.Z
8 * Thanks, Henry!
9 *
10 * My modifications are generally limited to converting error handling
11 * to Easel conventions, internalizing Spencer's code as all
12 * static to this module, and some cosmetic changes to names
13 * for namespace protection reasons. I am responsible for any
14 * errors that I've introduced into Spencer's code.
15 *
16 *****************************************************************
17 * nomenclature note:
18 * A "machine" is a persistent ESL_REGEXP object, which contains
19 * an NDFA for a pattern, but the NDFA may change throughout
20 * the life of the machine.
21 *
22 * An "NDFA" (nondeterministic finite automaton) refers to
23 * an internal esl__regexp structure, which is Spencer's
24 * compiled pattern-program. We try to compile an NDFA once per
25 * pattern.
26 *
27 * A "pattern" refers to actual regular expression we're trying
28 * to match, represented as an ASCII string.
29 *
30 *****************************************************************
31 * error handling note: (xref STL9/p2)
32 * We expect that the input pattern may be provided by the user,
33 * and so a very common error will be an invalid regular expression
34 * syntax. There are 9 types of syntax errors caught by the
35 * regcomp() code and its friends. All of them generate an
36 * eslESYNTAX error, with a terse message. Under the default
37 * error handler this message will be printed and the code will halt.
38 * If you do not want invalid input regex syntax to halt your application,
39 * you can install a custom error handler that can handle
40 * the eslESYNTAX errors as you wish.
41 *****************************************************************
42 * TODO:
43 * - would be great to have an esl_regexp_Sample(), which sampled
44 * strings from a regexp. We could use this in unit tests that
45 * need to stress edge cases (generating strings with unusual
46 * but legal characters, for example). We would probably want
47 * to implement some artificial limits on repeat operators,
48 * to keep length of sampled seq reasonable.
49 *
50 * Contents:
51 * 1. Easel's regexp API
52 * 2. Henry Spencer's regex library
53 * 3. My extensions to the Spencer code
54 * 4. Unit tests
55 * 5. Test driver
56 * 6. Examples
57 */
58 #include <esl_config.h>
59
60 #include <stdio.h>
61 #include <stdlib.h>
62 #include <string.h>
63 #include <ctype.h>
64
65 #include "easel.h"
66 #include "esl_regexp.h"
67
68 /* Forward declarations of Spencer's API as static, internalized in my module.
69 */
70 static esl__regexp *regcomp(const char *exp);
71 static int regexec(register esl__regexp *prog, const char *str);
72 /* his regsub() is present but unused, ifdef'd out to silence compilers; uncomment to reactivate */
73 /* static int regsub(const esl__regexp *rp, const char *source, char *dest); */
74 #ifdef DEBUG
75 static void regdump(esl__regexp *r);
76 #endif
77
78
79
80
81 /*****************************************************************
82 * 1. Easel's regexp API
83 *****************************************************************/
84
85 /* Function: esl_regexp_Create()
86 * Incept: SRE, Fri Jan 7 10:55:48 2005 [St. Louis]
87 *
88 * Purpose: Creates a new <ESL_REGEXP> machine.
89 *
90 * Throws: NULL on allocation failure.
91 *
92 * Xref: STL9/p1
93 */
94 ESL_REGEXP *
95 esl_regexp_Create(void)
96 {
97 int status;
98 ESL_REGEXP *machine = NULL;
99
100 ESL_ALLOC(machine, sizeof(ESL_REGEXP));
101 machine->ndfa = NULL;
102 return machine;
103
104 ERROR:
105 return NULL;
106 }
107
108
109 /* Function: esl_regexp_Destroy()
110 * Incept: SRE, Fri Jan 7 11:12:20 2005 [St. Louis]
111 *
112 * Purpose: Destroy a machine created by <esl_regexp_Create()>.
113 *
114 * Returns: void.
115 */
116 void
117 esl_regexp_Destroy(ESL_REGEXP *machine)
118 {
119 if (machine)
120 { /* Spencer's clever alloc for the NDFA allows us to free it w/ free() */
121 free(machine->ndfa);
122 free(machine);
123 }
124 return;
125 }
126
127
128 /* Function: esl_regexp_Compile()
129 * Incept: SRE, Sat Jan 8 09:56:21 2005 [St. Louis]
130 *
131 * Purpose: Precompile an NDFA for <pattern> and store it in
132 * a <machine>, in preparation for using the same
133 * pattern for multiple searches.
134 *
135 * Returns: <eslOK> on success.
136 *
137 * Throws: <eslEINVAL> if compilation fails.
138 */
139 int
140 esl_regexp_Compile(ESL_REGEXP *machine, const char *pattern)
141 {
142 if (machine->ndfa != NULL) { free(machine->ndfa); machine->ndfa = NULL; }
143 if ((machine->ndfa = regcomp(pattern)) == NULL) return eslEINVAL;
144 return eslOK;
145 }
146
147
148
149 /* Function: esl_regexp_Match()
150 * Incept: SRE, Fri Jan 7 11:24:02 2005 [St. Louis]
151 *
152 * Purpose: Determine if string <s> matches the regular expression
153 * <pattern>, using a <machine>. Upon return, <machine>
154 * contains the compiled <pattern>.
155 *
156 * If <pattern> is <NULL>, use the last pattern compiled
157 * into the <machine>.
158
159 * If there's a match, return <eslOK>, and the <machine>
160 * contains information about the match, which you can
161 * extract with <esl_regexp_Submatch*()> functions.
162 *
163 * If there's no match, return <eslEOD>.
164 *
165 * Returns: <eslOK> if <pattern> matches <s>; <eslEOD> if it doesn't.
166 *
167 * Throws: <eslEINVAL> if the <pattern> couldn't be compiled for any reason.
168 * <eslEINCONCEIVABLE> or <eslECORRUPT> if something
169 * went wrong in the search phase.
170 *
171 * (At the failure point, an error was generated with an appropriate
172 * code and message; an <ESL_SYNTAX> code, for example, may have
173 * been generated to indicate that the <pattern> is an invalid syntax.)
174 */
175 int
176 esl_regexp_Match(ESL_REGEXP *machine, const char *pattern, const char *s)
177 {
178 if (pattern)
179 {
180 if (machine->ndfa) { free(machine->ndfa); machine->ndfa = NULL; }
181 if ((machine->ndfa = regcomp(pattern)) == NULL) return eslEINVAL;
182 }
183 return regexec(machine->ndfa, s);
184 }
185
186
187
188 /* Function: esl_regexp_MultipleMatches()
189 * Incept: SRE, Sat Jan 8 10:01:27 2005 [St. Louis]
190 *
191 * Purpose: Given a <machine> that contains a precompiled NDFA (see
192 * <esl_regexp_Compile()>, search it against a <string>.
193 * pointed to by <sptr>. When a match is found, returns
194 * <eslOK>, and resets <sptr> to point at the next character
195 * after the matched substring. (This may be
196 * trailing NUL byte if the matched substring is at the
197 * very end of the string.) If no match is found in the
198 * string, returns <eslEOD>.
199 *
200 * Because <sptr> is changed, the caller should
201 * initialize and use a temporary pointer into the string
202 * to be searched, not the caller's own pointer to the
203 * target string.
204 *
205 * Example:
206 * s = string;
207 * while (esl_regexp_MultipleMatches(m, &s) == eslOK)
208 * // process one match at a time//;
209 *
210 * Throws: <eslEINCONCEIVABLE> or <eslECORRUPT> if something goes awry internally
211 * during the search.
212 */
213 int
214 esl_regexp_MultipleMatches(ESL_REGEXP *machine, char **sptr)
215 {
216 int status;
217
218 status = regexec(machine->ndfa, *sptr);
219 if (status == eslOK)
220 *sptr = machine->ndfa->endp[0]; /* endp points exactly where we want. */
221 else
222 *sptr = NULL;
223 return status;
224 }
225
226
227
228 /* Function: esl_regexp_GetMatch()
229 * Synopsis: Get matched text as a ptr and a length (esl_mem style)
230 * Incept: SRE, Mon 23 Nov 2020
231 *
232 * Purpose: Given a <machine> that just got done matching a pattern
233 * against a target string, retrieve a pointer to and a
234 * length of text that matched. <which> indicates which
235 * submatch to retrieve; 0 means the entire match, and
236 * 1..15 are up to 15 ()'d submatches in the pattern.
237 *
238 * Returns: <eslOK> on success. Now <*ret_s> points to the start of
239 * the match, and <*ret_n> is its length.
240 *
241 * Throws: (no abnormal error conditions)
242 */
243 int
244 esl_regexp_GetMatch(ESL_REGEXP *machine, int which, char **ret_s, esl_pos_t *ret_n)
245 {
246 ESL_DASSERT1(( which >= 0 && which < ESL_REGEXP_NSUB ));
247 ESL_DASSERT1(( machine->ndfa ));
248 ESL_DASSERT1(( machine->ndfa->startp[which] && machine->ndfa->endp[which] ));
249
250 *ret_s = machine->ndfa->startp[which];
251 *ret_n = (esl_pos_t) (machine->ndfa->endp[which] - machine->ndfa->startp[which]);
252 return eslOK;
253 }
254
255
256
257 /* Function: esl_regexp_SubmatchDup()
258 * Incept: SRE, Sat Jan 8 11:12:29 2005 [St. Louis]
259 *
260 * Purpose: Given a <machine> that has just got done matching
261 * some pattern against a target string,
262 * retrieve a substring that matched the pattern
263 * or one of the ()'d parts of it. <elem> indicates
264 * which submatch to retrieve. <elem> 0 is the complete
265 * match; 1..15 (assuming the default <ESL_REGEXP_NSUB>=16)
266 * are up to 15 ()'d submatches in the pattern.
267 *
268 * Returns: ptr to an allocated, NUL-terminated string containing
269 * the matched part of the string. Caller is responsible
270 * for free'ing this string.
271 *
272 * Throws: NULL on any internal failure.
273 */
274 char *
275 esl_regexp_SubmatchDup(ESL_REGEXP *machine, int elem)
276 {
277 char *s;
278 int len;
279 int status;
280
281 if (elem >= ESL_REGEXP_NSUB || elem < 0)
282 ESL_XEXCEPTION(eslEINVAL, "bad elem arg");
283 if (machine->ndfa->startp[elem] == NULL || machine->ndfa->endp[elem] == NULL)
284 ESL_XEXCEPTION(eslEINVAL, "no such submatch recorded");
285
286 len = machine->ndfa->endp[elem] - machine->ndfa->startp[elem];
287 ESL_ALLOC(s, sizeof(char) * (len+1));
288 strncpy(s, machine->ndfa->startp[elem], len);
289 s[len] = '\0';
290 return s;
291
292 ERROR:
293 return NULL;
294 }
295
296 /* Function: esl_regexp_SubmatchCopy()
297 * Incept: SRE, Sat Jan 8 11:12:29 2005 [St. Louis]
298 *
299 * Purpose: Given a <machine> that has just got done matching some
300 * pattern against a target string, copy a substring that
301 * matched the pattern or one of the ()'d parts of it into
302 * a provided <buffer> with <nc> chars of space allocated.
303 * <elem> indicates which submatch to retrieve. <elem> 0 is
304 * the complete match; 1..15 (assuming the default
305 * <ESL_REGEXP_NSUB>=16) are up to 15 ()'d submatches in
306 * the pattern.
307 *
308 * Returns: <eslOK> on success, and buffer contains the NUL-terminated
309 * substring.
310 *
311 * Throws: <eslEINVAL> on any of several possible internal failures,
312 * including the <buffer> being too small to contain the
313 * substring.
314 */
315 int
316 esl_regexp_SubmatchCopy(ESL_REGEXP *machine, int elem, char *buffer, int nc)
317 {
318 int len;
319 int status;
320
321 if (elem >= ESL_REGEXP_NSUB || elem < 0)
322 ESL_XEXCEPTION(eslEINVAL, "bad elem arg");
323 if (machine->ndfa->startp[elem] == NULL || machine->ndfa->endp[elem] == NULL)
324 ESL_XEXCEPTION(eslEINVAL, "no such submatch recorded");
325
326 len = machine->ndfa->endp[elem] - machine->ndfa->startp[elem];
327 if (len >= nc)
328 ESL_XEXCEPTION(eslEINVAL, "buffer too small to hold submatch");
329
330 strncpy(buffer, machine->ndfa->startp[elem], len);
331 buffer[len] = '\0';
332 return eslOK;
333
334 ERROR:
335 buffer[0] = '\0';
336 return status;
337 }
338
339
340
341 /* Function: esl_regexp_SubmatchCoords()
342 * Incept: SRE, Sat Jan 8 11:46:11 2005 [St. Louis]
343 *
344 * Purpose: Given a <machine> that has just got done matching some
345 * pattern against a target string, find the start/end
346 * coordinates of the substring that matched the
347 * pattern or one of the ()'d parts of it, relative to
348 * a pointer <origin> on the target string. Return the result
349 * through the ptrs <ret_start> and <ret_end>. <elem>
350 * indicates which submatch to retrieve. <elem> 0 is the
351 * complete match; 1..15 (assuming the default
352 * <ESL_REGEXP_NSUB> = 16) are up to 15 ()'d submatches in
353 * the pattern.
354 *
355 * The coordinates given in zero-offset convention relative
356 * to an <origin>. <origin> will usually be a pointer to
357 * the complete target string, in which case the coords
358 * would be [0..L-1]. However, one can extract coords
359 * relative to any other <origin> in the target string,
360 * even including an <origin> downstream of the match, so
361 * relative coords can be negative, ranging from -(L-1) to
362 * (L-1).
363 *
364 * Coords will be correct even if the match was
365 * found by a <esl_regexp_MultipleMatches()> call against
366 * a temp pointer into the target string.
367 *
368 * Returns: <eslOK> on success, and <ret_start> and <ret_end>
369 * are set to the start/end coordinates of the submatch.
370 *
371 * Throws: <eslEINVAL> on internal failures.
372 * The function is incapable of detecting a case in
373 * where <origin> is not in the same string that the
374 * <machine> matched like it should be. If a caller does
375 * this, the function may appear to succeed, but start and end
376 * coords will be garbage.
377 */
378 int
379 esl_regexp_SubmatchCoords(ESL_REGEXP *machine, char *origin, int elem,
380 int *ret_start, int *ret_end)
381 {
382 int status;
383
384 if (elem >= ESL_REGEXP_NSUB || elem < 0)
385 ESL_XEXCEPTION(eslEINVAL, "bad elem arg");
386 if (machine->ndfa->startp[elem] == NULL || machine->ndfa->endp[elem] == NULL)
387 ESL_XEXCEPTION(eslEINVAL, "no such submatch recorded");
388
389 *ret_start = machine->ndfa->startp[elem] - origin;
390 *ret_end = machine->ndfa->endp[elem] - origin - 1;
391 return eslOK;
392
393 ERROR:
394 *ret_start = 0;
395 *ret_end = 0;
396 return status;
397 }
398
399
400
401 /* Function: esl_regexp_ParseCoordString()
402 *
403 * Purpose: Given a string <cstring> of the format required for a
404 * range (<from>..<to>, e.g. 10..23 or 39-91) parse out
405 * the start and end, and return them within the variables
406 * <ret_start> and <ret_end>.
407 *
408 * Returns: <eslOK> on success, and <ret_start> and <ret_end>
409 * are set to the start/end coordinates of the parse.
410 *
411 * Throws: <eslESYNTAX> if a regexp match is not made, and
412 * <eslFAIL> if the start or end values are not parsed.
413 */
414 int
415 esl_regexp_ParseCoordString(const char *cstring, int64_t *ret_start, int64_t *ret_end)
416 {
417 ESL_REGEXP *re = esl_regexp_Create();
418 char tok1[20]; // max length of int64_t in char = 18 + '-' + '\0' = 20
419 char tok2[20];
420 int status;
421
422 if (esl_regexp_Match(re, "^(\\d+)\\D+(\\d*)$", cstring) != eslOK) { status = eslESYNTAX; goto ERROR; }
423 if (esl_regexp_SubmatchCopy(re, 1, tok1, 32) != eslOK) { status = eslFAIL; goto ERROR; }
424 if (esl_regexp_SubmatchCopy(re, 2, tok2, 32) != eslOK) { status = eslFAIL; goto ERROR; }
425
426 *ret_start = atol(tok1);
427 *ret_end = (tok2[0] == '\0') ? 0 : atol(tok2);
428
429 esl_regexp_Destroy(re);
430 return eslOK;
431
432 ERROR:
433 esl_regexp_Destroy(re);
434 return status;
435 }
436 /*=================== end of the exposed API ==========================================*/
437
438
439
440 /*****************************************************************
441 * 2. Henry Spencer's regexp library
442 *****************************************************************/
443
444 /**************************************************************************************
445 * This next big chunk of code is:
446 * Copyright (c) 1986, 1993, 1995 by University of Toronto.
447 * Written by Henry Spencer. Not derived from licensed software.
448 *
449 * Permission is granted to anyone to use this software for any
450 * purpose on any computer system, and to redistribute it in any way,
451 * subject to the following restrictions:
452 *
453 * 1. The author is not responsible for the consequences of use of
454 * this software, no matter how awful, even if they arise
455 * from defects in it.
456 *
457 * 2. The origin of this software must not be misrepresented, either
458 * by explicit claim or by omission.
459 *
460 * 3. Altered versions must be plainly marked as such, and must not
461 * be misrepresented (by explicit claim or omission) as being
462 * the original software.
463 *
464 * 4. This notice must not be removed or altered.
465 */
466
467 /*
468 * regcomp and regexec -- regsub and regerror are elsewhere
469 */
470
471 /*
472 * The first byte of the regexp internal "program" is actually this magic
473 * number; the start node begins in the second byte.
474 */
475 #define REGMAGIC 0234
476
477 /*
478 * The "internal use only" fields in regexp.h are present to pass info from
479 * compile to execute that permits the execute phase to run lots faster on
480 * simple cases. They are:
481 *
482 * regstart char that must begin a match; '\0' if none obvious
483 * reganch is the match anchored (at beginning-of-line only)?
484 * regmust string (pointer into program) that match must include, or NULL
485 * regmlen length of regmust string
486 *
487 * Regstart and reganch permit very fast decisions on suitable starting points
488 * for a match, cutting down the work a lot. Regmust permits fast rejection
489 * of lines that cannot possibly match. The regmust tests are costly enough
490 * that regcomp() supplies a regmust only if the r.e. contains something
491 * potentially expensive (at present, the only such thing detected is * or +
492 * at the start of the r.e., which can involve a lot of backup). Regmlen is
493 * supplied because the test in regexec() needs it and regcomp() is computing
494 * it anyway.
495 */
496
497 /*
498 * Structure for regexp "program". This is essentially a linear encoding
499 * of a nondeterministic finite-state machine (aka syntax charts or
500 * "railroad normal form" in parsing technology). Each node is an opcode
501 * plus a "next" pointer, possibly plus an operand. "Next" pointers of
502 * all nodes except BRANCH implement concatenation; a "next" pointer with
503 * a BRANCH on both ends of it is connecting two alternatives. (Here we
504 * have one of the subtle syntax dependencies: an individual BRANCH (as
505 * opposed to a collection of them) is never concatenated with anything
506 * because of operator precedence.) The operand of some types of node is
507 * a literal string; for others, it is a node leading into a sub-FSM. In
508 * particular, the operand of a BRANCH node is the first node of the branch.
509 * (NB this is *not* a tree structure: the tail of the branch connects
510 * to the thing following the set of BRANCHes.) The opcodes are:
511 */
512
513 /* definition number opnd? meaning */
514 #define END 0 /* no End of program. */
515 #define BOL 1 /* no Match beginning of line. */
516 #define EOL 2 /* no Match end of line. */
517 #define ANY 3 /* no Match any character. */
518 #define ANYOF 4 /* str Match any of these. */
519 #define ANYBUT 5 /* str Match any but one of these. */
520 #define BRANCH 6 /* node Match this, or the next..\&. */
521 #define BACK 7 /* no "next" ptr points backward. */
522 #define EXACTLY 8 /* str Match this string. */
523 #define NOTHING 9 /* no Match empty string. */
524 #define STAR 10 /* node Match this 0 or more times. */
525 #define PLUS 11 /* node Match this 1 or more times. */
526 #define OPEN 20 /* no Sub-RE starts here. */
527 /* OPEN+1 is number 1, etc. */
528 #define CLOSE 30 /* no Analogous to OPEN. */
529
530 /*
531 * Opcode notes:
532 *
533 * BRANCH The set of branches constituting a single choice are hooked
534 * together with their "next" pointers, since precedence prevents
535 * anything being concatenated to any individual branch. The
536 * "next" pointer of the last BRANCH in a choice points to the
537 * thing following the whole choice. This is also where the
538 * final "next" pointer of each individual branch points; each
539 * branch starts with the operand node of a BRANCH node.
540 *
541 * BACK Normal "next" pointers all implicitly point forward; BACK
542 * exists to make loop structures possible.
543 *
544 * STAR,PLUS '?', and complex '*' and '+', are implemented as circular
545 * BRANCH structures using BACK. Simple cases (one character
546 * per match) are implemented with STAR and PLUS for speed
547 * and to minimize recursive plunges.
548 *
549 * OPEN,CLOSE ...are numbered at compile time.
550 */
551
552 /*
553 * A node is one char of opcode followed by two chars of "next" pointer.
554 * "Next" pointers are stored as two 8-bit pieces, high order first. The
555 * value is a positive offset from the opcode of the node containing it.
556 * An operand, if any, simply follows the node. (Note that much of the
557 * code generation knows about this implicit relationship.)
558 *
559 * Using two bytes for the "next" pointer is vast overkill for most things,
560 * but allows patterns to get big without disasters.
561 */
562 #define OP(p) (*(p))
563 #define NEXT(p) (((*((p)+1)&0177)<<8) + (*((p)+2)&0377))
564 #define OPERAND(p) ((p) + 3)
565
566 /*
567 * Utility definitions.
568 */
569 #define ISREPN(c) ((c) == '*' || (c) == '+' || (c) == '?')
570 #define META "^$.[()|?+*\\"
571
572 /*
573 * Flags to be passed up and down.
574 */
575 #define HASWIDTH 01 /* Known never to match null string. */
576 #define SIMPLE 02 /* Simple enough to be STAR/PLUS operand. */
577 #define SPSTART 04 /* Starts with * or +. */
578 #define WORST 0 /* Worst case. */
579
580 /*
581 * Work-variable struct for regcomp().
582 */
583 struct comp {
584 char *regparse; /* Input-scan pointer. */
585 int regnpar; /* () count. */
586 char *regcode; /* Code-emit pointer; &regdummy = don't. */
587 char regdummy[3]; /* NOTHING, 0 next ptr */
588 long regsize; /* Code size. */
589 };
590 #define EMITTING(cp) ((cp)->regcode != (cp)->regdummy)
591
592 /*
593 * Forward declarations for regcomp()'s friends.
594 */
595 static char *reg(struct comp *cp, int paren, int *flagp);
596 static char *regbranch(struct comp *cp, int *flagp);
597 static char *regpiece(struct comp *cp, int *flagp);
598 static char *regatom(struct comp *cp, int *flagp);
599 static char *regnode(register struct comp *cp, char op);
600 static char *regnext(char *node);
601 static void regc(struct comp *cp, unsigned char c);
602 static void reginsert(struct comp *cp, char op, char *opnd);
603 static void regtail(struct comp *cp, char *p, char *val);
604 static void regoptail(struct comp *cp, char *p, char *val);
605 static char *regescape(struct comp *cp, char c);
606
607 /*
608 - regcomp - compile a regular expression into internal code
609 *
610 * We can't allocate space until we know how big the compiled form will be,
611 * but we can't compile it (and thus know how big it is) until we've got a
612 * place to put the code. So we cheat: we compile it twice, once with code
613 * generation turned off and size counting turned on, and once "for real".
614 * This also means that we don't allocate space until we are sure that the
615 * thing really will compile successfully, and we never have to move the
616 * code and thus invalidate pointers into it. (Note that it has to be in
617 * one piece because free() must be able to free it all.)
618 *
619 * Beware that the optimization-preparation code in here knows about some
620 * of the structure of the compiled regexp.
621 *
622 * Returns valid ptr on success.
623 * Throws NULL on internal errors, or if <exp> is invalid.
624 *
625 * Regular expressions with invalid syntax will fail to compile somewhere,
626 * generating an eslESYNTAX error with a terse but useful message.
627 *
628 */
629 static esl__regexp *
630 regcomp(const char *exp)
631 {
632 int status;
633 register esl__regexp *r = NULL;
634 register char *scan;
635 int flags;
636 struct comp co;
637
638 if (exp == NULL) ESL_XEXCEPTION(eslEINVAL, "NULL argument to regcomp");
639
640 /* First pass: determine size, legality. */
641 co.regparse = (char *)exp;
642 co.regnpar = 1;
643 co.regsize = 0L;
644 co.regdummy[0] = NOTHING;
645 co.regdummy[1] = co.regdummy[2] = 0;
646 co.regcode = co.regdummy;
647 regc(&co, REGMAGIC);
648 if (reg(&co, 0, &flags) == NULL) goto ERROR;
649
650 /* Small enough for pointer-storage convention? */
651 if (co.regsize >= 0x7fffL) /* Probably could be 0xffffL. */
652 ESL_XEXCEPTION(eslEMEM, "regexp too big");
653
654 /* Allocate space. */
655 ESL_ALLOC(r, sizeof(esl__regexp) + (size_t)co.regsize);
656
657 /* Second pass: emit code. */
658 co.regparse = (char *)exp;
659 co.regnpar = 1;
660 co.regcode = r->program;
661 regc(&co, REGMAGIC);
662 if (reg(&co, 0, &flags) == NULL) goto ERROR;
663
664 /* Dig out information for optimizations. */
665 r->regstart = '\0'; /* Worst-case defaults. */
666 r->reganch = 0;
667 r->regmust = NULL;
668 r->regmlen = 0;
669 scan = r->program+1; /* First BRANCH. */
670 if (OP(regnext(scan)) == END) { /* Only one top-level choice. */
671 scan = OPERAND(scan);
672
673 /* Starting-point info. */
674 if (OP(scan) == EXACTLY)
675 r->regstart = *OPERAND(scan);
676 else if (OP(scan) == BOL)
677 r->reganch = 1;
678
679 /*
680 * If there's something expensive in the r.e., find the
681 * longest literal string that must appear and make it the
682 * regmust. Resolve ties in favor of later strings, since
683 * the regstart check works with the beginning of the r.e.
684 * and avoiding duplication strengthens checking. Not a
685 * strong reason, but sufficient in the absence of others.
686 */
687 if (flags&SPSTART) {
688 register char *longest = NULL;
689 register size_t len = 0;
690
691 for (; scan != NULL; scan = regnext(scan))
692 if (OP(scan) == EXACTLY && strlen(OPERAND(scan)) >= len) {
693 longest = OPERAND(scan);
694 len = strlen(OPERAND(scan));
695 }
696 r->regmust = longest;
697 r->regmlen = (int)len;
698 }
699 }
700
701 return(r);
702
703 ERROR:
704 if (r != NULL) free(r);
705 return NULL;
706 }
707
708 /*
709 - reg - regular expression, i.e. main body or parenthesized thing
710 *
711 * Caller must absorb opening parenthesis.
712 *
713 * Combining parenthesis handling with the base level of regular expression
714 * is a trifle forced, but the need to tie the tails of the branches to what
715 * follows makes it hard to avoid.
716 */
717 static char *
718 reg(register struct comp *cp, int paren, int *flagp)
719 {
720 register char *ret = NULL; /* SRE: NULL init added to silence gcc */
721 register char *br;
722 register char *ender;
723 register int parno = 0; /* SRE: init added to silence gcc */
724 int flags;
725 int status;
726
727 *flagp = HASWIDTH; /* Tentatively. */
728
729 if (paren) {
730 /* Make an OPEN node. */
731 if (cp->regnpar >= ESL_REGEXP_NSUB)
732 ESL_XEXCEPTION(eslESYNTAX, "too many ()");
733 parno = cp->regnpar;
734 cp->regnpar++;
735 ret = regnode(cp, OPEN+parno);
736 }
737
738 /* Pick up the branches, linking them together. */
739 br = regbranch(cp, &flags);
740 if (br == NULL)
741 return(NULL);
742 if (paren)
743 regtail(cp, ret, br); /* OPEN -> first. */
744 else
745 ret = br;
746 *flagp &= ~(~flags&HASWIDTH); /* Clear bit if bit 0. */
747 *flagp |= flags&SPSTART;
748 while (*cp->regparse == '|') {
749 cp->regparse++;
750 br = regbranch(cp, &flags);
751 if (br == NULL)
752 return(NULL);
753 regtail(cp, ret, br); /* BRANCH -> BRANCH. */
754 *flagp &= ~(~flags&HASWIDTH);
755 *flagp |= flags&SPSTART;
756 }
757
758 /* Make a closing node, and hook it on the end. */
759 ender = regnode(cp, (paren) ? CLOSE+parno : END);
760 regtail(cp, ret, ender);
761
762 /* Hook the tails of the branches to the closing node. */
763 for (br = ret; br != NULL; br = regnext(br))
764 regoptail(cp, br, ender);
765
766 /* Check for proper termination. */
767 if (paren && *cp->regparse++ != ')') {
768 ESL_XEXCEPTION(eslESYNTAX, "unterminated ()");
769 } else if (!paren && *cp->regparse != '\0') {
770 if (*cp->regparse == ')') {
771 ESL_XEXCEPTION(eslESYNTAX, "unmatched ()");
772 } else
773 ESL_XEXCEPTION(eslECORRUPT, "internal error: junk on end");
774 /* NOTREACHED */
775 }
776 return(ret);
777
778 ERROR:
779 return (status == eslOK ? ret : NULL); // fake out: status always non-OK here, this is solely to use <status> and silence compiler warning
780 }
781
782 /*
783 - regbranch - one alternative of an | operator
784 *
785 * Implements the concatenation operator.
786 */
787 static char *
788 regbranch(register struct comp *cp, int *flagp)
789 {
790 register char *ret;
791 register char *chain;
792 register char *latest;
793 int flags;
794 register int c;
795
796 *flagp = WORST; /* Tentatively. */
797
798 ret = regnode(cp, BRANCH);
799 chain = NULL;
800 while ((c = *cp->regparse) != '\0' && c != '|' && c != ')') {
801 latest = regpiece(cp, &flags);
802 if (latest == NULL)
803 return(NULL);
804 *flagp |= flags&HASWIDTH;
805 if (chain == NULL) /* First piece. */
806 *flagp |= flags&SPSTART;
807 else
808 regtail(cp, chain, latest);
809 chain = latest;
810 }
811 if (chain == NULL) /* Loop ran zero times. */
812 (void) regnode(cp, NOTHING);
813
814 return(ret);
815 }
816
817 /*
818 - regpiece - something followed by possible [*+?]
819 *
820 * Note that the branching code sequences used for ? and the general cases
821 * of * and + are somewhat optimized: they use the same NOTHING node as
822 * both the endmarker for their branch list and the body of the last branch.
823 * It might seem that this node could be dispensed with entirely, but the
824 * endmarker role is not redundant.
825 *
826 * Returns valid ptr on success.
827 * Throws NULL on errors.
828 */
829 static char *
830 regpiece(register struct comp *cp, int *flagp)
831 {
832 register char *ret;
833 register char op;
834 register char *next;
835 int flags;
836 int status;
837
838 ret = regatom(cp, &flags);
839 if (ret == NULL)
840 return(NULL);
841
842 op = *cp->regparse;
843 if (!ISREPN(op)) {
844 *flagp = flags;
845 return(ret);
846 }
847
848 if (!(flags&HASWIDTH) && op != '?')
849 ESL_XEXCEPTION(eslESYNTAX, "*+ operand could be empty");
850 switch (op) {
851 case '*': *flagp = WORST|SPSTART; break;
852 case '+': *flagp = WORST|SPSTART|HASWIDTH; break;
853 case '?': *flagp = WORST; break;
854 }
855
856 if (op == '*' && (flags&SIMPLE))
857 reginsert(cp, STAR, ret);
858 else if (op == '*') {
859 /* Emit x* as (x&|), where & means "self". */
860 reginsert(cp, BRANCH, ret); /* Either x */
861 regoptail(cp, ret, regnode(cp, BACK)); /* and loop */
862 regoptail(cp, ret, ret); /* back */
863 regtail(cp, ret, regnode(cp, BRANCH)); /* or */
864 regtail(cp, ret, regnode(cp, NOTHING)); /* null. */
865 } else if (op == '+' && (flags&SIMPLE))
866 reginsert(cp, PLUS, ret);
867 else if (op == '+') {
868 /* Emit x+ as x(&|), where & means "self". */
869 next = regnode(cp, BRANCH); /* Either */
870 regtail(cp, ret, next);
871 regtail(cp, regnode(cp, BACK), ret); /* loop back */
872 regtail(cp, next, regnode(cp, BRANCH)); /* or */
873 regtail(cp, ret, regnode(cp, NOTHING)); /* null. */
874 } else if (op == '?') {
875 /* Emit x? as (x|) */
876 reginsert(cp, BRANCH, ret); /* Either x */
877 regtail(cp, ret, regnode(cp, BRANCH)); /* or */
878 next = regnode(cp, NOTHING); /* null. */
879 regtail(cp, ret, next);
880 regoptail(cp, ret, next);
881 }
882 cp->regparse++;
883 if (ISREPN(*cp->regparse))
884 ESL_XEXCEPTION(eslESYNTAX, "nested *?+");
885
886 return(ret);
887
888 ERROR:
889 return (status == eslOK ? ret : NULL); // status is not OK; this construction serves solely to silence compiler warning about unused <status>
890 }
891
892 /*
893 - regatom - the lowest level
894 *
895 * Optimization: gobbles an entire sequence of ordinary characters so that
896 * it can turn them into a single node, which is smaller to store and
897 * faster to run. Backslashed characters are exceptions, each becoming a
898 * separate node; the code is simpler that way and it's not worth fixing.
899 *
900 * Returns valid ptr on success.
901 * Throws NULL on an error.
902 */
903 static char *
904 regatom(register struct comp *cp, int *flagp)
905 {
906 register char *ret = NULL;
907 int flags;
908 int status;
909
910 *flagp = WORST; /* Tentatively. */
911
912 switch (*cp->regparse++) {
913 case '^':
914 ret = regnode(cp, BOL);
915 break;
916 case '$':
917 ret = regnode(cp, EOL);
918 break;
919 case '.':
920 ret = regnode(cp, ANY);
921 *flagp |= HASWIDTH|SIMPLE;
922 break;
923 case '[': {
924 register int range;
925 register int rangeend;
926 register int c;
927
928 if (*cp->regparse == '^') { /* Complement of range. */
929 ret = regnode(cp, ANYBUT);
930 cp->regparse++;
931 } else
932 ret = regnode(cp, ANYOF);
933 if ((c = *cp->regparse) == ']' || c == '-') {
934 regc(cp, c);
935 cp->regparse++;
936 }
937 while ((c = *cp->regparse++) != '\0' && c != ']') {
938 /* SRE: inserted code for \t, \n, \r, \f here:
939 * c is the \, and cp->regparse is an alphanumeric.
940 */
941 if (c == '\\') {
942 c = *cp->regparse++;
943 switch (c) {
944 case 'f': regc(cp, '\f'); break;
945 case 'n': regc(cp, '\n'); break;
946 case 'r': regc(cp, '\r'); break;
947 case 't': regc(cp, '\t'); break;
948 case '\\': regc(cp, '\\'); break;
949 default:
950 ESL_XEXCEPTION(eslESYNTAX, "Invalid \\ escape inside range operator");
951 break;
952 }
953 }/*end SRE*/
954 else if (c != '-')
955 regc(cp, c);
956 else if ((c = *cp->regparse) == ']' || c == '\0')
957 regc(cp, '-');
958 else {
959 range = (unsigned char)*(cp->regparse-2);
960 rangeend = (unsigned char)c;
961 if (range > rangeend)
962 ESL_XEXCEPTION(eslESYNTAX, "invalid [] range");
963 for (range++; range <= rangeend; range++)
964 regc(cp, range);
965 cp->regparse++;
966 }
967 }
968 regc(cp, '\0');
969 if (c != ']')
970 ESL_XEXCEPTION(eslESYNTAX, "unmatched []");
971 *flagp |= HASWIDTH|SIMPLE;
972 break;
973 }
974 case '(':
975 ret = reg(cp, 1, &flags);
976 if (ret == NULL)
977 return NULL;
978 *flagp |= flags&(HASWIDTH|SPSTART);
979 break;
980
981 case '\0':
982 case '|':
983 case ')':
984 /* supposed to be caught earlier */
985 ESL_XEXCEPTION(eslECORRUPT, "internal error: \\0|) unexpected");
986 /*NOTREACHED*/
987 break;
988
989 case '?':
990 case '+':
991 case '*':
992 ESL_XEXCEPTION(eslESYNTAX, "?+* follows nothing");
993 /*NOTREACHED*/
994 break;
995
996 case '\\':
997 if (*cp->regparse == '\0')
998 ESL_XEXCEPTION(eslESYNTAX, "trailing \\");
999
1000 if (! isalnum(*cp->regparse)) {
1001 ret = regnode(cp, EXACTLY); /* SRE: original Spencer code */
1002 regc(cp, *cp->regparse++);
1003 regc(cp, '\0');
1004 } else { /* SRE: my dropped in escape-code handling */
1005 ret = regescape(cp, *cp->regparse);
1006 }
1007 *flagp |= HASWIDTH|SIMPLE;
1008 break;
1009
1010 default: {
1011 register size_t len;
1012 register char ender;
1013
1014 cp->regparse--;
1015 len = strcspn(cp->regparse, META);
1016 if (len == 0)
1017 ESL_XEXCEPTION(eslECORRUPT, "strcspn 0");
1018 ender = *(cp->regparse+len);
1019 if (len > 1 && ISREPN(ender))
1020 len--; /* Back off clear of ?+* operand. */
1021 *flagp |= HASWIDTH;
1022 if (len == 1)
1023 *flagp |= SIMPLE;
1024 ret = regnode(cp, EXACTLY);
1025 for (; len > 0; len--)
1026 regc(cp, *cp->regparse++);
1027 regc(cp, '\0');
1028 break;
1029 }
1030 }
1031 return(ret);
1032
1033 ERROR:
1034 return (status == eslOK ? ret : NULL); // status is not OK. Construction serves to silence compiler warning about unused <status>.
1035 }
1036
1037 /*
1038 - regnode - emit a node
1039 */
1040 static char * /* Location. */
1041 regnode(register struct comp *cp, char op)
1042 {
1043 register char *const ret = cp->regcode;
1044 register char *ptr;
1045
1046 if (!EMITTING(cp)) {
1047 cp->regsize += 3;
1048 return(ret);
1049 }
1050
1051 ptr = ret;
1052 *ptr++ = op;
1053 *ptr++ = '\0'; /* Null next pointer. */
1054 *ptr++ = '\0';
1055 cp->regcode = ptr;
1056
1057 return(ret);
1058 }
1059
1060 /*
1061 - regc - emit (if appropriate) a byte of code
1062 */
1063 static void
1064 regc(register struct comp *cp, unsigned char b)
1065 {
1066 if (EMITTING(cp))
1067 *cp->regcode++ = b;
1068 else
1069 cp->regsize++;
1070 }
1071
1072 /*
1073 - reginsert - insert an operator in front of already-emitted operand
1074 *
1075 * Means relocating the operand.
1076 */
1077 static void
1078 reginsert(register struct comp *cp, char op, char *opnd)
1079 {
1080 register char *place;
1081
1082 if (!EMITTING(cp)) {
1083 cp->regsize += 3;
1084 return;
1085 }
1086
1087 (void) memmove(opnd+3, opnd, (size_t)(cp->regcode - opnd));
1088 cp->regcode += 3;
1089
1090 place = opnd; /* Op node, where operand used to be. */
1091 *place++ = op;
1092 *place++ = '\0';
1093 *place++ = '\0';
1094 return;
1095 }
1096
1097 /*
1098 - regtail - set the next-pointer at the end of a node chain
1099 */
1100 static void
1101 regtail(register struct comp *cp, char *p, char *val)
1102 {
1103 register char *scan;
1104 register char *temp;
1105 register int offset;
1106
1107 if (!EMITTING(cp))
1108 return;
1109
1110 /* Find last node. */
1111 for (scan = p; (temp = regnext(scan)) != NULL; scan = temp)
1112 continue;
1113
1114 offset = (OP(scan) == BACK) ? scan - val : val - scan;
1115 *(scan+1) = (offset>>8)&0177;
1116 *(scan+2) = offset&0377;
1117 return;
1118 }
1119
1120 /*
1121 - regoptail - regtail on operand of first argument; nop if operandless
1122 */
1123 static void
1124 regoptail(register struct comp *cp, char *p, char *val)
1125 {
1126 /* "Operandless" and "op != BRANCH" are synonymous in practice. */
1127 if (!EMITTING(cp) || OP(p) != BRANCH)
1128 return;
1129 regtail(cp, OPERAND(p), val);
1130 return;
1131 }
1132
1133 /*
1134 * regexec and friends
1135 */
1136
1137 /*
1138 * Work-variable struct for regexec().
1139 */
1140 struct exec {
1141 char *reginput; /* String-input pointer. */
1142 char *regbol; /* Beginning of input, for ^ check. */
1143 char **regstartp; /* Pointer to startp array. */
1144 char **regendp; /* Ditto for endp. */
1145 };
1146
1147 /*
1148 * Forwards.
1149 */
1150 static int regtry(struct exec *ep, esl__regexp *rp, char *string);
1151 static int regmatch(struct exec *ep, char *prog);
1152 static int regrepeat(struct exec *ep, char *node, size_t *ret_count);
1153 #ifdef DEBUG
1154 static int regnarrate = 0;
1155 static char *regprop(char *op);
1156 #endif
1157
1158 /*
1159 - regexec - match a regexp against a string
1160 *
1161 * Returns <eslOK> on match; <eslEOD> for no match.
1162 * Throws <eslEINCONCEIVABLE>,<eslECORRUPT> on internal errors.
1163 */
1164 static int
1165 regexec(register esl__regexp *prog, const char *str)
1166 {
1167 register char *string = (char *)str; /* avert const poisoning */
1168 register char *s;
1169 struct exec ex;
1170 int code;
1171
1172 /* Be paranoid. */
1173 if (prog == NULL || string == NULL)
1174 ESL_EXCEPTION(eslEINCONCEIVABLE, "NULL argument to regexec");
1175
1176 /* Check validity of program. */
1177 if ((unsigned char)*prog->program != REGMAGIC)
1178 ESL_EXCEPTION(eslECORRUPT, "corrupted regexp");
1179
1180 /* If there is a "must appear" string, look for it. */
1181 if (prog->regmust != NULL && strstr(string, prog->regmust) == NULL)
1182 return eslEOD;
1183
1184 /* Mark beginning of line for ^ . */
1185 ex.regbol = string;
1186 ex.regstartp = prog->startp;
1187 ex.regendp = prog->endp;
1188
1189 /* Simplest case: anchored match need be tried only once. */
1190 if (prog->reganch)
1191 return(regtry(&ex, prog, string));
1192
1193 /* Messy cases: unanchored match. */
1194 if (prog->regstart != '\0') {
1195 /* We know what char it must start with. */
1196 for (s = string; s != NULL; s = strchr(s+1, prog->regstart))
1197 if ((code = regtry(&ex, prog, s)) != eslEOD)
1198 return code; /* match, or throwing an error up */
1199 return eslEOD; /* no match in string */
1200 } else {
1201 /* We don't -- general case. */
1202 for (s = string; *s != '\0'; s++)
1203 if ((code = regtry(&ex, prog, s)) != eslEOD)
1204 return code; /* match, or throw an error up */
1205 return eslEOD; /* reached end of string, no match */
1206 }
1207 /* NOTREACHED */
1208 }
1209
1210 /*
1211 - regtry - try match at specific point
1212 *
1213 * Returns <eslOK> on success, <eslEOD> failure.
1214 * Throws <ESL_CORRUPT>,<eslEINCONCEIVABLE> on internal errors.
1215 */
1216 static int
1217 regtry(register struct exec *ep, esl__regexp *prog, char *string)
1218 {
1219 register int i;
1220 register char **stp;
1221 register char **enp;
1222 int code;
1223
1224 ep->reginput = string;
1225
1226 stp = prog->startp;
1227 enp = prog->endp;
1228 for (i = ESL_REGEXP_NSUB; i > 0; i--) {
1229 *stp++ = NULL;
1230 *enp++ = NULL;
1231 }
1232 if ((code = regmatch(ep, prog->program + 1)) == eslOK) {
1233 prog->startp[0] = string;
1234 prog->endp[0] = ep->reginput;
1235 return eslOK;
1236 } else
1237 return code; /* eslEOD for normal non-match; or other thrown codes */
1238 }
1239
1240 /*
1241 - regmatch - main matching routine
1242 *
1243 * Conceptually the strategy is simple: check to see whether the current
1244 * node matches, call self recursively to see whether the rest matches,
1245 * and then act accordingly. In practice we make some effort to avoid
1246 * recursion, in particular by going through "ordinary" nodes (that don't
1247 * need to know whether the rest of the match failed) by a loop instead of
1248 * by recursion.
1249 *
1250 * Returns <eslOK> on success, <eslEOD> on failure.
1251 * Throws <eslECORRUPT>,<eslEINCONCEIVABLE> on internal errors.
1252 */
1253 static int
1254 regmatch(register struct exec *ep, char *prog)
1255 {
1256 register char *scan; /* Current node. */
1257 char *next; /* Next node. */
1258 int code; /* error code */
1259
1260 #ifdef DEBUG
1261 if (prog != NULL && regnarrate)
1262 fprintf(stderr, "%s(\n", regprop(prog));
1263 #endif
1264 for (scan = prog; scan != NULL; scan = next) {
1265 #ifdef DEBUG
1266 if (regnarrate)
1267 fprintf(stderr, "%s...\n", regprop(scan));
1268 #endif
1269 next = regnext(scan);
1270
1271 switch (OP(scan)) {
1272 case BOL:
1273 if (ep->reginput != ep->regbol)
1274 return eslEOD;
1275 break;
1276 case EOL:
1277 if (*ep->reginput != '\0')
1278 return eslEOD;
1279 break;
1280 case ANY:
1281 if (*ep->reginput == '\0')
1282 return eslEOD;
1283 ep->reginput++;
1284 break;
1285 case EXACTLY: {
1286 register size_t len;
1287 register char *const opnd = OPERAND(scan);
1288
1289 /* Inline the first character, for speed. */
1290 if (*opnd != *ep->reginput)
1291 return eslEOD;
1292 len = strlen(opnd);
1293 if (len > 1 && strncmp(opnd, ep->reginput, len) != 0)
1294 return eslEOD;
1295 ep->reginput += len;
1296 break;
1297 }
1298 case ANYOF:
1299 if (*ep->reginput == '\0' ||
1300 strchr(OPERAND(scan), *ep->reginput) == NULL)
1301 return eslEOD;
1302 ep->reginput++;
1303 break;
1304 case ANYBUT:
1305 if (*ep->reginput == '\0' ||
1306 strchr(OPERAND(scan), *ep->reginput) != NULL)
1307 return eslEOD;
1308 ep->reginput++;
1309 break;
1310 case NOTHING:
1311 break;
1312 case BACK:
1313 break;
1314 case OPEN+1: case OPEN+2: case OPEN+3:
1315 case OPEN+4: case OPEN+5: case OPEN+6:
1316 case OPEN+7: case OPEN+8: case OPEN+9: {
1317 register const int no = OP(scan) - OPEN;
1318 register char *const input = ep->reginput;
1319
1320 if ((code = regmatch(ep, next)) == eslOK) {
1321 /*
1322 * Don't set startp if some later
1323 * invocation of the same parentheses
1324 * already has.
1325 */
1326 if (ep->regstartp[no] == NULL)
1327 ep->regstartp[no] = input;
1328 return eslOK;
1329 } else
1330 return code; /* usually eslEOD, except on error */
1331 /*NOTREACHED*/
1332 break;
1333 }
1334 case CLOSE+1: case CLOSE+2: case CLOSE+3:
1335 case CLOSE+4: case CLOSE+5: case CLOSE+6:
1336 case CLOSE+7: case CLOSE+8: case CLOSE+9: {
1337 register const int no = OP(scan) - CLOSE;
1338 register char *const input = ep->reginput;
1339
1340 if ((code = regmatch(ep, next)) == eslOK) {
1341 /*
1342 * Don't set endp if some later
1343 * invocation of the same parentheses
1344 * already has.
1345 */
1346 if (ep->regendp[no] == NULL)
1347 ep->regendp[no] = input;
1348 return eslOK;
1349 } else
1350 return code; /* usually eslEOD, except on error */
1351 /*NOTREACHED*/
1352 break;
1353 }
1354 case BRANCH: {
1355 register char *const save = ep->reginput;
1356
1357 if (OP(next) != BRANCH) /* No choice. */
1358 next = OPERAND(scan); /* Avoid recursion. */
1359 else {
1360 while (OP(scan) == BRANCH) {
1361 if ((code = regmatch(ep, OPERAND(scan))) != eslEOD)
1362 return code; /* usually eslOK, but also a thrown error*/
1363 ep->reginput = save;
1364 scan = regnext(scan);
1365 }
1366 return eslEOD;
1367 /*NOTREACHED*/
1368 }
1369 break;
1370 }
1371 case STAR: case PLUS: {
1372 register const char nextch =
1373 (OP(next) == EXACTLY) ? *OPERAND(next) : '\0';
1374 register char *const save = ep->reginput;
1375 register const size_t min = (OP(scan) == STAR) ? 0 : 1;
1376 size_t no;
1377
1378 if (regrepeat(ep, OPERAND(scan), &no) != eslOK) return eslEINCONCEIVABLE;
1379 for (++no; no > min; no--) {
1380 ep->reginput = save + no - 1;
1381 /* If it could work, try it. */
1382 if (nextch == '\0' || *ep->reginput == nextch)
1383 if (regmatch(ep, next) == eslOK)
1384 return eslOK;
1385 }
1386 return eslEOD;
1387 /*NOTREACHED*/
1388 break;
1389 }
1390 case END:
1391 return eslOK; /* Success! */
1392 break;
1393 default:
1394 ESL_EXCEPTION(eslECORRUPT, "regexp corruption");
1395 /*NOTREACHED*/
1396 break;
1397 }
1398 }
1399
1400 /*
1401 * We get here only if there's trouble -- normally "case END" is
1402 * the terminating point.
1403 */
1404 ESL_EXCEPTION(eslECORRUPT, "corrupted pointers");
1405 }
1406
1407 /*
1408 - regrepeat - report how many times something simple would match,
1409 * via <ret_result>
1410 * Returns <eslOK> on success.
1411 * Throws <eslEINCONCEIVABLE> - if node isn't a repeating one.
1412 */
1413 static int
1414 regrepeat(register struct exec *ep, char *node, size_t *ret_count)
1415 {
1416 register size_t count;
1417 register char *scan;
1418 register char ch;
1419
1420 switch (OP(node)) {
1421 case ANY:
1422 *ret_count = strlen(ep->reginput);
1423 return eslOK;
1424 case EXACTLY:
1425 ch = *OPERAND(node);
1426 count = 0;
1427 for (scan = ep->reginput; *scan == ch; scan++)
1428 count++;
1429 *ret_count = count;
1430 return eslOK;
1431 /*NOTREACHED*/
1432 break;
1433 case ANYOF:
1434 *ret_count = strspn(ep->reginput, OPERAND(node));
1435 return eslOK;
1436 /*NOTREACHED*/
1437 break;
1438 case ANYBUT:
1439 *ret_count = strcspn(ep->reginput, OPERAND(node));
1440 return eslOK;
1441 /*NOTREACHED*/
1442 break;
1443 default: /* Oh dear. Called inappropriately. */
1444 ESL_EXCEPTION(eslEINCONCEIVABLE, "bad call of regrepeat");
1445 /*NOTREACHED*/
1446 break;
1447 }
1448 /* NOTREACHED */
1449 return eslEINCONCEIVABLE;
1450 }
1451
1452 /*
1453 - regnext - dig the "next" pointer out of a node
1454 */
1455 static char *
1456 regnext(register char *p)
1457 {
1458 register const int offset = NEXT(p);
1459
1460 if (offset == 0)
1461 return(NULL);
1462
1463 return((OP(p) == BACK) ? p-offset : p+offset);
1464 }
1465
1466 #ifdef DEBUG
1467 /*
1468 - regdump - dump a regexp onto stdout in vaguely comprehensible form
1469 */
1470 static void
1471 regdump(esl__regexp *r)
1472 {
1473 register char *s;
1474 register char op = EXACTLY; /* Arbitrary non-END op. */
1475 register char *next;
1476
1477
1478 s = r->program + 1;
1479 while (op != END) { /* While that wasn't END last time... */
1480 op = OP(s);
1481 printf("%2d%s", s-r->program, regprop(s)); /* Where, what. */
1482 next = regnext(s);
1483 if (next == NULL) /* Next ptr. */
1484 printf("(0)");
1485 else
1486 printf("(%d)", (s-r->program)+(next-s));
1487 s += 3;
1488 if (op == ANYOF || op == ANYBUT || op == EXACTLY) {
1489 /* Literal string, where present. */
1490 while (*s != '\0') {
1491 putchar(*s);
1492 s++;
1493 }
1494 s++;
1495 }
1496 putchar('\n');
1497 }
1498
1499 /* Header fields of interest. */
1500 if (r->regstart != '\0')
1501 printf("start `%c' ", r->regstart);
1502 if (r->reganch)
1503 printf("anchored ");
1504 if (r->regmust != NULL)
1505 printf("must have \"%s\"", r->regmust);
1506 printf("\n");
1507 }
1508
1509 /*
1510 - regprop - printable representation of opcode
1511 */
1512 static char *
1513 regprop(char *op)
1514 {
1515 register char *p;
1516 static char buf[50]; // the alloc size of 50 is repeated in snprintf()'s below
1517
1518 (void) strcpy(buf, ":");
1519
1520 switch (OP(op)) {
1521 case BOL:
1522 p = "BOL";
1523 break;
1524 case EOL:
1525 p = "EOL";
1526 break;
1527 case ANY:
1528 p = "ANY";
1529 break;
1530 case ANYOF:
1531 p = "ANYOF";
1532 break;
1533 case ANYBUT:
1534 p = "ANYBUT";
1535 break;
1536 case BRANCH:
1537 p = "BRANCH";
1538 break;
1539 case EXACTLY:
1540 p = "EXACTLY";
1541 break;
1542 case NOTHING:
1543 p = "NOTHING";
1544 break;
1545 case BACK:
1546 p = "BACK";
1547 break;
1548 case END:
1549 p = "END";
1550 break;
1551 case OPEN+1:
1552 case OPEN+2:
1553 case OPEN+3:
1554 case OPEN+4:
1555 case OPEN+5:
1556 case OPEN+6:
1557 case OPEN+7:
1558 case OPEN+8:
1559 case OPEN+9:
1560 snprintf(buf+strlen(buf), 50-strlen(buf), "OPEN%d", OP(op)-OPEN); // 50 is the allocated size of buf
1561 p = NULL;
1562 break;
1563 case CLOSE+1:
1564 case CLOSE+2:
1565 case CLOSE+3:
1566 case CLOSE+4:
1567 case CLOSE+5:
1568 case CLOSE+6:
1569 case CLOSE+7:
1570 case CLOSE+8:
1571 case CLOSE+9:
1572 snprintf(buf+strlen(buf), 50-strlen(buf), "CLOSE%d", OP(op)-CLOSE);
1573 p = NULL;
1574 break;
1575 case STAR:
1576 p = "STAR";
1577 break;
1578 case PLUS:
1579 p = "PLUS";
1580 break;
1581 default:
1582 p = "[corrupted!]";
1583 break;
1584 }
1585 if (p != NULL)
1586 (void) strcat(buf, p);
1587 return(buf);
1588 }
1589 #endif /*DEBUG*/
1590
1591
1592 /* SRE: regsub() currently disabled; it is useful, but currently
1593 * unused. ifdef'ing it out silences zealous compiler warnings */
1594 #if 0
1595 /*
1596 - regsub - perform substitutions after a regexp match
1597 *
1598 * Returns <eslOK> on success.
1599 * Throws <eslEINCONCEIVABLE>, <eslECORRUPT> on internal errors.
1600 */
1601 static int
1602 regsub(const esl__regexp *rp, const char *source, char *dest)
1603 {
1604 register esl__regexp * const prog = (esl__regexp *)rp;
1605 register char *src = (char *)source;
1606 register char *dst = dest;
1607 register char c;
1608 register int no;
1609 register size_t len;
1610
1611 if (prog == NULL || source == NULL || dest == NULL)
1612 ESL_EXCEPTION(eslEINCONCEIVABLE, "NULL parameter to regsub");
1613
1614 if ((unsigned char)*(prog->program) != REGMAGIC)
1615 ESL_EXCEPTION(eslECORRUPT, "damaged regexp");
1616
1617 while ((c = *src++) != '\0') {
1618 if (c == '&')
1619 no = 0;
1620 else if (c == '\\' && isdigit((int) (*src)))
1621 no = *src++ - '0';
1622 else
1623 no = -1;
1624
1625 if (no < 0) { /* Ordinary character. */
1626 if (c == '\\' && (*src == '\\' || *src == '&'))
1627 c = *src++;
1628 *dst++ = c;
1629 } else if (prog->startp[no] != NULL && prog->endp[no] != NULL &&
1630 prog->endp[no] > prog->startp[no]) {
1631 len = prog->endp[no] - prog->startp[no];
1632 (void) strncpy(dst, prog->startp[no], len);
1633 dst += len;
1634 if (*(dst-1) == '\0') /* strncpy hit NUL. */
1635 ESL_EXCEPTION(eslECORRUPT, "damaged match string");
1636 }
1637 }
1638 *dst++ = '\0';
1639 return eslOK;
1640 }
1641 #endif /* regsub() currently disabled */
1642 /*============= end of Spencer's copyrighted regexp code =============================*/
1643
1644
1645
1646 /*****************************************************************
1647 * 3. My extensions to the Spencer code
1648 *****************************************************************/
1649
1650 /* Spencer's code originally handled a backslashed alphanum
1651 * like \t as t: in regatom(), the logic was:
1652 * ret = regnode(cp, EXACTLY);
1653 * regc(cp, *cp->regparse++);
1654 * regc(cp, '\0');
1655 * Here we provide a drop-in replacement for these lines.
1656 * We create an EXACTLY node for escapes, and a ANYBUT
1657 * or ANYOF node for character classes. Then
1658 * instead of pushing the char *cp->regparse onto the machine
1659 * and incrementing cp->regparse, we interpret an alphanumeric
1660 * character as an escape code, push one or more appropriate
1661 * chars onto the machine, and advance regparse,
1662 * before returning control to Spencer.
1663 *
1664 * that is: cp->regparse points to c when we come in,
1665 * and it's an alphanumeric following a \. On return,
1666 * we've advanced cp->regparse by one.
1667 */
1668 static char *
1669 regescape(struct comp *cp, char c)
1670 {
1671 char *ret = NULL;
1672 char x;
1673 int status;
1674
1675 switch (c) {
1676 /* escapes: */
1677 case 'f': ret = regnode(cp, EXACTLY); regc(cp, '\f'); break;
1678 case 'n': ret = regnode(cp, EXACTLY); regc(cp, '\n'); break;
1679 case 'r': ret = regnode(cp, EXACTLY); regc(cp, '\r'); break;
1680 case 't': ret = regnode(cp, EXACTLY); regc(cp, '\t'); break;
1681
1682 /* character classes: */
1683 case 'd':
1684 ret = regnode(cp, ANYOF);
1685 for (x = '0'; x <= '9'; x++)
1686 regc(cp, x);
1687 break;
1688
1689 case 'D':
1690 ret = regnode(cp, ANYBUT);
1691 for (x = '0'; x <= '9'; x++) regc(cp, x);
1692 break;
1693
1694 case 'w':
1695 ret = regnode(cp, ANYOF);
1696 for (x = '0'; x <= '9'; x++) regc(cp, x);
1697 for (x = 'a'; x <= 'z'; x++) regc(cp, x);
1698 for (x = 'A'; x <= 'Z'; x++) regc(cp, x);
1699 regc(cp, '_');
1700 break;
1701
1702 case 'W':
1703 ret = regnode(cp, ANYBUT);
1704 for (x = '0'; x <= '9'; x++) regc(cp, x);
1705 for (x = 'a'; x <= 'z'; x++) regc(cp, x);
1706 for (x = 'A'; x <= 'Z'; x++) regc(cp, x);
1707 regc(cp, '_');
1708 break;
1709
1710 case 's':
1711 ret = regnode(cp, ANYOF);
1712 regc(cp, ' ');
1713 regc(cp, '\t');
1714 regc(cp, '\n');
1715 regc(cp, '\r');
1716 regc(cp, '\f');
1717 break;
1718
1719 case 'S':
1720 ret = regnode(cp, ANYBUT);
1721 regc(cp, ' ');
1722 regc(cp, '\t');
1723 regc(cp, '\n');
1724 regc(cp, '\r');
1725 regc(cp, '\f');
1726 break;
1727
1728 default:
1729 ESL_XEXCEPTION(eslESYNTAX, "invalid \\ escape code");
1730 /*NOTREACHED*/
1731 break;
1732 }
1733
1734 regc(cp, '\0');
1735 cp->regparse++;
1736 return ret;
1737
1738 ERROR:
1739 return (status == eslOK ? ret : NULL); // status is not OK; construction serves to silence compiler warning about unused <status>
1740 }
1741
1742
1743 /*****************************************************************
1744 * 4. Unit tests
1745 *****************************************************************/
1746 #ifdef eslREGEXP_TESTDRIVE
1747
1748 static void
1749 utest_basic_ops(void)
1750 {
1751 char msg[] = "esl_regexp basic_ops test failed";
1752 ESL_REGEXP *m = esl_regexp_Create();
1753 char string[] = "aaafoobarfoooobazfo..aaa"; // positive
1754 char str2[] = "aaafoxbaxfoxoobaxfo..aaa"; // negative
1755 char *s;
1756 char buf[64];
1757 int status;
1758 int i,j;
1759 int n;
1760
1761 /* esl_regexp_Match() with a new pattern */
1762 if (esl_regexp_Match(m, "foo", str2) != eslEOD) esl_fatal(msg); // shouldn't match
1763 if (esl_regexp_Match(m, "foo", string) != eslOK) esl_fatal(msg); // should match
1764 esl_regexp_SubmatchCoords(m, string, 0, &i, &j);
1765 if (i != 3 || j != 5) esl_fatal(msg);
1766 s = esl_regexp_SubmatchDup(m, 0); if (strcmp(s, "foo") != 0) esl_fatal(msg);
1767 esl_regexp_SubmatchCopy(m, 0, buf, 64); if (strcmp(buf, "foo") != 0) esl_fatal(msg);
1768 free(s);
1769
1770 /* esl_regexp_Match() re-using the previous pattern */
1771 if (esl_regexp_Match(m, NULL, str2) != eslEOD) esl_fatal(msg);
1772 if (esl_regexp_Match(m, NULL, string) != eslOK) esl_fatal(msg);
1773 esl_regexp_SubmatchCoords(m, string, 0, &i, &j);
1774 if (i != 3 || j != 5) esl_fatal(msg);
1775
1776 /* test all the metacharacters in one pattern;
1777 * and token 2 extraction grabs "oobaz" 13..17
1778 */
1779 esl_regexp_Compile(m, "^aaaa*(foo|bar|baz)+([aboz]+).o\\.[^a-z]aaa?$");
1780 if (esl_regexp_Match(m, NULL, str2) != eslEOD) esl_fatal(msg);
1781 if (esl_regexp_Match(m, NULL, string) != eslOK) esl_fatal(msg);
1782 esl_regexp_SubmatchCoords(m, string, 2, &i, &j);
1783 if (i != 12 || j != 16) esl_fatal(msg);
1784 s = esl_regexp_SubmatchDup(m, 2);
1785 if (strcmp(s, "oobaz") != 0) esl_fatal(msg);
1786 free(s);
1787
1788 /* test multiple matching:
1789 * this pattern hits five times in the sequence, w/
1790 * variations on foo.
1791 */
1792 esl_regexp_Compile(m, "bar|foo*|baz");
1793 s = string;
1794 n = 0;
1795 while ((status = esl_regexp_MultipleMatches(m, &s)) == eslOK)
1796 {
1797 n++;
1798 esl_regexp_SubmatchCopy(m, 0, buf, 64);
1799 if ((n == 1 && strcmp(buf, "foo") != 0) ||
1800 (n == 2 && strcmp(buf, "bar") != 0) ||
1801 (n == 3 && strcmp(buf, "foooo") != 0) ||
1802 (n == 4 && strcmp(buf, "baz") != 0) ||
1803 (n == 5 && strcmp(buf, "fo") != 0))
1804 esl_fatal(msg);
1805 }
1806 if (n != 5) esl_fatal(msg);
1807 esl_regexp_Destroy(m);
1808 }
1809 #endif /*eslREGEXP_TESTDRIVE*/
1810
1811 /*****************************************************************
1812 * 5. Test driver
1813 *****************************************************************/
1814
1815 #ifdef eslREGEXP_TESTDRIVE
1816 #include <esl_config.h>
1817
1818 #include <stdio.h>
1819
1820 #include "easel.h"
1821 #include "esl_getopts.h"
1822
1823 static ESL_OPTIONS options[] = {
1824 /* name type default env range togs reqs incomp help docgrp */
1825 { "-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show help and usage", 0},
1826 { 0,0,0,0,0,0,0,0,0,0},
1827 };
1828 static char usage[] = "[-options]";
1829 static char banner[] = "test driver for regexp module";
1830
1831 int
1832 main(int argc, char **argv)
1833 {
1834 ESL_GETOPTS *go = esl_getopts_CreateDefaultApp(options, 0, argc, argv, banner, usage);
1835
1836 fprintf(stderr, "## %s\n", argv[0]);
1837
1838 utest_basic_ops();
1839
1840 fprintf(stderr, "# status = ok\n");
1841
1842 esl_getopts_Destroy(go);
1843 return 0;
1844 }
1845 #endif /*eslREGEXP_TESTDRIVE*/
1846
1847
1848 /*****************************************************************
1849 * 6. Examples
1850 *****************************************************************/
1851
1852 #ifdef eslREGEXP_EXAMPLE
1853 /* Single match example.
1854 * Find first match of <pattern> in <string>;
1855 * print coords of complete match.
1856 *
1857 * gcc -g -Wall -o example1 -I. -DeslREGEXP_EXAMPLE1 regexp.c easel.c
1858 * ./example1 <pattern> <string>
1859 */
1860
1861 #include <stdio.h> /* for printf() */
1862 #include "easel.h"
1863 #include "esl_regexp.h"
1864
1865 int
1866 main(int argc, char **argv)
1867 {
1868 ESL_REGEXP *m;
1869 char *pattern;
1870 char *string;
1871 int status;
1872 int i,j;
1873
1874 pattern = argv[1];
1875 string = argv[2];
1876
1877 m = esl_regexp_Create();
1878
1879 status = esl_regexp_Match(m, pattern, string);
1880
1881 if (status == eslOK)
1882 {
1883 esl_regexp_SubmatchCoords(m, string, 0, &i, &j);
1884 printf("Pattern matches string at positions %d..%d\n", i+1, j+1);
1885 }
1886 else if (status == eslEOD)
1887 {
1888 printf("Pattern does not match in string.\n");
1889 }
1890
1891 esl_regexp_Destroy(m);
1892 exit(0);
1893 }
1894 #endif /* eslREGEXP_EXAMPLE*/
1895
1896
1897 #ifdef eslREGEXP_EXAMPLE2
1898 /* Multiple match example.
1899 * Matches <pattern> against <string> multiple times, until
1900 * no more matches are found.
1901 *
1902 * gcc -g -Wall -o example2 -I. -DeslREGEXP_EXAMPLE2 regexp.c easel.c
1903 * ./example2 <pattern> <string>
1904 */
1905
1906 #include <stdio.h> /* for printf() */
1907 #include "easel.h"
1908 #include "esl_regexp.h"
1909
1910 int
1911 main(int argc, char **argv)
1912 {
1913 char *pattern;
1914 char *string;
1915 ESL_REGEXP *m;
1916 int status;
1917 int i,j;
1918 char *s;
1919 char buf[256];
1920 int n = 0;
1921
1922 pattern = argv[1];
1923 string = argv[2];
1924
1925 m = esl_regexp_Create();
1926
1927 esl_regexp_Compile(m, pattern);
1928 s = string;
1929 while ((status = esl_regexp_MultipleMatches(m, &s)) == eslOK)
1930 {
1931 n++;
1932 esl_regexp_SubmatchCoords(m, string, 0, &i, &j);
1933 esl_regexp_SubmatchCopy(m, 0, buf, 256);
1934
1935 printf("Match #%d: positions %d..%d sequence: %s\n", n, i+1, j+1, buf);
1936 }
1937
1938 esl_regexp_Destroy(m);
1939 exit(0);
1940 }
1941 #endif /* eslREGEXP_EXAMPLE2 */
1942
1943
1944 #ifdef eslREGEXP_EXAMPLE3
1945
1946 /* Token parsing example.
1947 * Match a <pattern> that contains <ntok> ()-tokens
1948 * against <string>; parse out the submatches to each () token.
1949 *
1950 * gcc -g -Wall -o example3 -I. -DeslREGEXP_EXAMPLE3 regexp.c easel.c
1951 * ./example3 <pattern> <string> <ntok>
1952 */
1953 #include <stdlib.h> /* for atoi() */
1954 #include <stdio.h> /* for printf() */
1955 #include "easel.h"
1956 #include "esl_regexp.h"
1957
1958 int
1959 main(int argc, char **argv)
1960 {
1961 char *pattern;
1962 char *string;
1963 int ntok;
1964 ESL_REGEXP *m;
1965 int status;
1966 int i,j;
1967 char *token;
1968 int n;
1969
1970 pattern = argv[1];
1971 string = argv[2];
1972 ntok = atoi(argv[3]);
1973
1974 m = esl_regexp_Create();
1975
1976 status = esl_regexp_Match(m, pattern, string);
1977 if (status == eslOK)
1978 {
1979 for (n = 1; n <= ntok; n++)
1980 {
1981 esl_regexp_SubmatchCoords(m, string, n, &i, &j);
1982 token = esl_regexp_SubmatchDup(m, n);
1983 printf("token #%d: %d..%d, %s\n", n, i+1, j+1, token);
1984 free(token);
1985 }
1986 }
1987 esl_regexp_Destroy(m);
1988 exit(0);
1989 }
1990 #endif /*eslREGEXP_EXAMPLE3*/
1991
1992
1993