home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Usenet 1994 October
/
usenetsourcesnewsgroupsinfomagicoctober1994disk2.iso
/
unix
/
volume24
/
gnudiff1.15
/
part07
/
regex.c1
Wrap
Text File
|
1991-03-05
|
45KB
|
1,505 lines
/* Extended regular expression matching and search library.
Copyright (C) 1985, 1989-90 Free Software Foundation, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 1, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */
/* To test, compile with -Dtest. This Dtestable feature turns this into
a self-contained program which reads a pattern, describes how it
compiles, then reads a string and searches for it.
On the other hand, if you compile with both -Dtest and -Dcanned you
can run some tests we've already thought of. */
#ifdef emacs
/* The `emacs' switch turns on certain special matching commands
that make sense only in emacs. */
#include "config.h"
#include "lisp.h"
#include "buffer.h"
#include "syntax.h"
#else /* not emacs */
#if defined (USG) || defined (STDC_HEADERS)
#ifndef BSTRING
#include <string.h>
#define bcopy(s,d,n) memcpy((d),(s),(n))
#define bcmp(s1,s2,n) memcmp((s1),(s2),(n))
#define bzero(s,n) memset((s),0,(n))
#endif
#endif
#ifdef STDC_HEADERS
#include <stdlib.h>
#else
char *malloc ();
char *realloc ();
#endif
/* Make alloca work the best possible way. */
#ifdef __GNUC__
#define alloca __builtin_alloca
#else
#ifdef sparc
#include <alloca.h>
#else
char *alloca ();
#endif
#endif
/* Define the syntax stuff, so we can do the \<, \>, etc. */
/* This must be nonzero for the wordchar and notwordchar pattern
commands in re_match_2. */
#ifndef Sword
#define Sword 1
#endif
#define SYNTAX(c) re_syntax_table[c]
#ifdef SYNTAX_TABLE
char *re_syntax_table;
#else /* not SYNTAX_TABLE */
static char re_syntax_table[256];
static void
init_syntax_once ()
{
register int c;
static int done = 0;
if (done)
return;
bzero (re_syntax_table, sizeof re_syntax_table);
for (c = 'a'; c <= 'z'; c++)
re_syntax_table[c] = Sword;
for (c = 'A'; c <= 'Z'; c++)
re_syntax_table[c] = Sword;
for (c = '0'; c <= '9'; c++)
re_syntax_table[c] = Sword;
done = 1;
}
#endif /* SYNTAX_TABLE */
#endif /* emacs */
/* We write fatal error messages on standard error. */
#include <stdio.h>
/* isalpha(3) etc. are used for the character classes. */
#include <ctype.h>
/* Sequents are missing isgraph. */
#ifndef isgraph
#define isgraph(c) (isprint((c)) && !isspace((c)))
#endif
/* Get the interface, including the syntax bits. */
#include "regex.h"
/* These are the command codes that appear in compiled regular
expressions, one per byte. Some command codes are followed by
argument bytes. A command code can specify any interpretation
whatsoever for its arguments. Zero-bytes may appear in the compiled
regular expression.
The value of `exactn' is needed in search.c (search_buffer) in emacs.
So regex.h defines a symbol `RE_EXACTN_VALUE' to be 1; the value of
`exactn' we use here must also be 1. */
enum regexpcode
{
unused=0,
exactn=1, /* Followed by one byte giving n, then by n literal bytes. */
begline, /* Fail unless at beginning of line. */
endline, /* Fail unless at end of line. */
jump, /* Followed by two bytes giving relative address to jump to. */
on_failure_jump, /* Followed by two bytes giving relative address of
place to resume at in case of failure. */
finalize_jump, /* Throw away latest failure point and then jump to
address. */
maybe_finalize_jump, /* Like jump but finalize if safe to do so.
This is used to jump back to the beginning
of a repeat. If the command that follows
this jump is clearly incompatible with the
one at the beginning of the repeat, such that
we can be sure that there is no use backtracking
out of repetitions already completed,
then we finalize. */
dummy_failure_jump, /* Jump, and push a dummy failure point. This
failure point will be thrown away if an attempt
is made to use it for a failure. A + construct
makes this before the first repeat. Also
use it as an intermediary kind of jump when
compiling an or construct. */
succeed_n, /* Used like on_failure_jump except has to succeed n times;
then gets turned into an on_failure_jump. The relative
address following it is useless until then. The
address is followed by two bytes containing n. */
jump_n, /* Similar to jump, but jump n times only; also the relative
address following is in turn followed by yet two more bytes
containing n. */
set_number_at, /* Set the following relative location to the
subsequent number. */
anychar, /* Matches any (more or less) one character. */
charset, /* Matches any one char belonging to specified set.
First following byte is number of bitmap bytes.
Then come bytes for a bitmap saying which chars are in.
Bits in each byte are ordered low-bit-first.
A character is in the set if its bit is 1.
A character too large to have a bit in the map
is automatically not in the set. */
charset_not, /* Same parameters as charset, but match any character
that is not one of those specified. */
start_memory, /* Start remembering the text that is matched, for
storing in a memory register. Followed by one
byte containing the register number. Register numbers
must be in the range 0 through RE_NREGS. */
stop_memory, /* Stop remembering the text that is matched
and store it in a memory register. Followed by
one byte containing the register number. Register
numbers must be in the range 0 through RE_NREGS. */
duplicate, /* Match a duplicate of something remembered.
Followed by one byte containing the index of the memory
register. */
before_dot, /* Succeeds if before point. */
at_dot, /* Succeeds if at point. */
after_dot, /* Succeeds if after point. */
begbuf, /* Succeeds if at beginning of buffer. */
endbuf, /* Succeeds if at end of buffer. */
wordchar, /* Matches any word-constituent character. */
notwordchar, /* Matches any char that is not a word-constituent. */
wordbeg, /* Succeeds if at word beginning. */
wordend, /* Succeeds if at word end. */
wordbound, /* Succeeds if at a word boundary. */
notwordbound,/* Succeeds if not at a word boundary. */
syntaxspec, /* Matches any character whose syntax is specified.
followed by a byte which contains a syntax code,
e.g., Sword. */
notsyntaxspec /* Matches any character whose syntax differs from
that specified. */
};
/* Number of failure points to allocate space for initially,
when matching. If this number is exceeded, more space is allocated,
so it is not a hard limit. */
#ifndef NFAILURES
#define NFAILURES 80
#endif
#ifdef CHAR_UNSIGNED
#define SIGN_EXTEND_CHAR(c) ((c)>(char)127?(c)-256:(c)) /* for IBM RT */
#endif
#ifndef SIGN_EXTEND_CHAR
#define SIGN_EXTEND_CHAR(x) (x)
#endif
/* Store NUMBER in two contiguous bytes starting at DESTINATION. */
#define STORE_NUMBER(destination, number) \
{ (destination)[0] = (number) & 0377; \
(destination)[1] = (number) >> 8; }
/* Same as STORE_NUMBER, except increment the destination pointer to
the byte after where the number is stored. Watch out that values for
DESTINATION such as p + 1 won't work, whereas p will. */
#define STORE_NUMBER_AND_INCR(destination, number) \
{ STORE_NUMBER(destination, number); \
(destination) += 2; }
/* Put into DESTINATION a number stored in two contingous bytes starting
at SOURCE. */
#define EXTRACT_NUMBER(destination, source) \
{ (destination) = *(source) & 0377; \
(destination) += SIGN_EXTEND_CHAR (*(char *)((source) + 1)) << 8; }
/* Same as EXTRACT_NUMBER, except increment the pointer for source to
point to second byte of SOURCE. Note that SOURCE has to be a value
such as p, not, e.g., p + 1. */
#define EXTRACT_NUMBER_AND_INCR(destination, source) \
{ EXTRACT_NUMBER (destination, source); \
(source) += 2; }
/* Specify the precise syntax of regexps for compilation. This provides
for compatibility for various utilities which historically have
different, incompatible syntaxes.
The argument SYNTAX is a bit-mask comprised of the various bits
defined in regex.h. */
int
re_set_syntax (syntax)
int syntax;
{
int ret;
ret = obscure_syntax;
obscure_syntax = syntax;
return ret;
}
/* Set by re_set_syntax to the current regexp syntax to recognize. */
int obscure_syntax = 0;
/* Macros for re_compile_pattern, which is found below these definitions. */
#define CHAR_CLASS_MAX_LENGTH 6
/* Fetch the next character in the uncompiled pattern, translating it if
necessary. */
#define PATFETCH(c) \
{if (p == pend) goto end_of_pattern; \
c = * (unsigned char *) p++; \
if (translate) c = translate[c]; }
/* Fetch the next character in the uncompiled pattern, with no
translation. */
#define PATFETCH_RAW(c) \
{if (p == pend) goto end_of_pattern; \
c = * (unsigned char *) p++; }
#define PATUNFETCH p--
/* If the buffer isn't allocated when it comes in, use this. */
#define INIT_BUF_SIZE 28
/* Make sure we have at least N more bytes of space in buffer. */
#define GET_BUFFER_SPACE(n) \
{ \
while (b - bufp->buffer + (n) >= bufp->allocated) \
EXTEND_BUFFER; \
}
/* Make sure we have one more byte of buffer space and then add CH to it. */
#define BUFPUSH(ch) \
{ \
GET_BUFFER_SPACE (1); \
*b++ = (char) (ch); \
}
/* Extend the buffer by twice its current size via reallociation and
reset the pointers that pointed into the old allocation to point to
the correct places in the new allocation. If extending the buffer
results in it being larger than 1 << 16, then flag memory exhausted. */
#define EXTEND_BUFFER \
{ char *old_buffer = bufp->buffer; \
if (bufp->allocated == (1L<<16)) goto too_big; \
bufp->allocated *= 2; \
if (bufp->allocated > (1L<<16)) bufp->allocated = (1L<<16); \
bufp->buffer = (char *) realloc (bufp->buffer, bufp->allocated); \
if (bufp->buffer == 0) \
goto memory_exhausted; \
b = (b - old_buffer) + bufp->buffer; \
if (fixup_jump) \
fixup_jump = (fixup_jump - old_buffer) + bufp->buffer; \
if (laststart) \
laststart = (laststart - old_buffer) + bufp->buffer; \
begalt = (begalt - old_buffer) + bufp->buffer; \
if (pending_exact) \
pending_exact = (pending_exact - old_buffer) + bufp->buffer; \
}
/* Set the bit for character C in a character set list. */
#define SET_LIST_BIT(c) (b[(c) / BYTEWIDTH] |= 1 << ((c) % BYTEWIDTH))
/* Get the next unsigned number in the uncompiled pattern. */
#define GET_UNSIGNED_NUMBER(num) \
{ if (p != pend) \
{ \
PATFETCH (c); \
while (isdigit (c)) \
{ \
if (num < 0) \
num = 0; \
num = num * 10 + c - '0'; \
if (p == pend) \
break; \
PATFETCH (c); \
} \
} \
}
/* Subroutines for re_compile_pattern. */
static void store_jump (), insert_jump (), store_jump_n (),
insert_jump_n (), insert_op_2 ();
/* re_compile_pattern takes a regular-expression string
and converts it into a buffer full of byte commands for matching.
PATTERN is the address of the pattern string
SIZE is the length of it.
BUFP is a struct re_pattern_buffer * which points to the info
on where to store the byte commands.
This structure contains a char * which points to the
actual space, which should have been obtained with malloc.
re_compile_pattern may use realloc to grow the buffer space.
The number of bytes of commands can be found out by looking in
the `struct re_pattern_buffer' that bufp pointed to, after
re_compile_pattern returns. */
char *
re_compile_pattern (pattern, size, bufp)
char *pattern;
int size;
struct re_pattern_buffer *bufp;
{
register char *b = bufp->buffer;
register char *p = pattern;
char *pend = pattern + size;
register unsigned c, c1;
char *p1;
unsigned char *translate = (unsigned char *) bufp->translate;
/* Address of the count-byte of the most recently inserted `exactn'
command. This makes it possible to tell whether a new exact-match
character can be added to that command or requires a new `exactn'
command. */
char *pending_exact = 0;
/* Address of the place where a forward-jump should go to the end of
the containing expression. Each alternative of an `or', except the
last, ends with a forward-jump of this sort. */
char *fixup_jump = 0;
/* Address of start of the most recently finished expression.
This tells postfix * where to find the start of its operand. */
char *laststart = 0;
/* In processing a repeat, 1 means zero matches is allowed. */
char zero_times_ok;
/* In processing a repeat, 1 means many matches is allowed. */
char many_times_ok;
/* Address of beginning of regexp, or inside of last \(. */
char *begalt = b;
/* In processing an interval, at least this many matches must be made. */
int lower_bound;
/* In processing an interval, at most this many matches can be made. */
int upper_bound;
/* Place in pattern (i.e., the {) to which to go back if the interval
is invalid. */
char *beg_interval = 0;
/* Stack of information saved by \( and restored by \).
Four stack elements are pushed by each \(:
First, the value of b.
Second, the value of fixup_jump.
Third, the value of regnum.
Fourth, the value of begalt. */
int stackb[40];
int *stackp = stackb;
int *stacke = stackb + 40;
int *stackt;
/* Counts \('s as they are encountered. Remembered for the matching \),
where it becomes the register number to put in the stop_memory
command. */
int regnum = 1;
bufp->fastmap_accurate = 0;
#ifndef emacs
#ifndef SYNTAX_TABLE
/* Initialize the syntax table. */
init_syntax_once();
#endif
#endif
if (bufp->allocated == 0)
{
bufp->allocated = INIT_BUF_SIZE;
if (bufp->buffer)
/* EXTEND_BUFFER loses when bufp->allocated is 0. */
bufp->buffer = (char *) realloc (bufp->buffer, INIT_BUF_SIZE);
else
/* Caller did not allocate a buffer. Do it for them. */
bufp->buffer = (char *) malloc (INIT_BUF_SIZE);
if (!bufp->buffer) goto memory_exhausted;
begalt = b = bufp->buffer;
}
while (p != pend)
{
PATFETCH (c);
switch (c)
{
case '$':
{
char *p1 = p;
/* When testing what follows the $,
look past the \-constructs that don't consume anything. */
if (! (obscure_syntax & RE_CONTEXT_INDEP_OPS))
while (p1 != pend)
{
if (*p1 == '\\' && p1 + 1 != pend
&& (p1[1] == '<' || p1[1] == '>'
|| p1[1] == '`' || p1[1] == '\''
#ifdef emacs
|| p1[1] == '='
#endif
|| p1[1] == 'b' || p1[1] == 'B'))
p1 += 2;
else
break;
}
if (obscure_syntax & RE_TIGHT_VBAR)
{
if (! (obscure_syntax & RE_CONTEXT_INDEP_OPS) && p1 != pend)
goto normal_char;
/* Make operand of last vbar end before this `$'. */
if (fixup_jump)
store_jump (fixup_jump, jump, b);
fixup_jump = 0;
BUFPUSH (endline);
break;
}
/* $ means succeed if at end of line, but only in special contexts.
If validly in the middle of a pattern, it is a normal character. */
if ((obscure_syntax & RE_CONTEXTUAL_INVALID_OPS) && p1 != pend)
goto invalid_pattern;
if (p1 == pend || *p1 == '\n'
|| (obscure_syntax & RE_CONTEXT_INDEP_OPS)
|| (obscure_syntax & RE_NO_BK_PARENS
? *p1 == ')'
: *p1 == '\\' && p1[1] == ')')
|| (obscure_syntax & RE_NO_BK_VBAR
? *p1 == '|'
: *p1 == '\\' && p1[1] == '|'))
{
BUFPUSH (endline);
break;
}
goto normal_char;
}
case '^':
/* ^ means succeed if at beg of line, but only if no preceding
pattern. */
if ((obscure_syntax & RE_CONTEXTUAL_INVALID_OPS) && laststart)
goto invalid_pattern;
if (laststart && p - 2 >= pattern && p[-2] != '\n'
&& !(obscure_syntax & RE_CONTEXT_INDEP_OPS))
goto normal_char;
if (obscure_syntax & RE_TIGHT_VBAR)
{
if (p != pattern + 1
&& ! (obscure_syntax & RE_CONTEXT_INDEP_OPS))
goto normal_char;
BUFPUSH (begline);
begalt = b;
}
else
BUFPUSH (begline);
break;
case '+':
case '?':
if ((obscure_syntax & RE_BK_PLUS_QM)
|| (obscure_syntax & RE_LIMITED_OPS))
goto normal_char;
handle_plus:
case '*':
/* If there is no previous pattern, char not special. */
if (!laststart)
{
if (obscure_syntax & RE_CONTEXTUAL_INVALID_OPS)
goto invalid_pattern;
else if (! (obscure_syntax & RE_CONTEXT_INDEP_OPS))
goto normal_char;
}
/* If there is a sequence of repetition chars,
collapse it down to just one. */
zero_times_ok = 0;
many_times_ok = 0;
while (1)
{
zero_times_ok |= c != '+';
many_times_ok |= c != '?';
if (p == pend)
break;
PATFETCH (c);
if (c == '*')
;
else if (!(obscure_syntax & RE_BK_PLUS_QM)
&& (c == '+' || c == '?'))
;
else if ((obscure_syntax & RE_BK_PLUS_QM)
&& c == '\\')
{
int c1;
PATFETCH (c1);
if (!(c1 == '+' || c1 == '?'))
{
PATUNFETCH;
PATUNFETCH;
break;
}
c = c1;
}
else
{
PATUNFETCH;
break;
}
}
/* Star, etc. applied to an empty pattern is equivalent
to an empty pattern. */
if (!laststart)
break;
/* Now we know whether or not zero matches is allowed
and also whether or not two or more matches is allowed. */
if (many_times_ok)
{
/* If more than one repetition is allowed, put in at the
end a backward relative jump from b to before the next
jump we're going to put in below (which jumps from
laststart to after this jump). */
GET_BUFFER_SPACE (3);
store_jump (b, maybe_finalize_jump, laststart - 3);
b += 3; /* Because store_jump put stuff here. */
}
/* On failure, jump from laststart to b + 3, which will be the
end of the buffer after this jump is inserted. */
GET_BUFFER_SPACE (3);
insert_jump (on_failure_jump, laststart, b + 3, b);
pending_exact = 0;
b += 3;
if (!zero_times_ok)
{
/* At least one repetition is required, so insert a
dummy-failure before the initial on-failure-jump
instruction of the loop. This effects a skip over that
instruction the first time we hit that loop. */
GET_BUFFER_SPACE (6);
insert_jump (dummy_failure_jump, laststart, laststart + 6, b);
b += 3;
}
break;
case '.':
laststart = b;
BUFPUSH (anychar);
break;
case '[':
if (p == pend)
goto invalid_pattern;
while (b - bufp->buffer
> bufp->allocated - 3 - (1 << BYTEWIDTH) / BYTEWIDTH)
EXTEND_BUFFER;
laststart = b;
if (*p == '^')
{
BUFPUSH (charset_not);
p++;
}
else
BUFPUSH (charset);
p1 = p;
BUFPUSH ((1 << BYTEWIDTH) / BYTEWIDTH);
/* Clear the whole map */
bzero (b, (1 << BYTEWIDTH) / BYTEWIDTH);
if ((obscure_syntax & RE_HAT_NOT_NEWLINE) && b[-2] == charset_not)
SET_LIST_BIT ('\n');
/* Read in characters and ranges, setting map bits. */
while (1)
{
PATFETCH (c);
/* If set, \ escapes characters when inside [...]. */
if ((obscure_syntax & RE_AWK_CLASS_HACK) && c == '\\')
{
PATFETCH(c1);
SET_LIST_BIT (c1);
continue;
}
if (c == ']')
{
if (p == p1 + 1)
{
/* If this is an empty bracket expression. */
if ((obscure_syntax & RE_NO_EMPTY_BRACKETS)
&& p == pend)
goto invalid_pattern;
}
else
/* Stop if this isn't merely a ] inside a bracket
expression, but rather the end of a bracket
expression. */
break;
}
/* Get a range. */
if (p[0] == '-' && p[1] != ']')
{
PATFETCH (c1);
PATFETCH (c1);
if ((obscure_syntax & RE_NO_EMPTY_RANGES) && c > c1)
goto invalid_pattern;
if ((obscure_syntax & RE_NO_HYPHEN_RANGE_END)
&& c1 == '-' && *p != ']')
goto invalid_pattern;
while (c <= c1)
{
SET_LIST_BIT (c);
c++;
}
}
else if ((obscure_syntax & RE_CHAR_CLASSES)
&& c == '[' && p[0] == ':')
{
/* Longest valid character class word has six characters. */
char str[CHAR_CLASS_MAX_LENGTH];
PATFETCH (c);
c1 = 0;
/* If no ] at end. */
if (p == pend)
goto invalid_pattern;
while (1)
{
/* Don't translate the ``character class'' characters. */
PATFETCH_RAW (c);
if (c == ':' || c == ']' || p == pend
|| c1 == CHAR_CLASS_MAX_LENGTH)
break;
str[c1++] = c;
}
str[c1] = '\0';
if (p == pend
|| c == ']' /* End of the bracket expression. */
|| p[0] != ']'
|| p + 1 == pend
|| (strcmp (str, "alpha") != 0
&& strcmp (str, "upper") != 0
&& strcmp (str, "lower") != 0
&& strcmp (str, "digit") != 0
&& strcmp (str, "alnum") != 0
&& strcmp (str, "xdigit") != 0
&& strcmp (str, "space") != 0
&& strcmp (str, "print") != 0
&& strcmp (str, "punct") != 0
&& strcmp (str, "graph") != 0
&& strcmp (str, "cntrl") != 0))
{
/* Undo the ending character, the letters, and leave
the leading : and [ (but set bits for them). */
c1++;
while (c1--)
PATUNFETCH;
SET_LIST_BIT ('[');
SET_LIST_BIT (':');
}
else
{
/* The ] at the end of the character class. */
PATFETCH (c);
if (c != ']')
goto invalid_pattern;
for (c = 0; c < (1 << BYTEWIDTH); c++)
{
if ((strcmp (str, "alpha") == 0 && isalpha (c))
|| (strcmp (str, "upper") == 0 && isupper (c))
|| (strcmp (str, "lower") == 0 && islower (c))
|| (strcmp (str, "digit") == 0 && isdigit (c))
|| (strcmp (str, "alnum") == 0 && isalnum (c))
|| (strcmp (str, "xdigit") == 0 && isxdigit (c))
|| (strcmp (str, "space") == 0 && isspace (c))
|| (strcmp (str, "print") == 0 && isprint (c))
|| (strcmp (str, "punct") == 0 && ispunct (c))
|| (strcmp (str, "graph") == 0 && isgraph (c))
|| (strcmp (str, "cntrl") == 0 && iscntrl (c)))
SET_LIST_BIT (c);
}
}
}
else
SET_LIST_BIT (c);
}
/* Discard any character set/class bitmap bytes that are all
0 at the end of the map. Decrement the map-length byte too. */
while ((int) b[-1] > 0 && b[b[-1] - 1] == 0)
b[-1]--;
b += b[-1];
break;
case '(':
if (! (obscure_syntax & RE_NO_BK_PARENS))
goto normal_char;
else
goto handle_open;
case ')':
if (! (obscure_syntax & RE_NO_BK_PARENS))
goto normal_char;
else
goto handle_close;
case '\n':
if (! (obscure_syntax & RE_NEWLINE_OR))
goto normal_char;
else
goto handle_bar;
case '|':
if ((obscure_syntax & RE_CONTEXTUAL_INVALID_OPS)
&& (! laststart || p == pend))
goto invalid_pattern;
else if (! (obscure_syntax & RE_NO_BK_VBAR))
goto normal_char;
else
goto handle_bar;
case '{':
if (! ((obscure_syntax & RE_NO_BK_CURLY_BRACES)
&& (obscure_syntax & RE_INTERVALS)))
goto normal_char;
else
goto handle_interval;
case '\\':
if (p == pend) goto invalid_pattern;
PATFETCH_RAW (c);
switch (c)
{
case '(':
if (obscure_syntax & RE_NO_BK_PARENS)
goto normal_backsl;
handle_open:
if (stackp == stacke) goto nesting_too_deep;
/* Laststart should point to the start_memory that we are about
to push (unless the pattern has RE_NREGS or more ('s). */
*stackp++ = b - bufp->buffer;
if (regnum < RE_NREGS)
{
BUFPUSH (start_memory);
BUFPUSH (regnum);
}
*stackp++ = fixup_jump ? fixup_jump - bufp->buffer + 1 : 0;
*stackp++ = regnum++;
*stackp++ = begalt - bufp->buffer;
fixup_jump = 0;
laststart = 0;
begalt = b;
break;
case ')':
if (obscure_syntax & RE_NO_BK_PARENS)
goto normal_backsl;
handle_close:
if (stackp == stackb) goto unmatched_close;
begalt = *--stackp + bufp->buffer;
if (fixup_jump)
store_jump (fixup_jump, jump, b);
if (stackp[-1] < RE_NREGS)
{
BUFPUSH (stop_memory);
BUFPUSH (stackp[-1]);
}
stackp -= 2;
fixup_jump = *stackp ? *stackp + bufp->buffer - 1 : 0;
laststart = *--stackp + bufp->buffer;
break;
case '|':
if ((obscure_syntax & RE_LIMITED_OPS)
|| (obscure_syntax & RE_NO_BK_VBAR))
goto normal_backsl;
handle_bar:
if (obscure_syntax & RE_LIMITED_OPS)
goto normal_char;
/* Insert before the previous alternative a jump which
jumps to this alternative if the former fails. */
GET_BUFFER_SPACE (6);
insert_jump (on_failure_jump, begalt, b + 6, b);
pending_exact = 0;
b += 3;
/* The alternative before the previous alternative has a
jump after it which gets executed if it gets matched.
Adjust that jump so it will jump to the previous
alternative's analogous jump (put in below, which in
turn will jump to the next (if any) alternative's such
jump, etc.). The last such jump jumps to the correct
final destination. */
if (fixup_jump)
store_jump (fixup_jump, jump, b);
/* Leave space for a jump after previous alternative---to be
filled in later. */
fixup_jump = b;
b += 3;
laststart = 0;
begalt = b;
break;
case '{':
if (! (obscure_syntax & RE_INTERVALS)
/* Let \{ be a literal. */
|| ((obscure_syntax & RE_INTERVALS)
&& (obscure_syntax & RE_NO_BK_CURLY_BRACES))
/* If it's the string "\{". */
|| (p - 2 == pattern && p == pend))
goto normal_backsl;
handle_interval:
beg_interval = p - 1; /* The {. */
/* If there is no previous pattern, this isn't an interval. */
if (!laststart)
{
if (obscure_syntax & RE_CONTEXTUAL_INVALID_OPS)
goto invalid_pattern;
else
goto normal_backsl;
}
/* It also isn't an interval if not preceded by an re
matching a single character or subexpression, or if
the current type of intervals can't handle back
references and the previous thing is a back reference. */
if (! (*laststart == anychar
|| *laststart == charset
|| *laststart == charset_not
|| *laststart == start_memory
|| (*laststart == exactn && laststart[1] == 1)
|| (! (obscure_syntax & RE_NO_BK_REFS)
&& *laststart == duplicate)))
{
if (obscure_syntax & RE_NO_BK_CURLY_BRACES)
goto normal_char;
/* Posix extended syntax is handled in previous
statement; this is for Posix basic syntax. */
if (obscure_syntax & RE_INTERVALS)
goto invalid_pattern;
goto normal_backsl;
}
lower_bound = -1; /* So can see if are set. */
upper_bound = -1;
GET_UNSIGNED_NUMBER (lower_bound);
if (c == ',')
{
GET_UNSIGNED_NUMBER (upper_bound);
if (upper_bound < 0)
upper_bound = RE_DUP_MAX;
}
if (upper_bound < 0)
upper_bound = lower_bound;
if (! (obscure_syntax & RE_NO_BK_CURLY_BRACES))
{
if (c != '\\')
goto invalid_pattern;
PATFETCH (c);
}
if (c != '}' || lower_bound < 0 || upper_bound > RE_DUP_MAX
|| lower_bound > upper_bound
|| ((obscure_syntax & RE_NO_BK_CURLY_BRACES)
&& p != pend && *p == '{'))
{
if (obscure_syntax & RE_NO_BK_CURLY_BRACES)
goto unfetch_interval;
else
goto invalid_pattern;
}
/* If upper_bound is zero, don't want to succeed at all;
jump from laststart to b + 3, which will be the end of
the buffer after this jump is inserted. */
if (upper_bound == 0)
{
GET_BUFFER_SPACE (3);
insert_jump (jump, laststart, b + 3, b);
b += 3;
}
/* Otherwise, after lower_bound number of succeeds, jump
to after the jump_n which will be inserted at the end
of the buffer, and insert that jump_n. */
else
{ /* Set to 5 if only one repetition is allowed and
hence no jump_n is inserted at the current end of
the buffer; then only space for the succeed_n is
needed. Otherwise, need space for both the
succeed_n and the jump_n. */
unsigned slots_needed = upper_bound == 1 ? 5 : 10;
GET_BUFFER_SPACE (slots_needed);
/* Initialize the succeed_n to n, even though it will
be set by its attendant set_number_at, because
re_compile_fastmap will need to know it. Jump to
what the end of buffer will be after inserting
this succeed_n and possibly appending a jump_n. */
insert_jump_n (succeed_n, laststart, b + slots_needed,
b, lower_bound);
b += 5; /* Just increment for the succeed_n here. */
/* More than one repetition is allowed, so put in at
the end of the buffer a backward jump from b to the
succeed_n we put in above. By the time we've gotten
to this jump when matching, we'll have matched once
already, so jump back only upper_bound - 1 times. */
if (upper_bound > 1)
{
store_jump_n (b, jump_n, laststart, upper_bound - 1);
b += 5;
/* When hit this when matching, reset the
preceding jump_n's n to upper_bound - 1. */
BUFPUSH (set_number_at);
GET_BUFFER_SPACE (2);
STORE_NUMBER_AND_INCR (b, -5);
STORE_NUMBER_AND_INCR (b, upper_bound - 1);
}
/* When hit this when matching, set the succeed_n's n. */
GET_BUFFER_SPACE (5);
insert_op_2 (set_number_at, laststart, b, 5, lower_bound);
b += 5;
}
pending_exact = 0;
beg_interval = 0;
break;
unfetch_interval:
/* If an invalid interval, match the characters as literals. */
if (beg_interval)
p = beg_interval;
else
{
fprintf (stderr,
"regex: no interval beginning to which to backtrack.\n");
exit (1);
}
beg_interval = 0;
PATFETCH (c); /* normal_char expects char in `c'. */
goto normal_char;
break;
#ifdef emacs
case '=':
BUFPUSH (at_dot);
break;
case 's':
laststart = b;
BUFPUSH (syntaxspec);
PATFETCH (c);
BUFPUSH (syntax_spec_code[c]);
break;
case 'S':
laststart = b;
BUFPUSH (notsyntaxspec);
PATFETCH (c);
BUFPUSH (syntax_spec_code[c]);
break;
#endif /* emacs */
case 'w':
laststart = b;
BUFPUSH (wordchar);
break;
case 'W':
laststart = b;
BUFPUSH (notwordchar);
break;
case '<':
BUFPUSH (wordbeg);
break;
case '>':
BUFPUSH (wordend);
break;
case 'b':
BUFPUSH (wordbound);
break;
case 'B':
BUFPUSH (notwordbound);
break;
case '`':
BUFPUSH (begbuf);
break;
case '\'':
BUFPUSH (endbuf);
break;
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
if (obscure_syntax & RE_NO_BK_REFS)
goto normal_char;
c1 = c - '0';
if (c1 >= regnum)
{
if (obscure_syntax & RE_NO_EMPTY_BK_REF)
goto invalid_pattern;
else
goto normal_char;
}
/* Can't back reference to a subexpression if inside of it. */
for (stackt = stackp - 2; stackt > stackb; stackt -= 4)
if (*stackt == c1)
goto normal_char;
laststart = b;
BUFPUSH (duplicate);
BUFPUSH (c1);
break;
case '+':
case '?':
if (obscure_syntax & RE_BK_PLUS_QM)
goto handle_plus;
else
goto normal_backsl;
break;
default:
normal_backsl:
/* You might think it would be useful for \ to mean
not to translate; but if we don't translate it
it will never match anything. */
if (translate) c = translate[c];
goto normal_char;
}
break;
default:
normal_char: /* Expects the character in `c'. */
if (!pending_exact || pending_exact + *pending_exact + 1 != b
|| *pending_exact == 0177 || *p == '*' || *p == '^'
|| ((obscure_syntax & RE_BK_PLUS_QM)
? *p == '\\' && (p[1] == '+' || p[1] == '?')
: (*p == '+' || *p == '?'))
|| ((obscure_syntax & RE_INTERVALS)
&& ((obscure_syntax & RE_NO_BK_CURLY_BRACES)
? *p == '{'
: (p[0] == '\\' && p[1] == '{'))))
{
laststart = b;
BUFPUSH (exactn);
pending_exact = b;
BUFPUSH (0);
}
BUFPUSH (c);
(*pending_exact)++;
}
}
if (fixup_jump)
store_jump (fixup_jump, jump, b);
if (stackp != stackb) goto unmatched_open;
bufp->used = b - bufp->buffer;
return 0;
invalid_pattern:
return "Invalid regular expression";
unmatched_open:
return "Unmatched \\(";
unmatched_close:
return "Unmatched \\)";
end_of_pattern:
return "Premature end of regular expression";
nesting_too_deep:
return "Nesting too deep";
too_big:
return "Regular expression too big";
memory_exhausted:
return "Memory exhausted";
}
/* Store a jump of the form <OPCODE> <relative address>.
Store in the location FROM a jump operation to jump to relative
address FROM - TO. OPCODE is the opcode to store. */
static void
store_jump (from, opcode, to)
char *from, *to;
char opcode;
{
from[0] = opcode;
STORE_NUMBER(from + 1, to - (from + 3));
}
/* Open up space before char FROM, and insert there a jump to TO.
CURRENT_END gives the end of the storage not in use, so we know
how much data to copy up. OP is the opcode of the jump to insert.
If you call this function, you must zero out pending_exact. */
static void
insert_jump (op, from, to, current_end)
char op;
char *from, *to, *current_end;
{
register char *pfrom = current_end; /* Copy from here... */
register char *pto = current_end + 3; /* ...to here. */
while (pfrom != from)
*--pto = *--pfrom;
store_jump (from, op, to);
}
/* Store a jump of the form <opcode> <relative address> <n> .
Store in the location FROM a jump operation to jump to relative
address FROM - TO. OPCODE is the opcode to store, N is a number the
jump uses, say, to decide how many times to jump.
If you call this function, you must zero out pending_exact. */
static void
store_jump_n (from, opcode, to, n)
char *from, *to;
char opcode;
unsigned n;
{
from[0] = opcode;
STORE_NUMBER (from + 1, to - (from + 3));
STORE_NUMBER (from + 3, n);
}
/* Similar to insert_jump, but handles a jump which needs an extra
number to handle minimum and maximum cases. Open up space at
location FROM, and insert there a jump to TO. CURRENT_END gives the
end of the storage in use, so we know how much data to copy up. OP is
the opcode of the jump to insert.
If you call this function, you must zero out pending_exact. */
static void
insert_jump_n (op, from, to, current_end, n)
char op;
char *from, *to, *current_end;
unsigned n;
{
register char *pfrom = current_end; /* Copy from here... */
register char *pto = current_end + 5; /* ...to here. */
while (pfrom != from)
*--pto = *--pfrom;
store_jump_n (from, op, to, n);
}
/* Open up space at location THERE, and insert operation OP followed by
NUM_1 and NUM_2. CURRENT_END gives the end of the storage in use, so
we know how much data to copy up.
If you call this function, you must zero out pending_exact. */
static void
insert_op_2 (op, there, current_end, num_1, num_2)
char op;
char *there, *current_end;
int num_1, num_2;
{
register char *pfrom = current_end; /* Copy from here... */
register char *pto = current_end + 5; /* ...to here. */
while (pfrom != there)
*--pto = *--pfrom;
there[0] = op;
STORE_NUMBER (there + 1, num_1);
STORE_NUMBER (there + 3, num_2);
}
/* Given a pattern, compute a fastmap from it. The fastmap records
which of the (1 << BYTEWIDTH) possible characters can start a string
that matches the pattern. This fastmap is used by re_search to skip
quickly over totally implausible text.
The caller must supply the address of a (1 << BYTEWIDTH)-byte data
area as bufp->fastmap.
The other components of bufp describe the pattern to be used. */
void
re_compile_fastmap (bufp)
struct re_pattern_buffer *bufp;
{
unsigned char *pattern = (unsigned char *) bufp->buffer;
int size = bufp->used;
register char *fastmap = bufp->fastmap;
register unsigned char *p = pattern;
register unsigned char *pend = pattern + size;
register int j, k;
unsigned char *translate = (unsigned char *) bufp->translate;
unsigned char *stackb[NFAILURES];
unsigned char **stackp = stackb;
unsigned is_a_succeed_n;
bzero (fastmap, (1 << BYTEWIDTH));
bufp->fastmap_accurate = 1;
bufp->can_be_null = 0;
while (p)
{
is_a_succeed_n = 0;
if (p == pend)
{
bufp->can_be_null = 1;
break;
}
#ifdef SWITCH_ENUM_BUG
switch ((int) ((enum regexpcode) *p++))
#else
switch ((enum regexpcode) *p++)
#endif
{
case exactn:
if (translate)
fastmap[translate[p[1]]] = 1;
else
fastmap[p[1]] = 1;
break;
case begline:
case before_dot:
case at_dot:
case after_dot:
case begbuf:
case endbuf:
case wordbound:
case notwordbound:
case wordbeg:
case wordend:
continue;
case endline:
if (translate)
fastmap[translate['\n']] = 1;
else
fastmap['\n'] = 1;
if (bufp->can_be_null != 1)
bufp->can_be_null = 2;
break;
case jump_n:
case finalize_jump:
case maybe_finalize_jump:
case jump:
case dummy_failure_jump:
EXTRACT_NUMBER_AND_INCR (j, p);
p += j;
if (j > 0)
continue;
/* Jump backward reached implies we just went through
the body of a loop and matched nothing.
Opcode jumped to should be an on_failure_jump.
Just treat it like an ordinary jump.
For a * loop, it has pushed its failure point already;
If so, discard that as redundant. */
if ((enum regexpcode) *p != on_failure_jump
&& (enum regexpcode) *p != succeed_n)
continue;
p++;
EXTRACT_NUMBER_AND_INCR (j, p);
p += j;
if (stackp != stackb && *stackp == p)
stackp--;
continue;
case on_failure_jump:
handle_on_failure_jump:
EXTRACT_NUMBER_AND_INCR (j, p);
*++stackp = p + j;
if (is_a_succeed_n)
EXTRACT_NUMBER_AND_INCR (k, p); /* Skip the n. */
continue;
case succeed_n:
is_a_succeed_n = 1;
/* Get to the number of times to succeed. */
p += 2;
/* Increment p past the n for when k != 0. */
EXTRACT_NUMBER_AND_INCR (k, p);
if (k == 0)
{
p -= 4;
goto handle_on_failure_jump;
}
continue;
case set_number_at:
p += 4;
continue;
case start_memory:
case stop_memory:
p++;
continue;
case duplicate:
bufp->can_be_null = 1;
fastmap['\n'] = 1;
case anychar:
for (j = 0; j < (1 << BYTEWIDTH); j++)
if (j != '\n')
fastmap[j] = 1;
if (bufp->can_be_null)
return;
/* Don't return; check the alternative paths
so we can set can_be_null if appropriate. */
break;
case wordchar:
for (j = 0; j < (1 << BYTEWIDTH); j++)
if (SYNTAX (j) == Sword)
fastmap[j] = 1;
break;
case notwordchar:
for (j = 0; j < (1 << BYTEWIDTH); j++)
if (SYNTAX (j) != Sword)
fastmap[j] = 1;
break;
#ifdef emacs
case syntaxspec:
k = *p++;
for (j = 0; j < (1 << BYTEWIDTH); j++)
if (SYNTAX (j) == (enum syntaxcode) k)
fastmap[j] = 1;
break;
case notsyntaxspec:
k = *p++;
for (j = 0; j < (1 << BYTEWIDTH); j++)
if (SYNTAX (j) != (enum syntaxcode) k)
fastmap[j] = 1;
break;
#endif /* not emacs */
case charset:
for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
if (p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH)))
{
if (translate)
fastmap[translate[j]] = 1;
else
fastmap[j] = 1;
}
break;
case charset_not:
/* Chars beyond end of map must be allowed */
for (j = *p * BYTEWIDTH; j < (1 << BYTEWIDTH); j++)
if (translate)
fastmap[translate[j]] = 1;
else
fastmap[j] = 1;
for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
if (!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))))
{
if (translate)
fastmap[translate[j]] = 1;
else
fastmap[j] = 1;
}
break;
}
/* Get here means we have successfully found the possible starting
characters of one path of the pattern. We need not follow this
path any farther. Instead, look at the next alternative
remembered in the stack. */
if (stackp != stackb)
p = *stackp--;
else
break;
}
}