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