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