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