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