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