ed0eaa58780f6666adb2167640d085077edc76d0
[gnulib.git] / lib / rx.h
1 #if !defined(RXH) || defined(RX_WANT_SE_DEFS)
2 #define RXH
3
4 /*      Copyright (C) 1992, 1993 Free Software Foundation, Inc.
5
6 This file is part of the librx library.
7
8 Librx is free software; you can redistribute it and/or modify it under
9 the terms of the GNU Library General Public License as published by
10 the Free Software Foundation; either version 2, or (at your option)
11 any later version.
12
13 Librx is distributed in the hope that it will be useful, but WITHOUT
14 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
16 for more details.
17
18 You should have received a copy of the GNU Library General Public
19 License along with this software; see the file COPYING.LIB.  If not,
20 write to the Free Software Foundation, 675 Mass Ave, Cambridge, MA
21 02139, USA.  */
22 /*  t. lord     Wed Sep 23 18:20:57 1992        */
23
24
25 \f
26
27
28
29
30
31 #ifndef RX_WANT_SE_DEFS
32
33 /* This page: Bitsets */
34
35 #ifndef RX_subset
36 typedef unsigned int RX_subset;
37 #define RX_subset_bits  (32)
38 #define RX_subset_mask  (RX_subset_bits - 1)
39 #endif
40
41 typedef RX_subset * rx_Bitset;
42
43 #ifdef __STDC__
44 typedef void (*rx_bitset_iterator) (void *, int member_index);
45 #else
46 typedef void (*rx_bitset_iterator) ();
47 #endif
48
49 #define rx_bitset_subset(N)  ((N) / RX_subset_bits)
50 #define rx_bitset_subset_val(B,N)  ((B)[rx_bitset_subset(N)])
51 #define RX_bitset_access(B,N,OP) \
52   ((B)[rx_bitset_subset(N)] OP rx_subset_singletons[(N) & RX_subset_mask])
53 #define RX_bitset_member(B,N)   RX_bitset_access(B, N, &)
54 #define RX_bitset_enjoin(B,N)   RX_bitset_access(B, N, |=)
55 #define RX_bitset_remove(B,N)   RX_bitset_access(B, N, &= ~)
56 #define RX_bitset_toggle(B,N)   RX_bitset_access(B, N, ^= )
57 #define rx_bitset_numb_subsets(N) (((N) + RX_subset_bits - 1) / RX_subset_bits)
58 #define rx_sizeof_bitset(N)     (rx_bitset_numb_subsets(N) * sizeof(RX_subset))
59
60 \f
61
62 /* This page: Splay trees. */
63
64 #ifdef __STDC__
65 typedef int (*rx_sp_comparer) (void * a, void * b);
66 #else
67 typedef int (*rx_sp_comparer) ();
68 #endif
69
70 struct rx_sp_node 
71 {
72   void * key;
73   void * data;
74   struct rx_sp_node * kids[2];
75 };
76
77 #ifdef __STDC__
78 typedef void (*rx_sp_key_data_freer) (struct rx_sp_node *);
79 #else
80 typedef void (*rx_sp_key_data_freer) ();
81 #endif
82
83 \f
84 /* giant inflatable hash trees */
85
86 struct rx_hash_item
87 {
88   struct rx_hash_item * next_same_hash;
89   struct rx_hash * table;
90   unsigned long hash;
91   void * data;
92   void * binding;
93 };
94
95 struct rx_hash
96 {
97   struct rx_hash * parent;
98   int refs;
99   struct rx_hash * children[13];
100   struct rx_hash_item * buckets [13];
101   int bucket_size [13];
102 };
103
104 struct rx_hash_rules;
105
106 #ifdef __STDC__
107 /* should return like == */
108 typedef int (*rx_hash_eq)(void *, void *);
109 typedef struct rx_hash * (*rx_alloc_hash)(struct rx_hash_rules *);
110 typedef void (*rx_free_hash)(struct rx_hash *,
111                             struct rx_hash_rules *);
112 typedef struct rx_hash_item * (*rx_alloc_hash_item)(struct rx_hash_rules *,
113                                                     void *);
114 typedef void (*rx_free_hash_item)(struct rx_hash_item *,
115                                  struct rx_hash_rules *);
116 #else
117 typedef int (*rx_hash_eq)();
118 typedef struct rx_hash * (*rx_alloc_hash)();
119 typedef void (*rx_free_hash)();
120 typedef struct rx_hash_item * (*rx_alloc_hash_item)();
121 typedef void (*rx_free_hash_item)();
122 #endif
123
124 struct rx_hash_rules
125 {
126   rx_hash_eq eq;
127   rx_alloc_hash hash_alloc;
128   rx_free_hash free_hash;
129   rx_alloc_hash_item hash_item_alloc;
130   rx_free_hash_item free_hash_item;
131 };
132
133 \f
134 /* Forward declarations */
135
136 struct rx_cache;
137 struct rx_superset;
138 struct rx;
139 struct rx_se_list;
140
141 \f
142
143 /* 
144  * GLOSSARY
145  *
146  * regexp
147  * regular expression
148  * expression
149  * pattern - a `regular' expression.  The expression
150  *       need not be formally regular -- it can contain
151  *       constructs that don't correspond to purely regular
152  *       expressions.
153  *
154  * buffer
155  * string - the string (or strings) being searched or matched.
156  *
157  * pattern buffer - a structure of type `struct re_pattern_buffer'
158  *       This in turn contains a `struct rx', which holds the
159  *       NFA compiled from a pattern, as well as some of the state
160  *       of a matcher using the pattern.
161  *
162  * NFA - nondeterministic finite automata.  Some people
163  *       use this term to a member of the class of 
164  *       regular automata (those corresponding to a regular
165  *       language).  However, in this code, the meaning is
166  *       more general.  The automata used by Rx are comperable
167  *       in power to what are usually called `push down automata'.
168  *
169  *       Two NFA are built by rx for every pattern.  One is built
170  *       by the compiler.  The other is built from the first, on
171  *       the fly, by the matcher.  The latter is called the `superstate
172  *       NFA' because its states correspond to sets of states from
173  *       the first NFA.  (Joe Keane gets credit for the name
174  *       `superstate NFA').
175  *
176  * NFA edges
177  * epsilon edges
178  * side-effect edges - The NFA compiled from a pattern can have three
179  *       kinds of edges.  Epsilon edges can be taken freely anytime
180  *       their source state is reached.  Character set edges can be
181  *       taken when their source state is reached and when the next 
182  *       character in the buffer is a member of the set.  Side effect
183  *       edges imply a transition that can only be taken after the
184  *       indicated side effect has been successfully accomplished.
185  *       Some examples of side effects are:
186  *
187  *              Storing the current match position to record the
188  *              location of a parentesized subexpression.
189  *
190  *              Advancing the matcher over N characters if they
191  *              match the N characters previously matched by a 
192  *              parentesized subexpression.
193  *
194  *       Both of those kinds of edges occur in the NFA generated
195  *       by the pattern:  \(.\)\1
196  *
197  *       Epsilon and side effect edges are similar.  Unfortunately,
198  *       some of the code uses the name `epsilon edge' to mean
199  *       both epsilon and side effect edges.  For example,  the
200  *       function has_non_idempotent_epsilon_path computes the existance
201  *       of a non-trivial path containing only a mix of epsilon and
202  *       side effect edges.  In that case `nonidempotent epsilon' is being
203  *       used to mean `side effect'.
204  */
205
206
207
208 \f
209
210 /* LOW LEVEL PATTERN BUFFERS */
211
212 /* Suppose that from some NFA state, more than one path through
213  * side-effect edges is possible.  In what order should the paths
214  * be tried?  A function of type rx_se_list_order answers that
215  * question.  It compares two lists of side effects, and says
216  * which list comes first.
217  */
218  
219 #ifdef __STDC__
220 typedef int (*rx_se_list_order) (struct rx *,
221                                  struct rx_se_list *, 
222                                  struct rx_se_list *);
223 #else
224 typedef int (*rx_se_list_order) ();
225 #endif
226
227
228
229 /* Struct RX holds a compiled regular expression - that is, an nfa
230  * ready to be converted on demand to a more efficient superstate nfa.
231  * This is for the low level interface.  The high-level interfaces enclose
232  * this in a `struct re_pattern_buffer'.  
233  */
234 struct rx
235 {
236   /* The compiler assigns a unique id to every pattern.
237    * Like sequence numbers in X, there is a subtle bug here
238    * if you use Rx in a system that runs for a long time.
239    * But, because of the way the caches work out, it is almost
240    * impossible to trigger the Rx version of this bug.
241    *
242    * The id is used to validate superstates found in a cache
243    * of superstates.  It isn't sufficient to let a superstate
244    * point back to the rx for which it was compiled -- the caller
245    * may be re-using a `struct rx' in which case the superstate
246    * is not really valid.  So instead, superstates are validated
247    * by checking the sequence number of the pattern for which
248    * they were built.
249    */
250   int rx_id;
251
252   /* This is memory mgt. state for superstates.  This may be 
253    * shared by more than one struct rx.
254    */
255   struct rx_cache * cache;
256
257   /* Every regex defines the size of its own character set. 
258    * A superstate has an array of this size, with each element
259    * a `struct rx_inx'.  So, don't make this number too large.
260    * In particular, don't make it 2^16.
261    */
262   int local_cset_size;
263
264   /* After the NFA is built, it is copied into a contiguous region
265    * of memory (mostly for compatability with GNU regex).
266    * Here is that region, and it's size:
267    */
268   void * buffer;
269   unsigned long allocated;
270
271   /* Clients of RX can ask for some extra storage in the space pointed
272    * to by BUFFER.  The field RESERVED is an input parameter to the
273    * compiler.  After compilation, this much space will be available 
274    * at (buffer + allocated - reserved)
275    */
276   unsigned long reserved;
277
278   /* --------- The remaining fields are for internal use only. --------- */
279   /* --------- But! they must be initialized to 0.             --------- */
280
281   /* NODEC is the number of nodes in the NFA with non-epsilon
282    * transitions. 
283    */
284   int nodec;
285
286   /* EPSNODEC is the number of nodes with only epsilon transitions. */
287   int epsnodec;
288
289   /* The sum (NODEC + EPSNODEC) is the total number of states in the
290    * compiled NFA.
291    */
292
293   /* Lists of side effects as stored in the NFA are `hash consed'..meaning
294    * that lists with the same elements are ==.  During compilation, 
295    * this table facilitates hash-consing.
296    */
297   struct rx_hash se_list_memo;
298
299   /* Lists of NFA states are also hashed. 
300    */
301   struct rx_hash set_list_memo;
302
303
304
305
306   /* The compiler and matcher must build a number of instruction frames.
307    * The format of these frames is fixed (c.f. struct rx_inx).  The values
308    * of the instructions is not fixed.
309    *
310    * An enumerated type (enum rx_opcode) defines the set of instructions
311    * that the compiler or matcher might generate.  When filling an instruction
312    * frame, the INX field is found by indexing this instruction table
313    * with an opcode:
314    */
315   void ** instruction_table;
316
317   /* The list of all states in an NFA.
318    * During compilation, the NEXT field of NFA states links this list.
319    * After compilation, all the states are compacted into an array,
320    * ordered by state id numbers.  At that time, this points to the base 
321    * of that array.
322    */
323   struct rx_nfa_state *nfa_states;
324
325   /* Every nfa begins with one distinguished starting state:
326    */
327   struct rx_nfa_state *start;
328
329   /* This orders the search through super-nfa paths.
330    * See the comment near the typedef of rx_se_list_order.
331    */
332   rx_se_list_order se_list_cmp;
333
334   struct rx_superset * start_set;
335 };
336
337
338
339 \f
340 /* SYNTAX TREES */
341
342 /* Compilation is in stages.  
343  *
344  * In the first stage, a pattern specified by a string is 
345  * translated into a syntax tree.  Later stages will convert
346  * the syntax tree into an NFA optimized for conversion to a
347  * superstate-NFA.
348  *
349  * This page is about syntax trees.
350  */
351
352 enum rexp_node_type
353 {
354   r_cset,                       /* Match from a character set. `a' or `[a-z]'*/
355   r_concat,                     /* Concat two subexpressions.   `ab' */
356   r_alternate,                  /* Choose one of two subexpressions. `a\|b' */
357   r_opt,                        /* Optional subexpression. `a?' */
358   r_star,                       /* Repeated subexpression. `a*' */
359
360
361   /* A 2phase-star is a variation on a repeated subexpression.
362    * In this case, there are two subexpressions.  The first, if matched,
363    * begins a repitition (otherwise, the whole expression is matches the
364    * empth string).  
365    * 
366    * After matching the first subexpression, a 2phase star either finishes,
367    * or matches the second subexpression.  If the second subexpression is
368    * matched, then the whole construct repeats.
369    *
370    * 2phase stars are used in two circumstances.  First, they
371    * are used as part of the implementation of POSIX intervals (counted
372    * repititions).  Second, they are used to implement proper star
373    * semantics when the repeated subexpression contains paths of
374    * only side effects.  See rx_compile for more information.
375    */
376   r_2phase_star,
377
378
379   /* c.f. "typedef void * rx_side_effect" */
380   r_side_effect,
381
382   /* This is an extension type:  It is for transient use in source->source
383    * transformations (implemented over syntax trees).
384    */
385   r_data
386 };
387
388 /* A side effect is a matcher-specific action associated with
389  * transitions in the NFA.  The details of side effects are up
390  * to the matcher.  To the compiler and superstate constructors
391  * side effects are opaque:
392  */
393
394 typedef void * rx_side_effect;
395
396 /* Nodes in a syntax tree are of this type:
397  */
398 struct rexp_node
399 {
400   enum rexp_node_type type;
401   union
402   {
403     rx_Bitset cset;
404     rx_side_effect side_effect;
405     struct
406       {
407         struct rexp_node *left;
408         struct rexp_node *right;
409       } pair;
410     void * data;
411   } params;
412 };
413
414
415 \f
416 /* NFA
417  *
418  * A syntax tree is compiled into an NFA.  This page defines the structure
419  * of that NFA.
420  */
421
422 struct rx_nfa_state
423 {
424   /* These are kept in a list as the NFA is being built. */
425   struct rx_nfa_state *next;
426
427   /* After the NFA is built, states are given integer id's.
428    * States whose outgoing transitions are all either epsilon or 
429    * side effect edges are given ids less than 0.  Other states
430    * are given successive non-negative ids starting from 0.
431    */
432   int id;
433
434   /* The list of NFA edges that go from this state to some other. */
435   struct rx_nfa_edge *edges;
436
437   /* If you land in this state, then you implicitly land
438    * in all other states reachable by only epsilon translations.
439    * Call the set of maximal paths to such states the epsilon closure
440    * of this state.
441    *
442    * There may be other states that are reachable by a mixture of
443    * epsilon and side effect edges.  Consider the set of maximal paths
444    * of that sort from this state.  Call it the epsilon-side-effect
445    * closure of the state.
446    * 
447    * The epsilon closure of the state is a subset of the epsilon-side-
448    * effect closure.  It consists of all the paths that contain 
449    * no side effects -- only epsilon edges.
450    * 
451    * The paths in the epsilon-side-effect closure  can be partitioned
452    * into equivalance sets. Two paths are equivalant if they have the
453    * same set of side effects, in the same order.  The epsilon-closure
454    * is one of these equivalance sets.  Let's call these equivalance
455    * sets: observably equivalant path sets.  That name is chosen
456    * because equivalance of two paths means they cause the same side
457    * effects -- so they lead to the same subsequent observations other
458    * than that they may wind up in different target states.
459    *
460    * The superstate nfa, which is derived from this nfa, is based on
461    * the observation that all of the paths in an observably equivalant
462    * path set can be explored at the same time, provided that the
463    * matcher keeps track not of a single nfa state, but of a set of
464    * states.   In particular, after following all the paths in an
465    * observably equivalant set, you wind up at a set of target states.
466    * That set of target states corresponds to one state in the
467    * superstate NFA.
468    *
469    * Staticly, before matching begins, it is convenient to analyze the
470    * nfa.  Each state is labeled with a list of the observably
471    * equivalant path sets who's union covers all the
472    * epsilon-side-effect paths beginning in this state.  This list is
473    * called the possible futures of the state.
474    *
475    * A trivial example is this NFA:
476    *             s1
477    *         A  --->  B
478    *
479    *             s2  
480    *            --->  C
481    *
482    *             epsilon           s1
483    *            --------->  D   ------> E
484    * 
485    * 
486    * In this example, A has two possible futures.
487    * One invokes the side effect `s1' and contains two paths,
488    * one ending in state B, the other in state E.
489    * The other invokes the side effect `s2' and contains only
490    * one path, landing in state C.
491    */
492   struct rx_possible_future *futures;
493
494
495   /* There are exactly two distinguished states in every NFA: */
496   unsigned int is_final:1;
497   unsigned int is_start:1;
498
499   /* These are used during NFA construction... */
500   unsigned int eclosure_needed:1;
501   unsigned int mark:1;
502 };
503
504
505 /* An edge in an NFA is typed: */
506 enum rx_nfa_etype
507 {
508   /* A cset edge is labled with a set of characters one of which
509    * must be matched for the edge to be taken.
510    */
511   ne_cset,
512
513   /* An epsilon edge is taken whenever its starting state is
514    * reached. 
515    */
516   ne_epsilon,
517
518   /* A side effect edge is taken whenever its starting state is
519    * reached.  Side effects may cause the match to fail or the
520    * position of the matcher to advance.
521    */
522   ne_side_effect                /* A special kind of epsilon. */
523 };
524
525 struct rx_nfa_edge
526 {
527   struct rx_nfa_edge *next;
528   enum rx_nfa_etype type;
529   struct rx_nfa_state *dest;
530   union
531   {
532     rx_Bitset cset;
533     rx_side_effect side_effect;
534   } params;
535 };
536
537
538
539 /* A possible future consists of a list of side effects
540  * and a set of destination states.  Below are their
541  * representations.  These structures are hash-consed which
542  * means that lists with the same elements share a representation
543  * (their addresses are ==).
544  */
545
546 struct rx_nfa_state_set
547 {
548   struct rx_nfa_state * car;
549   struct rx_nfa_state_set * cdr;
550 };
551
552 struct rx_se_list
553 {
554   rx_side_effect car;
555   struct rx_se_list * cdr;
556 };
557
558 struct rx_possible_future
559 {
560   struct rx_possible_future *next;
561   struct rx_se_list * effects;
562   struct rx_nfa_state_set * destset;
563 };
564
565 \f
566
567 /* This begins the description of the superstate NFA.
568  *
569  * The superstate NFA corresponds to the NFA in these ways:
570  *
571  * Every superstate NFA states SUPER correspond to sets of NFA states,
572  * nfa_states(SUPER).
573  *
574  * Superstate edges correspond to NFA paths.
575  *
576  * The superstate has no epsilon transitions;
577  * every edge has a character label, and a (possibly empty) side
578  * effect label.   The side effect label corresponds to a list of
579  * side effects that occur in the NFA.  These parts are referred
580  * to as:   superedge_character(EDGE) and superedge_sides(EDGE).
581  *
582  * For a superstate edge EDGE starting in some superstate SUPER,
583  * the following is true (in pseudo-notation :-):
584  *
585  *       exists DEST in nfa_states s.t. 
586  *         exists nfaEDGE in nfa_edges s.t.
587  *                 origin (nfaEDGE) == DEST
588  *              && origin (nfaEDGE) is a member of nfa_states(SUPER)
589  *              && exists PF in possible_futures(dest(nfaEDGE)) s.t.
590  *                      sides_of_possible_future (PF) == superedge_sides (EDGE)
591  *
592  * also:
593  *
594  *      let SUPER2 := superedge_destination(EDGE)
595  *          nfa_states(SUPER2)
596  *           == union of all nfa state sets S s.t.
597  *                          exists PF in possible_futures(dest(nfaEDGE)) s.t.
598  *                             sides_of_possible_future (PF) == superedge_sides (EDGE)
599  *                          && S == dests_of_possible_future (PF) }
600  *
601  * Or in english, every superstate is a set of nfa states.  A given
602  * character and a superstate implies many transitions in the NFA --
603  * those that begin with an edge labeled with that character from a
604  * state in the set corresponding to the superstate.
605  * 
606  * The destinations of those transitions each have a set of possible
607  * futures.  A possible future is a list of side effects and a set of
608  * destination NFA states.  Two sets of possible futures can be
609  * `merged' by combining all pairs of possible futures that have the
610  * same side effects.  A pair is combined by creating a new future
611  * with the same side effect but the union of the two destination sets.
612  * In this way, all the possible futures suggested by a superstate
613  * and a character can be merged into a set of possible futures where
614  * no two elements of the set have the same set of side effects.
615  *
616  * The destination of a possible future, being a set of NFA states, 
617  * corresponds to a supernfa state.  So, the merged set of possible
618  * futures we just created can serve as a set of edges in the
619  * supernfa.
620  *
621  * The representation of the superstate nfa and the nfa is critical.
622  * The nfa has to be compact, but has to facilitate the rapid
623  * computation of missing superstates.  The superstate nfa has to 
624  * be fast to interpret, lazilly constructed, and bounded in space.
625  *
626  * To facilitate interpretation, the superstate data structures are 
627  * peppered with `instruction frames'.  There is an instruction set
628  * defined below which matchers using the supernfa must be able to
629  * interpret.
630  *
631  * We'd like to make it possible but not mandatory to use code
632  * addresses to represent instructions (c.f. gcc's computed goto).
633  * Therefore, we define an enumerated type of opcodes, and when
634  * writing one of these instructions into a data structure, use
635  * the opcode as an index into a table of instruction values.
636  * 
637  * Here are the opcodes that occur in the superstate nfa:
638  */
639  
640
641 /* Every superstate contains a table of instruction frames indexed 
642  * by characters.  A normal `move' in a matcher is to fetch the next
643  * character and use it as an index into a superstates transition
644  * table.
645  *
646  * In the fasted case, only one edge follows from that character.
647  * In other cases there is more work to do.
648  * 
649  * The descriptions of the opcodes refer to data structures that are
650  * described further below. 
651  */
652
653 enum rx_opcode
654 {
655   /* 
656    * BACKTRACK_POINT is invoked when a character transition in 
657    * a superstate leads to more than one edge.  In that case,
658    * the edges have to be explored independently using a backtracking
659    * strategy.
660    *
661    * A BACKTRACK_POINT instruction is stored in a superstate's 
662    * transition table for some character when it is known that that
663    * character crosses more than one edge.  On encountering this
664    * instruction, the matcher saves enough state to backtrack to this
665    * point in the match later.
666    */
667   rx_backtrack_point = 0,       /* data is (struct transition_class *) */
668
669   /* 
670    * RX_DO_SIDE_EFFECTS evaluates the side effects of an epsilon path.
671    * There is one occurence of this instruction per rx_distinct_future.
672    * This instruction is skipped if a rx_distinct_future has no side effects.
673    */
674   rx_do_side_effects = rx_backtrack_point + 1,
675
676   /* data is (struct rx_distinct_future *) */
677
678   /* 
679    * RX_CACHE_MISS instructions are stored in rx_distinct_futures whose
680    * destination superstate has been reclaimed (or was never built).
681    * It recomputes the destination superstate.
682    * RX_CACHE_MISS is also stored in a superstate transition table before
683    * any of its edges have been built.
684    */
685   rx_cache_miss = rx_do_side_effects + 1,
686   /* data is (struct rx_distinct_future *) */
687
688   /* 
689    * RX_NEXT_CHAR is called to consume the next character and take the
690    * corresponding transition.  This is the only instruction that uses 
691    * the DATA field of the instruction frame instead of DATA_2.
692    * (see EXPLORE_FUTURE in regex.c).
693    */
694   rx_next_char = rx_cache_miss + 1, /* data is (struct superstate *) */
695
696   /* RX_BACKTRACK indicates that a transition fails.
697    */
698   rx_backtrack = rx_next_char + 1, /* no data */
699
700   /* 
701    * RX_ERROR_INX is stored only in places that should never be executed.
702    */
703   rx_error_inx = rx_backtrack + 1, /* Not supposed to occur. */
704
705   rx_num_instructions = rx_error_inx + 1
706 };
707
708 /* An id_instruction_table holds the values stored in instruction
709  * frames.  The table is indexed by the enums declared above.
710  */
711 extern void * rx_id_instruction_table[rx_num_instructions];
712
713 /* The heart of the matcher is a `word-code-interpreter' 
714  * (like a byte-code interpreter, except that instructions
715  * are a full word wide).
716  *
717  * Instructions are not stored in a vector of code, instead,
718  * they are scattered throughout the data structures built
719  * by the regexp compiler and the matcher.  One word-code instruction,
720  * together with the arguments to that instruction, constitute
721  * an instruction frame (struct rx_inx).
722  *
723  * This structure type is padded by hand to a power of 2 because
724  * in one of the dominant cases, we dispatch by indexing a table
725  * of instruction frames.  If that indexing can be accomplished
726  * by just a shift of the index, we're happy.
727  *
728  * Instructions take at most one argument, but there are two
729  * slots in an instruction frame that might hold that argument.
730  * These are called data and data_2.  The data slot is only
731  * used for one instruction (RX_NEXT_CHAR).  For all other 
732  * instructions, data should be set to 0.
733  *
734  * RX_NEXT_CHAR is the most important instruction by far.
735  * By reserving the data field for its exclusive use, 
736  * instruction dispatch is sped up in that case.  There is
737  * no need to fetch both the instruction and the data,
738  * only the data is needed.  In other words, a `cycle' begins
739  * by fetching the field data.  If that is non-0, then it must
740  * be the destination state of a next_char transition, so
741  * make that value the current state, advance the match position
742  * by one character, and start a new cycle.  On the other hand,
743  * if data is 0, fetch the instruction and do a more complicated
744  * dispatch on that.
745  */
746
747 struct rx_inx 
748 {
749   void * data;
750   void * data_2;
751   void * inx;
752   void * fnord;
753 };
754
755 #ifndef RX_TAIL_ARRAY
756 #define RX_TAIL_ARRAY  1
757 #endif
758
759 /* A superstate corresponds to a set of nfa states.  Those sets are
760  * represented by STRUCT RX_SUPERSET.  The constructors
761  * guarantee that only one (shared) structure is created for a given set.
762  */
763 struct rx_superset
764 {
765   int refs;                     /* This is a reference counted structure. */
766
767   /* We keep these sets in a cache because (in an unpredictable way),
768    * the same set is often created again and again.  But that is also
769    * problematic -- compatibility with POSIX and GNU regex requires
770    * that we not be able to tell when a program discards a particular
771    * NFA (thus invalidating the supersets created from it).
772    *
773    * But when a cache hit appears to occur, we will have in hand the
774    * nfa for which it may have happened.  That is why every nfa is given
775    * its own sequence number.  On a cache hit, the cache is validated
776    * by comparing the nfa sequence number to this field:
777    */
778   int id;
779
780   struct rx_nfa_state * car;    /* May or may not be a valid addr. */
781   struct rx_superset * cdr;
782
783   /* If the corresponding superstate exists: */
784   struct rx_superstate * superstate;
785
786
787   /* There is another bookkeeping problem.  It is expensive to 
788    * compute the starting nfa state set for an nfa.  So, once computed,
789    * it is cached in the `struct rx'.
790    *
791    * But, the state set can be flushed from the superstate cache.
792    * When that happens, we can't know if the corresponding `struct rx'
793    * is still alive or if it has been freed or re-used by the program.
794    * So, the cached pointer to this set in a struct rx might be invalid
795    * and we need a way to validate it.
796    *
797    * Fortunately, even if this set is flushed from the cache, it is
798    * not freed.  It just goes on the free-list of supersets.
799    * So we can still examine it.  
800    *
801    * So to validate a starting set memo, check to see if the
802    * starts_for field still points back to the struct rx in question,
803    * and if the ID matches the rx sequence number.
804    */
805   struct rx * starts_for;
806
807   /* This is used to link into a hash bucket so these objects can
808    * be `hash-consed'.
809    */
810   struct rx_hash_item hash_item;
811 };
812
813 #define rx_protect_superset(RX,CON) (++(CON)->refs)
814
815 /* The terminology may be confusing (rename this structure?).
816  * Every character occurs in at most one rx_super_edge per super-state.
817  * But, that structure might have more than one option, indicating a point
818  * of non-determinism. 
819  *
820  * In other words, this structure holds a list of superstate edges
821  * sharing a common starting state and character label.  The edges
822  * are in the field OPTIONS.  All superstate edges sharing the same
823  * starting state and character are in this list.
824  */
825 struct rx_super_edge
826 {
827   struct rx_super_edge *next;
828   struct rx_inx rx_backtrack_frame;
829   int cset_size;
830   rx_Bitset cset;
831   struct rx_distinct_future *options;
832 };
833
834 /* A superstate is a set of nfa states (RX_SUPERSET) along
835  * with a transition table.  Superstates are built on demand and reclaimed
836  * without warning.  To protect a superstate from this ghastly fate,
837  * use LOCK_SUPERSTATE. 
838  */
839 struct rx_superstate
840 {
841   int rx_id;                    /* c.f. the id field of rx_superset */
842   int locks;                    /* protection from reclamation */
843
844   /* Within a superstate cache, all the superstates are kept in a big
845    * queue.  The tail of the queue is the state most likely to be
846    * reclaimed.  The *recyclable fields hold the queue position of 
847    * this state.
848    */
849   struct rx_superstate * next_recyclable;
850   struct rx_superstate * prev_recyclable;
851
852   /* The supernfa edges that exist in the cache and that have
853    * this state as their destination are kept in this list:
854    */
855   struct rx_distinct_future * transition_refs;
856
857   /* The list of nfa states corresponding to this superstate: */
858   struct rx_superset * contents;
859
860   /* The list of edges in the cache beginning from this state. */
861   struct rx_super_edge * edges;
862
863   /* A tail of the recyclable queue is marked as semifree.  A semifree
864    * state has no incoming next_char transitions -- any transition
865    * into a semifree state causes a complex dispatch with the side
866    * effect of rescuing the state from its semifree state.
867    *
868    * An alternative to this might be to make next_char more expensive,
869    * and to move a state to the head of the recyclable queue whenever
870    * it is entered.  That way, popular states would never be recycled.
871    *
872    * But unilaterally making next_char more expensive actually loses.
873    * So, incoming transitions are only made expensive for states near
874    * the tail of the recyclable queue.  The more cache contention
875    * there is, the more frequently a state will have to prove itself
876    * and be moved back to the front of the queue.  If there is less 
877    * contention, then popular states just aggregate in the front of 
878    * the queue and stay there.
879    */
880   int is_semifree;
881
882
883   /* This keeps track of the size of the transition table for this
884    * state.  There is a half-hearted attempt to support variable sized
885    * superstates.
886    */
887   int trans_size;
888
889   /* Indexed by characters... */
890   struct rx_inx transitions[RX_TAIL_ARRAY];
891 };
892
893
894 /* A list of distinct futures define the edges that leave from a 
895  * given superstate on a given character.  c.f. rx_super_edge.
896  */
897
898 struct rx_distinct_future
899 {
900   struct rx_distinct_future * next_same_super_edge[2];
901   struct rx_distinct_future * next_same_dest;
902   struct rx_distinct_future * prev_same_dest;
903   struct rx_superstate * present;       /* source state */
904   struct rx_superstate * future;        /* destination state */
905   struct rx_super_edge * edge;
906
907
908   /* The future_frame holds the instruction that should be executed
909    * after all the side effects are done, when it is time to complete
910    * the transition to the next state.
911    *
912    * Normally this is a next_char instruction, but it may be a
913    * cache_miss instruction as well, depending on whether or not
914    * the superstate is in the cache and semifree.
915    * 
916    * If this is the only future for a given superstate/char, and
917    * if there are no side effects to be performed, this frame is
918    * not used (directly) at all.  Instead, its contents are copied
919    * into the transition table of the starting state of this dist. future.
920    */
921   struct rx_inx future_frame;
922
923   struct rx_inx side_effects_frame;
924   struct rx_se_list * effects;
925 };
926
927 #define rx_lock_superstate(R,S)  ((S)->locks++)
928 #define rx_unlock_superstate(R,S) (--(S)->locks)
929
930 \f
931 /* This page destined for rx.h */
932
933 struct rx_blocklist
934 {
935   struct rx_blocklist * next;
936   int bytes;
937 };
938
939 struct rx_freelist
940 {
941   struct rx_freelist * next;
942 };
943
944 struct rx_cache;
945
946 #ifdef __STDC__
947 typedef void (*rx_morecore_fn)(struct rx_cache *);
948 #else
949 typedef void (*rx_morecore_fn)();
950 #endif
951
952 /* You use this to control the allocation of superstate data 
953  * during matching.  Most of it should be initialized to 0.
954  *
955  * A MORECORE function is necessary.  It should allocate
956  * a new block of memory or return 0.
957  * A default that uses malloc is called `rx_morecore'.
958  *
959  * The number of SUPERSTATES_ALLOWED indirectly limits how much memory
960  * the system will try to allocate.  The default is 128.  Batch style
961  * applications that are very regexp intensive should use as high a number
962  * as possible without thrashing.
963  * 
964  * The LOCAL_CSET_SIZE is the number of characters in a character set.
965  * It is therefore the number of entries in a superstate transition table.
966  * Generally, it should be 256.  If your character set has 16 bits, 
967  * it is better to translate your regexps into equivalent 8 bit patterns.
968  */
969
970 struct rx_cache
971 {
972   struct rx_hash_rules superset_hash_rules;
973
974   /* Objects are allocated by incrementing a pointer that 
975    * scans across rx_blocklists.
976    */
977   struct rx_blocklist * memory;
978   struct rx_blocklist * memory_pos;
979   int bytes_left;
980   char * memory_addr;
981   rx_morecore_fn morecore;
982
983   /* Freelists. */
984   struct rx_freelist * free_superstates;
985   struct rx_freelist * free_transition_classes;
986   struct rx_freelist * free_discernable_futures;
987   struct rx_freelist * free_supersets;
988   struct rx_freelist * free_hash;
989
990   /* Two sets of superstates -- those that are semifreed, and those
991    * that are being used.
992    */
993   struct rx_superstate * lru_superstate;
994   struct rx_superstate * semifree_superstate;
995
996   struct rx_superset * empty_superset;
997
998   int superstates;
999   int semifree_superstates;
1000   int hits;
1001   int misses;
1002   int superstates_allowed;
1003
1004   int local_cset_size;
1005   void ** instruction_table;
1006
1007   struct rx_hash superset_table;
1008 };
1009
1010 \f
1011
1012 /* The lowest-level search function supports arbitrarily fragmented
1013  * strings and (optionally) suspendable/resumable searches.
1014  *
1015  * Callers have to provide a few hooks.
1016  */
1017
1018 #ifndef __GNUC__
1019 #ifdef __STDC__
1020 #define __const__ const
1021 #else
1022 #define __const__
1023 #endif
1024 #endif
1025
1026 /* This holds a matcher position */
1027 struct rx_string_position
1028 {
1029   __const__ unsigned char * pos;        /* The current pos. */
1030   __const__ unsigned char * string; /* The current string burst. */
1031   __const__ unsigned char * end;        /* First invalid position >= POS. */
1032   int offset;                   /* Integer address of the current burst. */
1033   int size;                     /* Current string's size. */
1034   int search_direction;         /* 1 or -1 */
1035   int search_end;               /* First position to not try. */
1036 };
1037
1038
1039 enum rx_get_burst_return
1040 {
1041   rx_get_burst_continuation,
1042   rx_get_burst_error,
1043   rx_get_burst_ok,
1044   rx_get_burst_no_more
1045 };
1046
1047
1048 /* A call to get burst should make POS valid.  It might be invalid
1049  * if the STRING field doesn't point to a burst that actually
1050  * contains POS.
1051  *
1052  * GET_BURST should take a clue from SEARCH_DIRECTION (1 or -1) as to
1053  * whether or not to pad to the left.  Padding to the right is always
1054  * appropriate, but need not go past the point indicated by STOP.
1055  *
1056  * If a continuation is returned, then the reentering call to
1057  * a search function will retry the get_burst.
1058  */
1059
1060 #ifdef __STDC__
1061 typedef enum rx_get_burst_return
1062   (*rx_get_burst_fn) (struct rx_string_position * pos,
1063                       void * app_closure,
1064                       int stop);
1065                                                
1066 #else
1067 typedef enum rx_get_burst_return (*rx_get_burst_fn) ();
1068 #endif
1069
1070
1071 enum rx_back_check_return
1072 {
1073   rx_back_check_continuation,
1074   rx_back_check_error,
1075   rx_back_check_pass,
1076   rx_back_check_fail
1077 };
1078
1079 /* Back_check should advance the position it is passed 
1080  * over rparen - lparen characters and return pass iff
1081  * the characters starting at POS match those indexed
1082  * by [LPAREN..RPAREN].
1083  *
1084  * If a continuation is returned, then the reentering call to
1085  * a search function will retry the back_check.
1086  */
1087
1088 #ifdef __STDC__
1089 typedef enum rx_back_check_return
1090   (*rx_back_check_fn) (struct rx_string_position * pos,
1091                        int lparen,
1092                        int rparen,
1093                        unsigned char * translate,
1094                        void * app_closure,
1095                        int stop);
1096                                                
1097 #else
1098 typedef enum rx_back_check_return (*rx_back_check_fn) ();
1099 #endif
1100
1101
1102
1103
1104 /* A call to fetch_char should return the character at POS or POS + 1.
1105  * Returning continuations here isn't supported.  OFFSET is either 0 or 1
1106  * and indicates which characters is desired.
1107  */
1108
1109 #ifdef __STDC__
1110 typedef int (*rx_fetch_char_fn) (struct rx_string_position * pos,
1111                                  int offset,
1112                                  void * app_closure,
1113                                  int stop);
1114 #else
1115 typedef int (*rx_fetch_char_fn) ();
1116 #endif
1117
1118
1119 enum rx_search_return
1120 {
1121   rx_search_continuation = -4,
1122   rx_search_error = -3,
1123   rx_search_soft_fail = -2,     /* failed by running out of string */
1124   rx_search_fail = -1           /* failed only by reaching failure states */
1125   /* return values >= 0 indicate the position of a successful match */
1126 };
1127
1128
1129
1130
1131 \f
1132
1133 /* regex.h
1134  * 
1135  * The remaining declarations replace regex.h.
1136  */
1137
1138 /* This is an array of error messages corresponding to the error codes.
1139  */
1140 extern __const__ char *re_error_msg[];
1141
1142 /* If any error codes are removed, changed, or added, update the
1143    `re_error_msg' table in regex.c.  */
1144 typedef enum
1145 {
1146   REG_NOERROR = 0,      /* Success.  */
1147   REG_NOMATCH,          /* Didn't find a match (for regexec).  */
1148
1149   /* POSIX regcomp return error codes.  (In the order listed in the
1150      standard.)  */
1151   REG_BADPAT,           /* Invalid pattern.  */
1152   REG_ECOLLATE,         /* Not implemented.  */
1153   REG_ECTYPE,           /* Invalid character class name.  */
1154   REG_EESCAPE,          /* Trailing backslash.  */
1155   REG_ESUBREG,          /* Invalid back reference.  */
1156   REG_EBRACK,           /* Unmatched left bracket.  */
1157   REG_EPAREN,           /* Parenthesis imbalance.  */ 
1158   REG_EBRACE,           /* Unmatched \{.  */
1159   REG_BADBR,            /* Invalid contents of \{\}.  */
1160   REG_ERANGE,           /* Invalid range end.  */
1161   REG_ESPACE,           /* Ran out of memory.  */
1162   REG_BADRPT,           /* No preceding re for repetition op.  */
1163
1164   /* Error codes we've added.  */
1165   REG_EEND,             /* Premature end.  */
1166   REG_ESIZE,            /* Compiled pattern bigger than 2^16 bytes.  */
1167   REG_ERPAREN           /* Unmatched ) or \); not returned from regcomp.  */
1168 } reg_errcode_t;
1169
1170 /* The regex.c support, as a client of rx, defines a set of possible
1171  * side effects that can be added to the edge lables of nfa edges.
1172  * Here is the list of sidef effects in use.
1173  */
1174
1175 enum re_side_effects
1176 {
1177 #define RX_WANT_SE_DEFS 1
1178 #undef RX_DEF_SE
1179 #undef RX_DEF_CPLX_SE
1180 #define RX_DEF_SE(IDEM, NAME, VALUE)          NAME VALUE,
1181 #define RX_DEF_CPLX_SE(IDEM, NAME, VALUE)     NAME VALUE,
1182 #include "rx.h"
1183 #undef RX_DEF_SE
1184 #undef RX_DEF_CPLX_SE
1185 #undef RX_WANT_SE_DEFS
1186    re_floogle_flap = 65533
1187 };
1188
1189 /* These hold paramaters for the kinds of side effects that are possible
1190  * in the supported pattern languages.  These include things like the 
1191  * numeric bounds of {} operators and the index of paren registers for 
1192  * subexpression measurement or backreferencing.
1193  */
1194 struct re_se_params
1195 {
1196   enum re_side_effects se;
1197   int op1;
1198   int op2;
1199 };
1200
1201 typedef unsigned reg_syntax_t;
1202
1203 struct re_pattern_buffer
1204 {
1205   struct rx rx;
1206   reg_syntax_t syntax;          /* See below for syntax bit definitions. */
1207
1208   unsigned int no_sub:1;        /* If set, don't  return register offsets. */
1209   unsigned int not_bol:1;       /* If set, the anchors ('^' and '$') don't */
1210   unsigned int not_eol:1;       /*     match at the ends of the string.  */  
1211   unsigned int newline_anchor:1;/* If true, an anchor at a newline matches.*/
1212   unsigned int least_subs:1;    /* If set, and returning registers, return
1213                                  * as few values as possible.  Only 
1214                                  * backreferenced groups and group 0 (the whole
1215                                  * match) will be returned.
1216                                  */
1217
1218   /* If true, this says that the matcher should keep registers on its
1219    * backtracking stack.  For many patterns, we can easily determine that
1220    * this isn't necessary.
1221    */
1222   unsigned int match_regs_on_stack:1;
1223   unsigned int search_regs_on_stack:1;
1224
1225   /* is_anchored and begbuf_only are filled in by rx_compile. */
1226   unsigned int is_anchored:1;   /* Anchorded by ^? */
1227   unsigned int begbuf_only:1;   /* Anchored to char position 0? */
1228
1229   
1230   /* If REGS_UNALLOCATED, allocate space in the `regs' structure
1231    * for `max (RE_NREGS, re_nsub + 1)' groups.
1232    * If REGS_REALLOCATE, reallocate space if necessary.
1233    * If REGS_FIXED, use what's there.  
1234    */
1235 #define REGS_UNALLOCATED 0
1236 #define REGS_REALLOCATE 1
1237 #define REGS_FIXED 2
1238   unsigned int regs_allocated:2;
1239
1240   
1241   /* Either a translate table to apply to all characters before
1242    * comparing them, or zero for no translation.  The translation
1243    * is applied to a pattern when it is compiled and to a string
1244    * when it is matched.
1245    */
1246   unsigned char * translate;
1247
1248   /* If this is a valid pointer, it tells rx not to store the extents of 
1249    * certain subexpressions (those corresponding to non-zero entries).
1250    * Passing 0x1 is the same as passing an array of all ones.  Passing 0x0
1251    * is the same as passing an array of all zeros.
1252    * The array should contain as many entries as their are subexps in the 
1253    * regexp.
1254    *
1255    * For POSIX compatability, when using regcomp and regexec this field
1256    * is zeroed and ignored.
1257    */
1258   char * syntax_parens;
1259
1260         /* Number of subexpressions found by the compiler.  */
1261   size_t re_nsub;
1262
1263   void * buffer;                /* Malloced memory for the nfa. */
1264   unsigned long allocated;      /* Size of that memory. */
1265
1266   /* Pointer to a fastmap, if any, otherwise zero.  re_search uses
1267    * the fastmap, if there is one, to skip over impossible
1268    * starting points for matches.  */
1269   char *fastmap;
1270
1271   unsigned int fastmap_accurate:1; /* These three are internal. */
1272   unsigned int can_match_empty:1;  
1273   struct rx_nfa_state * start;  /* The nfa starting state. */
1274
1275   /* This is the list of iterator bounds for {lo,hi} constructs.
1276    * The memory pointed to is part of the rx->buffer.
1277    */
1278   struct re_se_params *se_params;
1279
1280   /* This is a bitset representation of the fastmap.
1281    * This is a true fastmap that already takes the translate
1282    * table into account.
1283    */
1284   rx_Bitset fastset;
1285 };
1286
1287 /* Type for byte offsets within the string.  POSIX mandates this.  */
1288 typedef int regoff_t;
1289
1290 /* This is the structure we store register match data in.  See
1291    regex.texinfo for a full description of what registers match.  */
1292 struct re_registers
1293 {
1294   unsigned num_regs;
1295   regoff_t *start;
1296   regoff_t *end;
1297 };
1298
1299 typedef struct re_pattern_buffer regex_t;
1300
1301 /* POSIX specification for registers.  Aside from the different names than
1302    `re_registers', POSIX uses an array of structures, instead of a
1303    structure of arrays.  */
1304 typedef struct
1305 {
1306   regoff_t rm_so;  /* Byte offset from string's start to substring's start.  */
1307   regoff_t rm_eo;  /* Byte offset from string's start to substring's end.  */
1308 } regmatch_t;
1309
1310 \f
1311 /* The following bits are used to determine the regexp syntax we
1312    recognize.  The set/not-set meanings are chosen so that Emacs syntax
1313    remains the value 0.  The bits are given in alphabetical order, and
1314    the definitions shifted by one from the previous bit; thus, when we
1315    add or remove a bit, only one other definition need change.  */
1316
1317 /* If this bit is not set, then \ inside a bracket expression is literal.
1318    If set, then such a \ quotes the following character.  */
1319 #define RE_BACKSLASH_ESCAPE_IN_LISTS (1)
1320
1321 /* If this bit is not set, then + and ? are operators, and \+ and \? are
1322      literals. 
1323    If set, then \+ and \? are operators and + and ? are literals.  */
1324 #define RE_BK_PLUS_QM (RE_BACKSLASH_ESCAPE_IN_LISTS << 1)
1325
1326 /* If this bit is set, then character classes are supported.  They are:
1327      [:alpha:], [:upper:], [:lower:],  [:digit:], [:alnum:], [:xdigit:],
1328      [:space:], [:print:], [:punct:], [:graph:], and [:cntrl:].
1329    If not set, then character classes are not supported.  */
1330 #define RE_CHAR_CLASSES (RE_BK_PLUS_QM << 1)
1331
1332 /* If this bit is set, then ^ and $ are always anchors (outside bracket
1333      expressions, of course).
1334    If this bit is not set, then it depends:
1335         ^  is an anchor if it is at the beginning of a regular
1336            expression or after an open-group or an alternation operator;
1337         $  is an anchor if it is at the end of a regular expression, or
1338            before a close-group or an alternation operator.  
1339
1340    This bit could be (re)combined with RE_CONTEXT_INDEP_OPS, because
1341    POSIX draft 11.2 says that * etc. in leading positions is undefined.
1342    We already implemented a previous draft which made those constructs
1343    invalid, though, so we haven't changed the code back.  */
1344 #define RE_CONTEXT_INDEP_ANCHORS (RE_CHAR_CLASSES << 1)
1345
1346 /* If this bit is set, then special characters are always special
1347      regardless of where they are in the pattern.
1348    If this bit is not set, then special characters are special only in
1349      some contexts; otherwise they are ordinary.  Specifically, 
1350      * + ? and intervals are only special when not after the beginning,
1351      open-group, or alternation operator.  */
1352 #define RE_CONTEXT_INDEP_OPS (RE_CONTEXT_INDEP_ANCHORS << 1)
1353
1354 /* If this bit is set, then *, +, ?, and { cannot be first in an re or
1355      immediately after an alternation or begin-group operator.  */
1356 #define RE_CONTEXT_INVALID_OPS (RE_CONTEXT_INDEP_OPS << 1)
1357
1358 /* If this bit is set, then . matches newline.
1359    If not set, then it doesn't.  */
1360 #define RE_DOT_NEWLINE (RE_CONTEXT_INVALID_OPS << 1)
1361
1362 /* If this bit is set, then . doesn't match NUL.
1363    If not set, then it does.  */
1364 #define RE_DOT_NOT_NULL (RE_DOT_NEWLINE << 1)
1365
1366 /* If this bit is set, nonmatching lists [^...] do not match newline.
1367    If not set, they do.  */
1368 #define RE_HAT_LISTS_NOT_NEWLINE (RE_DOT_NOT_NULL << 1)
1369
1370 /* If this bit is set, either \{...\} or {...} defines an
1371      interval, depending on RE_NO_BK_BRACES. 
1372    If not set, \{, \}, {, and } are literals.  */
1373 #define RE_INTERVALS (RE_HAT_LISTS_NOT_NEWLINE << 1)
1374
1375 /* If this bit is set, +, ? and | aren't recognized as operators.
1376    If not set, they are.  */
1377 #define RE_LIMITED_OPS (RE_INTERVALS << 1)
1378
1379 /* If this bit is set, newline is an alternation operator.
1380    If not set, newline is literal.  */
1381 #define RE_NEWLINE_ALT (RE_LIMITED_OPS << 1)
1382
1383 /* If this bit is set, then `{...}' defines an interval, and \{ and \}
1384      are literals.
1385   If not set, then `\{...\}' defines an interval.  */
1386 #define RE_NO_BK_BRACES (RE_NEWLINE_ALT << 1)
1387
1388 /* If this bit is set, (...) defines a group, and \( and \) are literals.
1389    If not set, \(...\) defines a group, and ( and ) are literals.  */
1390 #define RE_NO_BK_PARENS (RE_NO_BK_BRACES << 1)
1391
1392 /* If this bit is set, then \<digit> matches <digit>.
1393    If not set, then \<digit> is a back-reference.  */
1394 #define RE_NO_BK_REFS (RE_NO_BK_PARENS << 1)
1395
1396 /* If this bit is set, then | is an alternation operator, and \| is literal. 
1397    If not set, then \| is an alternation operator, and | is literal.  */
1398 #define RE_NO_BK_VBAR (RE_NO_BK_REFS << 1)
1399
1400 /* If this bit is set, then an ending range point collating higher
1401      than the starting range point, as in [z-a], is invalid.
1402    If not set, then when ending range point collates higher than the
1403      starting range point, the range is ignored.  */
1404 #define RE_NO_EMPTY_RANGES (RE_NO_BK_VBAR << 1)
1405
1406 /* If this bit is set, then an unmatched ) is ordinary.
1407    If not set, then an unmatched ) is invalid.  */
1408 #define RE_UNMATCHED_RIGHT_PAREN_ORD (RE_NO_EMPTY_RANGES << 1)
1409
1410 /* This global variable defines the particular regexp syntax to use (for
1411    some interfaces).  When a regexp is compiled, the syntax used is
1412    stored in the pattern buffer, so changing this does not affect
1413    already-compiled regexps.  */
1414 extern reg_syntax_t re_syntax_options;
1415 \f
1416 /* Define combinations of the above bits for the standard possibilities.
1417    (The [[[ comments delimit what gets put into the Texinfo file, so
1418    don't delete them!)  */ 
1419 /* [[[begin syntaxes]]] */
1420 #define RE_SYNTAX_EMACS 0
1421
1422 #define RE_SYNTAX_AWK                                                   \
1423   (RE_BACKSLASH_ESCAPE_IN_LISTS | RE_DOT_NOT_NULL                       \
1424    | RE_NO_BK_PARENS            | RE_NO_BK_REFS                         \
1425    | RE_NO_BK_VAR               | RE_NO_EMPTY_RANGES                    \
1426    | RE_UNMATCHED_RIGHT_PAREN_ORD)
1427
1428 #define RE_SYNTAX_POSIX_AWK                                             \
1429   (RE_SYNTAX_POSIX_EXTENDED | RE_BACKSLASH_ESCAPE_IN_LISTS)
1430
1431 #define RE_SYNTAX_GREP                                                  \
1432   (RE_BK_PLUS_QM              | RE_CHAR_CLASSES                         \
1433    | RE_HAT_LISTS_NOT_NEWLINE | RE_INTERVALS                            \
1434    | RE_NEWLINE_ALT)
1435
1436 #define RE_SYNTAX_EGREP                                                 \
1437   (RE_CHAR_CLASSES        | RE_CONTEXT_INDEP_ANCHORS                    \
1438    | RE_CONTEXT_INDEP_OPS | RE_HAT_LISTS_NOT_NEWLINE                    \
1439    | RE_NEWLINE_ALT       | RE_NO_BK_PARENS                             \
1440    | RE_NO_BK_VBAR)
1441
1442 #define RE_SYNTAX_POSIX_EGREP                                           \
1443   (RE_SYNTAX_EGREP | RE_INTERVALS | RE_NO_BK_BRACES)
1444
1445 #define RE_SYNTAX_SED RE_SYNTAX_POSIX_BASIC
1446
1447 /* Syntax bits common to both basic and extended POSIX regex syntax.  */
1448 #define _RE_SYNTAX_POSIX_COMMON                                         \
1449   (RE_CHAR_CLASSES | RE_DOT_NEWLINE      | RE_DOT_NOT_NULL              \
1450    | RE_INTERVALS  | RE_NO_EMPTY_RANGES)
1451
1452 #define RE_SYNTAX_POSIX_BASIC                                           \
1453   (_RE_SYNTAX_POSIX_COMMON | RE_BK_PLUS_QM)
1454
1455 /* Differs from ..._POSIX_BASIC only in that RE_BK_PLUS_QM becomes
1456    RE_LIMITED_OPS, i.e., \? \+ \| are not recognized.  Actually, this
1457    isn't minimal, since other operators, such as \`, aren't disabled.  */
1458 #define RE_SYNTAX_POSIX_MINIMAL_BASIC                                   \
1459   (_RE_SYNTAX_POSIX_COMMON | RE_LIMITED_OPS)
1460
1461 #define RE_SYNTAX_POSIX_EXTENDED                                        \
1462   (_RE_SYNTAX_POSIX_COMMON | RE_CONTEXT_INDEP_ANCHORS                   \
1463    | RE_CONTEXT_INDEP_OPS  | RE_NO_BK_BRACES                            \
1464    | RE_NO_BK_PARENS       | RE_NO_BK_VBAR                              \
1465    | RE_UNMATCHED_RIGHT_PAREN_ORD)
1466
1467 /* Differs from ..._POSIX_EXTENDED in that RE_CONTEXT_INVALID_OPS
1468    replaces RE_CONTEXT_INDEP_OPS and RE_NO_BK_REFS is added.  */
1469 #define RE_SYNTAX_POSIX_MINIMAL_EXTENDED                                \
1470   (_RE_SYNTAX_POSIX_COMMON  | RE_CONTEXT_INDEP_ANCHORS                  \
1471    | RE_CONTEXT_INVALID_OPS | RE_NO_BK_BRACES                           \
1472    | RE_NO_BK_PARENS        | RE_NO_BK_REFS                             \
1473    | RE_NO_BK_VBAR          | RE_UNMATCHED_RIGHT_PAREN_ORD)
1474 /* [[[end syntaxes]]] */
1475
1476 /* Maximum number of duplicates an interval can allow.  Some systems
1477    (erroneously) define this in other header files, but we want our
1478    value, so remove any previous define.  */
1479 #ifdef RE_DUP_MAX
1480 #undef RE_DUP_MAX
1481 #endif
1482 #define RE_DUP_MAX ((1 << 15) - 1) 
1483
1484
1485
1486 /* POSIX `cflags' bits (i.e., information for `regcomp').  */
1487
1488 /* If this bit is set, then use extended regular expression syntax.
1489    If not set, then use basic regular expression syntax.  */
1490 #define REG_EXTENDED 1
1491
1492 /* If this bit is set, then ignore case when matching.
1493    If not set, then case is significant.  */
1494 #define REG_ICASE (REG_EXTENDED << 1)
1495  
1496 /* If this bit is set, then anchors do not match at newline
1497      characters in the string.
1498    If not set, then anchors do match at newlines.  */
1499 #define REG_NEWLINE (REG_ICASE << 1)
1500
1501 /* If this bit is set, then report only success or fail in regexec.
1502    If not set, then returns differ between not matching and errors.  */
1503 #define REG_NOSUB (REG_NEWLINE << 1)
1504
1505
1506 /* POSIX `eflags' bits (i.e., information for regexec).  */
1507
1508 /* If this bit is set, then the beginning-of-line operator doesn't match
1509      the beginning of the string (presumably because it's not the
1510      beginning of a line).
1511    If not set, then the beginning-of-line operator does match the
1512      beginning of the string.  */
1513 #define REG_NOTBOL 1
1514
1515 /* Like REG_NOTBOL, except for the end-of-line.  */
1516 #define REG_NOTEOL (1 << 1)
1517
1518 /* If `regs_allocated' is REGS_UNALLOCATED in the pattern buffer,
1519  * `re_match_2' returns information about at least this many registers
1520  * the first time a `regs' structure is passed. 
1521  *
1522  * Also, this is the greatest number of backreferenced subexpressions
1523  * allowed in a pattern being matched without caller-supplied registers.
1524  */
1525 #ifndef RE_NREGS
1526 #define RE_NREGS 30
1527 #endif
1528
1529 extern int rx_cache_bound;
1530 extern char rx_version_string[];
1531
1532
1533 \f
1534 #ifdef RX_WANT_RX_DEFS
1535
1536 /* This is decls to the interesting subsystems and lower layers
1537  * of rx.  Everything which doesn't have a public counterpart in 
1538  * regex.c is declared here.
1539  */
1540
1541
1542 #ifdef __STDC__
1543 typedef void (*rx_hash_freefn) (struct rx_hash_item * it);
1544 #else /* ndef __STDC__ */
1545 typedef void (*rx_hash_freefn) ();
1546 #endif /* ndef __STDC__ */
1547
1548
1549 \f
1550
1551 #ifdef __STDC__
1552 RX_DECL int rx_bitset_is_equal (int size, rx_Bitset a, rx_Bitset b);
1553 RX_DECL int rx_bitset_is_subset (int size, rx_Bitset a, rx_Bitset b);
1554 RX_DECL int rx_bitset_empty (int size, rx_Bitset set);
1555 RX_DECL void rx_bitset_null (int size, rx_Bitset b);
1556 RX_DECL void rx_bitset_universe (int size, rx_Bitset b);
1557 RX_DECL void rx_bitset_complement (int size, rx_Bitset b);
1558 RX_DECL void rx_bitset_assign (int size, rx_Bitset a, rx_Bitset b);
1559 RX_DECL void rx_bitset_union (int size, rx_Bitset a, rx_Bitset b);
1560 RX_DECL void rx_bitset_intersection (int size,
1561                                      rx_Bitset a, rx_Bitset b);
1562 RX_DECL void rx_bitset_difference (int size, rx_Bitset a, rx_Bitset b);
1563 RX_DECL void rx_bitset_revdifference (int size,
1564                                       rx_Bitset a, rx_Bitset b);
1565 RX_DECL void rx_bitset_xor (int size, rx_Bitset a, rx_Bitset b);
1566 RX_DECL unsigned long rx_bitset_hash (int size, rx_Bitset b);
1567 RX_DECL struct rx_hash_item * rx_hash_find (struct rx_hash * table,
1568                                             unsigned long hash,
1569                                             void * value,
1570                                             struct rx_hash_rules * rules);
1571 RX_DECL struct rx_hash_item * rx_hash_store (struct rx_hash * table,
1572                                              unsigned long hash,
1573                                              void * value,
1574                                              struct rx_hash_rules * rules);
1575 RX_DECL void rx_hash_free (struct rx_hash_item * it, struct rx_hash_rules * rules);
1576 RX_DECL void rx_free_hash_table (struct rx_hash * tab, rx_hash_freefn freefn,
1577                                  struct rx_hash_rules * rules);
1578 RX_DECL rx_Bitset rx_cset (struct rx *rx);
1579 RX_DECL rx_Bitset rx_copy_cset (struct rx *rx, rx_Bitset a);
1580 RX_DECL void rx_free_cset (struct rx * rx, rx_Bitset c);
1581 RX_DECL struct rexp_node * rexp_node (struct rx *rx,
1582                                       enum rexp_node_type type);
1583 RX_DECL struct rexp_node * rx_mk_r_cset (struct rx * rx,
1584                                          rx_Bitset b);
1585 RX_DECL struct rexp_node * rx_mk_r_concat (struct rx * rx,
1586                                            struct rexp_node * a,
1587                                            struct rexp_node * b);
1588 RX_DECL struct rexp_node * rx_mk_r_alternate (struct rx * rx,
1589                                               struct rexp_node * a,
1590                                               struct rexp_node * b);
1591 RX_DECL struct rexp_node * rx_mk_r_opt (struct rx * rx,
1592                                         struct rexp_node * a);
1593 RX_DECL struct rexp_node * rx_mk_r_star (struct rx * rx,
1594                                          struct rexp_node * a);
1595 RX_DECL struct rexp_node * rx_mk_r_2phase_star (struct rx * rx,
1596                                                 struct rexp_node * a,
1597                                                 struct rexp_node * b);
1598 RX_DECL struct rexp_node * rx_mk_r_side_effect (struct rx * rx,
1599                                                 rx_side_effect a);
1600 RX_DECL struct rexp_node * rx_mk_r_data  (struct rx * rx,
1601                                           void * a);
1602 RX_DECL void rx_free_rexp (struct rx * rx, struct rexp_node * node);
1603 RX_DECL struct rexp_node * rx_copy_rexp (struct rx *rx,
1604                                          struct rexp_node *node);
1605 RX_DECL struct rx_nfa_state * rx_nfa_state (struct rx *rx);
1606 RX_DECL void rx_free_nfa_state (struct rx_nfa_state * n);
1607 RX_DECL struct rx_nfa_state * rx_id_to_nfa_state (struct rx * rx,
1608                                                   int id);
1609 RX_DECL struct rx_nfa_edge * rx_nfa_edge (struct rx *rx,
1610                                           enum rx_nfa_etype type,
1611                                           struct rx_nfa_state *start,
1612                                           struct rx_nfa_state *dest);
1613 RX_DECL void rx_free_nfa_edge (struct rx_nfa_edge * e);
1614 RX_DECL void rx_free_nfa (struct rx *rx);
1615 RX_DECL int rx_build_nfa (struct rx *rx,
1616                           struct rexp_node *rexp,
1617                           struct rx_nfa_state **start,
1618                           struct rx_nfa_state **end);
1619 RX_DECL void rx_name_nfa_states (struct rx *rx);
1620 RX_DECL int rx_eclose_nfa (struct rx *rx);
1621 RX_DECL void rx_delete_epsilon_transitions (struct rx *rx);
1622 RX_DECL int rx_compactify_nfa (struct rx *rx,
1623                                void **mem, unsigned long *size);
1624 RX_DECL void rx_release_superset (struct rx *rx,
1625                                   struct rx_superset *set);
1626 RX_DECL struct rx_superset * rx_superset_cons (struct rx * rx,
1627                                                struct rx_nfa_state *car, struct rx_superset *cdr);
1628 RX_DECL struct rx_superset * rx_superstate_eclosure_union
1629   (struct rx * rx, struct rx_superset *set, struct rx_nfa_state_set *ecl);
1630 RX_DECL struct rx_superstate * rx_superstate (struct rx *rx,
1631                                               struct rx_superset *set);
1632 RX_DECL struct rx_inx * rx_handle_cache_miss
1633   (struct rx *rx, struct rx_superstate *super, unsigned char chr, void *data);
1634 RX_DECL reg_errcode_t rx_compile (__const__ char *pattern, int size,
1635                                   reg_syntax_t syntax,
1636                                   struct re_pattern_buffer * rxb);
1637 RX_DECL void rx_blow_up_fastmap (struct re_pattern_buffer * rxb);
1638 #else /* STDC */
1639 RX_DECL int rx_bitset_is_equal ();
1640 RX_DECL int rx_bitset_is_subset ();
1641 RX_DECL int rx_bitset_empty ();
1642 RX_DECL void rx_bitset_null ();
1643 RX_DECL void rx_bitset_universe ();
1644 RX_DECL void rx_bitset_complement ();
1645 RX_DECL void rx_bitset_assign ();
1646 RX_DECL void rx_bitset_union ();
1647 RX_DECL void rx_bitset_intersection ();
1648 RX_DECL void rx_bitset_difference ();
1649 RX_DECL void rx_bitset_revdifference ();
1650 RX_DECL void rx_bitset_xor ();
1651 RX_DECL unsigned long rx_bitset_hash ();
1652 RX_DECL struct rx_hash_item * rx_hash_find ();
1653 RX_DECL struct rx_hash_item * rx_hash_store ();
1654 RX_DECL void rx_hash_free ();
1655 RX_DECL void rx_free_hash_table ();
1656 RX_DECL rx_Bitset rx_cset ();
1657 RX_DECL rx_Bitset rx_copy_cset ();
1658 RX_DECL void rx_free_cset ();
1659 RX_DECL struct rexp_node * rexp_node ();
1660 RX_DECL struct rexp_node * rx_mk_r_cset ();
1661 RX_DECL struct rexp_node * rx_mk_r_concat ();
1662 RX_DECL struct rexp_node * rx_mk_r_alternate ();
1663 RX_DECL struct rexp_node * rx_mk_r_opt ();
1664 RX_DECL struct rexp_node * rx_mk_r_star ();
1665 RX_DECL struct rexp_node * rx_mk_r_2phase_star ();
1666 RX_DECL struct rexp_node * rx_mk_r_side_effect ();
1667 RX_DECL struct rexp_node * rx_mk_r_data  ();
1668 RX_DECL void rx_free_rexp ();
1669 RX_DECL struct rexp_node * rx_copy_rexp ();
1670 RX_DECL struct rx_nfa_state * rx_nfa_state ();
1671 RX_DECL void rx_free_nfa_state ();
1672 RX_DECL struct rx_nfa_state * rx_id_to_nfa_state ();
1673 RX_DECL struct rx_nfa_edge * rx_nfa_edge ();
1674 RX_DECL void rx_free_nfa_edge ();
1675 RX_DECL void rx_free_nfa ();
1676 RX_DECL int rx_build_nfa ();
1677 RX_DECL void rx_name_nfa_states ();
1678 RX_DECL int rx_eclose_nfa ();
1679 RX_DECL void rx_delete_epsilon_transitions ();
1680 RX_DECL int rx_compactify_nfa ();
1681 RX_DECL void rx_release_superset ();
1682 RX_DECL struct rx_superset * rx_superset_cons ();
1683 RX_DECL struct rx_superset * rx_superstate_eclosure_union ();
1684 RX_DECL struct rx_superstate * rx_superstate ();
1685 RX_DECL struct rx_inx * rx_handle_cache_miss ();
1686 RX_DECL reg_errcode_t rx_compile ();
1687 RX_DECL void rx_blow_up_fastmap ();
1688 #endif /* STDC */
1689
1690
1691 #endif /* RX_WANT_RX_DEFS */
1692
1693
1694 \f
1695 #ifdef __STDC__
1696 extern int re_search_2 (struct re_pattern_buffer *rxb,
1697                         __const__ char * string1, int size1,
1698                         __const__ char * string2, int size2,
1699                         int startpos, int range,
1700                         struct re_registers *regs,
1701                         int stop);
1702 extern int re_search (struct re_pattern_buffer * rxb, __const__ char *string,
1703                       int size, int startpos, int range,
1704                       struct re_registers *regs);
1705 extern int re_match_2 (struct re_pattern_buffer * rxb,
1706                        __const__ char * string1, int size1,
1707                        __const__ char * string2, int size2,
1708                        int pos, struct re_registers *regs, int stop);
1709 extern int re_match (struct re_pattern_buffer * rxb,
1710                      __const__ char * string,
1711                      int size, int pos,
1712                      struct re_registers *regs);
1713 extern reg_syntax_t re_set_syntax (reg_syntax_t syntax);
1714 extern void re_set_registers (struct re_pattern_buffer *bufp,
1715                               struct re_registers *regs,
1716                               unsigned num_regs,
1717                               regoff_t * starts, regoff_t * ends);
1718 extern __const__ char * re_compile_pattern (__const__ char *pattern,
1719                                         int length,
1720                                         struct re_pattern_buffer * rxb);
1721 extern int re_compile_fastmap (struct re_pattern_buffer * rxb);
1722 extern char * re_comp (__const__ char *s);
1723 extern int re_exec (__const__ char *s);
1724 extern int regcomp (regex_t * preg, __const__ char * pattern, int cflags);
1725 extern int regexec (__const__ regex_t *preg, __const__ char *string,
1726                     size_t nmatch, regmatch_t pmatch[],
1727                     int eflags);
1728 extern size_t regerror (int errcode, __const__ regex_t *preg,
1729                         char *errbuf, size_t errbuf_size);
1730 extern void regfree (regex_t *preg);
1731
1732 #else /* STDC */
1733 extern int re_search_2 ();
1734 extern int re_search ();
1735 extern int re_match_2 ();
1736 extern int re_match ();
1737 extern reg_syntax_t re_set_syntax ();
1738 extern void re_set_registers ();
1739 extern __const__ char * re_compile_pattern ();
1740 extern int re_compile_fastmap ();
1741 extern char * re_comp ();
1742 extern int re_exec ();
1743 extern int regcomp ();
1744 extern int regexec ();
1745 extern size_t regerror ();
1746 extern void regfree ();
1747
1748 #endif /* STDC */
1749
1750 \f
1751
1752 #ifdef RX_WANT_RX_DEFS
1753
1754 struct rx_counter_frame
1755 {
1756   int tag;
1757   int val;
1758   struct rx_counter_frame * inherited_from; /* If this is a copy. */
1759   struct rx_counter_frame * cdr;
1760 };
1761
1762 struct rx_backtrack_frame
1763 {
1764   char * counter_stack_sp;
1765
1766   /* A frame is used to save the matchers state when it crosses a 
1767    * backtracking point.  The `stk_' fields correspond to variables
1768    * in re_search_2 (just strip off thes `stk_').  They are documented
1769    * tere.
1770    */
1771   struct rx_superstate * stk_super;
1772   unsigned int stk_c;
1773   struct rx_string_position stk_test_pos;
1774   int stk_last_l;
1775   int stk_last_r;
1776   int stk_test_ret;
1777
1778   /* This is the list of options left to explore at the backtrack
1779    * point for which this frame was created. 
1780    */
1781   struct rx_distinct_future * df;
1782   struct rx_distinct_future * first_df;
1783
1784 #ifdef RX_DEBUG
1785    int stk_line_no;
1786 #endif
1787 };
1788
1789 struct rx_stack_chunk
1790 {
1791   struct rx_stack_chunk * next_chunk;
1792   int bytes_left;
1793   char * sp;
1794 };
1795
1796 enum rx_outer_entry
1797 {
1798   rx_outer_start,
1799   rx_outer_fastmap,
1800   rx_outer_test,
1801   rx_outer_restore_pos
1802 };
1803
1804 enum rx_fastmap_return
1805 {
1806   rx_fastmap_continuation,
1807   rx_fastmap_error,
1808   rx_fastmap_ok,
1809   rx_fastmap_fail
1810 };
1811
1812 enum rx_fastmap_entry
1813 {
1814   rx_fastmap_start,
1815   rx_fastmap_string_break
1816 };
1817
1818 enum rx_test_return
1819 {
1820   rx_test_continuation,
1821   rx_test_error,
1822   rx_test_fail,
1823   rx_test_ok
1824 };
1825
1826 enum rx_test_internal_return
1827 {
1828   rx_test_internal_error,
1829   rx_test_found_first,
1830   rx_test_line_finished
1831 };
1832
1833 enum rx_test_match_entry
1834 {
1835   rx_test_start,
1836   rx_test_cache_hit_loop,
1837   rx_test_backreference_check,
1838   rx_test_backtrack_return
1839 };
1840
1841 struct rx_search_state
1842 {
1843   /* Two groups of registers are kept.  The group with the register state
1844    * of the current test match, and the group that holds the state at the end
1845    * of the best known match, if any.
1846    *
1847    * For some patterns, there may also be registers saved on the stack.
1848    */
1849   unsigned num_regs;            /* Includes an element for register zero. */
1850   regoff_t * lparen;            /* scratch space for register returns */
1851   regoff_t * rparen;
1852   regoff_t * best_lpspace;      /* in case the user doesn't want these */
1853   regoff_t * best_rpspace;      /* values, we still need space to store
1854                                  * them.  Normally, this memoryis unused
1855                                  * and the space pointed to by REGS is 
1856                                  * used instead.
1857                                  */
1858   
1859   int last_l;                   /* Highest index of a valid lparen. */
1860   int last_r;                   /* It's dual. */
1861   
1862   int * best_lparen;            /* This contains the best known register */
1863   int * best_rparen;            /* assignments. 
1864                                  * This may point to the same mem as
1865                                  * best_lpspace, or it might point to memory
1866                                  * passed by the caller.
1867                                  */
1868   int best_last_l;              /* best_last_l:best_lparen::last_l:lparen */
1869   int best_last_r;
1870
1871
1872   unsigned char * translate;  
1873
1874   struct rx_string_position outer_pos;
1875
1876   struct rx_superstate * start_super;
1877   int nfa_choice;
1878   int first_found;              /* If true, return after finding any match. */
1879   int ret_val;
1880
1881   /* For continuations... */
1882   enum rx_outer_entry outer_search_resume_pt;
1883   struct re_pattern_buffer * saved_rxb;
1884   int saved_startpos;
1885   int saved_range;
1886   int saved_stop;
1887   int saved_total_size;
1888   rx_get_burst_fn saved_get_burst;
1889   rx_back_check_fn saved_back_check;
1890   struct re_registers * saved_regs;
1891   
1892   /**
1893    ** state for fastmap
1894    **/
1895   char * fastmap;
1896   int fastmap_chr;
1897   int fastmap_val;
1898
1899   /* for continuations in the fastmap procedure: */
1900   enum rx_fastmap_entry fastmap_resume_pt;
1901
1902   /**
1903    ** state for test_match 
1904    **/
1905
1906   /* The current superNFA position of the matcher. */
1907   struct rx_superstate * super;
1908   
1909   /* The matcher interprets a series of instruction frames.
1910    * This is the `instruction counter' for the interpretation.
1911    */
1912   struct rx_inx * ifr;
1913   
1914   /* We insert a ghost character in the string to prime
1915    * the nfa.  test_pos.pos, test_pos.str_half, and test_pos.end_half
1916    * keep track of the test-match position and string-half.
1917    */
1918   unsigned char c;
1919   
1920   /* Position within the string. */
1921   struct rx_string_position test_pos;
1922
1923   struct rx_stack_chunk * counter_stack;
1924   struct rx_stack_chunk * backtrack_stack;
1925   int backtrack_frame_bytes;
1926   int chunk_bytes;
1927   struct rx_stack_chunk * free_chunks;
1928
1929   /* To return from this function, set test_ret and 
1930    * `goto test_do_return'.
1931    *
1932    * Possible return values are:
1933    *     1   --- end of string while the superNFA is still going
1934    *     0   --- internal error (out of memory)
1935    *    -1   --- search completed by reaching the superNFA fail state
1936    *    -2   --- a match was found, maybe not the longest.
1937    *
1938    * When the search is complete (-1), best_last_r indicates whether
1939    * a match was found.
1940    *
1941    * -2 is return only if search_state.first_found is non-zero.
1942    *
1943    * if search_state.first_found is non-zero, a return of -1 indicates no match,
1944    * otherwise, best_last_r has to be checked.
1945    */
1946   int test_ret;
1947
1948   int could_have_continued;
1949   
1950 #ifdef RX_DEBUG
1951   int backtrack_depth;
1952   /* There is a search tree with every node as set of deterministic
1953    * transitions in the super nfa.  For every branch of a 
1954    * backtrack point is an edge in the tree.
1955    * This counts up a pre-order of nodes in that tree.
1956    * It's saved on the search stack and printed when debugging. 
1957    */
1958   int line_no;
1959   int lines_found;
1960 #endif
1961
1962
1963   /* For continuations within the match tester */
1964   enum rx_test_match_entry test_match_resume_pt;
1965   struct rx_inx * saved_next_tr_table;
1966   struct rx_inx * saved_this_tr_table;
1967   int saved_reg;
1968   struct rx_backtrack_frame * saved_bf;
1969   
1970 };
1971
1972 \f
1973 extern char rx_slowmap[];
1974 extern unsigned char rx_id_translation[];
1975
1976 static __inline__ void
1977 init_fastmap (rxb, search_state)
1978      struct re_pattern_buffer * rxb;
1979      struct rx_search_state * search_state;
1980 {
1981   search_state->fastmap = (rxb->fastmap
1982                            ? (char *)rxb->fastmap
1983                            : (char *)rx_slowmap);
1984   /* Update the fastmap now if not correct already. 
1985    * When the regexp was compiled, the fastmap was computed
1986    * and stored in a bitset.  This expands the bitset into a
1987    * character array containing 1s and 0s.
1988    */
1989   if ((search_state->fastmap == rxb->fastmap) && !rxb->fastmap_accurate)
1990     rx_blow_up_fastmap (rxb);
1991   search_state->fastmap_chr = -1;
1992   search_state->fastmap_val = 0;
1993   search_state->fastmap_resume_pt = rx_fastmap_start;
1994 }
1995
1996 static __inline__ void
1997 uninit_fastmap (rxb, search_state)
1998      struct re_pattern_buffer * rxb;
1999      struct rx_search_state * search_state;
2000 {
2001   /* Unset the fastmap sentinel */
2002   if (search_state->fastmap_chr >= 0)
2003     search_state->fastmap[search_state->fastmap_chr]
2004       = search_state->fastmap_val;
2005 }
2006
2007 static __inline__ int
2008 fastmap_search (rxb, stop, get_burst, app_closure, search_state)
2009      struct re_pattern_buffer * rxb;
2010      int stop;
2011      rx_get_burst_fn get_burst;
2012      void * app_closure;
2013      struct rx_search_state * search_state;
2014 {
2015   enum rx_fastmap_entry pc;
2016
2017   if (0)
2018     {
2019     return_continuation:
2020       search_state->fastmap_resume_pt = pc;
2021       return rx_fastmap_continuation;
2022     }
2023
2024   pc = search_state->fastmap_resume_pt;
2025
2026   switch (pc)
2027     {
2028     default:
2029       return rx_fastmap_error;
2030     case rx_fastmap_start:
2031     init_fastmap_sentinal:
2032       /* For the sake of fast fastmapping, set a sentinal in the fastmap.
2033        * This sentinal will trap the fastmap loop when it reaches the last
2034        * valid character in a string half.
2035        *
2036        * This must be reset when the fastmap/search loop crosses a string 
2037        * boundry, and before returning to the caller.  So sometimes,
2038        * the fastmap loop is restarted with `continue', othertimes by
2039        * `goto init_fastmap_sentinal'.
2040        */
2041       if (search_state->outer_pos.size)
2042         {
2043           search_state->fastmap_chr = ((search_state->outer_pos.search_direction == 1)
2044                                        ? *(search_state->outer_pos.end - 1)
2045                                        : *search_state->outer_pos.string);
2046           search_state->fastmap_val
2047             = search_state->fastmap[search_state->fastmap_chr];
2048           search_state->fastmap[search_state->fastmap_chr] = 1;
2049         }
2050       else
2051         {
2052           search_state->fastmap_chr = -1;
2053           search_state->fastmap_val = 0;
2054         }
2055       
2056       if (search_state->outer_pos.pos >= search_state->outer_pos.end)
2057         goto fastmap_hit_bound;
2058       else
2059         {
2060           if (search_state->outer_pos.search_direction == 1)
2061             {
2062               if (search_state->fastmap_val)
2063                 {
2064                   for (;;)
2065                     {
2066                       while (!search_state->fastmap[*search_state->outer_pos.pos])
2067                         ++search_state->outer_pos.pos;
2068                       return rx_fastmap_ok;
2069                     }
2070                 }
2071               else
2072                 {
2073                   for (;;)
2074                     {
2075                       while (!search_state->fastmap[*search_state->outer_pos.pos])
2076                         ++search_state->outer_pos.pos;
2077                       if (*search_state->outer_pos.pos != search_state->fastmap_chr)
2078                         return rx_fastmap_ok;
2079                       else 
2080                         {
2081                           ++search_state->outer_pos.pos;
2082                           if (search_state->outer_pos.pos == search_state->outer_pos.end)
2083                             goto fastmap_hit_bound;
2084                         }
2085                     }
2086                 }
2087             }
2088           else
2089             {
2090               __const__ unsigned char * bound;
2091               bound = search_state->outer_pos.string - 1;
2092               if (search_state->fastmap_val)
2093                 {
2094                   for (;;)
2095                     {
2096                       while (!search_state->fastmap[*search_state->outer_pos.pos])
2097                         --search_state->outer_pos.pos;
2098                       return rx_fastmap_ok;
2099                     }
2100                 }
2101               else
2102                 {
2103                   for (;;)
2104                     {
2105                       while (!search_state->fastmap[*search_state->outer_pos.pos])
2106                         --search_state->outer_pos.pos;
2107                       if ((*search_state->outer_pos.pos != search_state->fastmap_chr) || search_state->fastmap_val)
2108                         return rx_fastmap_ok;
2109                       else 
2110                         {
2111                           --search_state->outer_pos.pos;
2112                           if (search_state->outer_pos.pos == bound)
2113                             goto fastmap_hit_bound;
2114                         }
2115                     }
2116                 }
2117             }
2118         }
2119       
2120     case rx_fastmap_string_break:
2121     fastmap_hit_bound:
2122       {
2123         /* If we hit a bound, it may be time to fetch another burst
2124          * of string, or it may be time to return a continuation to 
2125          * the caller, or it might be time to fail.
2126          */
2127
2128         int burst_state;
2129         burst_state = get_burst (&search_state->outer_pos, app_closure, stop);
2130         switch (burst_state)
2131           {
2132           default:
2133           case rx_get_burst_error:
2134             return rx_fastmap_error;
2135           case rx_get_burst_continuation:
2136             {
2137               pc = rx_fastmap_string_break;
2138               goto return_continuation;
2139             }
2140           case rx_get_burst_ok:
2141             goto init_fastmap_sentinal;
2142           case rx_get_burst_no_more:
2143             /* ...not a string split, simply no more string. 
2144              *
2145              * When searching backward, running out of string
2146              * is reason to quit.
2147              *
2148              * When searching forward, we allow the possibility
2149              * of an (empty) match after the last character in the
2150              * virtual string.  So, fall through to the matcher
2151              */
2152             return (  (search_state->outer_pos.search_direction == 1)
2153                     ? rx_fastmap_ok
2154                     : rx_fastmap_fail);
2155           }
2156       }
2157     }
2158
2159 }
2160
2161 \f
2162
2163 #ifdef emacs
2164 /* The `emacs' switch turns on certain matching commands
2165  * that make sense only in Emacs. 
2166  */
2167 #include "config.h"
2168 #include "lisp.h"
2169 #include "buffer.h"
2170 #include "syntax.h"
2171 #endif /* emacs */
2172
2173 /* Setting RX_MEMDBUG is useful if you have dbmalloc.  Maybe with similar
2174  * packages too.
2175  */
2176 #ifdef RX_MEMDBUG
2177 #include <malloc.h>
2178 #endif /* RX_RX_MEMDBUG */
2179
2180 /* We used to test for `BSTRING' here, but only GCC and Emacs define
2181  * `BSTRING', as far as I know, and neither of them use this code.  
2182  */
2183 #if HAVE_STRING_H || STDC_HEADERS
2184 #include <string.h>
2185
2186 #ifndef bcmp
2187 #define bcmp(s1, s2, n) memcmp ((s1), (s2), (n))
2188 #endif
2189
2190 #ifndef bcopy
2191 #define bcopy(s, d, n)  memcpy ((d), (s), (n))
2192 #endif
2193
2194 #ifndef bzero
2195 #define bzero(s, n)     memset ((s), 0, (n))
2196 #endif
2197
2198 #else /*  HAVE_STRING_H || STDC_HEADERS */
2199 #include <strings.h>
2200 #endif   /* not (HAVE_STRING_H || STDC_HEADERS) */
2201
2202 #ifdef STDC_HEADERS
2203 #include <stdlib.h>
2204 #else /* not STDC_HEADERS */
2205 char *malloc ();
2206 char *realloc ();
2207 #endif /* not STDC_HEADERS */
2208
2209
2210 \f
2211
2212 /* How many characters in the character set.  */
2213 #define CHAR_SET_SIZE (1 << CHARBITS)
2214
2215 #ifndef emacs
2216 /* Define the syntax basics for \<, \>, etc.
2217  * This must be nonzero for the wordchar and notwordchar pattern
2218  * commands in re_match_2.
2219  */
2220 #ifndef Sword 
2221 #define Sword 1
2222 #endif
2223 #define SYNTAX(c) re_syntax_table[c]
2224 #ifdef SYNTAX_TABLE
2225 extern char *re_syntax_table;
2226 #else
2227 RX_DECL char re_syntax_table[CHAR_SET_SIZE];
2228 #endif
2229 #endif /* not emacs */
2230
2231
2232 /* Test if at very beginning or at very end of the virtual concatenation
2233  *  of `string1' and `string2'.  If only one string, it's `string2'.  
2234  */
2235
2236 #define AT_STRINGS_BEG() \
2237   (   -1                 \
2238    == ((search_state.test_pos.pos - search_state.test_pos.string) \
2239        + search_state.test_pos.offset))
2240
2241 #define AT_STRINGS_END() \
2242   (   (total_size - 1)   \
2243    == ((search_state.test_pos.pos - search_state.test_pos.string) \
2244        + search_state.test_pos.offset))
2245
2246
2247 /* Test if POS + 1 points to a character which is word-constituent.  We have
2248  * two special cases to check for: if past the end of string1, look at
2249  * the first character in string2; and if before the beginning of
2250  * string2, look at the last character in string1.
2251  *
2252  * Assumes `string1' exists, so use in conjunction with AT_STRINGS_BEG ().  
2253  */
2254 #define LETTER_P(POS,OFF)                                               \
2255   (   SYNTAX (fetch_char(POS, OFF, app_closure, stop))                  \
2256    == Sword)
2257
2258 /* Test if the character at D and the one after D differ with respect
2259  * to being word-constituent.  
2260  */
2261 #define AT_WORD_BOUNDARY(d)                                             \
2262   (AT_STRINGS_BEG () || AT_STRINGS_END () || LETTER_P (d,0) != LETTER_P (d, 1))
2263
2264
2265 #ifdef RX_SUPPORT_CONTINUATIONS
2266 #define RX_STACK_ALLOC(BYTES) malloc(BYTES)
2267 #define RX_STACK_FREE(MEM) free(MEM)
2268 #else
2269 #define RX_STACK_ALLOC(BYTES) alloca(BYTES)
2270 #define RX_STACK_FREE(MEM) \
2271       ((struct rx_stack_chunk *)MEM)->next_chunk = search_state.free_chunks; \
2272       search_state.free_chunks = ((struct rx_stack_chunk *)MEM);
2273
2274 #endif
2275
2276 #define PUSH(CHUNK_VAR,BYTES)   \
2277   if (!CHUNK_VAR || (CHUNK_VAR->bytes_left < (BYTES)))  \
2278     {                                   \
2279       struct rx_stack_chunk * new_chunk;        \
2280       if (search_state.free_chunks)                     \
2281         {                               \
2282           new_chunk = search_state.free_chunks; \
2283           search_state.free_chunks = search_state.free_chunks->next_chunk; \
2284         }                               \
2285       else                              \
2286         {                               \
2287           new_chunk = (struct rx_stack_chunk *)RX_STACK_ALLOC(search_state.chunk_bytes); \
2288           if (!new_chunk)               \
2289             {                           \
2290               search_state.ret_val = 0;         \
2291               goto test_do_return;      \
2292             }                           \
2293         }                               \
2294       new_chunk->sp = (char *)new_chunk + sizeof (struct rx_stack_chunk); \
2295       new_chunk->bytes_left = (search_state.chunk_bytes \
2296                                - (BYTES) \
2297                                - sizeof (struct rx_stack_chunk)); \
2298       new_chunk->next_chunk = CHUNK_VAR; \
2299       CHUNK_VAR = new_chunk;            \
2300     } \
2301   else \
2302     (CHUNK_VAR->sp += (BYTES)), (CHUNK_VAR->bytes_left -= (BYTES))
2303
2304 #define POP(CHUNK_VAR,BYTES) \
2305   if (CHUNK_VAR->sp == ((char *)CHUNK_VAR + sizeof(*CHUNK_VAR))) \
2306     { \
2307       struct rx_stack_chunk * new_chunk = CHUNK_VAR->next_chunk; \
2308       RX_STACK_FREE(CHUNK_VAR); \
2309       CHUNK_VAR = new_chunk; \
2310     } \
2311   else \
2312     (CHUNK_VAR->sp -= BYTES), (CHUNK_VAR->bytes_left += BYTES)
2313
2314
2315
2316 #define SRCH_TRANSLATE(C)  search_state.translate[(unsigned char) (C)]
2317
2318
2319 \f
2320
2321 #ifdef __STDC__
2322 RX_DECL __inline__ int
2323 rx_search  (struct re_pattern_buffer * rxb,
2324             int startpos,
2325             int range,
2326             int stop,
2327             int total_size,
2328             rx_get_burst_fn get_burst,
2329             rx_back_check_fn back_check,
2330             rx_fetch_char_fn fetch_char,
2331             void * app_closure,
2332             struct re_registers * regs,
2333             struct rx_search_state * resume_state,
2334             struct rx_search_state * save_state)
2335 #else
2336 RX_DECL __inline__ int
2337 rx_search  (rxb, startpos, range, stop, total_size,
2338             get_burst, back_check, fetch_char,
2339             app_closure, regs, resume_state, save_state)
2340      struct re_pattern_buffer * rxb;
2341      int startpos;
2342      int range;
2343      int stop;
2344      int total_size;
2345      rx_get_burst_fn get_burst;
2346      rx_back_check_fn back_check;
2347      rx_fetch_char_fn fetch_char;
2348      void * app_closure;
2349      struct re_registers * regs;
2350      struct rx_search_state * resume_state;
2351      struct rx_search_state * save_state;
2352 #endif
2353 {
2354   int pc;
2355   int test_state;
2356   struct rx_search_state search_state;
2357
2358   search_state.free_chunks = 0;
2359   if (!resume_state)
2360     pc = rx_outer_start;
2361   else
2362     {
2363       search_state = *resume_state;
2364       regs = search_state.saved_regs;
2365       rxb = search_state.saved_rxb;
2366       startpos = search_state.saved_startpos;
2367       range = search_state.saved_range;
2368       stop = search_state.saved_stop;
2369       total_size = search_state.saved_total_size;
2370       get_burst = search_state.saved_get_burst;
2371       back_check = search_state.saved_back_check;
2372       pc = search_state.outer_search_resume_pt;
2373       if (0)
2374         {
2375         return_continuation:
2376           if (save_state)
2377             {
2378               *save_state = search_state;
2379               save_state->saved_regs = regs;
2380               save_state->saved_rxb = rxb;
2381               save_state->saved_startpos = startpos;
2382               save_state->saved_range = range;
2383               save_state->saved_stop = stop;
2384               save_state->saved_total_size = total_size;
2385               save_state->saved_get_burst = get_burst;
2386               save_state->saved_back_check = back_check;
2387               save_state->outer_search_resume_pt = pc;
2388             }
2389           return rx_search_continuation;
2390         }
2391     }
2392
2393   switch (pc)
2394     {
2395     case rx_outer_start:
2396       search_state.ret_val = rx_search_fail;
2397       (  search_state.lparen
2398        = search_state.rparen
2399        = search_state.best_lpspace
2400        = search_state.best_rpspace
2401        = 0);
2402       
2403       /* figure the number of registers we may need for use in backreferences.
2404        * the number here includes an element for register zero.  
2405        */
2406       search_state.num_regs = rxb->re_nsub + 1;
2407       
2408       
2409       /* check for out-of-range startpos.  */
2410       if ((startpos < 0) || (startpos > total_size))
2411         return rx_search_fail;
2412       
2413       /* fix up range if it might eventually take us outside the string. */
2414       {
2415         int endpos;
2416         endpos = startpos + range;
2417         if (endpos < -1)
2418           range = (-1 - startpos);
2419         else if (endpos > (total_size + 1))
2420           range = total_size - startpos;
2421       }
2422       
2423       /* if the search isn't to be a backwards one, don't waste time in a
2424        * long search for a pattern that says it is anchored.
2425        */
2426       if (rxb->begbuf_only && (range > 0))
2427         {
2428           if (startpos > 0)
2429             return rx_search_fail;
2430           else
2431             range = 1;
2432         }
2433       
2434       /* decide whether to use internal or user-provided reg buffers. */
2435       if (!regs || rxb->no_sub)
2436         {
2437           search_state.best_lpspace =
2438             (regoff_t *)REGEX_ALLOCATE (search_state.num_regs * sizeof(regoff_t));
2439           search_state.best_rpspace =
2440             (regoff_t *)REGEX_ALLOCATE (search_state.num_regs * sizeof(regoff_t));
2441           search_state.best_lparen = search_state.best_lpspace;
2442           search_state.best_rparen = search_state.best_rpspace;
2443         }
2444       else
2445         {       
2446           /* have the register data arrays been allocated?  */
2447           if (rxb->regs_allocated == REGS_UNALLOCATED)
2448             { /* no.  so allocate them with malloc.  we need one
2449                  extra element beyond `search_state.num_regs' for the `-1' marker
2450                  gnu code uses.  */
2451               regs->num_regs = MAX (RE_NREGS, rxb->re_nsub + 1);
2452               regs->start = ((regoff_t *)
2453                              malloc (regs->num_regs * sizeof ( regoff_t)));
2454               regs->end = ((regoff_t *)
2455                            malloc (regs->num_regs * sizeof ( regoff_t)));
2456               if (regs->start == 0 || regs->end == 0)
2457                 return rx_search_error;
2458               rxb->regs_allocated = REGS_REALLOCATE;
2459             }
2460           else if (rxb->regs_allocated == REGS_REALLOCATE)
2461             { /* yes.  if we need more elements than were already
2462                  allocated, reallocate them.  if we need fewer, just
2463                  leave it alone.  */
2464               if (regs->num_regs < search_state.num_regs + 1)
2465                 {
2466                   regs->num_regs = search_state.num_regs + 1;
2467                   regs->start = ((regoff_t *)
2468                                  realloc (regs->start,
2469                                           regs->num_regs * sizeof (regoff_t)));
2470                   regs->end = ((regoff_t *)
2471                                realloc (regs->end,
2472                                         regs->num_regs * sizeof ( regoff_t)));
2473                   if (regs->start == 0 || regs->end == 0)
2474                     return rx_search_error;
2475                 }
2476             }
2477           else if (rxb->regs_allocated != REGS_FIXED)
2478             return rx_search_error;
2479           
2480           if (regs->num_regs < search_state.num_regs + 1)
2481             {
2482               search_state.best_lpspace =
2483                 ((regoff_t *)
2484                  REGEX_ALLOCATE (search_state.num_regs * sizeof(regoff_t)));
2485               search_state.best_rpspace =
2486                 ((regoff_t *)
2487                  REGEX_ALLOCATE (search_state.num_regs * sizeof(regoff_t)));
2488               search_state.best_lparen = search_state.best_lpspace;
2489               search_state.best_rparen = search_state.best_rpspace;
2490             }
2491           else
2492             {
2493               search_state.best_lparen = regs->start;
2494               search_state.best_rparen = regs->end;
2495             }
2496         }
2497       
2498       search_state.lparen =
2499         (regoff_t *) REGEX_ALLOCATE (search_state.num_regs * sizeof(regoff_t));
2500       search_state.rparen =
2501         (regoff_t *) REGEX_ALLOCATE (search_state.num_regs * sizeof(regoff_t)); 
2502       
2503       if (! (   search_state.best_rparen
2504              && search_state.best_lparen
2505              && search_state.lparen && search_state.rparen))
2506         return rx_search_error;
2507       
2508       search_state.best_last_l = search_state.best_last_r = -1;
2509       
2510       search_state.translate = (rxb->translate
2511                                 ? rxb->translate
2512                                 : rx_id_translation);
2513       
2514       
2515       
2516       /*
2517        * two nfa's were compiled.  
2518        * `0' is complete.
2519        * `1' faster but gets registers wrong and ends too soon.
2520        */
2521       search_state.nfa_choice = (regs && !rxb->least_subs) ? '\0' : '\1';
2522       
2523       /* we have the option to look for the best match or the first
2524        * one we can find.  if the user isn't asking for register information,
2525        * we don't need to find the best match.
2526        */
2527       search_state.first_found = !regs;
2528       
2529       if (range >= 0)
2530         {
2531           search_state.outer_pos.search_end = startpos + range;
2532           search_state.outer_pos.search_direction = 1;
2533         }
2534       else
2535         {
2536           search_state.outer_pos.search_end = startpos + range;
2537           search_state.outer_pos.search_direction = -1;
2538         }
2539       
2540       /* the vacuous search always turns up nothing. */
2541       if ((search_state.outer_pos.search_direction == 1)
2542           ? (startpos > search_state.outer_pos.search_end)
2543           : (startpos < search_state.outer_pos.search_end))
2544         return rx_search_fail;
2545       
2546       /* now we build the starting state of the supernfa. */
2547       {
2548         struct rx_superset * start_contents;
2549         struct rx_nfa_state_set * start_nfa_set;
2550         
2551         /* we presume here that the nfa start state has only one
2552          * possible future with no side effects.  
2553          */
2554         start_nfa_set = rxb->start->futures->destset;
2555         if (   rxb->rx.start_set
2556             && (rxb->rx.start_set->starts_for == &rxb->rx))
2557           start_contents = rxb->rx.start_set;
2558         else
2559           {
2560             start_contents =
2561               rx_superstate_eclosure_union (&rxb->rx,
2562                                             rx_superset_cons (&rxb->rx, 0, 0),
2563                                             start_nfa_set);
2564             
2565             if (!start_contents)
2566               return rx_search_fail;
2567             
2568             start_contents->starts_for = &rxb->rx;
2569             rxb->rx.start_set = start_contents;
2570           }
2571         if (   start_contents->superstate
2572             && (start_contents->superstate->rx_id == rxb->rx.rx_id))
2573           {
2574             search_state.start_super = start_contents->superstate;
2575             rx_lock_superstate (&rxb->rx, search_state.start_super);
2576           }
2577         else
2578           {
2579             rx_protect_superset (&rxb->rx, start_contents);
2580             
2581             search_state.start_super = rx_superstate (&rxb->rx, start_contents);
2582             if (!search_state.start_super)
2583               return rx_search_fail;
2584             rx_lock_superstate (&rxb->rx, search_state.start_super);
2585             rx_release_superset (&rxb->rx, start_contents);
2586           }
2587       }
2588       
2589       
2590       /* The outer_pos tracks the position within the strings
2591        * as seen by loop that calls fastmap_search.
2592        *
2593        * The caller supplied get_burst function actually 
2594        * gives us pointers to chars.
2595        * 
2596        * Communication with the get_burst function is through an
2597        * rx_string_position structure.  Here, the structure for
2598        * outer_pos is initialized.   It is set to point to the
2599        * NULL string, at an offset of STARTPOS.  STARTPOS is out
2600        * of range of the NULL string, so the first call to 
2601        * getburst will patch up the rx_string_position to point
2602        * to valid characters.
2603        */
2604
2605       (  search_state.outer_pos.string
2606        = search_state.outer_pos.end
2607        = 0);
2608
2609       search_state.outer_pos.offset = 0;
2610       search_state.outer_pos.size = 0;
2611       search_state.outer_pos.pos = (unsigned char *)startpos;
2612       init_fastmap (rxb, &search_state);
2613
2614       search_state.fastmap_resume_pt = rx_fastmap_start;
2615     case rx_outer_fastmap:
2616       /* do { */
2617     pseudo_do:
2618       {
2619         {
2620           int fastmap_state;
2621           fastmap_state = fastmap_search (rxb, stop, get_burst, app_closure,
2622                                           &search_state);
2623           switch (fastmap_state)
2624             {
2625             case rx_fastmap_continuation:
2626               pc = rx_outer_fastmap;
2627               goto return_continuation;
2628             case rx_fastmap_fail:
2629               goto finish;
2630             case rx_fastmap_ok:
2631               break;
2632             }
2633         }
2634         
2635         /* now the fastmap loop has brought us to a plausible 
2636          * starting point for a match.  so, it's time to run the
2637          * nfa and see if a match occured.
2638          */
2639         startpos = (  search_state.outer_pos.pos
2640                     - search_state.outer_pos.string
2641                     + search_state.outer_pos.offset);
2642 /*|*/   if ((range > 0) && (startpos == search_state.outer_pos.search_end))
2643 /*|*/     goto finish;
2644       }
2645
2646       search_state.test_match_resume_pt = rx_test_start;
2647       /* do interrupted for entry point... */
2648     case rx_outer_test:
2649       /* ...do continued */
2650       {
2651         goto test_match;
2652       test_returns_to_search:
2653         switch (test_state)
2654           {
2655           case rx_test_continuation:
2656             pc = rx_outer_test;
2657             goto return_continuation;
2658           case rx_test_error:
2659             search_state.ret_val = rx_search_error;
2660             goto finish;
2661           case rx_test_fail:
2662             break;
2663           case rx_test_ok:
2664             goto finish;
2665           }
2666         search_state.outer_pos.pos += search_state.outer_pos.search_direction;
2667         startpos += search_state.outer_pos.search_direction;
2668 #if 0
2669 /*|*/   if (search_state.test_pos.pos < search_state.test_pos.end)
2670 /*|*/     break;
2671 #endif
2672       }
2673       /* do interrupted for entry point... */
2674     case rx_outer_restore_pos:
2675       {
2676         int x;
2677         x = get_burst (&search_state.outer_pos, app_closure, stop);
2678         switch (x)
2679           {
2680           case rx_get_burst_continuation:
2681             pc = rx_outer_restore_pos;
2682             goto return_continuation;
2683           case rx_get_burst_error:
2684             search_state.ret_val = rx_search_error;
2685             goto finish;
2686           case rx_get_burst_no_more:
2687             if (rxb->can_match_empty)
2688               break;
2689             goto finish;
2690           case rx_get_burst_ok:
2691             break;
2692           }
2693       } /* } while (...see below...) */
2694
2695       if ((search_state.outer_pos.search_direction == 1)
2696           ? (startpos < search_state.outer_pos.search_end)
2697           : (startpos > search_state.outer_pos.search_end))
2698         goto pseudo_do;
2699
2700         
2701     finish:
2702       uninit_fastmap (rxb, &search_state);
2703       if (search_state.start_super)
2704         rx_unlock_superstate (&rxb->rx, search_state.start_super);
2705       
2706 #ifdef regex_malloc
2707       if (search_state.lparen) free (search_state.lparen);
2708       if (search_state.rparen) free (search_state.rparen);
2709       if (search_state.best_lpspace) free (search_state.best_lpspace);
2710       if (search_state.best_rpspace) free (search_state.best_rpspace);
2711 #endif
2712       return search_state.ret_val;
2713     }
2714
2715
2716  test_match:
2717   {
2718     enum rx_test_match_entry test_pc;
2719     int inx;
2720     test_pc = search_state.test_match_resume_pt;
2721     if (test_pc == rx_test_start)
2722       {
2723 #ifdef RX_DEBUG
2724         search_state.backtrack_depth = 0;
2725 #endif
2726         search_state.last_l = search_state.last_r = 0;
2727         search_state.lparen[0] = startpos;
2728         search_state.super = search_state.start_super;
2729         search_state.c = search_state.nfa_choice;
2730         search_state.test_pos.pos = search_state.outer_pos.pos - 1;    
2731         search_state.test_pos.string = search_state.outer_pos.string;
2732         search_state.test_pos.end = search_state.outer_pos.end;
2733         search_state.test_pos.offset = search_state.outer_pos.offset;
2734         search_state.test_pos.size = search_state.outer_pos.size;
2735         search_state.test_pos.search_direction = 1;
2736         search_state.counter_stack = 0;
2737         search_state.backtrack_stack = 0;
2738         search_state.backtrack_frame_bytes =
2739           (sizeof (struct rx_backtrack_frame)
2740            + (rxb->match_regs_on_stack
2741               ? sizeof (regoff_t) * (search_state.num_regs + 1) * 2
2742               : 0));
2743         search_state.chunk_bytes = search_state.backtrack_frame_bytes * 64;
2744         search_state.test_ret = rx_test_line_finished;
2745         search_state.could_have_continued = 0;
2746       }  
2747     /* This is while (1)...except that the body of the loop is interrupted 
2748      * by some alternative entry points.
2749      */
2750   pseudo_while_1:
2751     switch (test_pc)
2752       {
2753       case rx_test_cache_hit_loop:
2754         goto resume_continuation_1;
2755       case rx_test_backreference_check:
2756         goto resume_continuation_2;
2757       case rx_test_backtrack_return:
2758         goto resume_continuation_3;
2759       case rx_test_start:
2760 #ifdef RX_DEBUG
2761         /* There is a search tree with every node as set of deterministic
2762          * transitions in the super nfa.  For every branch of a 
2763          * backtrack point is an edge in the tree.
2764          * This counts up a pre-order of nodes in that tree.
2765          * It's saved on the search stack and printed when debugging. 
2766          */
2767         search_state.line_no = 0;
2768         search_state.lines_found = 0;
2769 #endif
2770         
2771       top_of_cycle:
2772         /* A superstate is basicly a transition table, indexed by 
2773          * characters from the string being tested, and containing 
2774          * RX_INX (`instruction frame') structures.
2775          */
2776         search_state.ifr = &search_state.super->transitions [search_state.c];
2777         
2778       recurse_test_match:
2779         /* This is the point to which control is sent when the
2780          * test matcher `recurses'.  Before jumping here, some variables
2781          * need to be saved on the stack and the next instruction frame
2782          * has to be computed.
2783          */
2784         
2785       restart:
2786         /* Some instructions don't advance the matcher, but just
2787          * carry out some side effects and fetch a new instruction.
2788          * To dispatch that new instruction, `goto restart'.
2789          */
2790         
2791         {
2792           struct rx_inx * next_tr_table;
2793           struct rx_inx * this_tr_table;
2794           /* The fastest route through the loop is when the instruction 
2795            * is RX_NEXT_CHAR.  This case is detected when SEARCH_STATE.IFR->DATA
2796            * is non-zero.  In that case, it points to the next
2797            * superstate. 
2798            *
2799            * This allows us to not bother fetching the bytecode.
2800            */
2801           next_tr_table = (struct rx_inx *)search_state.ifr->data;
2802           this_tr_table = search_state.super->transitions;
2803           while (next_tr_table)
2804             {
2805 #ifdef RX_DEBUG_0
2806               if (rx_debug_trace)
2807                 {
2808                   struct rx_superset * setp;
2809                   
2810                   fprintf (stderr, "%d %d>> re_next_char @ %d (%d)",
2811                            search_state.line_no,
2812                            search_state.backtrack_depth,
2813                            (search_state.test_pos.pos - search_state.test_pos.string
2814                             + search_state.test_pos.offset), search_state.c);
2815                   
2816                   search_state.super =
2817                     ((struct rx_superstate *)
2818                      ((char *)this_tr_table
2819                       - ((unsigned long)
2820                          ((struct rx_superstate *)0)->transitions)));
2821                   
2822                   setp = search_state.super->contents;
2823                   fprintf (stderr, "   superstet (rx=%d, &=%x: ",
2824                            rxb->rx.rx_id, setp);
2825                   while (setp)
2826                     {
2827                       fprintf (stderr, "%d ", setp->id);
2828                       setp = setp->cdr;
2829                     }
2830                   fprintf (stderr, "\n");
2831                 }
2832 #endif
2833               this_tr_table = next_tr_table;
2834               ++search_state.test_pos.pos;
2835               if (search_state.test_pos.pos == search_state.test_pos.end)
2836                 {
2837                   int burst_state;
2838                 try_burst_1:
2839                   burst_state = get_burst (&search_state.test_pos,
2840                                            app_closure, stop);
2841                   switch (burst_state)
2842                     {
2843                     case rx_get_burst_continuation:
2844                       search_state.saved_this_tr_table = this_tr_table;
2845                       search_state.saved_next_tr_table = next_tr_table;
2846                       test_pc = rx_test_cache_hit_loop;
2847                       goto test_return_continuation;
2848                       
2849                     resume_continuation_1:
2850                       /* Continuation one jumps here to do its work: */
2851                       search_state.saved_this_tr_table = this_tr_table;
2852                       search_state.saved_next_tr_table = next_tr_table;
2853                       goto try_burst_1;
2854                       
2855                     case rx_get_burst_ok:
2856                       /* get_burst succeeded...keep going */
2857                       break;
2858                       
2859                     case rx_get_burst_no_more:
2860                       search_state.test_ret = rx_test_line_finished;
2861                       search_state.could_have_continued = 1;
2862                       goto test_do_return;
2863                       
2864                     case rx_get_burst_error:
2865                       /* An error... */
2866                       search_state.test_ret = rx_test_internal_error;
2867                       goto test_do_return;
2868                     }
2869                 }
2870               search_state.c = *search_state.test_pos.pos;
2871               search_state.ifr = this_tr_table + search_state.c;
2872               next_tr_table = (struct rx_inx *)search_state.ifr->data;
2873             } /* Fast loop through cached transition tables */
2874           
2875           /* Here when we ran out of cached next-char transitions. 
2876            * So, it will be necessary to do a more expensive
2877            * dispatch on the current instruction.  The superstate
2878            * pointer is allowed to become invalid during next-char
2879            * transitions -- now we must bring it up to date.
2880            */
2881           search_state.super =
2882             ((struct rx_superstate *)
2883              ((char *)this_tr_table
2884               - ((unsigned long)
2885                  ((struct rx_superstate *)0)->transitions)));
2886         }
2887         
2888         /* We've encountered an instruction other than next-char.
2889          * Dispatch that instruction:
2890          */
2891         inx = (int)search_state.ifr->inx;
2892 #ifdef RX_DEBUG_0
2893         if (rx_debug_trace)
2894           {
2895             struct rx_superset * setp = search_state.super->contents;
2896             
2897             fprintf (stderr, "%d %d>> %s @ %d (%d)", search_state.line_no,
2898                      search_state.backtrack_depth,
2899                      inx_names[inx],
2900                      (search_state.test_pos.pos - search_state.test_pos.string
2901                       + (test_pos.half == 0 ? 0 : size1)), search_state.c);
2902             
2903             fprintf (stderr, "   superstet (rx=%d, &=%x: ",
2904                      rxb->rx.rx_id, setp);
2905             while (setp)
2906               {
2907                 fprintf (stderr, "%d ", setp->id);
2908                 setp = setp->cdr;
2909               }
2910             fprintf (stderr, "\n");
2911           }
2912 #endif
2913         switch ((enum rx_opcode)inx)
2914           {
2915           case rx_do_side_effects:
2916             
2917             /*  RX_DO_SIDE_EFFECTS occurs when we cross epsilon 
2918              *  edges associated with parentheses, backreferencing, etc.
2919              */
2920             {
2921               struct rx_distinct_future * df =
2922                 (struct rx_distinct_future *)search_state.ifr->data_2;
2923               struct rx_se_list * el = df->effects;
2924               /* Side effects come in lists.  This walks down
2925                * a list, dispatching.
2926                */
2927               while (el)
2928                 {
2929                   long effect;
2930                   effect = (long)el->car;
2931                   if (effect < 0)
2932                     {
2933 #ifdef RX_DEBUG_0
2934                       if (rx_debug_trace)
2935                         {
2936                           struct rx_superset * setp = search_state.super->contents;
2937                           
2938                           fprintf (stderr, "....%d %d>> %s\n", search_state.line_no,
2939                                    search_state.backtrack_depth,
2940                                    efnames[-effect]);
2941                         }
2942 #endif
2943                       switch ((enum re_side_effects) effect)
2944
2945                         {
2946                         case re_se_pushback:
2947                           search_state.ifr = &df->future_frame;
2948                           if (!search_state.ifr->data)
2949                             {
2950                               struct rx_superstate * sup;
2951                               sup = search_state.super;
2952                               rx_lock_superstate (rx, sup);
2953                               if (!rx_handle_cache_miss (&rxb->rx,
2954                                                          search_state.super,
2955                                                          search_state.c,
2956                                                          (search_state.ifr
2957                                                           ->data_2)))
2958                                 {
2959                                   rx_unlock_superstate (rx, sup);
2960                                   search_state.test_ret = rx_test_internal_error;
2961                                   goto test_do_return;
2962                                 }
2963                               rx_unlock_superstate (rx, sup);
2964                             }
2965                           /* --search_state.test_pos.pos; */
2966                           search_state.c = 't';
2967                           search_state.super
2968                             = ((struct rx_superstate *)
2969                                ((char *)search_state.ifr->data
2970                                 - (long)(((struct rx_superstate *)0)
2971                                          ->transitions)));
2972                           goto top_of_cycle;
2973                           break;
2974                         case re_se_push0:
2975                           {
2976                             struct rx_counter_frame * old_cf
2977                               = (search_state.counter_stack
2978                                  ? ((struct rx_counter_frame *)
2979                                     search_state.counter_stack->sp)
2980                                  : 0);
2981                             struct rx_counter_frame * cf;
2982                             PUSH (search_state.counter_stack,
2983                                   sizeof (struct rx_counter_frame));
2984                             cf = ((struct rx_counter_frame *)
2985                                   search_state.counter_stack->sp);
2986                             cf->tag = re_se_iter;
2987                             cf->val = 0;
2988                             cf->inherited_from = 0;
2989                             cf->cdr = old_cf;
2990                             break;
2991                           }
2992                         case re_se_fail:
2993                           goto test_do_return;
2994                         case re_se_begbuf:
2995                           if (!AT_STRINGS_BEG ())
2996                             goto test_do_return;
2997                           break;
2998                         case re_se_endbuf:
2999                           if (!AT_STRINGS_END ())
3000                             goto test_do_return;
3001                           break;
3002                         case re_se_wordbeg:
3003                           if (   LETTER_P (&search_state.test_pos, 1)
3004                               && (   AT_STRINGS_BEG()
3005                                   || !LETTER_P (&search_state.test_pos, 0)))
3006                             break;
3007                           else
3008                             goto test_do_return;
3009                         case re_se_wordend:
3010                           if (   !AT_STRINGS_BEG ()
3011                               && LETTER_P (&search_state.test_pos, 0)
3012                               && (AT_STRINGS_END ()
3013                                   || !LETTER_P (&search_state.test_pos, 1)))
3014                             break;
3015                           else
3016                             goto test_do_return;
3017                         case re_se_wordbound:
3018                           if (AT_WORD_BOUNDARY (&search_state.test_pos))
3019                             break;
3020                           else
3021                             goto test_do_return;
3022                         case re_se_notwordbound:
3023                           if (!AT_WORD_BOUNDARY (&search_state.test_pos))
3024                             break;
3025                           else
3026                             goto test_do_return;
3027                         case re_se_hat:
3028                           if (AT_STRINGS_BEG ())
3029                             {
3030                               if (rxb->not_bol)
3031                                 goto test_do_return;
3032                               else
3033                                 break;
3034                             }
3035                           else
3036                             {
3037                               char pos_c = *search_state.test_pos.pos;
3038                               if (   (SRCH_TRANSLATE (pos_c)
3039                                       == SRCH_TRANSLATE('\n'))
3040                                   && rxb->newline_anchor)
3041                                 break;
3042                               else
3043                                 goto test_do_return;
3044                             }
3045                         case re_se_dollar:
3046                           if (AT_STRINGS_END ())
3047                             {
3048                               if (rxb->not_eol)
3049                                 goto test_do_return;
3050                               else
3051                                 break;
3052                             }
3053                           else
3054                             {
3055                               if (   (   SRCH_TRANSLATE (fetch_char
3056                                                     (&search_state.test_pos, 1,
3057                                                      app_closure, stop))
3058                                       == SRCH_TRANSLATE ('\n'))
3059                                   && rxb->newline_anchor)
3060                                 break;
3061                               else
3062                                 goto test_do_return;
3063                             }
3064                           
3065                         case re_se_try:
3066                           /* This is the first side effect in every
3067                            * expression.
3068                            *
3069                            *  FOR NO GOOD REASON...get rid of it...
3070                            */
3071                           break;
3072                           
3073                         case re_se_pushpos:
3074                           {
3075                             int urhere =
3076                               ((int)(search_state.test_pos.pos
3077                                      - search_state.test_pos.string)
3078                                + search_state.test_pos.offset);
3079                             struct rx_counter_frame * old_cf
3080                               = (search_state.counter_stack
3081                                  ? ((struct rx_counter_frame *)
3082                                     search_state.counter_stack->sp)
3083                                  : 0);
3084                             struct rx_counter_frame * cf;
3085                             PUSH(search_state.counter_stack,
3086                                  sizeof (struct rx_counter_frame));
3087                             cf = ((struct rx_counter_frame *)
3088                                   search_state.counter_stack->sp);
3089                             cf->tag = re_se_pushpos;
3090                             cf->val = urhere;
3091                             cf->inherited_from = 0;
3092                             cf->cdr = old_cf;
3093                             break;
3094                           }
3095                           
3096                         case re_se_chkpos:
3097                           {
3098                             int urhere =
3099                               ((int)(search_state.test_pos.pos
3100                                      - search_state.test_pos.string)
3101                                + search_state.test_pos.offset);
3102                             struct rx_counter_frame * cf
3103                               = ((struct rx_counter_frame *)
3104                                  search_state.counter_stack->sp);
3105                             if (cf->val == urhere)
3106                               goto test_do_return;
3107                             cf->val = urhere;
3108                             break;
3109                           }
3110                           break;
3111                           
3112                         case re_se_poppos:
3113                           POP(search_state.counter_stack,
3114                               sizeof (struct rx_counter_frame));
3115                           break;
3116                           
3117                           
3118                         case re_se_at_dot:
3119                         case re_se_syntax:
3120                         case re_se_not_syntax:
3121 #ifdef emacs
3122                           /* 
3123                            * this release lacks emacs support
3124                            */
3125 #endif
3126                           break;
3127                         case re_se_win:
3128                         case re_se_lparen:
3129                         case re_se_rparen:
3130                         case re_se_backref:
3131                         case re_se_iter:
3132                         case re_se_end_iter:
3133                         case re_se_tv:
3134                         case re_floogle_flap:
3135                           search_state.ret_val = 0;
3136                           goto test_do_return;
3137                         }
3138                     }
3139                   else
3140                     {
3141 #ifdef RX_DEBUG_0
3142                       if (rx_debug_trace)
3143                         fprintf (stderr, "....%d %d>> %s %d %d\n", search_state.line_no,
3144                                  search_state.backtrack_depth,
3145                                  efnames2[rxb->se_params [effect].se],
3146                                  rxb->se_params [effect].op1,
3147                                  rxb->se_params [effect].op2);
3148 #endif
3149                       switch (rxb->se_params [effect].se)
3150                         {
3151                         case re_se_win:
3152                           /* This side effect indicates that we've 
3153                            * found a match, though not necessarily the 
3154                            * best match.  This is a fancy assignment to 
3155                            * register 0 unless the caller didn't 
3156                            * care about registers.  In which case,
3157                            * this stops the match.
3158                            */
3159                           {
3160                             int urhere =
3161                               ((int)(search_state.test_pos.pos
3162                                      - search_state.test_pos.string)
3163                                + search_state.test_pos.offset);
3164                             
3165                             if (   (search_state.best_last_r < 0)
3166                                 || (urhere + 1 > search_state.best_rparen[0]))
3167                               {
3168                                 /* Record the best known and keep
3169                                  * looking.
3170                                  */
3171                                 int x;
3172                                 for (x = 0; x <= search_state.last_l; ++x)
3173                                   search_state.best_lparen[x] = search_state.lparen[x];
3174                                 search_state.best_last_l = search_state.last_l;
3175                                 for (x = 0; x <= search_state.last_r; ++x)
3176                                   search_state.best_rparen[x] = search_state.rparen[x];
3177                                 search_state.best_rparen[0] = urhere + 1;
3178                                 search_state.best_last_r = search_state.last_r;
3179                               }
3180                             /* If we're not reporting the match-length 
3181                              * or other register info, we need look no
3182                              * further.
3183                              */
3184                             if (search_state.first_found)
3185                               {
3186                                 search_state.test_ret = rx_test_found_first;
3187                                 goto test_do_return;
3188                               }
3189                           }
3190                           break;
3191                         case re_se_lparen:
3192                           {
3193                             int urhere =
3194                               ((int)(search_state.test_pos.pos
3195                                      - search_state.test_pos.string)
3196                                + search_state.test_pos.offset);
3197                             
3198                             int reg = rxb->se_params [effect].op1;
3199 #if 0
3200                             if (reg > search_state.last_l)
3201 #endif
3202                               {
3203                                 search_state.lparen[reg] = urhere + 1;
3204                                 /* In addition to making this assignment,
3205                                  * we now know that lower numbered regs
3206                                  * that haven't already been assigned,
3207                                  * won't be.  We make sure they're
3208                                  * filled with -1, so they can be
3209                                  * recognized as unassigned.
3210                                  */
3211                                 if (search_state.last_l < reg)
3212                                   while (++search_state.last_l < reg)
3213                                     search_state.lparen[search_state.last_l] = -1;
3214                               }
3215                             break;
3216                           }
3217                           
3218                         case re_se_rparen:
3219                           {
3220                             int urhere =
3221                               ((int)(search_state.test_pos.pos
3222                                      - search_state.test_pos.string)
3223                                + search_state.test_pos.offset);
3224                             int reg = rxb->se_params [effect].op1;
3225                             search_state.rparen[reg] = urhere + 1;
3226                             if (search_state.last_r < reg)
3227                               {
3228                                 while (++search_state.last_r < reg)
3229                                   search_state.rparen[search_state.last_r]
3230                                     = -1;
3231                               }
3232                             break;
3233                           }
3234                           
3235                         case re_se_backref:
3236                           {
3237                             int reg = rxb->se_params [effect].op1;
3238                             if (   reg > search_state.last_r
3239                                 || search_state.rparen[reg] < 0)
3240                               goto test_do_return;
3241                             
3242                             {
3243                               int backref_status;
3244                             check_backreference:
3245                               backref_status
3246                                 = back_check (&search_state.test_pos,
3247                                               search_state.lparen[reg],
3248                                               search_state.rparen[reg],
3249                                               search_state.translate,
3250                                               app_closure,
3251                                               stop);
3252                               switch (backref_status)
3253                                 {
3254                                 case rx_back_check_continuation:
3255                                   search_state.saved_reg = reg;
3256                                   test_pc = rx_test_backreference_check;
3257                                   goto test_return_continuation;
3258                                 resume_continuation_2:
3259                                   reg = search_state.saved_reg;
3260                                   goto check_backreference;
3261                                 case rx_back_check_fail:
3262                                   /* Fail */
3263                                   goto test_do_return;
3264                                 case rx_back_check_pass:
3265                                   /* pass --
3266                                    * test_pos now advanced to last
3267                                    * char matched by backref
3268                                    */
3269                                   break;
3270                                 }
3271                             }
3272                             break;
3273                           }
3274                         case re_se_iter:
3275                           {
3276                             struct rx_counter_frame * csp
3277                               = ((struct rx_counter_frame *)
3278                                  search_state.counter_stack->sp);
3279                             if (csp->val == rxb->se_params[effect].op2)
3280                               goto test_do_return;
3281                             else
3282                               ++csp->val;
3283                             break;
3284                           }
3285                         case re_se_end_iter:
3286                           {
3287                             struct rx_counter_frame * csp
3288                               = ((struct rx_counter_frame *)
3289                                  search_state.counter_stack->sp);
3290                             if (csp->val < rxb->se_params[effect].op1)
3291                               goto test_do_return;
3292                             else
3293                               {
3294                                 struct rx_counter_frame * source = csp;
3295                                 while (source->inherited_from)
3296                                   source = source->inherited_from;
3297                                 if (!source || !source->cdr)
3298                                   {
3299                                     POP(search_state.counter_stack,
3300                                         sizeof(struct rx_counter_frame));
3301                                   }
3302                                 else
3303                                   {
3304                                     source = source->cdr;
3305                                     csp->val = source->val;
3306                                     csp->tag = source->tag;
3307                                     csp->cdr = 0;
3308                                     csp->inherited_from = source;
3309                                   }
3310                               }
3311                             break;
3312                           }
3313                         case re_se_tv:
3314                           /* is a noop */
3315                           break;
3316                         case re_se_try:
3317                         case re_se_pushback:
3318                         case re_se_push0:
3319                         case re_se_pushpos:
3320                         case re_se_chkpos:
3321                         case re_se_poppos:
3322                         case re_se_at_dot:
3323                         case re_se_syntax:
3324                         case re_se_not_syntax:
3325                         case re_se_begbuf:
3326                         case re_se_hat:
3327                         case re_se_wordbeg:
3328                         case re_se_wordbound:
3329                         case re_se_notwordbound:
3330                         case re_se_wordend:
3331                         case re_se_endbuf:
3332                         case re_se_dollar:
3333                         case re_se_fail:
3334                         case re_floogle_flap:
3335                           search_state.ret_val = 0;
3336                           goto test_do_return;
3337                         }
3338                     }
3339                   el = el->cdr;
3340                 }
3341               /* Now the side effects are done,
3342                * so get the next instruction.
3343                * and move on.
3344                */
3345               search_state.ifr = &df->future_frame;
3346               goto restart;
3347             }
3348             
3349           case rx_backtrack_point:
3350             {
3351               /* A backtrack point indicates that we've reached a
3352                * non-determinism in the superstate NFA.  This is a
3353                * loop that exhaustively searches the possibilities.
3354                *
3355                * A backtracking strategy is used.  We keep track of what
3356                * registers are valid so we can erase side effects.
3357                *
3358                * First, make sure there is some stack space to hold 
3359                * our state.
3360                */
3361               
3362               struct rx_backtrack_frame * bf;
3363               
3364               PUSH(search_state.backtrack_stack,
3365                    search_state.backtrack_frame_bytes);
3366 #ifdef RX_DEBUG_0
3367               ++search_state.backtrack_depth;
3368 #endif
3369               
3370               bf = ((struct rx_backtrack_frame *)
3371                     search_state.backtrack_stack->sp);
3372               {
3373                 bf->stk_super = search_state.super;
3374                 /* We prevent the current superstate from being
3375                  * deleted from the superstate cache.
3376                  */
3377                 rx_lock_superstate (&rxb->rx, search_state.super);
3378 #ifdef RX_DEBUG_0
3379                 bf->stk_search_state.line_no = search_state.line_no;
3380 #endif
3381                 bf->stk_c = search_state.c;
3382                 bf->stk_test_pos = search_state.test_pos;
3383                 bf->stk_last_l = search_state.last_l;
3384                 bf->stk_last_r = search_state.last_r;
3385                 bf->df = ((struct rx_super_edge *)
3386                           search_state.ifr->data_2)->options;
3387                 bf->first_df = bf->df;
3388                 bf->counter_stack_sp = (search_state.counter_stack
3389                                         ? search_state.counter_stack->sp
3390                                         : 0);
3391                 bf->stk_test_ret = search_state.test_ret;
3392                 if (rxb->match_regs_on_stack)
3393                   {
3394                     int x;
3395                     regoff_t * stk =
3396                       (regoff_t *)((char *)bf + sizeof (*bf));
3397                     for (x = 0; x <= search_state.last_l; ++x)
3398                       stk[x] = search_state.lparen[x];
3399                     stk += x;
3400                     for (x = 0; x <= search_state.last_r; ++x)
3401                       stk[x] = search_state.rparen[x];
3402                   }
3403               }
3404               
3405               /* Here is a while loop whose body is mainly a function
3406                * call and some code to handle a return from that
3407                * function.
3408                *
3409                * From here on for the rest of `case backtrack_point' it
3410                * is unsafe to assume that the search_state copies of 
3411                * variables saved on the backtracking stack are valid
3412                * -- so read their values from the backtracking stack.
3413                *
3414                * This lets us use one generation fewer stack saves in
3415                * the call-graph of a search.
3416                */
3417               
3418             while_non_det_options:
3419 #ifdef RX_DEBUG_0
3420               ++search_state.lines_found;
3421               if (rx_debug_trace)
3422                 fprintf (stderr, "@@@ %d calls %d @@@\n",
3423                          search_state.line_no, search_state.lines_found);
3424               
3425               search_state.line_no = search_state.lines_found;
3426 #endif
3427               
3428               if (bf->df->next_same_super_edge[0] == bf->first_df)
3429                 {
3430                   /* This is a tail-call optimization -- we don't recurse
3431                    * for the last of the possible futures.
3432                    */
3433                   search_state.ifr = (bf->df->effects
3434                                       ? &bf->df->side_effects_frame
3435                                       : &bf->df->future_frame);
3436                   
3437                   rx_unlock_superstate (&rxb->rx, search_state.super);
3438                   POP(search_state.backtrack_stack,
3439                       search_state.backtrack_frame_bytes);
3440 #ifdef RX_DEBUG
3441                   --search_state.backtrack_depth;
3442 #endif
3443                   goto restart;
3444                 }
3445               else
3446                 {
3447                   if (search_state.counter_stack)
3448                     {
3449                       struct rx_counter_frame * old_cf
3450                         = ((struct rx_counter_frame *)search_state.counter_stack->sp);
3451                       struct rx_counter_frame * cf;
3452                       PUSH(search_state.counter_stack, sizeof (struct rx_counter_frame));
3453                       cf = ((struct rx_counter_frame *)search_state.counter_stack->sp);
3454                       cf->tag = old_cf->tag;
3455                       cf->val = old_cf->val;
3456                       cf->inherited_from = old_cf;
3457                       cf->cdr = 0;
3458                     }                   
3459                   /* `Call' this test-match block */
3460                   search_state.ifr = (bf->df->effects
3461                                       ? &bf->df->side_effects_frame
3462                                       : &bf->df->future_frame);
3463                   goto recurse_test_match;
3464                 }
3465               
3466               /* Returns in this block are accomplished by
3467                * goto test_do_return.  There are two cases.
3468                * If there is some search-stack left,
3469                * then it is a return from a `recursive' call.
3470                * If there is no search-stack left, then
3471                * we should return to the fastmap/search loop.
3472                */
3473               
3474             test_do_return:
3475               
3476               if (!search_state.backtrack_stack)
3477                 {
3478 #ifdef RX_DEBUG_0
3479                   if (rx_debug_trace)
3480                     fprintf (stderr, "!!! %d bails returning %d !!!\n",
3481                              search_state.line_no, search_state.test_ret);
3482 #endif
3483                   
3484                   /* No more search-stack -- this test is done. */
3485                   if (search_state.test_ret)
3486                     goto return_from_test_match;
3487                   else
3488                     goto error_in_testing_match;
3489                 }
3490               
3491               /* Returning from a recursive call to 
3492                * the test match block:
3493                */
3494               
3495               bf = ((struct rx_backtrack_frame *)
3496                     search_state.backtrack_stack->sp);
3497 #ifdef RX_DEBUG_0
3498               if (rx_debug_trace)
3499                 fprintf (stderr, "+++ %d returns %d (to %d)+++\n",
3500                          search_state.line_no,
3501                          search_state.test_ret,
3502                          bf->stk_search_state.line_no);
3503 #endif
3504               
3505               while (search_state.counter_stack
3506                      && (!bf->counter_stack_sp
3507                          || (bf->counter_stack_sp
3508                              != search_state.counter_stack->sp)))
3509                 {
3510                   POP(search_state.counter_stack,
3511                       sizeof (struct rx_counter_frame));
3512                 }
3513               
3514               if (search_state.test_ret == rx_test_error)
3515                 {
3516                   POP (search_state.backtrack_stack,
3517                        search_state.backtrack_frame_bytes);
3518                   goto test_do_return;
3519                 }
3520               
3521               /* If a non-longest match was found and that is good 
3522                * enough, return immediately.
3523                */
3524               if (   (search_state.test_ret == rx_test_found_first)
3525                   && search_state.first_found)
3526                 {
3527                   rx_unlock_superstate (&rxb->rx, bf->stk_super);
3528                   POP (search_state.backtrack_stack,
3529                        search_state.backtrack_frame_bytes);
3530                   goto test_do_return;
3531                 }
3532               
3533               search_state.test_ret = bf->stk_test_ret;
3534               search_state.last_l = bf->stk_last_l;
3535               search_state.last_r = bf->stk_last_r;
3536               bf->df = bf->df->next_same_super_edge[0];
3537               search_state.super = bf->stk_super;
3538               search_state.c = bf->stk_c;
3539 #ifdef RX_DEBUG_0
3540               search_state.line_no = bf->stk_search_state.line_no;
3541 #endif
3542               
3543               if (rxb->match_regs_on_stack)
3544                 {
3545                   int x;
3546                   regoff_t * stk =
3547                     (regoff_t *)((char *)bf + sizeof (*bf));
3548                   for (x = 0; x <= search_state.last_l; ++x)
3549                     search_state.lparen[x] = stk[x];
3550                   stk += x;
3551                   for (x = 0; x <= search_state.last_r; ++x)
3552                     search_state.rparen[x] = stk[x];
3553                 }
3554               
3555               {
3556                 int x;
3557               try_burst_2:
3558                 x = get_burst (&bf->stk_test_pos, app_closure, stop);
3559                 switch (x)
3560                   {
3561                   case rx_get_burst_continuation:
3562                     search_state.saved_bf = bf;
3563                     test_pc = rx_test_backtrack_return;
3564                     goto test_return_continuation;
3565                   resume_continuation_3:
3566                     bf = search_state.saved_bf;
3567                     goto try_burst_2;
3568                   case rx_get_burst_no_more:
3569                     /* Since we've been here before, it is some kind of
3570                      * error that we can't return.
3571                      */
3572                   case rx_get_burst_error:
3573                     search_state.test_ret = rx_test_internal_error;
3574                     goto test_do_return;
3575                   case rx_get_burst_ok:
3576                     break;
3577                   }
3578               }
3579               search_state.test_pos = bf->stk_test_pos;
3580               goto while_non_det_options;
3581             }
3582             
3583             
3584           case rx_cache_miss:
3585             /* Because the superstate NFA is lazily constructed,
3586              * and in fact may erode from underneath us, we sometimes
3587              * have to construct the next instruction from the hard way.
3588              * This invokes one step in the lazy-conversion.
3589              */
3590             search_state.ifr = rx_handle_cache_miss (&rxb->rx,
3591                                                      search_state.super,
3592                                                      search_state.c,
3593                                                      search_state.ifr->data_2);
3594             if (!search_state.ifr)
3595               {
3596                 search_state.test_ret = rx_test_internal_error;
3597                 goto test_do_return;
3598               }
3599             goto restart;
3600             
3601           case rx_backtrack:
3602             /* RX_BACKTRACK means that we've reached the empty
3603              * superstate, indicating that match can't succeed
3604              * from this point.
3605              */
3606             goto test_do_return;
3607             
3608           case rx_next_char:
3609           case rx_error_inx:
3610           case rx_num_instructions:
3611             search_state.ret_val = 0;
3612             goto test_do_return;
3613           }
3614         goto pseudo_while_1;
3615       }
3616     
3617     /* Healthy exits from the test-match loop do a 
3618      * `goto return_from_test_match'   On the other hand, 
3619      * we might end up here.
3620      */
3621   error_in_testing_match:
3622     test_state = rx_test_error;
3623     goto test_returns_to_search;
3624     
3625     /***** fastmap/search loop body
3626      *        considering the results testing for a match
3627      */
3628     
3629   return_from_test_match:
3630     
3631     if (search_state.best_last_l >= 0)
3632       {
3633         if (regs && (regs->start != search_state.best_lparen))
3634           {
3635             bcopy (search_state.best_lparen, regs->start,
3636                    regs->num_regs * sizeof (int));
3637             bcopy (search_state.best_rparen, regs->end,
3638                    regs->num_regs * sizeof (int));
3639           }
3640         if (regs && !rxb->no_sub)
3641           {
3642             int q;
3643             int bound = (regs->num_regs > search_state.num_regs
3644                          ? regs->num_regs
3645                          : search_state.num_regs);
3646             regoff_t * s = regs->start;
3647             regoff_t * e = regs->end;
3648             for (q = search_state.best_last_l + 1;  q < bound; ++q)
3649               s[q] = e[q] = -1;
3650           }
3651         search_state.ret_val = search_state.best_lparen[0];
3652         test_state = rx_test_ok;
3653         goto test_returns_to_search;
3654       }
3655     else
3656       {
3657         test_state = rx_test_fail;
3658         goto test_returns_to_search;
3659       }
3660     
3661   test_return_continuation:
3662     search_state.test_match_resume_pt = test_pc;
3663     test_state = rx_test_continuation;
3664     goto test_returns_to_search;
3665   }
3666 }
3667
3668
3669
3670 #endif /* RX_WANT_RX_DEFS */
3671
3672
3673
3674 #else /* RX_WANT_SE_DEFS */
3675   /* Integers are used to represent side effects.
3676    *
3677    * Simple side effects are given negative integer names by these enums.
3678    * 
3679    * Non-negative names are reserved for complex effects.
3680    *
3681    * Complex effects are those that take arguments.  For example, 
3682    * a register assignment associated with a group is complex because
3683    * it requires an argument to tell which group is being matched.
3684    * 
3685    * The integer name of a complex effect is an index into rxb->se_params.
3686    */
3687  
3688   RX_DEF_SE(1, re_se_try, = -1)         /* Epsilon from start state */
3689
3690   RX_DEF_SE(0, re_se_pushback, = re_se_try - 1)
3691   RX_DEF_SE(0, re_se_push0, = re_se_pushback -1)
3692   RX_DEF_SE(0, re_se_pushpos, = re_se_push0 - 1)
3693   RX_DEF_SE(0, re_se_chkpos, = re_se_pushpos -1)
3694   RX_DEF_SE(0, re_se_poppos, = re_se_chkpos - 1)
3695
3696   RX_DEF_SE(1, re_se_at_dot, = re_se_poppos - 1)        /* Emacs only */
3697   RX_DEF_SE(0, re_se_syntax, = re_se_at_dot - 1) /* Emacs only */
3698   RX_DEF_SE(0, re_se_not_syntax, = re_se_syntax - 1) /* Emacs only */
3699
3700   RX_DEF_SE(1, re_se_begbuf, = re_se_not_syntax - 1) /* match beginning of buffer */
3701   RX_DEF_SE(1, re_se_hat, = re_se_begbuf - 1) /* match beginning of line */
3702
3703   RX_DEF_SE(1, re_se_wordbeg, = re_se_hat - 1) 
3704   RX_DEF_SE(1, re_se_wordbound, = re_se_wordbeg - 1)
3705   RX_DEF_SE(1, re_se_notwordbound, = re_se_wordbound - 1)
3706
3707   RX_DEF_SE(1, re_se_wordend, = re_se_notwordbound - 1)
3708   RX_DEF_SE(1, re_se_endbuf, = re_se_wordend - 1)
3709
3710   /* This fails except at the end of a line. 
3711    * It deserves to go here since it is typicly one of the last steps 
3712    * in a match.
3713    */
3714   RX_DEF_SE(1, re_se_dollar, = re_se_endbuf - 1)
3715
3716   /* Simple effects: */
3717   RX_DEF_SE(1, re_se_fail, = re_se_dollar - 1)
3718
3719   /* Complex effects.  These are used in the 'se' field of 
3720    * a struct re_se_params.  Indexes into the se array
3721    * are stored as instructions on nfa edges.
3722    */
3723   RX_DEF_CPLX_SE(1, re_se_win, = 0)
3724   RX_DEF_CPLX_SE(1, re_se_lparen, = re_se_win + 1)
3725   RX_DEF_CPLX_SE(1, re_se_rparen, = re_se_lparen + 1)
3726   RX_DEF_CPLX_SE(0, re_se_backref, = re_se_rparen + 1)
3727   RX_DEF_CPLX_SE(0, re_se_iter, = re_se_backref + 1) 
3728   RX_DEF_CPLX_SE(0, re_se_end_iter, = re_se_iter + 1)
3729   RX_DEF_CPLX_SE(0, re_se_tv, = re_se_end_iter + 1)
3730
3731 #endif
3732
3733 #endif