d3f1431ba1873cc0530c206b961e13b0d4d65072
[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_VBAR               | 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 const 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 RX_DECL char re_syntax_table[CHAR_SET_SIZE];
2225 #endif /* not emacs */
2226
2227
2228 /* Test if at very beginning or at very end of the virtual concatenation
2229  *  of `string1' and `string2'.  If only one string, it's `string2'.
2230  */
2231
2232 #define AT_STRINGS_BEG() \
2233   (   -1                 \
2234    == ((search_state.test_pos.pos - search_state.test_pos.string) \
2235        + search_state.test_pos.offset))
2236
2237 #define AT_STRINGS_END() \
2238   (   (total_size - 1)   \
2239    == ((search_state.test_pos.pos - search_state.test_pos.string) \
2240        + search_state.test_pos.offset))
2241
2242
2243 /* Test if POS + 1 points to a character which is word-constituent.  We have
2244  * two special cases to check for: if past the end of string1, look at
2245  * the first character in string2; and if before the beginning of
2246  * string2, look at the last character in string1.
2247  *
2248  * Assumes `string1' exists, so use in conjunction with AT_STRINGS_BEG ().
2249  */
2250 #define LETTER_P(POS,OFF)                                               \
2251   (   SYNTAX (fetch_char(POS, OFF, app_closure, stop))                  \
2252    == Sword)
2253
2254 /* Test if the character at D and the one after D differ with respect
2255  * to being word-constituent.
2256  */
2257 #define AT_WORD_BOUNDARY(d)                                             \
2258   (AT_STRINGS_BEG () || AT_STRINGS_END () || LETTER_P (d,0) != LETTER_P (d, 1))
2259
2260
2261 #ifdef RX_SUPPORT_CONTINUATIONS
2262 #define RX_STACK_ALLOC(BYTES) malloc(BYTES)
2263 #define RX_STACK_FREE(MEM) free(MEM)
2264 #else
2265 #define RX_STACK_ALLOC(BYTES) alloca(BYTES)
2266 #define RX_STACK_FREE(MEM) \
2267       ((struct rx_stack_chunk *)MEM)->next_chunk = search_state.free_chunks; \
2268       search_state.free_chunks = ((struct rx_stack_chunk *)MEM);
2269
2270 #endif
2271
2272 #define PUSH(CHUNK_VAR,BYTES)   \
2273   if (!CHUNK_VAR || (CHUNK_VAR->bytes_left < (BYTES)))  \
2274     {                                   \
2275       struct rx_stack_chunk * new_chunk;        \
2276       if (search_state.free_chunks)                     \
2277         {                               \
2278           new_chunk = search_state.free_chunks; \
2279           search_state.free_chunks = search_state.free_chunks->next_chunk; \
2280         }                               \
2281       else                              \
2282         {                               \
2283           new_chunk = (struct rx_stack_chunk *)RX_STACK_ALLOC(search_state.chunk_bytes); \
2284           if (!new_chunk)               \
2285             {                           \
2286               search_state.ret_val = 0;         \
2287               goto test_do_return;      \
2288             }                           \
2289         }                               \
2290       new_chunk->sp = (char *)new_chunk + sizeof (struct rx_stack_chunk); \
2291       new_chunk->bytes_left = (search_state.chunk_bytes \
2292                                - (BYTES) \
2293                                - sizeof (struct rx_stack_chunk)); \
2294       new_chunk->next_chunk = CHUNK_VAR; \
2295       CHUNK_VAR = new_chunk;            \
2296     } \
2297   else \
2298     (CHUNK_VAR->sp += (BYTES)), (CHUNK_VAR->bytes_left -= (BYTES))
2299
2300 #define POP(CHUNK_VAR,BYTES) \
2301   if (CHUNK_VAR->sp == ((char *)CHUNK_VAR + sizeof(*CHUNK_VAR))) \
2302     { \
2303       struct rx_stack_chunk * new_chunk = CHUNK_VAR->next_chunk; \
2304       RX_STACK_FREE(CHUNK_VAR); \
2305       CHUNK_VAR = new_chunk; \
2306     } \
2307   else \
2308     (CHUNK_VAR->sp -= BYTES), (CHUNK_VAR->bytes_left += BYTES)
2309
2310
2311
2312 #define SRCH_TRANSLATE(C)  search_state.translate[(unsigned char) (C)]
2313
2314
2315 \f
2316
2317 #ifdef __STDC__
2318 RX_DECL __inline__ int
2319 rx_search  (struct re_pattern_buffer * rxb,
2320             int startpos,
2321             int range,
2322             int stop,
2323             int total_size,
2324             rx_get_burst_fn get_burst,
2325             rx_back_check_fn back_check,
2326             rx_fetch_char_fn fetch_char,
2327             void * app_closure,
2328             struct re_registers * regs,
2329             struct rx_search_state * resume_state,
2330             struct rx_search_state * save_state)
2331 #else
2332 RX_DECL __inline__ int
2333 rx_search  (rxb, startpos, range, stop, total_size,
2334             get_burst, back_check, fetch_char,
2335             app_closure, regs, resume_state, save_state)
2336      struct re_pattern_buffer * rxb;
2337      int startpos;
2338      int range;
2339      int stop;
2340      int total_size;
2341      rx_get_burst_fn get_burst;
2342      rx_back_check_fn back_check;
2343      rx_fetch_char_fn fetch_char;
2344      void * app_closure;
2345      struct re_registers * regs;
2346      struct rx_search_state * resume_state;
2347      struct rx_search_state * save_state;
2348 #endif
2349 {
2350   int pc;
2351   int test_state;
2352   struct rx_search_state search_state;
2353
2354   search_state.free_chunks = 0;
2355   if (!resume_state)
2356     pc = rx_outer_start;
2357   else
2358     {
2359       search_state = *resume_state;
2360       regs = search_state.saved_regs;
2361       rxb = search_state.saved_rxb;
2362       startpos = search_state.saved_startpos;
2363       range = search_state.saved_range;
2364       stop = search_state.saved_stop;
2365       total_size = search_state.saved_total_size;
2366       get_burst = search_state.saved_get_burst;
2367       back_check = search_state.saved_back_check;
2368       pc = search_state.outer_search_resume_pt;
2369       if (0)
2370         {
2371         return_continuation:
2372           if (save_state)
2373             {
2374               *save_state = search_state;
2375               save_state->saved_regs = regs;
2376               save_state->saved_rxb = rxb;
2377               save_state->saved_startpos = startpos;
2378               save_state->saved_range = range;
2379               save_state->saved_stop = stop;
2380               save_state->saved_total_size = total_size;
2381               save_state->saved_get_burst = get_burst;
2382               save_state->saved_back_check = back_check;
2383               save_state->outer_search_resume_pt = pc;
2384             }
2385           return rx_search_continuation;
2386         }
2387     }
2388
2389   switch (pc)
2390     {
2391     case rx_outer_start:
2392       search_state.ret_val = rx_search_fail;
2393       (  search_state.lparen
2394        = search_state.rparen
2395        = search_state.best_lpspace
2396        = search_state.best_rpspace
2397        = 0);
2398
2399       /* figure the number of registers we may need for use in backreferences.
2400        * the number here includes an element for register zero.
2401        */
2402       search_state.num_regs = rxb->re_nsub + 1;
2403
2404
2405       /* check for out-of-range startpos.  */
2406       if ((startpos < 0) || (startpos > total_size))
2407         return rx_search_fail;
2408
2409       /* fix up range if it might eventually take us outside the string. */
2410       {
2411         int endpos;
2412         endpos = startpos + range;
2413         if (endpos < -1)
2414           range = (-1 - startpos);
2415         else if (endpos > (total_size + 1))
2416           range = total_size - startpos;
2417       }
2418
2419       /* if the search isn't to be a backwards one, don't waste time in a
2420        * long search for a pattern that says it is anchored.
2421        */
2422       if (rxb->begbuf_only && (range > 0))
2423         {
2424           if (startpos > 0)
2425             return rx_search_fail;
2426           else
2427             range = 1;
2428         }
2429
2430       /* decide whether to use internal or user-provided reg buffers. */
2431       if (!regs || rxb->no_sub)
2432         {
2433           search_state.best_lpspace =
2434             (regoff_t *)REGEX_ALLOCATE (search_state.num_regs * sizeof(regoff_t));
2435           search_state.best_rpspace =
2436             (regoff_t *)REGEX_ALLOCATE (search_state.num_regs * sizeof(regoff_t));
2437           search_state.best_lparen = search_state.best_lpspace;
2438           search_state.best_rparen = search_state.best_rpspace;
2439         }
2440       else
2441         {
2442           /* have the register data arrays been allocated?  */
2443           if (rxb->regs_allocated == REGS_UNALLOCATED)
2444             { /* no.  so allocate them with malloc.  we need one
2445                  extra element beyond `search_state.num_regs' for the `-1' marker
2446                  gnu code uses.  */
2447               regs->num_regs = MAX (RE_NREGS, rxb->re_nsub + 1);
2448               regs->start = ((regoff_t *)
2449                              malloc (regs->num_regs * sizeof ( regoff_t)));
2450               regs->end = ((regoff_t *)
2451                            malloc (regs->num_regs * sizeof ( regoff_t)));
2452               if (regs->start == 0 || regs->end == 0)
2453                 return rx_search_error;
2454               rxb->regs_allocated = REGS_REALLOCATE;
2455             }
2456           else if (rxb->regs_allocated == REGS_REALLOCATE)
2457             { /* yes.  if we need more elements than were already
2458                  allocated, reallocate them.  if we need fewer, just
2459                  leave it alone.  */
2460               if (regs->num_regs < search_state.num_regs + 1)
2461                 {
2462                   regs->num_regs = search_state.num_regs + 1;
2463                   regs->start = ((regoff_t *)
2464                                  realloc (regs->start,
2465                                           regs->num_regs * sizeof (regoff_t)));
2466                   regs->end = ((regoff_t *)
2467                                realloc (regs->end,
2468                                         regs->num_regs * sizeof ( regoff_t)));
2469                   if (regs->start == 0 || regs->end == 0)
2470                     return rx_search_error;
2471                 }
2472             }
2473           else if (rxb->regs_allocated != REGS_FIXED)
2474             return rx_search_error;
2475
2476           if (regs->num_regs < search_state.num_regs + 1)
2477             {
2478               search_state.best_lpspace =
2479                 ((regoff_t *)
2480                  REGEX_ALLOCATE (search_state.num_regs * sizeof(regoff_t)));
2481               search_state.best_rpspace =
2482                 ((regoff_t *)
2483                  REGEX_ALLOCATE (search_state.num_regs * sizeof(regoff_t)));
2484               search_state.best_lparen = search_state.best_lpspace;
2485               search_state.best_rparen = search_state.best_rpspace;
2486             }
2487           else
2488             {
2489               search_state.best_lparen = regs->start;
2490               search_state.best_rparen = regs->end;
2491             }
2492         }
2493
2494       search_state.lparen =
2495         (regoff_t *) REGEX_ALLOCATE (search_state.num_regs * sizeof(regoff_t));
2496       search_state.rparen =
2497         (regoff_t *) REGEX_ALLOCATE (search_state.num_regs * sizeof(regoff_t));
2498
2499       if (! (   search_state.best_rparen
2500              && search_state.best_lparen
2501              && search_state.lparen && search_state.rparen))
2502         return rx_search_error;
2503
2504       search_state.best_last_l = search_state.best_last_r = -1;
2505
2506       search_state.translate = (rxb->translate
2507                                 ? rxb->translate
2508                                 : rx_id_translation);
2509
2510
2511
2512       /*
2513        * two nfa's were compiled.
2514        * `0' is complete.
2515        * `1' faster but gets registers wrong and ends too soon.
2516        */
2517       search_state.nfa_choice = (regs && !rxb->least_subs) ? '\0' : '\1';
2518
2519       /* we have the option to look for the best match or the first
2520        * one we can find.  if the user isn't asking for register information,
2521        * we don't need to find the best match.
2522        */
2523       search_state.first_found = !regs;
2524
2525       if (range >= 0)
2526         {
2527           search_state.outer_pos.search_end = startpos + range;
2528           search_state.outer_pos.search_direction = 1;
2529         }
2530       else
2531         {
2532           search_state.outer_pos.search_end = startpos + range;
2533           search_state.outer_pos.search_direction = -1;
2534         }
2535
2536       /* the vacuous search always turns up nothing. */
2537       if ((search_state.outer_pos.search_direction == 1)
2538           ? (startpos > search_state.outer_pos.search_end)
2539           : (startpos < search_state.outer_pos.search_end))
2540         return rx_search_fail;
2541
2542       /* now we build the starting state of the supernfa. */
2543       {
2544         struct rx_superset * start_contents;
2545         struct rx_nfa_state_set * start_nfa_set;
2546
2547         /* we presume here that the nfa start state has only one
2548          * possible future with no side effects.
2549          */
2550         start_nfa_set = rxb->start->futures->destset;
2551         if (   rxb->rx.start_set
2552             && (rxb->rx.start_set->starts_for == &rxb->rx))
2553           start_contents = rxb->rx.start_set;
2554         else
2555           {
2556             start_contents =
2557               rx_superstate_eclosure_union (&rxb->rx,
2558                                             rx_superset_cons (&rxb->rx, 0, 0),
2559                                             start_nfa_set);
2560
2561             if (!start_contents)
2562               return rx_search_fail;
2563
2564             start_contents->starts_for = &rxb->rx;
2565             rxb->rx.start_set = start_contents;
2566           }
2567         if (   start_contents->superstate
2568             && (start_contents->superstate->rx_id == rxb->rx.rx_id))
2569           {
2570             search_state.start_super = start_contents->superstate;
2571             rx_lock_superstate (&rxb->rx, search_state.start_super);
2572           }
2573         else
2574           {
2575             rx_protect_superset (&rxb->rx, start_contents);
2576
2577             search_state.start_super = rx_superstate (&rxb->rx, start_contents);
2578             if (!search_state.start_super)
2579               return rx_search_fail;
2580             rx_lock_superstate (&rxb->rx, search_state.start_super);
2581             rx_release_superset (&rxb->rx, start_contents);
2582           }
2583       }
2584
2585
2586       /* The outer_pos tracks the position within the strings
2587        * as seen by loop that calls fastmap_search.
2588        *
2589        * The caller supplied get_burst function actually
2590        * gives us pointers to chars.
2591        *
2592        * Communication with the get_burst function is through an
2593        * rx_string_position structure.  Here, the structure for
2594        * outer_pos is initialized.   It is set to point to the
2595        * NULL string, at an offset of STARTPOS.  STARTPOS is out
2596        * of range of the NULL string, so the first call to
2597        * getburst will patch up the rx_string_position to point
2598        * to valid characters.
2599        */
2600
2601       (  search_state.outer_pos.string
2602        = search_state.outer_pos.end
2603        = 0);
2604
2605       search_state.outer_pos.offset = 0;
2606       search_state.outer_pos.size = 0;
2607       search_state.outer_pos.pos = (unsigned char *)startpos;
2608       init_fastmap (rxb, &search_state);
2609
2610       search_state.fastmap_resume_pt = rx_fastmap_start;
2611     case rx_outer_fastmap:
2612       /* do { */
2613     pseudo_do:
2614       {
2615         {
2616           int fastmap_state;
2617           fastmap_state = fastmap_search (rxb, stop, get_burst, app_closure,
2618                                           &search_state);
2619           switch (fastmap_state)
2620             {
2621             case rx_fastmap_continuation:
2622               pc = rx_outer_fastmap;
2623               goto return_continuation;
2624             case rx_fastmap_fail:
2625               goto finish;
2626             case rx_fastmap_ok:
2627               break;
2628             }
2629         }
2630
2631         /* now the fastmap loop has brought us to a plausible
2632          * starting point for a match.  so, it's time to run the
2633          * nfa and see if a match occured.
2634          */
2635         startpos = (  search_state.outer_pos.pos
2636                     - search_state.outer_pos.string
2637                     + search_state.outer_pos.offset);
2638 #if 0
2639 /*|*/   if ((range > 0) && (startpos == search_state.outer_pos.search_end))
2640 /*|*/     goto finish;
2641 #endif
2642       }
2643
2644       search_state.test_match_resume_pt = rx_test_start;
2645       /* do interrupted for entry point... */
2646     case rx_outer_test:
2647       /* ...do continued */
2648       {
2649         goto test_match;
2650       test_returns_to_search:
2651         switch (test_state)
2652           {
2653           case rx_test_continuation:
2654             pc = rx_outer_test;
2655             goto return_continuation;
2656           case rx_test_error:
2657             search_state.ret_val = rx_search_error;
2658             goto finish;
2659           case rx_test_fail:
2660             break;
2661           case rx_test_ok:
2662             goto finish;
2663           }
2664         search_state.outer_pos.pos += search_state.outer_pos.search_direction;
2665         startpos += search_state.outer_pos.search_direction;
2666 #if 0
2667 /*|*/   if (search_state.test_pos.pos < search_state.test_pos.end)
2668 /*|*/     break;
2669 #endif
2670       }
2671       /* do interrupted for entry point... */
2672     case rx_outer_restore_pos:
2673       {
2674         int x;
2675         x = get_burst (&search_state.outer_pos, app_closure, stop);
2676         switch (x)
2677           {
2678           case rx_get_burst_continuation:
2679             pc = rx_outer_restore_pos;
2680             goto return_continuation;
2681           case rx_get_burst_error:
2682             search_state.ret_val = rx_search_error;
2683             goto finish;
2684           case rx_get_burst_no_more:
2685             if (rxb->can_match_empty)
2686               break;
2687             goto finish;
2688           case rx_get_burst_ok:
2689             break;
2690           }
2691       } /* } while (...see below...) */
2692
2693       if ((search_state.outer_pos.search_direction == 1)
2694           ? (startpos <= search_state.outer_pos.search_end)
2695           : (startpos > search_state.outer_pos.search_end))
2696         goto pseudo_do;
2697
2698
2699     finish:
2700       uninit_fastmap (rxb, &search_state);
2701       if (search_state.start_super)
2702         rx_unlock_superstate (&rxb->rx, search_state.start_super);
2703
2704 #ifdef regex_malloc
2705       if (search_state.lparen) free (search_state.lparen);
2706       if (search_state.rparen) free (search_state.rparen);
2707       if (search_state.best_lpspace) free (search_state.best_lpspace);
2708       if (search_state.best_rpspace) free (search_state.best_rpspace);
2709 #endif
2710       return search_state.ret_val;
2711     }
2712
2713
2714  test_match:
2715   {
2716     enum rx_test_match_entry test_pc;
2717     int inx;
2718     test_pc = search_state.test_match_resume_pt;
2719     if (test_pc == rx_test_start)
2720       {
2721 #ifdef RX_DEBUG
2722         search_state.backtrack_depth = 0;
2723 #endif
2724         search_state.last_l = search_state.last_r = 0;
2725         search_state.lparen[0] = startpos;
2726         search_state.super = search_state.start_super;
2727         search_state.c = search_state.nfa_choice;
2728         search_state.test_pos.pos = search_state.outer_pos.pos - 1;
2729         search_state.test_pos.string = search_state.outer_pos.string;
2730         search_state.test_pos.end = search_state.outer_pos.end;
2731         search_state.test_pos.offset = search_state.outer_pos.offset;
2732         search_state.test_pos.size = search_state.outer_pos.size;
2733         search_state.test_pos.search_direction = 1;
2734         search_state.counter_stack = 0;
2735         search_state.backtrack_stack = 0;
2736         search_state.backtrack_frame_bytes =
2737           (sizeof (struct rx_backtrack_frame)
2738            + (rxb->match_regs_on_stack
2739               ? sizeof (regoff_t) * (search_state.num_regs + 1) * 2
2740               : 0));
2741         search_state.chunk_bytes = search_state.backtrack_frame_bytes * 64;
2742         search_state.test_ret = rx_test_line_finished;
2743         search_state.could_have_continued = 0;
2744       }
2745     /* This is while (1)...except that the body of the loop is interrupted
2746      * by some alternative entry points.
2747      */
2748   pseudo_while_1:
2749     switch (test_pc)
2750       {
2751       case rx_test_cache_hit_loop:
2752         goto resume_continuation_1;
2753       case rx_test_backreference_check:
2754         goto resume_continuation_2;
2755       case rx_test_backtrack_return:
2756         goto resume_continuation_3;
2757       case rx_test_start:
2758 #ifdef RX_DEBUG
2759         /* There is a search tree with every node as set of deterministic
2760          * transitions in the super nfa.  For every branch of a
2761          * backtrack point is an edge in the tree.
2762          * This counts up a pre-order of nodes in that tree.
2763          * It's saved on the search stack and printed when debugging.
2764          */
2765         search_state.line_no = 0;
2766         search_state.lines_found = 0;
2767 #endif
2768
2769       top_of_cycle:
2770         /* A superstate is basicly a transition table, indexed by
2771          * characters from the string being tested, and containing
2772          * RX_INX (`instruction frame') structures.
2773          */
2774         search_state.ifr = &search_state.super->transitions [search_state.c];
2775
2776       recurse_test_match:
2777         /* This is the point to which control is sent when the
2778          * test matcher `recurses'.  Before jumping here, some variables
2779          * need to be saved on the stack and the next instruction frame
2780          * has to be computed.
2781          */
2782
2783       restart:
2784         /* Some instructions don't advance the matcher, but just
2785          * carry out some side effects and fetch a new instruction.
2786          * To dispatch that new instruction, `goto restart'.
2787          */
2788
2789         {
2790           struct rx_inx * next_tr_table;
2791           struct rx_inx * this_tr_table;
2792           /* The fastest route through the loop is when the instruction
2793            * is RX_NEXT_CHAR.  This case is detected when SEARCH_STATE.IFR->DATA
2794            * is non-zero.  In that case, it points to the next
2795            * superstate.
2796            *
2797            * This allows us to not bother fetching the bytecode.
2798            */
2799           next_tr_table = (struct rx_inx *)search_state.ifr->data;
2800           this_tr_table = search_state.super->transitions;
2801           while (next_tr_table)
2802             {
2803 #ifdef RX_DEBUG_0
2804               if (rx_debug_trace)
2805                 {
2806                   struct rx_superset * setp;
2807
2808                   fprintf (stderr, "%d %d>> re_next_char @ %d (%d)",
2809                            search_state.line_no,
2810                            search_state.backtrack_depth,
2811                            (search_state.test_pos.pos - search_state.test_pos.string
2812                             + search_state.test_pos.offset), search_state.c);
2813
2814                   search_state.super =
2815                     ((struct rx_superstate *)
2816                      ((char *)this_tr_table
2817                       - ((unsigned long)
2818                          ((struct rx_superstate *)0)->transitions)));
2819
2820                   setp = search_state.super->contents;
2821                   fprintf (stderr, "   superstet (rx=%d, &=%x: ",
2822                            rxb->rx.rx_id, setp);
2823                   while (setp)
2824                     {
2825                       fprintf (stderr, "%d ", setp->id);
2826                       setp = setp->cdr;
2827                     }
2828                   fprintf (stderr, "\n");
2829                 }
2830 #endif
2831               this_tr_table = next_tr_table;
2832               ++search_state.test_pos.pos;
2833               if (search_state.test_pos.pos == search_state.test_pos.end)
2834                 {
2835                   int burst_state;
2836                 try_burst_1:
2837                   burst_state = get_burst (&search_state.test_pos,
2838                                            app_closure, stop);
2839                   switch (burst_state)
2840                     {
2841                     case rx_get_burst_continuation:
2842                       search_state.saved_this_tr_table = this_tr_table;
2843                       search_state.saved_next_tr_table = next_tr_table;
2844                       test_pc = rx_test_cache_hit_loop;
2845                       goto test_return_continuation;
2846
2847                     resume_continuation_1:
2848                       /* Continuation one jumps here to do its work: */
2849                       search_state.saved_this_tr_table = this_tr_table;
2850                       search_state.saved_next_tr_table = next_tr_table;
2851                       goto try_burst_1;
2852
2853                     case rx_get_burst_ok:
2854                       /* get_burst succeeded...keep going */
2855                       break;
2856
2857                     case rx_get_burst_no_more:
2858                       search_state.test_ret = rx_test_line_finished;
2859                       search_state.could_have_continued = 1;
2860                       goto test_do_return;
2861
2862                     case rx_get_burst_error:
2863                       /* An error... */
2864                       search_state.test_ret = rx_test_internal_error;
2865                       goto test_do_return;
2866                     }
2867                 }
2868               search_state.c = *search_state.test_pos.pos;
2869               search_state.ifr = this_tr_table + search_state.c;
2870               next_tr_table = (struct rx_inx *)search_state.ifr->data;
2871             } /* Fast loop through cached transition tables */
2872
2873           /* Here when we ran out of cached next-char transitions.
2874            * So, it will be necessary to do a more expensive
2875            * dispatch on the current instruction.  The superstate
2876            * pointer is allowed to become invalid during next-char
2877            * transitions -- now we must bring it up to date.
2878            */
2879           search_state.super =
2880             ((struct rx_superstate *)
2881              ((char *)this_tr_table
2882               - ((unsigned long)
2883                  ((struct rx_superstate *)0)->transitions)));
2884         }
2885
2886         /* We've encountered an instruction other than next-char.
2887          * Dispatch that instruction:
2888          */
2889         inx = (int)search_state.ifr->inx;
2890 #ifdef RX_DEBUG_0
2891         if (rx_debug_trace)
2892           {
2893             struct rx_superset * setp = search_state.super->contents;
2894
2895             fprintf (stderr, "%d %d>> %s @ %d (%d)", search_state.line_no,
2896                      search_state.backtrack_depth,
2897                      inx_names[inx],
2898                      (search_state.test_pos.pos - search_state.test_pos.string
2899                       + (test_pos.half == 0 ? 0 : size1)), search_state.c);
2900
2901             fprintf (stderr, "   superstet (rx=%d, &=%x: ",
2902                      rxb->rx.rx_id, setp);
2903             while (setp)
2904               {
2905                 fprintf (stderr, "%d ", setp->id);
2906                 setp = setp->cdr;
2907               }
2908             fprintf (stderr, "\n");
2909           }
2910 #endif
2911         switch ((enum rx_opcode)inx)
2912           {
2913           case rx_do_side_effects:
2914
2915             /*  RX_DO_SIDE_EFFECTS occurs when we cross epsilon
2916              *  edges associated with parentheses, backreferencing, etc.
2917              */
2918             {
2919               struct rx_distinct_future * df =
2920                 (struct rx_distinct_future *)search_state.ifr->data_2;
2921               struct rx_se_list * el = df->effects;
2922               /* Side effects come in lists.  This walks down
2923                * a list, dispatching.
2924                */
2925               while (el)
2926                 {
2927                   long effect;
2928                   effect = (long)el->car;
2929                   if (effect < 0)
2930                     {
2931 #ifdef RX_DEBUG_0
2932                       if (rx_debug_trace)
2933                         {
2934                           struct rx_superset * setp = search_state.super->contents;
2935
2936                           fprintf (stderr, "....%d %d>> %s\n", search_state.line_no,
2937                                    search_state.backtrack_depth,
2938                                    efnames[-effect]);
2939                         }
2940 #endif
2941                       switch ((enum re_side_effects) effect)
2942
2943                         {
2944                         case re_se_pushback:
2945                           search_state.ifr = &df->future_frame;
2946                           if (!search_state.ifr->data)
2947                             {
2948                               struct rx_superstate * sup;
2949                               sup = search_state.super;
2950                               rx_lock_superstate (rx, sup);
2951                               if (!rx_handle_cache_miss (&rxb->rx,
2952                                                          search_state.super,
2953                                                          search_state.c,
2954                                                          (search_state.ifr
2955                                                           ->data_2)))
2956                                 {
2957                                   rx_unlock_superstate (rx, sup);
2958                                   search_state.test_ret = rx_test_internal_error;
2959                                   goto test_do_return;
2960                                 }
2961                               rx_unlock_superstate (rx, sup);
2962                             }
2963                           /* --search_state.test_pos.pos; */
2964                           search_state.c = 't';
2965                           search_state.super
2966                             = ((struct rx_superstate *)
2967                                ((char *)search_state.ifr->data
2968                                 - (long)(((struct rx_superstate *)0)
2969                                          ->transitions)));
2970                           goto top_of_cycle;
2971                           break;
2972                         case re_se_push0:
2973                           {
2974                             struct rx_counter_frame * old_cf
2975                               = (search_state.counter_stack
2976                                  ? ((struct rx_counter_frame *)
2977                                     search_state.counter_stack->sp)
2978                                  : 0);
2979                             struct rx_counter_frame * cf;
2980                             PUSH (search_state.counter_stack,
2981                                   sizeof (struct rx_counter_frame));
2982                             cf = ((struct rx_counter_frame *)
2983                                   search_state.counter_stack->sp);
2984                             cf->tag = re_se_iter;
2985                             cf->val = 0;
2986                             cf->inherited_from = 0;
2987                             cf->cdr = old_cf;
2988                             break;
2989                           }
2990                         case re_se_fail:
2991                           goto test_do_return;
2992                         case re_se_begbuf:
2993                           if (!AT_STRINGS_BEG ())
2994                             goto test_do_return;
2995                           break;
2996                         case re_se_endbuf:
2997                           if (!AT_STRINGS_END ())
2998                             goto test_do_return;
2999                           break;
3000                         case re_se_wordbeg:
3001                           if (   LETTER_P (&search_state.test_pos, 1)
3002                               && (   AT_STRINGS_BEG()
3003                                   || !LETTER_P (&search_state.test_pos, 0)))
3004                             break;
3005                           else
3006                             goto test_do_return;
3007                         case re_se_wordend:
3008                           if (   !AT_STRINGS_BEG ()
3009                               && LETTER_P (&search_state.test_pos, 0)
3010                               && (AT_STRINGS_END ()
3011                                   || !LETTER_P (&search_state.test_pos, 1)))
3012                             break;
3013                           else
3014                             goto test_do_return;
3015                         case re_se_wordbound:
3016                           if (AT_WORD_BOUNDARY (&search_state.test_pos))
3017                             break;
3018                           else
3019                             goto test_do_return;
3020                         case re_se_notwordbound:
3021                           if (!AT_WORD_BOUNDARY (&search_state.test_pos))
3022                             break;
3023                           else
3024                             goto test_do_return;
3025                         case re_se_hat:
3026                           if (AT_STRINGS_BEG ())
3027                             {
3028                               if (rxb->not_bol)
3029                                 goto test_do_return;
3030                               else
3031                                 break;
3032                             }
3033                           else
3034                             {
3035                               char pos_c = *search_state.test_pos.pos;
3036                               if (   (SRCH_TRANSLATE (pos_c)
3037                                       == SRCH_TRANSLATE('\n'))
3038                                   && rxb->newline_anchor)
3039                                 break;
3040                               else
3041                                 goto test_do_return;
3042                             }
3043                         case re_se_dollar:
3044                           if (AT_STRINGS_END ())
3045                             {
3046                               if (rxb->not_eol)
3047                                 goto test_do_return;
3048                               else
3049                                 break;
3050                             }
3051                           else
3052                             {
3053                               if (   (   SRCH_TRANSLATE (fetch_char
3054                                                     (&search_state.test_pos, 1,
3055                                                      app_closure, stop))
3056                                       == SRCH_TRANSLATE ('\n'))
3057                                   && rxb->newline_anchor)
3058                                 break;
3059                               else
3060                                 goto test_do_return;
3061                             }
3062
3063                         case re_se_try:
3064                           /* This is the first side effect in every
3065                            * expression.
3066                            *
3067                            *  FOR NO GOOD REASON...get rid of it...
3068                            */
3069                           break;
3070
3071                         case re_se_pushpos:
3072                           {
3073                             int urhere =
3074                               ((int)(search_state.test_pos.pos
3075                                      - search_state.test_pos.string)
3076                                + search_state.test_pos.offset);
3077                             struct rx_counter_frame * old_cf
3078                               = (search_state.counter_stack
3079                                  ? ((struct rx_counter_frame *)
3080                                     search_state.counter_stack->sp)
3081                                  : 0);
3082                             struct rx_counter_frame * cf;
3083                             PUSH(search_state.counter_stack,
3084                                  sizeof (struct rx_counter_frame));
3085                             cf = ((struct rx_counter_frame *)
3086                                   search_state.counter_stack->sp);
3087                             cf->tag = re_se_pushpos;
3088                             cf->val = urhere;
3089                             cf->inherited_from = 0;
3090                             cf->cdr = old_cf;
3091                             break;
3092                           }
3093
3094                         case re_se_chkpos:
3095                           {
3096                             int urhere =
3097                               ((int)(search_state.test_pos.pos
3098                                      - search_state.test_pos.string)
3099                                + search_state.test_pos.offset);
3100                             struct rx_counter_frame * cf
3101                               = ((struct rx_counter_frame *)
3102                                  search_state.counter_stack->sp);
3103                             if (cf->val == urhere)
3104                               goto test_do_return;
3105                             cf->val = urhere;
3106                             break;
3107                           }
3108                           break;
3109
3110                         case re_se_poppos:
3111                           POP(search_state.counter_stack,
3112                               sizeof (struct rx_counter_frame));
3113                           break;
3114
3115
3116                         case re_se_at_dot:
3117                         case re_se_syntax:
3118                         case re_se_not_syntax:
3119 #ifdef emacs
3120                           /*
3121                            * this release lacks emacs support
3122                            */
3123 #endif
3124                           break;
3125                         case re_se_win:
3126                         case re_se_lparen:
3127                         case re_se_rparen:
3128                         case re_se_backref:
3129                         case re_se_iter:
3130                         case re_se_end_iter:
3131                         case re_se_tv:
3132                         case re_floogle_flap:
3133                           search_state.ret_val = 0;
3134                           goto test_do_return;
3135                         }
3136                     }
3137                   else
3138                     {
3139 #ifdef RX_DEBUG_0
3140                       if (rx_debug_trace)
3141                         fprintf (stderr, "....%d %d>> %s %d %d\n", search_state.line_no,
3142                                  search_state.backtrack_depth,
3143                                  efnames2[rxb->se_params [effect].se],
3144                                  rxb->se_params [effect].op1,
3145                                  rxb->se_params [effect].op2);
3146 #endif
3147                       switch (rxb->se_params [effect].se)
3148                         {
3149                         case re_se_win:
3150                           /* This side effect indicates that we've
3151                            * found a match, though not necessarily the
3152                            * best match.  This is a fancy assignment to
3153                            * register 0 unless the caller didn't
3154                            * care about registers.  In which case,
3155                            * this stops the match.
3156                            */
3157                           {
3158                             int urhere =
3159                               ((int)(search_state.test_pos.pos
3160                                      - search_state.test_pos.string)
3161                                + search_state.test_pos.offset);
3162
3163                             if (   (search_state.best_last_r < 0)
3164                                 || (urhere + 1 > search_state.best_rparen[0]))
3165                               {
3166                                 /* Record the best known and keep
3167                                  * looking.
3168                                  */
3169                                 int x;
3170                                 for (x = 0; x <= search_state.last_l; ++x)
3171                                   search_state.best_lparen[x] = search_state.lparen[x];
3172                                 search_state.best_last_l = search_state.last_l;
3173                                 for (x = 0; x <= search_state.last_r; ++x)
3174                                   search_state.best_rparen[x] = search_state.rparen[x];
3175                                 search_state.best_rparen[0] = urhere + 1;
3176                                 search_state.best_last_r = search_state.last_r;
3177                               }
3178                             /* If we're not reporting the match-length
3179                              * or other register info, we need look no
3180                              * further.
3181                              */
3182                             if (search_state.first_found)
3183                               {
3184                                 search_state.test_ret = rx_test_found_first;
3185                                 goto test_do_return;
3186                               }
3187                           }
3188                           break;
3189                         case re_se_lparen:
3190                           {
3191                             int urhere =
3192                               ((int)(search_state.test_pos.pos
3193                                      - search_state.test_pos.string)
3194                                + search_state.test_pos.offset);
3195
3196                             int reg = rxb->se_params [effect].op1;
3197 #if 0
3198                             if (reg > search_state.last_l)
3199 #endif
3200                               {
3201                                 search_state.lparen[reg] = urhere + 1;
3202                                 /* In addition to making this assignment,
3203                                  * we now know that lower numbered regs
3204                                  * that haven't already been assigned,
3205                                  * won't be.  We make sure they're
3206                                  * filled with -1, so they can be
3207                                  * recognized as unassigned.
3208                                  */
3209                                 if (search_state.last_l < reg)
3210                                   while (++search_state.last_l < reg)
3211                                     search_state.lparen[search_state.last_l] = -1;
3212                               }
3213                             break;
3214                           }
3215
3216                         case re_se_rparen:
3217                           {
3218                             int urhere =
3219                               ((int)(search_state.test_pos.pos
3220                                      - search_state.test_pos.string)
3221                                + search_state.test_pos.offset);
3222                             int reg = rxb->se_params [effect].op1;
3223                             search_state.rparen[reg] = urhere + 1;
3224                             if (search_state.last_r < reg)
3225                               {
3226                                 while (++search_state.last_r < reg)
3227                                   search_state.rparen[search_state.last_r]
3228                                     = -1;
3229                               }
3230                             break;
3231                           }
3232
3233                         case re_se_backref:
3234                           {
3235                             int reg = rxb->se_params [effect].op1;
3236                             if (   reg > search_state.last_r
3237                                 || search_state.rparen[reg] < 0)
3238                               goto test_do_return;
3239
3240                             {
3241                               int backref_status;
3242                             check_backreference:
3243                               backref_status
3244                                 = back_check (&search_state.test_pos,
3245                                               search_state.lparen[reg],
3246                                               search_state.rparen[reg],
3247                                               search_state.translate,
3248                                               app_closure,
3249                                               stop);
3250                               switch (backref_status)
3251                                 {
3252                                 case rx_back_check_continuation:
3253                                   search_state.saved_reg = reg;
3254                                   test_pc = rx_test_backreference_check;
3255                                   goto test_return_continuation;
3256                                 resume_continuation_2:
3257                                   reg = search_state.saved_reg;
3258                                   goto check_backreference;
3259                                 case rx_back_check_fail:
3260                                   /* Fail */
3261                                   goto test_do_return;
3262                                 case rx_back_check_pass:
3263                                   /* pass --
3264                                    * test_pos now advanced to last
3265                                    * char matched by backref
3266                                    */
3267                                   break;
3268                                 }
3269                             }
3270                             break;
3271                           }
3272                         case re_se_iter:
3273                           {
3274                             struct rx_counter_frame * csp
3275                               = ((struct rx_counter_frame *)
3276                                  search_state.counter_stack->sp);
3277                             if (csp->val == rxb->se_params[effect].op2)
3278                               goto test_do_return;
3279                             else
3280                               ++csp->val;
3281                             break;
3282                           }
3283                         case re_se_end_iter:
3284                           {
3285                             struct rx_counter_frame * csp
3286                               = ((struct rx_counter_frame *)
3287                                  search_state.counter_stack->sp);
3288                             if (csp->val < rxb->se_params[effect].op1)
3289                               goto test_do_return;
3290                             else
3291                               {
3292                                 struct rx_counter_frame * source = csp;
3293                                 while (source->inherited_from)
3294                                   source = source->inherited_from;
3295                                 if (!source || !source->cdr)
3296                                   {
3297                                     POP(search_state.counter_stack,
3298                                         sizeof(struct rx_counter_frame));
3299                                   }
3300                                 else
3301                                   {
3302                                     source = source->cdr;
3303                                     csp->val = source->val;
3304                                     csp->tag = source->tag;
3305                                     csp->cdr = 0;
3306                                     csp->inherited_from = source;
3307                                   }
3308                               }
3309                             break;
3310                           }
3311                         case re_se_tv:
3312                           /* is a noop */
3313                           break;
3314                         case re_se_try:
3315                         case re_se_pushback:
3316                         case re_se_push0:
3317                         case re_se_pushpos:
3318                         case re_se_chkpos:
3319                         case re_se_poppos:
3320                         case re_se_at_dot:
3321                         case re_se_syntax:
3322                         case re_se_not_syntax:
3323                         case re_se_begbuf:
3324                         case re_se_hat:
3325                         case re_se_wordbeg:
3326                         case re_se_wordbound:
3327                         case re_se_notwordbound:
3328                         case re_se_wordend:
3329                         case re_se_endbuf:
3330                         case re_se_dollar:
3331                         case re_se_fail:
3332                         case re_floogle_flap:
3333                           search_state.ret_val = 0;
3334                           goto test_do_return;
3335                         }
3336                     }
3337                   el = el->cdr;
3338                 }
3339               /* Now the side effects are done,
3340                * so get the next instruction.
3341                * and move on.
3342                */
3343               search_state.ifr = &df->future_frame;
3344               goto restart;
3345             }
3346
3347           case rx_backtrack_point:
3348             {
3349               /* A backtrack point indicates that we've reached a
3350                * non-determinism in the superstate NFA.  This is a
3351                * loop that exhaustively searches the possibilities.
3352                *
3353                * A backtracking strategy is used.  We keep track of what
3354                * registers are valid so we can erase side effects.
3355                *
3356                * First, make sure there is some stack space to hold
3357                * our state.
3358                */
3359
3360               struct rx_backtrack_frame * bf;
3361
3362               PUSH(search_state.backtrack_stack,
3363                    search_state.backtrack_frame_bytes);
3364 #ifdef RX_DEBUG_0
3365               ++search_state.backtrack_depth;
3366 #endif
3367
3368               bf = ((struct rx_backtrack_frame *)
3369                     search_state.backtrack_stack->sp);
3370               {
3371                 bf->stk_super = search_state.super;
3372                 /* We prevent the current superstate from being
3373                  * deleted from the superstate cache.
3374                  */
3375                 rx_lock_superstate (&rxb->rx, search_state.super);
3376 #ifdef RX_DEBUG_0
3377                 bf->stk_search_state.line_no = search_state.line_no;
3378 #endif
3379                 bf->stk_c = search_state.c;
3380                 bf->stk_test_pos = search_state.test_pos;
3381                 bf->stk_last_l = search_state.last_l;
3382                 bf->stk_last_r = search_state.last_r;
3383                 bf->df = ((struct rx_super_edge *)
3384                           search_state.ifr->data_2)->options;
3385                 bf->first_df = bf->df;
3386                 bf->counter_stack_sp = (search_state.counter_stack
3387                                         ? search_state.counter_stack->sp
3388                                         : 0);
3389                 bf->stk_test_ret = search_state.test_ret;
3390                 if (rxb->match_regs_on_stack)
3391                   {
3392                     int x;
3393                     regoff_t * stk =
3394                       (regoff_t *)((char *)bf + sizeof (*bf));
3395                     for (x = 0; x <= search_state.last_l; ++x)
3396                       stk[x] = search_state.lparen[x];
3397                     stk += x;
3398                     for (x = 0; x <= search_state.last_r; ++x)
3399                       stk[x] = search_state.rparen[x];
3400                   }
3401               }
3402
3403               /* Here is a while loop whose body is mainly a function
3404                * call and some code to handle a return from that
3405                * function.
3406                *
3407                * From here on for the rest of `case backtrack_point' it
3408                * is unsafe to assume that the search_state copies of
3409                * variables saved on the backtracking stack are valid
3410                * -- so read their values from the backtracking stack.
3411                *
3412                * This lets us use one generation fewer stack saves in
3413                * the call-graph of a search.
3414                */
3415
3416             while_non_det_options:
3417 #ifdef RX_DEBUG_0
3418               ++search_state.lines_found;
3419               if (rx_debug_trace)
3420                 fprintf (stderr, "@@@ %d calls %d @@@\n",
3421                          search_state.line_no, search_state.lines_found);
3422
3423               search_state.line_no = search_state.lines_found;
3424 #endif
3425
3426               if (bf->df->next_same_super_edge[0] == bf->first_df)
3427                 {
3428                   /* This is a tail-call optimization -- we don't recurse
3429                    * for the last of the possible futures.
3430                    */
3431                   search_state.ifr = (bf->df->effects
3432                                       ? &bf->df->side_effects_frame
3433                                       : &bf->df->future_frame);
3434
3435                   rx_unlock_superstate (&rxb->rx, search_state.super);
3436                   POP(search_state.backtrack_stack,
3437                       search_state.backtrack_frame_bytes);
3438 #ifdef RX_DEBUG
3439                   --search_state.backtrack_depth;
3440 #endif
3441                   goto restart;
3442                 }
3443               else
3444                 {
3445                   if (search_state.counter_stack)
3446                     {
3447                       struct rx_counter_frame * old_cf
3448                         = ((struct rx_counter_frame *)search_state.counter_stack->sp);
3449                       struct rx_counter_frame * cf;
3450                       PUSH(search_state.counter_stack, sizeof (struct rx_counter_frame));
3451                       cf = ((struct rx_counter_frame *)search_state.counter_stack->sp);
3452                       cf->tag = old_cf->tag;
3453                       cf->val = old_cf->val;
3454                       cf->inherited_from = old_cf;
3455                       cf->cdr = 0;
3456                     }
3457                   /* `Call' this test-match block */
3458                   search_state.ifr = (bf->df->effects
3459                                       ? &bf->df->side_effects_frame
3460                                       : &bf->df->future_frame);
3461                   goto recurse_test_match;
3462                 }
3463
3464               /* Returns in this block are accomplished by
3465                * goto test_do_return.  There are two cases.
3466                * If there is some search-stack left,
3467                * then it is a return from a `recursive' call.
3468                * If there is no search-stack left, then
3469                * we should return to the fastmap/search loop.
3470                */
3471
3472             test_do_return:
3473
3474               if (!search_state.backtrack_stack)
3475                 {
3476 #ifdef RX_DEBUG_0
3477                   if (rx_debug_trace)
3478                     fprintf (stderr, "!!! %d bails returning %d !!!\n",
3479                              search_state.line_no, search_state.test_ret);
3480 #endif
3481
3482                   /* No more search-stack -- this test is done. */
3483                   if (search_state.test_ret != rx_test_internal_error)
3484                     goto return_from_test_match;
3485                   else
3486                     goto error_in_testing_match;
3487                 }
3488
3489               /* Returning from a recursive call to
3490                * the test match block:
3491                */
3492
3493               bf = ((struct rx_backtrack_frame *)
3494                     search_state.backtrack_stack->sp);
3495 #ifdef RX_DEBUG_0
3496               if (rx_debug_trace)
3497                 fprintf (stderr, "+++ %d returns %d (to %d)+++\n",
3498                          search_state.line_no,
3499                          search_state.test_ret,
3500                          bf->stk_search_state.line_no);
3501 #endif
3502
3503               while (search_state.counter_stack
3504                      && (!bf->counter_stack_sp
3505                          || (bf->counter_stack_sp
3506                              != search_state.counter_stack->sp)))
3507                 {
3508                   POP(search_state.counter_stack,
3509                       sizeof (struct rx_counter_frame));
3510                 }
3511
3512               if (search_state.test_ret == rx_test_internal_error)
3513                 {
3514                   POP (search_state.backtrack_stack,
3515                        search_state.backtrack_frame_bytes);
3516                   search_state.test_ret = rx_test_internal_error;
3517                   goto test_do_return;
3518                 }
3519
3520               /* If a non-longest match was found and that is good
3521                * enough, return immediately.
3522                */
3523               if (   (search_state.test_ret == rx_test_found_first)
3524                   && search_state.first_found)
3525                 {
3526                   rx_unlock_superstate (&rxb->rx, bf->stk_super);
3527                   POP (search_state.backtrack_stack,
3528                        search_state.backtrack_frame_bytes);
3529                   goto test_do_return;
3530                 }
3531
3532               search_state.test_ret = bf->stk_test_ret;
3533               search_state.last_l = bf->stk_last_l;
3534               search_state.last_r = bf->stk_last_r;
3535               bf->df = bf->df->next_same_super_edge[0];
3536               search_state.super = bf->stk_super;
3537               search_state.c = bf->stk_c;
3538 #ifdef RX_DEBUG_0
3539               search_state.line_no = bf->stk_search_state.line_no;
3540 #endif
3541
3542               if (rxb->match_regs_on_stack)
3543                 {
3544                   int x;
3545                   regoff_t * stk =
3546                     (regoff_t *)((char *)bf + sizeof (*bf));
3547                   for (x = 0; x <= search_state.last_l; ++x)
3548                     search_state.lparen[x] = stk[x];
3549                   stk += x;
3550                   for (x = 0; x <= search_state.last_r; ++x)
3551                     search_state.rparen[x] = stk[x];
3552                 }
3553
3554               {
3555                 int x;
3556               try_burst_2:
3557                 x = get_burst (&bf->stk_test_pos, app_closure, stop);
3558                 switch (x)
3559                   {
3560                   case rx_get_burst_continuation:
3561                     search_state.saved_bf = bf;
3562                     test_pc = rx_test_backtrack_return;
3563                     goto test_return_continuation;
3564                   resume_continuation_3:
3565                     bf = search_state.saved_bf;
3566                     goto try_burst_2;
3567                   case rx_get_burst_no_more:
3568                     /* Since we've been here before, it is some kind of
3569                      * error that we can't return.
3570                      */
3571                   case rx_get_burst_error:
3572                     search_state.test_ret = rx_test_internal_error;
3573                     goto test_do_return;
3574                   case rx_get_burst_ok:
3575                     break;
3576                   }
3577               }
3578               search_state.test_pos = bf->stk_test_pos;
3579               goto while_non_det_options;
3580             }
3581
3582
3583           case rx_cache_miss:
3584             /* Because the superstate NFA is lazily constructed,
3585              * and in fact may erode from underneath us, we sometimes
3586              * have to construct the next instruction from the hard way.
3587              * This invokes one step in the lazy-conversion.
3588              */
3589             search_state.ifr = rx_handle_cache_miss (&rxb->rx,
3590                                                      search_state.super,
3591                                                      search_state.c,
3592                                                      search_state.ifr->data_2);
3593             if (!search_state.ifr)
3594               {
3595                 search_state.test_ret = rx_test_internal_error;
3596                 goto test_do_return;
3597               }
3598             goto restart;
3599
3600           case rx_backtrack:
3601             /* RX_BACKTRACK means that we've reached the empty
3602              * superstate, indicating that match can't succeed
3603              * from this point.
3604              */
3605             goto test_do_return;
3606
3607           case rx_next_char:
3608           case rx_error_inx:
3609           case rx_num_instructions:
3610             search_state.ret_val = 0;
3611             goto test_do_return;
3612           }
3613         goto pseudo_while_1;
3614       }
3615
3616     /* Healthy exits from the test-match loop do a
3617      * `goto return_from_test_match'   On the other hand,
3618      * we might end up here.
3619      */
3620   error_in_testing_match:
3621     test_state = rx_test_error;
3622     goto test_returns_to_search;
3623
3624     /***** fastmap/search loop body
3625      *        considering the results testing for a match
3626      */
3627
3628   return_from_test_match:
3629
3630     if (search_state.best_last_l >= 0)
3631       {
3632         if (regs && (regs->start != search_state.best_lparen))
3633           {
3634             bcopy (search_state.best_lparen, regs->start,
3635                    regs->num_regs * sizeof (int));
3636             bcopy (search_state.best_rparen, regs->end,
3637                    regs->num_regs * sizeof (int));
3638           }
3639         if (regs && !rxb->no_sub)
3640           {
3641             int q;
3642             int bound = (regs->num_regs > search_state.num_regs
3643                          ? regs->num_regs
3644                          : search_state.num_regs);
3645             regoff_t * s = regs->start;
3646             regoff_t * e = regs->end;
3647             for (q = search_state.best_last_l + 1;  q < bound; ++q)
3648               s[q] = e[q] = -1;
3649           }
3650         search_state.ret_val = search_state.best_lparen[0];
3651         test_state = rx_test_ok;
3652         goto test_returns_to_search;
3653       }
3654     else
3655       {
3656         test_state = rx_test_fail;
3657         goto test_returns_to_search;
3658       }
3659
3660   test_return_continuation:
3661     search_state.test_match_resume_pt = test_pc;
3662     test_state = rx_test_continuation;
3663     goto test_returns_to_search;
3664   }
3665 }
3666
3667
3668
3669 #endif /* RX_WANT_RX_DEFS */
3670
3671
3672
3673 #else /* RX_WANT_SE_DEFS */
3674   /* Integers are used to represent side effects.
3675    *
3676    * Simple side effects are given negative integer names by these enums.
3677    *
3678    * Non-negative names are reserved for complex effects.
3679    *
3680    * Complex effects are those that take arguments.  For example,
3681    * a register assignment associated with a group is complex because
3682    * it requires an argument to tell which group is being matched.
3683    *
3684    * The integer name of a complex effect is an index into rxb->se_params.
3685    */
3686
3687   RX_DEF_SE(1, re_se_try, = -1)         /* Epsilon from start state */
3688
3689   RX_DEF_SE(0, re_se_pushback, = re_se_try - 1)
3690   RX_DEF_SE(0, re_se_push0, = re_se_pushback -1)
3691   RX_DEF_SE(0, re_se_pushpos, = re_se_push0 - 1)
3692   RX_DEF_SE(0, re_se_chkpos, = re_se_pushpos -1)
3693   RX_DEF_SE(0, re_se_poppos, = re_se_chkpos - 1)
3694
3695   RX_DEF_SE(1, re_se_at_dot, = re_se_poppos - 1)        /* Emacs only */
3696   RX_DEF_SE(0, re_se_syntax, = re_se_at_dot - 1) /* Emacs only */
3697   RX_DEF_SE(0, re_se_not_syntax, = re_se_syntax - 1) /* Emacs only */
3698
3699   RX_DEF_SE(1, re_se_begbuf, = re_se_not_syntax - 1) /* match beginning of buffer */
3700   RX_DEF_SE(1, re_se_hat, = re_se_begbuf - 1) /* match beginning of line */
3701
3702   RX_DEF_SE(1, re_se_wordbeg, = re_se_hat - 1)
3703   RX_DEF_SE(1, re_se_wordbound, = re_se_wordbeg - 1)
3704   RX_DEF_SE(1, re_se_notwordbound, = re_se_wordbound - 1)
3705
3706   RX_DEF_SE(1, re_se_wordend, = re_se_notwordbound - 1)
3707   RX_DEF_SE(1, re_se_endbuf, = re_se_wordend - 1)
3708
3709   /* This fails except at the end of a line.
3710    * It deserves to go here since it is typicly one of the last steps
3711    * in a match.
3712    */
3713   RX_DEF_SE(1, re_se_dollar, = re_se_endbuf - 1)
3714
3715   /* Simple effects: */
3716   RX_DEF_SE(1, re_se_fail, = re_se_dollar - 1)
3717
3718   /* Complex effects.  These are used in the 'se' field of
3719    * a struct re_se_params.  Indexes into the se array
3720    * are stored as instructions on nfa edges.
3721    */
3722   RX_DEF_CPLX_SE(1, re_se_win, = 0)
3723   RX_DEF_CPLX_SE(1, re_se_lparen, = re_se_win + 1)
3724   RX_DEF_CPLX_SE(1, re_se_rparen, = re_se_lparen + 1)
3725   RX_DEF_CPLX_SE(0, re_se_backref, = re_se_rparen + 1)
3726   RX_DEF_CPLX_SE(0, re_se_iter, = re_se_backref + 1)
3727   RX_DEF_CPLX_SE(0, re_se_end_iter, = re_se_iter + 1)
3728   RX_DEF_CPLX_SE(0, re_se_tv, = re_se_end_iter + 1)
3729
3730 #endif
3731
3732 #endif