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