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