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