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