home *** CD-ROM | disk | FTP | other *** search
/ Borland Programmer's Resource / Borland_Programmers_Resource_CD_1995.iso / ntcode / gnugrep / dfa.h < prev    next >
Encoding:
C/C++ Source or Header  |  1995-05-19  |  15.5 KB  |  380 lines

  1. #include <stdlib.h>
  2. #include <sys/types.h>
  3. #include <string.h>
  4. #include <malloc.h>
  5. extern char *bcopy(), *bzero();
  6.  
  7. #ifdef SOMEDAY
  8. #define ISALNUM(c) isalnum(c)
  9. #define ISALPHA(c) isalpha(c)
  10. #else
  11. #define ISALNUM(c) (isascii(c) && isalnum(c))
  12. #define ISALPHA(c) (isascii(c) && isalpha(c))
  13. #endif
  14.  
  15. /* 1 means plain parentheses serve as grouping, and backslash
  16.      parentheses are needed for literal searching.
  17.    0 means backslash-parentheses are grouping, and plain parentheses
  18.      are for literal searching.  */
  19. #define RE_NO_BK_PARENS 1
  20.  
  21. /* 1 means plain | serves as the "or"-operator, and \| is a literal.
  22.    0 means \| serves as the "or"-operator, and | is a literal.  */
  23. #define RE_NO_BK_VBAR 2
  24.  
  25. /* 0 means plain + or ? serves as an operator, and \+, \? are literals.
  26.    1 means \+, \? are operators and plain +, ? are literals.  */
  27. #define RE_BK_PLUS_QM 4
  28.  
  29. /* 1 means | binds tighter than ^ or $.
  30.    0 means the contrary.  */
  31. #define RE_TIGHT_VBAR 8
  32.  
  33. /* 1 means treat \n as an _OR operator
  34.    0 means treat it as a normal character */
  35. #define RE_NEWLINE_OR 16
  36.  
  37. /* 0 means that a special characters (such as *, ^, and $) always have
  38.      their special meaning regardless of the surrounding context.
  39.    1 means that special characters may act as normal characters in some
  40.      contexts.  Specifically, this applies to:
  41.     ^ - only special at the beginning, or after ( or |
  42.     $ - only special at the end, or before ) or |
  43.     *, +, ? - only special when not after the beginning, (, or | */
  44. #define RE_CONTEXT_INDEP_OPS 32
  45.  
  46. /* Now define combinations of bits for the standard possibilities.  */
  47. #define RE_SYNTAX_AWK (RE_NO_BK_PARENS | RE_NO_BK_VBAR | RE_CONTEXT_INDEP_OPS)
  48. #define RE_SYNTAX_EGREP (RE_SYNTAX_AWK | RE_NEWLINE_OR)
  49. #define RE_SYNTAX_GREP (RE_BK_PLUS_QM | RE_NEWLINE_OR)
  50. #define RE_SYNTAX_EMACS 0
  51.  
  52. /* Number of bits in an unsigned char. */
  53. #define CHARBITS 8
  54.  
  55. /* First integer value that is greater than any character code. */
  56. #define _NOTCHAR (1 << CHARBITS)
  57.  
  58. /* INTBITS need not be exact, just a lower bound. */
  59. #define INTBITS (CHARBITS * sizeof (int))
  60.  
  61. /* Number of ints required to hold a bit for every character. */
  62. #define _CHARSET_INTS ((_NOTCHAR + INTBITS - 1) / INTBITS)
  63.  
  64. /* Sets of unsigned characters are stored as bit vectors in arrays of ints. */
  65. typedef int _charset[_CHARSET_INTS];
  66.  
  67. /* The regexp is parsed into an array of tokens in postfix form.  Some tokens
  68.    are operators and others are terminal symbols.  Most (but not all) of these
  69.    codes are returned by the lexical analyzer. */
  70. typedef enum
  71. {
  72.   _END = -1,            /* _END is a terminal symbol that matches the
  73.                    end of input; any value of _END or less in
  74.                    the parse tree is such a symbol.  Accepting
  75.                    states of the DFA are those that would have
  76.                    a transition on _END. */
  77.  
  78.   /* Ordinary character values are terminal symbols that match themselves. */
  79.  
  80.   _EMPTY = _NOTCHAR,        /* _EMPTY is a terminal symbol that matches
  81.                    the empty string. */
  82.  
  83.   _BACKREF,            /* _BACKREF is generated by \<digit>; it
  84.                    it not completely handled.  If the scanner
  85.                    detects a transition on backref, it returns
  86.                    a kind of "semi-success" indicating that
  87.                    the match will have to be verified with
  88.                    a backtracking matcher. */
  89.  
  90.   _BEGLINE,            /* _BEGLINE is a terminal symbol that matches
  91.                    the empty string if it is at the beginning
  92.                    of a line. */
  93.  
  94.   _ALLBEGLINE,            /* _ALLBEGLINE is a terminal symbol that
  95.                    matches the empty string if it is at the
  96.                    beginning of a line; _ALLBEGLINE applies
  97.                    to the entire regexp and can only occur
  98.                    as the first token thereof.  _ALLBEGLINE
  99.                    never appears in the parse tree; a _BEGLINE
  100.                    is prepended with _CAT to the entire
  101.                    regexp instead. */
  102.  
  103.   _ENDLINE,            /* _ENDLINE is a terminal symbol that matches
  104.                    the empty string if it is at the end of
  105.                    a line. */
  106.  
  107.   _ALLENDLINE,            /* _ALLENDLINE is to _ENDLINE as _ALLBEGLINE
  108.                    is to _BEGLINE. */
  109.  
  110.   _BEGWORD,            /* _BEGWORD is a terminal symbol that matches
  111.                    the empty string if it is at the beginning
  112.                    of a word. */
  113.  
  114.   _ENDWORD,            /* _ENDWORD is a terminal symbol that matches
  115.                    the empty string if it is at the end of
  116.                    a word. */
  117.  
  118.   _LIMWORD,            /* _LIMWORD is a terminal symbol that matches
  119.                    the empty string if it is at the beginning
  120.                    or the end of a word. */
  121.  
  122.   _NOTLIMWORD,            /* _NOTLIMWORD is a terminal symbol that
  123.                    matches the empty string if it is not at
  124.                    the beginning or end of a word. */
  125.  
  126.   _QMARK,            /* _QMARK is an operator of one argument that
  127.                    matches zero or one occurences of its
  128.                    argument. */
  129.  
  130.   _STAR,            /* _STAR is an operator of one argument that
  131.                    matches the Kleene closure (zero or more
  132.                    occurrences) of its argument. */
  133.  
  134.   _PLUS,            /* _PLUS is an operator of one argument that
  135.                    matches the positive closure (one or more
  136.                    occurrences) of its argument. */
  137.  
  138.   _CAT,                /* _CAT is an operator of two arguments that
  139.                    matches the concatenation of its
  140.                    arguments.  _CAT is never returned by the
  141.                    lexical analyzer. */
  142.  
  143.   _OR,                /* _OR is an operator of two arguments that
  144.                    matches either of its arguments. */
  145.  
  146.   _LPAREN,            /* _LPAREN never appears in the parse tree,
  147.                    it is only a lexeme. */
  148.  
  149.   _RPAREN,            /* _RPAREN never appears in the parse tree. */
  150.  
  151.   _SET                /* _SET and (and any value greater) is a
  152.                    terminal symbol that matches any of a
  153.                    class of characters. */
  154. } _token;
  155.  
  156.  
  157. /* Sets are stored in an array in the compiled regexp; the index of the
  158.    array corresponding to a given set token is given by _SET_INDEX(t). */
  159. #define _SET_INDEX(t) ((t) - _SET)
  160.  
  161. /* Sometimes characters can only be matched depending on the surrounding
  162.    context.  Such context decisions depend on what the previous character
  163.    was, and the value of the current (lookahead) character.  Context
  164.    dependent constraints are encoded as 8 bit integers.  Each bit that
  165.    is set indicates that the constraint succeeds in the corresponding
  166.    context.
  167.  
  168.    bit 7 - previous and current are newlines
  169.    bit 6 - previous was newline, current isn't
  170.    bit 5 - previous wasn't newline, current is
  171.    bit 4 - neither previous nor current is a newline
  172.    bit 3 - previous and current are word-constituents
  173.    bit 2 - previous was word-constituent, current isn't
  174.    bit 1 - previous wasn't word-constituent, current is
  175.    bit 0 - neither previous nor current is word-constituent
  176.  
  177.    Word-constituent characters are those that satisfy isalnum().
  178.  
  179.    The macro _SUCCEEDS_IN_CONTEXT determines whether a a given constraint
  180.    succeeds in a particular context.  Prevn is true if the previous character
  181.    was a newline, currn is true if the lookahead character is a newline.
  182.    Prevl and currl similarly depend upon whether the previous and current
  183.    characters are word-constituent letters. */
  184. #define _MATCHES_NEWLINE_CONTEXT(constraint, prevn, currn) \
  185.   ((constraint) & 1 << ((prevn) ? 2 : 0) + ((currn) ? 1 : 0) + 4)
  186. #define _MATCHES_LETTER_CONTEXT(constraint, prevl, currl) \
  187.   ((constraint) & 1 << ((prevl) ? 2 : 0) + ((currl) ? 1 : 0))
  188. #define _SUCCEEDS_IN_CONTEXT(constraint, prevn, currn, prevl, currl) \
  189.   (_MATCHES_NEWLINE_CONTEXT(constraint, prevn, currn)             \
  190.    && _MATCHES_LETTER_CONTEXT(constraint, prevl, currl))
  191.  
  192. /* The following macros give information about what a constraint depends on. */
  193. #define _PREV_NEWLINE_DEPENDENT(constraint) \
  194.   (((constraint) & 0xc0) >> 2 != ((constraint) & 0x30))
  195. #define _PREV_LETTER_DEPENDENT(constraint) \
  196.   (((constraint) & 0x0c) >> 2 != ((constraint) & 0x03))
  197.  
  198. /* Tokens that match the empty string subject to some constraint actually
  199.    work by applying that constraint to determine what may follow them,
  200.    taking into account what has gone before.  The following values are
  201.    the constraints corresponding to the special tokens previously defined. */
  202. #define _NO_CONSTRAINT 0xff
  203. #define _BEGLINE_CONSTRAINT 0xcf
  204. #define _ENDLINE_CONSTRAINT 0xaf
  205. #define _BEGWORD_CONSTRAINT 0xf2
  206. #define _ENDWORD_CONSTRAINT 0xf4
  207. #define _LIMWORD_CONSTRAINT 0xf6
  208. #define _NOTLIMWORD_CONSTRAINT 0xf9
  209.  
  210. /* States of the recognizer correspond to sets of positions in the parse
  211.    tree, together with the constraints under which they may be matched.
  212.    So a position is encoded as an index into the parse tree together with
  213.    a constraint. */
  214. typedef struct
  215. {
  216.   long index;    /* Index into the parse array. */
  217.   int constraint;    /* Constraint for matching this position. */
  218. } _position;
  219.  
  220. /* Sets of positions are stored as arrays. */
  221. typedef struct
  222. {
  223.   _position *elems;        /* Elements of this position set. */
  224.   int nelem;            /* Number of elements in this set. */
  225. } _position_set;
  226.  
  227. /* A state of the regexp consists of a set of positions, some flags,
  228.    and the token value of the lowest-numbered position of the state that
  229.    contains an _END token. */
  230. typedef struct
  231. {
  232.   int hash;            /* Hash of the positions of this state. */
  233.   _position_set elems;        /* Positions this state could match. */
  234.   unsigned newline:1,        /* True if previous state matched newline. */
  235.        letter:1,        /* True if previous state matched a letter. */
  236.        backref:1,        /* True if this state matches a \<digit>. */
  237.        constraint:8;    /* Constraint for this state to accept. */
  238.   int first_end;        /* Token value of the first _END in elems. */
  239. } _dfa_state;
  240.  
  241. /* If an r.e. is at most MUST_MAX characters long, we look for a string which
  242.    must appear in it; whatever's found is dropped into the struct reg. */
  243.  
  244. #define MUST_MAX    50
  245.  
  246. /* A compiled regular expression. */
  247. struct regexp
  248. {
  249.   /* Stuff built by the scanner. */
  250.   _charset *charsets;        /* Array of character sets for _SET tokens. */
  251.   int cindex;            /* Index for adding new charsets. */
  252.   int calloc;            /* Number of charsets currently allocated. */
  253.  
  254.   /* Stuff built by the parser. */
  255.   _token *tokens;        /* Postfix parse array. */
  256.   int tindex;            /* Index for adding new tokens. */
  257.   int talloc;            /* Number of tokens currently allocated. */
  258.   int depth;            /* Depth required of an evaluation stack
  259.                    used for depth-first traversal of the
  260.                    parse tree. */
  261.   int nleaves;            /* Number of leaves on the parse tree. */
  262.   int nregexps;            /* Count of parallel regexps being built
  263.                    with regparse(). */
  264.  
  265.   /* Stuff owned by the state builder. */
  266.   _dfa_state *states;        /* States of the regexp. */
  267.   int sindex;            /* Index for adding new states. */
  268.   int salloc;            /* Number of states currently allocated. */
  269.  
  270.   /* Stuff built by the structure analyzer. */
  271.   _position_set *follows;    /* Array of follow sets, indexed by position
  272.                    index.  The follow of a position is the set
  273.                    of positions containing characters that
  274.                    could conceivably follow a character
  275.                    matching the given position in a string
  276.                    matching the regexp.  Allocated to the
  277.                    maximum possible position index. */
  278.   int searchflag;        /* True if we are supposed to build a searching
  279.                    as opposed to an exact matcher.  A searching
  280.                    matcher finds the first and shortest string
  281.                    matching a regexp anywhere in the buffer,
  282.                    whereas an exact matcher finds the longest
  283.                    string matching, but anchored to the
  284.                    beginning of the buffer. */
  285.  
  286.   /* Stuff owned by the executor. */
  287.   int tralloc;            /* Number of transition tables that have
  288.                    slots so far. */
  289.   int trcount;            /* Number of transition tables that have
  290.                    actually been built. */
  291.   int **trans;            /* Transition tables for states that can
  292.                    never accept.  If the transitions for a
  293.                    state have not yet been computed, or the
  294.                    state could possibly accept, its entry in
  295.                    this table is NULL. */
  296.   int **realtrans;        /* Trans always points to realtrans + 1; this
  297.                    is so trans[-1] can contain NULL. */
  298.   int **fails;            /* Transition tables after failing to accept
  299.                    on a state that potentially could do so. */
  300.   int *success;            /* Table of acceptance conditions used in
  301.                    regexecute and computed in build_state. */
  302.   int *newlines;        /* Transitions on newlines.  The entry for a
  303.                    newline in any transition table is always
  304.                    -1 so we can count lines without wasting
  305.                    too many cycles.  The transition for a
  306.                    newline is stored separately and handled
  307.                    as a special case.  Newline is also used
  308.                    as a sentinel at the end of the buffer. */
  309.   char must[MUST_MAX];
  310.   int mustn;
  311. };
  312.  
  313. /* Some macros for user access to regexp internals. */
  314.  
  315. /* ACCEPTING returns true if s could possibly be an accepting state of r. */
  316. #define ACCEPTING(s, r) ((r).states[s].constraint)
  317.  
  318. /* ACCEPTS_IN_CONTEXT returns true if the given state accepts in the
  319.    specified context. */
  320. #define ACCEPTS_IN_CONTEXT(prevn, currn, prevl, currl, state, reg) \
  321.   _SUCCEEDS_IN_CONTEXT((reg).states[state].constraint,           \
  322.                prevn, currn, prevl, currl)
  323.  
  324. /* FIRST_MATCHING_REGEXP returns the index number of the first of parallel
  325.    regexps that a given state could accept.  Parallel regexps are numbered
  326.    starting at 1. */
  327. #define FIRST_MATCHING_REGEXP(state, reg) (-(reg).states[state].first_end)
  328.  
  329. /* Entry points. */
  330.  
  331. /* Regsyntax() takes two arguments; the first sets the syntax bits described
  332.    earlier in this file, and the second sets the case-folding flag. */
  333. extern void regsyntax(int, int);
  334.  
  335. /* Compile the given string of the given length into the given struct regexp.
  336.    Final argument is a flag specifying whether to build a searching or an
  337.    exact matcher. */
  338. extern void regcompile(const char *, size_t, struct regexp *, int);
  339.  
  340. /* Execute the given struct regexp on the buffer of characters.  The
  341.    first char * points to the beginning, and the second points to the
  342.    first character after the end of the buffer, which must be a writable
  343.    place so a sentinel end-of-buffer marker can be stored there.  The
  344.    second-to-last argument is a flag telling whether to allow newlines to
  345.    be part of a string matching the regexp.  The next-to-last argument,
  346.    if non-NULL, points to a place to increment every time we see a
  347.    newline.  The final argument, if non-NULL, points to a flag that will
  348.    be set if further examination by a backtracking matcher is needed in
  349.    order to verify backreferencing; otherwise the flag will be cleared.
  350.    Returns NULL if no match is found, or a pointer to the first
  351.    character after the first & shortest matching string in the buffer. */
  352. extern char *regexecute(struct regexp *, char *, char *, int, int *, int *);
  353.  
  354. /* Free the storage held by the components of a struct regexp. */
  355. extern void regfree(struct regexp *);
  356.  
  357. /* Entry points for people who know what they're doing. */
  358.  
  359. /* Initialize the components of a struct regexp. */
  360. extern void reginit(struct regexp *);
  361.  
  362. /* Incrementally parse a string of given length into a struct regexp. */
  363. extern void regparse(const char *, size_t, struct regexp *);
  364.  
  365. /* Analyze a parsed regexp; second argument tells whether to build a searching
  366.    or an exact matcher. */
  367. extern void reganalyze(struct regexp *, int);
  368.  
  369. /* Compute, for each possible character, the transitions out of a given
  370.    state, storing them in an array of integers. */
  371. extern void regstate(int, struct regexp *, int []);
  372.  
  373. /* Error handling. */
  374.  
  375. /* Regerror() is called by the regexp routines whenever an error occurs.  It
  376.    takes a single argument, a NUL-terminated string describing the error.
  377.    The default regerror() prints the error message to stderr and exits.
  378.    The user can provide a different regfree() if so desired. */
  379. extern void regerror(const char *);
  380.