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