home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 22 gnu / 22-gnu.zip / GNUGRE.ZIP / grep / dfa.h < prev    next >
C/C++ Source or Header  |  1992-07-18  |  18KB  |  456 lines

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