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