74fca1cbbae6c8823db708f393b87b544a4158b7
[gnulib.git] / regex.c
1 /* Extended regular expression matching and search library,
2    version 0.12.
3    (Implements POSIX draft P10003.2/D11.2, except for
4    internationalization features.)
5
6    Copyright (C) 1993, 1994 Free Software Foundation, Inc.
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 2, or (at your option)
11    any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program; if not, write to the Free Software
20    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
21
22 /* AIX requires this to be the first thing in the file. */
23 #if defined (_AIX) && !defined (REGEX_MALLOC)
24   #pragma alloca
25 #endif
26
27 #define _GNU_SOURCE
28
29 #ifdef HAVE_CONFIG_H
30 #include <config.h>
31 #endif
32
33 /* We need this for `regex.h', and perhaps for the Emacs include files.  */
34 #include <sys/types.h>
35
36 /* This is for other GNU distributions with internationalized messages.
37    The GNU C Library itself does not yet support such messages.  */
38 #if HAVE_LIBINTL_H
39 # include <libintl.h>
40 #else
41 # define gettext(msgid) (msgid)
42 #endif
43
44 /* The `emacs' switch turns on certain matching commands
45    that make sense only in Emacs. */
46 #ifdef emacs
47
48 #include "lisp.h"
49 #include "buffer.h"
50 #include "syntax.h"
51
52 #else  /* not emacs */
53
54 /* If we are not linking with Emacs proper,
55    we can't use the relocating allocator
56    even if config.h says that we can.  */
57 #undef REL_ALLOC
58
59 #ifdef STDC_HEADERS
60 #include <stdlib.h>
61 #else
62 char *malloc ();
63 char *realloc ();
64 #endif
65
66 /* We used to test for `BSTRING' here, but only GCC and Emacs define
67    `BSTRING', as far as I know, and neither of them use this code.  */
68 #ifndef INHIBIT_STRING_HEADER
69 #if HAVE_STRING_H || STDC_HEADERS
70 #include <string.h>
71 #ifndef bcmp
72 #define bcmp(s1, s2, n) memcmp ((s1), (s2), (n))
73 #endif
74 #ifndef bcopy
75 #define bcopy(s, d, n)  memcpy ((d), (s), (n))
76 #endif
77 #ifndef bzero
78 #define bzero(s, n)     memset ((s), 0, (n))
79 #endif
80 #else
81 #include <strings.h>
82 #endif
83 #endif
84
85 /* Define the syntax stuff for \<, \>, etc.  */
86
87 /* This must be nonzero for the wordchar and notwordchar pattern
88    commands in re_match_2.  */
89 #ifndef Sword 
90 #define Sword 1
91 #endif
92
93 #ifdef SWITCH_ENUM_BUG
94 #define SWITCH_ENUM_CAST(x) ((int)(x))
95 #else
96 #define SWITCH_ENUM_CAST(x) (x)
97 #endif
98
99 #ifdef SYNTAX_TABLE
100
101 extern char *re_syntax_table;
102
103 #else /* not SYNTAX_TABLE */
104
105 /* How many characters in the character set.  */
106 #define CHAR_SET_SIZE 256
107
108 static char re_syntax_table[CHAR_SET_SIZE];
109
110 static void
111 init_syntax_once ()
112 {
113    register int c;
114    static int done = 0;
115
116    if (done)
117      return;
118
119    bzero (re_syntax_table, sizeof re_syntax_table);
120
121    for (c = 'a'; c <= 'z'; c++)
122      re_syntax_table[c] = Sword;
123
124    for (c = 'A'; c <= 'Z'; c++)
125      re_syntax_table[c] = Sword;
126
127    for (c = '0'; c <= '9'; c++)
128      re_syntax_table[c] = Sword;
129
130    re_syntax_table['_'] = Sword;
131
132    done = 1;
133 }
134
135 #endif /* not SYNTAX_TABLE */
136
137 #define SYNTAX(c) re_syntax_table[c]
138
139 #endif /* not emacs */
140 \f
141 /* Get the interface, including the syntax bits.  */
142 #include "regex.h"
143
144 /* isalpha etc. are used for the character classes.  */
145 #include <ctype.h>
146
147 /* Jim Meyering writes:
148
149    "... Some ctype macros are valid only for character codes that
150    isascii says are ASCII (SGI's IRIX-4.0.5 is one such system --when
151    using /bin/cc or gcc but without giving an ansi option).  So, all
152    ctype uses should be through macros like ISPRINT...  If
153    STDC_HEADERS is defined, then autoconf has verified that the ctype
154    macros don't need to be guarded with references to isascii. ...
155    Defining isascii to 1 should let any compiler worth its salt
156    eliminate the && through constant folding."  */
157
158 #if defined (STDC_HEADERS) || (!defined (isascii) && !defined (HAVE_ISASCII))
159 #define ISASCII(c) 1
160 #else
161 #define ISASCII(c) isascii(c)
162 #endif
163
164 #ifdef isblank
165 #define ISBLANK(c) (ISASCII (c) && isblank (c))
166 #else
167 #define ISBLANK(c) ((c) == ' ' || (c) == '\t')
168 #endif
169 #ifdef isgraph
170 #define ISGRAPH(c) (ISASCII (c) && isgraph (c))
171 #else
172 #define ISGRAPH(c) (ISASCII (c) && isprint (c) && !isspace (c))
173 #endif
174
175 #define ISPRINT(c) (ISASCII (c) && isprint (c))
176 #define ISDIGIT(c) (ISASCII (c) && isdigit (c))
177 #define ISALNUM(c) (ISASCII (c) && isalnum (c))
178 #define ISALPHA(c) (ISASCII (c) && isalpha (c))
179 #define ISCNTRL(c) (ISASCII (c) && iscntrl (c))
180 #define ISLOWER(c) (ISASCII (c) && islower (c))
181 #define ISPUNCT(c) (ISASCII (c) && ispunct (c))
182 #define ISSPACE(c) (ISASCII (c) && isspace (c))
183 #define ISUPPER(c) (ISASCII (c) && isupper (c))
184 #define ISXDIGIT(c) (ISASCII (c) && isxdigit (c))
185
186 #ifndef NULL
187 #define NULL 0
188 #endif
189
190 /* We remove any previous definition of `SIGN_EXTEND_CHAR',
191    since ours (we hope) works properly with all combinations of
192    machines, compilers, `char' and `unsigned char' argument types.
193    (Per Bothner suggested the basic approach.)  */
194 #undef SIGN_EXTEND_CHAR
195 #if __STDC__
196 #define SIGN_EXTEND_CHAR(c) ((signed char) (c))
197 #else  /* not __STDC__ */
198 /* As in Harbison and Steele.  */
199 #define SIGN_EXTEND_CHAR(c) ((((unsigned char) (c)) ^ 128) - 128)
200 #endif
201 \f
202 /* Should we use malloc or alloca?  If REGEX_MALLOC is not defined, we
203    use `alloca' instead of `malloc'.  This is because using malloc in
204    re_search* or re_match* could cause memory leaks when C-g is used in
205    Emacs; also, malloc is slower and causes storage fragmentation.  On
206    the other hand, malloc is more portable, and easier to debug.  
207    
208    Because we sometimes use alloca, some routines have to be macros,
209    not functions -- `alloca'-allocated space disappears at the end of the
210    function it is called in.  */
211
212 #ifdef REGEX_MALLOC
213
214 #define REGEX_ALLOCATE malloc
215 #define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
216 #define REGEX_FREE free
217
218 #else /* not REGEX_MALLOC  */
219
220 /* Emacs already defines alloca, sometimes.  */
221 #ifndef alloca
222
223 /* Make alloca work the best possible way.  */
224 #ifdef __GNUC__
225 #define alloca __builtin_alloca
226 #else /* not __GNUC__ */
227 #if HAVE_ALLOCA_H
228 #include <alloca.h>
229 #else /* not __GNUC__ or HAVE_ALLOCA_H */
230 #ifndef _AIX /* Already did AIX, up at the top.  */
231 char *alloca ();
232 #endif /* not _AIX */
233 #endif /* not HAVE_ALLOCA_H */ 
234 #endif /* not __GNUC__ */
235
236 #endif /* not alloca */
237
238 #define REGEX_ALLOCATE alloca
239
240 /* Assumes a `char *destination' variable.  */
241 #define REGEX_REALLOCATE(source, osize, nsize)                          \
242   (destination = (char *) alloca (nsize),                               \
243    bcopy (source, destination, osize),                                  \
244    destination)
245
246 /* No need to do anything to free, after alloca.  */
247 #define REGEX_FREE(arg) (0)
248
249 #endif /* not REGEX_MALLOC */
250
251 /* Define how to allocate the failure stack.  */
252
253 #ifdef REL_ALLOC
254 #define REGEX_ALLOCATE_STACK(size)                              \
255   r_alloc (&failure_stack_ptr, (size))
256 #define REGEX_REALLOCATE_STACK(source, osize, nsize)            \
257   r_re_alloc (&failure_stack_ptr, (nsize))
258 #define REGEX_FREE_STACK(ptr)                                   \
259   r_alloc_free (&failure_stack_ptr)
260
261 #else /* not REL_ALLOC */
262
263 #ifdef REGEX_MALLOC
264
265 #define REGEX_ALLOCATE_STACK malloc
266 #define REGEX_REALLOCATE_STACK(source, osize, nsize) realloc (source, nsize)
267 #define REGEX_FREE_STACK free
268
269 #else /* not REGEX_MALLOC */
270
271 #define REGEX_ALLOCATE_STACK alloca
272
273 #define REGEX_REALLOCATE_STACK(source, osize, nsize)                    \
274    REGEX_REALLOCATE (source, osize, nsize)
275 /* No need to explicitly free anything.  */
276 #define REGEX_FREE_STACK(arg)
277
278 #endif /* not REGEX_MALLOC */
279 #endif /* not REL_ALLOC */
280
281
282 /* True if `size1' is non-NULL and PTR is pointing anywhere inside
283    `string1' or just past its end.  This works if PTR is NULL, which is
284    a good thing.  */
285 #define FIRST_STRING_P(ptr)                                     \
286   (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
287
288 /* (Re)Allocate N items of type T using malloc, or fail.  */
289 #define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
290 #define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
291 #define RETALLOC_IF(addr, n, t) \
292   if (addr) RETALLOC((addr), (n), t); else (addr) = TALLOC ((n), t)
293 #define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
294
295 #define BYTEWIDTH 8 /* In bits.  */
296
297 #define STREQ(s1, s2) ((strcmp (s1, s2) == 0))
298
299 #undef MAX
300 #undef MIN
301 #define MAX(a, b) ((a) > (b) ? (a) : (b))
302 #define MIN(a, b) ((a) < (b) ? (a) : (b))
303
304 typedef char boolean;
305 #define false 0
306 #define true 1
307
308 static int re_match_2_internal ();
309 \f
310 /* These are the command codes that appear in compiled regular
311    expressions.  Some opcodes are followed by argument bytes.  A
312    command code can specify any interpretation whatsoever for its
313    arguments.  Zero bytes may appear in the compiled regular expression.  */
314
315 typedef enum
316 {
317   no_op = 0,
318
319   /* Succeed right away--no more backtracking.  */
320   succeed,
321
322         /* Followed by one byte giving n, then by n literal bytes.  */
323   exactn,
324
325         /* Matches any (more or less) character.  */
326   anychar,
327
328         /* Matches any one char belonging to specified set.  First
329            following byte is number of bitmap bytes.  Then come bytes
330            for a bitmap saying which chars are in.  Bits in each byte
331            are ordered low-bit-first.  A character is in the set if its
332            bit is 1.  A character too large to have a bit in the map is
333            automatically not in the set.  */
334   charset,
335
336         /* Same parameters as charset, but match any character that is
337            not one of those specified.  */
338   charset_not,
339
340         /* Start remembering the text that is matched, for storing in a
341            register.  Followed by one byte with the register number, in
342            the range 0 to one less than the pattern buffer's re_nsub
343            field.  Then followed by one byte with the number of groups
344            inner to this one.  (This last has to be part of the
345            start_memory only because we need it in the on_failure_jump
346            of re_match_2.)  */
347   start_memory,
348
349         /* Stop remembering the text that is matched and store it in a
350            memory register.  Followed by one byte with the register
351            number, in the range 0 to one less than `re_nsub' in the
352            pattern buffer, and one byte with the number of inner groups,
353            just like `start_memory'.  (We need the number of inner
354            groups here because we don't have any easy way of finding the
355            corresponding start_memory when we're at a stop_memory.)  */
356   stop_memory,
357
358         /* Match a duplicate of something remembered. Followed by one
359            byte containing the register number.  */
360   duplicate,
361
362         /* Fail unless at beginning of line.  */
363   begline,
364
365         /* Fail unless at end of line.  */
366   endline,
367
368         /* Succeeds if at beginning of buffer (if emacs) or at beginning
369            of string to be matched (if not).  */
370   begbuf,
371
372         /* Analogously, for end of buffer/string.  */
373   endbuf,
374  
375         /* Followed by two byte relative address to which to jump.  */
376   jump, 
377
378         /* Same as jump, but marks the end of an alternative.  */
379   jump_past_alt,
380
381         /* Followed by two-byte relative address of place to resume at
382            in case of failure.  */
383   on_failure_jump,
384         
385         /* Like on_failure_jump, but pushes a placeholder instead of the
386            current string position when executed.  */
387   on_failure_keep_string_jump,
388   
389         /* Throw away latest failure point and then jump to following
390            two-byte relative address.  */
391   pop_failure_jump,
392
393         /* Change to pop_failure_jump if know won't have to backtrack to
394            match; otherwise change to jump.  This is used to jump
395            back to the beginning of a repeat.  If what follows this jump
396            clearly won't match what the repeat does, such that we can be
397            sure that there is no use backtracking out of repetitions
398            already matched, then we change it to a pop_failure_jump.
399            Followed by two-byte address.  */
400   maybe_pop_jump,
401
402         /* Jump to following two-byte address, and push a dummy failure
403            point. This failure point will be thrown away if an attempt
404            is made to use it for a failure.  A `+' construct makes this
405            before the first repeat.  Also used as an intermediary kind
406            of jump when compiling an alternative.  */
407   dummy_failure_jump,
408
409         /* Push a dummy failure point and continue.  Used at the end of
410            alternatives.  */
411   push_dummy_failure,
412
413         /* Followed by two-byte relative address and two-byte number n.
414            After matching N times, jump to the address upon failure.  */
415   succeed_n,
416
417         /* Followed by two-byte relative address, and two-byte number n.
418            Jump to the address N times, then fail.  */
419   jump_n,
420
421         /* Set the following two-byte relative address to the
422            subsequent two-byte number.  The address *includes* the two
423            bytes of number.  */
424   set_number_at,
425
426   wordchar,     /* Matches any word-constituent character.  */
427   notwordchar,  /* Matches any char that is not a word-constituent.  */
428
429   wordbeg,      /* Succeeds if at word beginning.  */
430   wordend,      /* Succeeds if at word end.  */
431
432   wordbound,    /* Succeeds if at a word boundary.  */
433   notwordbound  /* Succeeds if not at a word boundary.  */
434
435 #ifdef emacs
436   ,before_dot,  /* Succeeds if before point.  */
437   at_dot,       /* Succeeds if at point.  */
438   after_dot,    /* Succeeds if after point.  */
439
440         /* Matches any character whose syntax is specified.  Followed by
441            a byte which contains a syntax code, e.g., Sword.  */
442   syntaxspec,
443
444         /* Matches any character whose syntax is not that specified.  */
445   notsyntaxspec
446 #endif /* emacs */
447 } re_opcode_t;
448 \f
449 /* Common operations on the compiled pattern.  */
450
451 /* Store NUMBER in two contiguous bytes starting at DESTINATION.  */
452
453 #define STORE_NUMBER(destination, number)                               \
454   do {                                                                  \
455     (destination)[0] = (number) & 0377;                                 \
456     (destination)[1] = (number) >> 8;                                   \
457   } while (0)
458
459 /* Same as STORE_NUMBER, except increment DESTINATION to
460    the byte after where the number is stored.  Therefore, DESTINATION
461    must be an lvalue.  */
462
463 #define STORE_NUMBER_AND_INCR(destination, number)                      \
464   do {                                                                  \
465     STORE_NUMBER (destination, number);                                 \
466     (destination) += 2;                                                 \
467   } while (0)
468
469 /* Put into DESTINATION a number stored in two contiguous bytes starting
470    at SOURCE.  */
471
472 #define EXTRACT_NUMBER(destination, source)                             \
473   do {                                                                  \
474     (destination) = *(source) & 0377;                                   \
475     (destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8;           \
476   } while (0)
477
478 #ifdef DEBUG
479 static void
480 extract_number (dest, source)
481     int *dest;
482     unsigned char *source;
483 {
484   int temp = SIGN_EXTEND_CHAR (*(source + 1)); 
485   *dest = *source & 0377;
486   *dest += temp << 8;
487 }
488
489 #ifndef EXTRACT_MACROS /* To debug the macros.  */
490 #undef EXTRACT_NUMBER
491 #define EXTRACT_NUMBER(dest, src) extract_number (&dest, src)
492 #endif /* not EXTRACT_MACROS */
493
494 #endif /* DEBUG */
495
496 /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
497    SOURCE must be an lvalue.  */
498
499 #define EXTRACT_NUMBER_AND_INCR(destination, source)                    \
500   do {                                                                  \
501     EXTRACT_NUMBER (destination, source);                               \
502     (source) += 2;                                                      \
503   } while (0)
504
505 #ifdef DEBUG
506 static void
507 extract_number_and_incr (destination, source)
508     int *destination;
509     unsigned char **source;
510
511   extract_number (destination, *source);
512   *source += 2;
513 }
514
515 #ifndef EXTRACT_MACROS
516 #undef EXTRACT_NUMBER_AND_INCR
517 #define EXTRACT_NUMBER_AND_INCR(dest, src) \
518   extract_number_and_incr (&dest, &src)
519 #endif /* not EXTRACT_MACROS */
520
521 #endif /* DEBUG */
522 \f
523 /* If DEBUG is defined, Regex prints many voluminous messages about what
524    it is doing (if the variable `debug' is nonzero).  If linked with the
525    main program in `iregex.c', you can enter patterns and strings
526    interactively.  And if linked with the main program in `main.c' and
527    the other test files, you can run the already-written tests.  */
528
529 #ifdef DEBUG
530
531 /* We use standard I/O for debugging.  */
532 #include <stdio.h>
533
534 /* It is useful to test things that ``must'' be true when debugging.  */
535 #include <assert.h>
536
537 static int debug = 0;
538
539 #define DEBUG_STATEMENT(e) e
540 #define DEBUG_PRINT1(x) if (debug) printf (x)
541 #define DEBUG_PRINT2(x1, x2) if (debug) printf (x1, x2)
542 #define DEBUG_PRINT3(x1, x2, x3) if (debug) printf (x1, x2, x3)
543 #define DEBUG_PRINT4(x1, x2, x3, x4) if (debug) printf (x1, x2, x3, x4)
544 #define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)                           \
545   if (debug) print_partial_compiled_pattern (s, e)
546 #define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)                  \
547   if (debug) print_double_string (w, s1, sz1, s2, sz2)
548
549
550 /* Print the fastmap in human-readable form.  */
551
552 void
553 print_fastmap (fastmap)
554     char *fastmap;
555 {
556   unsigned was_a_range = 0;
557   unsigned i = 0;  
558   
559   while (i < (1 << BYTEWIDTH))
560     {
561       if (fastmap[i++])
562         {
563           was_a_range = 0;
564           putchar (i - 1);
565           while (i < (1 << BYTEWIDTH)  &&  fastmap[i])
566             {
567               was_a_range = 1;
568               i++;
569             }
570           if (was_a_range)
571             {
572               printf ("-");
573               putchar (i - 1);
574             }
575         }
576     }
577   putchar ('\n'); 
578 }
579
580
581 /* Print a compiled pattern string in human-readable form, starting at
582    the START pointer into it and ending just before the pointer END.  */
583
584 void
585 print_partial_compiled_pattern (start, end)
586     unsigned char *start;
587     unsigned char *end;
588 {
589   int mcnt, mcnt2;
590   unsigned char *p = start;
591   unsigned char *pend = end;
592
593   if (start == NULL)
594     {
595       printf ("(null)\n");
596       return;
597     }
598     
599   /* Loop over pattern commands.  */
600   while (p < pend)
601     {
602       printf ("%d:\t", p - start);
603
604       switch ((re_opcode_t) *p++)
605         {
606         case no_op:
607           printf ("/no_op");
608           break;
609
610         case exactn:
611           mcnt = *p++;
612           printf ("/exactn/%d", mcnt);
613           do
614             {
615               putchar ('/');
616               putchar (*p++);
617             }
618           while (--mcnt);
619           break;
620
621         case start_memory:
622           mcnt = *p++;
623           printf ("/start_memory/%d/%d", mcnt, *p++);
624           break;
625
626         case stop_memory:
627           mcnt = *p++;
628           printf ("/stop_memory/%d/%d", mcnt, *p++);
629           break;
630
631         case duplicate:
632           printf ("/duplicate/%d", *p++);
633           break;
634
635         case anychar:
636           printf ("/anychar");
637           break;
638
639         case charset:
640         case charset_not:
641           {
642             register int c, last = -100;
643             register int in_range = 0;
644
645             printf ("/charset [%s",
646                     (re_opcode_t) *(p - 1) == charset_not ? "^" : "");
647             
648             assert (p + *p < pend);
649
650             for (c = 0; c < 256; c++)
651               if (c / 8 < *p
652                   && (p[1 + (c/8)] & (1 << (c % 8))))
653                 {
654                   /* Are we starting a range?  */
655                   if (last + 1 == c && ! in_range)
656                     {
657                       putchar ('-');
658                       in_range = 1;
659                     }
660                   /* Have we broken a range?  */
661                   else if (last + 1 != c && in_range)
662               {
663                       putchar (last);
664                       in_range = 0;
665                     }
666                 
667                   if (! in_range)
668                     putchar (c);
669
670                   last = c;
671               }
672
673             if (in_range)
674               putchar (last);
675
676             putchar (']');
677
678             p += 1 + *p;
679           }
680           break;
681
682         case begline:
683           printf ("/begline");
684           break;
685
686         case endline:
687           printf ("/endline");
688           break;
689
690         case on_failure_jump:
691           extract_number_and_incr (&mcnt, &p);
692           printf ("/on_failure_jump to %d", p + mcnt - start);
693           break;
694
695         case on_failure_keep_string_jump:
696           extract_number_and_incr (&mcnt, &p);
697           printf ("/on_failure_keep_string_jump to %d", p + mcnt - start);
698           break;
699
700         case dummy_failure_jump:
701           extract_number_and_incr (&mcnt, &p);
702           printf ("/dummy_failure_jump to %d", p + mcnt - start);
703           break;
704
705         case push_dummy_failure:
706           printf ("/push_dummy_failure");
707           break;
708           
709         case maybe_pop_jump:
710           extract_number_and_incr (&mcnt, &p);
711           printf ("/maybe_pop_jump to %d", p + mcnt - start);
712           break;
713
714         case pop_failure_jump:
715           extract_number_and_incr (&mcnt, &p);
716           printf ("/pop_failure_jump to %d", p + mcnt - start);
717           break;          
718           
719         case jump_past_alt:
720           extract_number_and_incr (&mcnt, &p);
721           printf ("/jump_past_alt to %d", p + mcnt - start);
722           break;          
723           
724         case jump:
725           extract_number_and_incr (&mcnt, &p);
726           printf ("/jump to %d", p + mcnt - start);
727           break;
728
729         case succeed_n: 
730           extract_number_and_incr (&mcnt, &p);
731           extract_number_and_incr (&mcnt2, &p);
732           printf ("/succeed_n to %d, %d times", p + mcnt - start, mcnt2);
733           break;
734         
735         case jump_n: 
736           extract_number_and_incr (&mcnt, &p);
737           extract_number_and_incr (&mcnt2, &p);
738           printf ("/jump_n to %d, %d times", p + mcnt - start, mcnt2);
739           break;
740         
741         case set_number_at: 
742           extract_number_and_incr (&mcnt, &p);
743           extract_number_and_incr (&mcnt2, &p);
744           printf ("/set_number_at location %d to %d", p + mcnt - start, mcnt2);
745           break;
746         
747         case wordbound:
748           printf ("/wordbound");
749           break;
750
751         case notwordbound:
752           printf ("/notwordbound");
753           break;
754
755         case wordbeg:
756           printf ("/wordbeg");
757           break;
758           
759         case wordend:
760           printf ("/wordend");
761           
762 #ifdef emacs
763         case before_dot:
764           printf ("/before_dot");
765           break;
766
767         case at_dot:
768           printf ("/at_dot");
769           break;
770
771         case after_dot:
772           printf ("/after_dot");
773           break;
774
775         case syntaxspec:
776           printf ("/syntaxspec");
777           mcnt = *p++;
778           printf ("/%d", mcnt);
779           break;
780           
781         case notsyntaxspec:
782           printf ("/notsyntaxspec");
783           mcnt = *p++;
784           printf ("/%d", mcnt);
785           break;
786 #endif /* emacs */
787
788         case wordchar:
789           printf ("/wordchar");
790           break;
791           
792         case notwordchar:
793           printf ("/notwordchar");
794           break;
795
796         case begbuf:
797           printf ("/begbuf");
798           break;
799
800         case endbuf:
801           printf ("/endbuf");
802           break;
803
804         default:
805           printf ("?%d", *(p-1));
806         }
807
808       putchar ('\n');
809     }
810
811   printf ("%d:\tend of pattern.\n", p - start);
812 }
813
814
815 void
816 print_compiled_pattern (bufp)
817     struct re_pattern_buffer *bufp;
818 {
819   unsigned char *buffer = bufp->buffer;
820
821   print_partial_compiled_pattern (buffer, buffer + bufp->used);
822   printf ("%d bytes used/%d bytes allocated.\n", bufp->used, bufp->allocated);
823
824   if (bufp->fastmap_accurate && bufp->fastmap)
825     {
826       printf ("fastmap: ");
827       print_fastmap (bufp->fastmap);
828     }
829
830   printf ("re_nsub: %d\t", bufp->re_nsub);
831   printf ("regs_alloc: %d\t", bufp->regs_allocated);
832   printf ("can_be_null: %d\t", bufp->can_be_null);
833   printf ("newline_anchor: %d\n", bufp->newline_anchor);
834   printf ("no_sub: %d\t", bufp->no_sub);
835   printf ("not_bol: %d\t", bufp->not_bol);
836   printf ("not_eol: %d\t", bufp->not_eol);
837   printf ("syntax: %d\n", bufp->syntax);
838   /* Perhaps we should print the translate table?  */
839 }
840
841
842 void
843 print_double_string (where, string1, size1, string2, size2)
844     const char *where;
845     const char *string1;
846     const char *string2;
847     int size1;
848     int size2;
849 {
850   unsigned this_char;
851   
852   if (where == NULL)
853     printf ("(null)");
854   else
855     {
856       if (FIRST_STRING_P (where))
857         {
858           for (this_char = where - string1; this_char < size1; this_char++)
859             putchar (string1[this_char]);
860
861           where = string2;    
862         }
863
864       for (this_char = where - string2; this_char < size2; this_char++)
865         putchar (string2[this_char]);
866     }
867 }
868
869 #else /* not DEBUG */
870
871 #undef assert
872 #define assert(e)
873
874 #define DEBUG_STATEMENT(e)
875 #define DEBUG_PRINT1(x)
876 #define DEBUG_PRINT2(x1, x2)
877 #define DEBUG_PRINT3(x1, x2, x3)
878 #define DEBUG_PRINT4(x1, x2, x3, x4)
879 #define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
880 #define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
881
882 #endif /* not DEBUG */
883 \f
884 /* Set by `re_set_syntax' to the current regexp syntax to recognize.  Can
885    also be assigned to arbitrarily: each pattern buffer stores its own
886    syntax, so it can be changed between regex compilations.  */
887 /* This has no initializer because initialized variables in Emacs
888    become read-only after dumping.  */
889 reg_syntax_t re_syntax_options;
890
891
892 /* Specify the precise syntax of regexps for compilation.  This provides
893    for compatibility for various utilities which historically have
894    different, incompatible syntaxes.
895
896    The argument SYNTAX is a bit mask comprised of the various bits
897    defined in regex.h.  We return the old syntax.  */
898
899 reg_syntax_t
900 re_set_syntax (syntax)
901     reg_syntax_t syntax;
902 {
903   reg_syntax_t ret = re_syntax_options;
904   
905   re_syntax_options = syntax;
906   return ret;
907 }
908 \f
909 /* This table gives an error message for each of the error codes listed
910    in regex.h.  Obviously the order here has to be same as there.
911    POSIX doesn't require that we do anything for REG_NOERROR,
912    but why not be nice?  */
913
914 static const char *re_error_msgid[] =
915   { "Success",                                  /* REG_NOERROR */
916     "No match",                                 /* REG_NOMATCH */
917     "Invalid regular expression",               /* REG_BADPAT */
918     "Invalid collation character",              /* REG_ECOLLATE */
919     "Invalid character class name",             /* REG_ECTYPE */
920     "Trailing backslash",                       /* REG_EESCAPE */
921     "Invalid back reference",                   /* REG_ESUBREG */
922     "Unmatched [ or [^",                        /* REG_EBRACK */
923     "Unmatched ( or \\(",                       /* REG_EPAREN */
924     "Unmatched \\{",                            /* REG_EBRACE */
925     "Invalid content of \\{\\}",                /* REG_BADBR */
926     "Invalid range end",                        /* REG_ERANGE */
927     "Memory exhausted",                         /* REG_ESPACE */
928     "Invalid preceding regular expression",     /* REG_BADRPT */
929     "Premature end of regular expression",      /* REG_EEND */
930     "Regular expression too big",               /* REG_ESIZE */
931     "Unmatched ) or \\)",                       /* REG_ERPAREN */
932   };
933 \f
934 /* Avoiding alloca during matching, to placate r_alloc.  */
935
936 /* Define MATCH_MAY_ALLOCATE unless we need to make sure that the
937    searching and matching functions should not call alloca.  On some
938    systems, alloca is implemented in terms of malloc, and if we're
939    using the relocating allocator routines, then malloc could cause a
940    relocation, which might (if the strings being searched are in the
941    ralloc heap) shift the data out from underneath the regexp
942    routines.
943
944    Here's another reason to avoid allocation: Emacs 
945    processes input from X in a signal handler; processing X input may
946    call malloc; if input arrives while a matching routine is calling
947    malloc, then we're scrod.  But Emacs can't just block input while
948    calling matching routines; then we don't notice interrupts when
949    they come in.  So, Emacs blocks input around all regexp calls
950    except the matching calls, which it leaves unprotected, in the
951    faith that they will not malloc.  */
952
953 /* Normally, this is fine.  */
954 #define MATCH_MAY_ALLOCATE
955
956 /* When using GNU C, we are not REALLY using the C alloca, no matter
957    what config.h may say.  So don't take precautions for it.  */
958 #ifdef __GNUC__
959 #undef C_ALLOCA
960 #endif
961
962 /* The match routines may not allocate if (1) they would do it with malloc
963    and (2) it's not safe for them to use malloc.
964    Note that if REL_ALLOC is defined, matching would not use malloc for the
965    failure stack, but we would still use it for the register vectors;
966    so REL_ALLOC should not affect this.  */
967 #if (defined (C_ALLOCA) || defined (REGEX_MALLOC)) && defined (emacs)
968 #undef MATCH_MAY_ALLOCATE
969 #endif
970
971 \f
972 /* Failure stack declarations and macros; both re_compile_fastmap and
973    re_match_2 use a failure stack.  These have to be macros because of
974    REGEX_ALLOCATE_STACK.  */
975    
976
977 /* Number of failure points for which to initially allocate space
978    when matching.  If this number is exceeded, we allocate more
979    space, so it is not a hard limit.  */
980 #ifndef INIT_FAILURE_ALLOC
981 #define INIT_FAILURE_ALLOC 5
982 #endif
983
984 /* Roughly the maximum number of failure points on the stack.  Would be
985    exactly that if always used MAX_FAILURE_SPACE each time we failed.
986    This is a variable only so users of regex can assign to it; we never
987    change it ourselves.  */
988 #if defined (MATCH_MAY_ALLOCATE)
989 int re_max_failures = 200000;
990 #else
991 int re_max_failures = 2000;
992 #endif
993
994 union fail_stack_elt
995 {
996   unsigned char *pointer;
997   int integer;
998 };
999
1000 typedef union fail_stack_elt fail_stack_elt_t;
1001
1002 typedef struct
1003 {
1004   fail_stack_elt_t *stack;
1005   unsigned size;
1006   unsigned avail;                       /* Offset of next open position.  */
1007 } fail_stack_type;
1008
1009 #define FAIL_STACK_EMPTY()     (fail_stack.avail == 0)
1010 #define FAIL_STACK_PTR_EMPTY() (fail_stack_ptr->avail == 0)
1011 #define FAIL_STACK_FULL()      (fail_stack.avail == fail_stack.size)
1012
1013
1014 /* Initialize `fail_stack'.  Do `return -2' if the alloc fails.  */
1015
1016 #ifdef MATCH_MAY_ALLOCATE
1017 #define INIT_FAIL_STACK()                                               \
1018   do {                                                                  \
1019     fail_stack.stack = (fail_stack_elt_t *)                             \
1020       REGEX_ALLOCATE_STACK (INIT_FAILURE_ALLOC * sizeof (fail_stack_elt_t));    \
1021                                                                         \
1022     if (fail_stack.stack == NULL)                                       \
1023       return -2;                                                        \
1024                                                                         \
1025     fail_stack.size = INIT_FAILURE_ALLOC;                               \
1026     fail_stack.avail = 0;                                               \
1027   } while (0)
1028 #else
1029 #define INIT_FAIL_STACK()                                               \
1030   do {                                                                  \
1031     fail_stack.avail = 0;                                               \
1032   } while (0)
1033 #endif
1034
1035
1036 /* Double the size of FAIL_STACK, up to approximately `re_max_failures' items.
1037
1038    Return 1 if succeeds, and 0 if either ran out of memory
1039    allocating space for it or it was already too large.  
1040    
1041    REGEX_REALLOCATE_STACK requires `destination' be declared.   */
1042
1043 #define DOUBLE_FAIL_STACK(fail_stack)                                   \
1044   ((fail_stack).size > re_max_failures * MAX_FAILURE_ITEMS              \
1045    ? 0                                                                  \
1046    : ((fail_stack).stack = (fail_stack_elt_t *)                         \
1047         REGEX_REALLOCATE_STACK ((fail_stack).stack,                     \
1048           (fail_stack).size * sizeof (fail_stack_elt_t),                \
1049           ((fail_stack).size << 1) * sizeof (fail_stack_elt_t)),        \
1050                                                                         \
1051       (fail_stack).stack == NULL                                        \
1052       ? 0                                                               \
1053       : ((fail_stack).size <<= 1,                                       \
1054          1)))
1055
1056
1057 /* Push pointer POINTER on FAIL_STACK. 
1058    Return 1 if was able to do so and 0 if ran out of memory allocating
1059    space to do so.  */
1060 #define PUSH_PATTERN_OP(POINTER, FAIL_STACK)                            \
1061   ((FAIL_STACK_FULL ()                                                  \
1062     && !DOUBLE_FAIL_STACK (FAIL_STACK))                                 \
1063    ? 0                                                                  \
1064    : ((FAIL_STACK).stack[(FAIL_STACK).avail++].pointer = POINTER,       \
1065       1))
1066
1067 /* Push a pointer value onto the failure stack.
1068    Assumes the variable `fail_stack'.  Probably should only
1069    be called from within `PUSH_FAILURE_POINT'.  */
1070 #define PUSH_FAILURE_POINTER(item)                                      \
1071   fail_stack.stack[fail_stack.avail++].pointer = (unsigned char *) (item)
1072
1073 /* This pushes an integer-valued item onto the failure stack.
1074    Assumes the variable `fail_stack'.  Probably should only
1075    be called from within `PUSH_FAILURE_POINT'.  */
1076 #define PUSH_FAILURE_INT(item)                                  \
1077   fail_stack.stack[fail_stack.avail++].integer = (item)
1078
1079 /* Push a fail_stack_elt_t value onto the failure stack.
1080    Assumes the variable `fail_stack'.  Probably should only
1081    be called from within `PUSH_FAILURE_POINT'.  */
1082 #define PUSH_FAILURE_ELT(item)                                  \
1083   fail_stack.stack[fail_stack.avail++] =  (item)
1084
1085 /* These three POP... operations complement the three PUSH... operations.
1086    All assume that `fail_stack' is nonempty.  */
1087 #define POP_FAILURE_POINTER() fail_stack.stack[--fail_stack.avail].pointer
1088 #define POP_FAILURE_INT() fail_stack.stack[--fail_stack.avail].integer
1089 #define POP_FAILURE_ELT() fail_stack.stack[--fail_stack.avail]
1090
1091 /* Used to omit pushing failure point id's when we're not debugging.  */
1092 #ifdef DEBUG
1093 #define DEBUG_PUSH PUSH_FAILURE_INT
1094 #define DEBUG_POP(item_addr) *(item_addr) = POP_FAILURE_INT ()
1095 #else
1096 #define DEBUG_PUSH(item)
1097 #define DEBUG_POP(item_addr)
1098 #endif
1099
1100
1101 /* Push the information about the state we will need
1102    if we ever fail back to it.  
1103    
1104    Requires variables fail_stack, regstart, regend, reg_info, and
1105    num_regs be declared.  DOUBLE_FAIL_STACK requires `destination' be
1106    declared.
1107    
1108    Does `return FAILURE_CODE' if runs out of memory.  */
1109
1110 #define PUSH_FAILURE_POINT(pattern_place, string_place, failure_code)   \
1111   do {                                                                  \
1112     char *destination;                                                  \
1113     /* Must be int, so when we don't save any registers, the arithmetic \
1114        of 0 + -1 isn't done as unsigned.  */                            \
1115     int this_reg;                                                       \
1116                                                                         \
1117     DEBUG_STATEMENT (failure_id++);                                     \
1118     DEBUG_STATEMENT (nfailure_points_pushed++);                         \
1119     DEBUG_PRINT2 ("\nPUSH_FAILURE_POINT #%u:\n", failure_id);           \
1120     DEBUG_PRINT2 ("  Before push, next avail: %d\n", (fail_stack).avail);\
1121     DEBUG_PRINT2 ("                     size: %d\n", (fail_stack).size);\
1122                                                                         \
1123     DEBUG_PRINT2 ("  slots needed: %d\n", NUM_FAILURE_ITEMS);           \
1124     DEBUG_PRINT2 ("     available: %d\n", REMAINING_AVAIL_SLOTS);       \
1125                                                                         \
1126     /* Ensure we have enough space allocated for what we will push.  */ \
1127     while (REMAINING_AVAIL_SLOTS < NUM_FAILURE_ITEMS)                   \
1128       {                                                                 \
1129         if (!DOUBLE_FAIL_STACK (fail_stack))                            \
1130           return failure_code;                                          \
1131                                                                         \
1132         DEBUG_PRINT2 ("\n  Doubled stack; size now: %d\n",              \
1133                        (fail_stack).size);                              \
1134         DEBUG_PRINT2 ("  slots available: %d\n", REMAINING_AVAIL_SLOTS);\
1135       }                                                                 \
1136                                                                         \
1137     /* Push the info, starting with the registers.  */                  \
1138     DEBUG_PRINT1 ("\n");                                                \
1139                                                                         \
1140     for (this_reg = lowest_active_reg; this_reg <= highest_active_reg;  \
1141          this_reg++)                                                    \
1142       {                                                                 \
1143         DEBUG_PRINT2 ("  Pushing reg: %d\n", this_reg);                 \
1144         DEBUG_STATEMENT (num_regs_pushed++);                            \
1145                                                                         \
1146         DEBUG_PRINT2 ("    start: 0x%x\n", regstart[this_reg]);         \
1147         PUSH_FAILURE_POINTER (regstart[this_reg]);                      \
1148                                                                         \
1149         DEBUG_PRINT2 ("    end: 0x%x\n", regend[this_reg]);             \
1150         PUSH_FAILURE_POINTER (regend[this_reg]);                        \
1151                                                                         \
1152         DEBUG_PRINT2 ("    info: 0x%x\n      ", reg_info[this_reg]);    \
1153         DEBUG_PRINT2 (" match_null=%d",                                 \
1154                       REG_MATCH_NULL_STRING_P (reg_info[this_reg]));    \
1155         DEBUG_PRINT2 (" active=%d", IS_ACTIVE (reg_info[this_reg]));    \
1156         DEBUG_PRINT2 (" matched_something=%d",                          \
1157                       MATCHED_SOMETHING (reg_info[this_reg]));          \
1158         DEBUG_PRINT2 (" ever_matched=%d",                               \
1159                       EVER_MATCHED_SOMETHING (reg_info[this_reg]));     \
1160         DEBUG_PRINT1 ("\n");                                            \
1161         PUSH_FAILURE_ELT (reg_info[this_reg].word);                     \
1162       }                                                                 \
1163                                                                         \
1164     DEBUG_PRINT2 ("  Pushing  low active reg: %d\n", lowest_active_reg);\
1165     PUSH_FAILURE_INT (lowest_active_reg);                               \
1166                                                                         \
1167     DEBUG_PRINT2 ("  Pushing high active reg: %d\n", highest_active_reg);\
1168     PUSH_FAILURE_INT (highest_active_reg);                              \
1169                                                                         \
1170     DEBUG_PRINT2 ("  Pushing pattern 0x%x: ", pattern_place);           \
1171     DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern_place, pend);           \
1172     PUSH_FAILURE_POINTER (pattern_place);                               \
1173                                                                         \
1174     DEBUG_PRINT2 ("  Pushing string 0x%x: `", string_place);            \
1175     DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2,   \
1176                                  size2);                                \
1177     DEBUG_PRINT1 ("'\n");                                               \
1178     PUSH_FAILURE_POINTER (string_place);                                \
1179                                                                         \
1180     DEBUG_PRINT2 ("  Pushing failure id: %u\n", failure_id);            \
1181     DEBUG_PUSH (failure_id);                                            \
1182   } while (0)
1183
1184 /* This is the number of items that are pushed and popped on the stack
1185    for each register.  */
1186 #define NUM_REG_ITEMS  3
1187
1188 /* Individual items aside from the registers.  */
1189 #ifdef DEBUG
1190 #define NUM_NONREG_ITEMS 5 /* Includes failure point id.  */
1191 #else
1192 #define NUM_NONREG_ITEMS 4
1193 #endif
1194
1195 /* We push at most this many items on the stack.  */
1196 #define MAX_FAILURE_ITEMS ((num_regs - 1) * NUM_REG_ITEMS + NUM_NONREG_ITEMS)
1197
1198 /* We actually push this many items.  */
1199 #define NUM_FAILURE_ITEMS                                               \
1200   ((highest_active_reg - lowest_active_reg + 1) * NUM_REG_ITEMS         \
1201     + NUM_NONREG_ITEMS)
1202
1203 /* How many items can still be added to the stack without overflowing it.  */
1204 #define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
1205
1206
1207 /* Pops what PUSH_FAIL_STACK pushes.
1208
1209    We restore into the parameters, all of which should be lvalues:
1210      STR -- the saved data position.
1211      PAT -- the saved pattern position.
1212      LOW_REG, HIGH_REG -- the highest and lowest active registers.
1213      REGSTART, REGEND -- arrays of string positions.
1214      REG_INFO -- array of information about each subexpression.
1215    
1216    Also assumes the variables `fail_stack' and (if debugging), `bufp',
1217    `pend', `string1', `size1', `string2', and `size2'.  */
1218
1219 #define POP_FAILURE_POINT(str, pat, low_reg, high_reg, regstart, regend, reg_info)\
1220 {                                                                       \
1221   DEBUG_STATEMENT (fail_stack_elt_t failure_id;)                        \
1222   int this_reg;                                                         \
1223   const unsigned char *string_temp;                                     \
1224                                                                         \
1225   assert (!FAIL_STACK_EMPTY ());                                        \
1226                                                                         \
1227   /* Remove failure points and point to how many regs pushed.  */       \
1228   DEBUG_PRINT1 ("POP_FAILURE_POINT:\n");                                \
1229   DEBUG_PRINT2 ("  Before pop, next avail: %d\n", fail_stack.avail);    \
1230   DEBUG_PRINT2 ("                    size: %d\n", fail_stack.size);     \
1231                                                                         \
1232   assert (fail_stack.avail >= NUM_NONREG_ITEMS);                        \
1233                                                                         \
1234   DEBUG_POP (&failure_id);                                              \
1235   DEBUG_PRINT2 ("  Popping failure id: %u\n", failure_id);              \
1236                                                                         \
1237   /* If the saved string location is NULL, it came from an              \
1238      on_failure_keep_string_jump opcode, and we want to throw away the  \
1239      saved NULL, thus retaining our current position in the string.  */ \
1240   string_temp = POP_FAILURE_POINTER ();                                 \
1241   if (string_temp != NULL)                                              \
1242     str = (const char *) string_temp;                                   \
1243                                                                         \
1244   DEBUG_PRINT2 ("  Popping string 0x%x: `", str);                       \
1245   DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2);      \
1246   DEBUG_PRINT1 ("'\n");                                                 \
1247                                                                         \
1248   pat = (unsigned char *) POP_FAILURE_POINTER ();                       \
1249   DEBUG_PRINT2 ("  Popping pattern 0x%x: ", pat);                       \
1250   DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend);                       \
1251                                                                         \
1252   /* Restore register info.  */                                         \
1253   high_reg = (unsigned) POP_FAILURE_INT ();                             \
1254   DEBUG_PRINT2 ("  Popping high active reg: %d\n", high_reg);           \
1255                                                                         \
1256   low_reg = (unsigned) POP_FAILURE_INT ();                              \
1257   DEBUG_PRINT2 ("  Popping  low active reg: %d\n", low_reg);            \
1258                                                                         \
1259   for (this_reg = high_reg; this_reg >= low_reg; this_reg--)            \
1260     {                                                                   \
1261       DEBUG_PRINT2 ("    Popping reg: %d\n", this_reg);                 \
1262                                                                         \
1263       reg_info[this_reg].word = POP_FAILURE_ELT ();                     \
1264       DEBUG_PRINT2 ("      info: 0x%x\n", reg_info[this_reg]);          \
1265                                                                         \
1266       regend[this_reg] = (const char *) POP_FAILURE_POINTER ();         \
1267       DEBUG_PRINT2 ("      end: 0x%x\n", regend[this_reg]);             \
1268                                                                         \
1269       regstart[this_reg] = (const char *) POP_FAILURE_POINTER ();       \
1270       DEBUG_PRINT2 ("      start: 0x%x\n", regstart[this_reg]);         \
1271     }                                                                   \
1272                                                                         \
1273   set_regs_matched_done = 0;                                            \
1274   DEBUG_STATEMENT (nfailure_points_popped++);                           \
1275 } /* POP_FAILURE_POINT */
1276
1277
1278 \f
1279 /* Structure for per-register (a.k.a. per-group) information.
1280    Other register information, such as the
1281    starting and ending positions (which are addresses), and the list of
1282    inner groups (which is a bits list) are maintained in separate
1283    variables.  
1284    
1285    We are making a (strictly speaking) nonportable assumption here: that
1286    the compiler will pack our bit fields into something that fits into
1287    the type of `word', i.e., is something that fits into one item on the
1288    failure stack.  */
1289
1290 typedef union
1291 {
1292   fail_stack_elt_t word;
1293   struct
1294   {
1295       /* This field is one if this group can match the empty string,
1296          zero if not.  If not yet determined,  `MATCH_NULL_UNSET_VALUE'.  */
1297 #define MATCH_NULL_UNSET_VALUE 3
1298     unsigned match_null_string_p : 2;
1299     unsigned is_active : 1;
1300     unsigned matched_something : 1;
1301     unsigned ever_matched_something : 1;
1302   } bits;
1303 } register_info_type;
1304
1305 #define REG_MATCH_NULL_STRING_P(R)  ((R).bits.match_null_string_p)
1306 #define IS_ACTIVE(R)  ((R).bits.is_active)
1307 #define MATCHED_SOMETHING(R)  ((R).bits.matched_something)
1308 #define EVER_MATCHED_SOMETHING(R)  ((R).bits.ever_matched_something)
1309
1310
1311 /* Call this when have matched a real character; it sets `matched' flags
1312    for the subexpressions which we are currently inside.  Also records
1313    that those subexprs have matched.  */
1314 #define SET_REGS_MATCHED()                                              \
1315   do                                                                    \
1316     {                                                                   \
1317       if (!set_regs_matched_done)                                       \
1318         {                                                               \
1319           unsigned r;                                                   \
1320           set_regs_matched_done = 1;                                    \
1321           for (r = lowest_active_reg; r <= highest_active_reg; r++)     \
1322             {                                                           \
1323               MATCHED_SOMETHING (reg_info[r])                           \
1324                 = EVER_MATCHED_SOMETHING (reg_info[r])                  \
1325                 = 1;                                                    \
1326             }                                                           \
1327         }                                                               \
1328     }                                                                   \
1329   while (0)
1330
1331 /* Registers are set to a sentinel when they haven't yet matched.  */
1332 static char reg_unset_dummy;
1333 #define REG_UNSET_VALUE (&reg_unset_dummy)
1334 #define REG_UNSET(e) ((e) == REG_UNSET_VALUE)
1335 \f
1336 /* Subroutine declarations and macros for regex_compile.  */
1337
1338 static void store_op1 (), store_op2 ();
1339 static void insert_op1 (), insert_op2 ();
1340 static boolean at_begline_loc_p (), at_endline_loc_p ();
1341 static boolean group_in_compile_stack ();
1342 static reg_errcode_t compile_range ();
1343
1344 /* Fetch the next character in the uncompiled pattern---translating it 
1345    if necessary.  Also cast from a signed character in the constant
1346    string passed to us by the user to an unsigned char that we can use
1347    as an array index (in, e.g., `translate').  */
1348 #define PATFETCH(c)                                                     \
1349   do {if (p == pend) return REG_EEND;                                   \
1350     c = (unsigned char) *p++;                                           \
1351     if (translate) c = translate[c];                                    \
1352   } while (0)
1353
1354 /* Fetch the next character in the uncompiled pattern, with no
1355    translation.  */
1356 #define PATFETCH_RAW(c)                                                 \
1357   do {if (p == pend) return REG_EEND;                                   \
1358     c = (unsigned char) *p++;                                           \
1359   } while (0)
1360
1361 /* Go backwards one character in the pattern.  */
1362 #define PATUNFETCH p--
1363
1364
1365 /* If `translate' is non-null, return translate[D], else just D.  We
1366    cast the subscript to translate because some data is declared as
1367    `char *', to avoid warnings when a string constant is passed.  But
1368    when we use a character as a subscript we must make it unsigned.  */
1369 #define TRANSLATE(d) (translate ? translate[(unsigned char) (d)] : (d))
1370
1371
1372 /* Macros for outputting the compiled pattern into `buffer'.  */
1373
1374 /* If the buffer isn't allocated when it comes in, use this.  */
1375 #define INIT_BUF_SIZE  32
1376
1377 /* Make sure we have at least N more bytes of space in buffer.  */
1378 #define GET_BUFFER_SPACE(n)                                             \
1379     while (b - bufp->buffer + (n) > bufp->allocated)                    \
1380       EXTEND_BUFFER ()
1381
1382 /* Make sure we have one more byte of buffer space and then add C to it.  */
1383 #define BUF_PUSH(c)                                                     \
1384   do {                                                                  \
1385     GET_BUFFER_SPACE (1);                                               \
1386     *b++ = (unsigned char) (c);                                         \
1387   } while (0)
1388
1389
1390 /* Ensure we have two more bytes of buffer space and then append C1 and C2.  */
1391 #define BUF_PUSH_2(c1, c2)                                              \
1392   do {                                                                  \
1393     GET_BUFFER_SPACE (2);                                               \
1394     *b++ = (unsigned char) (c1);                                        \
1395     *b++ = (unsigned char) (c2);                                        \
1396   } while (0)
1397
1398
1399 /* As with BUF_PUSH_2, except for three bytes.  */
1400 #define BUF_PUSH_3(c1, c2, c3)                                          \
1401   do {                                                                  \
1402     GET_BUFFER_SPACE (3);                                               \
1403     *b++ = (unsigned char) (c1);                                        \
1404     *b++ = (unsigned char) (c2);                                        \
1405     *b++ = (unsigned char) (c3);                                        \
1406   } while (0)
1407
1408
1409 /* Store a jump with opcode OP at LOC to location TO.  We store a
1410    relative address offset by the three bytes the jump itself occupies.  */
1411 #define STORE_JUMP(op, loc, to) \
1412   store_op1 (op, loc, (to) - (loc) - 3)
1413
1414 /* Likewise, for a two-argument jump.  */
1415 #define STORE_JUMP2(op, loc, to, arg) \
1416   store_op2 (op, loc, (to) - (loc) - 3, arg)
1417
1418 /* Like `STORE_JUMP', but for inserting.  Assume `b' is the buffer end.  */
1419 #define INSERT_JUMP(op, loc, to) \
1420   insert_op1 (op, loc, (to) - (loc) - 3, b)
1421
1422 /* Like `STORE_JUMP2', but for inserting.  Assume `b' is the buffer end.  */
1423 #define INSERT_JUMP2(op, loc, to, arg) \
1424   insert_op2 (op, loc, (to) - (loc) - 3, arg, b)
1425
1426
1427 /* This is not an arbitrary limit: the arguments which represent offsets
1428    into the pattern are two bytes long.  So if 2^16 bytes turns out to
1429    be too small, many things would have to change.  */
1430 #define MAX_BUF_SIZE (1L << 16)
1431
1432
1433 /* Extend the buffer by twice its current size via realloc and
1434    reset the pointers that pointed into the old block to point to the
1435    correct places in the new one.  If extending the buffer results in it
1436    being larger than MAX_BUF_SIZE, then flag memory exhausted.  */
1437 #define EXTEND_BUFFER()                                                 \
1438   do {                                                                  \
1439     unsigned char *old_buffer = bufp->buffer;                           \
1440     if (bufp->allocated == MAX_BUF_SIZE)                                \
1441       return REG_ESIZE;                                                 \
1442     bufp->allocated <<= 1;                                              \
1443     if (bufp->allocated > MAX_BUF_SIZE)                                 \
1444       bufp->allocated = MAX_BUF_SIZE;                                   \
1445     bufp->buffer = (unsigned char *) realloc (bufp->buffer, bufp->allocated);\
1446     if (bufp->buffer == NULL)                                           \
1447       return REG_ESPACE;                                                \
1448     /* If the buffer moved, move all the pointers into it.  */          \
1449     if (old_buffer != bufp->buffer)                                     \
1450       {                                                                 \
1451         b = (b - old_buffer) + bufp->buffer;                            \
1452         begalt = (begalt - old_buffer) + bufp->buffer;                  \
1453         if (fixup_alt_jump)                                             \
1454           fixup_alt_jump = (fixup_alt_jump - old_buffer) + bufp->buffer;\
1455         if (laststart)                                                  \
1456           laststart = (laststart - old_buffer) + bufp->buffer;          \
1457         if (pending_exact)                                              \
1458           pending_exact = (pending_exact - old_buffer) + bufp->buffer;  \
1459       }                                                                 \
1460   } while (0)
1461
1462
1463 /* Since we have one byte reserved for the register number argument to
1464    {start,stop}_memory, the maximum number of groups we can report
1465    things about is what fits in that byte.  */
1466 #define MAX_REGNUM 255
1467
1468 /* But patterns can have more than `MAX_REGNUM' registers.  We just
1469    ignore the excess.  */
1470 typedef unsigned regnum_t;
1471
1472
1473 /* Macros for the compile stack.  */
1474
1475 /* Since offsets can go either forwards or backwards, this type needs to
1476    be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1.  */
1477 typedef int pattern_offset_t;
1478
1479 typedef struct
1480 {
1481   pattern_offset_t begalt_offset;
1482   pattern_offset_t fixup_alt_jump;
1483   pattern_offset_t inner_group_offset;
1484   pattern_offset_t laststart_offset;  
1485   regnum_t regnum;
1486 } compile_stack_elt_t;
1487
1488
1489 typedef struct
1490 {
1491   compile_stack_elt_t *stack;
1492   unsigned size;
1493   unsigned avail;                       /* Offset of next open position.  */
1494 } compile_stack_type;
1495
1496
1497 #define INIT_COMPILE_STACK_SIZE 32
1498
1499 #define COMPILE_STACK_EMPTY  (compile_stack.avail == 0)
1500 #define COMPILE_STACK_FULL  (compile_stack.avail == compile_stack.size)
1501
1502 /* The next available element.  */
1503 #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
1504
1505
1506 /* Set the bit for character C in a list.  */
1507 #define SET_LIST_BIT(c)                               \
1508   (b[((unsigned char) (c)) / BYTEWIDTH]               \
1509    |= 1 << (((unsigned char) c) % BYTEWIDTH))
1510
1511
1512 /* Get the next unsigned number in the uncompiled pattern.  */
1513 #define GET_UNSIGNED_NUMBER(num)                                        \
1514   { if (p != pend)                                                      \
1515      {                                                                  \
1516        PATFETCH (c);                                                    \
1517        while (ISDIGIT (c))                                              \
1518          {                                                              \
1519            if (num < 0)                                                 \
1520               num = 0;                                                  \
1521            num = num * 10 + c - '0';                                    \
1522            if (p == pend)                                               \
1523               break;                                                    \
1524            PATFETCH (c);                                                \
1525          }                                                              \
1526        }                                                                \
1527     }           
1528
1529 #define CHAR_CLASS_MAX_LENGTH  6 /* Namely, `xdigit'.  */
1530
1531 #define IS_CHAR_CLASS(string)                                           \
1532    (STREQ (string, "alpha") || STREQ (string, "upper")                  \
1533     || STREQ (string, "lower") || STREQ (string, "digit")               \
1534     || STREQ (string, "alnum") || STREQ (string, "xdigit")              \
1535     || STREQ (string, "space") || STREQ (string, "print")               \
1536     || STREQ (string, "punct") || STREQ (string, "graph")               \
1537     || STREQ (string, "cntrl") || STREQ (string, "blank"))
1538 \f
1539 #ifndef MATCH_MAY_ALLOCATE
1540
1541 /* If we cannot allocate large objects within re_match_2_internal,
1542    we make the fail stack and register vectors global.
1543    The fail stack, we grow to the maximum size when a regexp
1544    is compiled.
1545    The register vectors, we adjust in size each time we
1546    compile a regexp, according to the number of registers it needs.  */
1547
1548 static fail_stack_type fail_stack;
1549
1550 /* Size with which the following vectors are currently allocated.
1551    That is so we can make them bigger as needed,
1552    but never make them smaller.  */
1553 static int regs_allocated_size;
1554
1555 static const char **     regstart, **     regend;
1556 static const char ** old_regstart, ** old_regend;
1557 static const char **best_regstart, **best_regend;
1558 static register_info_type *reg_info; 
1559 static const char **reg_dummy;
1560 static register_info_type *reg_info_dummy;
1561
1562 /* Make the register vectors big enough for NUM_REGS registers,
1563    but don't make them smaller.  */
1564
1565 static
1566 regex_grow_registers (num_regs)
1567      int num_regs;
1568 {
1569   if (num_regs > regs_allocated_size)
1570     {
1571       RETALLOC_IF (regstart,     num_regs, const char *);
1572       RETALLOC_IF (regend,       num_regs, const char *);
1573       RETALLOC_IF (old_regstart, num_regs, const char *);
1574       RETALLOC_IF (old_regend,   num_regs, const char *);
1575       RETALLOC_IF (best_regstart, num_regs, const char *);
1576       RETALLOC_IF (best_regend,  num_regs, const char *);
1577       RETALLOC_IF (reg_info,     num_regs, register_info_type);
1578       RETALLOC_IF (reg_dummy,    num_regs, const char *);
1579       RETALLOC_IF (reg_info_dummy, num_regs, register_info_type);
1580
1581       regs_allocated_size = num_regs;
1582     }
1583 }
1584
1585 #endif /* not MATCH_MAY_ALLOCATE */
1586 \f
1587 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
1588    Returns one of error codes defined in `regex.h', or zero for success.
1589
1590    Assumes the `allocated' (and perhaps `buffer') and `translate'
1591    fields are set in BUFP on entry.
1592
1593    If it succeeds, results are put in BUFP (if it returns an error, the
1594    contents of BUFP are undefined):
1595      `buffer' is the compiled pattern;
1596      `syntax' is set to SYNTAX;
1597      `used' is set to the length of the compiled pattern;
1598      `fastmap_accurate' is zero;
1599      `re_nsub' is the number of subexpressions in PATTERN;
1600      `not_bol' and `not_eol' are zero;
1601    
1602    The `fastmap' and `newline_anchor' fields are neither
1603    examined nor set.  */
1604
1605 /* Return, freeing storage we allocated.  */
1606 #define FREE_STACK_RETURN(value)                \
1607   return (free (compile_stack.stack), value)
1608
1609 static reg_errcode_t
1610 regex_compile (pattern, size, syntax, bufp)
1611      const char *pattern;
1612      int size;
1613      reg_syntax_t syntax;
1614      struct re_pattern_buffer *bufp;
1615 {
1616   /* We fetch characters from PATTERN here.  Even though PATTERN is
1617      `char *' (i.e., signed), we declare these variables as unsigned, so
1618      they can be reliably used as array indices.  */
1619   register unsigned char c, c1;
1620   
1621   /* A random temporary spot in PATTERN.  */
1622   const char *p1;
1623
1624   /* Points to the end of the buffer, where we should append.  */
1625   register unsigned char *b;
1626   
1627   /* Keeps track of unclosed groups.  */
1628   compile_stack_type compile_stack;
1629
1630   /* Points to the current (ending) position in the pattern.  */
1631   const char *p = pattern;
1632   const char *pend = pattern + size;
1633   
1634   /* How to translate the characters in the pattern.  */
1635   char *translate = bufp->translate;
1636
1637   /* Address of the count-byte of the most recently inserted `exactn'
1638      command.  This makes it possible to tell if a new exact-match
1639      character can be added to that command or if the character requires
1640      a new `exactn' command.  */
1641   unsigned char *pending_exact = 0;
1642
1643   /* Address of start of the most recently finished expression.
1644      This tells, e.g., postfix * where to find the start of its
1645      operand.  Reset at the beginning of groups and alternatives.  */
1646   unsigned char *laststart = 0;
1647
1648   /* Address of beginning of regexp, or inside of last group.  */
1649   unsigned char *begalt;
1650
1651   /* Place in the uncompiled pattern (i.e., the {) to
1652      which to go back if the interval is invalid.  */
1653   const char *beg_interval;
1654                 
1655   /* Address of the place where a forward jump should go to the end of
1656      the containing expression.  Each alternative of an `or' -- except the
1657      last -- ends with a forward jump of this sort.  */
1658   unsigned char *fixup_alt_jump = 0;
1659
1660   /* Counts open-groups as they are encountered.  Remembered for the
1661      matching close-group on the compile stack, so the same register
1662      number is put in the stop_memory as the start_memory.  */
1663   regnum_t regnum = 0;
1664
1665 #ifdef DEBUG
1666   DEBUG_PRINT1 ("\nCompiling pattern: ");
1667   if (debug)
1668     {
1669       unsigned debug_count;
1670       
1671       for (debug_count = 0; debug_count < size; debug_count++)
1672         putchar (pattern[debug_count]);
1673       putchar ('\n');
1674     }
1675 #endif /* DEBUG */
1676
1677   /* Initialize the compile stack.  */
1678   compile_stack.stack = TALLOC (INIT_COMPILE_STACK_SIZE, compile_stack_elt_t);
1679   if (compile_stack.stack == NULL)
1680     return REG_ESPACE;
1681
1682   compile_stack.size = INIT_COMPILE_STACK_SIZE;
1683   compile_stack.avail = 0;
1684
1685   /* Initialize the pattern buffer.  */
1686   bufp->syntax = syntax;
1687   bufp->fastmap_accurate = 0;
1688   bufp->not_bol = bufp->not_eol = 0;
1689
1690   /* Set `used' to zero, so that if we return an error, the pattern
1691      printer (for debugging) will think there's no pattern.  We reset it
1692      at the end.  */
1693   bufp->used = 0;
1694   
1695   /* Always count groups, whether or not bufp->no_sub is set.  */
1696   bufp->re_nsub = 0;                            
1697
1698 #if !defined (emacs) && !defined (SYNTAX_TABLE)
1699   /* Initialize the syntax table.  */
1700    init_syntax_once ();
1701 #endif
1702
1703   if (bufp->allocated == 0)
1704     {
1705       if (bufp->buffer)
1706         { /* If zero allocated, but buffer is non-null, try to realloc
1707              enough space.  This loses if buffer's address is bogus, but
1708              that is the user's responsibility.  */
1709           RETALLOC (bufp->buffer, INIT_BUF_SIZE, unsigned char);
1710         }
1711       else
1712         { /* Caller did not allocate a buffer.  Do it for them.  */
1713           bufp->buffer = TALLOC (INIT_BUF_SIZE, unsigned char);
1714         }
1715       if (!bufp->buffer) FREE_STACK_RETURN (REG_ESPACE);
1716
1717       bufp->allocated = INIT_BUF_SIZE;
1718     }
1719
1720   begalt = b = bufp->buffer;
1721
1722   /* Loop through the uncompiled pattern until we're at the end.  */
1723   while (p != pend)
1724     {
1725       PATFETCH (c);
1726
1727       switch (c)
1728         {
1729         case '^':
1730           {
1731             if (   /* If at start of pattern, it's an operator.  */
1732                    p == pattern + 1
1733                    /* If context independent, it's an operator.  */
1734                 || syntax & RE_CONTEXT_INDEP_ANCHORS
1735                    /* Otherwise, depends on what's come before.  */
1736                 || at_begline_loc_p (pattern, p, syntax))
1737               BUF_PUSH (begline);
1738             else
1739               goto normal_char;
1740           }
1741           break;
1742
1743
1744         case '$':
1745           {
1746             if (   /* If at end of pattern, it's an operator.  */
1747                    p == pend 
1748                    /* If context independent, it's an operator.  */
1749                 || syntax & RE_CONTEXT_INDEP_ANCHORS
1750                    /* Otherwise, depends on what's next.  */
1751                 || at_endline_loc_p (p, pend, syntax))
1752                BUF_PUSH (endline);
1753              else
1754                goto normal_char;
1755            }
1756            break;
1757
1758
1759         case '+':
1760         case '?':
1761           if ((syntax & RE_BK_PLUS_QM)
1762               || (syntax & RE_LIMITED_OPS))
1763             goto normal_char;
1764         handle_plus:
1765         case '*':
1766           /* If there is no previous pattern... */
1767           if (!laststart)
1768             {
1769               if (syntax & RE_CONTEXT_INVALID_OPS)
1770                 FREE_STACK_RETURN (REG_BADRPT);
1771               else if (!(syntax & RE_CONTEXT_INDEP_OPS))
1772                 goto normal_char;
1773             }
1774
1775           {
1776             /* Are we optimizing this jump?  */
1777             boolean keep_string_p = false;
1778             
1779             /* 1 means zero (many) matches is allowed.  */
1780             char zero_times_ok = 0, many_times_ok = 0;
1781
1782             /* If there is a sequence of repetition chars, collapse it
1783                down to just one (the right one).  We can't combine
1784                interval operators with these because of, e.g., `a{2}*',
1785                which should only match an even number of `a's.  */
1786
1787             for (;;)
1788               {
1789                 zero_times_ok |= c != '+';
1790                 many_times_ok |= c != '?';
1791
1792                 if (p == pend)
1793                   break;
1794
1795                 PATFETCH (c);
1796
1797                 if (c == '*'
1798                     || (!(syntax & RE_BK_PLUS_QM) && (c == '+' || c == '?')))
1799                   ;
1800
1801                 else if (syntax & RE_BK_PLUS_QM  &&  c == '\\')
1802                   {
1803                     if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
1804
1805                     PATFETCH (c1);
1806                     if (!(c1 == '+' || c1 == '?'))
1807                       {
1808                         PATUNFETCH;
1809                         PATUNFETCH;
1810                         break;
1811                       }
1812
1813                     c = c1;
1814                   }
1815                 else
1816                   {
1817                     PATUNFETCH;
1818                     break;
1819                   }
1820
1821                 /* If we get here, we found another repeat character.  */
1822                }
1823
1824             /* Star, etc. applied to an empty pattern is equivalent
1825                to an empty pattern.  */
1826             if (!laststart)  
1827               break;
1828
1829             /* Now we know whether or not zero matches is allowed
1830                and also whether or not two or more matches is allowed.  */
1831             if (many_times_ok)
1832               { /* More than one repetition is allowed, so put in at the
1833                    end a backward relative jump from `b' to before the next
1834                    jump we're going to put in below (which jumps from
1835                    laststart to after this jump).  
1836
1837                    But if we are at the `*' in the exact sequence `.*\n',
1838                    insert an unconditional jump backwards to the .,
1839                    instead of the beginning of the loop.  This way we only
1840                    push a failure point once, instead of every time
1841                    through the loop.  */
1842                 assert (p - 1 > pattern);
1843
1844                 /* Allocate the space for the jump.  */
1845                 GET_BUFFER_SPACE (3);
1846
1847                 /* We know we are not at the first character of the pattern,
1848                    because laststart was nonzero.  And we've already
1849                    incremented `p', by the way, to be the character after
1850                    the `*'.  Do we have to do something analogous here
1851                    for null bytes, because of RE_DOT_NOT_NULL?  */
1852                 if (TRANSLATE (*(p - 2)) == TRANSLATE ('.')
1853                     && zero_times_ok
1854                     && p < pend && TRANSLATE (*p) == TRANSLATE ('\n')
1855                     && !(syntax & RE_DOT_NEWLINE))
1856                   { /* We have .*\n.  */
1857                     STORE_JUMP (jump, b, laststart);
1858                     keep_string_p = true;
1859                   }
1860                 else
1861                   /* Anything else.  */
1862                   STORE_JUMP (maybe_pop_jump, b, laststart - 3);
1863
1864                 /* We've added more stuff to the buffer.  */
1865                 b += 3;
1866               }
1867
1868             /* On failure, jump from laststart to b + 3, which will be the
1869                end of the buffer after this jump is inserted.  */
1870             GET_BUFFER_SPACE (3);
1871             INSERT_JUMP (keep_string_p ? on_failure_keep_string_jump
1872                                        : on_failure_jump,
1873                          laststart, b + 3);
1874             pending_exact = 0;
1875             b += 3;
1876
1877             if (!zero_times_ok)
1878               {
1879                 /* At least one repetition is required, so insert a
1880                    `dummy_failure_jump' before the initial
1881                    `on_failure_jump' instruction of the loop. This
1882                    effects a skip over that instruction the first time
1883                    we hit that loop.  */
1884                 GET_BUFFER_SPACE (3);
1885                 INSERT_JUMP (dummy_failure_jump, laststart, laststart + 6);
1886                 b += 3;
1887               }
1888             }
1889           break;
1890
1891
1892         case '.':
1893           laststart = b;
1894           BUF_PUSH (anychar);
1895           break;
1896
1897
1898         case '[':
1899           {
1900             boolean had_char_class = false;
1901
1902             if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
1903
1904             /* Ensure that we have enough space to push a charset: the
1905                opcode, the length count, and the bitset; 34 bytes in all.  */
1906             GET_BUFFER_SPACE (34);
1907
1908             laststart = b;
1909
1910             /* We test `*p == '^' twice, instead of using an if
1911                statement, so we only need one BUF_PUSH.  */
1912             BUF_PUSH (*p == '^' ? charset_not : charset); 
1913             if (*p == '^')
1914               p++;
1915
1916             /* Remember the first position in the bracket expression.  */
1917             p1 = p;
1918
1919             /* Push the number of bytes in the bitmap.  */
1920             BUF_PUSH ((1 << BYTEWIDTH) / BYTEWIDTH);
1921
1922             /* Clear the whole map.  */
1923             bzero (b, (1 << BYTEWIDTH) / BYTEWIDTH);
1924
1925             /* charset_not matches newline according to a syntax bit.  */
1926             if ((re_opcode_t) b[-2] == charset_not
1927                 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
1928               SET_LIST_BIT ('\n');
1929
1930             /* Read in characters and ranges, setting map bits.  */
1931             for (;;)
1932               {
1933                 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
1934
1935                 PATFETCH (c);
1936
1937                 /* \ might escape characters inside [...] and [^...].  */
1938                 if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
1939                   {
1940                     if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
1941
1942                     PATFETCH (c1);
1943                     SET_LIST_BIT (c1);
1944                     continue;
1945                   }
1946
1947                 /* Could be the end of the bracket expression.  If it's
1948                    not (i.e., when the bracket expression is `[]' so
1949                    far), the ']' character bit gets set way below.  */
1950                 if (c == ']' && p != p1 + 1)
1951                   break;
1952
1953                 /* Look ahead to see if it's a range when the last thing
1954                    was a character class.  */
1955                 if (had_char_class && c == '-' && *p != ']')
1956                   FREE_STACK_RETURN (REG_ERANGE);
1957
1958                 /* Look ahead to see if it's a range when the last thing
1959                    was a character: if this is a hyphen not at the
1960                    beginning or the end of a list, then it's the range
1961                    operator.  */
1962                 if (c == '-' 
1963                     && !(p - 2 >= pattern && p[-2] == '[') 
1964                     && !(p - 3 >= pattern && p[-3] == '[' && p[-2] == '^')
1965                     && *p != ']')
1966                   {
1967                     reg_errcode_t ret
1968                       = compile_range (&p, pend, translate, syntax, b);
1969                     if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
1970                   }
1971
1972                 else if (p[0] == '-' && p[1] != ']')
1973                   { /* This handles ranges made up of characters only.  */
1974                     reg_errcode_t ret;
1975
1976                     /* Move past the `-'.  */
1977                     PATFETCH (c1);
1978                     
1979                     ret = compile_range (&p, pend, translate, syntax, b);
1980                     if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
1981                   }
1982
1983                 /* See if we're at the beginning of a possible character
1984                    class.  */
1985
1986                 else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == ':')
1987                   { /* Leave room for the null.  */
1988                     char str[CHAR_CLASS_MAX_LENGTH + 1];
1989
1990                     PATFETCH (c);
1991                     c1 = 0;
1992
1993                     /* If pattern is `[[:'.  */
1994                     if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
1995
1996                     for (;;)
1997                       {
1998                         PATFETCH (c);
1999                         if (c == ':' || c == ']' || p == pend
2000                             || c1 == CHAR_CLASS_MAX_LENGTH)
2001                           break;
2002                         str[c1++] = c;
2003                       }
2004                     str[c1] = '\0';
2005
2006                     /* If isn't a word bracketed by `[:' and:`]':
2007                        undo the ending character, the letters, and leave 
2008                        the leading `:' and `[' (but set bits for them).  */
2009                     if (c == ':' && *p == ']')
2010                       {
2011                         int ch;
2012                         boolean is_alnum = STREQ (str, "alnum");
2013                         boolean is_alpha = STREQ (str, "alpha");
2014                         boolean is_blank = STREQ (str, "blank");
2015                         boolean is_cntrl = STREQ (str, "cntrl");
2016                         boolean is_digit = STREQ (str, "digit");
2017                         boolean is_graph = STREQ (str, "graph");
2018                         boolean is_lower = STREQ (str, "lower");
2019                         boolean is_print = STREQ (str, "print");
2020                         boolean is_punct = STREQ (str, "punct");
2021                         boolean is_space = STREQ (str, "space");
2022                         boolean is_upper = STREQ (str, "upper");
2023                         boolean is_xdigit = STREQ (str, "xdigit");
2024                         
2025                         if (!IS_CHAR_CLASS (str))
2026                           FREE_STACK_RETURN (REG_ECTYPE);
2027
2028                         /* Throw away the ] at the end of the character
2029                            class.  */
2030                         PATFETCH (c);                                   
2031
2032                         if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2033
2034                         for (ch = 0; ch < 1 << BYTEWIDTH; ch++)
2035                           {
2036                             /* This was split into 3 if's to
2037                                avoid an arbitrary limit in some compiler.  */
2038                             if (   (is_alnum  && ISALNUM (ch))
2039                                 || (is_alpha  && ISALPHA (ch))
2040                                 || (is_blank  && ISBLANK (ch))
2041                                 || (is_cntrl  && ISCNTRL (ch)))
2042                               SET_LIST_BIT (ch);
2043                             if (   (is_digit  && ISDIGIT (ch))
2044                                 || (is_graph  && ISGRAPH (ch))
2045                                 || (is_lower  && ISLOWER (ch))
2046                                 || (is_print  && ISPRINT (ch)))
2047                               SET_LIST_BIT (ch);
2048                             if (   (is_punct  && ISPUNCT (ch))
2049                                 || (is_space  && ISSPACE (ch))
2050                                 || (is_upper  && ISUPPER (ch))
2051                                 || (is_xdigit && ISXDIGIT (ch)))
2052                               SET_LIST_BIT (ch);
2053                           }
2054                         had_char_class = true;
2055                       }
2056                     else
2057                       {
2058                         c1++;
2059                         while (c1--)    
2060                           PATUNFETCH;
2061                         SET_LIST_BIT ('[');
2062                         SET_LIST_BIT (':');
2063                         had_char_class = false;
2064                       }
2065                   }
2066                 else
2067                   {
2068                     had_char_class = false;
2069                     SET_LIST_BIT (c);
2070                   }
2071               }
2072
2073             /* Discard any (non)matching list bytes that are all 0 at the
2074                end of the map.  Decrease the map-length byte too.  */
2075             while ((int) b[-1] > 0 && b[b[-1] - 1] == 0) 
2076               b[-1]--; 
2077             b += b[-1];
2078           }
2079           break;
2080
2081
2082         case '(':
2083           if (syntax & RE_NO_BK_PARENS)
2084             goto handle_open;
2085           else
2086             goto normal_char;
2087
2088
2089         case ')':
2090           if (syntax & RE_NO_BK_PARENS)
2091             goto handle_close;
2092           else
2093             goto normal_char;
2094
2095
2096         case '\n':
2097           if (syntax & RE_NEWLINE_ALT)
2098             goto handle_alt;
2099           else
2100             goto normal_char;
2101
2102
2103         case '|':
2104           if (syntax & RE_NO_BK_VBAR)
2105             goto handle_alt;
2106           else
2107             goto normal_char;
2108
2109
2110         case '{':
2111            if (syntax & RE_INTERVALS && syntax & RE_NO_BK_BRACES)
2112              goto handle_interval;
2113            else
2114              goto normal_char;
2115
2116
2117         case '\\':
2118           if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2119
2120           /* Do not translate the character after the \, so that we can
2121              distinguish, e.g., \B from \b, even if we normally would
2122              translate, e.g., B to b.  */
2123           PATFETCH_RAW (c);
2124
2125           switch (c)
2126             {
2127             case '(':
2128               if (syntax & RE_NO_BK_PARENS)
2129                 goto normal_backslash;
2130
2131             handle_open:
2132               bufp->re_nsub++;
2133               regnum++;
2134
2135               if (COMPILE_STACK_FULL)
2136                 { 
2137                   RETALLOC (compile_stack.stack, compile_stack.size << 1,
2138                             compile_stack_elt_t);
2139                   if (compile_stack.stack == NULL) return REG_ESPACE;
2140
2141                   compile_stack.size <<= 1;
2142                 }
2143
2144               /* These are the values to restore when we hit end of this
2145                  group.  They are all relative offsets, so that if the
2146                  whole pattern moves because of realloc, they will still
2147                  be valid.  */
2148               COMPILE_STACK_TOP.begalt_offset = begalt - bufp->buffer;
2149               COMPILE_STACK_TOP.fixup_alt_jump 
2150                 = fixup_alt_jump ? fixup_alt_jump - bufp->buffer + 1 : 0;
2151               COMPILE_STACK_TOP.laststart_offset = b - bufp->buffer;
2152               COMPILE_STACK_TOP.regnum = regnum;
2153
2154               /* We will eventually replace the 0 with the number of
2155                  groups inner to this one.  But do not push a
2156                  start_memory for groups beyond the last one we can
2157                  represent in the compiled pattern.  */
2158               if (regnum <= MAX_REGNUM)
2159                 {
2160                   COMPILE_STACK_TOP.inner_group_offset = b - bufp->buffer + 2;
2161                   BUF_PUSH_3 (start_memory, regnum, 0);
2162                 }
2163                 
2164               compile_stack.avail++;
2165
2166               fixup_alt_jump = 0;
2167               laststart = 0;
2168               begalt = b;
2169               /* If we've reached MAX_REGNUM groups, then this open
2170                  won't actually generate any code, so we'll have to
2171                  clear pending_exact explicitly.  */
2172               pending_exact = 0;
2173               break;
2174
2175
2176             case ')':
2177               if (syntax & RE_NO_BK_PARENS) goto normal_backslash;
2178
2179               if (COMPILE_STACK_EMPTY)
2180                 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
2181                   goto normal_backslash;
2182                 else
2183                   FREE_STACK_RETURN (REG_ERPAREN);
2184
2185             handle_close:
2186               if (fixup_alt_jump)
2187                 { /* Push a dummy failure point at the end of the
2188                      alternative for a possible future
2189                      `pop_failure_jump' to pop.  See comments at
2190                      `push_dummy_failure' in `re_match_2'.  */
2191                   BUF_PUSH (push_dummy_failure);
2192                   
2193                   /* We allocated space for this jump when we assigned
2194                      to `fixup_alt_jump', in the `handle_alt' case below.  */
2195                   STORE_JUMP (jump_past_alt, fixup_alt_jump, b - 1);
2196                 }
2197
2198               /* See similar code for backslashed left paren above.  */
2199               if (COMPILE_STACK_EMPTY)
2200                 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
2201                   goto normal_char;
2202                 else
2203                   FREE_STACK_RETURN (REG_ERPAREN);
2204
2205               /* Since we just checked for an empty stack above, this
2206                  ``can't happen''.  */
2207               assert (compile_stack.avail != 0);
2208               {
2209                 /* We don't just want to restore into `regnum', because
2210                    later groups should continue to be numbered higher,
2211                    as in `(ab)c(de)' -- the second group is #2.  */
2212                 regnum_t this_group_regnum;
2213
2214                 compile_stack.avail--;          
2215                 begalt = bufp->buffer + COMPILE_STACK_TOP.begalt_offset;
2216                 fixup_alt_jump
2217                   = COMPILE_STACK_TOP.fixup_alt_jump
2218                     ? bufp->buffer + COMPILE_STACK_TOP.fixup_alt_jump - 1 
2219                     : 0;
2220                 laststart = bufp->buffer + COMPILE_STACK_TOP.laststart_offset;
2221                 this_group_regnum = COMPILE_STACK_TOP.regnum;
2222                 /* If we've reached MAX_REGNUM groups, then this open
2223                    won't actually generate any code, so we'll have to
2224                    clear pending_exact explicitly.  */
2225                 pending_exact = 0;
2226
2227                 /* We're at the end of the group, so now we know how many
2228                    groups were inside this one.  */
2229                 if (this_group_regnum <= MAX_REGNUM)
2230                   {
2231                     unsigned char *inner_group_loc
2232                       = bufp->buffer + COMPILE_STACK_TOP.inner_group_offset;
2233                     
2234                     *inner_group_loc = regnum - this_group_regnum;
2235                     BUF_PUSH_3 (stop_memory, this_group_regnum,
2236                                 regnum - this_group_regnum);
2237                   }
2238               }
2239               break;
2240
2241
2242             case '|':                                   /* `\|'.  */
2243               if (syntax & RE_LIMITED_OPS || syntax & RE_NO_BK_VBAR)
2244                 goto normal_backslash;
2245             handle_alt:
2246               if (syntax & RE_LIMITED_OPS)
2247                 goto normal_char;
2248
2249               /* Insert before the previous alternative a jump which
2250                  jumps to this alternative if the former fails.  */
2251               GET_BUFFER_SPACE (3);
2252               INSERT_JUMP (on_failure_jump, begalt, b + 6);
2253               pending_exact = 0;
2254               b += 3;
2255
2256               /* The alternative before this one has a jump after it
2257                  which gets executed if it gets matched.  Adjust that
2258                  jump so it will jump to this alternative's analogous
2259                  jump (put in below, which in turn will jump to the next
2260                  (if any) alternative's such jump, etc.).  The last such
2261                  jump jumps to the correct final destination.  A picture:
2262                           _____ _____ 
2263                           |   | |   |   
2264                           |   v |   v 
2265                          a | b   | c   
2266
2267                  If we are at `b', then fixup_alt_jump right now points to a
2268                  three-byte space after `a'.  We'll put in the jump, set
2269                  fixup_alt_jump to right after `b', and leave behind three
2270                  bytes which we'll fill in when we get to after `c'.  */
2271
2272               if (fixup_alt_jump)
2273                 STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
2274
2275               /* Mark and leave space for a jump after this alternative,
2276                  to be filled in later either by next alternative or
2277                  when know we're at the end of a series of alternatives.  */
2278               fixup_alt_jump = b;
2279               GET_BUFFER_SPACE (3);
2280               b += 3;
2281
2282               laststart = 0;
2283               begalt = b;
2284               break;
2285
2286
2287             case '{': 
2288               /* If \{ is a literal.  */
2289               if (!(syntax & RE_INTERVALS)
2290                      /* If we're at `\{' and it's not the open-interval 
2291                         operator.  */
2292                   || ((syntax & RE_INTERVALS) && (syntax & RE_NO_BK_BRACES))
2293                   || (p - 2 == pattern  &&  p == pend))
2294                 goto normal_backslash;
2295
2296             handle_interval:
2297               {
2298                 /* If got here, then the syntax allows intervals.  */
2299
2300                 /* At least (most) this many matches must be made.  */
2301                 int lower_bound = -1, upper_bound = -1;
2302
2303                 beg_interval = p - 1;
2304
2305                 if (p == pend)
2306                   {
2307                     if (syntax & RE_NO_BK_BRACES)
2308                       goto unfetch_interval;
2309                     else
2310                       FREE_STACK_RETURN (REG_EBRACE);
2311                   }
2312
2313                 GET_UNSIGNED_NUMBER (lower_bound);
2314
2315                 if (c == ',')
2316                   {
2317                     GET_UNSIGNED_NUMBER (upper_bound);
2318                     if (upper_bound < 0) upper_bound = RE_DUP_MAX;
2319                   }
2320                 else
2321                   /* Interval such as `{1}' => match exactly once. */
2322                   upper_bound = lower_bound;
2323
2324                 if (lower_bound < 0 || upper_bound > RE_DUP_MAX
2325                     || lower_bound > upper_bound)
2326                   {
2327                     if (syntax & RE_NO_BK_BRACES)
2328                       goto unfetch_interval;
2329                     else 
2330                       FREE_STACK_RETURN (REG_BADBR);
2331                   }
2332
2333                 if (!(syntax & RE_NO_BK_BRACES)) 
2334                   {
2335                     if (c != '\\') FREE_STACK_RETURN (REG_EBRACE);
2336
2337                     PATFETCH (c);
2338                   }
2339
2340                 if (c != '}')
2341                   {
2342                     if (syntax & RE_NO_BK_BRACES)
2343                       goto unfetch_interval;
2344                     else 
2345                       FREE_STACK_RETURN (REG_BADBR);
2346                   }
2347
2348                 /* We just parsed a valid interval.  */
2349
2350                 /* If it's invalid to have no preceding re.  */
2351                 if (!laststart)
2352                   {
2353                     if (syntax & RE_CONTEXT_INVALID_OPS)
2354                       FREE_STACK_RETURN (REG_BADRPT);
2355                     else if (syntax & RE_CONTEXT_INDEP_OPS)
2356                       laststart = b;
2357                     else
2358                       goto unfetch_interval;
2359                   }
2360
2361                 /* If the upper bound is zero, don't want to succeed at
2362                    all; jump from `laststart' to `b + 3', which will be
2363                    the end of the buffer after we insert the jump.  */
2364                  if (upper_bound == 0)
2365                    {
2366                      GET_BUFFER_SPACE (3);
2367                      INSERT_JUMP (jump, laststart, b + 3);
2368                      b += 3;
2369                    }
2370
2371                  /* Otherwise, we have a nontrivial interval.  When
2372                     we're all done, the pattern will look like:
2373                       set_number_at <jump count> <upper bound>
2374                       set_number_at <succeed_n count> <lower bound>
2375                       succeed_n <after jump addr> <succeed_n count>
2376                       <body of loop>
2377                       jump_n <succeed_n addr> <jump count>
2378                     (The upper bound and `jump_n' are omitted if
2379                     `upper_bound' is 1, though.)  */
2380                  else 
2381                    { /* If the upper bound is > 1, we need to insert
2382                         more at the end of the loop.  */
2383                      unsigned nbytes = 10 + (upper_bound > 1) * 10;
2384
2385                      GET_BUFFER_SPACE (nbytes);
2386
2387                      /* Initialize lower bound of the `succeed_n', even
2388                         though it will be set during matching by its
2389                         attendant `set_number_at' (inserted next),
2390                         because `re_compile_fastmap' needs to know.
2391                         Jump to the `jump_n' we might insert below.  */
2392                      INSERT_JUMP2 (succeed_n, laststart,
2393                                    b + 5 + (upper_bound > 1) * 5,
2394                                    lower_bound);
2395                      b += 5;
2396
2397                      /* Code to initialize the lower bound.  Insert 
2398                         before the `succeed_n'.  The `5' is the last two
2399                         bytes of this `set_number_at', plus 3 bytes of
2400                         the following `succeed_n'.  */
2401                      insert_op2 (set_number_at, laststart, 5, lower_bound, b);
2402                      b += 5;
2403
2404                      if (upper_bound > 1)
2405                        { /* More than one repetition is allowed, so
2406                             append a backward jump to the `succeed_n'
2407                             that starts this interval.
2408                             
2409                             When we've reached this during matching,
2410                             we'll have matched the interval once, so
2411                             jump back only `upper_bound - 1' times.  */
2412                          STORE_JUMP2 (jump_n, b, laststart + 5,
2413                                       upper_bound - 1);
2414                          b += 5;
2415
2416                          /* The location we want to set is the second
2417                             parameter of the `jump_n'; that is `b-2' as
2418                             an absolute address.  `laststart' will be
2419                             the `set_number_at' we're about to insert;
2420                             `laststart+3' the number to set, the source
2421                             for the relative address.  But we are
2422                             inserting into the middle of the pattern --
2423                             so everything is getting moved up by 5.
2424                             Conclusion: (b - 2) - (laststart + 3) + 5,
2425                             i.e., b - laststart.
2426                             
2427                             We insert this at the beginning of the loop
2428                             so that if we fail during matching, we'll
2429                             reinitialize the bounds.  */
2430                          insert_op2 (set_number_at, laststart, b - laststart,
2431                                      upper_bound - 1, b);
2432                          b += 5;
2433                        }
2434                    }
2435                 pending_exact = 0;
2436                 beg_interval = NULL;
2437               }
2438               break;
2439
2440             unfetch_interval:
2441               /* If an invalid interval, match the characters as literals.  */
2442                assert (beg_interval);
2443                p = beg_interval;
2444                beg_interval = NULL;
2445
2446                /* normal_char and normal_backslash need `c'.  */
2447                PATFETCH (c);    
2448
2449                if (!(syntax & RE_NO_BK_BRACES))
2450                  {
2451                    if (p > pattern  &&  p[-1] == '\\')
2452                      goto normal_backslash;
2453                  }
2454                goto normal_char;
2455
2456 #ifdef emacs
2457             /* There is no way to specify the before_dot and after_dot
2458                operators.  rms says this is ok.  --karl  */
2459             case '=':
2460               BUF_PUSH (at_dot);
2461               break;
2462
2463             case 's':   
2464               laststart = b;
2465               PATFETCH (c);
2466               BUF_PUSH_2 (syntaxspec, syntax_spec_code[c]);
2467               break;
2468
2469             case 'S':
2470               laststart = b;
2471               PATFETCH (c);
2472               BUF_PUSH_2 (notsyntaxspec, syntax_spec_code[c]);
2473               break;
2474 #endif /* emacs */
2475
2476
2477             case 'w':
2478               laststart = b;
2479               BUF_PUSH (wordchar);
2480               break;
2481
2482
2483             case 'W':
2484               laststart = b;
2485               BUF_PUSH (notwordchar);
2486               break;
2487
2488
2489             case '<':
2490               BUF_PUSH (wordbeg);
2491               break;
2492
2493             case '>':
2494               BUF_PUSH (wordend);
2495               break;
2496
2497             case 'b':
2498               BUF_PUSH (wordbound);
2499               break;
2500
2501             case 'B':
2502               BUF_PUSH (notwordbound);
2503               break;
2504
2505             case '`':
2506               BUF_PUSH (begbuf);
2507               break;
2508
2509             case '\'':
2510               BUF_PUSH (endbuf);
2511               break;
2512
2513             case '1': case '2': case '3': case '4': case '5':
2514             case '6': case '7': case '8': case '9':
2515               if (syntax & RE_NO_BK_REFS)
2516                 goto normal_char;
2517
2518               c1 = c - '0';
2519
2520               if (c1 > regnum)
2521                 FREE_STACK_RETURN (REG_ESUBREG);
2522
2523               /* Can't back reference to a subexpression if inside of it.  */
2524               if (group_in_compile_stack (compile_stack, c1))
2525                 goto normal_char;
2526
2527               laststart = b;
2528               BUF_PUSH_2 (duplicate, c1);
2529               break;
2530
2531
2532             case '+':
2533             case '?':
2534               if (syntax & RE_BK_PLUS_QM)
2535                 goto handle_plus;
2536               else
2537                 goto normal_backslash;
2538
2539             default:
2540             normal_backslash:
2541               /* You might think it would be useful for \ to mean
2542                  not to translate; but if we don't translate it
2543                  it will never match anything.  */
2544               c = TRANSLATE (c);
2545               goto normal_char;
2546             }
2547           break;
2548
2549
2550         default:
2551         /* Expects the character in `c'.  */
2552         normal_char:
2553               /* If no exactn currently being built.  */
2554           if (!pending_exact 
2555
2556               /* If last exactn not at current position.  */
2557               || pending_exact + *pending_exact + 1 != b
2558               
2559               /* We have only one byte following the exactn for the count.  */
2560               || *pending_exact == (1 << BYTEWIDTH) - 1
2561
2562               /* If followed by a repetition operator.  */
2563               || *p == '*' || *p == '^'
2564               || ((syntax & RE_BK_PLUS_QM)
2565                   ? *p == '\\' && (p[1] == '+' || p[1] == '?')
2566                   : (*p == '+' || *p == '?'))
2567               || ((syntax & RE_INTERVALS)
2568                   && ((syntax & RE_NO_BK_BRACES)
2569                       ? *p == '{'
2570                       : (p[0] == '\\' && p[1] == '{'))))
2571             {
2572               /* Start building a new exactn.  */
2573               
2574               laststart = b;
2575
2576               BUF_PUSH_2 (exactn, 0);
2577               pending_exact = b - 1;
2578             }
2579             
2580           BUF_PUSH (c);
2581           (*pending_exact)++;
2582           break;
2583         } /* switch (c) */
2584     } /* while p != pend */
2585
2586   
2587   /* Through the pattern now.  */
2588   
2589   if (fixup_alt_jump)
2590     STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
2591
2592   if (!COMPILE_STACK_EMPTY) 
2593     FREE_STACK_RETURN (REG_EPAREN);
2594
2595   /* If we don't want backtracking, force success
2596      the first time we reach the end of the compiled pattern.  */
2597   if (syntax & RE_NO_POSIX_BACKTRACKING)
2598     BUF_PUSH (succeed);
2599
2600   free (compile_stack.stack);
2601
2602   /* We have succeeded; set the length of the buffer.  */
2603   bufp->used = b - bufp->buffer;
2604
2605 #ifdef DEBUG
2606   if (debug)
2607     {
2608       DEBUG_PRINT1 ("\nCompiled pattern: \n");
2609       print_compiled_pattern (bufp);
2610     }
2611 #endif /* DEBUG */
2612
2613 #ifndef MATCH_MAY_ALLOCATE
2614   /* Initialize the failure stack to the largest possible stack.  This
2615      isn't necessary unless we're trying to avoid calling alloca in
2616      the search and match routines.  */
2617   {
2618     int num_regs = bufp->re_nsub + 1;
2619
2620     /* Since DOUBLE_FAIL_STACK refuses to double only if the current size
2621        is strictly greater than re_max_failures, the largest possible stack
2622        is 2 * re_max_failures failure points.  */
2623     if (fail_stack.size < (2 * re_max_failures * MAX_FAILURE_ITEMS))
2624       {
2625         fail_stack.size = (2 * re_max_failures * MAX_FAILURE_ITEMS);
2626
2627 #ifdef emacs
2628         if (! fail_stack.stack)
2629           fail_stack.stack
2630             = (fail_stack_elt_t *) xmalloc (fail_stack.size 
2631                                             * sizeof (fail_stack_elt_t));
2632         else
2633           fail_stack.stack
2634             = (fail_stack_elt_t *) xrealloc (fail_stack.stack,
2635                                              (fail_stack.size
2636                                               * sizeof (fail_stack_elt_t)));
2637 #else /* not emacs */
2638         if (! fail_stack.stack)
2639           fail_stack.stack
2640             = (fail_stack_elt_t *) malloc (fail_stack.size 
2641                                            * sizeof (fail_stack_elt_t));
2642         else
2643           fail_stack.stack
2644             = (fail_stack_elt_t *) realloc (fail_stack.stack,
2645                                             (fail_stack.size
2646                                              * sizeof (fail_stack_elt_t)));
2647 #endif /* not emacs */
2648       }
2649
2650     regex_grow_registers (num_regs);
2651   }
2652 #endif /* not MATCH_MAY_ALLOCATE */
2653
2654   return REG_NOERROR;
2655 } /* regex_compile */
2656 \f
2657 /* Subroutines for `regex_compile'.  */
2658
2659 /* Store OP at LOC followed by two-byte integer parameter ARG.  */
2660
2661 static void
2662 store_op1 (op, loc, arg)
2663     re_opcode_t op;
2664     unsigned char *loc;
2665     int arg;
2666 {
2667   *loc = (unsigned char) op;
2668   STORE_NUMBER (loc + 1, arg);
2669 }
2670
2671
2672 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2.  */
2673
2674 static void
2675 store_op2 (op, loc, arg1, arg2)
2676     re_opcode_t op;
2677     unsigned char *loc;
2678     int arg1, arg2;
2679 {
2680   *loc = (unsigned char) op;
2681   STORE_NUMBER (loc + 1, arg1);
2682   STORE_NUMBER (loc + 3, arg2);
2683 }
2684
2685
2686 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
2687    for OP followed by two-byte integer parameter ARG.  */
2688
2689 static void
2690 insert_op1 (op, loc, arg, end)
2691     re_opcode_t op;
2692     unsigned char *loc;
2693     int arg;
2694     unsigned char *end;    
2695 {
2696   register unsigned char *pfrom = end;
2697   register unsigned char *pto = end + 3;
2698
2699   while (pfrom != loc)
2700     *--pto = *--pfrom;
2701     
2702   store_op1 (op, loc, arg);
2703 }
2704
2705
2706 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2.  */
2707
2708 static void
2709 insert_op2 (op, loc, arg1, arg2, end)
2710     re_opcode_t op;
2711     unsigned char *loc;
2712     int arg1, arg2;
2713     unsigned char *end;    
2714 {
2715   register unsigned char *pfrom = end;
2716   register unsigned char *pto = end + 5;
2717
2718   while (pfrom != loc)
2719     *--pto = *--pfrom;
2720     
2721   store_op2 (op, loc, arg1, arg2);
2722 }
2723
2724
2725 /* P points to just after a ^ in PATTERN.  Return true if that ^ comes
2726    after an alternative or a begin-subexpression.  We assume there is at
2727    least one character before the ^.  */
2728
2729 static boolean
2730 at_begline_loc_p (pattern, p, syntax)
2731     const char *pattern, *p;
2732     reg_syntax_t syntax;
2733 {
2734   const char *prev = p - 2;
2735   boolean prev_prev_backslash = prev > pattern && prev[-1] == '\\';
2736   
2737   return
2738        /* After a subexpression?  */
2739        (*prev == '(' && (syntax & RE_NO_BK_PARENS || prev_prev_backslash))
2740        /* After an alternative?  */
2741     || (*prev == '|' && (syntax & RE_NO_BK_VBAR || prev_prev_backslash));
2742 }
2743
2744
2745 /* The dual of at_begline_loc_p.  This one is for $.  We assume there is
2746    at least one character after the $, i.e., `P < PEND'.  */
2747
2748 static boolean
2749 at_endline_loc_p (p, pend, syntax)
2750     const char *p, *pend;
2751     int syntax;
2752 {
2753   const char *next = p;
2754   boolean next_backslash = *next == '\\';
2755   const char *next_next = p + 1 < pend ? p + 1 : NULL;
2756   
2757   return
2758        /* Before a subexpression?  */
2759        (syntax & RE_NO_BK_PARENS ? *next == ')'
2760         : next_backslash && next_next && *next_next == ')')
2761        /* Before an alternative?  */
2762     || (syntax & RE_NO_BK_VBAR ? *next == '|'
2763         : next_backslash && next_next && *next_next == '|');
2764 }
2765
2766
2767 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and 
2768    false if it's not.  */
2769
2770 static boolean
2771 group_in_compile_stack (compile_stack, regnum)
2772     compile_stack_type compile_stack;
2773     regnum_t regnum;
2774 {
2775   int this_element;
2776
2777   for (this_element = compile_stack.avail - 1;  
2778        this_element >= 0; 
2779        this_element--)
2780     if (compile_stack.stack[this_element].regnum == regnum)
2781       return true;
2782
2783   return false;
2784 }
2785
2786
2787 /* Read the ending character of a range (in a bracket expression) from the
2788    uncompiled pattern *P_PTR (which ends at PEND).  We assume the
2789    starting character is in `P[-2]'.  (`P[-1]' is the character `-'.)
2790    Then we set the translation of all bits between the starting and
2791    ending characters (inclusive) in the compiled pattern B.
2792    
2793    Return an error code.
2794    
2795    We use these short variable names so we can use the same macros as
2796    `regex_compile' itself.  */
2797
2798 static reg_errcode_t
2799 compile_range (p_ptr, pend, translate, syntax, b)
2800     const char **p_ptr, *pend;
2801     char *translate;
2802     reg_syntax_t syntax;
2803     unsigned char *b;
2804 {
2805   unsigned this_char;
2806
2807   const char *p = *p_ptr;
2808   int range_start, range_end;
2809   
2810   if (p == pend)
2811     return REG_ERANGE;
2812
2813   /* Even though the pattern is a signed `char *', we need to fetch
2814      with unsigned char *'s; if the high bit of the pattern character
2815      is set, the range endpoints will be negative if we fetch using a
2816      signed char *.
2817
2818      We also want to fetch the endpoints without translating them; the 
2819      appropriate translation is done in the bit-setting loop below.  */
2820   /* The SVR4 compiler on the 3B2 had trouble with unsigned const char *.  */
2821   range_start = ((const unsigned char *) p)[-2];
2822   range_end   = ((const unsigned char *) p)[0];
2823
2824   /* Have to increment the pointer into the pattern string, so the
2825      caller isn't still at the ending character.  */
2826   (*p_ptr)++;
2827
2828   /* If the start is after the end, the range is empty.  */
2829   if (range_start > range_end)
2830     return syntax & RE_NO_EMPTY_RANGES ? REG_ERANGE : REG_NOERROR;
2831
2832   /* Here we see why `this_char' has to be larger than an `unsigned
2833      char' -- the range is inclusive, so if `range_end' == 0xff
2834      (assuming 8-bit characters), we would otherwise go into an infinite
2835      loop, since all characters <= 0xff.  */
2836   for (this_char = range_start; this_char <= range_end; this_char++)
2837     {
2838       SET_LIST_BIT (TRANSLATE (this_char));
2839     }
2840   
2841   return REG_NOERROR;
2842 }
2843 \f
2844 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
2845    BUFP.  A fastmap records which of the (1 << BYTEWIDTH) possible
2846    characters can start a string that matches the pattern.  This fastmap
2847    is used by re_search to skip quickly over impossible starting points.
2848
2849    The caller must supply the address of a (1 << BYTEWIDTH)-byte data
2850    area as BUFP->fastmap.
2851    
2852    We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
2853    the pattern buffer.
2854
2855    Returns 0 if we succeed, -2 if an internal error.   */
2856
2857 int
2858 re_compile_fastmap (bufp)
2859      struct re_pattern_buffer *bufp;
2860 {
2861   int j, k;
2862 #ifdef MATCH_MAY_ALLOCATE
2863   fail_stack_type fail_stack;
2864 #endif
2865 #ifndef REGEX_MALLOC
2866   char *destination;
2867 #endif
2868   /* We don't push any register information onto the failure stack.  */
2869   unsigned num_regs = 0;
2870   
2871   register char *fastmap = bufp->fastmap;
2872   unsigned char *pattern = bufp->buffer;
2873   unsigned long size = bufp->used;
2874   unsigned char *p = pattern;
2875   register unsigned char *pend = pattern + size;
2876
2877   /* This holds the pointer to the failure stack, when
2878      it is allocated relocatably.  */
2879   fail_stack_elt_t *failure_stack_ptr;
2880
2881   /* Assume that each path through the pattern can be null until
2882      proven otherwise.  We set this false at the bottom of switch
2883      statement, to which we get only if a particular path doesn't
2884      match the empty string.  */
2885   boolean path_can_be_null = true;
2886
2887   /* We aren't doing a `succeed_n' to begin with.  */
2888   boolean succeed_n_p = false;
2889
2890   assert (fastmap != NULL && p != NULL);
2891   
2892   INIT_FAIL_STACK ();
2893   bzero (fastmap, 1 << BYTEWIDTH);  /* Assume nothing's valid.  */
2894   bufp->fastmap_accurate = 1;       /* It will be when we're done.  */
2895   bufp->can_be_null = 0;
2896       
2897   while (1)
2898     {
2899       if (p == pend || *p == succeed)
2900         {
2901           /* We have reached the (effective) end of pattern.  */
2902           if (!FAIL_STACK_EMPTY ())
2903             {
2904               bufp->can_be_null |= path_can_be_null;
2905
2906               /* Reset for next path.  */
2907               path_can_be_null = true;
2908
2909               p = fail_stack.stack[--fail_stack.avail].pointer;
2910
2911               continue;
2912             }
2913           else
2914             break;
2915         }
2916
2917       /* We should never be about to go beyond the end of the pattern.  */
2918       assert (p < pend);
2919       
2920       switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
2921         {
2922
2923         /* I guess the idea here is to simply not bother with a fastmap
2924            if a backreference is used, since it's too hard to figure out
2925            the fastmap for the corresponding group.  Setting
2926            `can_be_null' stops `re_search_2' from using the fastmap, so
2927            that is all we do.  */
2928         case duplicate:
2929           bufp->can_be_null = 1;
2930           goto done;
2931
2932
2933       /* Following are the cases which match a character.  These end
2934          with `break'.  */
2935
2936         case exactn:
2937           fastmap[p[1]] = 1;
2938           break;
2939
2940
2941         case charset:
2942           for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
2943             if (p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH)))
2944               fastmap[j] = 1;
2945           break;
2946
2947
2948         case charset_not:
2949           /* Chars beyond end of map must be allowed.  */
2950           for (j = *p * BYTEWIDTH; j < (1 << BYTEWIDTH); j++)
2951             fastmap[j] = 1;
2952
2953           for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
2954             if (!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))))
2955               fastmap[j] = 1;
2956           break;
2957
2958
2959         case wordchar:
2960           for (j = 0; j < (1 << BYTEWIDTH); j++)
2961             if (SYNTAX (j) == Sword)
2962               fastmap[j] = 1;
2963           break;
2964
2965
2966         case notwordchar:
2967           for (j = 0; j < (1 << BYTEWIDTH); j++)
2968             if (SYNTAX (j) != Sword)
2969               fastmap[j] = 1;
2970           break;
2971
2972
2973         case anychar:
2974           {
2975             int fastmap_newline = fastmap['\n'];
2976
2977             /* `.' matches anything ...  */
2978             for (j = 0; j < (1 << BYTEWIDTH); j++)
2979               fastmap[j] = 1;
2980
2981             /* ... except perhaps newline.  */
2982             if (!(bufp->syntax & RE_DOT_NEWLINE))
2983               fastmap['\n'] = fastmap_newline;
2984
2985             /* Return if we have already set `can_be_null'; if we have,
2986                then the fastmap is irrelevant.  Something's wrong here.  */
2987             else if (bufp->can_be_null)
2988               goto done;
2989
2990             /* Otherwise, have to check alternative paths.  */
2991             break;
2992           }
2993
2994 #ifdef emacs
2995         case syntaxspec:
2996           k = *p++;
2997           for (j = 0; j < (1 << BYTEWIDTH); j++)
2998             if (SYNTAX (j) == (enum syntaxcode) k)
2999               fastmap[j] = 1;
3000           break;
3001
3002
3003         case notsyntaxspec:
3004           k = *p++;
3005           for (j = 0; j < (1 << BYTEWIDTH); j++)
3006             if (SYNTAX (j) != (enum syntaxcode) k)
3007               fastmap[j] = 1;
3008           break;
3009
3010
3011       /* All cases after this match the empty string.  These end with
3012          `continue'.  */
3013
3014
3015         case before_dot:
3016         case at_dot:
3017         case after_dot:
3018           continue;
3019 #endif /* not emacs */
3020
3021
3022         case no_op:
3023         case begline:
3024         case endline:
3025         case begbuf:
3026         case endbuf:
3027         case wordbound:
3028         case notwordbound:
3029         case wordbeg:
3030         case wordend:
3031         case push_dummy_failure:
3032           continue;
3033
3034
3035         case jump_n:
3036         case pop_failure_jump:
3037         case maybe_pop_jump:
3038         case jump:
3039         case jump_past_alt:
3040         case dummy_failure_jump:
3041           EXTRACT_NUMBER_AND_INCR (j, p);
3042           p += j;       
3043           if (j > 0)
3044             continue;
3045             
3046           /* Jump backward implies we just went through the body of a
3047              loop and matched nothing.  Opcode jumped to should be
3048              `on_failure_jump' or `succeed_n'.  Just treat it like an
3049              ordinary jump.  For a * loop, it has pushed its failure
3050              point already; if so, discard that as redundant.  */
3051           if ((re_opcode_t) *p != on_failure_jump
3052               && (re_opcode_t) *p != succeed_n)
3053             continue;
3054
3055           p++;
3056           EXTRACT_NUMBER_AND_INCR (j, p);
3057           p += j;               
3058           
3059           /* If what's on the stack is where we are now, pop it.  */
3060           if (!FAIL_STACK_EMPTY () 
3061               && fail_stack.stack[fail_stack.avail - 1].pointer == p)
3062             fail_stack.avail--;
3063
3064           continue;
3065
3066
3067         case on_failure_jump:
3068         case on_failure_keep_string_jump:
3069         handle_on_failure_jump:
3070           EXTRACT_NUMBER_AND_INCR (j, p);
3071
3072           /* For some patterns, e.g., `(a?)?', `p+j' here points to the
3073              end of the pattern.  We don't want to push such a point,
3074              since when we restore it above, entering the switch will
3075              increment `p' past the end of the pattern.  We don't need
3076              to push such a point since we obviously won't find any more
3077              fastmap entries beyond `pend'.  Such a pattern can match
3078              the null string, though.  */
3079           if (p + j < pend)
3080             {
3081               if (!PUSH_PATTERN_OP (p + j, fail_stack))
3082                 {
3083                   REGEX_FREE_STACK (fail_stack.stack);
3084                   return -2;
3085                 }
3086             }
3087           else
3088             bufp->can_be_null = 1;
3089
3090           if (succeed_n_p)
3091             {
3092               EXTRACT_NUMBER_AND_INCR (k, p);   /* Skip the n.  */
3093               succeed_n_p = false;
3094             }
3095
3096           continue;
3097
3098
3099         case succeed_n:
3100           /* Get to the number of times to succeed.  */
3101           p += 2;               
3102
3103           /* Increment p past the n for when k != 0.  */
3104           EXTRACT_NUMBER_AND_INCR (k, p);
3105           if (k == 0)
3106             {
3107               p -= 4;
3108               succeed_n_p = true;  /* Spaghetti code alert.  */
3109               goto handle_on_failure_jump;
3110             }
3111           continue;
3112
3113
3114         case set_number_at:
3115           p += 4;
3116           continue;
3117
3118
3119         case start_memory:
3120         case stop_memory:
3121           p += 2;
3122           continue;
3123
3124
3125         default:
3126           abort (); /* We have listed all the cases.  */
3127         } /* switch *p++ */
3128
3129       /* Getting here means we have found the possible starting
3130          characters for one path of the pattern -- and that the empty
3131          string does not match.  We need not follow this path further.
3132          Instead, look at the next alternative (remembered on the
3133          stack), or quit if no more.  The test at the top of the loop
3134          does these things.  */
3135       path_can_be_null = false;
3136       p = pend;
3137     } /* while p */
3138
3139   /* Set `can_be_null' for the last path (also the first path, if the
3140      pattern is empty).  */
3141   bufp->can_be_null |= path_can_be_null;
3142
3143  done:
3144   if (!FAIL_STACK_EMPTY ())
3145      REGEX_FREE_STACK (fail_stack.stack);
3146   return 0;
3147 } /* re_compile_fastmap */
3148 \f
3149 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
3150    ENDS.  Subsequent matches using PATTERN_BUFFER and REGS will use
3151    this memory for recording register information.  STARTS and ENDS
3152    must be allocated using the malloc library routine, and must each
3153    be at least NUM_REGS * sizeof (regoff_t) bytes long.
3154
3155    If NUM_REGS == 0, then subsequent matches should allocate their own
3156    register data.
3157
3158    Unless this function is called, the first search or match using
3159    PATTERN_BUFFER will allocate its own register data, without
3160    freeing the old data.  */
3161
3162 void
3163 re_set_registers (bufp, regs, num_regs, starts, ends)
3164     struct re_pattern_buffer *bufp;
3165     struct re_registers *regs;
3166     unsigned num_regs;
3167     regoff_t *starts, *ends;
3168 {
3169   if (num_regs)
3170     {
3171       bufp->regs_allocated = REGS_REALLOCATE;
3172       regs->num_regs = num_regs;
3173       regs->start = starts;
3174       regs->end = ends;
3175     }
3176   else
3177     {
3178       bufp->regs_allocated = REGS_UNALLOCATED;
3179       regs->num_regs = 0;
3180       regs->start = regs->end = (regoff_t *) 0;
3181     }
3182 }
3183 \f
3184 /* Searching routines.  */
3185
3186 /* Like re_search_2, below, but only one string is specified, and
3187    doesn't let you say where to stop matching. */
3188
3189 int
3190 re_search (bufp, string, size, startpos, range, regs)
3191      struct re_pattern_buffer *bufp;
3192      const char *string;
3193      int size, startpos, range;
3194      struct re_registers *regs;
3195 {
3196   return re_search_2 (bufp, NULL, 0, string, size, startpos, range, 
3197                       regs, size);
3198 }
3199
3200
3201 /* Using the compiled pattern in BUFP->buffer, first tries to match the
3202    virtual concatenation of STRING1 and STRING2, starting first at index
3203    STARTPOS, then at STARTPOS + 1, and so on.
3204    
3205    STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
3206    
3207    RANGE is how far to scan while trying to match.  RANGE = 0 means try
3208    only at STARTPOS; in general, the last start tried is STARTPOS +
3209    RANGE.
3210    
3211    In REGS, return the indices of the virtual concatenation of STRING1
3212    and STRING2 that matched the entire BUFP->buffer and its contained
3213    subexpressions.
3214    
3215    Do not consider matching one past the index STOP in the virtual
3216    concatenation of STRING1 and STRING2.
3217
3218    We return either the position in the strings at which the match was
3219    found, -1 if no match, or -2 if error (such as failure
3220    stack overflow).  */
3221
3222 int
3223 re_search_2 (bufp, string1, size1, string2, size2, startpos, range, regs, stop)
3224      struct re_pattern_buffer *bufp;
3225      const char *string1, *string2;
3226      int size1, size2;
3227      int startpos;
3228      int range;
3229      struct re_registers *regs;
3230      int stop;
3231 {
3232   int val;
3233   register char *fastmap = bufp->fastmap;
3234   register char *translate = bufp->translate;
3235   int total_size = size1 + size2;
3236   int endpos = startpos + range;
3237
3238   /* Check for out-of-range STARTPOS.  */
3239   if (startpos < 0 || startpos > total_size)
3240     return -1;
3241     
3242   /* Fix up RANGE if it might eventually take us outside
3243      the virtual concatenation of STRING1 and STRING2.  */
3244   if (endpos < -1)
3245     range = -1 - startpos;
3246   else if (endpos > total_size)
3247     range = total_size - startpos;
3248
3249   /* If the search isn't to be a backwards one, don't waste time in a
3250      search for a pattern that must be anchored.  */
3251   if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == begbuf && range > 0)
3252     {
3253       if (startpos > 0)
3254         return -1;
3255       else
3256         range = 1;
3257     }
3258
3259   /* Update the fastmap now if not correct already.  */
3260   if (fastmap && !bufp->fastmap_accurate)
3261     if (re_compile_fastmap (bufp) == -2)
3262       return -2;
3263   
3264   /* Loop through the string, looking for a place to start matching.  */
3265   for (;;)
3266     { 
3267       /* If a fastmap is supplied, skip quickly over characters that
3268          cannot be the start of a match.  If the pattern can match the
3269          null string, however, we don't need to skip characters; we want
3270          the first null string.  */
3271       if (fastmap && startpos < total_size && !bufp->can_be_null)
3272         {
3273           if (range > 0)        /* Searching forwards.  */
3274             {
3275               register const char *d;
3276               register int lim = 0;
3277               int irange = range;
3278
3279               if (startpos < size1 && startpos + range >= size1)
3280                 lim = range - (size1 - startpos);
3281
3282               d = (startpos >= size1 ? string2 - size1 : string1) + startpos;
3283    
3284               /* Written out as an if-else to avoid testing `translate'
3285                  inside the loop.  */
3286               if (translate)
3287                 while (range > lim
3288                        && !fastmap[(unsigned char)
3289                                    translate[(unsigned char) *d++]])
3290                   range--;
3291               else
3292                 while (range > lim && !fastmap[(unsigned char) *d++])
3293                   range--;
3294
3295               startpos += irange - range;
3296             }
3297           else                          /* Searching backwards.  */
3298             {
3299               register char c = (size1 == 0 || startpos >= size1
3300                                  ? string2[startpos - size1] 
3301                                  : string1[startpos]);
3302
3303               if (!fastmap[(unsigned char) TRANSLATE (c)])
3304                 goto advance;
3305             }
3306         }
3307
3308       /* If can't match the null string, and that's all we have left, fail.  */
3309       if (range >= 0 && startpos == total_size && fastmap
3310           && !bufp->can_be_null)
3311         return -1;
3312
3313       val = re_match_2_internal (bufp, string1, size1, string2, size2,
3314                                  startpos, regs, stop);
3315 #ifndef REGEX_MALLOC
3316 #ifdef C_ALLOCA
3317       alloca (0);
3318 #endif
3319 #endif
3320
3321       if (val >= 0)
3322         return startpos;
3323         
3324       if (val == -2)
3325         return -2;
3326
3327     advance:
3328       if (!range) 
3329         break;
3330       else if (range > 0) 
3331         {
3332           range--; 
3333           startpos++;
3334         }
3335       else
3336         {
3337           range++; 
3338           startpos--;
3339         }
3340     }
3341   return -1;
3342 } /* re_search_2 */
3343 \f
3344 /* Declarations and macros for re_match_2.  */
3345
3346 static int bcmp_translate ();
3347 static boolean alt_match_null_string_p (),
3348                common_op_match_null_string_p (),
3349                group_match_null_string_p ();
3350
3351 /* This converts PTR, a pointer into one of the search strings `string1'
3352    and `string2' into an offset from the beginning of that string.  */
3353 #define POINTER_TO_OFFSET(ptr)                  \
3354   (FIRST_STRING_P (ptr)                         \
3355    ? ((regoff_t) ((ptr) - string1))             \
3356    : ((regoff_t) ((ptr) - string2 + size1)))
3357
3358 /* Macros for dealing with the split strings in re_match_2.  */
3359
3360 #define MATCHING_IN_FIRST_STRING  (dend == end_match_1)
3361
3362 /* Call before fetching a character with *d.  This switches over to
3363    string2 if necessary.  */
3364 #define PREFETCH()                                                      \
3365   while (d == dend)                                                     \
3366     {                                                                   \
3367       /* End of string2 => fail.  */                                    \
3368       if (dend == end_match_2)                                          \
3369         goto fail;                                                      \
3370       /* End of string1 => advance to string2.  */                      \
3371       d = string2;                                                      \
3372       dend = end_match_2;                                               \
3373     }
3374
3375
3376 /* Test if at very beginning or at very end of the virtual concatenation
3377    of `string1' and `string2'.  If only one string, it's `string2'.  */
3378 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
3379 #define AT_STRINGS_END(d) ((d) == end2) 
3380
3381
3382 /* Test if D points to a character which is word-constituent.  We have
3383    two special cases to check for: if past the end of string1, look at
3384    the first character in string2; and if before the beginning of
3385    string2, look at the last character in string1.  */
3386 #define WORDCHAR_P(d)                                                   \
3387   (SYNTAX ((d) == end1 ? *string2                                       \
3388            : (d) == string2 - 1 ? *(end1 - 1) : *(d))                   \
3389    == Sword)
3390
3391 /* Test if the character before D and the one at D differ with respect
3392    to being word-constituent.  */
3393 #define AT_WORD_BOUNDARY(d)                                             \
3394   (AT_STRINGS_BEG (d) || AT_STRINGS_END (d)                             \
3395    || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
3396
3397
3398 /* Free everything we malloc.  */
3399 #ifdef MATCH_MAY_ALLOCATE
3400 #define FREE_VAR(var) if (var) REGEX_FREE (var); var = NULL
3401 #define FREE_VARIABLES()                                                \
3402   do {                                                                  \
3403     REGEX_FREE_STACK (fail_stack.stack);                                \
3404     FREE_VAR (regstart);                                                \
3405     FREE_VAR (regend);                                                  \
3406     FREE_VAR (old_regstart);                                            \
3407     FREE_VAR (old_regend);                                              \
3408     FREE_VAR (best_regstart);                                           \
3409     FREE_VAR (best_regend);                                             \
3410     FREE_VAR (reg_info);                                                \
3411     FREE_VAR (reg_dummy);                                               \
3412     FREE_VAR (reg_info_dummy);                                          \
3413   } while (0)
3414 #else
3415 #define FREE_VARIABLES() /* Do nothing!  */
3416 #endif /* not MATCH_MAY_ALLOCATE */
3417
3418 /* These values must meet several constraints.  They must not be valid
3419    register values; since we have a limit of 255 registers (because
3420    we use only one byte in the pattern for the register number), we can
3421    use numbers larger than 255.  They must differ by 1, because of
3422    NUM_FAILURE_ITEMS above.  And the value for the lowest register must
3423    be larger than the value for the highest register, so we do not try
3424    to actually save any registers when none are active.  */
3425 #define NO_HIGHEST_ACTIVE_REG (1 << BYTEWIDTH)
3426 #define NO_LOWEST_ACTIVE_REG (NO_HIGHEST_ACTIVE_REG + 1)
3427 \f
3428 /* Matching routines.  */
3429
3430 #ifndef emacs   /* Emacs never uses this.  */
3431 /* re_match is like re_match_2 except it takes only a single string.  */
3432
3433 int
3434 re_match (bufp, string, size, pos, regs)
3435      struct re_pattern_buffer *bufp;
3436      const char *string;
3437      int size, pos;
3438      struct re_registers *regs;
3439 {
3440   int result = re_match_2_internal (bufp, NULL, 0, string, size,
3441                                     pos, regs, size);
3442   alloca (0);
3443   return result;
3444 }
3445 #endif /* not emacs */
3446
3447
3448 /* re_match_2 matches the compiled pattern in BUFP against the
3449    the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
3450    and SIZE2, respectively).  We start matching at POS, and stop
3451    matching at STOP.
3452    
3453    If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
3454    store offsets for the substring each group matched in REGS.  See the
3455    documentation for exactly how many groups we fill.
3456
3457    We return -1 if no match, -2 if an internal error (such as the
3458    failure stack overflowing).  Otherwise, we return the length of the
3459    matched substring.  */
3460
3461 int
3462 re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
3463      struct re_pattern_buffer *bufp;
3464      const char *string1, *string2;
3465      int size1, size2;
3466      int pos;
3467      struct re_registers *regs;
3468      int stop;
3469 {
3470   int result = re_match_2_internal (bufp, string1, size1, string2, size2,
3471                                     pos, regs, stop);
3472   alloca (0);
3473   return result;
3474 }
3475
3476 /* This is a separate function so that we can force an alloca cleanup
3477    afterwards.  */
3478 static int
3479 re_match_2_internal (bufp, string1, size1, string2, size2, pos, regs, stop)
3480      struct re_pattern_buffer *bufp;
3481      const char *string1, *string2;
3482      int size1, size2;
3483      int pos;
3484      struct re_registers *regs;
3485      int stop;
3486 {
3487   /* General temporaries.  */
3488   int mcnt;
3489   unsigned char *p1;
3490
3491   /* Just past the end of the corresponding string.  */
3492   const char *end1, *end2;
3493
3494   /* Pointers into string1 and string2, just past the last characters in
3495      each to consider matching.  */
3496   const char *end_match_1, *end_match_2;
3497
3498   /* Where we are in the data, and the end of the current string.  */
3499   const char *d, *dend;
3500   
3501   /* Where we are in the pattern, and the end of the pattern.  */
3502   unsigned char *p = bufp->buffer;
3503   register unsigned char *pend = p + bufp->used;
3504
3505   /* Mark the opcode just after a start_memory, so we can test for an
3506      empty subpattern when we get to the stop_memory.  */
3507   unsigned char *just_past_start_mem = 0;
3508
3509   /* We use this to map every character in the string.  */
3510   char *translate = bufp->translate;
3511
3512   /* Failure point stack.  Each place that can handle a failure further
3513      down the line pushes a failure point on this stack.  It consists of
3514      restart, regend, and reg_info for all registers corresponding to
3515      the subexpressions we're currently inside, plus the number of such
3516      registers, and, finally, two char *'s.  The first char * is where
3517      to resume scanning the pattern; the second one is where to resume
3518      scanning the strings.  If the latter is zero, the failure point is
3519      a ``dummy''; if a failure happens and the failure point is a dummy,
3520      it gets discarded and the next next one is tried.  */
3521 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global.  */
3522   fail_stack_type fail_stack;
3523 #endif
3524 #ifdef DEBUG
3525   static unsigned failure_id = 0;
3526   unsigned nfailure_points_pushed = 0, nfailure_points_popped = 0;
3527 #endif
3528
3529   /* This holds the pointer to the failure stack, when
3530      it is allocated relocatably.  */
3531   fail_stack_elt_t *failure_stack_ptr;
3532
3533   /* We fill all the registers internally, independent of what we
3534      return, for use in backreferences.  The number here includes
3535      an element for register zero.  */
3536   unsigned num_regs = bufp->re_nsub + 1;
3537   
3538   /* The currently active registers.  */
3539   unsigned lowest_active_reg = NO_LOWEST_ACTIVE_REG;
3540   unsigned highest_active_reg = NO_HIGHEST_ACTIVE_REG;
3541
3542   /* Information on the contents of registers. These are pointers into
3543      the input strings; they record just what was matched (on this
3544      attempt) by a subexpression part of the pattern, that is, the
3545      regnum-th regstart pointer points to where in the pattern we began
3546      matching and the regnum-th regend points to right after where we
3547      stopped matching the regnum-th subexpression.  (The zeroth register
3548      keeps track of what the whole pattern matches.)  */
3549 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global.  */
3550   const char **regstart, **regend;
3551 #endif
3552
3553   /* If a group that's operated upon by a repetition operator fails to
3554      match anything, then the register for its start will need to be
3555      restored because it will have been set to wherever in the string we
3556      are when we last see its open-group operator.  Similarly for a
3557      register's end.  */
3558 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global.  */
3559   const char **old_regstart, **old_regend;
3560 #endif
3561
3562   /* The is_active field of reg_info helps us keep track of which (possibly
3563      nested) subexpressions we are currently in. The matched_something
3564      field of reg_info[reg_num] helps us tell whether or not we have
3565      matched any of the pattern so far this time through the reg_num-th
3566      subexpression.  These two fields get reset each time through any
3567      loop their register is in.  */
3568 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global.  */
3569   register_info_type *reg_info; 
3570 #endif
3571
3572   /* The following record the register info as found in the above
3573      variables when we find a match better than any we've seen before. 
3574      This happens as we backtrack through the failure points, which in
3575      turn happens only if we have not yet matched the entire string. */
3576   unsigned best_regs_set = false;
3577 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global.  */
3578   const char **best_regstart, **best_regend;
3579 #endif
3580   
3581   /* Logically, this is `best_regend[0]'.  But we don't want to have to
3582      allocate space for that if we're not allocating space for anything
3583      else (see below).  Also, we never need info about register 0 for
3584      any of the other register vectors, and it seems rather a kludge to
3585      treat `best_regend' differently than the rest.  So we keep track of
3586      the end of the best match so far in a separate variable.  We
3587      initialize this to NULL so that when we backtrack the first time
3588      and need to test it, it's not garbage.  */
3589   const char *match_end = NULL;
3590
3591   /* This helps SET_REGS_MATCHED avoid doing redundant work.  */
3592   int set_regs_matched_done = 0;
3593
3594   /* Used when we pop values we don't care about.  */
3595 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global.  */
3596   const char **reg_dummy;
3597   register_info_type *reg_info_dummy;
3598 #endif
3599
3600 #ifdef DEBUG
3601   /* Counts the total number of registers pushed.  */
3602   unsigned num_regs_pushed = 0;         
3603 #endif
3604
3605   DEBUG_PRINT1 ("\n\nEntering re_match_2.\n");
3606   
3607   INIT_FAIL_STACK ();
3608   
3609 #ifdef MATCH_MAY_ALLOCATE
3610   /* Do not bother to initialize all the register variables if there are
3611      no groups in the pattern, as it takes a fair amount of time.  If
3612      there are groups, we include space for register 0 (the whole
3613      pattern), even though we never use it, since it simplifies the
3614      array indexing.  We should fix this.  */
3615   if (bufp->re_nsub)
3616     {
3617       regstart = REGEX_TALLOC (num_regs, const char *);
3618       regend = REGEX_TALLOC (num_regs, const char *);
3619       old_regstart = REGEX_TALLOC (num_regs, const char *);
3620       old_regend = REGEX_TALLOC (num_regs, const char *);
3621       best_regstart = REGEX_TALLOC (num_regs, const char *);
3622       best_regend = REGEX_TALLOC (num_regs, const char *);
3623       reg_info = REGEX_TALLOC (num_regs, register_info_type);
3624       reg_dummy = REGEX_TALLOC (num_regs, const char *);
3625       reg_info_dummy = REGEX_TALLOC (num_regs, register_info_type);
3626
3627       if (!(regstart && regend && old_regstart && old_regend && reg_info 
3628             && best_regstart && best_regend && reg_dummy && reg_info_dummy)) 
3629         {
3630           FREE_VARIABLES ();
3631           return -2;
3632         }
3633     }
3634   else
3635     {
3636       /* We must initialize all our variables to NULL, so that
3637          `FREE_VARIABLES' doesn't try to free them.  */
3638       regstart = regend = old_regstart = old_regend = best_regstart
3639         = best_regend = reg_dummy = NULL;
3640       reg_info = reg_info_dummy = (register_info_type *) NULL;
3641     }
3642 #endif /* MATCH_MAY_ALLOCATE */
3643
3644   /* The starting position is bogus.  */
3645   if (pos < 0 || pos > size1 + size2)
3646     {
3647       FREE_VARIABLES ();
3648       return -1;
3649     }
3650     
3651   /* Initialize subexpression text positions to -1 to mark ones that no
3652      start_memory/stop_memory has been seen for. Also initialize the
3653      register information struct.  */
3654   for (mcnt = 1; mcnt < num_regs; mcnt++)
3655     {
3656       regstart[mcnt] = regend[mcnt] 
3657         = old_regstart[mcnt] = old_regend[mcnt] = REG_UNSET_VALUE;
3658         
3659       REG_MATCH_NULL_STRING_P (reg_info[mcnt]) = MATCH_NULL_UNSET_VALUE;
3660       IS_ACTIVE (reg_info[mcnt]) = 0;
3661       MATCHED_SOMETHING (reg_info[mcnt]) = 0;
3662       EVER_MATCHED_SOMETHING (reg_info[mcnt]) = 0;
3663     }
3664   
3665   /* We move `string1' into `string2' if the latter's empty -- but not if
3666      `string1' is null.  */
3667   if (size2 == 0 && string1 != NULL)
3668     {
3669       string2 = string1;
3670       size2 = size1;
3671       string1 = 0;
3672       size1 = 0;
3673     }
3674   end1 = string1 + size1;
3675   end2 = string2 + size2;
3676
3677   /* Compute where to stop matching, within the two strings.  */
3678   if (stop <= size1)
3679     {
3680       end_match_1 = string1 + stop;
3681       end_match_2 = string2;
3682     }
3683   else
3684     {
3685       end_match_1 = end1;
3686       end_match_2 = string2 + stop - size1;
3687     }
3688
3689   /* `p' scans through the pattern as `d' scans through the data. 
3690      `dend' is the end of the input string that `d' points within.  `d'
3691      is advanced into the following input string whenever necessary, but
3692      this happens before fetching; therefore, at the beginning of the
3693      loop, `d' can be pointing at the end of a string, but it cannot
3694      equal `string2'.  */
3695   if (size1 > 0 && pos <= size1)
3696     {
3697       d = string1 + pos;
3698       dend = end_match_1;
3699     }
3700   else
3701     {
3702       d = string2 + pos - size1;
3703       dend = end_match_2;
3704     }
3705
3706   DEBUG_PRINT1 ("The compiled pattern is: ");
3707   DEBUG_PRINT_COMPILED_PATTERN (bufp, p, pend);
3708   DEBUG_PRINT1 ("The string to match is: `");
3709   DEBUG_PRINT_DOUBLE_STRING (d, string1, size1, string2, size2);
3710   DEBUG_PRINT1 ("'\n");
3711   
3712   /* This loops over pattern commands.  It exits by returning from the
3713      function if the match is complete, or it drops through if the match
3714      fails at this starting point in the input data.  */
3715   for (;;)
3716     {
3717       DEBUG_PRINT2 ("\n0x%x: ", p);
3718
3719       if (p == pend)
3720         { /* End of pattern means we might have succeeded.  */
3721           DEBUG_PRINT1 ("end of pattern ... ");
3722           
3723           /* If we haven't matched the entire string, and we want the
3724              longest match, try backtracking.  */
3725           if (d != end_match_2)
3726             {
3727               /* 1 if this match ends in the same string (string1 or string2)
3728                  as the best previous match.  */
3729               boolean same_str_p = (FIRST_STRING_P (match_end) 
3730                                     == MATCHING_IN_FIRST_STRING);
3731               /* 1 if this match is the best seen so far.  */
3732               boolean best_match_p;
3733
3734               /* AIX compiler got confused when this was combined
3735                  with the previous declaration.  */
3736               if (same_str_p)
3737                 best_match_p = d > match_end;
3738               else
3739                 best_match_p = !MATCHING_IN_FIRST_STRING;
3740
3741               DEBUG_PRINT1 ("backtracking.\n");
3742               
3743               if (!FAIL_STACK_EMPTY ())
3744                 { /* More failure points to try.  */
3745
3746                   /* If exceeds best match so far, save it.  */
3747                   if (!best_regs_set || best_match_p)
3748                     {
3749                       best_regs_set = true;
3750                       match_end = d;
3751                       
3752                       DEBUG_PRINT1 ("\nSAVING match as best so far.\n");
3753                       
3754                       for (mcnt = 1; mcnt < num_regs; mcnt++)
3755                         {
3756                           best_regstart[mcnt] = regstart[mcnt];
3757                           best_regend[mcnt] = regend[mcnt];
3758                         }
3759                     }
3760                   goto fail;           
3761                 }
3762
3763               /* If no failure points, don't restore garbage.  And if
3764                  last match is real best match, don't restore second
3765                  best one. */
3766               else if (best_regs_set && !best_match_p)
3767                 {
3768                 restore_best_regs:
3769                   /* Restore best match.  It may happen that `dend ==
3770                      end_match_1' while the restored d is in string2.
3771                      For example, the pattern `x.*y.*z' against the
3772                      strings `x-' and `y-z-', if the two strings are
3773                      not consecutive in memory.  */
3774                   DEBUG_PRINT1 ("Restoring best registers.\n");
3775                   
3776                   d = match_end;
3777                   dend = ((d >= string1 && d <= end1)
3778                            ? end_match_1 : end_match_2);
3779
3780                   for (mcnt = 1; mcnt < num_regs; mcnt++)
3781                     {
3782                       regstart[mcnt] = best_regstart[mcnt];
3783                       regend[mcnt] = best_regend[mcnt];
3784                     }
3785                 }
3786             } /* d != end_match_2 */
3787
3788         succeed_label:
3789           DEBUG_PRINT1 ("Accepting match.\n");
3790
3791           /* If caller wants register contents data back, do it.  */
3792           if (regs && !bufp->no_sub)
3793             {
3794               /* Have the register data arrays been allocated?  */
3795               if (bufp->regs_allocated == REGS_UNALLOCATED)
3796                 { /* No.  So allocate them with malloc.  We need one
3797                      extra element beyond `num_regs' for the `-1' marker
3798                      GNU code uses.  */
3799                   regs->num_regs = MAX (RE_NREGS, num_regs + 1);
3800                   regs->start = TALLOC (regs->num_regs, regoff_t);
3801                   regs->end = TALLOC (regs->num_regs, regoff_t);
3802                   if (regs->start == NULL || regs->end == NULL)
3803                     {
3804                       FREE_VARIABLES ();
3805                       return -2;
3806                     }
3807                   bufp->regs_allocated = REGS_REALLOCATE;
3808                 }
3809               else if (bufp->regs_allocated == REGS_REALLOCATE)
3810                 { /* Yes.  If we need more elements than were already
3811                      allocated, reallocate them.  If we need fewer, just
3812                      leave it alone.  */
3813                   if (regs->num_regs < num_regs + 1)
3814                     {
3815                       regs->num_regs = num_regs + 1;
3816                       RETALLOC (regs->start, regs->num_regs, regoff_t);
3817                       RETALLOC (regs->end, regs->num_regs, regoff_t);
3818                       if (regs->start == NULL || regs->end == NULL)
3819                         {
3820                           FREE_VARIABLES ();
3821                           return -2;
3822                         }
3823                     }
3824                 }
3825               else
3826                 {
3827                   /* These braces fend off a "empty body in an else-statement"
3828                      warning under GCC when assert expands to nothing.  */
3829                   assert (bufp->regs_allocated == REGS_FIXED);
3830                 }
3831
3832               /* Convert the pointer data in `regstart' and `regend' to
3833                  indices.  Register zero has to be set differently,
3834                  since we haven't kept track of any info for it.  */
3835               if (regs->num_regs > 0)
3836                 {
3837                   regs->start[0] = pos;
3838                   regs->end[0] = (MATCHING_IN_FIRST_STRING
3839                                   ? ((regoff_t) (d - string1))
3840                                   : ((regoff_t) (d - string2 + size1)));
3841                 }
3842               
3843               /* Go through the first `min (num_regs, regs->num_regs)'
3844                  registers, since that is all we initialized.  */
3845               for (mcnt = 1; mcnt < MIN (num_regs, regs->num_regs); mcnt++)
3846                 {
3847                   if (REG_UNSET (regstart[mcnt]) || REG_UNSET (regend[mcnt]))
3848                     regs->start[mcnt] = regs->end[mcnt] = -1;
3849                   else
3850                     {
3851                       regs->start[mcnt]
3852                         = (regoff_t) POINTER_TO_OFFSET (regstart[mcnt]);
3853                       regs->end[mcnt]
3854                         = (regoff_t) POINTER_TO_OFFSET (regend[mcnt]);
3855                     }
3856                 }
3857               
3858               /* If the regs structure we return has more elements than
3859                  were in the pattern, set the extra elements to -1.  If
3860                  we (re)allocated the registers, this is the case,
3861                  because we always allocate enough to have at least one
3862                  -1 at the end.  */
3863               for (mcnt = num_regs; mcnt < regs->num_regs; mcnt++)
3864                 regs->start[mcnt] = regs->end[mcnt] = -1;
3865             } /* regs && !bufp->no_sub */
3866
3867           DEBUG_PRINT4 ("%u failure points pushed, %u popped (%u remain).\n",
3868                         nfailure_points_pushed, nfailure_points_popped,
3869                         nfailure_points_pushed - nfailure_points_popped);
3870           DEBUG_PRINT2 ("%u registers pushed.\n", num_regs_pushed);
3871
3872           mcnt = d - pos - (MATCHING_IN_FIRST_STRING 
3873                             ? string1 
3874                             : string2 - size1);
3875
3876           DEBUG_PRINT2 ("Returning %d from re_match_2.\n", mcnt);
3877
3878           FREE_VARIABLES ();
3879           return mcnt;
3880         }
3881
3882       /* Otherwise match next pattern command.  */
3883       switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
3884         {
3885         /* Ignore these.  Used to ignore the n of succeed_n's which
3886            currently have n == 0.  */
3887         case no_op:
3888           DEBUG_PRINT1 ("EXECUTING no_op.\n");
3889           break;
3890
3891         case succeed:
3892           DEBUG_PRINT1 ("EXECUTING succeed.\n");
3893           goto succeed_label;
3894
3895         /* Match the next n pattern characters exactly.  The following
3896            byte in the pattern defines n, and the n bytes after that
3897            are the characters to match.  */
3898         case exactn:
3899           mcnt = *p++;
3900           DEBUG_PRINT2 ("EXECUTING exactn %d.\n", mcnt);
3901
3902           /* This is written out as an if-else so we don't waste time
3903              testing `translate' inside the loop.  */
3904           if (translate)
3905             {
3906               do
3907                 {
3908                   PREFETCH ();
3909                   if (translate[(unsigned char) *d++] != (char) *p++)
3910                     goto fail;
3911                 }
3912               while (--mcnt);
3913             }
3914           else
3915             {
3916               do
3917                 {
3918                   PREFETCH ();
3919                   if (*d++ != (char) *p++) goto fail;
3920                 }
3921               while (--mcnt);
3922             }
3923           SET_REGS_MATCHED ();
3924           break;
3925
3926
3927         /* Match any character except possibly a newline or a null.  */
3928         case anychar:
3929           DEBUG_PRINT1 ("EXECUTING anychar.\n");
3930
3931           PREFETCH ();
3932
3933           if ((!(bufp->syntax & RE_DOT_NEWLINE) && TRANSLATE (*d) == '\n')
3934               || (bufp->syntax & RE_DOT_NOT_NULL && TRANSLATE (*d) == '\000'))
3935             goto fail;
3936
3937           SET_REGS_MATCHED ();
3938           DEBUG_PRINT2 ("  Matched `%d'.\n", *d);
3939           d++;
3940           break;
3941
3942
3943         case charset:
3944         case charset_not:
3945           {
3946             register unsigned char c;
3947             boolean not = (re_opcode_t) *(p - 1) == charset_not;
3948
3949             DEBUG_PRINT2 ("EXECUTING charset%s.\n", not ? "_not" : "");
3950
3951             PREFETCH ();
3952             c = TRANSLATE (*d); /* The character to match.  */
3953
3954             /* Cast to `unsigned' instead of `unsigned char' in case the
3955                bit list is a full 32 bytes long.  */
3956             if (c < (unsigned) (*p * BYTEWIDTH)
3957                 && p[1 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
3958               not = !not;
3959
3960             p += 1 + *p;
3961
3962             if (!not) goto fail;
3963             
3964             SET_REGS_MATCHED ();
3965             d++;
3966             break;
3967           }
3968
3969
3970         /* The beginning of a group is represented by start_memory.
3971            The arguments are the register number in the next byte, and the
3972            number of groups inner to this one in the next.  The text
3973            matched within the group is recorded (in the internal
3974            registers data structure) under the register number.  */
3975         case start_memory:
3976           DEBUG_PRINT3 ("EXECUTING start_memory %d (%d):\n", *p, p[1]);
3977
3978           /* Find out if this group can match the empty string.  */
3979           p1 = p;               /* To send to group_match_null_string_p.  */
3980           
3981           if (REG_MATCH_NULL_STRING_P (reg_info[*p]) == MATCH_NULL_UNSET_VALUE)
3982             REG_MATCH_NULL_STRING_P (reg_info[*p]) 
3983               = group_match_null_string_p (&p1, pend, reg_info);
3984
3985           /* Save the position in the string where we were the last time
3986              we were at this open-group operator in case the group is
3987              operated upon by a repetition operator, e.g., with `(a*)*b'
3988              against `ab'; then we want to ignore where we are now in
3989              the string in case this attempt to match fails.  */
3990           old_regstart[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
3991                              ? REG_UNSET (regstart[*p]) ? d : regstart[*p]
3992                              : regstart[*p];
3993           DEBUG_PRINT2 ("  old_regstart: %d\n", 
3994                          POINTER_TO_OFFSET (old_regstart[*p]));
3995
3996           regstart[*p] = d;
3997           DEBUG_PRINT2 ("  regstart: %d\n", POINTER_TO_OFFSET (regstart[*p]));
3998
3999           IS_ACTIVE (reg_info[*p]) = 1;
4000           MATCHED_SOMETHING (reg_info[*p]) = 0;
4001
4002           /* Clear this whenever we change the register activity status.  */
4003           set_regs_matched_done = 0;
4004           
4005           /* This is the new highest active register.  */
4006           highest_active_reg = *p;
4007           
4008           /* If nothing was active before, this is the new lowest active
4009              register.  */
4010           if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
4011             lowest_active_reg = *p;
4012
4013           /* Move past the register number and inner group count.  */
4014           p += 2;
4015           just_past_start_mem = p;
4016
4017           break;
4018
4019
4020         /* The stop_memory opcode represents the end of a group.  Its
4021            arguments are the same as start_memory's: the register
4022            number, and the number of inner groups.  */
4023         case stop_memory:
4024           DEBUG_PRINT3 ("EXECUTING stop_memory %d (%d):\n", *p, p[1]);
4025              
4026           /* We need to save the string position the last time we were at
4027              this close-group operator in case the group is operated
4028              upon by a repetition operator, e.g., with `((a*)*(b*)*)*'
4029              against `aba'; then we want to ignore where we are now in
4030              the string in case this attempt to match fails.  */
4031           old_regend[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
4032                            ? REG_UNSET (regend[*p]) ? d : regend[*p]
4033                            : regend[*p];
4034           DEBUG_PRINT2 ("      old_regend: %d\n", 
4035                          POINTER_TO_OFFSET (old_regend[*p]));
4036
4037           regend[*p] = d;
4038           DEBUG_PRINT2 ("      regend: %d\n", POINTER_TO_OFFSET (regend[*p]));
4039
4040           /* This register isn't active anymore.  */
4041           IS_ACTIVE (reg_info[*p]) = 0;
4042
4043           /* Clear this whenever we change the register activity status.  */
4044           set_regs_matched_done = 0;
4045
4046           /* If this was the only register active, nothing is active
4047              anymore.  */
4048           if (lowest_active_reg == highest_active_reg)
4049             {
4050               lowest_active_reg = NO_LOWEST_ACTIVE_REG;
4051               highest_active_reg = NO_HIGHEST_ACTIVE_REG;
4052             }
4053           else
4054             { /* We must scan for the new highest active register, since
4055                  it isn't necessarily one less than now: consider
4056                  (a(b)c(d(e)f)g).  When group 3 ends, after the f), the
4057                  new highest active register is 1.  */
4058               unsigned char r = *p - 1;
4059               while (r > 0 && !IS_ACTIVE (reg_info[r]))
4060                 r--;
4061               
4062               /* If we end up at register zero, that means that we saved
4063                  the registers as the result of an `on_failure_jump', not
4064                  a `start_memory', and we jumped to past the innermost
4065                  `stop_memory'.  For example, in ((.)*) we save
4066                  registers 1 and 2 as a result of the *, but when we pop
4067                  back to the second ), we are at the stop_memory 1.
4068                  Thus, nothing is active.  */
4069               if (r == 0)
4070                 {
4071                   lowest_active_reg = NO_LOWEST_ACTIVE_REG;
4072                   highest_active_reg = NO_HIGHEST_ACTIVE_REG;
4073                 }
4074               else
4075                 highest_active_reg = r;
4076             }
4077           
4078           /* If just failed to match something this time around with a
4079              group that's operated on by a repetition operator, try to
4080              force exit from the ``loop'', and restore the register
4081              information for this group that we had before trying this
4082              last match.  */
4083           if ((!MATCHED_SOMETHING (reg_info[*p])
4084                || just_past_start_mem == p - 1)
4085               && (p + 2) < pend)              
4086             {
4087               boolean is_a_jump_n = false;
4088               
4089               p1 = p + 2;
4090               mcnt = 0;
4091               switch ((re_opcode_t) *p1++)
4092                 {
4093                   case jump_n:
4094                     is_a_jump_n = true;
4095                   case pop_failure_jump:
4096                   case maybe_pop_jump:
4097                   case jump:
4098                   case dummy_failure_jump:
4099                     EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4100                     if (is_a_jump_n)
4101                       p1 += 2;
4102                     break;
4103                   
4104                   default:
4105                     /* do nothing */ ;
4106                 }
4107               p1 += mcnt;
4108         
4109               /* If the next operation is a jump backwards in the pattern
4110                  to an on_failure_jump right before the start_memory
4111                  corresponding to this stop_memory, exit from the loop
4112                  by forcing a failure after pushing on the stack the
4113                  on_failure_jump's jump in the pattern, and d.  */
4114               if (mcnt < 0 && (re_opcode_t) *p1 == on_failure_jump
4115                   && (re_opcode_t) p1[3] == start_memory && p1[4] == *p)
4116                 {
4117                   /* If this group ever matched anything, then restore
4118                      what its registers were before trying this last
4119                      failed match, e.g., with `(a*)*b' against `ab' for
4120                      regstart[1], and, e.g., with `((a*)*(b*)*)*'
4121                      against `aba' for regend[3].
4122                      
4123                      Also restore the registers for inner groups for,
4124                      e.g., `((a*)(b*))*' against `aba' (register 3 would
4125                      otherwise get trashed).  */
4126                      
4127                   if (EVER_MATCHED_SOMETHING (reg_info[*p]))
4128                     {
4129                       unsigned r; 
4130         
4131                       EVER_MATCHED_SOMETHING (reg_info[*p]) = 0;
4132                       
4133                       /* Restore this and inner groups' (if any) registers.  */
4134                       for (r = *p; r < *p + *(p + 1); r++)
4135                         {
4136                           regstart[r] = old_regstart[r];
4137
4138                           /* xx why this test?  */
4139                           if (old_regend[r] >= regstart[r])
4140                             regend[r] = old_regend[r];
4141                         }     
4142                     }
4143                   p1++;
4144                   EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4145                   PUSH_FAILURE_POINT (p1 + mcnt, d, -2);
4146
4147                   goto fail;
4148                 }
4149             }
4150           
4151           /* Move past the register number and the inner group count.  */
4152           p += 2;
4153           break;
4154
4155
4156         /* \<digit> has been turned into a `duplicate' command which is
4157            followed by the numeric value of <digit> as the register number.  */
4158         case duplicate:
4159           {
4160             register const char *d2, *dend2;
4161             int regno = *p++;   /* Get which register to match against.  */
4162             DEBUG_PRINT2 ("EXECUTING duplicate %d.\n", regno);
4163
4164             /* Can't back reference a group which we've never matched.  */
4165             if (REG_UNSET (regstart[regno]) || REG_UNSET (regend[regno]))
4166               goto fail;
4167               
4168             /* Where in input to try to start matching.  */
4169             d2 = regstart[regno];
4170             
4171             /* Where to stop matching; if both the place to start and
4172                the place to stop matching are in the same string, then
4173                set to the place to stop, otherwise, for now have to use
4174                the end of the first string.  */
4175
4176             dend2 = ((FIRST_STRING_P (regstart[regno]) 
4177                       == FIRST_STRING_P (regend[regno]))
4178                      ? regend[regno] : end_match_1);
4179             for (;;)
4180               {
4181                 /* If necessary, advance to next segment in register
4182                    contents.  */
4183                 while (d2 == dend2)
4184                   {
4185                     if (dend2 == end_match_2) break;
4186                     if (dend2 == regend[regno]) break;
4187
4188                     /* End of string1 => advance to string2. */
4189                     d2 = string2;
4190                     dend2 = regend[regno];
4191                   }
4192                 /* At end of register contents => success */
4193                 if (d2 == dend2) break;
4194
4195                 /* If necessary, advance to next segment in data.  */
4196                 PREFETCH ();
4197
4198                 /* How many characters left in this segment to match.  */
4199                 mcnt = dend - d;
4200                 
4201                 /* Want how many consecutive characters we can match in
4202                    one shot, so, if necessary, adjust the count.  */
4203                 if (mcnt > dend2 - d2)
4204                   mcnt = dend2 - d2;
4205                   
4206                 /* Compare that many; failure if mismatch, else move
4207                    past them.  */
4208                 if (translate 
4209                     ? bcmp_translate (d, d2, mcnt, translate) 
4210                     : bcmp (d, d2, mcnt))
4211                   goto fail;
4212                 d += mcnt, d2 += mcnt;
4213
4214                 /* Do this because we've match some characters.  */
4215                 SET_REGS_MATCHED ();
4216               }
4217           }
4218           break;
4219
4220
4221         /* begline matches the empty string at the beginning of the string
4222            (unless `not_bol' is set in `bufp'), and, if
4223            `newline_anchor' is set, after newlines.  */
4224         case begline:
4225           DEBUG_PRINT1 ("EXECUTING begline.\n");
4226           
4227           if (AT_STRINGS_BEG (d))
4228             {
4229               if (!bufp->not_bol) break;
4230             }
4231           else if (d[-1] == '\n' && bufp->newline_anchor)
4232             {
4233               break;
4234             }
4235           /* In all other cases, we fail.  */
4236           goto fail;
4237
4238
4239         /* endline is the dual of begline.  */
4240         case endline:
4241           DEBUG_PRINT1 ("EXECUTING endline.\n");
4242
4243           if (AT_STRINGS_END (d))
4244             {
4245               if (!bufp->not_eol) break;
4246             }
4247           
4248           /* We have to ``prefetch'' the next character.  */
4249           else if ((d == end1 ? *string2 : *d) == '\n'
4250                    && bufp->newline_anchor)
4251             {
4252               break;
4253             }
4254           goto fail;
4255
4256
4257         /* Match at the very beginning of the data.  */
4258         case begbuf:
4259           DEBUG_PRINT1 ("EXECUTING begbuf.\n");
4260           if (AT_STRINGS_BEG (d))
4261             break;
4262           goto fail;
4263
4264
4265         /* Match at the very end of the data.  */
4266         case endbuf:
4267           DEBUG_PRINT1 ("EXECUTING endbuf.\n");
4268           if (AT_STRINGS_END (d))
4269             break;
4270           goto fail;
4271
4272
4273         /* on_failure_keep_string_jump is used to optimize `.*\n'.  It
4274            pushes NULL as the value for the string on the stack.  Then
4275            `pop_failure_point' will keep the current value for the
4276            string, instead of restoring it.  To see why, consider
4277            matching `foo\nbar' against `.*\n'.  The .* matches the foo;
4278            then the . fails against the \n.  But the next thing we want
4279            to do is match the \n against the \n; if we restored the
4280            string value, we would be back at the foo.
4281            
4282            Because this is used only in specific cases, we don't need to
4283            check all the things that `on_failure_jump' does, to make
4284            sure the right things get saved on the stack.  Hence we don't
4285            share its code.  The only reason to push anything on the
4286            stack at all is that otherwise we would have to change
4287            `anychar's code to do something besides goto fail in this
4288            case; that seems worse than this.  */
4289         case on_failure_keep_string_jump:
4290           DEBUG_PRINT1 ("EXECUTING on_failure_keep_string_jump");
4291           
4292           EXTRACT_NUMBER_AND_INCR (mcnt, p);
4293           DEBUG_PRINT3 (" %d (to 0x%x):\n", mcnt, p + mcnt);
4294
4295           PUSH_FAILURE_POINT (p + mcnt, NULL, -2);
4296           break;
4297
4298
4299         /* Uses of on_failure_jump:
4300         
4301            Each alternative starts with an on_failure_jump that points
4302            to the beginning of the next alternative.  Each alternative
4303            except the last ends with a jump that in effect jumps past
4304            the rest of the alternatives.  (They really jump to the
4305            ending jump of the following alternative, because tensioning
4306            these jumps is a hassle.)
4307
4308            Repeats start with an on_failure_jump that points past both
4309            the repetition text and either the following jump or
4310            pop_failure_jump back to this on_failure_jump.  */
4311         case on_failure_jump:
4312         on_failure:
4313           DEBUG_PRINT1 ("EXECUTING on_failure_jump");
4314
4315           EXTRACT_NUMBER_AND_INCR (mcnt, p);
4316           DEBUG_PRINT3 (" %d (to 0x%x)", mcnt, p + mcnt);
4317
4318           /* If this on_failure_jump comes right before a group (i.e.,
4319              the original * applied to a group), save the information
4320              for that group and all inner ones, so that if we fail back
4321              to this point, the group's information will be correct.
4322              For example, in \(a*\)*\1, we need the preceding group,
4323              and in \(\(a*\)b*\)\2, we need the inner group.  */
4324
4325           /* We can't use `p' to check ahead because we push
4326              a failure point to `p + mcnt' after we do this.  */
4327           p1 = p;
4328
4329           /* We need to skip no_op's before we look for the
4330              start_memory in case this on_failure_jump is happening as
4331              the result of a completed succeed_n, as in \(a\)\{1,3\}b\1
4332              against aba.  */
4333           while (p1 < pend && (re_opcode_t) *p1 == no_op)
4334             p1++;
4335
4336           if (p1 < pend && (re_opcode_t) *p1 == start_memory)
4337             {
4338               /* We have a new highest active register now.  This will
4339                  get reset at the start_memory we are about to get to,
4340                  but we will have saved all the registers relevant to
4341                  this repetition op, as described above.  */
4342               highest_active_reg = *(p1 + 1) + *(p1 + 2);
4343               if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
4344                 lowest_active_reg = *(p1 + 1);
4345             }
4346
4347           DEBUG_PRINT1 (":\n");
4348           PUSH_FAILURE_POINT (p + mcnt, d, -2);
4349           break;
4350
4351
4352         /* A smart repeat ends with `maybe_pop_jump'.
4353            We change it to either `pop_failure_jump' or `jump'.  */
4354         case maybe_pop_jump:
4355           EXTRACT_NUMBER_AND_INCR (mcnt, p);
4356           DEBUG_PRINT2 ("EXECUTING maybe_pop_jump %d.\n", mcnt);
4357           {
4358             register unsigned char *p2 = p;
4359
4360             /* Compare the beginning of the repeat with what in the
4361                pattern follows its end. If we can establish that there
4362                is nothing that they would both match, i.e., that we
4363                would have to backtrack because of (as in, e.g., `a*a')
4364                then we can change to pop_failure_jump, because we'll
4365                never have to backtrack.
4366                
4367                This is not true in the case of alternatives: in
4368                `(a|ab)*' we do need to backtrack to the `ab' alternative
4369                (e.g., if the string was `ab').  But instead of trying to
4370                detect that here, the alternative has put on a dummy
4371                failure point which is what we will end up popping.  */
4372
4373             /* Skip over open/close-group commands.
4374                If what follows this loop is a ...+ construct,
4375                look at what begins its body, since we will have to
4376                match at least one of that.  */
4377             while (1)
4378               {
4379                 if (p2 + 2 < pend
4380                     && ((re_opcode_t) *p2 == stop_memory
4381                         || (re_opcode_t) *p2 == start_memory))
4382                   p2 += 3;
4383                 else if (p2 + 6 < pend
4384                          && (re_opcode_t) *p2 == dummy_failure_jump)
4385                   p2 += 6;
4386                 else
4387                   break;
4388               }
4389
4390             p1 = p + mcnt;
4391             /* p1[0] ... p1[2] are the `on_failure_jump' corresponding
4392                to the `maybe_finalize_jump' of this case.  Examine what 
4393                follows.  */
4394
4395             /* If we're at the end of the pattern, we can change.  */
4396             if (p2 == pend)
4397               {
4398                 /* Consider what happens when matching ":\(.*\)"
4399                    against ":/".  I don't really understand this code
4400                    yet.  */
4401                 p[-3] = (unsigned char) pop_failure_jump;
4402                 DEBUG_PRINT1
4403                   ("  End of pattern: change to `pop_failure_jump'.\n");
4404               }
4405
4406             else if ((re_opcode_t) *p2 == exactn
4407                      || (bufp->newline_anchor && (re_opcode_t) *p2 == endline))
4408               {
4409                 register unsigned char c
4410                   = *p2 == (unsigned char) endline ? '\n' : p2[2];
4411
4412                 if ((re_opcode_t) p1[3] == exactn && p1[5] != c)
4413                   {
4414                     p[-3] = (unsigned char) pop_failure_jump;
4415                     DEBUG_PRINT3 ("  %c != %c => pop_failure_jump.\n",
4416                                   c, p1[5]);
4417                   }
4418                   
4419                 else if ((re_opcode_t) p1[3] == charset
4420                          || (re_opcode_t) p1[3] == charset_not)
4421                   {
4422                     int not = (re_opcode_t) p1[3] == charset_not;
4423                     
4424                     if (c < (unsigned char) (p1[4] * BYTEWIDTH)
4425                         && p1[5 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
4426                       not = !not;
4427
4428                     /* `not' is equal to 1 if c would match, which means
4429                         that we can't change to pop_failure_jump.  */
4430                     if (!not)
4431                       {
4432                         p[-3] = (unsigned char) pop_failure_jump;
4433                         DEBUG_PRINT1 ("  No match => pop_failure_jump.\n");
4434                       }
4435                   }
4436               }
4437             else if ((re_opcode_t) *p2 == charset)
4438               {
4439 #ifdef DEBUG
4440                 register unsigned char c
4441                   = *p2 == (unsigned char) endline ? '\n' : p2[2];
4442 #endif
4443
4444                 if ((re_opcode_t) p1[3] == exactn
4445                     && ! ((int) p2[1] * BYTEWIDTH > (int) p1[4]
4446                           && (p2[1 + p1[4] / BYTEWIDTH]
4447                               & (1 << (p1[4] % BYTEWIDTH)))))
4448                   {
4449                     p[-3] = (unsigned char) pop_failure_jump;
4450                     DEBUG_PRINT3 ("  %c != %c => pop_failure_jump.\n",
4451                                   c, p1[5]);
4452                   }
4453                   
4454                 else if ((re_opcode_t) p1[3] == charset_not)
4455                   {
4456                     int idx;
4457                     /* We win if the charset_not inside the loop
4458                        lists every character listed in the charset after.  */
4459                     for (idx = 0; idx < (int) p2[1]; idx++)
4460                       if (! (p2[2 + idx] == 0
4461                              || (idx < (int) p1[4]
4462                                  && ((p2[2 + idx] & ~ p1[5 + idx]) == 0))))
4463                         break;
4464
4465                     if (idx == p2[1])
4466                       {
4467                         p[-3] = (unsigned char) pop_failure_jump;
4468                         DEBUG_PRINT1 ("  No match => pop_failure_jump.\n");
4469                       }
4470                   }
4471                 else if ((re_opcode_t) p1[3] == charset)
4472                   {
4473                     int idx;
4474                     /* We win if the charset inside the loop
4475                        has no overlap with the one after the loop.  */
4476                     for (idx = 0;
4477                          idx < (int) p2[1] && idx < (int) p1[4];
4478                          idx++)
4479                       if ((p2[2 + idx] & p1[5 + idx]) != 0)
4480                         break;
4481
4482                     if (idx == p2[1] || idx == p1[4])
4483                       {
4484                         p[-3] = (unsigned char) pop_failure_jump;
4485                         DEBUG_PRINT1 ("  No match => pop_failure_jump.\n");
4486                       }
4487                   }
4488               }
4489           }
4490           p -= 2;               /* Point at relative address again.  */
4491           if ((re_opcode_t) p[-1] != pop_failure_jump)
4492             {
4493               p[-1] = (unsigned char) jump;
4494               DEBUG_PRINT1 ("  Match => jump.\n");
4495               goto unconditional_jump;
4496             }
4497         /* Note fall through.  */
4498
4499
4500         /* The end of a simple repeat has a pop_failure_jump back to
4501            its matching on_failure_jump, where the latter will push a
4502            failure point.  The pop_failure_jump takes off failure
4503            points put on by this pop_failure_jump's matching
4504            on_failure_jump; we got through the pattern to here from the
4505            matching on_failure_jump, so didn't fail.  */
4506         case pop_failure_jump:
4507           {
4508             /* We need to pass separate storage for the lowest and
4509                highest registers, even though we don't care about the
4510                actual values.  Otherwise, we will restore only one
4511                register from the stack, since lowest will == highest in
4512                `pop_failure_point'.  */
4513             unsigned dummy_low_reg, dummy_high_reg;
4514             unsigned char *pdummy;
4515             const char *sdummy;
4516
4517             DEBUG_PRINT1 ("EXECUTING pop_failure_jump.\n");
4518             POP_FAILURE_POINT (sdummy, pdummy,
4519                                dummy_low_reg, dummy_high_reg,
4520                                reg_dummy, reg_dummy, reg_info_dummy);
4521           }
4522           /* Note fall through.  */
4523
4524           
4525         /* Unconditionally jump (without popping any failure points).  */
4526         case jump:
4527         unconditional_jump:
4528           EXTRACT_NUMBER_AND_INCR (mcnt, p);    /* Get the amount to jump.  */
4529           DEBUG_PRINT2 ("EXECUTING jump %d ", mcnt);
4530           p += mcnt;                            /* Do the jump.  */
4531           DEBUG_PRINT2 ("(to 0x%x).\n", p);
4532           break;
4533
4534         
4535         /* We need this opcode so we can detect where alternatives end
4536            in `group_match_null_string_p' et al.  */
4537         case jump_past_alt:
4538           DEBUG_PRINT1 ("EXECUTING jump_past_alt.\n");
4539           goto unconditional_jump;
4540
4541
4542         /* Normally, the on_failure_jump pushes a failure point, which
4543            then gets popped at pop_failure_jump.  We will end up at
4544            pop_failure_jump, also, and with a pattern of, say, `a+', we
4545            are skipping over the on_failure_jump, so we have to push
4546            something meaningless for pop_failure_jump to pop.  */
4547         case dummy_failure_jump:
4548           DEBUG_PRINT1 ("EXECUTING dummy_failure_jump.\n");
4549           /* It doesn't matter what we push for the string here.  What
4550              the code at `fail' tests is the value for the pattern.  */
4551           PUSH_FAILURE_POINT (0, 0, -2);
4552           goto unconditional_jump;
4553
4554
4555         /* At the end of an alternative, we need to push a dummy failure
4556            point in case we are followed by a `pop_failure_jump', because
4557            we don't want the failure point for the alternative to be
4558            popped.  For example, matching `(a|ab)*' against `aab'
4559            requires that we match the `ab' alternative.  */
4560         case push_dummy_failure:
4561           DEBUG_PRINT1 ("EXECUTING push_dummy_failure.\n");
4562           /* See comments just above at `dummy_failure_jump' about the
4563              two zeroes.  */
4564           PUSH_FAILURE_POINT (0, 0, -2);
4565           break;
4566
4567         /* Have to succeed matching what follows at least n times.
4568            After that, handle like `on_failure_jump'.  */
4569         case succeed_n: 
4570           EXTRACT_NUMBER (mcnt, p + 2);
4571           DEBUG_PRINT2 ("EXECUTING succeed_n %d.\n", mcnt);
4572
4573           assert (mcnt >= 0);
4574           /* Originally, this is how many times we HAVE to succeed.  */
4575           if (mcnt > 0)
4576             {
4577                mcnt--;
4578                p += 2;
4579                STORE_NUMBER_AND_INCR (p, mcnt);
4580                DEBUG_PRINT3 ("  Setting 0x%x to %d.\n", p, mcnt);
4581             }
4582           else if (mcnt == 0)
4583             {
4584               DEBUG_PRINT2 ("  Setting two bytes from 0x%x to no_op.\n", p+2);
4585               p[2] = (unsigned char) no_op;
4586               p[3] = (unsigned char) no_op;
4587               goto on_failure;
4588             }
4589           break;
4590         
4591         case jump_n: 
4592           EXTRACT_NUMBER (mcnt, p + 2);
4593           DEBUG_PRINT2 ("EXECUTING jump_n %d.\n", mcnt);
4594
4595           /* Originally, this is how many times we CAN jump.  */
4596           if (mcnt)
4597             {
4598                mcnt--;
4599                STORE_NUMBER (p + 2, mcnt);
4600                goto unconditional_jump;      
4601             }
4602           /* If don't have to jump any more, skip over the rest of command.  */
4603           else      
4604             p += 4;                  
4605           break;
4606         
4607         case set_number_at:
4608           {
4609             DEBUG_PRINT1 ("EXECUTING set_number_at.\n");
4610
4611             EXTRACT_NUMBER_AND_INCR (mcnt, p);
4612             p1 = p + mcnt;
4613             EXTRACT_NUMBER_AND_INCR (mcnt, p);
4614             DEBUG_PRINT3 ("  Setting 0x%x to %d.\n", p1, mcnt);
4615             STORE_NUMBER (p1, mcnt);
4616             break;
4617           }
4618
4619         case wordbound:
4620           DEBUG_PRINT1 ("EXECUTING wordbound.\n");
4621           if (AT_WORD_BOUNDARY (d))
4622             break;
4623           goto fail;
4624
4625         case notwordbound:
4626           DEBUG_PRINT1 ("EXECUTING notwordbound.\n");
4627           if (AT_WORD_BOUNDARY (d))
4628             goto fail;
4629           break;
4630
4631         case wordbeg:
4632           DEBUG_PRINT1 ("EXECUTING wordbeg.\n");
4633           if (WORDCHAR_P (d) && (AT_STRINGS_BEG (d) || !WORDCHAR_P (d - 1)))
4634             break;
4635           goto fail;
4636
4637         case wordend:
4638           DEBUG_PRINT1 ("EXECUTING wordend.\n");
4639           if (!AT_STRINGS_BEG (d) && WORDCHAR_P (d - 1)
4640               && (!WORDCHAR_P (d) || AT_STRINGS_END (d)))
4641             break;
4642           goto fail;
4643
4644 #ifdef emacs
4645         case before_dot:
4646           DEBUG_PRINT1 ("EXECUTING before_dot.\n");
4647           if (PTR_CHAR_POS ((unsigned char *) d) >= point)
4648             goto fail;
4649           break;
4650   
4651         case at_dot:
4652           DEBUG_PRINT1 ("EXECUTING at_dot.\n");
4653           if (PTR_CHAR_POS ((unsigned char *) d) != point)
4654             goto fail;
4655           break;
4656   
4657         case after_dot:
4658           DEBUG_PRINT1 ("EXECUTING after_dot.\n");
4659           if (PTR_CHAR_POS ((unsigned char *) d) <= point)
4660             goto fail;
4661           break;
4662 #if 0 /* not emacs19 */
4663         case at_dot:
4664           DEBUG_PRINT1 ("EXECUTING at_dot.\n");
4665           if (PTR_CHAR_POS ((unsigned char *) d) + 1 != point)
4666             goto fail;
4667           break;
4668 #endif /* not emacs19 */
4669
4670         case syntaxspec:
4671           DEBUG_PRINT2 ("EXECUTING syntaxspec %d.\n", mcnt);
4672           mcnt = *p++;
4673           goto matchsyntax;
4674
4675         case wordchar:
4676           DEBUG_PRINT1 ("EXECUTING Emacs wordchar.\n");
4677           mcnt = (int) Sword;
4678         matchsyntax:
4679           PREFETCH ();
4680           /* Can't use *d++ here; SYNTAX may be an unsafe macro.  */
4681           d++;
4682           if (SYNTAX (d[-1]) != (enum syntaxcode) mcnt)
4683             goto fail;
4684           SET_REGS_MATCHED ();
4685           break;
4686
4687         case notsyntaxspec:
4688           DEBUG_PRINT2 ("EXECUTING notsyntaxspec %d.\n", mcnt);
4689           mcnt = *p++;
4690           goto matchnotsyntax;
4691
4692         case notwordchar:
4693           DEBUG_PRINT1 ("EXECUTING Emacs notwordchar.\n");
4694           mcnt = (int) Sword;
4695         matchnotsyntax:
4696           PREFETCH ();
4697           /* Can't use *d++ here; SYNTAX may be an unsafe macro.  */
4698           d++;
4699           if (SYNTAX (d[-1]) == (enum syntaxcode) mcnt)
4700             goto fail;
4701           SET_REGS_MATCHED ();
4702           break;
4703
4704 #else /* not emacs */
4705         case wordchar:
4706           DEBUG_PRINT1 ("EXECUTING non-Emacs wordchar.\n");
4707           PREFETCH ();
4708           if (!WORDCHAR_P (d))
4709             goto fail;
4710           SET_REGS_MATCHED ();
4711           d++;
4712           break;
4713           
4714         case notwordchar:
4715           DEBUG_PRINT1 ("EXECUTING non-Emacs notwordchar.\n");
4716           PREFETCH ();
4717           if (WORDCHAR_P (d))
4718             goto fail;
4719           SET_REGS_MATCHED ();
4720           d++;
4721           break;
4722 #endif /* not emacs */
4723           
4724         default:
4725           abort ();
4726         }
4727       continue;  /* Successfully executed one pattern command; keep going.  */
4728
4729
4730     /* We goto here if a matching operation fails. */
4731     fail:
4732       if (!FAIL_STACK_EMPTY ())
4733         { /* A restart point is known.  Restore to that state.  */
4734           DEBUG_PRINT1 ("\nFAIL:\n");
4735           POP_FAILURE_POINT (d, p,
4736                              lowest_active_reg, highest_active_reg,
4737                              regstart, regend, reg_info);
4738
4739           /* If this failure point is a dummy, try the next one.  */
4740           if (!p)
4741             goto fail;
4742
4743           /* If we failed to the end of the pattern, don't examine *p.  */
4744           assert (p <= pend);
4745           if (p < pend)
4746             {
4747               boolean is_a_jump_n = false;
4748               
4749               /* If failed to a backwards jump that's part of a repetition
4750                  loop, need to pop this failure point and use the next one.  */
4751               switch ((re_opcode_t) *p)
4752                 {
4753                 case jump_n:
4754                   is_a_jump_n = true;
4755                 case maybe_pop_jump:
4756                 case pop_failure_jump:
4757                 case jump:
4758                   p1 = p + 1;
4759                   EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4760                   p1 += mcnt;   
4761
4762                   if ((is_a_jump_n && (re_opcode_t) *p1 == succeed_n)
4763                       || (!is_a_jump_n
4764                           && (re_opcode_t) *p1 == on_failure_jump))
4765                     goto fail;
4766                   break;
4767                 default:
4768                   /* do nothing */ ;
4769                 }
4770             }
4771
4772           if (d >= string1 && d <= end1)
4773             dend = end_match_1;
4774         }
4775       else
4776         break;   /* Matching at this starting point really fails.  */
4777     } /* for (;;) */
4778
4779   if (best_regs_set)
4780     goto restore_best_regs;
4781
4782   FREE_VARIABLES ();
4783
4784   return -1;                            /* Failure to match.  */
4785 } /* re_match_2 */
4786 \f
4787 /* Subroutine definitions for re_match_2.  */
4788
4789
4790 /* We are passed P pointing to a register number after a start_memory.
4791    
4792    Return true if the pattern up to the corresponding stop_memory can
4793    match the empty string, and false otherwise.
4794    
4795    If we find the matching stop_memory, sets P to point to one past its number.
4796    Otherwise, sets P to an undefined byte less than or equal to END.
4797
4798    We don't handle duplicates properly (yet).  */
4799
4800 static boolean
4801 group_match_null_string_p (p, end, reg_info)
4802     unsigned char **p, *end;
4803     register_info_type *reg_info;
4804 {
4805   int mcnt;
4806   /* Point to after the args to the start_memory.  */
4807   unsigned char *p1 = *p + 2;
4808   
4809   while (p1 < end)
4810     {
4811       /* Skip over opcodes that can match nothing, and return true or
4812          false, as appropriate, when we get to one that can't, or to the
4813          matching stop_memory.  */
4814       
4815       switch ((re_opcode_t) *p1)
4816         {
4817         /* Could be either a loop or a series of alternatives.  */
4818         case on_failure_jump:
4819           p1++;
4820           EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4821           
4822           /* If the next operation is not a jump backwards in the
4823              pattern.  */
4824
4825           if (mcnt >= 0)
4826             {
4827               /* Go through the on_failure_jumps of the alternatives,
4828                  seeing if any of the alternatives cannot match nothing.
4829                  The last alternative starts with only a jump,
4830                  whereas the rest start with on_failure_jump and end
4831                  with a jump, e.g., here is the pattern for `a|b|c':
4832
4833                  /on_failure_jump/0/6/exactn/1/a/jump_past_alt/0/6
4834                  /on_failure_jump/0/6/exactn/1/b/jump_past_alt/0/3
4835                  /exactn/1/c                                            
4836
4837                  So, we have to first go through the first (n-1)
4838                  alternatives and then deal with the last one separately.  */
4839
4840
4841               /* Deal with the first (n-1) alternatives, which start
4842                  with an on_failure_jump (see above) that jumps to right
4843                  past a jump_past_alt.  */
4844
4845               while ((re_opcode_t) p1[mcnt-3] == jump_past_alt)
4846                 {
4847                   /* `mcnt' holds how many bytes long the alternative
4848                      is, including the ending `jump_past_alt' and
4849                      its number.  */
4850
4851                   if (!alt_match_null_string_p (p1, p1 + mcnt - 3, 
4852                                                       reg_info))
4853                     return false;
4854
4855                   /* Move to right after this alternative, including the
4856                      jump_past_alt.  */
4857                   p1 += mcnt;   
4858
4859                   /* Break if it's the beginning of an n-th alternative
4860                      that doesn't begin with an on_failure_jump.  */
4861                   if ((re_opcode_t) *p1 != on_failure_jump)
4862                     break;
4863                 
4864                   /* Still have to check that it's not an n-th
4865                      alternative that starts with an on_failure_jump.  */
4866                   p1++;
4867                   EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4868                   if ((re_opcode_t) p1[mcnt-3] != jump_past_alt)
4869                     {
4870                       /* Get to the beginning of the n-th alternative.  */
4871                       p1 -= 3;
4872                       break;
4873                     }
4874                 }
4875
4876               /* Deal with the last alternative: go back and get number
4877                  of the `jump_past_alt' just before it.  `mcnt' contains
4878                  the length of the alternative.  */
4879               EXTRACT_NUMBER (mcnt, p1 - 2);
4880
4881               if (!alt_match_null_string_p (p1, p1 + mcnt, reg_info))
4882                 return false;
4883
4884               p1 += mcnt;       /* Get past the n-th alternative.  */
4885             } /* if mcnt > 0 */
4886           break;
4887
4888           
4889         case stop_memory:
4890           assert (p1[1] == **p);
4891           *p = p1 + 2;
4892           return true;
4893
4894         
4895         default: 
4896           if (!common_op_match_null_string_p (&p1, end, reg_info))
4897             return false;
4898         }
4899     } /* while p1 < end */
4900
4901   return false;
4902 } /* group_match_null_string_p */
4903
4904
4905 /* Similar to group_match_null_string_p, but doesn't deal with alternatives:
4906    It expects P to be the first byte of a single alternative and END one
4907    byte past the last. The alternative can contain groups.  */
4908    
4909 static boolean
4910 alt_match_null_string_p (p, end, reg_info)
4911     unsigned char *p, *end;
4912     register_info_type *reg_info;
4913 {
4914   int mcnt;
4915   unsigned char *p1 = p;
4916   
4917   while (p1 < end)
4918     {
4919       /* Skip over opcodes that can match nothing, and break when we get 
4920          to one that can't.  */
4921       
4922       switch ((re_opcode_t) *p1)
4923         {
4924         /* It's a loop.  */
4925         case on_failure_jump:
4926           p1++;
4927           EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4928           p1 += mcnt;
4929           break;
4930           
4931         default: 
4932           if (!common_op_match_null_string_p (&p1, end, reg_info))
4933             return false;
4934         }
4935     }  /* while p1 < end */
4936
4937   return true;
4938 } /* alt_match_null_string_p */
4939
4940
4941 /* Deals with the ops common to group_match_null_string_p and
4942    alt_match_null_string_p.  
4943    
4944    Sets P to one after the op and its arguments, if any.  */
4945
4946 static boolean
4947 common_op_match_null_string_p (p, end, reg_info)
4948     unsigned char **p, *end;
4949     register_info_type *reg_info;
4950 {
4951   int mcnt;
4952   boolean ret;
4953   int reg_no;
4954   unsigned char *p1 = *p;
4955
4956   switch ((re_opcode_t) *p1++)
4957     {
4958     case no_op:
4959     case begline:
4960     case endline:
4961     case begbuf:
4962     case endbuf:
4963     case wordbeg:
4964     case wordend:
4965     case wordbound:
4966     case notwordbound:
4967 #ifdef emacs
4968     case before_dot:
4969     case at_dot:
4970     case after_dot:
4971 #endif
4972       break;
4973
4974     case start_memory:
4975       reg_no = *p1;
4976       assert (reg_no > 0 && reg_no <= MAX_REGNUM);
4977       ret = group_match_null_string_p (&p1, end, reg_info);
4978       
4979       /* Have to set this here in case we're checking a group which
4980          contains a group and a back reference to it.  */
4981
4982       if (REG_MATCH_NULL_STRING_P (reg_info[reg_no]) == MATCH_NULL_UNSET_VALUE)
4983         REG_MATCH_NULL_STRING_P (reg_info[reg_no]) = ret;
4984
4985       if (!ret)
4986         return false;
4987       break;
4988           
4989     /* If this is an optimized succeed_n for zero times, make the jump.  */
4990     case jump:
4991       EXTRACT_NUMBER_AND_INCR (mcnt, p1);
4992       if (mcnt >= 0)
4993         p1 += mcnt;
4994       else
4995         return false;
4996       break;
4997
4998     case succeed_n:
4999       /* Get to the number of times to succeed.  */
5000       p1 += 2;          
5001       EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5002
5003       if (mcnt == 0)
5004         {
5005           p1 -= 4;
5006           EXTRACT_NUMBER_AND_INCR (mcnt, p1);
5007           p1 += mcnt;
5008         }
5009       else
5010         return false;
5011       break;
5012
5013     case duplicate: 
5014       if (!REG_MATCH_NULL_STRING_P (reg_info[*p1]))
5015         return false;
5016       break;
5017
5018     case set_number_at:
5019       p1 += 4;
5020
5021     default:
5022       /* All other opcodes mean we cannot match the empty string.  */
5023       return false;
5024   }
5025
5026   *p = p1;
5027   return true;
5028 } /* common_op_match_null_string_p */
5029
5030
5031 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
5032    bytes; nonzero otherwise.  */
5033    
5034 static int
5035 bcmp_translate (s1, s2, len, translate)
5036      unsigned char *s1, *s2;
5037      register int len;
5038      char *translate;
5039 {
5040   register unsigned char *p1 = s1, *p2 = s2;
5041   while (len)
5042     {
5043       if (translate[*p1++] != translate[*p2++]) return 1;
5044       len--;
5045     }
5046   return 0;
5047 }
5048 \f
5049 /* Entry points for GNU code.  */
5050
5051 /* re_compile_pattern is the GNU regular expression compiler: it
5052    compiles PATTERN (of length SIZE) and puts the result in BUFP.
5053    Returns 0 if the pattern was valid, otherwise an error string.
5054    
5055    Assumes the `allocated' (and perhaps `buffer') and `translate' fields
5056    are set in BUFP on entry.
5057    
5058    We call regex_compile to do the actual compilation.  */
5059
5060 const char *
5061 re_compile_pattern (pattern, length, bufp)
5062      const char *pattern;
5063      int length;
5064      struct re_pattern_buffer *bufp;
5065 {
5066   reg_errcode_t ret;
5067   
5068   /* GNU code is written to assume at least RE_NREGS registers will be set
5069      (and at least one extra will be -1).  */
5070   bufp->regs_allocated = REGS_UNALLOCATED;
5071   
5072   /* And GNU code determines whether or not to get register information
5073      by passing null for the REGS argument to re_match, etc., not by
5074      setting no_sub.  */
5075   bufp->no_sub = 0;
5076   
5077   /* Match anchors at newline.  */
5078   bufp->newline_anchor = 1;
5079   
5080   ret = regex_compile (pattern, length, re_syntax_options, bufp);
5081
5082   if (!ret)
5083     return NULL;
5084   return gettext (re_error_msgid[(int) ret]);
5085 }     
5086 \f
5087 /* Entry points compatible with 4.2 BSD regex library.  We don't define
5088    them unless specifically requested.  */
5089
5090 #ifdef _REGEX_RE_COMP
5091
5092 /* BSD has one and only one pattern buffer.  */
5093 static struct re_pattern_buffer re_comp_buf;
5094
5095 char *
5096 re_comp (s)
5097     const char *s;
5098 {
5099   reg_errcode_t ret;
5100   
5101   if (!s)
5102     {
5103       if (!re_comp_buf.buffer)
5104         return gettext ("No previous regular expression");
5105       return 0;
5106     }
5107
5108   if (!re_comp_buf.buffer)
5109     {
5110       re_comp_buf.buffer = (unsigned char *) malloc (200);
5111       if (re_comp_buf.buffer == NULL)
5112         return gettext (re_error_msgid[(int) REG_ESPACE]);
5113       re_comp_buf.allocated = 200;
5114
5115       re_comp_buf.fastmap = (char *) malloc (1 << BYTEWIDTH);
5116       if (re_comp_buf.fastmap == NULL)
5117         return gettext (re_error_msgid[(int) REG_ESPACE]);
5118     }
5119
5120   /* Since `re_exec' always passes NULL for the `regs' argument, we
5121      don't need to initialize the pattern buffer fields which affect it.  */
5122
5123   /* Match anchors at newlines.  */
5124   re_comp_buf.newline_anchor = 1;
5125
5126   ret = regex_compile (s, strlen (s), re_syntax_options, &re_comp_buf);
5127   
5128   if (!ret)
5129     return NULL;
5130
5131   /* Yes, we're discarding `const' here if !HAVE_LIBINTL.  */
5132   return (char *) gettext (re_error_msgid[(int) ret]);
5133 }
5134
5135
5136 int
5137 re_exec (s)
5138     const char *s;
5139 {
5140   const int len = strlen (s);
5141   return
5142     0 <= re_search (&re_comp_buf, s, len, 0, len, (struct re_registers *) 0);
5143 }
5144 #endif /* _REGEX_RE_COMP */
5145 \f
5146 /* POSIX.2 functions.  Don't define these for Emacs.  */
5147
5148 #ifndef emacs
5149
5150 /* regcomp takes a regular expression as a string and compiles it.
5151
5152    PREG is a regex_t *.  We do not expect any fields to be initialized,
5153    since POSIX says we shouldn't.  Thus, we set
5154
5155      `buffer' to the compiled pattern;
5156      `used' to the length of the compiled pattern;
5157      `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
5158        REG_EXTENDED bit in CFLAGS is set; otherwise, to
5159        RE_SYNTAX_POSIX_BASIC;
5160      `newline_anchor' to REG_NEWLINE being set in CFLAGS;
5161      `fastmap' and `fastmap_accurate' to zero;
5162      `re_nsub' to the number of subexpressions in PATTERN.
5163
5164    PATTERN is the address of the pattern string.
5165
5166    CFLAGS is a series of bits which affect compilation.
5167
5168      If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
5169      use POSIX basic syntax.
5170
5171      If REG_NEWLINE is set, then . and [^...] don't match newline.
5172      Also, regexec will try a match beginning after every newline.
5173
5174      If REG_ICASE is set, then we considers upper- and lowercase
5175      versions of letters to be equivalent when matching.
5176
5177      If REG_NOSUB is set, then when PREG is passed to regexec, that
5178      routine will report only success or failure, and nothing about the
5179      registers.
5180
5181    It returns 0 if it succeeds, nonzero if it doesn't.  (See regex.h for
5182    the return codes and their meanings.)  */
5183
5184 int
5185 regcomp (preg, pattern, cflags)
5186     regex_t *preg;
5187     const char *pattern; 
5188     int cflags;
5189 {
5190   reg_errcode_t ret;
5191   unsigned syntax
5192     = (cflags & REG_EXTENDED) ?
5193       RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC;
5194
5195   /* regex_compile will allocate the space for the compiled pattern.  */
5196   preg->buffer = 0;
5197   preg->allocated = 0;
5198   preg->used = 0;
5199   
5200   /* Don't bother to use a fastmap when searching.  This simplifies the
5201      REG_NEWLINE case: if we used a fastmap, we'd have to put all the
5202      characters after newlines into the fastmap.  This way, we just try
5203      every character.  */
5204   preg->fastmap = 0;
5205   
5206   if (cflags & REG_ICASE)
5207     {
5208       unsigned i;
5209       
5210       preg->translate = (char *) malloc (CHAR_SET_SIZE);
5211       if (preg->translate == NULL)
5212         return (int) REG_ESPACE;
5213
5214       /* Map uppercase characters to corresponding lowercase ones.  */
5215       for (i = 0; i < CHAR_SET_SIZE; i++)
5216         preg->translate[i] = ISUPPER (i) ? tolower (i) : i;
5217     }
5218   else
5219     preg->translate = NULL;
5220
5221   /* If REG_NEWLINE is set, newlines are treated differently.  */
5222   if (cflags & REG_NEWLINE)
5223     { /* REG_NEWLINE implies neither . nor [^...] match newline.  */
5224       syntax &= ~RE_DOT_NEWLINE;
5225       syntax |= RE_HAT_LISTS_NOT_NEWLINE;
5226       /* It also changes the matching behavior.  */
5227       preg->newline_anchor = 1;
5228     }
5229   else
5230     preg->newline_anchor = 0;
5231
5232   preg->no_sub = !!(cflags & REG_NOSUB);
5233
5234   /* POSIX says a null character in the pattern terminates it, so we 
5235      can use strlen here in compiling the pattern.  */
5236   ret = regex_compile (pattern, strlen (pattern), syntax, preg);
5237   
5238   /* POSIX doesn't distinguish between an unmatched open-group and an
5239      unmatched close-group: both are REG_EPAREN.  */
5240   if (ret == REG_ERPAREN) ret = REG_EPAREN;
5241   
5242   return (int) ret;
5243 }
5244
5245
5246 /* regexec searches for a given pattern, specified by PREG, in the
5247    string STRING.
5248    
5249    If NMATCH is zero or REG_NOSUB was set in the cflags argument to
5250    `regcomp', we ignore PMATCH.  Otherwise, we assume PMATCH has at
5251    least NMATCH elements, and we set them to the offsets of the
5252    corresponding matched substrings.
5253    
5254    EFLAGS specifies `execution flags' which affect matching: if
5255    REG_NOTBOL is set, then ^ does not match at the beginning of the
5256    string; if REG_NOTEOL is set, then $ does not match at the end.
5257    
5258    We return 0 if we find a match and REG_NOMATCH if not.  */
5259
5260 int
5261 regexec (preg, string, nmatch, pmatch, eflags)
5262     const regex_t *preg;
5263     const char *string; 
5264     size_t nmatch; 
5265     regmatch_t pmatch[]; 
5266     int eflags;
5267 {
5268   int ret;
5269   struct re_registers regs;
5270   regex_t private_preg;
5271   int len = strlen (string);
5272   boolean want_reg_info = !preg->no_sub && nmatch > 0;
5273
5274   private_preg = *preg;
5275   
5276   private_preg.not_bol = !!(eflags & REG_NOTBOL);
5277   private_preg.not_eol = !!(eflags & REG_NOTEOL);
5278   
5279   /* The user has told us exactly how many registers to return
5280      information about, via `nmatch'.  We have to pass that on to the
5281      matching routines.  */
5282   private_preg.regs_allocated = REGS_FIXED;
5283   
5284   if (want_reg_info)
5285     {
5286       regs.num_regs = nmatch;
5287       regs.start = TALLOC (nmatch, regoff_t);
5288       regs.end = TALLOC (nmatch, regoff_t);
5289       if (regs.start == NULL || regs.end == NULL)
5290         return (int) REG_NOMATCH;
5291     }
5292
5293   /* Perform the searching operation.  */
5294   ret = re_search (&private_preg, string, len,
5295                    /* start: */ 0, /* range: */ len,
5296                    want_reg_info ? &regs : (struct re_registers *) 0);
5297   
5298   /* Copy the register information to the POSIX structure.  */
5299   if (want_reg_info)
5300     {
5301       if (ret >= 0)
5302         {
5303           unsigned r;
5304
5305           for (r = 0; r < nmatch; r++)
5306             {
5307               pmatch[r].rm_so = regs.start[r];
5308               pmatch[r].rm_eo = regs.end[r];
5309             }
5310         }
5311
5312       /* If we needed the temporary register info, free the space now.  */
5313       free (regs.start);
5314       free (regs.end);
5315     }
5316
5317   /* We want zero return to mean success, unlike `re_search'.  */
5318   return ret >= 0 ? (int) REG_NOERROR : (int) REG_NOMATCH;
5319 }
5320
5321
5322 /* Returns a message corresponding to an error code, ERRCODE, returned
5323    from either regcomp or regexec.   We don't use PREG here.  */
5324
5325 size_t
5326 regerror (errcode, preg, errbuf, errbuf_size)
5327     int errcode;
5328     const regex_t *preg;
5329     char *errbuf;
5330     size_t errbuf_size;
5331 {
5332   const char *msg;
5333   size_t msg_size;
5334
5335   if (errcode < 0
5336       || errcode >= (sizeof (re_error_msgid) / sizeof (re_error_msgid[0])))
5337     /* Only error codes returned by the rest of the code should be passed 
5338        to this routine.  If we are given anything else, or if other regex
5339        code generates an invalid error code, then the program has a bug.
5340        Dump core so we can fix it.  */
5341     abort ();
5342
5343   msg = gettext (re_error_msgid[errcode]);
5344
5345   msg_size = strlen (msg) + 1; /* Includes the null.  */
5346   
5347   if (errbuf_size != 0)
5348     {
5349       if (msg_size > errbuf_size)
5350         {
5351           strncpy (errbuf, msg, errbuf_size - 1);
5352           errbuf[errbuf_size - 1] = 0;
5353         }
5354       else
5355         strcpy (errbuf, msg);
5356     }
5357
5358   return msg_size;
5359 }
5360
5361
5362 /* Free dynamically allocated space used by PREG.  */
5363
5364 void
5365 regfree (preg)
5366     regex_t *preg;
5367 {
5368   if (preg->buffer != NULL)
5369     free (preg->buffer);
5370   preg->buffer = NULL;
5371   
5372   preg->allocated = 0;
5373   preg->used = 0;
5374
5375   if (preg->fastmap != NULL)
5376     free (preg->fastmap);
5377   preg->fastmap = NULL;
5378   preg->fastmap_accurate = 0;
5379
5380   if (preg->translate != NULL)
5381     free (preg->translate);
5382   preg->translate = NULL;
5383 }
5384
5385 #endif /* not emacs  */
5386 \f
5387 /*
5388 Local variables:
5389 make-backup-files: t
5390 version-control: t
5391 trim-versions-without-asking: nil
5392 End:
5393 */