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