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