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