regex.c revision 131543
1218Sconklin/* Extended regular expression matching and search library,
2218Sconklin   version 0.12.
3126209Sache   (Implements POSIX draft P1003.2/D11.2, except for some of the
4218Sconklin   internationalization features.)
5131543Stjr   Copyright (C) 1993-1999, 2000, 2001 Free Software Foundation, Inc.
6218Sconklin
7126209Sache   The GNU C Library is free software; you can redistribute it and/or
8126209Sache   modify it under the terms of the GNU Library General Public License as
9126209Sache   published by the Free Software Foundation; either version 2 of the
10126209Sache   License, or (at your option) any later version.
11218Sconklin
12126209Sache   The GNU C Library is distributed in the hope that it will be useful,
13218Sconklin   but WITHOUT ANY WARRANTY; without even the implied warranty of
14126209Sache   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15126209Sache   Library General Public License for more details.
16218Sconklin
17126209Sache   You should have received a copy of the GNU Library General Public
18126209Sache   License along with the GNU C Library; see the file COPYING.LIB.  If not,
19126209Sache   write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20126209Sache   Boston, MA 02111-1307, USA.  */
21218Sconklin
22218Sconklin/* AIX requires this to be the first thing in the file. */
23126209Sache#if defined _AIX && !defined REGEX_MALLOC
24218Sconklin  #pragma alloca
25218Sconklin#endif
26218Sconklin
27126209Sache#undef	_GNU_SOURCE
28218Sconklin#define _GNU_SOURCE
29218Sconklin
30218Sconklin#ifdef HAVE_CONFIG_H
31126209Sache# include <config.h>
32218Sconklin#endif
33218Sconklin
34126209Sache#ifndef PARAMS
35126209Sache# if defined __GNUC__ || (defined __STDC__ && __STDC__)
36126209Sache#  define PARAMS(args) args
37126209Sache# else
38126209Sache#  define PARAMS(args) ()
39126209Sache# endif  /* GCC.  */
40126209Sache#endif  /* Not PARAMS.  */
41218Sconklin
42126209Sache#if defined STDC_HEADERS && !defined emacs
43126209Sache# include <stddef.h>
44218Sconklin#else
45126209Sache/* We need this for `regex.h', and perhaps for the Emacs include files.  */
46126209Sache# include <sys/types.h>
47218Sconklin#endif
48218Sconklin
49126209Sache#define WIDE_CHAR_SUPPORT (HAVE_WCTYPE_H && HAVE_WCHAR_H && HAVE_BTOWC)
50126209Sache
51126209Sache/* For platform which support the ISO C amendement 1 functionality we
52126209Sache   support user defined character classes.  */
53126209Sache#if defined _LIBC || WIDE_CHAR_SUPPORT
54126209Sache/* Solaris 2.5 has a bug: <wchar.h> must be included before <wctype.h>.  */
55126209Sache# include <wchar.h>
56126209Sache# include <wctype.h>
57218Sconklin#endif
58218Sconklin
59131543Stjr/* This is for multi byte string support.  */
60131543Stjr#ifdef MBS_SUPPORT
61131543Stjr# define CHAR_TYPE wchar_t
62131543Stjr# define US_CHAR_TYPE wchar_t/* unsigned character type */
63131543Stjr# define COMPILED_BUFFER_VAR wc_buffer
64131543Stjr# define OFFSET_ADDRESS_SIZE 1 /* the size which STORE_NUMBER macro use */
65131543Stjr# define CHAR_CLASS_SIZE ((__alignof__(wctype_t)+sizeof(wctype_t))/sizeof(CHAR_TYPE)+1)
66131543Stjr# define PUT_CHAR(c) \
67131543Stjr  do {									      \
68131543Stjr    if (MB_CUR_MAX == 1)						      \
69131543Stjr      putchar (c);							      \
70131543Stjr    else								      \
71131543Stjr      printf ("%C", (wint_t) c); /* Should we use wide stream??  */	      \
72131543Stjr  } while (0)
73131543Stjr# define TRUE 1
74131543Stjr# define FALSE 0
75131543Stjr#else
76131543Stjr# define CHAR_TYPE char
77131543Stjr# define US_CHAR_TYPE unsigned char /* unsigned character type */
78131543Stjr# define COMPILED_BUFFER_VAR bufp->buffer
79131543Stjr# define OFFSET_ADDRESS_SIZE 2
80131543Stjr# define PUT_CHAR(c) putchar (c)
81131543Stjr#endif /* MBS_SUPPORT */
82131543Stjr
83126209Sache#ifdef _LIBC
84126209Sache/* We have to keep the namespace clean.  */
85126209Sache# define regfree(preg) __regfree (preg)
86126209Sache# define regexec(pr, st, nm, pm, ef) __regexec (pr, st, nm, pm, ef)
87126209Sache# define regcomp(preg, pattern, cflags) __regcomp (preg, pattern, cflags)
88126209Sache# define regerror(errcode, preg, errbuf, errbuf_size) \
89126209Sache	__regerror(errcode, preg, errbuf, errbuf_size)
90126209Sache# define re_set_registers(bu, re, nu, st, en) \
91126209Sache	__re_set_registers (bu, re, nu, st, en)
92126209Sache# define re_match_2(bufp, string1, size1, string2, size2, pos, regs, stop) \
93126209Sache	__re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
94126209Sache# define re_match(bufp, string, size, pos, regs) \
95126209Sache	__re_match (bufp, string, size, pos, regs)
96126209Sache# define re_search(bufp, string, size, startpos, range, regs) \
97126209Sache	__re_search (bufp, string, size, startpos, range, regs)
98126209Sache# define re_compile_pattern(pattern, length, bufp) \
99126209Sache	__re_compile_pattern (pattern, length, bufp)
100126209Sache# define re_set_syntax(syntax) __re_set_syntax (syntax)
101126209Sache# define re_search_2(bufp, st1, s1, st2, s2, startpos, range, regs, stop) \
102126209Sache	__re_search_2 (bufp, st1, s1, st2, s2, startpos, range, regs, stop)
103126209Sache# define re_compile_fastmap(bufp) __re_compile_fastmap (bufp)
104218Sconklin
105131543Stjr# define btowc __btowc
106131543Stjr
107131543Stjr/* We are also using some library internals.  */
108131543Stjr# include <locale/localeinfo.h>
109131543Stjr# include <locale/elem-hash.h>
110131543Stjr# include <langinfo.h>
111131543Stjr# include <locale/coll-lookup.h>
112218Sconklin#endif
113218Sconklin
114131543Stjr/* This is for other GNU distributions with internationalized messages.  */
115131543Stjr#if HAVE_LIBINTL_H || defined _LIBC
116131543Stjr# include <libintl.h>
117131543Stjr# ifdef _LIBC
118131543Stjr#  undef gettext
119131543Stjr#  define gettext(msgid) __dcgettext ("libc", msgid, LC_MESSAGES)
120126209Sache# endif
121131543Stjr#else
122131543Stjr# define gettext(msgid) (msgid)
123126209Sache#endif
124218Sconklin
125131543Stjr#ifndef gettext_noop
126131543Stjr/* This define is so xgettext can find the internationalizable
127131543Stjr   strings.  */
128131543Stjr# define gettext_noop(String) String
129131543Stjr#endif
130131543Stjr
131126209Sache/* The `emacs' switch turns on certain matching commands
132126209Sache   that make sense only in Emacs. */
133126209Sache#ifdef emacs
134218Sconklin
135126209Sache# include "lisp.h"
136126209Sache# include "buffer.h"
137126209Sache# include "syntax.h"
138218Sconklin
139126209Sache#else  /* not emacs */
140218Sconklin
141126209Sache/* If we are not linking with Emacs proper,
142126209Sache   we can't use the relocating allocator
143126209Sache   even if config.h says that we can.  */
144126209Sache# undef REL_ALLOC
145218Sconklin
146126209Sache# if defined STDC_HEADERS || defined _LIBC
147126209Sache#  include <stdlib.h>
148126209Sache# else
149126209Sachechar *malloc ();
150126209Sachechar *realloc ();
151126209Sache# endif
152218Sconklin
153126209Sache/* When used in Emacs's lib-src, we need to get bzero and bcopy somehow.
154126209Sache   If nothing else has been done, use the method below.  */
155126209Sache# ifdef INHIBIT_STRING_HEADER
156126209Sache#  if !(defined HAVE_BZERO && defined HAVE_BCOPY)
157126209Sache#   if !defined bzero && !defined bcopy
158126209Sache#    undef INHIBIT_STRING_HEADER
159126209Sache#   endif
160126209Sache#  endif
161126209Sache# endif
162218Sconklin
163126209Sache/* This is the normal way of making sure we have a bcopy and a bzero.
164126209Sache   This is used in most programs--a few other programs avoid this
165126209Sache   by defining INHIBIT_STRING_HEADER.  */
166126209Sache# ifndef INHIBIT_STRING_HEADER
167126209Sache#  if defined HAVE_STRING_H || defined STDC_HEADERS || defined _LIBC
168126209Sache#   include <string.h>
169126209Sache#   ifndef bzero
170126209Sache#    ifndef _LIBC
171126209Sache#     define bzero(s, n)	(memset (s, '\0', n), (s))
172126209Sache#    else
173126209Sache#     define bzero(s, n)	__bzero (s, n)
174126209Sache#    endif
175126209Sache#   endif
176126209Sache#  else
177126209Sache#   include <strings.h>
178126209Sache#   ifndef memcmp
179126209Sache#    define memcmp(s1, s2, n)	bcmp (s1, s2, n)
180126209Sache#   endif
181126209Sache#   ifndef memcpy
182126209Sache#    define memcpy(d, s, n)	(bcopy (s, d, n), (d))
183126209Sache#   endif
184126209Sache#  endif
185126209Sache# endif
186218Sconklin
187126209Sache/* Define the syntax stuff for \<, \>, etc.  */
188218Sconklin
189126209Sache/* This must be nonzero for the wordchar and notwordchar pattern
190126209Sache   commands in re_match_2.  */
191126209Sache# ifndef Sword
192126209Sache#  define Sword 1
193126209Sache# endif
194218Sconklin
195126209Sache# ifdef SWITCH_ENUM_BUG
196126209Sache#  define SWITCH_ENUM_CAST(x) ((int)(x))
197126209Sache# else
198126209Sache#  define SWITCH_ENUM_CAST(x) (x)
199126209Sache# endif
200218Sconklin
201218Sconklin#endif /* not emacs */
202131543Stjr
203131543Stjr#if defined _LIBC || HAVE_LIMITS_H
204131543Stjr# include <limits.h>
205131543Stjr#endif
206131543Stjr
207131543Stjr#ifndef MB_LEN_MAX
208131543Stjr# define MB_LEN_MAX 1
209131543Stjr#endif
210218Sconklin
211218Sconklin/* Get the interface, including the syntax bits.  */
212126209Sache#include <regex.h>
213218Sconklin
214218Sconklin/* isalpha etc. are used for the character classes.  */
215218Sconklin#include <ctype.h>
216218Sconklin
217126209Sache/* Jim Meyering writes:
218126209Sache
219126209Sache   "... Some ctype macros are valid only for character codes that
220126209Sache   isascii says are ASCII (SGI's IRIX-4.0.5 is one such system --when
221126209Sache   using /bin/cc or gcc but without giving an ansi option).  So, all
222126209Sache   ctype uses should be through macros like ISPRINT...  If
223126209Sache   STDC_HEADERS is defined, then autoconf has verified that the ctype
224126209Sache   macros don't need to be guarded with references to isascii. ...
225126209Sache   Defining isascii to 1 should let any compiler worth its salt
226126209Sache   eliminate the && through constant folding."
227126209Sache   Solaris defines some of these symbols so we must undefine them first.  */
228126209Sache
229126209Sache#undef ISASCII
230126209Sache#if defined STDC_HEADERS || (!defined isascii && !defined HAVE_ISASCII)
231126209Sache# define ISASCII(c) 1
232126209Sache#else
233126209Sache# define ISASCII(c) isascii(c)
234218Sconklin#endif
235218Sconklin
236218Sconklin#ifdef isblank
237126209Sache# define ISBLANK(c) (ISASCII (c) && isblank (c))
238218Sconklin#else
239126209Sache# define ISBLANK(c) ((c) == ' ' || (c) == '\t')
240218Sconklin#endif
241218Sconklin#ifdef isgraph
242126209Sache# define ISGRAPH(c) (ISASCII (c) && isgraph (c))
243218Sconklin#else
244126209Sache# define ISGRAPH(c) (ISASCII (c) && isprint (c) && !isspace (c))
245218Sconklin#endif
246218Sconklin
247126209Sache#undef ISPRINT
248126209Sache#define ISPRINT(c) (ISASCII (c) && isprint (c))
249126209Sache#define ISDIGIT(c) (ISASCII (c) && isdigit (c))
250126209Sache#define ISALNUM(c) (ISASCII (c) && isalnum (c))
251126209Sache#define ISALPHA(c) (ISASCII (c) && isalpha (c))
252126209Sache#define ISCNTRL(c) (ISASCII (c) && iscntrl (c))
253126209Sache#define ISLOWER(c) (ISASCII (c) && islower (c))
254126209Sache#define ISPUNCT(c) (ISASCII (c) && ispunct (c))
255126209Sache#define ISSPACE(c) (ISASCII (c) && isspace (c))
256126209Sache#define ISUPPER(c) (ISASCII (c) && isupper (c))
257126209Sache#define ISXDIGIT(c) (ISASCII (c) && isxdigit (c))
258218Sconklin
259126209Sache#ifdef _tolower
260126209Sache# define TOLOWER(c) _tolower(c)
261126209Sache#else
262126209Sache# define TOLOWER(c) tolower(c)
263126209Sache#endif
264126209Sache
265218Sconklin#ifndef NULL
266126209Sache# define NULL (void *)0
267218Sconklin#endif
268218Sconklin
269218Sconklin/* We remove any previous definition of `SIGN_EXTEND_CHAR',
270218Sconklin   since ours (we hope) works properly with all combinations of
271218Sconklin   machines, compilers, `char' and `unsigned char' argument types.
272218Sconklin   (Per Bothner suggested the basic approach.)  */
273218Sconklin#undef SIGN_EXTEND_CHAR
274218Sconklin#if __STDC__
275126209Sache# define SIGN_EXTEND_CHAR(c) ((signed char) (c))
276218Sconklin#else  /* not __STDC__ */
277218Sconklin/* As in Harbison and Steele.  */
278126209Sache# define SIGN_EXTEND_CHAR(c) ((((unsigned char) (c)) ^ 128) - 128)
279218Sconklin#endif
280218Sconklin
281126209Sache#ifndef emacs
282126209Sache/* How many characters in the character set.  */
283126209Sache# define CHAR_SET_SIZE 256
284126209Sache
285126209Sache# ifdef SYNTAX_TABLE
286126209Sache
287126209Sacheextern char *re_syntax_table;
288126209Sache
289126209Sache# else /* not SYNTAX_TABLE */
290126209Sache
291126209Sachestatic char re_syntax_table[CHAR_SET_SIZE];
292126209Sache
293131543Stjrstatic void init_syntax_once PARAMS ((void));
294131543Stjr
295126209Sachestatic void
296126209Sacheinit_syntax_once ()
297126209Sache{
298126209Sache   register int c;
299126209Sache   static int done = 0;
300126209Sache
301126209Sache   if (done)
302126209Sache     return;
303126209Sache   bzero (re_syntax_table, sizeof re_syntax_table);
304126209Sache
305126209Sache   for (c = 0; c < CHAR_SET_SIZE; ++c)
306126209Sache     if (ISALNUM (c))
307126209Sache	re_syntax_table[c] = Sword;
308126209Sache
309126209Sache   re_syntax_table['_'] = Sword;
310126209Sache
311126209Sache   done = 1;
312126209Sache}
313126209Sache
314126209Sache# endif /* not SYNTAX_TABLE */
315126209Sache
316131543Stjr# define SYNTAX(c) re_syntax_table[(unsigned char) (c)]
317126209Sache
318126209Sache#endif /* emacs */
319126209Sache
320218Sconklin/* Should we use malloc or alloca?  If REGEX_MALLOC is not defined, we
321218Sconklin   use `alloca' instead of `malloc'.  This is because using malloc in
322218Sconklin   re_search* or re_match* could cause memory leaks when C-g is used in
323218Sconklin   Emacs; also, malloc is slower and causes storage fragmentation.  On
324126209Sache   the other hand, malloc is more portable, and easier to debug.
325126209Sache
326218Sconklin   Because we sometimes use alloca, some routines have to be macros,
327218Sconklin   not functions -- `alloca'-allocated space disappears at the end of the
328218Sconklin   function it is called in.  */
329218Sconklin
330218Sconklin#ifdef REGEX_MALLOC
331218Sconklin
332126209Sache# define REGEX_ALLOCATE malloc
333126209Sache# define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
334126209Sache# define REGEX_FREE free
335218Sconklin
336218Sconklin#else /* not REGEX_MALLOC  */
337218Sconklin
338218Sconklin/* Emacs already defines alloca, sometimes.  */
339126209Sache# ifndef alloca
340218Sconklin
341218Sconklin/* Make alloca work the best possible way.  */
342126209Sache#  ifdef __GNUC__
343126209Sache#   define alloca __builtin_alloca
344126209Sache#  else /* not __GNUC__ */
345126209Sache#   if HAVE_ALLOCA_H
346126209Sache#    include <alloca.h>
347126209Sache#   endif /* HAVE_ALLOCA_H */
348126209Sache#  endif /* not __GNUC__ */
349218Sconklin
350126209Sache# endif /* not alloca */
351218Sconklin
352126209Sache# define REGEX_ALLOCATE alloca
353218Sconklin
354218Sconklin/* Assumes a `char *destination' variable.  */
355126209Sache# define REGEX_REALLOCATE(source, osize, nsize)				\
356218Sconklin  (destination = (char *) alloca (nsize),				\
357126209Sache   memcpy (destination, source, osize))
358218Sconklin
359126209Sache/* No need to do anything to free, after alloca.  */
360126209Sache# define REGEX_FREE(arg) ((void)0) /* Do nothing!  But inhibit gcc warning.  */
361126209Sache
362218Sconklin#endif /* not REGEX_MALLOC */
363218Sconklin
364126209Sache/* Define how to allocate the failure stack.  */
365218Sconklin
366126209Sache#if defined REL_ALLOC && defined REGEX_MALLOC
367126209Sache
368126209Sache# define REGEX_ALLOCATE_STACK(size)				\
369126209Sache  r_alloc (&failure_stack_ptr, (size))
370126209Sache# define REGEX_REALLOCATE_STACK(source, osize, nsize)		\
371126209Sache  r_re_alloc (&failure_stack_ptr, (nsize))
372126209Sache# define REGEX_FREE_STACK(ptr)					\
373126209Sache  r_alloc_free (&failure_stack_ptr)
374126209Sache
375126209Sache#else /* not using relocating allocator */
376126209Sache
377126209Sache# ifdef REGEX_MALLOC
378126209Sache
379126209Sache#  define REGEX_ALLOCATE_STACK malloc
380126209Sache#  define REGEX_REALLOCATE_STACK(source, osize, nsize) realloc (source, nsize)
381126209Sache#  define REGEX_FREE_STACK free
382126209Sache
383126209Sache# else /* not REGEX_MALLOC */
384126209Sache
385126209Sache#  define REGEX_ALLOCATE_STACK alloca
386126209Sache
387126209Sache#  define REGEX_REALLOCATE_STACK(source, osize, nsize)			\
388126209Sache   REGEX_REALLOCATE (source, osize, nsize)
389126209Sache/* No need to explicitly free anything.  */
390126209Sache#  define REGEX_FREE_STACK(arg)
391126209Sache
392126209Sache# endif /* not REGEX_MALLOC */
393126209Sache#endif /* not using relocating allocator */
394126209Sache
395126209Sache
396218Sconklin/* True if `size1' is non-NULL and PTR is pointing anywhere inside
397218Sconklin   `string1' or just past its end.  This works if PTR is NULL, which is
398218Sconklin   a good thing.  */
399218Sconklin#define FIRST_STRING_P(ptr) 					\
400218Sconklin  (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
401218Sconklin
402218Sconklin/* (Re)Allocate N items of type T using malloc, or fail.  */
403218Sconklin#define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
404218Sconklin#define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
405126209Sache#define RETALLOC_IF(addr, n, t) \
406126209Sache  if (addr) RETALLOC((addr), (n), t); else (addr) = TALLOC ((n), t)
407218Sconklin#define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
408218Sconklin
409218Sconklin#define BYTEWIDTH 8 /* In bits.  */
410218Sconklin
411218Sconklin#define STREQ(s1, s2) ((strcmp (s1, s2) == 0))
412218Sconklin
413126209Sache#undef MAX
414126209Sache#undef MIN
415218Sconklin#define MAX(a, b) ((a) > (b) ? (a) : (b))
416218Sconklin#define MIN(a, b) ((a) < (b) ? (a) : (b))
417218Sconklin
418218Sconklintypedef char boolean;
419218Sconklin#define false 0
420218Sconklin#define true 1
421126209Sache
422126209Sachestatic int re_match_2_internal PARAMS ((struct re_pattern_buffer *bufp,
423126209Sache					const char *string1, int size1,
424126209Sache					const char *string2, int size2,
425126209Sache					int pos,
426126209Sache					struct re_registers *regs,
427126209Sache					int stop));
428218Sconklin
429218Sconklin/* These are the command codes that appear in compiled regular
430218Sconklin   expressions.  Some opcodes are followed by argument bytes.  A
431218Sconklin   command code can specify any interpretation whatsoever for its
432126209Sache   arguments.  Zero bytes may appear in the compiled regular expression.  */
433218Sconklin
434218Sconklintypedef enum
435218Sconklin{
436218Sconklin  no_op = 0,
437218Sconklin
438126209Sache  /* Succeed right away--no more backtracking.  */
439126209Sache  succeed,
440126209Sache
441218Sconklin        /* Followed by one byte giving n, then by n literal bytes.  */
442126209Sache  exactn,
443218Sconklin
444131543Stjr#ifdef MBS_SUPPORT
445131543Stjr	/* Same as exactn, but contains binary data.  */
446131543Stjr  exactn_bin,
447131543Stjr#endif
448131543Stjr
449218Sconklin        /* Matches any (more or less) character.  */
450218Sconklin  anychar,
451218Sconklin
452218Sconklin        /* Matches any one char belonging to specified set.  First
453218Sconklin           following byte is number of bitmap bytes.  Then come bytes
454218Sconklin           for a bitmap saying which chars are in.  Bits in each byte
455218Sconklin           are ordered low-bit-first.  A character is in the set if its
456218Sconklin           bit is 1.  A character too large to have a bit in the map is
457218Sconklin           automatically not in the set.  */
458131543Stjr        /* ifdef MBS_SUPPORT, following element is length of character
459131543Stjr	   classes, length of collating symbols, length of equivalence
460131543Stjr	   classes, length of character ranges, and length of characters.
461131543Stjr	   Next, character class element, collating symbols elements,
462131543Stjr	   equivalence class elements, range elements, and character
463131543Stjr	   elements follow.
464131543Stjr	   See regex_compile function.  */
465218Sconklin  charset,
466218Sconklin
467218Sconklin        /* Same parameters as charset, but match any character that is
468218Sconklin           not one of those specified.  */
469218Sconklin  charset_not,
470218Sconklin
471218Sconklin        /* Start remembering the text that is matched, for storing in a
472218Sconklin           register.  Followed by one byte with the register number, in
473218Sconklin           the range 0 to one less than the pattern buffer's re_nsub
474218Sconklin           field.  Then followed by one byte with the number of groups
475218Sconklin           inner to this one.  (This last has to be part of the
476218Sconklin           start_memory only because we need it in the on_failure_jump
477218Sconklin           of re_match_2.)  */
478218Sconklin  start_memory,
479218Sconklin
480218Sconklin        /* Stop remembering the text that is matched and store it in a
481218Sconklin           memory register.  Followed by one byte with the register
482218Sconklin           number, in the range 0 to one less than `re_nsub' in the
483218Sconklin           pattern buffer, and one byte with the number of inner groups,
484218Sconklin           just like `start_memory'.  (We need the number of inner
485218Sconklin           groups here because we don't have any easy way of finding the
486218Sconklin           corresponding start_memory when we're at a stop_memory.)  */
487218Sconklin  stop_memory,
488218Sconklin
489218Sconklin        /* Match a duplicate of something remembered. Followed by one
490218Sconklin           byte containing the register number.  */
491218Sconklin  duplicate,
492218Sconklin
493218Sconklin        /* Fail unless at beginning of line.  */
494218Sconklin  begline,
495218Sconklin
496218Sconklin        /* Fail unless at end of line.  */
497218Sconklin  endline,
498218Sconklin
499218Sconklin        /* Succeeds if at beginning of buffer (if emacs) or at beginning
500218Sconklin           of string to be matched (if not).  */
501218Sconklin  begbuf,
502218Sconklin
503218Sconklin        /* Analogously, for end of buffer/string.  */
504218Sconklin  endbuf,
505126209Sache
506218Sconklin        /* Followed by two byte relative address to which to jump.  */
507126209Sache  jump,
508218Sconklin
509218Sconklin	/* Same as jump, but marks the end of an alternative.  */
510218Sconklin  jump_past_alt,
511218Sconklin
512218Sconklin        /* Followed by two-byte relative address of place to resume at
513218Sconklin           in case of failure.  */
514131543Stjr        /* ifdef MBS_SUPPORT, the size of address is 1.  */
515218Sconklin  on_failure_jump,
516126209Sache
517218Sconklin        /* Like on_failure_jump, but pushes a placeholder instead of the
518218Sconklin           current string position when executed.  */
519218Sconklin  on_failure_keep_string_jump,
520126209Sache
521218Sconklin        /* Throw away latest failure point and then jump to following
522218Sconklin           two-byte relative address.  */
523131543Stjr        /* ifdef MBS_SUPPORT, the size of address is 1.  */
524218Sconklin  pop_failure_jump,
525218Sconklin
526218Sconklin        /* Change to pop_failure_jump if know won't have to backtrack to
527218Sconklin           match; otherwise change to jump.  This is used to jump
528218Sconklin           back to the beginning of a repeat.  If what follows this jump
529218Sconklin           clearly won't match what the repeat does, such that we can be
530218Sconklin           sure that there is no use backtracking out of repetitions
531218Sconklin           already matched, then we change it to a pop_failure_jump.
532218Sconklin           Followed by two-byte address.  */
533131543Stjr        /* ifdef MBS_SUPPORT, the size of address is 1.  */
534218Sconklin  maybe_pop_jump,
535218Sconklin
536218Sconklin        /* Jump to following two-byte address, and push a dummy failure
537218Sconklin           point. This failure point will be thrown away if an attempt
538218Sconklin           is made to use it for a failure.  A `+' construct makes this
539218Sconklin           before the first repeat.  Also used as an intermediary kind
540218Sconklin           of jump when compiling an alternative.  */
541131543Stjr        /* ifdef MBS_SUPPORT, the size of address is 1.  */
542218Sconklin  dummy_failure_jump,
543218Sconklin
544218Sconklin	/* Push a dummy failure point and continue.  Used at the end of
545218Sconklin	   alternatives.  */
546218Sconklin  push_dummy_failure,
547218Sconklin
548218Sconklin        /* Followed by two-byte relative address and two-byte number n.
549218Sconklin           After matching N times, jump to the address upon failure.  */
550131543Stjr        /* ifdef MBS_SUPPORT, the size of address is 1.  */
551218Sconklin  succeed_n,
552218Sconklin
553218Sconklin        /* Followed by two-byte relative address, and two-byte number n.
554218Sconklin           Jump to the address N times, then fail.  */
555131543Stjr        /* ifdef MBS_SUPPORT, the size of address is 1.  */
556218Sconklin  jump_n,
557218Sconklin
558218Sconklin        /* Set the following two-byte relative address to the
559218Sconklin           subsequent two-byte number.  The address *includes* the two
560218Sconklin           bytes of number.  */
561131543Stjr        /* ifdef MBS_SUPPORT, the size of address is 1.  */
562218Sconklin  set_number_at,
563218Sconklin
564218Sconklin  wordchar,	/* Matches any word-constituent character.  */
565218Sconklin  notwordchar,	/* Matches any char that is not a word-constituent.  */
566218Sconklin
567218Sconklin  wordbeg,	/* Succeeds if at word beginning.  */
568218Sconklin  wordend,	/* Succeeds if at word end.  */
569218Sconklin
570218Sconklin  wordbound,	/* Succeeds if at a word boundary.  */
571218Sconklin  notwordbound	/* Succeeds if not at a word boundary.  */
572218Sconklin
573218Sconklin#ifdef emacs
574218Sconklin  ,before_dot,	/* Succeeds if before point.  */
575218Sconklin  at_dot,	/* Succeeds if at point.  */
576218Sconklin  after_dot,	/* Succeeds if after point.  */
577218Sconklin
578218Sconklin	/* Matches any character whose syntax is specified.  Followed by
579218Sconklin           a byte which contains a syntax code, e.g., Sword.  */
580218Sconklin  syntaxspec,
581218Sconklin
582218Sconklin	/* Matches any character whose syntax is not that specified.  */
583218Sconklin  notsyntaxspec
584218Sconklin#endif /* emacs */
585218Sconklin} re_opcode_t;
586218Sconklin
587218Sconklin/* Common operations on the compiled pattern.  */
588218Sconklin
589218Sconklin/* Store NUMBER in two contiguous bytes starting at DESTINATION.  */
590131543Stjr/* ifdef MBS_SUPPORT, we store NUMBER in 1 element.  */
591218Sconklin
592131543Stjr#ifdef MBS_SUPPORT
593131543Stjr# define STORE_NUMBER(destination, number)				\
594218Sconklin  do {									\
595131543Stjr    *(destination) = (US_CHAR_TYPE)(number);				\
596131543Stjr  } while (0)
597131543Stjr#else
598131543Stjr# define STORE_NUMBER(destination, number)				\
599131543Stjr  do {									\
600218Sconklin    (destination)[0] = (number) & 0377;					\
601218Sconklin    (destination)[1] = (number) >> 8;					\
602218Sconklin  } while (0)
603131543Stjr#endif /* MBS_SUPPORT */
604218Sconklin
605218Sconklin/* Same as STORE_NUMBER, except increment DESTINATION to
606218Sconklin   the byte after where the number is stored.  Therefore, DESTINATION
607218Sconklin   must be an lvalue.  */
608131543Stjr/* ifdef MBS_SUPPORT, we store NUMBER in 1 element.  */
609218Sconklin
610218Sconklin#define STORE_NUMBER_AND_INCR(destination, number)			\
611218Sconklin  do {									\
612218Sconklin    STORE_NUMBER (destination, number);					\
613131543Stjr    (destination) += OFFSET_ADDRESS_SIZE;				\
614218Sconklin  } while (0)
615218Sconklin
616218Sconklin/* Put into DESTINATION a number stored in two contiguous bytes starting
617218Sconklin   at SOURCE.  */
618131543Stjr/* ifdef MBS_SUPPORT, we store NUMBER in 1 element.  */
619218Sconklin
620131543Stjr#ifdef MBS_SUPPORT
621131543Stjr# define EXTRACT_NUMBER(destination, source)				\
622218Sconklin  do {									\
623131543Stjr    (destination) = *(source);						\
624131543Stjr  } while (0)
625131543Stjr#else
626131543Stjr# define EXTRACT_NUMBER(destination, source)				\
627131543Stjr  do {									\
628218Sconklin    (destination) = *(source) & 0377;					\
629218Sconklin    (destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8;		\
630218Sconklin  } while (0)
631131543Stjr#endif
632218Sconklin
633218Sconklin#ifdef DEBUG
634131543Stjrstatic void extract_number _RE_ARGS ((int *dest, US_CHAR_TYPE *source));
635218Sconklinstatic void
636218Sconklinextract_number (dest, source)
637218Sconklin    int *dest;
638131543Stjr    US_CHAR_TYPE *source;
639218Sconklin{
640131543Stjr#ifdef MBS_SUPPORT
641131543Stjr  *dest = *source;
642131543Stjr#else
643126209Sache  int temp = SIGN_EXTEND_CHAR (*(source + 1));
644218Sconklin  *dest = *source & 0377;
645218Sconklin  *dest += temp << 8;
646131543Stjr#endif
647218Sconklin}
648218Sconklin
649126209Sache# ifndef EXTRACT_MACROS /* To debug the macros.  */
650126209Sache#  undef EXTRACT_NUMBER
651126209Sache#  define EXTRACT_NUMBER(dest, src) extract_number (&dest, src)
652126209Sache# endif /* not EXTRACT_MACROS */
653218Sconklin
654218Sconklin#endif /* DEBUG */
655218Sconklin
656218Sconklin/* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
657218Sconklin   SOURCE must be an lvalue.  */
658218Sconklin
659218Sconklin#define EXTRACT_NUMBER_AND_INCR(destination, source)			\
660218Sconklin  do {									\
661218Sconklin    EXTRACT_NUMBER (destination, source);				\
662131543Stjr    (source) += OFFSET_ADDRESS_SIZE; 					\
663218Sconklin  } while (0)
664218Sconklin
665218Sconklin#ifdef DEBUG
666126209Sachestatic void extract_number_and_incr _RE_ARGS ((int *destination,
667131543Stjr					       US_CHAR_TYPE **source));
668218Sconklinstatic void
669218Sconklinextract_number_and_incr (destination, source)
670218Sconklin    int *destination;
671131543Stjr    US_CHAR_TYPE **source;
672126209Sache{
673218Sconklin  extract_number (destination, *source);
674131543Stjr  *source += OFFSET_ADDRESS_SIZE;
675218Sconklin}
676218Sconklin
677126209Sache# ifndef EXTRACT_MACROS
678126209Sache#  undef EXTRACT_NUMBER_AND_INCR
679126209Sache#  define EXTRACT_NUMBER_AND_INCR(dest, src) \
680218Sconklin  extract_number_and_incr (&dest, &src)
681126209Sache# endif /* not EXTRACT_MACROS */
682218Sconklin
683218Sconklin#endif /* DEBUG */
684218Sconklin
685218Sconklin/* If DEBUG is defined, Regex prints many voluminous messages about what
686218Sconklin   it is doing (if the variable `debug' is nonzero).  If linked with the
687218Sconklin   main program in `iregex.c', you can enter patterns and strings
688218Sconklin   interactively.  And if linked with the main program in `main.c' and
689218Sconklin   the other test files, you can run the already-written tests.  */
690218Sconklin
691218Sconklin#ifdef DEBUG
692218Sconklin
693218Sconklin/* We use standard I/O for debugging.  */
694126209Sache# include <stdio.h>
695218Sconklin
696218Sconklin/* It is useful to test things that ``must'' be true when debugging.  */
697126209Sache# include <assert.h>
698218Sconklin
699126209Sachestatic int debug;
700218Sconklin
701126209Sache# define DEBUG_STATEMENT(e) e
702126209Sache# define DEBUG_PRINT1(x) if (debug) printf (x)
703126209Sache# define DEBUG_PRINT2(x1, x2) if (debug) printf (x1, x2)
704126209Sache# define DEBUG_PRINT3(x1, x2, x3) if (debug) printf (x1, x2, x3)
705126209Sache# define DEBUG_PRINT4(x1, x2, x3, x4) if (debug) printf (x1, x2, x3, x4)
706126209Sache# define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) 				\
707218Sconklin  if (debug) print_partial_compiled_pattern (s, e)
708126209Sache# define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)			\
709218Sconklin  if (debug) print_double_string (w, s1, sz1, s2, sz2)
710218Sconklin
711218Sconklin
712218Sconklin/* Print the fastmap in human-readable form.  */
713218Sconklin
714218Sconklinvoid
715218Sconklinprint_fastmap (fastmap)
716218Sconklin    char *fastmap;
717218Sconklin{
718218Sconklin  unsigned was_a_range = 0;
719126209Sache  unsigned i = 0;
720126209Sache
721218Sconklin  while (i < (1 << BYTEWIDTH))
722218Sconklin    {
723218Sconklin      if (fastmap[i++])
724218Sconklin	{
725218Sconklin	  was_a_range = 0;
726126209Sache          putchar (i - 1);
727218Sconklin          while (i < (1 << BYTEWIDTH)  &&  fastmap[i])
728218Sconklin            {
729218Sconklin              was_a_range = 1;
730218Sconklin              i++;
731218Sconklin            }
732218Sconklin	  if (was_a_range)
733218Sconklin            {
734218Sconklin              printf ("-");
735126209Sache              putchar (i - 1);
736218Sconklin            }
737218Sconklin        }
738218Sconklin    }
739126209Sache  putchar ('\n');
740218Sconklin}
741218Sconklin
742218Sconklin
743218Sconklin/* Print a compiled pattern string in human-readable form, starting at
744218Sconklin   the START pointer into it and ending just before the pointer END.  */
745218Sconklin
746218Sconklinvoid
747218Sconklinprint_partial_compiled_pattern (start, end)
748131543Stjr    US_CHAR_TYPE *start;
749131543Stjr    US_CHAR_TYPE *end;
750218Sconklin{
751218Sconklin  int mcnt, mcnt2;
752131543Stjr  US_CHAR_TYPE *p1;
753131543Stjr  US_CHAR_TYPE *p = start;
754131543Stjr  US_CHAR_TYPE *pend = end;
755218Sconklin
756218Sconklin  if (start == NULL)
757218Sconklin    {
758218Sconklin      printf ("(null)\n");
759218Sconklin      return;
760218Sconklin    }
761126209Sache
762218Sconklin  /* Loop over pattern commands.  */
763218Sconklin  while (p < pend)
764218Sconklin    {
765131543Stjr#ifdef _LIBC
766131543Stjr      printf ("%td:\t", p - start);
767131543Stjr#else
768131543Stjr      printf ("%ld:\t", (long int) (p - start));
769131543Stjr#endif
770126209Sache
771218Sconklin      switch ((re_opcode_t) *p++)
772218Sconklin	{
773218Sconklin        case no_op:
774218Sconklin          printf ("/no_op");
775218Sconklin          break;
776218Sconklin
777218Sconklin	case exactn:
778218Sconklin	  mcnt = *p++;
779218Sconklin          printf ("/exactn/%d", mcnt);
780218Sconklin          do
781218Sconklin	    {
782218Sconklin              putchar ('/');
783131543Stjr	      PUT_CHAR (*p++);
784218Sconklin            }
785218Sconklin          while (--mcnt);
786218Sconklin          break;
787218Sconklin
788131543Stjr#ifdef MBS_SUPPORT
789131543Stjr	case exactn_bin:
790131543Stjr	  mcnt = *p++;
791131543Stjr	  printf ("/exactn_bin/%d", mcnt);
792131543Stjr          do
793131543Stjr	    {
794131543Stjr	      printf("/%lx", (long int) *p++);
795131543Stjr            }
796131543Stjr          while (--mcnt);
797131543Stjr          break;
798131543Stjr#endif /* MBS_SUPPORT */
799131543Stjr
800218Sconklin	case start_memory:
801218Sconklin          mcnt = *p++;
802131543Stjr          printf ("/start_memory/%d/%ld", mcnt, (long int) *p++);
803218Sconklin          break;
804218Sconklin
805218Sconklin	case stop_memory:
806218Sconklin          mcnt = *p++;
807131543Stjr	  printf ("/stop_memory/%d/%ld", mcnt, (long int) *p++);
808218Sconklin          break;
809218Sconklin
810218Sconklin	case duplicate:
811131543Stjr	  printf ("/duplicate/%ld", (long int) *p++);
812218Sconklin	  break;
813218Sconklin
814218Sconklin	case anychar:
815218Sconklin	  printf ("/anychar");
816218Sconklin	  break;
817218Sconklin
818218Sconklin	case charset:
819218Sconklin        case charset_not:
820218Sconklin          {
821131543Stjr#ifdef MBS_SUPPORT
822131543Stjr	    int i, length;
823131543Stjr	    wchar_t *workp = p;
824131543Stjr	    printf ("/charset [%s",
825131543Stjr	            (re_opcode_t) *(workp - 1) == charset_not ? "^" : "");
826131543Stjr	    p += 5;
827131543Stjr	    length = *workp++; /* the length of char_classes */
828131543Stjr	    for (i=0 ; i<length ; i++)
829131543Stjr	      printf("[:%lx:]", (long int) *p++);
830131543Stjr	    length = *workp++; /* the length of collating_symbol */
831131543Stjr	    for (i=0 ; i<length ;)
832131543Stjr	      {
833131543Stjr		printf("[.");
834131543Stjr		while(*p != 0)
835131543Stjr		  PUT_CHAR((i++,*p++));
836131543Stjr		i++,p++;
837131543Stjr		printf(".]");
838131543Stjr	      }
839131543Stjr	    length = *workp++; /* the length of equivalence_class */
840131543Stjr	    for (i=0 ; i<length ;)
841131543Stjr	      {
842131543Stjr		printf("[=");
843131543Stjr		while(*p != 0)
844131543Stjr		  PUT_CHAR((i++,*p++));
845131543Stjr		i++,p++;
846131543Stjr		printf("=]");
847131543Stjr	      }
848131543Stjr	    length = *workp++; /* the length of char_range */
849131543Stjr	    for (i=0 ; i<length ; i++)
850131543Stjr	      {
851131543Stjr		wchar_t range_start = *p++;
852131543Stjr		wchar_t range_end = *p++;
853131543Stjr		if (MB_CUR_MAX == 1)
854131543Stjr		  printf("%c-%c", (char) range_start, (char) range_end);
855131543Stjr		else
856131543Stjr		  printf("%C-%C", (wint_t) range_start, (wint_t) range_end);
857131543Stjr	      }
858131543Stjr	    length = *workp++; /* the length of char */
859131543Stjr	    for (i=0 ; i<length ; i++)
860131543Stjr	      if (MB_CUR_MAX == 1)
861131543Stjr		putchar (*p++);
862131543Stjr	      else
863131543Stjr		printf("%C", (wint_t) *p++);
864131543Stjr	    putchar (']');
865131543Stjr#else
866126209Sache            register int c, last = -100;
867126209Sache	    register int in_range = 0;
868218Sconklin
869126209Sache	    printf ("/charset [%s",
870126209Sache	            (re_opcode_t) *(p - 1) == charset_not ? "^" : "");
871126209Sache
872218Sconklin            assert (p + *p < pend);
873218Sconklin
874126209Sache            for (c = 0; c < 256; c++)
875126209Sache	      if (c / 8 < *p
876126209Sache		  && (p[1 + (c/8)] & (1 << (c % 8))))
877126209Sache		{
878126209Sache		  /* Are we starting a range?  */
879126209Sache		  if (last + 1 == c && ! in_range)
880126209Sache		    {
881126209Sache		      putchar ('-');
882126209Sache		      in_range = 1;
883126209Sache		    }
884126209Sache		  /* Have we broken a range?  */
885126209Sache		  else if (last + 1 != c && in_range)
886218Sconklin              {
887126209Sache		      putchar (last);
888126209Sache		      in_range = 0;
889126209Sache		    }
890218Sconklin
891126209Sache		  if (! in_range)
892126209Sache		    putchar (c);
893126209Sache
894126209Sache		  last = c;
895218Sconklin              }
896126209Sache
897126209Sache	    if (in_range)
898126209Sache	      putchar (last);
899126209Sache
900126209Sache	    putchar (']');
901126209Sache
902218Sconklin	    p += 1 + *p;
903131543Stjr#endif /* MBS_SUPPORT */
904218Sconklin	  }
905126209Sache	  break;
906218Sconklin
907218Sconklin	case begline:
908218Sconklin	  printf ("/begline");
909218Sconklin          break;
910218Sconklin
911218Sconklin	case endline:
912218Sconklin          printf ("/endline");
913218Sconklin          break;
914218Sconklin
915218Sconklin	case on_failure_jump:
916218Sconklin          extract_number_and_incr (&mcnt, &p);
917131543Stjr#ifdef _LIBC
918131543Stjr  	  printf ("/on_failure_jump to %td", p + mcnt - start);
919131543Stjr#else
920131543Stjr  	  printf ("/on_failure_jump to %ld", (long int) (p + mcnt - start));
921131543Stjr#endif
922218Sconklin          break;
923218Sconklin
924218Sconklin	case on_failure_keep_string_jump:
925218Sconklin          extract_number_and_incr (&mcnt, &p);
926131543Stjr#ifdef _LIBC
927131543Stjr  	  printf ("/on_failure_keep_string_jump to %td", p + mcnt - start);
928131543Stjr#else
929131543Stjr  	  printf ("/on_failure_keep_string_jump to %ld",
930131543Stjr		  (long int) (p + mcnt - start));
931131543Stjr#endif
932218Sconklin          break;
933218Sconklin
934218Sconklin	case dummy_failure_jump:
935218Sconklin          extract_number_and_incr (&mcnt, &p);
936131543Stjr#ifdef _LIBC
937131543Stjr  	  printf ("/dummy_failure_jump to %td", p + mcnt - start);
938131543Stjr#else
939131543Stjr  	  printf ("/dummy_failure_jump to %ld", (long int) (p + mcnt - start));
940131543Stjr#endif
941218Sconklin          break;
942218Sconklin
943218Sconklin	case push_dummy_failure:
944218Sconklin          printf ("/push_dummy_failure");
945218Sconklin          break;
946126209Sache
947218Sconklin        case maybe_pop_jump:
948218Sconklin          extract_number_and_incr (&mcnt, &p);
949131543Stjr#ifdef _LIBC
950131543Stjr  	  printf ("/maybe_pop_jump to %td", p + mcnt - start);
951131543Stjr#else
952131543Stjr  	  printf ("/maybe_pop_jump to %ld", (long int) (p + mcnt - start));
953131543Stjr#endif
954218Sconklin	  break;
955218Sconklin
956218Sconklin        case pop_failure_jump:
957218Sconklin	  extract_number_and_incr (&mcnt, &p);
958131543Stjr#ifdef _LIBC
959131543Stjr  	  printf ("/pop_failure_jump to %td", p + mcnt - start);
960131543Stjr#else
961131543Stjr  	  printf ("/pop_failure_jump to %ld", (long int) (p + mcnt - start));
962131543Stjr#endif
963126209Sache	  break;
964126209Sache
965218Sconklin        case jump_past_alt:
966218Sconklin	  extract_number_and_incr (&mcnt, &p);
967131543Stjr#ifdef _LIBC
968131543Stjr  	  printf ("/jump_past_alt to %td", p + mcnt - start);
969131543Stjr#else
970131543Stjr  	  printf ("/jump_past_alt to %ld", (long int) (p + mcnt - start));
971131543Stjr#endif
972126209Sache	  break;
973126209Sache
974218Sconklin        case jump:
975218Sconklin	  extract_number_and_incr (&mcnt, &p);
976131543Stjr#ifdef _LIBC
977131543Stjr  	  printf ("/jump to %td", p + mcnt - start);
978131543Stjr#else
979131543Stjr  	  printf ("/jump to %ld", (long int) (p + mcnt - start));
980131543Stjr#endif
981218Sconklin	  break;
982218Sconklin
983126209Sache        case succeed_n:
984218Sconklin          extract_number_and_incr (&mcnt, &p);
985126209Sache	  p1 = p + mcnt;
986218Sconklin          extract_number_and_incr (&mcnt2, &p);
987131543Stjr#ifdef _LIBC
988131543Stjr	  printf ("/succeed_n to %td, %d times", p1 - start, mcnt2);
989131543Stjr#else
990131543Stjr	  printf ("/succeed_n to %ld, %d times",
991131543Stjr		  (long int) (p1 - start), mcnt2);
992131543Stjr#endif
993218Sconklin          break;
994126209Sache
995126209Sache        case jump_n:
996218Sconklin          extract_number_and_incr (&mcnt, &p);
997126209Sache	  p1 = p + mcnt;
998218Sconklin          extract_number_and_incr (&mcnt2, &p);
999126209Sache	  printf ("/jump_n to %d, %d times", p1 - start, mcnt2);
1000218Sconklin          break;
1001126209Sache
1002126209Sache        case set_number_at:
1003218Sconklin          extract_number_and_incr (&mcnt, &p);
1004126209Sache	  p1 = p + mcnt;
1005218Sconklin          extract_number_and_incr (&mcnt2, &p);
1006131543Stjr#ifdef _LIBC
1007131543Stjr	  printf ("/set_number_at location %td to %d", p1 - start, mcnt2);
1008131543Stjr#else
1009131543Stjr	  printf ("/set_number_at location %ld to %d",
1010131543Stjr		  (long int) (p1 - start), mcnt2);
1011131543Stjr#endif
1012218Sconklin          break;
1013126209Sache
1014218Sconklin        case wordbound:
1015218Sconklin	  printf ("/wordbound");
1016218Sconklin	  break;
1017218Sconklin
1018218Sconklin	case notwordbound:
1019218Sconklin	  printf ("/notwordbound");
1020218Sconklin          break;
1021218Sconklin
1022218Sconklin	case wordbeg:
1023218Sconklin	  printf ("/wordbeg");
1024218Sconklin	  break;
1025126209Sache
1026218Sconklin	case wordend:
1027218Sconklin	  printf ("/wordend");
1028131543Stjr	  break;
1029126209Sache
1030126209Sache# ifdef emacs
1031218Sconklin	case before_dot:
1032218Sconklin	  printf ("/before_dot");
1033218Sconklin          break;
1034218Sconklin
1035218Sconklin	case at_dot:
1036218Sconklin	  printf ("/at_dot");
1037218Sconklin          break;
1038218Sconklin
1039218Sconklin	case after_dot:
1040218Sconklin	  printf ("/after_dot");
1041218Sconklin          break;
1042218Sconklin
1043218Sconklin	case syntaxspec:
1044218Sconklin          printf ("/syntaxspec");
1045218Sconklin	  mcnt = *p++;
1046218Sconklin	  printf ("/%d", mcnt);
1047218Sconklin          break;
1048126209Sache
1049218Sconklin	case notsyntaxspec:
1050218Sconklin          printf ("/notsyntaxspec");
1051218Sconklin	  mcnt = *p++;
1052218Sconklin	  printf ("/%d", mcnt);
1053218Sconklin	  break;
1054126209Sache# endif /* emacs */
1055218Sconklin
1056218Sconklin	case wordchar:
1057218Sconklin	  printf ("/wordchar");
1058218Sconklin          break;
1059126209Sache
1060218Sconklin	case notwordchar:
1061218Sconklin	  printf ("/notwordchar");
1062218Sconklin          break;
1063218Sconklin
1064218Sconklin	case begbuf:
1065218Sconklin	  printf ("/begbuf");
1066218Sconklin          break;
1067218Sconklin
1068218Sconklin	case endbuf:
1069218Sconklin	  printf ("/endbuf");
1070218Sconklin          break;
1071218Sconklin
1072218Sconklin        default:
1073131543Stjr          printf ("?%ld", (long int) *(p-1));
1074218Sconklin	}
1075126209Sache
1076126209Sache      putchar ('\n');
1077218Sconklin    }
1078126209Sache
1079131543Stjr#ifdef _LIBC
1080131543Stjr  printf ("%td:\tend of pattern.\n", p - start);
1081131543Stjr#else
1082131543Stjr  printf ("%ld:\tend of pattern.\n", (long int) (p - start));
1083131543Stjr#endif
1084218Sconklin}
1085218Sconklin
1086218Sconklin
1087218Sconklinvoid
1088218Sconklinprint_compiled_pattern (bufp)
1089218Sconklin    struct re_pattern_buffer *bufp;
1090218Sconklin{
1091131543Stjr  US_CHAR_TYPE *buffer = (US_CHAR_TYPE*) bufp->buffer;
1092218Sconklin
1093131543Stjr  print_partial_compiled_pattern (buffer, buffer
1094131543Stjr				  + bufp->used / sizeof(US_CHAR_TYPE));
1095126209Sache  printf ("%ld bytes used/%ld bytes allocated.\n",
1096126209Sache	  bufp->used, bufp->allocated);
1097218Sconklin
1098218Sconklin  if (bufp->fastmap_accurate && bufp->fastmap)
1099218Sconklin    {
1100218Sconklin      printf ("fastmap: ");
1101218Sconklin      print_fastmap (bufp->fastmap);
1102218Sconklin    }
1103218Sconklin
1104131543Stjr#ifdef _LIBC
1105131543Stjr  printf ("re_nsub: %Zd\t", bufp->re_nsub);
1106131543Stjr#else
1107131543Stjr  printf ("re_nsub: %ld\t", (long int) bufp->re_nsub);
1108131543Stjr#endif
1109218Sconklin  printf ("regs_alloc: %d\t", bufp->regs_allocated);
1110218Sconklin  printf ("can_be_null: %d\t", bufp->can_be_null);
1111218Sconklin  printf ("newline_anchor: %d\n", bufp->newline_anchor);
1112218Sconklin  printf ("no_sub: %d\t", bufp->no_sub);
1113218Sconklin  printf ("not_bol: %d\t", bufp->not_bol);
1114218Sconklin  printf ("not_eol: %d\t", bufp->not_eol);
1115126209Sache  printf ("syntax: %lx\n", bufp->syntax);
1116218Sconklin  /* Perhaps we should print the translate table?  */
1117218Sconklin}
1118218Sconklin
1119218Sconklin
1120218Sconklinvoid
1121218Sconklinprint_double_string (where, string1, size1, string2, size2)
1122131543Stjr    const CHAR_TYPE *where;
1123131543Stjr    const CHAR_TYPE *string1;
1124131543Stjr    const CHAR_TYPE *string2;
1125218Sconklin    int size1;
1126218Sconklin    int size2;
1127218Sconklin{
1128126209Sache  int this_char;
1129126209Sache
1130218Sconklin  if (where == NULL)
1131218Sconklin    printf ("(null)");
1132218Sconklin  else
1133218Sconklin    {
1134218Sconklin      if (FIRST_STRING_P (where))
1135218Sconklin        {
1136218Sconklin          for (this_char = where - string1; this_char < size1; this_char++)
1137131543Stjr	    PUT_CHAR (string1[this_char]);
1138218Sconklin
1139126209Sache          where = string2;
1140218Sconklin        }
1141218Sconklin
1142218Sconklin      for (this_char = where - string2; this_char < size2; this_char++)
1143131543Stjr        PUT_CHAR (string2[this_char]);
1144218Sconklin    }
1145218Sconklin}
1146218Sconklin
1147126209Sachevoid
1148126209Sacheprintchar (c)
1149126209Sache     int c;
1150126209Sache{
1151126209Sache  putc (c, stderr);
1152126209Sache}
1153126209Sache
1154218Sconklin#else /* not DEBUG */
1155218Sconklin
1156126209Sache# undef assert
1157126209Sache# define assert(e)
1158218Sconklin
1159126209Sache# define DEBUG_STATEMENT(e)
1160126209Sache# define DEBUG_PRINT1(x)
1161126209Sache# define DEBUG_PRINT2(x1, x2)
1162126209Sache# define DEBUG_PRINT3(x1, x2, x3)
1163126209Sache# define DEBUG_PRINT4(x1, x2, x3, x4)
1164126209Sache# define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
1165126209Sache# define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
1166218Sconklin
1167218Sconklin#endif /* not DEBUG */
1168218Sconklin
1169131543Stjr#ifdef MBS_SUPPORT
1170131543Stjr/* This  convert a multibyte string to a wide character string.
1171131543Stjr   And write their correspondances to offset_buffer(see below)
1172131543Stjr   and write whether each wchar_t is binary data to is_binary.
1173131543Stjr   This assume invalid multibyte sequences as binary data.
1174131543Stjr   We assume offset_buffer and is_binary is already allocated
1175131543Stjr   enough space.  */
1176131543Stjr
1177131543Stjrstatic size_t convert_mbs_to_wcs (CHAR_TYPE *dest, const unsigned char* src,
1178131543Stjr				  size_t len, int *offset_buffer,
1179131543Stjr				  char *is_binary);
1180131543Stjrstatic size_t
1181131543Stjrconvert_mbs_to_wcs (dest, src, len, offset_buffer, is_binary)
1182131543Stjr     CHAR_TYPE *dest;
1183131543Stjr     const unsigned char* src;
1184131543Stjr     size_t len; /* the length of multibyte string.  */
1185131543Stjr
1186131543Stjr     /* It hold correspondances between src(char string) and
1187131543Stjr	dest(wchar_t string) for optimization.
1188131543Stjr	e.g. src  = "xxxyzz"
1189131543Stjr             dest = {'X', 'Y', 'Z'}
1190131543Stjr	      (each "xxx", "y" and "zz" represent one multibyte character
1191131543Stjr	       corresponding to 'X', 'Y' and 'Z'.)
1192131543Stjr	  offset_buffer = {0, 0+3("xxx"), 0+3+1("y"), 0+3+1+2("zz")}
1193131543Stjr	  	        = {0, 3, 4, 6}
1194131543Stjr     */
1195131543Stjr     int *offset_buffer;
1196131543Stjr     char *is_binary;
1197131543Stjr{
1198131543Stjr  wchar_t *pdest = dest;
1199131543Stjr  const unsigned char *psrc = src;
1200131543Stjr  size_t wc_count = 0;
1201131543Stjr
1202131543Stjr  if (MB_CUR_MAX == 1)
1203131543Stjr    { /* We don't need conversion.  */
1204131543Stjr      for ( ; wc_count < len ; ++wc_count)
1205131543Stjr	{
1206131543Stjr	  *pdest++ = *psrc++;
1207131543Stjr	  is_binary[wc_count] = FALSE;
1208131543Stjr	  offset_buffer[wc_count] = wc_count;
1209131543Stjr	}
1210131543Stjr      offset_buffer[wc_count] = wc_count;
1211131543Stjr    }
1212131543Stjr  else
1213131543Stjr    {
1214131543Stjr      /* We need conversion.  */
1215131543Stjr      mbstate_t mbs;
1216131543Stjr      int consumed;
1217131543Stjr      size_t mb_remain = len;
1218131543Stjr      size_t mb_count = 0;
1219131543Stjr
1220131543Stjr      /* Initialize the conversion state.  */
1221131543Stjr      memset (&mbs, 0, sizeof (mbstate_t));
1222131543Stjr
1223131543Stjr      offset_buffer[0] = 0;
1224131543Stjr      for( ; mb_remain > 0 ; ++wc_count, ++pdest, mb_remain -= consumed,
1225131543Stjr	     psrc += consumed)
1226131543Stjr	{
1227131543Stjr	  consumed = mbrtowc (pdest, psrc, mb_remain, &mbs);
1228131543Stjr
1229131543Stjr	  if (consumed <= 0)
1230131543Stjr	    /* failed to convert. maybe src contains binary data.
1231131543Stjr	       So we consume 1 byte manualy.  */
1232131543Stjr	    {
1233131543Stjr	      *pdest = *psrc;
1234131543Stjr	      consumed = 1;
1235131543Stjr	      is_binary[wc_count] = TRUE;
1236131543Stjr	    }
1237131543Stjr	  else
1238131543Stjr	    is_binary[wc_count] = FALSE;
1239131543Stjr	  /* In sjis encoding, we use yen sign as escape character in
1240131543Stjr	     place of reverse solidus. So we convert 0x5c(yen sign in
1241131543Stjr	     sjis) to not 0xa5(yen sign in UCS2) but 0x5c(reverse
1242131543Stjr	     solidus in UCS2).  */
1243131543Stjr	  if (consumed == 1 && (int) *psrc == 0x5c && (int) *pdest == 0xa5)
1244131543Stjr	    *pdest = (wchar_t) *psrc;
1245131543Stjr
1246131543Stjr	  offset_buffer[wc_count + 1] = mb_count += consumed;
1247131543Stjr	}
1248131543Stjr    }
1249131543Stjr
1250131543Stjr  return wc_count;
1251131543Stjr}
1252131543Stjr
1253131543Stjr#endif /* MBS_SUPPORT */
1254131543Stjr
1255218Sconklin/* Set by `re_set_syntax' to the current regexp syntax to recognize.  Can
1256218Sconklin   also be assigned to arbitrarily: each pattern buffer stores its own
1257218Sconklin   syntax, so it can be changed between regex compilations.  */
1258126209Sache/* This has no initializer because initialized variables in Emacs
1259126209Sache   become read-only after dumping.  */
1260126209Sachereg_syntax_t re_syntax_options;
1261218Sconklin
1262218Sconklin
1263218Sconklin/* Specify the precise syntax of regexps for compilation.  This provides
1264218Sconklin   for compatibility for various utilities which historically have
1265218Sconklin   different, incompatible syntaxes.
1266218Sconklin
1267218Sconklin   The argument SYNTAX is a bit mask comprised of the various bits
1268218Sconklin   defined in regex.h.  We return the old syntax.  */
1269218Sconklin
1270218Sconklinreg_syntax_t
1271218Sconklinre_set_syntax (syntax)
1272218Sconklin    reg_syntax_t syntax;
1273218Sconklin{
1274218Sconklin  reg_syntax_t ret = re_syntax_options;
1275126209Sache
1276218Sconklin  re_syntax_options = syntax;
1277126209Sache#ifdef DEBUG
1278126209Sache  if (syntax & RE_DEBUG)
1279126209Sache    debug = 1;
1280126209Sache  else if (debug) /* was on but now is not */
1281126209Sache    debug = 0;
1282126209Sache#endif /* DEBUG */
1283218Sconklin  return ret;
1284218Sconklin}
1285126209Sache#ifdef _LIBC
1286126209Sacheweak_alias (__re_set_syntax, re_set_syntax)
1287126209Sache#endif
1288218Sconklin
1289218Sconklin/* This table gives an error message for each of the error codes listed
1290126209Sache   in regex.h.  Obviously the order here has to be same as there.
1291126209Sache   POSIX doesn't require that we do anything for REG_NOERROR,
1292126209Sache   but why not be nice?  */
1293218Sconklin
1294131543Stjrstatic const char re_error_msgid[] =
1295131543Stjr  {
1296126209Sache#define REG_NOERROR_IDX	0
1297131543Stjr    gettext_noop ("Success")	/* REG_NOERROR */
1298131543Stjr    "\0"
1299126209Sache#define REG_NOMATCH_IDX (REG_NOERROR_IDX + sizeof "Success")
1300131543Stjr    gettext_noop ("No match")	/* REG_NOMATCH */
1301131543Stjr    "\0"
1302126209Sache#define REG_BADPAT_IDX	(REG_NOMATCH_IDX + sizeof "No match")
1303131543Stjr    gettext_noop ("Invalid regular expression") /* REG_BADPAT */
1304131543Stjr    "\0"
1305126209Sache#define REG_ECOLLATE_IDX (REG_BADPAT_IDX + sizeof "Invalid regular expression")
1306131543Stjr    gettext_noop ("Invalid collation character") /* REG_ECOLLATE */
1307131543Stjr    "\0"
1308126209Sache#define REG_ECTYPE_IDX	(REG_ECOLLATE_IDX + sizeof "Invalid collation character")
1309131543Stjr    gettext_noop ("Invalid character class name") /* REG_ECTYPE */
1310131543Stjr    "\0"
1311126209Sache#define REG_EESCAPE_IDX	(REG_ECTYPE_IDX + sizeof "Invalid character class name")
1312131543Stjr    gettext_noop ("Trailing backslash") /* REG_EESCAPE */
1313131543Stjr    "\0"
1314126209Sache#define REG_ESUBREG_IDX	(REG_EESCAPE_IDX + sizeof "Trailing backslash")
1315131543Stjr    gettext_noop ("Invalid back reference") /* REG_ESUBREG */
1316131543Stjr    "\0"
1317126209Sache#define REG_EBRACK_IDX	(REG_ESUBREG_IDX + sizeof "Invalid back reference")
1318131543Stjr    gettext_noop ("Unmatched [ or [^")	/* REG_EBRACK */
1319131543Stjr    "\0"
1320126209Sache#define REG_EPAREN_IDX	(REG_EBRACK_IDX + sizeof "Unmatched [ or [^")
1321131543Stjr    gettext_noop ("Unmatched ( or \\(") /* REG_EPAREN */
1322131543Stjr    "\0"
1323126209Sache#define REG_EBRACE_IDX	(REG_EPAREN_IDX + sizeof "Unmatched ( or \\(")
1324131543Stjr    gettext_noop ("Unmatched \\{") /* REG_EBRACE */
1325131543Stjr    "\0"
1326126209Sache#define REG_BADBR_IDX	(REG_EBRACE_IDX + sizeof "Unmatched \\{")
1327131543Stjr    gettext_noop ("Invalid content of \\{\\}") /* REG_BADBR */
1328131543Stjr    "\0"
1329126209Sache#define REG_ERANGE_IDX	(REG_BADBR_IDX + sizeof "Invalid content of \\{\\}")
1330131543Stjr    gettext_noop ("Invalid range end")	/* REG_ERANGE */
1331131543Stjr    "\0"
1332126209Sache#define REG_ESPACE_IDX	(REG_ERANGE_IDX + sizeof "Invalid range end")
1333131543Stjr    gettext_noop ("Memory exhausted") /* REG_ESPACE */
1334131543Stjr    "\0"
1335126209Sache#define REG_BADRPT_IDX	(REG_ESPACE_IDX + sizeof "Memory exhausted")
1336131543Stjr    gettext_noop ("Invalid preceding regular expression") /* REG_BADRPT */
1337131543Stjr    "\0"
1338126209Sache#define REG_EEND_IDX	(REG_BADRPT_IDX + sizeof "Invalid preceding regular expression")
1339131543Stjr    gettext_noop ("Premature end of regular expression") /* REG_EEND */
1340131543Stjr    "\0"
1341126209Sache#define REG_ESIZE_IDX	(REG_EEND_IDX + sizeof "Premature end of regular expression")
1342131543Stjr    gettext_noop ("Regular expression too big") /* REG_ESIZE */
1343131543Stjr    "\0"
1344126209Sache#define REG_ERPAREN_IDX	(REG_ESIZE_IDX + sizeof "Regular expression too big")
1345131543Stjr    gettext_noop ("Unmatched ) or \\)") /* REG_ERPAREN */
1346131543Stjr  };
1347126209Sache
1348126209Sachestatic const size_t re_error_msgid_idx[] =
1349126209Sache  {
1350126209Sache    REG_NOERROR_IDX,
1351126209Sache    REG_NOMATCH_IDX,
1352126209Sache    REG_BADPAT_IDX,
1353126209Sache    REG_ECOLLATE_IDX,
1354126209Sache    REG_ECTYPE_IDX,
1355126209Sache    REG_EESCAPE_IDX,
1356126209Sache    REG_ESUBREG_IDX,
1357126209Sache    REG_EBRACK_IDX,
1358126209Sache    REG_EPAREN_IDX,
1359126209Sache    REG_EBRACE_IDX,
1360126209Sache    REG_BADBR_IDX,
1361126209Sache    REG_ERANGE_IDX,
1362126209Sache    REG_ESPACE_IDX,
1363126209Sache    REG_BADRPT_IDX,
1364126209Sache    REG_EEND_IDX,
1365126209Sache    REG_ESIZE_IDX,
1366126209Sache    REG_ERPAREN_IDX
1367218Sconklin  };
1368218Sconklin
1369126209Sache/* Avoiding alloca during matching, to placate r_alloc.  */
1370126209Sache
1371126209Sache/* Define MATCH_MAY_ALLOCATE unless we need to make sure that the
1372126209Sache   searching and matching functions should not call alloca.  On some
1373126209Sache   systems, alloca is implemented in terms of malloc, and if we're
1374126209Sache   using the relocating allocator routines, then malloc could cause a
1375126209Sache   relocation, which might (if the strings being searched are in the
1376126209Sache   ralloc heap) shift the data out from underneath the regexp
1377126209Sache   routines.
1378126209Sache
1379126209Sache   Here's another reason to avoid allocation: Emacs
1380126209Sache   processes input from X in a signal handler; processing X input may
1381126209Sache   call malloc; if input arrives while a matching routine is calling
1382126209Sache   malloc, then we're scrod.  But Emacs can't just block input while
1383126209Sache   calling matching routines; then we don't notice interrupts when
1384126209Sache   they come in.  So, Emacs blocks input around all regexp calls
1385126209Sache   except the matching calls, which it leaves unprotected, in the
1386126209Sache   faith that they will not malloc.  */
1387126209Sache
1388126209Sache/* Normally, this is fine.  */
1389126209Sache#define MATCH_MAY_ALLOCATE
1390126209Sache
1391126209Sache/* When using GNU C, we are not REALLY using the C alloca, no matter
1392126209Sache   what config.h may say.  So don't take precautions for it.  */
1393126209Sache#ifdef __GNUC__
1394126209Sache# undef C_ALLOCA
1395126209Sache#endif
1396126209Sache
1397126209Sache/* The match routines may not allocate if (1) they would do it with malloc
1398126209Sache   and (2) it's not safe for them to use malloc.
1399126209Sache   Note that if REL_ALLOC is defined, matching would not use malloc for the
1400126209Sache   failure stack, but we would still use it for the register vectors;
1401126209Sache   so REL_ALLOC should not affect this.  */
1402126209Sache#if (defined C_ALLOCA || defined REGEX_MALLOC) && defined emacs
1403126209Sache# undef MATCH_MAY_ALLOCATE
1404126209Sache#endif
1405126209Sache
1406126209Sache
1407126209Sache/* Failure stack declarations and macros; both re_compile_fastmap and
1408126209Sache   re_match_2 use a failure stack.  These have to be macros because of
1409126209Sache   REGEX_ALLOCATE_STACK.  */
1410126209Sache
1411126209Sache
1412126209Sache/* Number of failure points for which to initially allocate space
1413126209Sache   when matching.  If this number is exceeded, we allocate more
1414126209Sache   space, so it is not a hard limit.  */
1415126209Sache#ifndef INIT_FAILURE_ALLOC
1416126209Sache# define INIT_FAILURE_ALLOC 5
1417126209Sache#endif
1418126209Sache
1419126209Sache/* Roughly the maximum number of failure points on the stack.  Would be
1420126209Sache   exactly that if always used MAX_FAILURE_ITEMS items each time we failed.
1421126209Sache   This is a variable only so users of regex can assign to it; we never
1422126209Sache   change it ourselves.  */
1423126209Sache
1424126209Sache#ifdef INT_IS_16BIT
1425126209Sache
1426126209Sache# if defined MATCH_MAY_ALLOCATE
1427126209Sache/* 4400 was enough to cause a crash on Alpha OSF/1,
1428126209Sache   whose default stack limit is 2mb.  */
1429126209Sachelong int re_max_failures = 4000;
1430126209Sache# else
1431126209Sachelong int re_max_failures = 2000;
1432126209Sache# endif
1433126209Sache
1434126209Sacheunion fail_stack_elt
1435126209Sache{
1436131543Stjr  US_CHAR_TYPE *pointer;
1437126209Sache  long int integer;
1438126209Sache};
1439126209Sache
1440126209Sachetypedef union fail_stack_elt fail_stack_elt_t;
1441126209Sache
1442126209Sachetypedef struct
1443126209Sache{
1444126209Sache  fail_stack_elt_t *stack;
1445126209Sache  unsigned long int size;
1446126209Sache  unsigned long int avail;		/* Offset of next open position.  */
1447126209Sache} fail_stack_type;
1448126209Sache
1449126209Sache#else /* not INT_IS_16BIT */
1450126209Sache
1451126209Sache# if defined MATCH_MAY_ALLOCATE
1452126209Sache/* 4400 was enough to cause a crash on Alpha OSF/1,
1453126209Sache   whose default stack limit is 2mb.  */
1454131543Stjrint re_max_failures = 4000;
1455126209Sache# else
1456126209Sacheint re_max_failures = 2000;
1457126209Sache# endif
1458126209Sache
1459126209Sacheunion fail_stack_elt
1460126209Sache{
1461131543Stjr  US_CHAR_TYPE *pointer;
1462126209Sache  int integer;
1463126209Sache};
1464126209Sache
1465126209Sachetypedef union fail_stack_elt fail_stack_elt_t;
1466126209Sache
1467126209Sachetypedef struct
1468126209Sache{
1469126209Sache  fail_stack_elt_t *stack;
1470126209Sache  unsigned size;
1471126209Sache  unsigned avail;			/* Offset of next open position.  */
1472126209Sache} fail_stack_type;
1473126209Sache
1474126209Sache#endif /* INT_IS_16BIT */
1475126209Sache
1476126209Sache#define FAIL_STACK_EMPTY()     (fail_stack.avail == 0)
1477126209Sache#define FAIL_STACK_PTR_EMPTY() (fail_stack_ptr->avail == 0)
1478126209Sache#define FAIL_STACK_FULL()      (fail_stack.avail == fail_stack.size)
1479126209Sache
1480126209Sache
1481126209Sache/* Define macros to initialize and free the failure stack.
1482126209Sache   Do `return -2' if the alloc fails.  */
1483126209Sache
1484126209Sache#ifdef MATCH_MAY_ALLOCATE
1485126209Sache# define INIT_FAIL_STACK()						\
1486126209Sache  do {									\
1487126209Sache    fail_stack.stack = (fail_stack_elt_t *)				\
1488126209Sache      REGEX_ALLOCATE_STACK (INIT_FAILURE_ALLOC * sizeof (fail_stack_elt_t)); \
1489126209Sache									\
1490126209Sache    if (fail_stack.stack == NULL)					\
1491126209Sache      return -2;							\
1492126209Sache									\
1493126209Sache    fail_stack.size = INIT_FAILURE_ALLOC;				\
1494126209Sache    fail_stack.avail = 0;						\
1495126209Sache  } while (0)
1496126209Sache
1497126209Sache# define RESET_FAIL_STACK()  REGEX_FREE_STACK (fail_stack.stack)
1498126209Sache#else
1499126209Sache# define INIT_FAIL_STACK()						\
1500126209Sache  do {									\
1501126209Sache    fail_stack.avail = 0;						\
1502126209Sache  } while (0)
1503126209Sache
1504126209Sache# define RESET_FAIL_STACK()
1505126209Sache#endif
1506126209Sache
1507126209Sache
1508126209Sache/* Double the size of FAIL_STACK, up to approximately `re_max_failures' items.
1509126209Sache
1510126209Sache   Return 1 if succeeds, and 0 if either ran out of memory
1511126209Sache   allocating space for it or it was already too large.
1512126209Sache
1513126209Sache   REGEX_REALLOCATE_STACK requires `destination' be declared.   */
1514126209Sache
1515126209Sache#define DOUBLE_FAIL_STACK(fail_stack)					\
1516126209Sache  ((fail_stack).size > (unsigned) (re_max_failures * MAX_FAILURE_ITEMS)	\
1517126209Sache   ? 0									\
1518126209Sache   : ((fail_stack).stack = (fail_stack_elt_t *)				\
1519126209Sache        REGEX_REALLOCATE_STACK ((fail_stack).stack, 			\
1520126209Sache          (fail_stack).size * sizeof (fail_stack_elt_t),		\
1521126209Sache          ((fail_stack).size << 1) * sizeof (fail_stack_elt_t)),	\
1522126209Sache									\
1523126209Sache      (fail_stack).stack == NULL					\
1524126209Sache      ? 0								\
1525126209Sache      : ((fail_stack).size <<= 1, 					\
1526126209Sache         1)))
1527126209Sache
1528126209Sache
1529126209Sache/* Push pointer POINTER on FAIL_STACK.
1530126209Sache   Return 1 if was able to do so and 0 if ran out of memory allocating
1531126209Sache   space to do so.  */
1532126209Sache#define PUSH_PATTERN_OP(POINTER, FAIL_STACK)				\
1533126209Sache  ((FAIL_STACK_FULL ()							\
1534126209Sache    && !DOUBLE_FAIL_STACK (FAIL_STACK))					\
1535126209Sache   ? 0									\
1536126209Sache   : ((FAIL_STACK).stack[(FAIL_STACK).avail++].pointer = POINTER,	\
1537126209Sache      1))
1538126209Sache
1539126209Sache/* Push a pointer value onto the failure stack.
1540126209Sache   Assumes the variable `fail_stack'.  Probably should only
1541126209Sache   be called from within `PUSH_FAILURE_POINT'.  */
1542126209Sache#define PUSH_FAILURE_POINTER(item)					\
1543131543Stjr  fail_stack.stack[fail_stack.avail++].pointer = (US_CHAR_TYPE *) (item)
1544126209Sache
1545126209Sache/* This pushes an integer-valued item onto the failure stack.
1546126209Sache   Assumes the variable `fail_stack'.  Probably should only
1547126209Sache   be called from within `PUSH_FAILURE_POINT'.  */
1548126209Sache#define PUSH_FAILURE_INT(item)					\
1549126209Sache  fail_stack.stack[fail_stack.avail++].integer = (item)
1550126209Sache
1551126209Sache/* Push a fail_stack_elt_t value onto the failure stack.
1552126209Sache   Assumes the variable `fail_stack'.  Probably should only
1553126209Sache   be called from within `PUSH_FAILURE_POINT'.  */
1554126209Sache#define PUSH_FAILURE_ELT(item)					\
1555126209Sache  fail_stack.stack[fail_stack.avail++] =  (item)
1556126209Sache
1557126209Sache/* These three POP... operations complement the three PUSH... operations.
1558126209Sache   All assume that `fail_stack' is nonempty.  */
1559126209Sache#define POP_FAILURE_POINTER() fail_stack.stack[--fail_stack.avail].pointer
1560126209Sache#define POP_FAILURE_INT() fail_stack.stack[--fail_stack.avail].integer
1561126209Sache#define POP_FAILURE_ELT() fail_stack.stack[--fail_stack.avail]
1562126209Sache
1563126209Sache/* Used to omit pushing failure point id's when we're not debugging.  */
1564126209Sache#ifdef DEBUG
1565126209Sache# define DEBUG_PUSH PUSH_FAILURE_INT
1566126209Sache# define DEBUG_POP(item_addr) *(item_addr) = POP_FAILURE_INT ()
1567126209Sache#else
1568126209Sache# define DEBUG_PUSH(item)
1569126209Sache# define DEBUG_POP(item_addr)
1570126209Sache#endif
1571126209Sache
1572126209Sache
1573126209Sache/* Push the information about the state we will need
1574126209Sache   if we ever fail back to it.
1575126209Sache
1576126209Sache   Requires variables fail_stack, regstart, regend, reg_info, and
1577126209Sache   num_regs_pushed be declared.  DOUBLE_FAIL_STACK requires `destination'
1578126209Sache   be declared.
1579126209Sache
1580126209Sache   Does `return FAILURE_CODE' if runs out of memory.  */
1581126209Sache
1582126209Sache#define PUSH_FAILURE_POINT(pattern_place, string_place, failure_code)	\
1583126209Sache  do {									\
1584126209Sache    char *destination;							\
1585126209Sache    /* Must be int, so when we don't save any registers, the arithmetic	\
1586126209Sache       of 0 + -1 isn't done as unsigned.  */				\
1587126209Sache    /* Can't be int, since there is not a shred of a guarantee that int	\
1588126209Sache       is wide enough to hold a value of something to which pointer can	\
1589126209Sache       be assigned */							\
1590126209Sache    active_reg_t this_reg;						\
1591126209Sache    									\
1592126209Sache    DEBUG_STATEMENT (failure_id++);					\
1593126209Sache    DEBUG_STATEMENT (nfailure_points_pushed++);				\
1594126209Sache    DEBUG_PRINT2 ("\nPUSH_FAILURE_POINT #%u:\n", failure_id);		\
1595126209Sache    DEBUG_PRINT2 ("  Before push, next avail: %d\n", (fail_stack).avail);\
1596126209Sache    DEBUG_PRINT2 ("                     size: %d\n", (fail_stack).size);\
1597126209Sache									\
1598126209Sache    DEBUG_PRINT2 ("  slots needed: %ld\n", NUM_FAILURE_ITEMS);		\
1599126209Sache    DEBUG_PRINT2 ("     available: %d\n", REMAINING_AVAIL_SLOTS);	\
1600126209Sache									\
1601126209Sache    /* Ensure we have enough space allocated for what we will push.  */	\
1602126209Sache    while (REMAINING_AVAIL_SLOTS < NUM_FAILURE_ITEMS)			\
1603126209Sache      {									\
1604126209Sache        if (!DOUBLE_FAIL_STACK (fail_stack))				\
1605126209Sache          return failure_code;						\
1606126209Sache									\
1607126209Sache        DEBUG_PRINT2 ("\n  Doubled stack; size now: %d\n",		\
1608126209Sache		       (fail_stack).size);				\
1609126209Sache        DEBUG_PRINT2 ("  slots available: %d\n", REMAINING_AVAIL_SLOTS);\
1610126209Sache      }									\
1611126209Sache									\
1612126209Sache    /* Push the info, starting with the registers.  */			\
1613126209Sache    DEBUG_PRINT1 ("\n");						\
1614126209Sache									\
1615126209Sache    if (1)								\
1616126209Sache      for (this_reg = lowest_active_reg; this_reg <= highest_active_reg; \
1617126209Sache	   this_reg++)							\
1618126209Sache	{								\
1619126209Sache	  DEBUG_PRINT2 ("  Pushing reg: %lu\n", this_reg);		\
1620126209Sache	  DEBUG_STATEMENT (num_regs_pushed++);				\
1621126209Sache									\
1622126209Sache	  DEBUG_PRINT2 ("    start: %p\n", regstart[this_reg]);		\
1623126209Sache	  PUSH_FAILURE_POINTER (regstart[this_reg]);			\
1624126209Sache									\
1625126209Sache	  DEBUG_PRINT2 ("    end: %p\n", regend[this_reg]);		\
1626126209Sache	  PUSH_FAILURE_POINTER (regend[this_reg]);			\
1627126209Sache									\
1628126209Sache	  DEBUG_PRINT2 ("    info: %p\n      ",				\
1629126209Sache			reg_info[this_reg].word.pointer);		\
1630126209Sache	  DEBUG_PRINT2 (" match_null=%d",				\
1631126209Sache			REG_MATCH_NULL_STRING_P (reg_info[this_reg]));	\
1632126209Sache	  DEBUG_PRINT2 (" active=%d", IS_ACTIVE (reg_info[this_reg]));	\
1633126209Sache	  DEBUG_PRINT2 (" matched_something=%d",			\
1634126209Sache			MATCHED_SOMETHING (reg_info[this_reg]));	\
1635126209Sache	  DEBUG_PRINT2 (" ever_matched=%d",				\
1636126209Sache			EVER_MATCHED_SOMETHING (reg_info[this_reg]));	\
1637126209Sache	  DEBUG_PRINT1 ("\n");						\
1638126209Sache	  PUSH_FAILURE_ELT (reg_info[this_reg].word);			\
1639126209Sache	}								\
1640126209Sache									\
1641126209Sache    DEBUG_PRINT2 ("  Pushing  low active reg: %ld\n", lowest_active_reg);\
1642126209Sache    PUSH_FAILURE_INT (lowest_active_reg);				\
1643126209Sache									\
1644126209Sache    DEBUG_PRINT2 ("  Pushing high active reg: %ld\n", highest_active_reg);\
1645126209Sache    PUSH_FAILURE_INT (highest_active_reg);				\
1646126209Sache									\
1647126209Sache    DEBUG_PRINT2 ("  Pushing pattern %p:\n", pattern_place);		\
1648126209Sache    DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern_place, pend);		\
1649126209Sache    PUSH_FAILURE_POINTER (pattern_place);				\
1650126209Sache									\
1651126209Sache    DEBUG_PRINT2 ("  Pushing string %p: `", string_place);		\
1652126209Sache    DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2,   \
1653126209Sache				 size2);				\
1654126209Sache    DEBUG_PRINT1 ("'\n");						\
1655126209Sache    PUSH_FAILURE_POINTER (string_place);				\
1656126209Sache									\
1657126209Sache    DEBUG_PRINT2 ("  Pushing failure id: %u\n", failure_id);		\
1658126209Sache    DEBUG_PUSH (failure_id);						\
1659126209Sache  } while (0)
1660126209Sache
1661126209Sache/* This is the number of items that are pushed and popped on the stack
1662126209Sache   for each register.  */
1663126209Sache#define NUM_REG_ITEMS  3
1664126209Sache
1665126209Sache/* Individual items aside from the registers.  */
1666126209Sache#ifdef DEBUG
1667126209Sache# define NUM_NONREG_ITEMS 5 /* Includes failure point id.  */
1668126209Sache#else
1669126209Sache# define NUM_NONREG_ITEMS 4
1670126209Sache#endif
1671126209Sache
1672126209Sache/* We push at most this many items on the stack.  */
1673126209Sache/* We used to use (num_regs - 1), which is the number of registers
1674126209Sache   this regexp will save; but that was changed to 5
1675126209Sache   to avoid stack overflow for a regexp with lots of parens.  */
1676126209Sache#define MAX_FAILURE_ITEMS (5 * NUM_REG_ITEMS + NUM_NONREG_ITEMS)
1677126209Sache
1678126209Sache/* We actually push this many items.  */
1679126209Sache#define NUM_FAILURE_ITEMS				\
1680126209Sache  (((0							\
1681126209Sache     ? 0 : highest_active_reg - lowest_active_reg + 1)	\
1682126209Sache    * NUM_REG_ITEMS)					\
1683126209Sache   + NUM_NONREG_ITEMS)
1684126209Sache
1685126209Sache/* How many items can still be added to the stack without overflowing it.  */
1686126209Sache#define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
1687126209Sache
1688126209Sache
1689126209Sache/* Pops what PUSH_FAIL_STACK pushes.
1690126209Sache
1691126209Sache   We restore into the parameters, all of which should be lvalues:
1692126209Sache     STR -- the saved data position.
1693126209Sache     PAT -- the saved pattern position.
1694126209Sache     LOW_REG, HIGH_REG -- the highest and lowest active registers.
1695126209Sache     REGSTART, REGEND -- arrays of string positions.
1696126209Sache     REG_INFO -- array of information about each subexpression.
1697126209Sache
1698126209Sache   Also assumes the variables `fail_stack' and (if debugging), `bufp',
1699126209Sache   `pend', `string1', `size1', `string2', and `size2'.  */
1700126209Sache#define POP_FAILURE_POINT(str, pat, low_reg, high_reg, regstart, regend, reg_info)\
1701126209Sache{									\
1702126209Sache  DEBUG_STATEMENT (unsigned failure_id;)				\
1703126209Sache  active_reg_t this_reg;						\
1704131543Stjr  const US_CHAR_TYPE *string_temp;					\
1705126209Sache									\
1706126209Sache  assert (!FAIL_STACK_EMPTY ());					\
1707126209Sache									\
1708126209Sache  /* Remove failure points and point to how many regs pushed.  */	\
1709126209Sache  DEBUG_PRINT1 ("POP_FAILURE_POINT:\n");				\
1710126209Sache  DEBUG_PRINT2 ("  Before pop, next avail: %d\n", fail_stack.avail);	\
1711126209Sache  DEBUG_PRINT2 ("                    size: %d\n", fail_stack.size);	\
1712126209Sache									\
1713126209Sache  assert (fail_stack.avail >= NUM_NONREG_ITEMS);			\
1714126209Sache									\
1715126209Sache  DEBUG_POP (&failure_id);						\
1716126209Sache  DEBUG_PRINT2 ("  Popping failure id: %u\n", failure_id);		\
1717126209Sache									\
1718126209Sache  /* If the saved string location is NULL, it came from an		\
1719126209Sache     on_failure_keep_string_jump opcode, and we want to throw away the	\
1720126209Sache     saved NULL, thus retaining our current position in the string.  */	\
1721126209Sache  string_temp = POP_FAILURE_POINTER ();					\
1722126209Sache  if (string_temp != NULL)						\
1723131543Stjr    str = (const CHAR_TYPE *) string_temp;				\
1724126209Sache									\
1725126209Sache  DEBUG_PRINT2 ("  Popping string %p: `", str);				\
1726126209Sache  DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2);	\
1727126209Sache  DEBUG_PRINT1 ("'\n");							\
1728126209Sache									\
1729131543Stjr  pat = (US_CHAR_TYPE *) POP_FAILURE_POINTER ();			\
1730126209Sache  DEBUG_PRINT2 ("  Popping pattern %p:\n", pat);			\
1731126209Sache  DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend);			\
1732126209Sache									\
1733126209Sache  /* Restore register info.  */						\
1734126209Sache  high_reg = (active_reg_t) POP_FAILURE_INT ();				\
1735126209Sache  DEBUG_PRINT2 ("  Popping high active reg: %ld\n", high_reg);		\
1736126209Sache									\
1737126209Sache  low_reg = (active_reg_t) POP_FAILURE_INT ();				\
1738126209Sache  DEBUG_PRINT2 ("  Popping  low active reg: %ld\n", low_reg);		\
1739126209Sache									\
1740126209Sache  if (1)								\
1741126209Sache    for (this_reg = high_reg; this_reg >= low_reg; this_reg--)		\
1742126209Sache      {									\
1743126209Sache	DEBUG_PRINT2 ("    Popping reg: %ld\n", this_reg);		\
1744126209Sache									\
1745126209Sache	reg_info[this_reg].word = POP_FAILURE_ELT ();			\
1746126209Sache	DEBUG_PRINT2 ("      info: %p\n",				\
1747126209Sache		      reg_info[this_reg].word.pointer);			\
1748126209Sache									\
1749131543Stjr	regend[this_reg] = (const CHAR_TYPE *) POP_FAILURE_POINTER ();	\
1750126209Sache	DEBUG_PRINT2 ("      end: %p\n", regend[this_reg]);		\
1751126209Sache									\
1752131543Stjr	regstart[this_reg] = (const CHAR_TYPE *) POP_FAILURE_POINTER ();\
1753126209Sache	DEBUG_PRINT2 ("      start: %p\n", regstart[this_reg]);		\
1754126209Sache      }									\
1755126209Sache  else									\
1756126209Sache    {									\
1757126209Sache      for (this_reg = highest_active_reg; this_reg > high_reg; this_reg--) \
1758126209Sache	{								\
1759126209Sache	  reg_info[this_reg].word.integer = 0;				\
1760126209Sache	  regend[this_reg] = 0;						\
1761126209Sache	  regstart[this_reg] = 0;					\
1762126209Sache	}								\
1763126209Sache      highest_active_reg = high_reg;					\
1764126209Sache    }									\
1765126209Sache									\
1766126209Sache  set_regs_matched_done = 0;						\
1767126209Sache  DEBUG_STATEMENT (nfailure_points_popped++);				\
1768126209Sache} /* POP_FAILURE_POINT */
1769126209Sache
1770126209Sache
1771126209Sache/* Structure for per-register (a.k.a. per-group) information.
1772126209Sache   Other register information, such as the
1773126209Sache   starting and ending positions (which are addresses), and the list of
1774126209Sache   inner groups (which is a bits list) are maintained in separate
1775126209Sache   variables.
1776126209Sache
1777126209Sache   We are making a (strictly speaking) nonportable assumption here: that
1778126209Sache   the compiler will pack our bit fields into something that fits into
1779126209Sache   the type of `word', i.e., is something that fits into one item on the
1780126209Sache   failure stack.  */
1781126209Sache
1782126209Sache
1783126209Sache/* Declarations and macros for re_match_2.  */
1784126209Sache
1785126209Sachetypedef union
1786126209Sache{
1787126209Sache  fail_stack_elt_t word;
1788126209Sache  struct
1789126209Sache  {
1790126209Sache      /* This field is one if this group can match the empty string,
1791126209Sache         zero if not.  If not yet determined,  `MATCH_NULL_UNSET_VALUE'.  */
1792126209Sache#define MATCH_NULL_UNSET_VALUE 3
1793126209Sache    unsigned match_null_string_p : 2;
1794126209Sache    unsigned is_active : 1;
1795126209Sache    unsigned matched_something : 1;
1796126209Sache    unsigned ever_matched_something : 1;
1797126209Sache  } bits;
1798126209Sache} register_info_type;
1799126209Sache
1800126209Sache#define REG_MATCH_NULL_STRING_P(R)  ((R).bits.match_null_string_p)
1801126209Sache#define IS_ACTIVE(R)  ((R).bits.is_active)
1802126209Sache#define MATCHED_SOMETHING(R)  ((R).bits.matched_something)
1803126209Sache#define EVER_MATCHED_SOMETHING(R)  ((R).bits.ever_matched_something)
1804126209Sache
1805126209Sache
1806126209Sache/* Call this when have matched a real character; it sets `matched' flags
1807126209Sache   for the subexpressions which we are currently inside.  Also records
1808126209Sache   that those subexprs have matched.  */
1809126209Sache#define SET_REGS_MATCHED()						\
1810126209Sache  do									\
1811126209Sache    {									\
1812126209Sache      if (!set_regs_matched_done)					\
1813126209Sache	{								\
1814126209Sache	  active_reg_t r;						\
1815126209Sache	  set_regs_matched_done = 1;					\
1816126209Sache	  for (r = lowest_active_reg; r <= highest_active_reg; r++)	\
1817126209Sache	    {								\
1818126209Sache	      MATCHED_SOMETHING (reg_info[r])				\
1819126209Sache		= EVER_MATCHED_SOMETHING (reg_info[r])			\
1820126209Sache		= 1;							\
1821126209Sache	    }								\
1822126209Sache	}								\
1823126209Sache    }									\
1824126209Sache  while (0)
1825126209Sache
1826126209Sache/* Registers are set to a sentinel when they haven't yet matched.  */
1827131543Stjrstatic CHAR_TYPE reg_unset_dummy;
1828126209Sache#define REG_UNSET_VALUE (&reg_unset_dummy)
1829126209Sache#define REG_UNSET(e) ((e) == REG_UNSET_VALUE)
1830126209Sache
1831218Sconklin/* Subroutine declarations and macros for regex_compile.  */
1832218Sconklin
1833126209Sachestatic reg_errcode_t regex_compile _RE_ARGS ((const char *pattern, size_t size,
1834126209Sache					      reg_syntax_t syntax,
1835126209Sache					      struct re_pattern_buffer *bufp));
1836131543Stjrstatic void store_op1 _RE_ARGS ((re_opcode_t op, US_CHAR_TYPE *loc, int arg));
1837131543Stjrstatic void store_op2 _RE_ARGS ((re_opcode_t op, US_CHAR_TYPE *loc,
1838126209Sache				 int arg1, int arg2));
1839131543Stjrstatic void insert_op1 _RE_ARGS ((re_opcode_t op, US_CHAR_TYPE *loc,
1840131543Stjr				  int arg, US_CHAR_TYPE *end));
1841131543Stjrstatic void insert_op2 _RE_ARGS ((re_opcode_t op, US_CHAR_TYPE *loc,
1842131543Stjr				  int arg1, int arg2, US_CHAR_TYPE *end));
1843131543Stjrstatic boolean at_begline_loc_p _RE_ARGS ((const CHAR_TYPE *pattern,
1844131543Stjr					   const CHAR_TYPE *p,
1845126209Sache					   reg_syntax_t syntax));
1846131543Stjrstatic boolean at_endline_loc_p _RE_ARGS ((const CHAR_TYPE *p,
1847131543Stjr					   const CHAR_TYPE *pend,
1848126209Sache					   reg_syntax_t syntax));
1849131543Stjr#ifdef MBS_SUPPORT
1850131543Stjrstatic reg_errcode_t compile_range _RE_ARGS ((CHAR_TYPE range_start,
1851131543Stjr					      const CHAR_TYPE **p_ptr,
1852131543Stjr					      const CHAR_TYPE *pend,
1853126209Sache					      char *translate,
1854126209Sache					      reg_syntax_t syntax,
1855131543Stjr					      US_CHAR_TYPE *b,
1856131543Stjr					      CHAR_TYPE *char_set));
1857131543Stjrstatic void insert_space _RE_ARGS ((int num, CHAR_TYPE *loc, CHAR_TYPE *end));
1858131543Stjr#else
1859131543Stjrstatic reg_errcode_t compile_range _RE_ARGS ((unsigned int range_start,
1860131543Stjr					      const CHAR_TYPE **p_ptr,
1861131543Stjr					      const CHAR_TYPE *pend,
1862131543Stjr					      char *translate,
1863131543Stjr					      reg_syntax_t syntax,
1864131543Stjr					      US_CHAR_TYPE *b));
1865131543Stjr#endif /* MBS_SUPPORT */
1866218Sconklin
1867126209Sache/* Fetch the next character in the uncompiled pattern---translating it
1868218Sconklin   if necessary.  Also cast from a signed character in the constant
1869218Sconklin   string passed to us by the user to an unsigned char that we can use
1870218Sconklin   as an array index (in, e.g., `translate').  */
1871131543Stjr/* ifdef MBS_SUPPORT, we translate only if character <= 0xff,
1872131543Stjr   because it is impossible to allocate 4GB array for some encodings
1873131543Stjr   which have 4 byte character_set like UCS4.  */
1874126209Sache#ifndef PATFETCH
1875131543Stjr# ifdef MBS_SUPPORT
1876131543Stjr#  define PATFETCH(c)							\
1877218Sconklin  do {if (p == pend) return REG_EEND;					\
1878131543Stjr    c = (US_CHAR_TYPE) *p++;						\
1879131543Stjr    if (translate && (c <= 0xff)) c = (US_CHAR_TYPE) translate[c];	\
1880131543Stjr  } while (0)
1881131543Stjr# else
1882131543Stjr#  define PATFETCH(c)							\
1883131543Stjr  do {if (p == pend) return REG_EEND;					\
1884218Sconklin    c = (unsigned char) *p++;						\
1885126209Sache    if (translate) c = (unsigned char) translate[c];			\
1886218Sconklin  } while (0)
1887131543Stjr# endif /* MBS_SUPPORT */
1888126209Sache#endif
1889218Sconklin
1890218Sconklin/* Fetch the next character in the uncompiled pattern, with no
1891218Sconklin   translation.  */
1892218Sconklin#define PATFETCH_RAW(c)							\
1893218Sconklin  do {if (p == pend) return REG_EEND;					\
1894131543Stjr    c = (US_CHAR_TYPE) *p++; 						\
1895218Sconklin  } while (0)
1896218Sconklin
1897218Sconklin/* Go backwards one character in the pattern.  */
1898218Sconklin#define PATUNFETCH p--
1899218Sconklin
1900218Sconklin
1901218Sconklin/* If `translate' is non-null, return translate[D], else just D.  We
1902218Sconklin   cast the subscript to translate because some data is declared as
1903218Sconklin   `char *', to avoid warnings when a string constant is passed.  But
1904218Sconklin   when we use a character as a subscript we must make it unsigned.  */
1905131543Stjr/* ifdef MBS_SUPPORT, we translate only if character <= 0xff,
1906131543Stjr   because it is impossible to allocate 4GB array for some encodings
1907131543Stjr   which have 4 byte character_set like UCS4.  */
1908126209Sache#ifndef TRANSLATE
1909131543Stjr# ifdef MBS_SUPPORT
1910131543Stjr#  define TRANSLATE(d) \
1911131543Stjr  ((translate && ((US_CHAR_TYPE) (d)) <= 0xff) \
1912131543Stjr   ? (char) translate[(unsigned char) (d)] : (d))
1913131543Stjr#else
1914131543Stjr#  define TRANSLATE(d) \
1915126209Sache  (translate ? (char) translate[(unsigned char) (d)] : (d))
1916131543Stjr# endif /* MBS_SUPPORT */
1917126209Sache#endif
1918218Sconklin
1919218Sconklin
1920218Sconklin/* Macros for outputting the compiled pattern into `buffer'.  */
1921218Sconklin
1922218Sconklin/* If the buffer isn't allocated when it comes in, use this.  */
1923131543Stjr#define INIT_BUF_SIZE  (32 * sizeof(US_CHAR_TYPE))
1924218Sconklin
1925218Sconklin/* Make sure we have at least N more bytes of space in buffer.  */
1926131543Stjr#ifdef MBS_SUPPORT
1927131543Stjr# define GET_BUFFER_SPACE(n)						\
1928131543Stjr    while (((unsigned long)b - (unsigned long)COMPILED_BUFFER_VAR	\
1929131543Stjr            + (n)*sizeof(CHAR_TYPE)) > bufp->allocated)			\
1930131543Stjr      EXTEND_BUFFER ()
1931131543Stjr#else
1932131543Stjr# define GET_BUFFER_SPACE(n)						\
1933126209Sache    while ((unsigned long) (b - bufp->buffer + (n)) > bufp->allocated)	\
1934218Sconklin      EXTEND_BUFFER ()
1935131543Stjr#endif /* MBS_SUPPORT */
1936218Sconklin
1937218Sconklin/* Make sure we have one more byte of buffer space and then add C to it.  */
1938218Sconklin#define BUF_PUSH(c)							\
1939218Sconklin  do {									\
1940218Sconklin    GET_BUFFER_SPACE (1);						\
1941131543Stjr    *b++ = (US_CHAR_TYPE) (c);						\
1942218Sconklin  } while (0)
1943218Sconklin
1944218Sconklin
1945218Sconklin/* Ensure we have two more bytes of buffer space and then append C1 and C2.  */
1946218Sconklin#define BUF_PUSH_2(c1, c2)						\
1947218Sconklin  do {									\
1948218Sconklin    GET_BUFFER_SPACE (2);						\
1949131543Stjr    *b++ = (US_CHAR_TYPE) (c1);					\
1950131543Stjr    *b++ = (US_CHAR_TYPE) (c2);					\
1951218Sconklin  } while (0)
1952218Sconklin
1953218Sconklin
1954218Sconklin/* As with BUF_PUSH_2, except for three bytes.  */
1955218Sconklin#define BUF_PUSH_3(c1, c2, c3)						\
1956218Sconklin  do {									\
1957218Sconklin    GET_BUFFER_SPACE (3);						\
1958131543Stjr    *b++ = (US_CHAR_TYPE) (c1);					\
1959131543Stjr    *b++ = (US_CHAR_TYPE) (c2);					\
1960131543Stjr    *b++ = (US_CHAR_TYPE) (c3);					\
1961218Sconklin  } while (0)
1962218Sconklin
1963218Sconklin/* Store a jump with opcode OP at LOC to location TO.  We store a
1964218Sconklin   relative address offset by the three bytes the jump itself occupies.  */
1965218Sconklin#define STORE_JUMP(op, loc, to) \
1966131543Stjr  store_op1 (op, loc, (int) ((to) - (loc) - (1 + OFFSET_ADDRESS_SIZE)))
1967218Sconklin
1968218Sconklin/* Likewise, for a two-argument jump.  */
1969218Sconklin#define STORE_JUMP2(op, loc, to, arg) \
1970131543Stjr  store_op2 (op, loc, (int) ((to) - (loc) - (1 + OFFSET_ADDRESS_SIZE)), arg)
1971218Sconklin
1972218Sconklin/* Like `STORE_JUMP', but for inserting.  Assume `b' is the buffer end.  */
1973218Sconklin#define INSERT_JUMP(op, loc, to) \
1974131543Stjr  insert_op1 (op, loc, (int) ((to) - (loc) - (1 + OFFSET_ADDRESS_SIZE)), b)
1975218Sconklin
1976218Sconklin/* Like `STORE_JUMP2', but for inserting.  Assume `b' is the buffer end.  */
1977218Sconklin#define INSERT_JUMP2(op, loc, to, arg) \
1978131543Stjr  insert_op2 (op, loc, (int) ((to) - (loc) - (1 + OFFSET_ADDRESS_SIZE)),\
1979131543Stjr	      arg, b)
1980218Sconklin
1981218Sconklin
1982218Sconklin/* This is not an arbitrary limit: the arguments which represent offsets
1983218Sconklin   into the pattern are two bytes long.  So if 2^16 bytes turns out to
1984218Sconklin   be too small, many things would have to change.  */
1985126209Sache/* Any other compiler which, like MSC, has allocation limit below 2^16
1986126209Sache   bytes will have to use approach similar to what was done below for
1987126209Sache   MSC and drop MAX_BUF_SIZE a bit.  Otherwise you may end up
1988126209Sache   reallocating to 0 bytes.  Such thing is not going to work too well.
1989126209Sache   You have been warned!!  */
1990126209Sache#if defined _MSC_VER  && !defined WIN32
1991126209Sache/* Microsoft C 16-bit versions limit malloc to approx 65512 bytes.
1992126209Sache   The REALLOC define eliminates a flurry of conversion warnings,
1993126209Sache   but is not required. */
1994126209Sache# define MAX_BUF_SIZE  65500L
1995126209Sache# define REALLOC(p,s) realloc ((p), (size_t) (s))
1996126209Sache#else
1997126209Sache# define MAX_BUF_SIZE (1L << 16)
1998126209Sache# define REALLOC(p,s) realloc ((p), (s))
1999126209Sache#endif
2000218Sconklin
2001218Sconklin/* Extend the buffer by twice its current size via realloc and
2002218Sconklin   reset the pointers that pointed into the old block to point to the
2003218Sconklin   correct places in the new one.  If extending the buffer results in it
2004218Sconklin   being larger than MAX_BUF_SIZE, then flag memory exhausted.  */
2005131543Stjr#if __BOUNDED_POINTERS__
2006131543Stjr# define SET_HIGH_BOUND(P) (__ptrhigh (P) = __ptrlow (P) + bufp->allocated)
2007131543Stjr# define MOVE_BUFFER_POINTER(P) \
2008131543Stjr  (__ptrlow (P) += incr, SET_HIGH_BOUND (P), __ptrvalue (P) += incr)
2009131543Stjr# define ELSE_EXTEND_BUFFER_HIGH_BOUND		\
2010131543Stjr  else						\
2011131543Stjr    {						\
2012131543Stjr      SET_HIGH_BOUND (b);			\
2013131543Stjr      SET_HIGH_BOUND (begalt);			\
2014131543Stjr      if (fixup_alt_jump)			\
2015131543Stjr	SET_HIGH_BOUND (fixup_alt_jump);	\
2016131543Stjr      if (laststart)				\
2017131543Stjr	SET_HIGH_BOUND (laststart);		\
2018131543Stjr      if (pending_exact)			\
2019131543Stjr	SET_HIGH_BOUND (pending_exact);		\
2020131543Stjr    }
2021131543Stjr#else
2022131543Stjr# define MOVE_BUFFER_POINTER(P) (P) += incr
2023131543Stjr# define ELSE_EXTEND_BUFFER_HIGH_BOUND
2024131543Stjr#endif
2025131543Stjr
2026131543Stjr#ifdef MBS_SUPPORT
2027131543Stjr# define EXTEND_BUFFER()						\
2028131543Stjr  do {									\
2029131543Stjr    US_CHAR_TYPE *old_buffer = COMPILED_BUFFER_VAR;			\
2030131543Stjr    int wchar_count;							\
2031131543Stjr    if (bufp->allocated + sizeof(US_CHAR_TYPE) > MAX_BUF_SIZE)		\
2032218Sconklin      return REG_ESIZE;							\
2033218Sconklin    bufp->allocated <<= 1;						\
2034218Sconklin    if (bufp->allocated > MAX_BUF_SIZE)					\
2035131543Stjr      bufp->allocated = MAX_BUF_SIZE;					\
2036131543Stjr    /* How many characters the new buffer can have?  */			\
2037131543Stjr    wchar_count = bufp->allocated / sizeof(US_CHAR_TYPE);		\
2038131543Stjr    if (wchar_count == 0) wchar_count = 1;				\
2039131543Stjr    /* Truncate the buffer to CHAR_TYPE align.  */			\
2040131543Stjr    bufp->allocated = wchar_count * sizeof(US_CHAR_TYPE);		\
2041131543Stjr    RETALLOC (COMPILED_BUFFER_VAR, wchar_count, US_CHAR_TYPE);		\
2042131543Stjr    bufp->buffer = (char*)COMPILED_BUFFER_VAR;				\
2043131543Stjr    if (COMPILED_BUFFER_VAR == NULL)					\
2044218Sconklin      return REG_ESPACE;						\
2045218Sconklin    /* If the buffer moved, move all the pointers into it.  */		\
2046131543Stjr    if (old_buffer != COMPILED_BUFFER_VAR)				\
2047218Sconklin      {									\
2048131543Stjr	int incr = COMPILED_BUFFER_VAR - old_buffer;			\
2049131543Stjr	MOVE_BUFFER_POINTER (b);					\
2050131543Stjr	MOVE_BUFFER_POINTER (begalt);					\
2051131543Stjr	if (fixup_alt_jump)						\
2052131543Stjr	  MOVE_BUFFER_POINTER (fixup_alt_jump);				\
2053131543Stjr	if (laststart)							\
2054131543Stjr	  MOVE_BUFFER_POINTER (laststart);				\
2055131543Stjr	if (pending_exact)						\
2056131543Stjr	  MOVE_BUFFER_POINTER (pending_exact);				\
2057218Sconklin      }									\
2058131543Stjr    ELSE_EXTEND_BUFFER_HIGH_BOUND					\
2059218Sconklin  } while (0)
2060131543Stjr#else
2061131543Stjr# define EXTEND_BUFFER()						\
2062131543Stjr  do {									\
2063131543Stjr    US_CHAR_TYPE *old_buffer = COMPILED_BUFFER_VAR;			\
2064131543Stjr    if (bufp->allocated == MAX_BUF_SIZE)				\
2065131543Stjr      return REG_ESIZE;							\
2066131543Stjr    bufp->allocated <<= 1;						\
2067131543Stjr    if (bufp->allocated > MAX_BUF_SIZE)					\
2068131543Stjr      bufp->allocated = MAX_BUF_SIZE;					\
2069131543Stjr    bufp->buffer = (US_CHAR_TYPE *) REALLOC (COMPILED_BUFFER_VAR,	\
2070131543Stjr						bufp->allocated);	\
2071131543Stjr    if (COMPILED_BUFFER_VAR == NULL)					\
2072131543Stjr      return REG_ESPACE;						\
2073131543Stjr    /* If the buffer moved, move all the pointers into it.  */		\
2074131543Stjr    if (old_buffer != COMPILED_BUFFER_VAR)				\
2075131543Stjr      {									\
2076131543Stjr	int incr = COMPILED_BUFFER_VAR - old_buffer;			\
2077131543Stjr	MOVE_BUFFER_POINTER (b);					\
2078131543Stjr	MOVE_BUFFER_POINTER (begalt);					\
2079131543Stjr	if (fixup_alt_jump)						\
2080131543Stjr	  MOVE_BUFFER_POINTER (fixup_alt_jump);				\
2081131543Stjr	if (laststart)							\
2082131543Stjr	  MOVE_BUFFER_POINTER (laststart);				\
2083131543Stjr	if (pending_exact)						\
2084131543Stjr	  MOVE_BUFFER_POINTER (pending_exact);				\
2085131543Stjr      }									\
2086131543Stjr    ELSE_EXTEND_BUFFER_HIGH_BOUND					\
2087131543Stjr  } while (0)
2088131543Stjr#endif /* MBS_SUPPORT */
2089218Sconklin
2090218Sconklin/* Since we have one byte reserved for the register number argument to
2091218Sconklin   {start,stop}_memory, the maximum number of groups we can report
2092218Sconklin   things about is what fits in that byte.  */
2093218Sconklin#define MAX_REGNUM 255
2094218Sconklin
2095218Sconklin/* But patterns can have more than `MAX_REGNUM' registers.  We just
2096218Sconklin   ignore the excess.  */
2097218Sconklintypedef unsigned regnum_t;
2098218Sconklin
2099218Sconklin
2100218Sconklin/* Macros for the compile stack.  */
2101218Sconklin
2102218Sconklin/* Since offsets can go either forwards or backwards, this type needs to
2103218Sconklin   be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1.  */
2104126209Sache/* int may be not enough when sizeof(int) == 2.  */
2105126209Sachetypedef long pattern_offset_t;
2106218Sconklin
2107218Sconklintypedef struct
2108218Sconklin{
2109218Sconklin  pattern_offset_t begalt_offset;
2110218Sconklin  pattern_offset_t fixup_alt_jump;
2111218Sconklin  pattern_offset_t inner_group_offset;
2112126209Sache  pattern_offset_t laststart_offset;
2113218Sconklin  regnum_t regnum;
2114218Sconklin} compile_stack_elt_t;
2115218Sconklin
2116218Sconklin
2117218Sconklintypedef struct
2118218Sconklin{
2119218Sconklin  compile_stack_elt_t *stack;
2120218Sconklin  unsigned size;
2121218Sconklin  unsigned avail;			/* Offset of next open position.  */
2122218Sconklin} compile_stack_type;
2123218Sconklin
2124218Sconklin
2125218Sconklin#define INIT_COMPILE_STACK_SIZE 32
2126218Sconklin
2127218Sconklin#define COMPILE_STACK_EMPTY  (compile_stack.avail == 0)
2128218Sconklin#define COMPILE_STACK_FULL  (compile_stack.avail == compile_stack.size)
2129218Sconklin
2130218Sconklin/* The next available element.  */
2131218Sconklin#define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
2132218Sconklin
2133218Sconklin
2134218Sconklin/* Set the bit for character C in a list.  */
2135218Sconklin#define SET_LIST_BIT(c)                               \
2136218Sconklin  (b[((unsigned char) (c)) / BYTEWIDTH]               \
2137218Sconklin   |= 1 << (((unsigned char) c) % BYTEWIDTH))
2138218Sconklin
2139218Sconklin
2140218Sconklin/* Get the next unsigned number in the uncompiled pattern.  */
2141218Sconklin#define GET_UNSIGNED_NUMBER(num) 					\
2142131543Stjr  {									\
2143131543Stjr    while (p != pend)							\
2144131543Stjr      {									\
2145131543Stjr	PATFETCH (c);							\
2146131543Stjr	if (! ('0' <= c && c <= '9'))					\
2147131543Stjr	  break;							\
2148131543Stjr	if (num <= RE_DUP_MAX)						\
2149131543Stjr	  {								\
2150131543Stjr	    if (num < 0)						\
2151131543Stjr	      num = 0;							\
2152131543Stjr	    num = num * 10 + c - '0';					\
2153131543Stjr	  }								\
2154131543Stjr      }									\
2155131543Stjr  }
2156218Sconklin
2157126209Sache#if defined _LIBC || WIDE_CHAR_SUPPORT
2158126209Sache/* The GNU C library provides support for user-defined character classes
2159126209Sache   and the functions from ISO C amendement 1.  */
2160126209Sache# ifdef CHARCLASS_NAME_MAX
2161126209Sache#  define CHAR_CLASS_MAX_LENGTH CHARCLASS_NAME_MAX
2162126209Sache# else
2163126209Sache/* This shouldn't happen but some implementation might still have this
2164126209Sache   problem.  Use a reasonable default value.  */
2165126209Sache#  define CHAR_CLASS_MAX_LENGTH 256
2166126209Sache# endif
2167218Sconklin
2168126209Sache# ifdef _LIBC
2169126209Sache#  define IS_CHAR_CLASS(string) __wctype (string)
2170126209Sache# else
2171126209Sache#  define IS_CHAR_CLASS(string) wctype (string)
2172126209Sache# endif
2173126209Sache#else
2174126209Sache# define CHAR_CLASS_MAX_LENGTH  6 /* Namely, `xdigit'.  */
2175126209Sache
2176126209Sache# define IS_CHAR_CLASS(string)						\
2177218Sconklin   (STREQ (string, "alpha") || STREQ (string, "upper")			\
2178218Sconklin    || STREQ (string, "lower") || STREQ (string, "digit")		\
2179218Sconklin    || STREQ (string, "alnum") || STREQ (string, "xdigit")		\
2180218Sconklin    || STREQ (string, "space") || STREQ (string, "print")		\
2181218Sconklin    || STREQ (string, "punct") || STREQ (string, "graph")		\
2182218Sconklin    || STREQ (string, "cntrl") || STREQ (string, "blank"))
2183126209Sache#endif
2184218Sconklin
2185126209Sache#ifndef MATCH_MAY_ALLOCATE
2186126209Sache
2187126209Sache/* If we cannot allocate large objects within re_match_2_internal,
2188126209Sache   we make the fail stack and register vectors global.
2189126209Sache   The fail stack, we grow to the maximum size when a regexp
2190126209Sache   is compiled.
2191126209Sache   The register vectors, we adjust in size each time we
2192126209Sache   compile a regexp, according to the number of registers it needs.  */
2193126209Sache
2194126209Sachestatic fail_stack_type fail_stack;
2195126209Sache
2196126209Sache/* Size with which the following vectors are currently allocated.
2197126209Sache   That is so we can make them bigger as needed,
2198126209Sache   but never make them smaller.  */
2199126209Sachestatic int regs_allocated_size;
2200126209Sache
2201126209Sachestatic const char **     regstart, **     regend;
2202126209Sachestatic const char ** old_regstart, ** old_regend;
2203126209Sachestatic const char **best_regstart, **best_regend;
2204126209Sachestatic register_info_type *reg_info;
2205126209Sachestatic const char **reg_dummy;
2206126209Sachestatic register_info_type *reg_info_dummy;
2207126209Sache
2208126209Sache/* Make the register vectors big enough for NUM_REGS registers,
2209126209Sache   but don't make them smaller.  */
2210126209Sache
2211126209Sachestatic
2212126209Sacheregex_grow_registers (num_regs)
2213126209Sache     int num_regs;
2214126209Sache{
2215126209Sache  if (num_regs > regs_allocated_size)
2216126209Sache    {
2217126209Sache      RETALLOC_IF (regstart,	 num_regs, const char *);
2218126209Sache      RETALLOC_IF (regend,	 num_regs, const char *);
2219126209Sache      RETALLOC_IF (old_regstart, num_regs, const char *);
2220126209Sache      RETALLOC_IF (old_regend,	 num_regs, const char *);
2221126209Sache      RETALLOC_IF (best_regstart, num_regs, const char *);
2222126209Sache      RETALLOC_IF (best_regend,	 num_regs, const char *);
2223126209Sache      RETALLOC_IF (reg_info,	 num_regs, register_info_type);
2224126209Sache      RETALLOC_IF (reg_dummy,	 num_regs, const char *);
2225126209Sache      RETALLOC_IF (reg_info_dummy, num_regs, register_info_type);
2226126209Sache
2227126209Sache      regs_allocated_size = num_regs;
2228126209Sache    }
2229126209Sache}
2230126209Sache
2231126209Sache#endif /* not MATCH_MAY_ALLOCATE */
2232126209Sache
2233126209Sachestatic boolean group_in_compile_stack _RE_ARGS ((compile_stack_type
2234126209Sache						 compile_stack,
2235126209Sache						 regnum_t regnum));
2236126209Sache
2237218Sconklin/* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
2238218Sconklin   Returns one of error codes defined in `regex.h', or zero for success.
2239218Sconklin
2240218Sconklin   Assumes the `allocated' (and perhaps `buffer') and `translate'
2241218Sconklin   fields are set in BUFP on entry.
2242218Sconklin
2243218Sconklin   If it succeeds, results are put in BUFP (if it returns an error, the
2244218Sconklin   contents of BUFP are undefined):
2245218Sconklin     `buffer' is the compiled pattern;
2246218Sconklin     `syntax' is set to SYNTAX;
2247218Sconklin     `used' is set to the length of the compiled pattern;
2248218Sconklin     `fastmap_accurate' is zero;
2249218Sconklin     `re_nsub' is the number of subexpressions in PATTERN;
2250218Sconklin     `not_bol' and `not_eol' are zero;
2251126209Sache
2252218Sconklin   The `fastmap' and `newline_anchor' fields are neither
2253218Sconklin   examined nor set.  */
2254218Sconklin
2255126209Sache/* Return, freeing storage we allocated.  */
2256131543Stjr#ifdef MBS_SUPPORT
2257131543Stjr# define FREE_STACK_RETURN(value)		\
2258131543Stjr  return (free(pattern), free(mbs_offset), free(is_binary), free (compile_stack.stack), value)
2259131543Stjr#else
2260131543Stjr# define FREE_STACK_RETURN(value)		\
2261126209Sache  return (free (compile_stack.stack), value)
2262131543Stjr#endif /* MBS_SUPPORT */
2263126209Sache
2264218Sconklinstatic reg_errcode_t
2265131543Stjr#ifdef MBS_SUPPORT
2266131543Stjrregex_compile (cpattern, csize, syntax, bufp)
2267131543Stjr     const char *cpattern;
2268131543Stjr     size_t csize;
2269131543Stjr#else
2270218Sconklinregex_compile (pattern, size, syntax, bufp)
2271218Sconklin     const char *pattern;
2272126209Sache     size_t size;
2273131543Stjr#endif /* MBS_SUPPORT */
2274218Sconklin     reg_syntax_t syntax;
2275218Sconklin     struct re_pattern_buffer *bufp;
2276218Sconklin{
2277218Sconklin  /* We fetch characters from PATTERN here.  Even though PATTERN is
2278218Sconklin     `char *' (i.e., signed), we declare these variables as unsigned, so
2279218Sconklin     they can be reliably used as array indices.  */
2280131543Stjr  register US_CHAR_TYPE c, c1;
2281126209Sache
2282131543Stjr#ifdef MBS_SUPPORT
2283131543Stjr  /* A temporary space to keep wchar_t pattern and compiled pattern.  */
2284131543Stjr  CHAR_TYPE *pattern, *COMPILED_BUFFER_VAR;
2285131543Stjr  size_t size;
2286131543Stjr  /* offset buffer for optimizatoin. See convert_mbs_to_wc.  */
2287131543Stjr  int *mbs_offset = NULL;
2288131543Stjr  /* It hold whether each wchar_t is binary data or not.  */
2289131543Stjr  char *is_binary = NULL;
2290131543Stjr  /* A flag whether exactn is handling binary data or not.  */
2291131543Stjr  char is_exactn_bin = FALSE;
2292131543Stjr#endif /* MBS_SUPPORT */
2293131543Stjr
2294126209Sache  /* A random temporary spot in PATTERN.  */
2295131543Stjr  const CHAR_TYPE *p1;
2296218Sconklin
2297218Sconklin  /* Points to the end of the buffer, where we should append.  */
2298131543Stjr  register US_CHAR_TYPE *b;
2299126209Sache
2300218Sconklin  /* Keeps track of unclosed groups.  */
2301218Sconklin  compile_stack_type compile_stack;
2302218Sconklin
2303218Sconklin  /* Points to the current (ending) position in the pattern.  */
2304131543Stjr#ifdef MBS_SUPPORT
2305131543Stjr  const CHAR_TYPE *p;
2306131543Stjr  const CHAR_TYPE *pend;
2307131543Stjr#else
2308131543Stjr  const CHAR_TYPE *p = pattern;
2309131543Stjr  const CHAR_TYPE *pend = pattern + size;
2310131543Stjr#endif /* MBS_SUPPORT */
2311126209Sache
2312218Sconklin  /* How to translate the characters in the pattern.  */
2313126209Sache  RE_TRANSLATE_TYPE translate = bufp->translate;
2314218Sconklin
2315218Sconklin  /* Address of the count-byte of the most recently inserted `exactn'
2316218Sconklin     command.  This makes it possible to tell if a new exact-match
2317218Sconklin     character can be added to that command or if the character requires
2318218Sconklin     a new `exactn' command.  */
2319131543Stjr  US_CHAR_TYPE *pending_exact = 0;
2320218Sconklin
2321218Sconklin  /* Address of start of the most recently finished expression.
2322218Sconklin     This tells, e.g., postfix * where to find the start of its
2323218Sconklin     operand.  Reset at the beginning of groups and alternatives.  */
2324131543Stjr  US_CHAR_TYPE *laststart = 0;
2325218Sconklin
2326218Sconklin  /* Address of beginning of regexp, or inside of last group.  */
2327131543Stjr  US_CHAR_TYPE *begalt;
2328218Sconklin
2329218Sconklin  /* Address of the place where a forward jump should go to the end of
2330218Sconklin     the containing expression.  Each alternative of an `or' -- except the
2331218Sconklin     last -- ends with a forward jump of this sort.  */
2332131543Stjr  US_CHAR_TYPE *fixup_alt_jump = 0;
2333218Sconklin
2334218Sconklin  /* Counts open-groups as they are encountered.  Remembered for the
2335218Sconklin     matching close-group on the compile stack, so the same register
2336218Sconklin     number is put in the stop_memory as the start_memory.  */
2337218Sconklin  regnum_t regnum = 0;
2338218Sconklin
2339131543Stjr#ifdef MBS_SUPPORT
2340131543Stjr  /* Initialize the wchar_t PATTERN and offset_buffer.  */
2341131543Stjr  p = pend = pattern = TALLOC(csize + 1, CHAR_TYPE);
2342131543Stjr  p[csize] = L'\0';	/* sentinel */
2343131543Stjr  mbs_offset = TALLOC(csize + 1, int);
2344131543Stjr  is_binary = TALLOC(csize + 1, char);
2345131543Stjr  if (pattern == NULL || mbs_offset == NULL || is_binary == NULL)
2346131543Stjr    {
2347131543Stjr      if (pattern) free(pattern);
2348131543Stjr      if (mbs_offset) free(mbs_offset);
2349131543Stjr      if (is_binary) free(is_binary);
2350131543Stjr      return REG_ESPACE;
2351131543Stjr    }
2352131543Stjr  size = convert_mbs_to_wcs(pattern, cpattern, csize, mbs_offset, is_binary);
2353131543Stjr  pend = p + size;
2354131543Stjr  if (size < 0)
2355131543Stjr    {
2356131543Stjr      if (pattern) free(pattern);
2357131543Stjr      if (mbs_offset) free(mbs_offset);
2358131543Stjr      if (is_binary) free(is_binary);
2359131543Stjr      return REG_BADPAT;
2360131543Stjr    }
2361131543Stjr#endif
2362131543Stjr
2363218Sconklin#ifdef DEBUG
2364218Sconklin  DEBUG_PRINT1 ("\nCompiling pattern: ");
2365218Sconklin  if (debug)
2366218Sconklin    {
2367218Sconklin      unsigned debug_count;
2368126209Sache
2369218Sconklin      for (debug_count = 0; debug_count < size; debug_count++)
2370131543Stjr        PUT_CHAR (pattern[debug_count]);
2371218Sconklin      putchar ('\n');
2372218Sconklin    }
2373218Sconklin#endif /* DEBUG */
2374218Sconklin
2375218Sconklin  /* Initialize the compile stack.  */
2376218Sconklin  compile_stack.stack = TALLOC (INIT_COMPILE_STACK_SIZE, compile_stack_elt_t);
2377218Sconklin  if (compile_stack.stack == NULL)
2378131543Stjr    {
2379131543Stjr#ifdef MBS_SUPPORT
2380131543Stjr      if (pattern) free(pattern);
2381131543Stjr      if (mbs_offset) free(mbs_offset);
2382131543Stjr      if (is_binary) free(is_binary);
2383131543Stjr#endif
2384131543Stjr      return REG_ESPACE;
2385131543Stjr    }
2386218Sconklin
2387218Sconklin  compile_stack.size = INIT_COMPILE_STACK_SIZE;
2388218Sconklin  compile_stack.avail = 0;
2389218Sconklin
2390218Sconklin  /* Initialize the pattern buffer.  */
2391218Sconklin  bufp->syntax = syntax;
2392218Sconklin  bufp->fastmap_accurate = 0;
2393218Sconklin  bufp->not_bol = bufp->not_eol = 0;
2394218Sconklin
2395218Sconklin  /* Set `used' to zero, so that if we return an error, the pattern
2396218Sconklin     printer (for debugging) will think there's no pattern.  We reset it
2397218Sconklin     at the end.  */
2398218Sconklin  bufp->used = 0;
2399126209Sache
2400218Sconklin  /* Always count groups, whether or not bufp->no_sub is set.  */
2401126209Sache  bufp->re_nsub = 0;
2402218Sconklin
2403126209Sache#if !defined emacs && !defined SYNTAX_TABLE
2404218Sconklin  /* Initialize the syntax table.  */
2405218Sconklin   init_syntax_once ();
2406218Sconklin#endif
2407218Sconklin
2408218Sconklin  if (bufp->allocated == 0)
2409218Sconklin    {
2410218Sconklin      if (bufp->buffer)
2411218Sconklin	{ /* If zero allocated, but buffer is non-null, try to realloc
2412218Sconklin             enough space.  This loses if buffer's address is bogus, but
2413218Sconklin             that is the user's responsibility.  */
2414131543Stjr#ifdef MBS_SUPPORT
2415131543Stjr	  /* Free bufp->buffer and allocate an array for wchar_t pattern
2416131543Stjr	     buffer.  */
2417131543Stjr          free(bufp->buffer);
2418131543Stjr          COMPILED_BUFFER_VAR = TALLOC (INIT_BUF_SIZE/sizeof(US_CHAR_TYPE),
2419131543Stjr					US_CHAR_TYPE);
2420131543Stjr#else
2421131543Stjr          RETALLOC (COMPILED_BUFFER_VAR, INIT_BUF_SIZE, US_CHAR_TYPE);
2422131543Stjr#endif /* MBS_SUPPORT */
2423218Sconklin        }
2424218Sconklin      else
2425218Sconklin        { /* Caller did not allocate a buffer.  Do it for them.  */
2426131543Stjr          COMPILED_BUFFER_VAR = TALLOC (INIT_BUF_SIZE / sizeof(US_CHAR_TYPE),
2427131543Stjr					US_CHAR_TYPE);
2428218Sconklin        }
2429218Sconklin
2430131543Stjr      if (!COMPILED_BUFFER_VAR) FREE_STACK_RETURN (REG_ESPACE);
2431131543Stjr#ifdef MBS_SUPPORT
2432131543Stjr      bufp->buffer = (char*)COMPILED_BUFFER_VAR;
2433131543Stjr#endif /* MBS_SUPPORT */
2434218Sconklin      bufp->allocated = INIT_BUF_SIZE;
2435218Sconklin    }
2436131543Stjr#ifdef MBS_SUPPORT
2437131543Stjr  else
2438131543Stjr    COMPILED_BUFFER_VAR = (US_CHAR_TYPE*) bufp->buffer;
2439131543Stjr#endif
2440218Sconklin
2441131543Stjr  begalt = b = COMPILED_BUFFER_VAR;
2442218Sconklin
2443218Sconklin  /* Loop through the uncompiled pattern until we're at the end.  */
2444218Sconklin  while (p != pend)
2445218Sconklin    {
2446218Sconklin      PATFETCH (c);
2447218Sconklin
2448218Sconklin      switch (c)
2449218Sconklin        {
2450218Sconklin        case '^':
2451218Sconklin          {
2452218Sconklin            if (   /* If at start of pattern, it's an operator.  */
2453218Sconklin                   p == pattern + 1
2454218Sconklin                   /* If context independent, it's an operator.  */
2455218Sconklin                || syntax & RE_CONTEXT_INDEP_ANCHORS
2456218Sconklin                   /* Otherwise, depends on what's come before.  */
2457218Sconklin                || at_begline_loc_p (pattern, p, syntax))
2458218Sconklin              BUF_PUSH (begline);
2459218Sconklin            else
2460218Sconklin              goto normal_char;
2461218Sconklin          }
2462218Sconklin          break;
2463218Sconklin
2464218Sconklin
2465218Sconklin        case '$':
2466218Sconklin          {
2467218Sconklin            if (   /* If at end of pattern, it's an operator.  */
2468126209Sache                   p == pend
2469218Sconklin                   /* If context independent, it's an operator.  */
2470218Sconklin                || syntax & RE_CONTEXT_INDEP_ANCHORS
2471218Sconklin                   /* Otherwise, depends on what's next.  */
2472218Sconklin                || at_endline_loc_p (p, pend, syntax))
2473218Sconklin               BUF_PUSH (endline);
2474218Sconklin             else
2475218Sconklin               goto normal_char;
2476218Sconklin           }
2477218Sconklin           break;
2478218Sconklin
2479218Sconklin
2480218Sconklin	case '+':
2481218Sconklin        case '?':
2482218Sconklin          if ((syntax & RE_BK_PLUS_QM)
2483218Sconklin              || (syntax & RE_LIMITED_OPS))
2484218Sconklin            goto normal_char;
2485218Sconklin        handle_plus:
2486218Sconklin        case '*':
2487218Sconklin          /* If there is no previous pattern... */
2488218Sconklin          if (!laststart)
2489218Sconklin            {
2490218Sconklin              if (syntax & RE_CONTEXT_INVALID_OPS)
2491126209Sache                FREE_STACK_RETURN (REG_BADRPT);
2492218Sconklin              else if (!(syntax & RE_CONTEXT_INDEP_OPS))
2493218Sconklin                goto normal_char;
2494218Sconklin            }
2495218Sconklin
2496218Sconklin          {
2497218Sconklin            /* Are we optimizing this jump?  */
2498218Sconklin            boolean keep_string_p = false;
2499126209Sache
2500218Sconklin            /* 1 means zero (many) matches is allowed.  */
2501218Sconklin            char zero_times_ok = 0, many_times_ok = 0;
2502218Sconklin
2503218Sconklin            /* If there is a sequence of repetition chars, collapse it
2504218Sconklin               down to just one (the right one).  We can't combine
2505218Sconklin               interval operators with these because of, e.g., `a{2}*',
2506218Sconklin               which should only match an even number of `a's.  */
2507218Sconklin
2508218Sconklin            for (;;)
2509218Sconklin              {
2510218Sconklin                zero_times_ok |= c != '+';
2511218Sconklin                many_times_ok |= c != '?';
2512218Sconklin
2513218Sconklin                if (p == pend)
2514218Sconklin                  break;
2515218Sconklin
2516218Sconklin                PATFETCH (c);
2517218Sconklin
2518218Sconklin                if (c == '*'
2519218Sconklin                    || (!(syntax & RE_BK_PLUS_QM) && (c == '+' || c == '?')))
2520218Sconklin                  ;
2521218Sconklin
2522218Sconklin                else if (syntax & RE_BK_PLUS_QM  &&  c == '\\')
2523218Sconklin                  {
2524126209Sache                    if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2525218Sconklin
2526218Sconklin                    PATFETCH (c1);
2527218Sconklin                    if (!(c1 == '+' || c1 == '?'))
2528218Sconklin                      {
2529218Sconklin                        PATUNFETCH;
2530218Sconklin                        PATUNFETCH;
2531218Sconklin                        break;
2532218Sconklin                      }
2533218Sconklin
2534218Sconklin                    c = c1;
2535218Sconklin                  }
2536218Sconklin                else
2537218Sconklin                  {
2538218Sconklin                    PATUNFETCH;
2539218Sconklin                    break;
2540218Sconklin                  }
2541218Sconklin
2542218Sconklin                /* If we get here, we found another repeat character.  */
2543218Sconklin               }
2544218Sconklin
2545218Sconklin            /* Star, etc. applied to an empty pattern is equivalent
2546218Sconklin               to an empty pattern.  */
2547126209Sache            if (!laststart)
2548218Sconklin              break;
2549218Sconklin
2550218Sconklin            /* Now we know whether or not zero matches is allowed
2551218Sconklin               and also whether or not two or more matches is allowed.  */
2552218Sconklin            if (many_times_ok)
2553218Sconklin              { /* More than one repetition is allowed, so put in at the
2554218Sconklin                   end a backward relative jump from `b' to before the next
2555218Sconklin                   jump we're going to put in below (which jumps from
2556126209Sache                   laststart to after this jump).
2557218Sconklin
2558218Sconklin                   But if we are at the `*' in the exact sequence `.*\n',
2559218Sconklin                   insert an unconditional jump backwards to the .,
2560218Sconklin                   instead of the beginning of the loop.  This way we only
2561218Sconklin                   push a failure point once, instead of every time
2562218Sconklin                   through the loop.  */
2563218Sconklin                assert (p - 1 > pattern);
2564218Sconklin
2565218Sconklin                /* Allocate the space for the jump.  */
2566131543Stjr                GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
2567218Sconklin
2568218Sconklin                /* We know we are not at the first character of the pattern,
2569218Sconklin                   because laststart was nonzero.  And we've already
2570218Sconklin                   incremented `p', by the way, to be the character after
2571218Sconklin                   the `*'.  Do we have to do something analogous here
2572218Sconklin                   for null bytes, because of RE_DOT_NOT_NULL?  */
2573218Sconklin                if (TRANSLATE (*(p - 2)) == TRANSLATE ('.')
2574218Sconklin		    && zero_times_ok
2575218Sconklin                    && p < pend && TRANSLATE (*p) == TRANSLATE ('\n')
2576218Sconklin                    && !(syntax & RE_DOT_NEWLINE))
2577218Sconklin                  { /* We have .*\n.  */
2578218Sconklin                    STORE_JUMP (jump, b, laststart);
2579218Sconklin                    keep_string_p = true;
2580218Sconklin                  }
2581218Sconklin                else
2582218Sconklin                  /* Anything else.  */
2583131543Stjr                  STORE_JUMP (maybe_pop_jump, b, laststart -
2584131543Stjr			      (1 + OFFSET_ADDRESS_SIZE));
2585218Sconklin
2586218Sconklin                /* We've added more stuff to the buffer.  */
2587131543Stjr                b += 1 + OFFSET_ADDRESS_SIZE;
2588218Sconklin              }
2589218Sconklin
2590218Sconklin            /* On failure, jump from laststart to b + 3, which will be the
2591218Sconklin               end of the buffer after this jump is inserted.  */
2592131543Stjr	    /* ifdef MBS_SUPPORT, 'b + 1 + OFFSET_ADDRESS_SIZE' instead of
2593131543Stjr	       'b + 3'.  */
2594131543Stjr            GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
2595218Sconklin            INSERT_JUMP (keep_string_p ? on_failure_keep_string_jump
2596218Sconklin                                       : on_failure_jump,
2597131543Stjr                         laststart, b + 1 + OFFSET_ADDRESS_SIZE);
2598218Sconklin            pending_exact = 0;
2599131543Stjr            b += 1 + OFFSET_ADDRESS_SIZE;
2600218Sconklin
2601218Sconklin            if (!zero_times_ok)
2602218Sconklin              {
2603218Sconklin                /* At least one repetition is required, so insert a
2604218Sconklin                   `dummy_failure_jump' before the initial
2605218Sconklin                   `on_failure_jump' instruction of the loop. This
2606218Sconklin                   effects a skip over that instruction the first time
2607218Sconklin                   we hit that loop.  */
2608131543Stjr                GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
2609131543Stjr                INSERT_JUMP (dummy_failure_jump, laststart, laststart +
2610131543Stjr			     2 + 2 * OFFSET_ADDRESS_SIZE);
2611131543Stjr                b += 1 + OFFSET_ADDRESS_SIZE;
2612218Sconklin              }
2613218Sconklin            }
2614218Sconklin	  break;
2615218Sconklin
2616218Sconklin
2617218Sconklin	case '.':
2618218Sconklin          laststart = b;
2619218Sconklin          BUF_PUSH (anychar);
2620218Sconklin          break;
2621218Sconklin
2622218Sconklin
2623218Sconklin        case '[':
2624218Sconklin          {
2625218Sconklin            boolean had_char_class = false;
2626131543Stjr#ifdef MBS_SUPPORT
2627131543Stjr	    CHAR_TYPE range_start = 0xffffffff;
2628131543Stjr#else
2629131543Stjr	    unsigned int range_start = 0xffffffff;
2630131543Stjr#endif
2631126209Sache            if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2632218Sconklin
2633131543Stjr#ifdef MBS_SUPPORT
2634131543Stjr	    /* We assume a charset(_not) structure as a wchar_t array.
2635131543Stjr	       charset[0] = (re_opcode_t) charset(_not)
2636131543Stjr               charset[1] = l (= length of char_classes)
2637131543Stjr               charset[2] = m (= length of collating_symbols)
2638131543Stjr               charset[3] = n (= length of equivalence_classes)
2639131543Stjr	       charset[4] = o (= length of char_ranges)
2640131543Stjr	       charset[5] = p (= length of chars)
2641131543Stjr
2642131543Stjr               charset[6] = char_class (wctype_t)
2643131543Stjr               charset[6+CHAR_CLASS_SIZE] = char_class (wctype_t)
2644131543Stjr                         ...
2645131543Stjr               charset[l+5]  = char_class (wctype_t)
2646131543Stjr
2647131543Stjr               charset[l+6]  = collating_symbol (wchar_t)
2648131543Stjr                            ...
2649131543Stjr               charset[l+m+5]  = collating_symbol (wchar_t)
2650131543Stjr					ifdef _LIBC we use the index if
2651131543Stjr					_NL_COLLATE_SYMB_EXTRAMB instead of
2652131543Stjr					wchar_t string.
2653131543Stjr
2654131543Stjr               charset[l+m+6]  = equivalence_classes (wchar_t)
2655131543Stjr                              ...
2656131543Stjr               charset[l+m+n+5]  = equivalence_classes (wchar_t)
2657131543Stjr					ifdef _LIBC we use the index in
2658131543Stjr					_NL_COLLATE_WEIGHT instead of
2659131543Stjr					wchar_t string.
2660131543Stjr
2661131543Stjr	       charset[l+m+n+6] = range_start
2662131543Stjr	       charset[l+m+n+7] = range_end
2663131543Stjr	                       ...
2664131543Stjr	       charset[l+m+n+2o+4] = range_start
2665131543Stjr	       charset[l+m+n+2o+5] = range_end
2666131543Stjr					ifdef _LIBC we use the value looked up
2667131543Stjr					in _NL_COLLATE_COLLSEQ instead of
2668131543Stjr					wchar_t character.
2669131543Stjr
2670131543Stjr	       charset[l+m+n+2o+6] = char
2671131543Stjr	                          ...
2672131543Stjr	       charset[l+m+n+2o+p+5] = char
2673131543Stjr
2674131543Stjr	     */
2675131543Stjr
2676131543Stjr	    /* We need at least 6 spaces: the opcode, the length of
2677131543Stjr               char_classes, the length of collating_symbols, the length of
2678131543Stjr               equivalence_classes, the length of char_ranges, the length of
2679131543Stjr               chars.  */
2680131543Stjr	    GET_BUFFER_SPACE (6);
2681131543Stjr
2682131543Stjr	    /* Save b as laststart. And We use laststart as the pointer
2683131543Stjr	       to the first element of the charset here.
2684131543Stjr	       In other words, laststart[i] indicates charset[i].  */
2685131543Stjr            laststart = b;
2686131543Stjr
2687131543Stjr            /* We test `*p == '^' twice, instead of using an if
2688131543Stjr               statement, so we only need one BUF_PUSH.  */
2689131543Stjr            BUF_PUSH (*p == '^' ? charset_not : charset);
2690131543Stjr            if (*p == '^')
2691131543Stjr              p++;
2692131543Stjr
2693131543Stjr            /* Push the length of char_classes, the length of
2694131543Stjr               collating_symbols, the length of equivalence_classes, the
2695131543Stjr               length of char_ranges and the length of chars.  */
2696131543Stjr            BUF_PUSH_3 (0, 0, 0);
2697131543Stjr            BUF_PUSH_2 (0, 0);
2698131543Stjr
2699131543Stjr            /* Remember the first position in the bracket expression.  */
2700131543Stjr            p1 = p;
2701131543Stjr
2702131543Stjr            /* charset_not matches newline according to a syntax bit.  */
2703131543Stjr            if ((re_opcode_t) b[-6] == charset_not
2704131543Stjr                && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
2705131543Stjr	      {
2706131543Stjr		BUF_PUSH('\n');
2707131543Stjr		laststart[5]++; /* Update the length of characters  */
2708131543Stjr	      }
2709131543Stjr
2710131543Stjr            /* Read in characters and ranges, setting map bits.  */
2711131543Stjr            for (;;)
2712131543Stjr              {
2713131543Stjr                if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2714131543Stjr
2715131543Stjr                PATFETCH (c);
2716131543Stjr
2717131543Stjr                /* \ might escape characters inside [...] and [^...].  */
2718131543Stjr                if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
2719131543Stjr                  {
2720131543Stjr                    if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2721131543Stjr
2722131543Stjr                    PATFETCH (c1);
2723131543Stjr		    BUF_PUSH(c1);
2724131543Stjr		    laststart[5]++; /* Update the length of chars  */
2725131543Stjr		    range_start = c1;
2726131543Stjr                    continue;
2727131543Stjr                  }
2728131543Stjr
2729131543Stjr                /* Could be the end of the bracket expression.  If it's
2730131543Stjr                   not (i.e., when the bracket expression is `[]' so
2731131543Stjr                   far), the ']' character bit gets set way below.  */
2732131543Stjr                if (c == ']' && p != p1 + 1)
2733131543Stjr                  break;
2734131543Stjr
2735131543Stjr                /* Look ahead to see if it's a range when the last thing
2736131543Stjr                   was a character class.  */
2737131543Stjr                if (had_char_class && c == '-' && *p != ']')
2738131543Stjr                  FREE_STACK_RETURN (REG_ERANGE);
2739131543Stjr
2740131543Stjr                /* Look ahead to see if it's a range when the last thing
2741131543Stjr                   was a character: if this is a hyphen not at the
2742131543Stjr                   beginning or the end of a list, then it's the range
2743131543Stjr                   operator.  */
2744131543Stjr                if (c == '-'
2745131543Stjr                    && !(p - 2 >= pattern && p[-2] == '[')
2746131543Stjr                    && !(p - 3 >= pattern && p[-3] == '[' && p[-2] == '^')
2747131543Stjr                    && *p != ']')
2748131543Stjr                  {
2749131543Stjr                    reg_errcode_t ret;
2750131543Stjr		    /* Allocate the space for range_start and range_end.  */
2751131543Stjr		    GET_BUFFER_SPACE (2);
2752131543Stjr		    /* Update the pointer to indicate end of buffer.  */
2753131543Stjr                    b += 2;
2754131543Stjr                    ret = compile_range (range_start, &p, pend, translate,
2755131543Stjr                                         syntax, b, laststart);
2756131543Stjr                    if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
2757131543Stjr                    range_start = 0xffffffff;
2758131543Stjr                  }
2759131543Stjr                else if (p[0] == '-' && p[1] != ']')
2760131543Stjr                  { /* This handles ranges made up of characters only.  */
2761131543Stjr                    reg_errcode_t ret;
2762131543Stjr
2763131543Stjr		    /* Move past the `-'.  */
2764131543Stjr                    PATFETCH (c1);
2765131543Stjr		    /* Allocate the space for range_start and range_end.  */
2766131543Stjr		    GET_BUFFER_SPACE (2);
2767131543Stjr		    /* Update the pointer to indicate end of buffer.  */
2768131543Stjr                    b += 2;
2769131543Stjr                    ret = compile_range (c, &p, pend, translate, syntax, b,
2770131543Stjr                                         laststart);
2771131543Stjr                    if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
2772131543Stjr		    range_start = 0xffffffff;
2773131543Stjr                  }
2774131543Stjr
2775131543Stjr                /* See if we're at the beginning of a possible character
2776131543Stjr                   class.  */
2777131543Stjr                else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == ':')
2778131543Stjr                  { /* Leave room for the null.  */
2779131543Stjr                    char str[CHAR_CLASS_MAX_LENGTH + 1];
2780131543Stjr
2781131543Stjr                    PATFETCH (c);
2782131543Stjr                    c1 = 0;
2783131543Stjr
2784131543Stjr                    /* If pattern is `[[:'.  */
2785131543Stjr                    if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2786131543Stjr
2787131543Stjr                    for (;;)
2788131543Stjr                      {
2789131543Stjr                        PATFETCH (c);
2790131543Stjr                        if ((c == ':' && *p == ']') || p == pend)
2791131543Stjr                          break;
2792131543Stjr			if (c1 < CHAR_CLASS_MAX_LENGTH)
2793131543Stjr			  str[c1++] = c;
2794131543Stjr			else
2795131543Stjr			  /* This is in any case an invalid class name.  */
2796131543Stjr			  str[0] = '\0';
2797131543Stjr                      }
2798131543Stjr                    str[c1] = '\0';
2799131543Stjr
2800131543Stjr                    /* If isn't a word bracketed by `[:' and `:]':
2801131543Stjr                       undo the ending character, the letters, and leave
2802131543Stjr                       the leading `:' and `[' (but store them as character).  */
2803131543Stjr                    if (c == ':' && *p == ']')
2804131543Stjr                      {
2805131543Stjr			wctype_t wt;
2806131543Stjr			uintptr_t alignedp;
2807131543Stjr
2808131543Stjr			/* Query the character class as wctype_t.  */
2809131543Stjr			wt = IS_CHAR_CLASS (str);
2810131543Stjr			if (wt == 0)
2811131543Stjr			  FREE_STACK_RETURN (REG_ECTYPE);
2812131543Stjr
2813131543Stjr                        /* Throw away the ] at the end of the character
2814131543Stjr                           class.  */
2815131543Stjr                        PATFETCH (c);
2816131543Stjr
2817131543Stjr                        if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2818131543Stjr
2819131543Stjr			/* Allocate the space for character class.  */
2820131543Stjr                        GET_BUFFER_SPACE(CHAR_CLASS_SIZE);
2821131543Stjr			/* Update the pointer to indicate end of buffer.  */
2822131543Stjr                        b += CHAR_CLASS_SIZE;
2823131543Stjr			/* Move data which follow character classes
2824131543Stjr			    not to violate the data.  */
2825131543Stjr                        insert_space(CHAR_CLASS_SIZE,
2826131543Stjr				     laststart + 6 + laststart[1],
2827131543Stjr				     b - 1);
2828131543Stjr			alignedp = ((uintptr_t)(laststart + 6 + laststart[1])
2829131543Stjr				    + __alignof__(wctype_t) - 1)
2830131543Stjr			  	    & ~(uintptr_t)(__alignof__(wctype_t) - 1);
2831131543Stjr			/* Store the character class.  */
2832131543Stjr                        *((wctype_t*)alignedp) = wt;
2833131543Stjr                        /* Update length of char_classes */
2834131543Stjr                        laststart[1] += CHAR_CLASS_SIZE;
2835131543Stjr
2836131543Stjr                        had_char_class = true;
2837131543Stjr                      }
2838131543Stjr                    else
2839131543Stjr                      {
2840131543Stjr                        c1++;
2841131543Stjr                        while (c1--)
2842131543Stjr                          PATUNFETCH;
2843131543Stjr                        BUF_PUSH ('[');
2844131543Stjr                        BUF_PUSH (':');
2845131543Stjr                        laststart[5] += 2; /* Update the length of characters  */
2846131543Stjr			range_start = ':';
2847131543Stjr                        had_char_class = false;
2848131543Stjr                      }
2849131543Stjr                  }
2850131543Stjr                else if (syntax & RE_CHAR_CLASSES && c == '[' && (*p == '='
2851131543Stjr							  || *p == '.'))
2852131543Stjr		  {
2853131543Stjr		    CHAR_TYPE str[128];	/* Should be large enough.  */
2854131543Stjr		    CHAR_TYPE delim = *p; /* '=' or '.'  */
2855131543Stjr# ifdef _LIBC
2856131543Stjr		    uint32_t nrules =
2857131543Stjr		      _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
2858131543Stjr# endif
2859131543Stjr		    PATFETCH (c);
2860131543Stjr		    c1 = 0;
2861131543Stjr
2862131543Stjr		    /* If pattern is `[[=' or '[[.'.  */
2863131543Stjr		    if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2864131543Stjr
2865131543Stjr		    for (;;)
2866131543Stjr		      {
2867131543Stjr			PATFETCH (c);
2868131543Stjr			if ((c == delim && *p == ']') || p == pend)
2869131543Stjr			  break;
2870131543Stjr			if (c1 < sizeof (str) - 1)
2871131543Stjr			  str[c1++] = c;
2872131543Stjr			else
2873131543Stjr			  /* This is in any case an invalid class name.  */
2874131543Stjr			  str[0] = '\0';
2875131543Stjr                      }
2876131543Stjr		    str[c1] = '\0';
2877131543Stjr
2878131543Stjr		    if (c == delim && *p == ']' && str[0] != '\0')
2879131543Stjr		      {
2880131543Stjr                        unsigned int i, offset;
2881131543Stjr			/* If we have no collation data we use the default
2882131543Stjr			   collation in which each character is in a class
2883131543Stjr			   by itself.  It also means that ASCII is the
2884131543Stjr			   character set and therefore we cannot have character
2885131543Stjr			   with more than one byte in the multibyte
2886131543Stjr			   representation.  */
2887131543Stjr
2888131543Stjr                        /* If not defined _LIBC, we push the name and
2889131543Stjr			   `\0' for the sake of matching performance.  */
2890131543Stjr			int datasize = c1 + 1;
2891131543Stjr
2892131543Stjr# ifdef _LIBC
2893131543Stjr			int32_t idx = 0;
2894131543Stjr			if (nrules == 0)
2895131543Stjr# endif
2896131543Stjr			  {
2897131543Stjr			    if (c1 != 1)
2898131543Stjr			      FREE_STACK_RETURN (REG_ECOLLATE);
2899131543Stjr			  }
2900131543Stjr# ifdef _LIBC
2901131543Stjr			else
2902131543Stjr			  {
2903131543Stjr			    const int32_t *table;
2904131543Stjr			    const int32_t *weights;
2905131543Stjr			    const int32_t *extra;
2906131543Stjr			    const int32_t *indirect;
2907131543Stjr			    wint_t *cp;
2908131543Stjr
2909131543Stjr			    /* This #include defines a local function!  */
2910131543Stjr#  include <locale/weightwc.h>
2911131543Stjr
2912131543Stjr			    if(delim == '=')
2913131543Stjr			      {
2914131543Stjr				/* We push the index for equivalence class.  */
2915131543Stjr				cp = (wint_t*)str;
2916131543Stjr
2917131543Stjr				table = (const int32_t *)
2918131543Stjr				  _NL_CURRENT (LC_COLLATE,
2919131543Stjr					       _NL_COLLATE_TABLEWC);
2920131543Stjr				weights = (const int32_t *)
2921131543Stjr				  _NL_CURRENT (LC_COLLATE,
2922131543Stjr					       _NL_COLLATE_WEIGHTWC);
2923131543Stjr				extra = (const int32_t *)
2924131543Stjr				  _NL_CURRENT (LC_COLLATE,
2925131543Stjr					       _NL_COLLATE_EXTRAWC);
2926131543Stjr				indirect = (const int32_t *)
2927131543Stjr				  _NL_CURRENT (LC_COLLATE,
2928131543Stjr					       _NL_COLLATE_INDIRECTWC);
2929131543Stjr
2930131543Stjr				idx = findidx ((const wint_t**)&cp);
2931131543Stjr				if (idx == 0 || cp < (wint_t*) str + c1)
2932131543Stjr				  /* This is no valid character.  */
2933131543Stjr				  FREE_STACK_RETURN (REG_ECOLLATE);
2934131543Stjr
2935131543Stjr				str[0] = (wchar_t)idx;
2936131543Stjr			      }
2937131543Stjr			    else /* delim == '.' */
2938131543Stjr			      {
2939131543Stjr				/* We push collation sequence value
2940131543Stjr				   for collating symbol.  */
2941131543Stjr				int32_t table_size;
2942131543Stjr				const int32_t *symb_table;
2943131543Stjr				const unsigned char *extra;
2944131543Stjr				int32_t idx;
2945131543Stjr				int32_t elem;
2946131543Stjr				int32_t second;
2947131543Stjr				int32_t hash;
2948131543Stjr				char char_str[c1];
2949131543Stjr
2950131543Stjr				/* We have to convert the name to a single-byte
2951131543Stjr				   string.  This is possible since the names
2952131543Stjr				   consist of ASCII characters and the internal
2953131543Stjr				   representation is UCS4.  */
2954131543Stjr				for (i = 0; i < c1; ++i)
2955131543Stjr				  char_str[i] = str[i];
2956131543Stjr
2957131543Stjr				table_size =
2958131543Stjr				  _NL_CURRENT_WORD (LC_COLLATE,
2959131543Stjr						    _NL_COLLATE_SYMB_HASH_SIZEMB);
2960131543Stjr				symb_table = (const int32_t *)
2961131543Stjr				  _NL_CURRENT (LC_COLLATE,
2962131543Stjr					       _NL_COLLATE_SYMB_TABLEMB);
2963131543Stjr				extra = (const unsigned char *)
2964131543Stjr				  _NL_CURRENT (LC_COLLATE,
2965131543Stjr					       _NL_COLLATE_SYMB_EXTRAMB);
2966131543Stjr
2967131543Stjr				/* Locate the character in the hashing table.  */
2968131543Stjr				hash = elem_hash (char_str, c1);
2969131543Stjr
2970131543Stjr				idx = 0;
2971131543Stjr				elem = hash % table_size;
2972131543Stjr				second = hash % (table_size - 2);
2973131543Stjr				while (symb_table[2 * elem] != 0)
2974131543Stjr				  {
2975131543Stjr				    /* First compare the hashing value.  */
2976131543Stjr				    if (symb_table[2 * elem] == hash
2977131543Stjr					&& c1 == extra[symb_table[2 * elem + 1]]
2978131543Stjr					&& memcmp (str,
2979131543Stjr						   &extra[symb_table[2 * elem + 1]
2980131543Stjr							 + 1], c1) == 0)
2981131543Stjr				      {
2982131543Stjr					/* Yep, this is the entry.  */
2983131543Stjr					idx = symb_table[2 * elem + 1];
2984131543Stjr					idx += 1 + extra[idx];
2985131543Stjr					break;
2986131543Stjr				      }
2987131543Stjr
2988131543Stjr				    /* Next entry.  */
2989131543Stjr				    elem += second;
2990131543Stjr				  }
2991131543Stjr
2992131543Stjr				if (symb_table[2 * elem] != 0)
2993131543Stjr				  {
2994131543Stjr				    /* Compute the index of the byte sequence
2995131543Stjr				       in the table.  */
2996131543Stjr				    idx += 1 + extra[idx];
2997131543Stjr				    /* Adjust for the alignment.  */
2998131543Stjr				    idx = (idx + 3) & ~4;
2999131543Stjr
3000131543Stjr				    str[0] = (wchar_t) idx + 4;
3001131543Stjr				  }
3002131543Stjr				else if (symb_table[2 * elem] == 0 && c1 == 1)
3003131543Stjr				  {
3004131543Stjr				    /* No valid character.  Match it as a
3005131543Stjr				       single byte character.  */
3006131543Stjr				    had_char_class = false;
3007131543Stjr				    BUF_PUSH(str[0]);
3008131543Stjr				    /* Update the length of characters  */
3009131543Stjr				    laststart[5]++;
3010131543Stjr				    range_start = str[0];
3011131543Stjr
3012131543Stjr				    /* Throw away the ] at the end of the
3013131543Stjr				       collating symbol.  */
3014131543Stjr				    PATFETCH (c);
3015131543Stjr				    /* exit from the switch block.  */
3016131543Stjr				    continue;
3017131543Stjr				  }
3018131543Stjr				else
3019131543Stjr				  FREE_STACK_RETURN (REG_ECOLLATE);
3020131543Stjr			      }
3021131543Stjr			    datasize = 1;
3022131543Stjr			  }
3023131543Stjr# endif
3024131543Stjr                        /* Throw away the ] at the end of the equivalence
3025131543Stjr                           class (or collating symbol).  */
3026131543Stjr                        PATFETCH (c);
3027131543Stjr
3028131543Stjr			/* Allocate the space for the equivalence class
3029131543Stjr			   (or collating symbol) (and '\0' if needed).  */
3030131543Stjr                        GET_BUFFER_SPACE(datasize);
3031131543Stjr			/* Update the pointer to indicate end of buffer.  */
3032131543Stjr                        b += datasize;
3033131543Stjr
3034131543Stjr			if (delim == '=')
3035131543Stjr			  { /* equivalence class  */
3036131543Stjr			    /* Calculate the offset of char_ranges,
3037131543Stjr			       which is next to equivalence_classes.  */
3038131543Stjr			    offset = laststart[1] + laststart[2]
3039131543Stjr			      + laststart[3] +6;
3040131543Stjr			    /* Insert space.  */
3041131543Stjr			    insert_space(datasize, laststart + offset, b - 1);
3042131543Stjr
3043131543Stjr			    /* Write the equivalence_class and \0.  */
3044131543Stjr			    for (i = 0 ; i < datasize ; i++)
3045131543Stjr			      laststart[offset + i] = str[i];
3046131543Stjr
3047131543Stjr			    /* Update the length of equivalence_classes.  */
3048131543Stjr			    laststart[3] += datasize;
3049131543Stjr			    had_char_class = true;
3050131543Stjr			  }
3051131543Stjr			else /* delim == '.' */
3052131543Stjr			  { /* collating symbol  */
3053131543Stjr			    /* Calculate the offset of the equivalence_classes,
3054131543Stjr			       which is next to collating_symbols.  */
3055131543Stjr			    offset = laststart[1] + laststart[2] + 6;
3056131543Stjr			    /* Insert space and write the collationg_symbol
3057131543Stjr			       and \0.  */
3058131543Stjr			    insert_space(datasize, laststart + offset, b-1);
3059131543Stjr			    for (i = 0 ; i < datasize ; i++)
3060131543Stjr			      laststart[offset + i] = str[i];
3061131543Stjr
3062131543Stjr			    /* In re_match_2_internal if range_start < -1, we
3063131543Stjr			       assume -range_start is the offset of the
3064131543Stjr			       collating symbol which is specified as
3065131543Stjr			       the character of the range start.  So we assign
3066131543Stjr			       -(laststart[1] + laststart[2] + 6) to
3067131543Stjr			       range_start.  */
3068131543Stjr			    range_start = -(laststart[1] + laststart[2] + 6);
3069131543Stjr			    /* Update the length of collating_symbol.  */
3070131543Stjr			    laststart[2] += datasize;
3071131543Stjr			    had_char_class = false;
3072131543Stjr			  }
3073131543Stjr		      }
3074131543Stjr                    else
3075131543Stjr                      {
3076131543Stjr                        c1++;
3077131543Stjr                        while (c1--)
3078131543Stjr                          PATUNFETCH;
3079131543Stjr                        BUF_PUSH ('[');
3080131543Stjr                        BUF_PUSH (delim);
3081131543Stjr                        laststart[5] += 2; /* Update the length of characters  */
3082131543Stjr			range_start = delim;
3083131543Stjr                        had_char_class = false;
3084131543Stjr                      }
3085131543Stjr		  }
3086131543Stjr                else
3087131543Stjr                  {
3088131543Stjr                    had_char_class = false;
3089131543Stjr		    BUF_PUSH(c);
3090131543Stjr		    laststart[5]++;  /* Update the length of characters  */
3091131543Stjr		    range_start = c;
3092131543Stjr                  }
3093131543Stjr	      }
3094131543Stjr
3095131543Stjr#else /* not MBS_SUPPORT */
3096218Sconklin            /* Ensure that we have enough space to push a charset: the
3097218Sconklin               opcode, the length count, and the bitset; 34 bytes in all.  */
3098218Sconklin	    GET_BUFFER_SPACE (34);
3099218Sconklin
3100218Sconklin            laststart = b;
3101218Sconklin
3102218Sconklin            /* We test `*p == '^' twice, instead of using an if
3103218Sconklin               statement, so we only need one BUF_PUSH.  */
3104126209Sache            BUF_PUSH (*p == '^' ? charset_not : charset);
3105218Sconklin            if (*p == '^')
3106218Sconklin              p++;
3107218Sconklin
3108218Sconklin            /* Remember the first position in the bracket expression.  */
3109218Sconklin            p1 = p;
3110218Sconklin
3111218Sconklin            /* Push the number of bytes in the bitmap.  */
3112218Sconklin            BUF_PUSH ((1 << BYTEWIDTH) / BYTEWIDTH);
3113218Sconklin
3114218Sconklin            /* Clear the whole map.  */
3115218Sconklin            bzero (b, (1 << BYTEWIDTH) / BYTEWIDTH);
3116218Sconklin
3117218Sconklin            /* charset_not matches newline according to a syntax bit.  */
3118218Sconklin            if ((re_opcode_t) b[-2] == charset_not
3119218Sconklin                && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
3120218Sconklin              SET_LIST_BIT ('\n');
3121218Sconklin
3122218Sconklin            /* Read in characters and ranges, setting map bits.  */
3123218Sconklin            for (;;)
3124218Sconklin              {
3125126209Sache                if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3126218Sconklin
3127218Sconklin                PATFETCH (c);
3128218Sconklin
3129218Sconklin                /* \ might escape characters inside [...] and [^...].  */
3130218Sconklin                if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
3131218Sconklin                  {
3132126209Sache                    if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
3133218Sconklin
3134218Sconklin                    PATFETCH (c1);
3135218Sconklin                    SET_LIST_BIT (c1);
3136131543Stjr		    range_start = c1;
3137218Sconklin                    continue;
3138218Sconklin                  }
3139218Sconklin
3140218Sconklin                /* Could be the end of the bracket expression.  If it's
3141218Sconklin                   not (i.e., when the bracket expression is `[]' so
3142218Sconklin                   far), the ']' character bit gets set way below.  */
3143218Sconklin                if (c == ']' && p != p1 + 1)
3144218Sconklin                  break;
3145218Sconklin
3146218Sconklin                /* Look ahead to see if it's a range when the last thing
3147218Sconklin                   was a character class.  */
3148218Sconklin                if (had_char_class && c == '-' && *p != ']')
3149126209Sache                  FREE_STACK_RETURN (REG_ERANGE);
3150218Sconklin
3151218Sconklin                /* Look ahead to see if it's a range when the last thing
3152218Sconklin                   was a character: if this is a hyphen not at the
3153218Sconklin                   beginning or the end of a list, then it's the range
3154218Sconklin                   operator.  */
3155126209Sache                if (c == '-'
3156126209Sache                    && !(p - 2 >= pattern && p[-2] == '[')
3157218Sconklin                    && !(p - 3 >= pattern && p[-3] == '[' && p[-2] == '^')
3158218Sconklin                    && *p != ']')
3159218Sconklin                  {
3160218Sconklin                    reg_errcode_t ret
3161131543Stjr                      = compile_range (range_start, &p, pend, translate,
3162131543Stjr				       syntax, b);
3163126209Sache                    if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
3164131543Stjr		    range_start = 0xffffffff;
3165218Sconklin                  }
3166218Sconklin
3167218Sconklin                else if (p[0] == '-' && p[1] != ']')
3168218Sconklin                  { /* This handles ranges made up of characters only.  */
3169218Sconklin                    reg_errcode_t ret;
3170218Sconklin
3171218Sconklin		    /* Move past the `-'.  */
3172218Sconklin                    PATFETCH (c1);
3173126209Sache
3174131543Stjr                    ret = compile_range (c, &p, pend, translate, syntax, b);
3175126209Sache                    if (ret != REG_NOERROR) FREE_STACK_RETURN (ret);
3176131543Stjr		    range_start = 0xffffffff;
3177218Sconklin                  }
3178218Sconklin
3179218Sconklin                /* See if we're at the beginning of a possible character
3180218Sconklin                   class.  */
3181218Sconklin
3182218Sconklin                else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == ':')
3183218Sconklin                  { /* Leave room for the null.  */
3184218Sconklin                    char str[CHAR_CLASS_MAX_LENGTH + 1];
3185218Sconklin
3186218Sconklin                    PATFETCH (c);
3187218Sconklin                    c1 = 0;
3188218Sconklin
3189218Sconklin                    /* If pattern is `[[:'.  */
3190126209Sache                    if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3191218Sconklin
3192218Sconklin                    for (;;)
3193218Sconklin                      {
3194218Sconklin                        PATFETCH (c);
3195126209Sache                        if ((c == ':' && *p == ']') || p == pend)
3196218Sconklin                          break;
3197126209Sache			if (c1 < CHAR_CLASS_MAX_LENGTH)
3198126209Sache			  str[c1++] = c;
3199126209Sache			else
3200126209Sache			  /* This is in any case an invalid class name.  */
3201126209Sache			  str[0] = '\0';
3202218Sconklin                      }
3203218Sconklin                    str[c1] = '\0';
3204218Sconklin
3205126209Sache                    /* If isn't a word bracketed by `[:' and `:]':
3206126209Sache                       undo the ending character, the letters, and leave
3207218Sconklin                       the leading `:' and `[' (but set bits for them).  */
3208218Sconklin                    if (c == ':' && *p == ']')
3209218Sconklin                      {
3210131543Stjr# if defined _LIBC || WIDE_CHAR_SUPPORT
3211126209Sache                        boolean is_lower = STREQ (str, "lower");
3212126209Sache                        boolean is_upper = STREQ (str, "upper");
3213126209Sache			wctype_t wt;
3214218Sconklin                        int ch;
3215126209Sache
3216126209Sache			wt = IS_CHAR_CLASS (str);
3217126209Sache			if (wt == 0)
3218126209Sache			  FREE_STACK_RETURN (REG_ECTYPE);
3219126209Sache
3220126209Sache                        /* Throw away the ] at the end of the character
3221126209Sache                           class.  */
3222126209Sache                        PATFETCH (c);
3223126209Sache
3224126209Sache                        if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3225126209Sache
3226126209Sache                        for (ch = 0; ch < 1 << BYTEWIDTH; ++ch)
3227126209Sache			  {
3228131543Stjr#  ifdef _LIBC
3229126209Sache			    if (__iswctype (__btowc (ch), wt))
3230126209Sache			      SET_LIST_BIT (ch);
3231131543Stjr#  else
3232126209Sache			    if (iswctype (btowc (ch), wt))
3233126209Sache			      SET_LIST_BIT (ch);
3234131543Stjr#  endif
3235126209Sache
3236126209Sache			    if (translate && (is_upper || is_lower)
3237126209Sache				&& (ISUPPER (ch) || ISLOWER (ch)))
3238126209Sache			      SET_LIST_BIT (ch);
3239126209Sache			  }
3240126209Sache
3241126209Sache                        had_char_class = true;
3242131543Stjr# else
3243126209Sache                        int ch;
3244218Sconklin                        boolean is_alnum = STREQ (str, "alnum");
3245218Sconklin                        boolean is_alpha = STREQ (str, "alpha");
3246218Sconklin                        boolean is_blank = STREQ (str, "blank");
3247218Sconklin                        boolean is_cntrl = STREQ (str, "cntrl");
3248218Sconklin                        boolean is_digit = STREQ (str, "digit");
3249218Sconklin                        boolean is_graph = STREQ (str, "graph");
3250218Sconklin                        boolean is_lower = STREQ (str, "lower");
3251218Sconklin                        boolean is_print = STREQ (str, "print");
3252218Sconklin                        boolean is_punct = STREQ (str, "punct");
3253218Sconklin                        boolean is_space = STREQ (str, "space");
3254218Sconklin                        boolean is_upper = STREQ (str, "upper");
3255218Sconklin                        boolean is_xdigit = STREQ (str, "xdigit");
3256218Sconklin
3257126209Sache                        if (!IS_CHAR_CLASS (str))
3258126209Sache			  FREE_STACK_RETURN (REG_ECTYPE);
3259126209Sache
3260218Sconklin                        /* Throw away the ] at the end of the character
3261218Sconklin                           class.  */
3262126209Sache                        PATFETCH (c);
3263218Sconklin
3264126209Sache                        if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3265218Sconklin
3266218Sconklin                        for (ch = 0; ch < 1 << BYTEWIDTH; ch++)
3267218Sconklin                          {
3268126209Sache			    /* This was split into 3 if's to
3269126209Sache			       avoid an arbitrary limit in some compiler.  */
3270218Sconklin                            if (   (is_alnum  && ISALNUM (ch))
3271218Sconklin                                || (is_alpha  && ISALPHA (ch))
3272218Sconklin                                || (is_blank  && ISBLANK (ch))
3273126209Sache                                || (is_cntrl  && ISCNTRL (ch)))
3274126209Sache			      SET_LIST_BIT (ch);
3275126209Sache			    if (   (is_digit  && ISDIGIT (ch))
3276218Sconklin                                || (is_graph  && ISGRAPH (ch))
3277218Sconklin                                || (is_lower  && ISLOWER (ch))
3278126209Sache                                || (is_print  && ISPRINT (ch)))
3279126209Sache			      SET_LIST_BIT (ch);
3280126209Sache			    if (   (is_punct  && ISPUNCT (ch))
3281218Sconklin                                || (is_space  && ISSPACE (ch))
3282218Sconklin                                || (is_upper  && ISUPPER (ch))
3283218Sconklin                                || (is_xdigit && ISXDIGIT (ch)))
3284126209Sache			      SET_LIST_BIT (ch);
3285126209Sache			    if (   translate && (is_upper || is_lower)
3286126209Sache				&& (ISUPPER (ch) || ISLOWER (ch)))
3287126209Sache			      SET_LIST_BIT (ch);
3288218Sconklin                          }
3289218Sconklin                        had_char_class = true;
3290131543Stjr# endif	/* libc || wctype.h */
3291218Sconklin                      }
3292218Sconklin                    else
3293218Sconklin                      {
3294218Sconklin                        c1++;
3295126209Sache                        while (c1--)
3296218Sconklin                          PATUNFETCH;
3297218Sconklin                        SET_LIST_BIT ('[');
3298218Sconklin                        SET_LIST_BIT (':');
3299131543Stjr			range_start = ':';
3300218Sconklin                        had_char_class = false;
3301218Sconklin                      }
3302218Sconklin                  }
3303131543Stjr                else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == '=')
3304131543Stjr		  {
3305131543Stjr		    unsigned char str[MB_LEN_MAX + 1];
3306131543Stjr# ifdef _LIBC
3307131543Stjr		    uint32_t nrules =
3308131543Stjr		      _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
3309131543Stjr# endif
3310131543Stjr
3311131543Stjr		    PATFETCH (c);
3312131543Stjr		    c1 = 0;
3313131543Stjr
3314131543Stjr		    /* If pattern is `[[='.  */
3315131543Stjr		    if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3316131543Stjr
3317131543Stjr		    for (;;)
3318131543Stjr		      {
3319131543Stjr			PATFETCH (c);
3320131543Stjr			if ((c == '=' && *p == ']') || p == pend)
3321131543Stjr			  break;
3322131543Stjr			if (c1 < MB_LEN_MAX)
3323131543Stjr			  str[c1++] = c;
3324131543Stjr			else
3325131543Stjr			  /* This is in any case an invalid class name.  */
3326131543Stjr			  str[0] = '\0';
3327131543Stjr                      }
3328131543Stjr		    str[c1] = '\0';
3329131543Stjr
3330131543Stjr		    if (c == '=' && *p == ']' && str[0] != '\0')
3331131543Stjr		      {
3332131543Stjr			/* If we have no collation data we use the default
3333131543Stjr			   collation in which each character is in a class
3334131543Stjr			   by itself.  It also means that ASCII is the
3335131543Stjr			   character set and therefore we cannot have character
3336131543Stjr			   with more than one byte in the multibyte
3337131543Stjr			   representation.  */
3338131543Stjr# ifdef _LIBC
3339131543Stjr			if (nrules == 0)
3340131543Stjr# endif
3341131543Stjr			  {
3342131543Stjr			    if (c1 != 1)
3343131543Stjr			      FREE_STACK_RETURN (REG_ECOLLATE);
3344131543Stjr
3345131543Stjr			    /* Throw away the ] at the end of the equivalence
3346131543Stjr			       class.  */
3347131543Stjr			    PATFETCH (c);
3348131543Stjr
3349131543Stjr			    /* Set the bit for the character.  */
3350131543Stjr			    SET_LIST_BIT (str[0]);
3351131543Stjr			  }
3352131543Stjr# ifdef _LIBC
3353131543Stjr			else
3354131543Stjr			  {
3355131543Stjr			    /* Try to match the byte sequence in `str' against
3356131543Stjr			       those known to the collate implementation.
3357131543Stjr			       First find out whether the bytes in `str' are
3358131543Stjr			       actually from exactly one character.  */
3359131543Stjr			    const int32_t *table;
3360131543Stjr			    const unsigned char *weights;
3361131543Stjr			    const unsigned char *extra;
3362131543Stjr			    const int32_t *indirect;
3363131543Stjr			    int32_t idx;
3364131543Stjr			    const unsigned char *cp = str;
3365131543Stjr			    int ch;
3366131543Stjr
3367131543Stjr			    /* This #include defines a local function!  */
3368131543Stjr#  include <locale/weight.h>
3369131543Stjr
3370131543Stjr			    table = (const int32_t *)
3371131543Stjr			      _NL_CURRENT (LC_COLLATE, _NL_COLLATE_TABLEMB);
3372131543Stjr			    weights = (const unsigned char *)
3373131543Stjr			      _NL_CURRENT (LC_COLLATE, _NL_COLLATE_WEIGHTMB);
3374131543Stjr			    extra = (const unsigned char *)
3375131543Stjr			      _NL_CURRENT (LC_COLLATE, _NL_COLLATE_EXTRAMB);
3376131543Stjr			    indirect = (const int32_t *)
3377131543Stjr			      _NL_CURRENT (LC_COLLATE, _NL_COLLATE_INDIRECTMB);
3378131543Stjr
3379131543Stjr			    idx = findidx (&cp);
3380131543Stjr			    if (idx == 0 || cp < str + c1)
3381131543Stjr			      /* This is no valid character.  */
3382131543Stjr			      FREE_STACK_RETURN (REG_ECOLLATE);
3383131543Stjr
3384131543Stjr			    /* Throw away the ] at the end of the equivalence
3385131543Stjr			       class.  */
3386131543Stjr			    PATFETCH (c);
3387131543Stjr
3388131543Stjr			    /* Now we have to go throught the whole table
3389131543Stjr			       and find all characters which have the same
3390131543Stjr			       first level weight.
3391131543Stjr
3392131543Stjr			       XXX Note that this is not entirely correct.
3393131543Stjr			       we would have to match multibyte sequences
3394131543Stjr			       but this is not possible with the current
3395131543Stjr			       implementation.  */
3396131543Stjr			    for (ch = 1; ch < 256; ++ch)
3397131543Stjr			      /* XXX This test would have to be changed if we
3398131543Stjr				 would allow matching multibyte sequences.  */
3399131543Stjr			      if (table[ch] > 0)
3400131543Stjr				{
3401131543Stjr				  int32_t idx2 = table[ch];
3402131543Stjr				  size_t len = weights[idx2];
3403131543Stjr
3404131543Stjr				  /* Test whether the lenghts match.  */
3405131543Stjr				  if (weights[idx] == len)
3406131543Stjr				    {
3407131543Stjr				      /* They do.  New compare the bytes of
3408131543Stjr					 the weight.  */
3409131543Stjr				      size_t cnt = 0;
3410131543Stjr
3411131543Stjr				      while (cnt < len
3412131543Stjr					     && (weights[idx + 1 + cnt]
3413131543Stjr						 == weights[idx2 + 1 + cnt]))
3414131543Stjr					++cnt;
3415131543Stjr
3416131543Stjr				      if (cnt == len)
3417131543Stjr					/* They match.  Mark the character as
3418131543Stjr					   acceptable.  */
3419131543Stjr					SET_LIST_BIT (ch);
3420131543Stjr				    }
3421131543Stjr				}
3422131543Stjr			  }
3423131543Stjr# endif
3424131543Stjr			had_char_class = true;
3425131543Stjr		      }
3426131543Stjr                    else
3427131543Stjr                      {
3428131543Stjr                        c1++;
3429131543Stjr                        while (c1--)
3430131543Stjr                          PATUNFETCH;
3431131543Stjr                        SET_LIST_BIT ('[');
3432131543Stjr                        SET_LIST_BIT ('=');
3433131543Stjr			range_start = '=';
3434131543Stjr                        had_char_class = false;
3435131543Stjr                      }
3436131543Stjr		  }
3437131543Stjr                else if (syntax & RE_CHAR_CLASSES && c == '[' && *p == '.')
3438131543Stjr		  {
3439131543Stjr		    unsigned char str[128];	/* Should be large enough.  */
3440131543Stjr# ifdef _LIBC
3441131543Stjr		    uint32_t nrules =
3442131543Stjr		      _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
3443131543Stjr# endif
3444131543Stjr
3445131543Stjr		    PATFETCH (c);
3446131543Stjr		    c1 = 0;
3447131543Stjr
3448131543Stjr		    /* If pattern is `[[.'.  */
3449131543Stjr		    if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3450131543Stjr
3451131543Stjr		    for (;;)
3452131543Stjr		      {
3453131543Stjr			PATFETCH (c);
3454131543Stjr			if ((c == '.' && *p == ']') || p == pend)
3455131543Stjr			  break;
3456131543Stjr			if (c1 < sizeof (str))
3457131543Stjr			  str[c1++] = c;
3458131543Stjr			else
3459131543Stjr			  /* This is in any case an invalid class name.  */
3460131543Stjr			  str[0] = '\0';
3461131543Stjr                      }
3462131543Stjr		    str[c1] = '\0';
3463131543Stjr
3464131543Stjr		    if (c == '.' && *p == ']' && str[0] != '\0')
3465131543Stjr		      {
3466131543Stjr			/* If we have no collation data we use the default
3467131543Stjr			   collation in which each character is the name
3468131543Stjr			   for its own class which contains only the one
3469131543Stjr			   character.  It also means that ASCII is the
3470131543Stjr			   character set and therefore we cannot have character
3471131543Stjr			   with more than one byte in the multibyte
3472131543Stjr			   representation.  */
3473131543Stjr# ifdef _LIBC
3474131543Stjr			if (nrules == 0)
3475131543Stjr# endif
3476131543Stjr			  {
3477131543Stjr			    if (c1 != 1)
3478131543Stjr			      FREE_STACK_RETURN (REG_ECOLLATE);
3479131543Stjr
3480131543Stjr			    /* Throw away the ] at the end of the equivalence
3481131543Stjr			       class.  */
3482131543Stjr			    PATFETCH (c);
3483131543Stjr
3484131543Stjr			    /* Set the bit for the character.  */
3485131543Stjr			    SET_LIST_BIT (str[0]);
3486131543Stjr			    range_start = ((const unsigned char *) str)[0];
3487131543Stjr			  }
3488131543Stjr# ifdef _LIBC
3489131543Stjr			else
3490131543Stjr			  {
3491131543Stjr			    /* Try to match the byte sequence in `str' against
3492131543Stjr			       those known to the collate implementation.
3493131543Stjr			       First find out whether the bytes in `str' are
3494131543Stjr			       actually from exactly one character.  */
3495131543Stjr			    int32_t table_size;
3496131543Stjr			    const int32_t *symb_table;
3497131543Stjr			    const unsigned char *extra;
3498131543Stjr			    int32_t idx;
3499131543Stjr			    int32_t elem;
3500131543Stjr			    int32_t second;
3501131543Stjr			    int32_t hash;
3502131543Stjr
3503131543Stjr			    table_size =
3504131543Stjr			      _NL_CURRENT_WORD (LC_COLLATE,
3505131543Stjr						_NL_COLLATE_SYMB_HASH_SIZEMB);
3506131543Stjr			    symb_table = (const int32_t *)
3507131543Stjr			      _NL_CURRENT (LC_COLLATE,
3508131543Stjr					   _NL_COLLATE_SYMB_TABLEMB);
3509131543Stjr			    extra = (const unsigned char *)
3510131543Stjr			      _NL_CURRENT (LC_COLLATE,
3511131543Stjr					   _NL_COLLATE_SYMB_EXTRAMB);
3512131543Stjr
3513131543Stjr			    /* Locate the character in the hashing table.  */
3514131543Stjr			    hash = elem_hash (str, c1);
3515131543Stjr
3516131543Stjr			    idx = 0;
3517131543Stjr			    elem = hash % table_size;
3518131543Stjr			    second = hash % (table_size - 2);
3519131543Stjr			    while (symb_table[2 * elem] != 0)
3520131543Stjr			      {
3521131543Stjr				/* First compare the hashing value.  */
3522131543Stjr				if (symb_table[2 * elem] == hash
3523131543Stjr				    && c1 == extra[symb_table[2 * elem + 1]]
3524131543Stjr				    && memcmp (str,
3525131543Stjr					       &extra[symb_table[2 * elem + 1]
3526131543Stjr						     + 1],
3527131543Stjr					       c1) == 0)
3528131543Stjr				  {
3529131543Stjr				    /* Yep, this is the entry.  */
3530131543Stjr				    idx = symb_table[2 * elem + 1];
3531131543Stjr				    idx += 1 + extra[idx];
3532131543Stjr				    break;
3533131543Stjr				  }
3534131543Stjr
3535131543Stjr				/* Next entry.  */
3536131543Stjr				elem += second;
3537131543Stjr			      }
3538131543Stjr
3539131543Stjr			    if (symb_table[2 * elem] == 0)
3540131543Stjr			      /* This is no valid character.  */
3541131543Stjr			      FREE_STACK_RETURN (REG_ECOLLATE);
3542131543Stjr
3543131543Stjr			    /* Throw away the ] at the end of the equivalence
3544131543Stjr			       class.  */
3545131543Stjr			    PATFETCH (c);
3546131543Stjr
3547131543Stjr			    /* Now add the multibyte character(s) we found
3548131543Stjr			       to the accept list.
3549131543Stjr
3550131543Stjr			       XXX Note that this is not entirely correct.
3551131543Stjr			       we would have to match multibyte sequences
3552131543Stjr			       but this is not possible with the current
3553131543Stjr			       implementation.  Also, we have to match
3554131543Stjr			       collating symbols, which expand to more than
3555131543Stjr			       one file, as a whole and not allow the
3556131543Stjr			       individual bytes.  */
3557131543Stjr			    c1 = extra[idx++];
3558131543Stjr			    if (c1 == 1)
3559131543Stjr			      range_start = extra[idx];
3560131543Stjr			    while (c1-- > 0)
3561131543Stjr			      {
3562131543Stjr				SET_LIST_BIT (extra[idx]);
3563131543Stjr				++idx;
3564131543Stjr			      }
3565131543Stjr			  }
3566131543Stjr# endif
3567131543Stjr			had_char_class = false;
3568131543Stjr		      }
3569131543Stjr                    else
3570131543Stjr                      {
3571131543Stjr                        c1++;
3572131543Stjr                        while (c1--)
3573131543Stjr                          PATUNFETCH;
3574131543Stjr                        SET_LIST_BIT ('[');
3575131543Stjr                        SET_LIST_BIT ('.');
3576131543Stjr			range_start = '.';
3577131543Stjr                        had_char_class = false;
3578131543Stjr                      }
3579131543Stjr		  }
3580218Sconklin                else
3581218Sconklin                  {
3582218Sconklin                    had_char_class = false;
3583218Sconklin                    SET_LIST_BIT (c);
3584131543Stjr		    range_start = c;
3585218Sconklin                  }
3586218Sconklin              }
3587218Sconklin
3588218Sconklin            /* Discard any (non)matching list bytes that are all 0 at the
3589218Sconklin               end of the map.  Decrease the map-length byte too.  */
3590126209Sache            while ((int) b[-1] > 0 && b[b[-1] - 1] == 0)
3591126209Sache              b[-1]--;
3592218Sconklin            b += b[-1];
3593131543Stjr#endif /* MBS_SUPPORT */
3594218Sconklin          }
3595218Sconklin          break;
3596218Sconklin
3597218Sconklin
3598218Sconklin	case '(':
3599218Sconklin          if (syntax & RE_NO_BK_PARENS)
3600218Sconklin            goto handle_open;
3601218Sconklin          else
3602218Sconklin            goto normal_char;
3603218Sconklin
3604218Sconklin
3605218Sconklin        case ')':
3606218Sconklin          if (syntax & RE_NO_BK_PARENS)
3607218Sconklin            goto handle_close;
3608218Sconklin          else
3609218Sconklin            goto normal_char;
3610218Sconklin
3611218Sconklin
3612218Sconklin        case '\n':
3613218Sconklin          if (syntax & RE_NEWLINE_ALT)
3614218Sconklin            goto handle_alt;
3615218Sconklin          else
3616218Sconklin            goto normal_char;
3617218Sconklin
3618218Sconklin
3619218Sconklin	case '|':
3620218Sconklin          if (syntax & RE_NO_BK_VBAR)
3621218Sconklin            goto handle_alt;
3622218Sconklin          else
3623218Sconklin            goto normal_char;
3624218Sconklin
3625218Sconklin
3626218Sconklin        case '{':
3627218Sconklin           if (syntax & RE_INTERVALS && syntax & RE_NO_BK_BRACES)
3628218Sconklin             goto handle_interval;
3629218Sconklin           else
3630218Sconklin             goto normal_char;
3631218Sconklin
3632218Sconklin
3633218Sconklin        case '\\':
3634126209Sache          if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
3635218Sconklin
3636218Sconklin          /* Do not translate the character after the \, so that we can
3637218Sconklin             distinguish, e.g., \B from \b, even if we normally would
3638218Sconklin             translate, e.g., B to b.  */
3639218Sconklin          PATFETCH_RAW (c);
3640218Sconklin
3641218Sconklin          switch (c)
3642218Sconklin            {
3643218Sconklin            case '(':
3644218Sconklin              if (syntax & RE_NO_BK_PARENS)
3645218Sconklin                goto normal_backslash;
3646218Sconklin
3647218Sconklin            handle_open:
3648218Sconklin              bufp->re_nsub++;
3649218Sconklin              regnum++;
3650218Sconklin
3651218Sconklin              if (COMPILE_STACK_FULL)
3652126209Sache                {
3653218Sconklin                  RETALLOC (compile_stack.stack, compile_stack.size << 1,
3654218Sconklin                            compile_stack_elt_t);
3655218Sconklin                  if (compile_stack.stack == NULL) return REG_ESPACE;
3656218Sconklin
3657218Sconklin                  compile_stack.size <<= 1;
3658218Sconklin                }
3659218Sconklin
3660218Sconklin              /* These are the values to restore when we hit end of this
3661218Sconklin                 group.  They are all relative offsets, so that if the
3662218Sconklin                 whole pattern moves because of realloc, they will still
3663218Sconklin                 be valid.  */
3664131543Stjr              COMPILE_STACK_TOP.begalt_offset = begalt - COMPILED_BUFFER_VAR;
3665126209Sache              COMPILE_STACK_TOP.fixup_alt_jump
3666131543Stjr                = fixup_alt_jump ? fixup_alt_jump - COMPILED_BUFFER_VAR + 1 : 0;
3667131543Stjr              COMPILE_STACK_TOP.laststart_offset = b - COMPILED_BUFFER_VAR;
3668218Sconklin              COMPILE_STACK_TOP.regnum = regnum;
3669218Sconklin
3670218Sconklin              /* We will eventually replace the 0 with the number of
3671218Sconklin                 groups inner to this one.  But do not push a
3672218Sconklin                 start_memory for groups beyond the last one we can
3673218Sconklin                 represent in the compiled pattern.  */
3674218Sconklin              if (regnum <= MAX_REGNUM)
3675218Sconklin                {
3676131543Stjr                  COMPILE_STACK_TOP.inner_group_offset = b
3677131543Stjr		    - COMPILED_BUFFER_VAR + 2;
3678218Sconklin                  BUF_PUSH_3 (start_memory, regnum, 0);
3679218Sconklin                }
3680126209Sache
3681218Sconklin              compile_stack.avail++;
3682218Sconklin
3683218Sconklin              fixup_alt_jump = 0;
3684218Sconklin              laststart = 0;
3685218Sconklin              begalt = b;
3686218Sconklin	      /* If we've reached MAX_REGNUM groups, then this open
3687218Sconklin		 won't actually generate any code, so we'll have to
3688218Sconklin		 clear pending_exact explicitly.  */
3689218Sconklin	      pending_exact = 0;
3690218Sconklin              break;
3691218Sconklin
3692218Sconklin
3693218Sconklin            case ')':
3694218Sconklin              if (syntax & RE_NO_BK_PARENS) goto normal_backslash;
3695218Sconklin
3696218Sconklin              if (COMPILE_STACK_EMPTY)
3697126209Sache		{
3698126209Sache		  if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
3699126209Sache		    goto normal_backslash;
3700126209Sache		  else
3701126209Sache		    FREE_STACK_RETURN (REG_ERPAREN);
3702126209Sache		}
3703218Sconklin
3704218Sconklin            handle_close:
3705218Sconklin              if (fixup_alt_jump)
3706218Sconklin                { /* Push a dummy failure point at the end of the
3707218Sconklin                     alternative for a possible future
3708218Sconklin                     `pop_failure_jump' to pop.  See comments at
3709218Sconklin                     `push_dummy_failure' in `re_match_2'.  */
3710218Sconklin                  BUF_PUSH (push_dummy_failure);
3711126209Sache
3712218Sconklin                  /* We allocated space for this jump when we assigned
3713218Sconklin                     to `fixup_alt_jump', in the `handle_alt' case below.  */
3714218Sconklin                  STORE_JUMP (jump_past_alt, fixup_alt_jump, b - 1);
3715218Sconklin                }
3716218Sconklin
3717218Sconklin              /* See similar code for backslashed left paren above.  */
3718218Sconklin              if (COMPILE_STACK_EMPTY)
3719126209Sache		{
3720126209Sache		  if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
3721126209Sache		    goto normal_char;
3722126209Sache		  else
3723126209Sache		    FREE_STACK_RETURN (REG_ERPAREN);
3724126209Sache		}
3725218Sconklin
3726218Sconklin              /* Since we just checked for an empty stack above, this
3727218Sconklin                 ``can't happen''.  */
3728218Sconklin              assert (compile_stack.avail != 0);
3729218Sconklin              {
3730218Sconklin                /* We don't just want to restore into `regnum', because
3731218Sconklin                   later groups should continue to be numbered higher,
3732218Sconklin                   as in `(ab)c(de)' -- the second group is #2.  */
3733218Sconklin                regnum_t this_group_regnum;
3734218Sconklin
3735126209Sache                compile_stack.avail--;
3736131543Stjr                begalt = COMPILED_BUFFER_VAR + COMPILE_STACK_TOP.begalt_offset;
3737218Sconklin                fixup_alt_jump
3738218Sconklin                  = COMPILE_STACK_TOP.fixup_alt_jump
3739131543Stjr                    ? COMPILED_BUFFER_VAR + COMPILE_STACK_TOP.fixup_alt_jump - 1
3740218Sconklin                    : 0;
3741131543Stjr                laststart = COMPILED_BUFFER_VAR + COMPILE_STACK_TOP.laststart_offset;
3742218Sconklin                this_group_regnum = COMPILE_STACK_TOP.regnum;
3743218Sconklin		/* If we've reached MAX_REGNUM groups, then this open
3744218Sconklin		   won't actually generate any code, so we'll have to
3745218Sconklin		   clear pending_exact explicitly.  */
3746218Sconklin		pending_exact = 0;
3747218Sconklin
3748218Sconklin                /* We're at the end of the group, so now we know how many
3749218Sconklin                   groups were inside this one.  */
3750218Sconklin                if (this_group_regnum <= MAX_REGNUM)
3751218Sconklin                  {
3752131543Stjr		    US_CHAR_TYPE *inner_group_loc
3753131543Stjr                      = COMPILED_BUFFER_VAR + COMPILE_STACK_TOP.inner_group_offset;
3754126209Sache
3755218Sconklin                    *inner_group_loc = regnum - this_group_regnum;
3756218Sconklin                    BUF_PUSH_3 (stop_memory, this_group_regnum,
3757218Sconklin                                regnum - this_group_regnum);
3758218Sconklin                  }
3759218Sconklin              }
3760218Sconklin              break;
3761218Sconklin
3762218Sconklin
3763218Sconklin            case '|':					/* `\|'.  */
3764218Sconklin              if (syntax & RE_LIMITED_OPS || syntax & RE_NO_BK_VBAR)
3765218Sconklin                goto normal_backslash;
3766218Sconklin            handle_alt:
3767218Sconklin              if (syntax & RE_LIMITED_OPS)
3768218Sconklin                goto normal_char;
3769218Sconklin
3770218Sconklin              /* Insert before the previous alternative a jump which
3771218Sconklin                 jumps to this alternative if the former fails.  */
3772131543Stjr              GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
3773131543Stjr              INSERT_JUMP (on_failure_jump, begalt,
3774131543Stjr			   b + 2 + 2 * OFFSET_ADDRESS_SIZE);
3775218Sconklin              pending_exact = 0;
3776131543Stjr              b += 1 + OFFSET_ADDRESS_SIZE;
3777218Sconklin
3778218Sconklin              /* The alternative before this one has a jump after it
3779218Sconklin                 which gets executed if it gets matched.  Adjust that
3780218Sconklin                 jump so it will jump to this alternative's analogous
3781218Sconklin                 jump (put in below, which in turn will jump to the next
3782218Sconklin                 (if any) alternative's such jump, etc.).  The last such
3783218Sconklin                 jump jumps to the correct final destination.  A picture:
3784126209Sache                          _____ _____
3785126209Sache                          |   | |   |
3786126209Sache                          |   v |   v
3787126209Sache                         a | b   | c
3788218Sconklin
3789218Sconklin                 If we are at `b', then fixup_alt_jump right now points to a
3790218Sconklin                 three-byte space after `a'.  We'll put in the jump, set
3791218Sconklin                 fixup_alt_jump to right after `b', and leave behind three
3792218Sconklin                 bytes which we'll fill in when we get to after `c'.  */
3793218Sconklin
3794218Sconklin              if (fixup_alt_jump)
3795218Sconklin                STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
3796218Sconklin
3797218Sconklin              /* Mark and leave space for a jump after this alternative,
3798218Sconklin                 to be filled in later either by next alternative or
3799218Sconklin                 when know we're at the end of a series of alternatives.  */
3800218Sconklin              fixup_alt_jump = b;
3801131543Stjr              GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
3802131543Stjr              b += 1 + OFFSET_ADDRESS_SIZE;
3803218Sconklin
3804218Sconklin              laststart = 0;
3805218Sconklin              begalt = b;
3806218Sconklin              break;
3807218Sconklin
3808218Sconklin
3809126209Sache            case '{':
3810218Sconklin              /* If \{ is a literal.  */
3811218Sconklin              if (!(syntax & RE_INTERVALS)
3812126209Sache                     /* If we're at `\{' and it's not the open-interval
3813218Sconklin                        operator.  */
3814131543Stjr		  || (syntax & RE_NO_BK_BRACES))
3815218Sconklin                goto normal_backslash;
3816218Sconklin
3817218Sconklin            handle_interval:
3818218Sconklin              {
3819218Sconklin                /* If got here, then the syntax allows intervals.  */
3820218Sconklin
3821218Sconklin                /* At least (most) this many matches must be made.  */
3822218Sconklin                int lower_bound = -1, upper_bound = -1;
3823218Sconklin
3824131543Stjr		/* Place in the uncompiled pattern (i.e., just after
3825131543Stjr		   the '{') to go back to if the interval is invalid.  */
3826131543Stjr		const CHAR_TYPE *beg_interval = p;
3827218Sconklin
3828218Sconklin                if (p == pend)
3829131543Stjr		  goto invalid_interval;
3830218Sconklin
3831218Sconklin                GET_UNSIGNED_NUMBER (lower_bound);
3832218Sconklin
3833218Sconklin                if (c == ',')
3834218Sconklin                  {
3835218Sconklin                    GET_UNSIGNED_NUMBER (upper_bound);
3836131543Stjr		    if (upper_bound < 0)
3837131543Stjr		      upper_bound = RE_DUP_MAX;
3838218Sconklin                  }
3839218Sconklin                else
3840218Sconklin                  /* Interval such as `{1}' => match exactly once. */
3841218Sconklin                  upper_bound = lower_bound;
3842218Sconklin
3843131543Stjr                if (! (0 <= lower_bound && lower_bound <= upper_bound))
3844131543Stjr		  goto invalid_interval;
3845218Sconklin
3846126209Sache                if (!(syntax & RE_NO_BK_BRACES))
3847218Sconklin                  {
3848131543Stjr		    if (c != '\\' || p == pend)
3849131543Stjr		      goto invalid_interval;
3850218Sconklin                    PATFETCH (c);
3851218Sconklin                  }
3852218Sconklin
3853218Sconklin                if (c != '}')
3854131543Stjr		  goto invalid_interval;
3855218Sconklin
3856218Sconklin                /* If it's invalid to have no preceding re.  */
3857218Sconklin                if (!laststart)
3858218Sconklin                  {
3859131543Stjr		    if (syntax & RE_CONTEXT_INVALID_OPS
3860131543Stjr			&& !(syntax & RE_INVALID_INTERVAL_ORD))
3861126209Sache                      FREE_STACK_RETURN (REG_BADRPT);
3862218Sconklin                    else if (syntax & RE_CONTEXT_INDEP_OPS)
3863218Sconklin                      laststart = b;
3864218Sconklin                    else
3865218Sconklin                      goto unfetch_interval;
3866218Sconklin                  }
3867218Sconklin
3868131543Stjr                /* We just parsed a valid interval.  */
3869131543Stjr
3870131543Stjr                if (RE_DUP_MAX < upper_bound)
3871131543Stjr		  FREE_STACK_RETURN (REG_BADBR);
3872131543Stjr
3873218Sconklin                /* If the upper bound is zero, don't want to succeed at
3874218Sconklin                   all; jump from `laststart' to `b + 3', which will be
3875131543Stjr		   the end of the buffer after we insert the jump.  */
3876131543Stjr		/* ifdef MBS_SUPPORT, 'b + 1 + OFFSET_ADDRESS_SIZE'
3877131543Stjr		   instead of 'b + 3'.  */
3878218Sconklin                 if (upper_bound == 0)
3879218Sconklin                   {
3880131543Stjr                     GET_BUFFER_SPACE (1 + OFFSET_ADDRESS_SIZE);
3881131543Stjr                     INSERT_JUMP (jump, laststart, b + 1
3882131543Stjr				  + OFFSET_ADDRESS_SIZE);
3883131543Stjr                     b += 1 + OFFSET_ADDRESS_SIZE;
3884218Sconklin                   }
3885218Sconklin
3886218Sconklin                 /* Otherwise, we have a nontrivial interval.  When
3887218Sconklin                    we're all done, the pattern will look like:
3888218Sconklin                      set_number_at <jump count> <upper bound>
3889218Sconklin                      set_number_at <succeed_n count> <lower bound>
3890126209Sache                      succeed_n <after jump addr> <succeed_n count>
3891218Sconklin                      <body of loop>
3892218Sconklin                      jump_n <succeed_n addr> <jump count>
3893218Sconklin                    (The upper bound and `jump_n' are omitted if
3894218Sconklin                    `upper_bound' is 1, though.)  */
3895126209Sache                 else
3896218Sconklin                   { /* If the upper bound is > 1, we need to insert
3897218Sconklin                        more at the end of the loop.  */
3898131543Stjr                     unsigned nbytes = 2 + 4 * OFFSET_ADDRESS_SIZE +
3899131543Stjr		       (upper_bound > 1) * (2 + 4 * OFFSET_ADDRESS_SIZE);
3900218Sconklin
3901218Sconklin                     GET_BUFFER_SPACE (nbytes);
3902218Sconklin
3903218Sconklin                     /* Initialize lower bound of the `succeed_n', even
3904218Sconklin                        though it will be set during matching by its
3905218Sconklin                        attendant `set_number_at' (inserted next),
3906218Sconklin                        because `re_compile_fastmap' needs to know.
3907218Sconklin                        Jump to the `jump_n' we might insert below.  */
3908218Sconklin                     INSERT_JUMP2 (succeed_n, laststart,
3909131543Stjr                                   b + 1 + 2 * OFFSET_ADDRESS_SIZE
3910131543Stjr				   + (upper_bound > 1) * (1 + 2 * OFFSET_ADDRESS_SIZE)
3911131543Stjr				   , lower_bound);
3912131543Stjr                     b += 1 + 2 * OFFSET_ADDRESS_SIZE;
3913218Sconklin
3914126209Sache                     /* Code to initialize the lower bound.  Insert
3915218Sconklin                        before the `succeed_n'.  The `5' is the last two
3916218Sconklin                        bytes of this `set_number_at', plus 3 bytes of
3917218Sconklin                        the following `succeed_n'.  */
3918131543Stjr		     /* ifdef MBS_SUPPORT, The '1+2*OFFSET_ADDRESS_SIZE'
3919131543Stjr			is the 'set_number_at', plus '1+OFFSET_ADDRESS_SIZE'
3920131543Stjr			of the following `succeed_n'.  */
3921131543Stjr                     insert_op2 (set_number_at, laststart, 1
3922131543Stjr				 + 2 * OFFSET_ADDRESS_SIZE, lower_bound, b);
3923131543Stjr                     b += 1 + 2 * OFFSET_ADDRESS_SIZE;
3924218Sconklin
3925218Sconklin                     if (upper_bound > 1)
3926218Sconklin                       { /* More than one repetition is allowed, so
3927218Sconklin                            append a backward jump to the `succeed_n'
3928218Sconklin                            that starts this interval.
3929126209Sache
3930218Sconklin                            When we've reached this during matching,
3931218Sconklin                            we'll have matched the interval once, so
3932218Sconklin                            jump back only `upper_bound - 1' times.  */
3933131543Stjr                         STORE_JUMP2 (jump_n, b, laststart
3934131543Stjr				      + 2 * OFFSET_ADDRESS_SIZE + 1,
3935218Sconklin                                      upper_bound - 1);
3936131543Stjr                         b += 1 + 2 * OFFSET_ADDRESS_SIZE;
3937218Sconklin
3938218Sconklin                         /* The location we want to set is the second
3939218Sconklin                            parameter of the `jump_n'; that is `b-2' as
3940218Sconklin                            an absolute address.  `laststart' will be
3941218Sconklin                            the `set_number_at' we're about to insert;
3942218Sconklin                            `laststart+3' the number to set, the source
3943218Sconklin                            for the relative address.  But we are
3944218Sconklin                            inserting into the middle of the pattern --
3945218Sconklin                            so everything is getting moved up by 5.
3946218Sconklin                            Conclusion: (b - 2) - (laststart + 3) + 5,
3947218Sconklin                            i.e., b - laststart.
3948126209Sache
3949218Sconklin                            We insert this at the beginning of the loop
3950218Sconklin                            so that if we fail during matching, we'll
3951218Sconklin                            reinitialize the bounds.  */
3952218Sconklin                         insert_op2 (set_number_at, laststart, b - laststart,
3953218Sconklin                                     upper_bound - 1, b);
3954131543Stjr                         b += 1 + 2 * OFFSET_ADDRESS_SIZE;
3955218Sconklin                       }
3956218Sconklin                   }
3957218Sconklin                pending_exact = 0;
3958131543Stjr		break;
3959218Sconklin
3960131543Stjr	      invalid_interval:
3961131543Stjr		if (!(syntax & RE_INVALID_INTERVAL_ORD))
3962131543Stjr		  FREE_STACK_RETURN (p == pend ? REG_EBRACE : REG_BADBR);
3963131543Stjr	      unfetch_interval:
3964131543Stjr		/* Match the characters as literals.  */
3965131543Stjr		p = beg_interval;
3966131543Stjr		c = '{';
3967131543Stjr		if (syntax & RE_NO_BK_BRACES)
3968131543Stjr		  goto normal_char;
3969131543Stjr		else
3970131543Stjr		  goto normal_backslash;
3971131543Stjr	      }
3972218Sconklin
3973218Sconklin#ifdef emacs
3974218Sconklin            /* There is no way to specify the before_dot and after_dot
3975218Sconklin               operators.  rms says this is ok.  --karl  */
3976218Sconklin            case '=':
3977218Sconklin              BUF_PUSH (at_dot);
3978218Sconklin              break;
3979218Sconklin
3980126209Sache            case 's':
3981218Sconklin              laststart = b;
3982218Sconklin              PATFETCH (c);
3983218Sconklin              BUF_PUSH_2 (syntaxspec, syntax_spec_code[c]);
3984218Sconklin              break;
3985218Sconklin
3986218Sconklin            case 'S':
3987218Sconklin              laststart = b;
3988218Sconklin              PATFETCH (c);
3989218Sconklin              BUF_PUSH_2 (notsyntaxspec, syntax_spec_code[c]);
3990218Sconklin              break;
3991218Sconklin#endif /* emacs */
3992218Sconklin
3993218Sconklin
3994218Sconklin            case 'w':
3995126209Sache	      if (syntax & RE_NO_GNU_OPS)
3996126209Sache		goto normal_char;
3997218Sconklin              laststart = b;
3998218Sconklin              BUF_PUSH (wordchar);
3999218Sconklin              break;
4000218Sconklin
4001218Sconklin
4002218Sconklin            case 'W':
4003126209Sache	      if (syntax & RE_NO_GNU_OPS)
4004126209Sache		goto normal_char;
4005218Sconklin              laststart = b;
4006218Sconklin              BUF_PUSH (notwordchar);
4007218Sconklin              break;
4008218Sconklin
4009218Sconklin
4010218Sconklin            case '<':
4011126209Sache	      if (syntax & RE_NO_GNU_OPS)
4012126209Sache		goto normal_char;
4013218Sconklin              BUF_PUSH (wordbeg);
4014218Sconklin              break;
4015218Sconklin
4016218Sconklin            case '>':
4017126209Sache	      if (syntax & RE_NO_GNU_OPS)
4018126209Sache		goto normal_char;
4019218Sconklin              BUF_PUSH (wordend);
4020218Sconklin              break;
4021218Sconklin
4022218Sconklin            case 'b':
4023126209Sache	      if (syntax & RE_NO_GNU_OPS)
4024126209Sache		goto normal_char;
4025218Sconklin              BUF_PUSH (wordbound);
4026218Sconklin              break;
4027218Sconklin
4028218Sconklin            case 'B':
4029126209Sache	      if (syntax & RE_NO_GNU_OPS)
4030126209Sache		goto normal_char;
4031218Sconklin              BUF_PUSH (notwordbound);
4032218Sconklin              break;
4033218Sconklin
4034218Sconklin            case '`':
4035126209Sache	      if (syntax & RE_NO_GNU_OPS)
4036126209Sache		goto normal_char;
4037218Sconklin              BUF_PUSH (begbuf);
4038218Sconklin              break;
4039218Sconklin
4040218Sconklin            case '\'':
4041126209Sache	      if (syntax & RE_NO_GNU_OPS)
4042126209Sache		goto normal_char;
4043218Sconklin              BUF_PUSH (endbuf);
4044218Sconklin              break;
4045218Sconklin
4046218Sconklin            case '1': case '2': case '3': case '4': case '5':
4047218Sconklin            case '6': case '7': case '8': case '9':
4048218Sconklin              if (syntax & RE_NO_BK_REFS)
4049218Sconklin                goto normal_char;
4050218Sconklin
4051218Sconklin              c1 = c - '0';
4052218Sconklin
4053218Sconklin              if (c1 > regnum)
4054126209Sache                FREE_STACK_RETURN (REG_ESUBREG);
4055218Sconklin
4056218Sconklin              /* Can't back reference to a subexpression if inside of it.  */
4057126209Sache              if (group_in_compile_stack (compile_stack, (regnum_t) c1))
4058218Sconklin                goto normal_char;
4059218Sconklin
4060218Sconklin              laststart = b;
4061218Sconklin              BUF_PUSH_2 (duplicate, c1);
4062218Sconklin              break;
4063218Sconklin
4064218Sconklin
4065218Sconklin            case '+':
4066218Sconklin            case '?':
4067218Sconklin              if (syntax & RE_BK_PLUS_QM)
4068218Sconklin                goto handle_plus;
4069218Sconklin              else
4070218Sconklin                goto normal_backslash;
4071218Sconklin
4072218Sconklin            default:
4073218Sconklin            normal_backslash:
4074218Sconklin              /* You might think it would be useful for \ to mean
4075218Sconklin                 not to translate; but if we don't translate it
4076218Sconklin                 it will never match anything.  */
4077218Sconklin              c = TRANSLATE (c);
4078218Sconklin              goto normal_char;
4079218Sconklin            }
4080218Sconklin          break;
4081218Sconklin
4082218Sconklin
4083218Sconklin	default:
4084218Sconklin        /* Expects the character in `c'.  */
4085218Sconklin	normal_char:
4086218Sconklin	      /* If no exactn currently being built.  */
4087126209Sache          if (!pending_exact
4088131543Stjr#ifdef MBS_SUPPORT
4089131543Stjr	      /* If last exactn handle binary(or character) and
4090131543Stjr		 new exactn handle character(or binary).  */
4091131543Stjr	      || is_exactn_bin != is_binary[p - 1 - pattern]
4092131543Stjr#endif /* MBS_SUPPORT */
4093218Sconklin
4094218Sconklin              /* If last exactn not at current position.  */
4095218Sconklin              || pending_exact + *pending_exact + 1 != b
4096126209Sache
4097218Sconklin              /* We have only one byte following the exactn for the count.  */
4098218Sconklin	      || *pending_exact == (1 << BYTEWIDTH) - 1
4099218Sconklin
4100218Sconklin              /* If followed by a repetition operator.  */
4101218Sconklin              || *p == '*' || *p == '^'
4102218Sconklin	      || ((syntax & RE_BK_PLUS_QM)
4103218Sconklin		  ? *p == '\\' && (p[1] == '+' || p[1] == '?')
4104218Sconklin		  : (*p == '+' || *p == '?'))
4105218Sconklin	      || ((syntax & RE_INTERVALS)
4106218Sconklin                  && ((syntax & RE_NO_BK_BRACES)
4107218Sconklin		      ? *p == '{'
4108218Sconklin                      : (p[0] == '\\' && p[1] == '{'))))
4109218Sconklin	    {
4110218Sconklin	      /* Start building a new exactn.  */
4111126209Sache
4112218Sconklin              laststart = b;
4113218Sconklin
4114131543Stjr#ifdef MBS_SUPPORT
4115131543Stjr	      /* Is this exactn binary data or character? */
4116131543Stjr	      is_exactn_bin = is_binary[p - 1 - pattern];
4117131543Stjr	      if (is_exactn_bin)
4118131543Stjr		  BUF_PUSH_2 (exactn_bin, 0);
4119131543Stjr	      else
4120131543Stjr		  BUF_PUSH_2 (exactn, 0);
4121131543Stjr#else
4122218Sconklin	      BUF_PUSH_2 (exactn, 0);
4123131543Stjr#endif /* MBS_SUPPORT */
4124218Sconklin	      pending_exact = b - 1;
4125218Sconklin            }
4126126209Sache
4127218Sconklin	  BUF_PUSH (c);
4128218Sconklin          (*pending_exact)++;
4129218Sconklin	  break;
4130218Sconklin        } /* switch (c) */
4131218Sconklin    } /* while p != pend */
4132218Sconklin
4133126209Sache
4134218Sconklin  /* Through the pattern now.  */
4135126209Sache
4136218Sconklin  if (fixup_alt_jump)
4137218Sconklin    STORE_JUMP (jump_past_alt, fixup_alt_jump, b);
4138218Sconklin
4139126209Sache  if (!COMPILE_STACK_EMPTY)
4140126209Sache    FREE_STACK_RETURN (REG_EPAREN);
4141218Sconklin
4142126209Sache  /* If we don't want backtracking, force success
4143126209Sache     the first time we reach the end of the compiled pattern.  */
4144126209Sache  if (syntax & RE_NO_POSIX_BACKTRACKING)
4145126209Sache    BUF_PUSH (succeed);
4146126209Sache
4147131543Stjr#ifdef MBS_SUPPORT
4148131543Stjr  free (pattern);
4149131543Stjr  free (mbs_offset);
4150131543Stjr  free (is_binary);
4151131543Stjr#endif
4152218Sconklin  free (compile_stack.stack);
4153218Sconklin
4154218Sconklin  /* We have succeeded; set the length of the buffer.  */
4155131543Stjr#ifdef MBS_SUPPORT
4156131543Stjr  bufp->used = (uintptr_t) b - (uintptr_t) COMPILED_BUFFER_VAR;
4157131543Stjr#else
4158218Sconklin  bufp->used = b - bufp->buffer;
4159131543Stjr#endif
4160218Sconklin
4161218Sconklin#ifdef DEBUG
4162218Sconklin  if (debug)
4163218Sconklin    {
4164126209Sache      DEBUG_PRINT1 ("\nCompiled pattern: \n");
4165218Sconklin      print_compiled_pattern (bufp);
4166218Sconklin    }
4167218Sconklin#endif /* DEBUG */
4168218Sconklin
4169126209Sache#ifndef MATCH_MAY_ALLOCATE
4170126209Sache  /* Initialize the failure stack to the largest possible stack.  This
4171126209Sache     isn't necessary unless we're trying to avoid calling alloca in
4172126209Sache     the search and match routines.  */
4173126209Sache  {
4174126209Sache    int num_regs = bufp->re_nsub + 1;
4175126209Sache
4176126209Sache    /* Since DOUBLE_FAIL_STACK refuses to double only if the current size
4177126209Sache       is strictly greater than re_max_failures, the largest possible stack
4178126209Sache       is 2 * re_max_failures failure points.  */
4179126209Sache    if (fail_stack.size < (2 * re_max_failures * MAX_FAILURE_ITEMS))
4180126209Sache      {
4181126209Sache	fail_stack.size = (2 * re_max_failures * MAX_FAILURE_ITEMS);
4182126209Sache
4183126209Sache# ifdef emacs
4184126209Sache	if (! fail_stack.stack)
4185126209Sache	  fail_stack.stack
4186126209Sache	    = (fail_stack_elt_t *) xmalloc (fail_stack.size
4187126209Sache					    * sizeof (fail_stack_elt_t));
4188126209Sache	else
4189126209Sache	  fail_stack.stack
4190126209Sache	    = (fail_stack_elt_t *) xrealloc (fail_stack.stack,
4191126209Sache					     (fail_stack.size
4192126209Sache					      * sizeof (fail_stack_elt_t)));
4193126209Sache# else /* not emacs */
4194126209Sache	if (! fail_stack.stack)
4195126209Sache	  fail_stack.stack
4196126209Sache	    = (fail_stack_elt_t *) malloc (fail_stack.size
4197126209Sache					   * sizeof (fail_stack_elt_t));
4198126209Sache	else
4199126209Sache	  fail_stack.stack
4200126209Sache	    = (fail_stack_elt_t *) realloc (fail_stack.stack,
4201126209Sache					    (fail_stack.size
4202126209Sache					     * sizeof (fail_stack_elt_t)));
4203126209Sache# endif /* not emacs */
4204126209Sache      }
4205126209Sache
4206126209Sache    regex_grow_registers (num_regs);
4207126209Sache  }
4208126209Sache#endif /* not MATCH_MAY_ALLOCATE */
4209126209Sache
4210218Sconklin  return REG_NOERROR;
4211218Sconklin} /* regex_compile */
4212218Sconklin
4213218Sconklin/* Subroutines for `regex_compile'.  */
4214218Sconklin
4215218Sconklin/* Store OP at LOC followed by two-byte integer parameter ARG.  */
4216131543Stjr/* ifdef MBS_SUPPORT, integer parameter is 1 wchar_t.  */
4217218Sconklin
4218218Sconklinstatic void
4219218Sconklinstore_op1 (op, loc, arg)
4220218Sconklin    re_opcode_t op;
4221131543Stjr    US_CHAR_TYPE *loc;
4222218Sconklin    int arg;
4223218Sconklin{
4224131543Stjr  *loc = (US_CHAR_TYPE) op;
4225218Sconklin  STORE_NUMBER (loc + 1, arg);
4226218Sconklin}
4227218Sconklin
4228218Sconklin
4229218Sconklin/* Like `store_op1', but for two two-byte parameters ARG1 and ARG2.  */
4230131543Stjr/* ifdef MBS_SUPPORT, integer parameter is 1 wchar_t.  */
4231218Sconklin
4232218Sconklinstatic void
4233218Sconklinstore_op2 (op, loc, arg1, arg2)
4234218Sconklin    re_opcode_t op;
4235131543Stjr    US_CHAR_TYPE *loc;
4236218Sconklin    int arg1, arg2;
4237218Sconklin{
4238131543Stjr  *loc = (US_CHAR_TYPE) op;
4239218Sconklin  STORE_NUMBER (loc + 1, arg1);
4240131543Stjr  STORE_NUMBER (loc + 1 + OFFSET_ADDRESS_SIZE, arg2);
4241218Sconklin}
4242218Sconklin
4243218Sconklin
4244218Sconklin/* Copy the bytes from LOC to END to open up three bytes of space at LOC
4245218Sconklin   for OP followed by two-byte integer parameter ARG.  */
4246131543Stjr/* ifdef MBS_SUPPORT, integer parameter is 1 wchar_t.  */
4247218Sconklin
4248218Sconklinstatic void
4249218Sconklininsert_op1 (op, loc, arg, end)
4250218Sconklin    re_opcode_t op;
4251131543Stjr    US_CHAR_TYPE *loc;
4252218Sconklin    int arg;
4253131543Stjr    US_CHAR_TYPE *end;
4254218Sconklin{
4255131543Stjr  register US_CHAR_TYPE *pfrom = end;
4256131543Stjr  register US_CHAR_TYPE *pto = end + 1 + OFFSET_ADDRESS_SIZE;
4257218Sconklin
4258218Sconklin  while (pfrom != loc)
4259218Sconklin    *--pto = *--pfrom;
4260126209Sache
4261218Sconklin  store_op1 (op, loc, arg);
4262218Sconklin}
4263218Sconklin
4264218Sconklin
4265218Sconklin/* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2.  */
4266131543Stjr/* ifdef MBS_SUPPORT, integer parameter is 1 wchar_t.  */
4267218Sconklin
4268218Sconklinstatic void
4269218Sconklininsert_op2 (op, loc, arg1, arg2, end)
4270218Sconklin    re_opcode_t op;
4271131543Stjr    US_CHAR_TYPE *loc;
4272218Sconklin    int arg1, arg2;
4273131543Stjr    US_CHAR_TYPE *end;
4274218Sconklin{
4275131543Stjr  register US_CHAR_TYPE *pfrom = end;
4276131543Stjr  register US_CHAR_TYPE *pto = end + 1 + 2 * OFFSET_ADDRESS_SIZE;
4277218Sconklin
4278218Sconklin  while (pfrom != loc)
4279218Sconklin    *--pto = *--pfrom;
4280126209Sache
4281218Sconklin  store_op2 (op, loc, arg1, arg2);
4282218Sconklin}
4283218Sconklin
4284218Sconklin
4285218Sconklin/* P points to just after a ^ in PATTERN.  Return true if that ^ comes
4286218Sconklin   after an alternative or a begin-subexpression.  We assume there is at
4287218Sconklin   least one character before the ^.  */
4288218Sconklin
4289218Sconklinstatic boolean
4290218Sconklinat_begline_loc_p (pattern, p, syntax)
4291131543Stjr    const CHAR_TYPE *pattern, *p;
4292218Sconklin    reg_syntax_t syntax;
4293218Sconklin{
4294131543Stjr  const CHAR_TYPE *prev = p - 2;
4295218Sconklin  boolean prev_prev_backslash = prev > pattern && prev[-1] == '\\';
4296126209Sache
4297218Sconklin  return
4298218Sconklin       /* After a subexpression?  */
4299218Sconklin       (*prev == '(' && (syntax & RE_NO_BK_PARENS || prev_prev_backslash))
4300218Sconklin       /* After an alternative?  */
4301218Sconklin    || (*prev == '|' && (syntax & RE_NO_BK_VBAR || prev_prev_backslash));
4302218Sconklin}
4303218Sconklin
4304218Sconklin
4305218Sconklin/* The dual of at_begline_loc_p.  This one is for $.  We assume there is
4306218Sconklin   at least one character after the $, i.e., `P < PEND'.  */
4307218Sconklin
4308218Sconklinstatic boolean
4309218Sconklinat_endline_loc_p (p, pend, syntax)
4310131543Stjr    const CHAR_TYPE *p, *pend;
4311126209Sache    reg_syntax_t syntax;
4312218Sconklin{
4313131543Stjr  const CHAR_TYPE *next = p;
4314218Sconklin  boolean next_backslash = *next == '\\';
4315131543Stjr  const CHAR_TYPE *next_next = p + 1 < pend ? p + 1 : 0;
4316126209Sache
4317218Sconklin  return
4318218Sconklin       /* Before a subexpression?  */
4319218Sconklin       (syntax & RE_NO_BK_PARENS ? *next == ')'
4320218Sconklin        : next_backslash && next_next && *next_next == ')')
4321218Sconklin       /* Before an alternative?  */
4322218Sconklin    || (syntax & RE_NO_BK_VBAR ? *next == '|'
4323218Sconklin        : next_backslash && next_next && *next_next == '|');
4324218Sconklin}
4325218Sconklin
4326218Sconklin
4327126209Sache/* Returns true if REGNUM is in one of COMPILE_STACK's elements and
4328218Sconklin   false if it's not.  */
4329218Sconklin
4330218Sconklinstatic boolean
4331218Sconklingroup_in_compile_stack (compile_stack, regnum)
4332218Sconklin    compile_stack_type compile_stack;
4333218Sconklin    regnum_t regnum;
4334218Sconklin{
4335218Sconklin  int this_element;
4336218Sconklin
4337126209Sache  for (this_element = compile_stack.avail - 1;
4338126209Sache       this_element >= 0;
4339218Sconklin       this_element--)
4340218Sconklin    if (compile_stack.stack[this_element].regnum == regnum)
4341218Sconklin      return true;
4342218Sconklin
4343218Sconklin  return false;
4344218Sconklin}
4345218Sconklin
4346131543Stjr#ifdef MBS_SUPPORT
4347131543Stjr/* This insert space, which size is "num", into the pattern at "loc".
4348131543Stjr   "end" must point the end of the allocated buffer.  */
4349131543Stjrstatic void
4350131543Stjrinsert_space (num, loc, end)
4351131543Stjr     int num;
4352131543Stjr     CHAR_TYPE *loc;
4353131543Stjr     CHAR_TYPE *end;
4354131543Stjr{
4355131543Stjr  register CHAR_TYPE *pto = end;
4356131543Stjr  register CHAR_TYPE *pfrom = end - num;
4357218Sconklin
4358131543Stjr  while (pfrom >= loc)
4359131543Stjr    *pto-- = *pfrom--;
4360131543Stjr}
4361131543Stjr#endif /* MBS_SUPPORT */
4362131543Stjr
4363131543Stjr#ifdef MBS_SUPPORT
4364131543Stjrstatic reg_errcode_t
4365131543Stjrcompile_range (range_start_char, p_ptr, pend, translate, syntax, b,
4366131543Stjr	       char_set)
4367131543Stjr     CHAR_TYPE range_start_char;
4368131543Stjr     const CHAR_TYPE **p_ptr, *pend;
4369131543Stjr     CHAR_TYPE *char_set, *b;
4370131543Stjr     RE_TRANSLATE_TYPE translate;
4371131543Stjr     reg_syntax_t syntax;
4372131543Stjr{
4373131543Stjr  const CHAR_TYPE *p = *p_ptr;
4374131543Stjr  CHAR_TYPE range_start, range_end;
4375131543Stjr  reg_errcode_t ret;
4376131543Stjr# ifdef _LIBC
4377131543Stjr  uint32_t nrules;
4378131543Stjr  uint32_t start_val, end_val;
4379131543Stjr# endif
4380131543Stjr  if (p == pend)
4381131543Stjr    return REG_ERANGE;
4382131543Stjr
4383131543Stjr# ifdef _LIBC
4384131543Stjr  nrules = _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
4385131543Stjr  if (nrules != 0)
4386131543Stjr    {
4387131543Stjr      const char *collseq = (const char *) _NL_CURRENT(LC_COLLATE,
4388131543Stjr						       _NL_COLLATE_COLLSEQWC);
4389131543Stjr      const unsigned char *extra = (const unsigned char *)
4390131543Stjr	_NL_CURRENT (LC_COLLATE, _NL_COLLATE_SYMB_EXTRAMB);
4391131543Stjr
4392131543Stjr      if (range_start_char < -1)
4393131543Stjr	{
4394131543Stjr	  /* range_start is a collating symbol.  */
4395131543Stjr	  int32_t *wextra;
4396131543Stjr	  /* Retreive the index and get collation sequence value.  */
4397131543Stjr	  wextra = (int32_t*)(extra + char_set[-range_start_char]);
4398131543Stjr	  start_val = wextra[1 + *wextra];
4399131543Stjr	}
4400131543Stjr      else
4401131543Stjr	start_val = collseq_table_lookup(collseq, TRANSLATE(range_start_char));
4402131543Stjr
4403131543Stjr      end_val = collseq_table_lookup (collseq, TRANSLATE (p[0]));
4404131543Stjr
4405131543Stjr      /* Report an error if the range is empty and the syntax prohibits
4406131543Stjr	 this.  */
4407131543Stjr      ret = ((syntax & RE_NO_EMPTY_RANGES)
4408131543Stjr	     && (start_val > end_val))? REG_ERANGE : REG_NOERROR;
4409131543Stjr
4410131543Stjr      /* Insert space to the end of the char_ranges.  */
4411131543Stjr      insert_space(2, b - char_set[5] - 2, b - 1);
4412131543Stjr      *(b - char_set[5] - 2) = (wchar_t)start_val;
4413131543Stjr      *(b - char_set[5] - 1) = (wchar_t)end_val;
4414131543Stjr      char_set[4]++; /* ranges_index */
4415131543Stjr    }
4416131543Stjr  else
4417131543Stjr# endif
4418131543Stjr    {
4419131543Stjr      range_start = (range_start_char >= 0)? TRANSLATE (range_start_char):
4420131543Stjr	range_start_char;
4421131543Stjr      range_end = TRANSLATE (p[0]);
4422131543Stjr      /* Report an error if the range is empty and the syntax prohibits
4423131543Stjr	 this.  */
4424131543Stjr      ret = ((syntax & RE_NO_EMPTY_RANGES)
4425131543Stjr	     && (range_start > range_end))? REG_ERANGE : REG_NOERROR;
4426131543Stjr
4427131543Stjr      /* Insert space to the end of the char_ranges.  */
4428131543Stjr      insert_space(2, b - char_set[5] - 2, b - 1);
4429131543Stjr      *(b - char_set[5] - 2) = range_start;
4430131543Stjr      *(b - char_set[5] - 1) = range_end;
4431131543Stjr      char_set[4]++; /* ranges_index */
4432131543Stjr    }
4433131543Stjr  /* Have to increment the pointer into the pattern string, so the
4434131543Stjr     caller isn't still at the ending character.  */
4435131543Stjr  (*p_ptr)++;
4436131543Stjr
4437131543Stjr  return ret;
4438131543Stjr}
4439131543Stjr#else
4440218Sconklin/* Read the ending character of a range (in a bracket expression) from the
4441218Sconklin   uncompiled pattern *P_PTR (which ends at PEND).  We assume the
4442218Sconklin   starting character is in `P[-2]'.  (`P[-1]' is the character `-'.)
4443218Sconklin   Then we set the translation of all bits between the starting and
4444218Sconklin   ending characters (inclusive) in the compiled pattern B.
4445126209Sache
4446218Sconklin   Return an error code.
4447126209Sache
4448218Sconklin   We use these short variable names so we can use the same macros as
4449218Sconklin   `regex_compile' itself.  */
4450218Sconklin
4451218Sconklinstatic reg_errcode_t
4452131543Stjrcompile_range (range_start_char, p_ptr, pend, translate, syntax, b)
4453131543Stjr     unsigned int range_start_char;
4454131543Stjr     const char **p_ptr, *pend;
4455131543Stjr     RE_TRANSLATE_TYPE translate;
4456131543Stjr     reg_syntax_t syntax;
4457131543Stjr     unsigned char *b;
4458218Sconklin{
4459218Sconklin  unsigned this_char;
4460218Sconklin  const char *p = *p_ptr;
4461126209Sache  reg_errcode_t ret;
4462131543Stjr# if _LIBC
4463131543Stjr  const unsigned char *collseq;
4464131543Stjr  unsigned int start_colseq;
4465131543Stjr  unsigned int end_colseq;
4466131543Stjr# else
4467131543Stjr  unsigned end_char;
4468131543Stjr# endif
4469126209Sache
4470218Sconklin  if (p == pend)
4471218Sconklin    return REG_ERANGE;
4472218Sconklin
4473218Sconklin  /* Have to increment the pointer into the pattern string, so the
4474218Sconklin     caller isn't still at the ending character.  */
4475218Sconklin  (*p_ptr)++;
4476218Sconklin
4477126209Sache  /* Report an error if the range is empty and the syntax prohibits this.  */
4478126209Sache  ret = syntax & RE_NO_EMPTY_RANGES ? REG_ERANGE : REG_NOERROR;
4479218Sconklin
4480131543Stjr# if _LIBC
4481131543Stjr  collseq = (const unsigned char *) _NL_CURRENT (LC_COLLATE,
4482131543Stjr						 _NL_COLLATE_COLLSEQMB);
4483131543Stjr
4484131543Stjr  start_colseq = collseq[(unsigned char) TRANSLATE (range_start_char)];
4485131543Stjr  end_colseq = collseq[(unsigned char) TRANSLATE (p[0])];
4486131543Stjr  for (this_char = 0; this_char <= (unsigned char) -1; ++this_char)
4487218Sconklin    {
4488131543Stjr      unsigned int this_colseq = collseq[(unsigned char) TRANSLATE (this_char)];
4489131543Stjr
4490131543Stjr      if (start_colseq <= this_colseq && this_colseq <= end_colseq)
4491126209Sache	{
4492126209Sache	  SET_LIST_BIT (TRANSLATE (this_char));
4493126209Sache	  ret = REG_NOERROR;
4494126209Sache	}
4495218Sconklin    }
4496131543Stjr# else
4497131543Stjr  /* Here we see why `this_char' has to be larger than an `unsigned
4498131543Stjr     char' -- we would otherwise go into an infinite loop, since all
4499131543Stjr     characters <= 0xff.  */
4500131543Stjr  range_start_char = TRANSLATE (range_start_char);
4501131543Stjr  /* TRANSLATE(p[0]) is casted to char (not unsigned char) in TRANSLATE,
4502131543Stjr     and some compilers cast it to int implicitly, so following for_loop
4503131543Stjr     may fall to (almost) infinite loop.
4504131543Stjr     e.g. If translate[p[0]] = 0xff, end_char may equals to 0xffffffff.
4505131543Stjr     To avoid this, we cast p[0] to unsigned int and truncate it.  */
4506131543Stjr  end_char = ((unsigned)TRANSLATE(p[0]) & ((1 << BYTEWIDTH) - 1));
4507126209Sache
4508131543Stjr  for (this_char = range_start_char; this_char <= end_char; ++this_char)
4509131543Stjr    {
4510131543Stjr      SET_LIST_BIT (TRANSLATE (this_char));
4511131543Stjr      ret = REG_NOERROR;
4512131543Stjr    }
4513131543Stjr# endif
4514131543Stjr
4515126209Sache  return ret;
4516218Sconklin}
4517131543Stjr#endif /* MBS_SUPPORT */
4518218Sconklin
4519218Sconklin/* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
4520218Sconklin   BUFP.  A fastmap records which of the (1 << BYTEWIDTH) possible
4521218Sconklin   characters can start a string that matches the pattern.  This fastmap
4522218Sconklin   is used by re_search to skip quickly over impossible starting points.
4523218Sconklin
4524218Sconklin   The caller must supply the address of a (1 << BYTEWIDTH)-byte data
4525218Sconklin   area as BUFP->fastmap.
4526126209Sache
4527218Sconklin   We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
4528218Sconklin   the pattern buffer.
4529218Sconklin
4530218Sconklin   Returns 0 if we succeed, -2 if an internal error.   */
4531218Sconklin
4532131543Stjr#ifdef MBS_SUPPORT
4533131543Stjr/* local function for re_compile_fastmap.
4534131543Stjr   truncate wchar_t character to char.  */
4535131543Stjrstatic unsigned char truncate_wchar (CHAR_TYPE c);
4536131543Stjr
4537131543Stjrstatic unsigned char
4538131543Stjrtruncate_wchar (c)
4539131543Stjr     CHAR_TYPE c;
4540131543Stjr{
4541131543Stjr  unsigned char buf[MB_LEN_MAX];
4542131543Stjr  int retval = wctomb(buf, c);
4543131543Stjr  return retval > 0 ? buf[0] : (unsigned char)c;
4544131543Stjr}
4545131543Stjr#endif /* MBS_SUPPORT */
4546131543Stjr
4547218Sconklinint
4548218Sconklinre_compile_fastmap (bufp)
4549218Sconklin     struct re_pattern_buffer *bufp;
4550218Sconklin{
4551218Sconklin  int j, k;
4552126209Sache#ifdef MATCH_MAY_ALLOCATE
4553218Sconklin  fail_stack_type fail_stack;
4554126209Sache#endif
4555218Sconklin#ifndef REGEX_MALLOC
4556218Sconklin  char *destination;
4557218Sconklin#endif
4558126209Sache
4559218Sconklin  register char *fastmap = bufp->fastmap;
4560218Sconklin
4561131543Stjr#ifdef MBS_SUPPORT
4562131543Stjr  /* We need to cast pattern to (wchar_t*), because we casted this compiled
4563131543Stjr     pattern to (char*) in regex_compile.  */
4564131543Stjr  US_CHAR_TYPE *pattern = (US_CHAR_TYPE*)bufp->buffer;
4565131543Stjr  register US_CHAR_TYPE *pend = (US_CHAR_TYPE*) (bufp->buffer + bufp->used);
4566131543Stjr#else
4567131543Stjr  US_CHAR_TYPE *pattern = bufp->buffer;
4568131543Stjr  register US_CHAR_TYPE *pend = pattern + bufp->used;
4569131543Stjr#endif /* MBS_SUPPORT */
4570131543Stjr  US_CHAR_TYPE *p = pattern;
4571131543Stjr
4572126209Sache#ifdef REL_ALLOC
4573126209Sache  /* This holds the pointer to the failure stack, when
4574126209Sache     it is allocated relocatably.  */
4575126209Sache  fail_stack_elt_t *failure_stack_ptr;
4576126209Sache#endif
4577126209Sache
4578218Sconklin  /* Assume that each path through the pattern can be null until
4579218Sconklin     proven otherwise.  We set this false at the bottom of switch
4580218Sconklin     statement, to which we get only if a particular path doesn't
4581218Sconklin     match the empty string.  */
4582218Sconklin  boolean path_can_be_null = true;
4583218Sconklin
4584218Sconklin  /* We aren't doing a `succeed_n' to begin with.  */
4585218Sconklin  boolean succeed_n_p = false;
4586218Sconklin
4587218Sconklin  assert (fastmap != NULL && p != NULL);
4588126209Sache
4589218Sconklin  INIT_FAIL_STACK ();
4590218Sconklin  bzero (fastmap, 1 << BYTEWIDTH);  /* Assume nothing's valid.  */
4591218Sconklin  bufp->fastmap_accurate = 1;	    /* It will be when we're done.  */
4592218Sconklin  bufp->can_be_null = 0;
4593126209Sache
4594126209Sache  while (1)
4595218Sconklin    {
4596126209Sache      if (p == pend || *p == succeed)
4597126209Sache	{
4598126209Sache	  /* We have reached the (effective) end of pattern.  */
4599126209Sache	  if (!FAIL_STACK_EMPTY ())
4600126209Sache	    {
4601126209Sache	      bufp->can_be_null |= path_can_be_null;
4602126209Sache
4603126209Sache	      /* Reset for next path.  */
4604126209Sache	      path_can_be_null = true;
4605126209Sache
4606126209Sache	      p = fail_stack.stack[--fail_stack.avail].pointer;
4607126209Sache
4608126209Sache	      continue;
4609126209Sache	    }
4610126209Sache	  else
4611126209Sache	    break;
4612218Sconklin	}
4613218Sconklin
4614218Sconklin      /* We should never be about to go beyond the end of the pattern.  */
4615218Sconklin      assert (p < pend);
4616126209Sache
4617126209Sache      switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
4618218Sconklin	{
4619218Sconklin
4620218Sconklin        /* I guess the idea here is to simply not bother with a fastmap
4621218Sconklin           if a backreference is used, since it's too hard to figure out
4622218Sconklin           the fastmap for the corresponding group.  Setting
4623218Sconklin           `can_be_null' stops `re_search_2' from using the fastmap, so
4624218Sconklin           that is all we do.  */
4625218Sconklin	case duplicate:
4626218Sconklin	  bufp->can_be_null = 1;
4627126209Sache          goto done;
4628218Sconklin
4629218Sconklin
4630218Sconklin      /* Following are the cases which match a character.  These end
4631218Sconklin         with `break'.  */
4632218Sconklin
4633131543Stjr#ifdef MBS_SUPPORT
4634218Sconklin	case exactn:
4635131543Stjr          fastmap[truncate_wchar(p[1])] = 1;
4636131543Stjr	  break;
4637131543Stjr	case exactn_bin:
4638131543Stjr	  fastmap[p[1]] = 1;
4639131543Stjr	  break;
4640131543Stjr#else
4641131543Stjr	case exactn:
4642218Sconklin          fastmap[p[1]] = 1;
4643218Sconklin	  break;
4644131543Stjr#endif /* MBS_SUPPORT */
4645218Sconklin
4646218Sconklin
4647131543Stjr#ifdef MBS_SUPPORT
4648131543Stjr        /* It is hard to distinguish fastmap from (multi byte) characters
4649131543Stjr           which depends on current locale.  */
4650218Sconklin        case charset:
4651131543Stjr	case charset_not:
4652131543Stjr	case wordchar:
4653131543Stjr	case notwordchar:
4654131543Stjr          bufp->can_be_null = 1;
4655131543Stjr          goto done;
4656131543Stjr#else
4657131543Stjr        case charset:
4658218Sconklin          for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
4659218Sconklin	    if (p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH)))
4660218Sconklin              fastmap[j] = 1;
4661218Sconklin	  break;
4662218Sconklin
4663218Sconklin
4664218Sconklin	case charset_not:
4665218Sconklin	  /* Chars beyond end of map must be allowed.  */
4666218Sconklin	  for (j = *p * BYTEWIDTH; j < (1 << BYTEWIDTH); j++)
4667218Sconklin            fastmap[j] = 1;
4668218Sconklin
4669218Sconklin	  for (j = *p++ * BYTEWIDTH - 1; j >= 0; j--)
4670218Sconklin	    if (!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))))
4671218Sconklin              fastmap[j] = 1;
4672218Sconklin          break;
4673218Sconklin
4674218Sconklin
4675218Sconklin	case wordchar:
4676218Sconklin	  for (j = 0; j < (1 << BYTEWIDTH); j++)
4677218Sconklin	    if (SYNTAX (j) == Sword)
4678218Sconklin	      fastmap[j] = 1;
4679218Sconklin	  break;
4680218Sconklin
4681218Sconklin
4682218Sconklin	case notwordchar:
4683218Sconklin	  for (j = 0; j < (1 << BYTEWIDTH); j++)
4684218Sconklin	    if (SYNTAX (j) != Sword)
4685218Sconklin	      fastmap[j] = 1;
4686218Sconklin	  break;
4687131543Stjr#endif
4688218Sconklin
4689218Sconklin        case anychar:
4690126209Sache	  {
4691126209Sache	    int fastmap_newline = fastmap['\n'];
4692218Sconklin
4693126209Sache	    /* `.' matches anything ...  */
4694126209Sache	    for (j = 0; j < (1 << BYTEWIDTH); j++)
4695126209Sache	      fastmap[j] = 1;
4696218Sconklin
4697126209Sache	    /* ... except perhaps newline.  */
4698126209Sache	    if (!(bufp->syntax & RE_DOT_NEWLINE))
4699126209Sache	      fastmap['\n'] = fastmap_newline;
4700218Sconklin
4701126209Sache	    /* Return if we have already set `can_be_null'; if we have,
4702126209Sache	       then the fastmap is irrelevant.  Something's wrong here.  */
4703126209Sache	    else if (bufp->can_be_null)
4704126209Sache	      goto done;
4705218Sconklin
4706126209Sache	    /* Otherwise, have to check alternative paths.  */
4707126209Sache	    break;
4708126209Sache	  }
4709218Sconklin
4710218Sconklin#ifdef emacs
4711218Sconklin        case syntaxspec:
4712218Sconklin	  k = *p++;
4713218Sconklin	  for (j = 0; j < (1 << BYTEWIDTH); j++)
4714218Sconklin	    if (SYNTAX (j) == (enum syntaxcode) k)
4715218Sconklin	      fastmap[j] = 1;
4716218Sconklin	  break;
4717218Sconklin
4718218Sconklin
4719218Sconklin	case notsyntaxspec:
4720218Sconklin	  k = *p++;
4721218Sconklin	  for (j = 0; j < (1 << BYTEWIDTH); j++)
4722218Sconklin	    if (SYNTAX (j) != (enum syntaxcode) k)
4723218Sconklin	      fastmap[j] = 1;
4724218Sconklin	  break;
4725218Sconklin
4726218Sconklin
4727218Sconklin      /* All cases after this match the empty string.  These end with
4728218Sconklin         `continue'.  */
4729218Sconklin
4730218Sconklin
4731218Sconklin	case before_dot:
4732218Sconklin	case at_dot:
4733218Sconklin	case after_dot:
4734218Sconklin          continue;
4735126209Sache#endif /* emacs */
4736218Sconklin
4737218Sconklin
4738218Sconklin        case no_op:
4739218Sconklin        case begline:
4740218Sconklin        case endline:
4741218Sconklin	case begbuf:
4742218Sconklin	case endbuf:
4743218Sconklin	case wordbound:
4744218Sconklin	case notwordbound:
4745218Sconklin	case wordbeg:
4746218Sconklin	case wordend:
4747218Sconklin        case push_dummy_failure:
4748218Sconklin          continue;
4749218Sconklin
4750218Sconklin
4751218Sconklin	case jump_n:
4752218Sconklin        case pop_failure_jump:
4753218Sconklin	case maybe_pop_jump:
4754218Sconklin	case jump:
4755218Sconklin        case jump_past_alt:
4756218Sconklin	case dummy_failure_jump:
4757218Sconklin          EXTRACT_NUMBER_AND_INCR (j, p);
4758126209Sache	  p += j;
4759218Sconklin	  if (j > 0)
4760218Sconklin	    continue;
4761126209Sache
4762218Sconklin          /* Jump backward implies we just went through the body of a
4763218Sconklin             loop and matched nothing.  Opcode jumped to should be
4764218Sconklin             `on_failure_jump' or `succeed_n'.  Just treat it like an
4765218Sconklin             ordinary jump.  For a * loop, it has pushed its failure
4766218Sconklin             point already; if so, discard that as redundant.  */
4767218Sconklin          if ((re_opcode_t) *p != on_failure_jump
4768218Sconklin	      && (re_opcode_t) *p != succeed_n)
4769218Sconklin	    continue;
4770218Sconklin
4771218Sconklin          p++;
4772218Sconklin          EXTRACT_NUMBER_AND_INCR (j, p);
4773126209Sache          p += j;
4774126209Sache
4775218Sconklin          /* If what's on the stack is where we are now, pop it.  */
4776126209Sache          if (!FAIL_STACK_EMPTY ()
4777126209Sache	      && fail_stack.stack[fail_stack.avail - 1].pointer == p)
4778218Sconklin            fail_stack.avail--;
4779218Sconklin
4780218Sconklin          continue;
4781218Sconklin
4782218Sconklin
4783218Sconklin        case on_failure_jump:
4784218Sconklin        case on_failure_keep_string_jump:
4785218Sconklin	handle_on_failure_jump:
4786218Sconklin          EXTRACT_NUMBER_AND_INCR (j, p);
4787218Sconklin
4788218Sconklin          /* For some patterns, e.g., `(a?)?', `p+j' here points to the
4789218Sconklin             end of the pattern.  We don't want to push such a point,
4790218Sconklin             since when we restore it above, entering the switch will
4791218Sconklin             increment `p' past the end of the pattern.  We don't need
4792218Sconklin             to push such a point since we obviously won't find any more
4793218Sconklin             fastmap entries beyond `pend'.  Such a pattern can match
4794218Sconklin             the null string, though.  */
4795218Sconklin          if (p + j < pend)
4796218Sconklin            {
4797218Sconklin              if (!PUSH_PATTERN_OP (p + j, fail_stack))
4798126209Sache		{
4799126209Sache		  RESET_FAIL_STACK ();
4800126209Sache		  return -2;
4801126209Sache		}
4802218Sconklin            }
4803218Sconklin          else
4804218Sconklin            bufp->can_be_null = 1;
4805218Sconklin
4806218Sconklin          if (succeed_n_p)
4807218Sconklin            {
4808218Sconklin              EXTRACT_NUMBER_AND_INCR (k, p);	/* Skip the n.  */
4809218Sconklin              succeed_n_p = false;
4810218Sconklin	    }
4811218Sconklin
4812218Sconklin          continue;
4813218Sconklin
4814218Sconklin
4815218Sconklin	case succeed_n:
4816218Sconklin          /* Get to the number of times to succeed.  */
4817131543Stjr          p += OFFSET_ADDRESS_SIZE;
4818218Sconklin
4819218Sconklin          /* Increment p past the n for when k != 0.  */
4820218Sconklin          EXTRACT_NUMBER_AND_INCR (k, p);
4821218Sconklin          if (k == 0)
4822218Sconklin	    {
4823131543Stjr              p -= 2 * OFFSET_ADDRESS_SIZE;
4824218Sconklin  	      succeed_n_p = true;  /* Spaghetti code alert.  */
4825218Sconklin              goto handle_on_failure_jump;
4826218Sconklin            }
4827218Sconklin          continue;
4828218Sconklin
4829218Sconklin
4830218Sconklin	case set_number_at:
4831131543Stjr          p += 2 * OFFSET_ADDRESS_SIZE;
4832218Sconklin          continue;
4833218Sconklin
4834218Sconklin
4835218Sconklin	case start_memory:
4836218Sconklin        case stop_memory:
4837218Sconklin	  p += 2;
4838218Sconklin	  continue;
4839218Sconklin
4840218Sconklin
4841218Sconklin	default:
4842218Sconklin          abort (); /* We have listed all the cases.  */
4843218Sconklin        } /* switch *p++ */
4844218Sconklin
4845218Sconklin      /* Getting here means we have found the possible starting
4846218Sconklin         characters for one path of the pattern -- and that the empty
4847218Sconklin         string does not match.  We need not follow this path further.
4848218Sconklin         Instead, look at the next alternative (remembered on the
4849218Sconklin         stack), or quit if no more.  The test at the top of the loop
4850218Sconklin         does these things.  */
4851218Sconklin      path_can_be_null = false;
4852218Sconklin      p = pend;
4853218Sconklin    } /* while p */
4854218Sconklin
4855218Sconklin  /* Set `can_be_null' for the last path (also the first path, if the
4856218Sconklin     pattern is empty).  */
4857218Sconklin  bufp->can_be_null |= path_can_be_null;
4858126209Sache
4859126209Sache done:
4860126209Sache  RESET_FAIL_STACK ();
4861218Sconklin  return 0;
4862218Sconklin} /* re_compile_fastmap */
4863126209Sache#ifdef _LIBC
4864126209Sacheweak_alias (__re_compile_fastmap, re_compile_fastmap)
4865126209Sache#endif
4866218Sconklin
4867218Sconklin/* Set REGS to hold NUM_REGS registers, storing them in STARTS and
4868218Sconklin   ENDS.  Subsequent matches using PATTERN_BUFFER and REGS will use
4869218Sconklin   this memory for recording register information.  STARTS and ENDS
4870218Sconklin   must be allocated using the malloc library routine, and must each
4871218Sconklin   be at least NUM_REGS * sizeof (regoff_t) bytes long.
4872218Sconklin
4873218Sconklin   If NUM_REGS == 0, then subsequent matches should allocate their own
4874218Sconklin   register data.
4875218Sconklin
4876218Sconklin   Unless this function is called, the first search or match using
4877218Sconklin   PATTERN_BUFFER will allocate its own register data, without
4878218Sconklin   freeing the old data.  */
4879218Sconklin
4880218Sconklinvoid
4881218Sconklinre_set_registers (bufp, regs, num_regs, starts, ends)
4882218Sconklin    struct re_pattern_buffer *bufp;
4883218Sconklin    struct re_registers *regs;
4884218Sconklin    unsigned num_regs;
4885218Sconklin    regoff_t *starts, *ends;
4886218Sconklin{
4887218Sconklin  if (num_regs)
4888218Sconklin    {
4889218Sconklin      bufp->regs_allocated = REGS_REALLOCATE;
4890218Sconklin      regs->num_regs = num_regs;
4891218Sconklin      regs->start = starts;
4892218Sconklin      regs->end = ends;
4893218Sconklin    }
4894218Sconklin  else
4895218Sconklin    {
4896218Sconklin      bufp->regs_allocated = REGS_UNALLOCATED;
4897218Sconklin      regs->num_regs = 0;
4898126209Sache      regs->start = regs->end = (regoff_t *) 0;
4899218Sconklin    }
4900218Sconklin}
4901126209Sache#ifdef _LIBC
4902126209Sacheweak_alias (__re_set_registers, re_set_registers)
4903126209Sache#endif
4904218Sconklin
4905218Sconklin/* Searching routines.  */
4906218Sconklin
4907218Sconklin/* Like re_search_2, below, but only one string is specified, and
4908131543Stjr   doesn't let you say where to stop matching.  */
4909218Sconklin
4910218Sconklinint
4911218Sconklinre_search (bufp, string, size, startpos, range, regs)
4912218Sconklin     struct re_pattern_buffer *bufp;
4913218Sconklin     const char *string;
4914218Sconklin     int size, startpos, range;
4915218Sconklin     struct re_registers *regs;
4916218Sconklin{
4917126209Sache  return re_search_2 (bufp, NULL, 0, string, size, startpos, range,
4918218Sconklin		      regs, size);
4919218Sconklin}
4920126209Sache#ifdef _LIBC
4921126209Sacheweak_alias (__re_search, re_search)
4922126209Sache#endif
4923218Sconklin
4924218Sconklin
4925218Sconklin/* Using the compiled pattern in BUFP->buffer, first tries to match the
4926218Sconklin   virtual concatenation of STRING1 and STRING2, starting first at index
4927218Sconklin   STARTPOS, then at STARTPOS + 1, and so on.
4928126209Sache
4929218Sconklin   STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
4930126209Sache
4931218Sconklin   RANGE is how far to scan while trying to match.  RANGE = 0 means try
4932218Sconklin   only at STARTPOS; in general, the last start tried is STARTPOS +
4933218Sconklin   RANGE.
4934126209Sache
4935218Sconklin   In REGS, return the indices of the virtual concatenation of STRING1
4936218Sconklin   and STRING2 that matched the entire BUFP->buffer and its contained
4937218Sconklin   subexpressions.
4938126209Sache
4939218Sconklin   Do not consider matching one past the index STOP in the virtual
4940218Sconklin   concatenation of STRING1 and STRING2.
4941218Sconklin
4942218Sconklin   We return either the position in the strings at which the match was
4943218Sconklin   found, -1 if no match, or -2 if error (such as failure
4944218Sconklin   stack overflow).  */
4945218Sconklin
4946218Sconklinint
4947218Sconklinre_search_2 (bufp, string1, size1, string2, size2, startpos, range, regs, stop)
4948218Sconklin     struct re_pattern_buffer *bufp;
4949218Sconklin     const char *string1, *string2;
4950218Sconklin     int size1, size2;
4951218Sconklin     int startpos;
4952218Sconklin     int range;
4953218Sconklin     struct re_registers *regs;
4954218Sconklin     int stop;
4955218Sconklin{
4956218Sconklin  int val;
4957218Sconklin  register char *fastmap = bufp->fastmap;
4958126209Sache  register RE_TRANSLATE_TYPE translate = bufp->translate;
4959218Sconklin  int total_size = size1 + size2;
4960218Sconklin  int endpos = startpos + range;
4961218Sconklin
4962218Sconklin  /* Check for out-of-range STARTPOS.  */
4963218Sconklin  if (startpos < 0 || startpos > total_size)
4964218Sconklin    return -1;
4965126209Sache
4966218Sconklin  /* Fix up RANGE if it might eventually take us outside
4967126209Sache     the virtual concatenation of STRING1 and STRING2.
4968126209Sache     Make sure we won't move STARTPOS below 0 or above TOTAL_SIZE.  */
4969126209Sache  if (endpos < 0)
4970126209Sache    range = 0 - startpos;
4971218Sconklin  else if (endpos > total_size)
4972218Sconklin    range = total_size - startpos;
4973218Sconklin
4974218Sconklin  /* If the search isn't to be a backwards one, don't waste time in a
4975218Sconklin     search for a pattern that must be anchored.  */
4976126209Sache  if (bufp->used > 0 && range > 0
4977126209Sache      && ((re_opcode_t) bufp->buffer[0] == begbuf
4978126209Sache	  /* `begline' is like `begbuf' if it cannot match at newlines.  */
4979126209Sache	  || ((re_opcode_t) bufp->buffer[0] == begline
4980126209Sache	      && !bufp->newline_anchor)))
4981218Sconklin    {
4982218Sconklin      if (startpos > 0)
4983218Sconklin	return -1;
4984218Sconklin      else
4985218Sconklin	range = 1;
4986218Sconklin    }
4987218Sconklin
4988126209Sache#ifdef emacs
4989126209Sache  /* In a forward search for something that starts with \=.
4990126209Sache     don't keep searching past point.  */
4991126209Sache  if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == at_dot && range > 0)
4992126209Sache    {
4993126209Sache      range = PT - startpos;
4994126209Sache      if (range <= 0)
4995126209Sache	return -1;
4996126209Sache    }
4997126209Sache#endif /* emacs */
4998126209Sache
4999218Sconklin  /* Update the fastmap now if not correct already.  */
5000218Sconklin  if (fastmap && !bufp->fastmap_accurate)
5001218Sconklin    if (re_compile_fastmap (bufp) == -2)
5002218Sconklin      return -2;
5003126209Sache
5004218Sconklin  /* Loop through the string, looking for a place to start matching.  */
5005218Sconklin  for (;;)
5006126209Sache    {
5007218Sconklin      /* If a fastmap is supplied, skip quickly over characters that
5008218Sconklin         cannot be the start of a match.  If the pattern can match the
5009218Sconklin         null string, however, we don't need to skip characters; we want
5010218Sconklin         the first null string.  */
5011218Sconklin      if (fastmap && startpos < total_size && !bufp->can_be_null)
5012218Sconklin	{
5013218Sconklin	  if (range > 0)	/* Searching forwards.  */
5014218Sconklin	    {
5015218Sconklin	      register const char *d;
5016218Sconklin	      register int lim = 0;
5017218Sconklin	      int irange = range;
5018218Sconklin
5019218Sconklin              if (startpos < size1 && startpos + range >= size1)
5020218Sconklin                lim = range - (size1 - startpos);
5021218Sconklin
5022218Sconklin	      d = (startpos >= size1 ? string2 - size1 : string1) + startpos;
5023126209Sache
5024218Sconklin              /* Written out as an if-else to avoid testing `translate'
5025218Sconklin                 inside the loop.  */
5026218Sconklin	      if (translate)
5027218Sconklin                while (range > lim
5028218Sconklin                       && !fastmap[(unsigned char)
5029218Sconklin				   translate[(unsigned char) *d++]])
5030218Sconklin                  range--;
5031218Sconklin	      else
5032218Sconklin                while (range > lim && !fastmap[(unsigned char) *d++])
5033218Sconklin                  range--;
5034218Sconklin
5035218Sconklin	      startpos += irange - range;
5036218Sconklin	    }
5037218Sconklin	  else				/* Searching backwards.  */
5038218Sconklin	    {
5039131543Stjr	      register CHAR_TYPE c = (size1 == 0 || startpos >= size1
5040131543Stjr				      ? string2[startpos - size1]
5041131543Stjr				      : string1[startpos]);
5042218Sconklin
5043218Sconklin	      if (!fastmap[(unsigned char) TRANSLATE (c)])
5044218Sconklin		goto advance;
5045218Sconklin	    }
5046218Sconklin	}
5047218Sconklin
5048218Sconklin      /* If can't match the null string, and that's all we have left, fail.  */
5049218Sconklin      if (range >= 0 && startpos == total_size && fastmap
5050218Sconklin          && !bufp->can_be_null)
5051218Sconklin	return -1;
5052218Sconklin
5053126209Sache      val = re_match_2_internal (bufp, string1, size1, string2, size2,
5054126209Sache				 startpos, regs, stop);
5055126209Sache#ifndef REGEX_MALLOC
5056126209Sache# ifdef C_ALLOCA
5057126209Sache      alloca (0);
5058126209Sache# endif
5059126209Sache#endif
5060126209Sache
5061218Sconklin      if (val >= 0)
5062218Sconklin	return startpos;
5063126209Sache
5064218Sconklin      if (val == -2)
5065218Sconklin	return -2;
5066218Sconklin
5067218Sconklin    advance:
5068126209Sache      if (!range)
5069218Sconklin        break;
5070126209Sache      else if (range > 0)
5071218Sconklin        {
5072126209Sache          range--;
5073218Sconklin          startpos++;
5074218Sconklin        }
5075218Sconklin      else
5076218Sconklin        {
5077126209Sache          range++;
5078218Sconklin          startpos--;
5079218Sconklin        }
5080218Sconklin    }
5081218Sconklin  return -1;
5082218Sconklin} /* re_search_2 */
5083126209Sache#ifdef _LIBC
5084126209Sacheweak_alias (__re_search_2, re_search_2)
5085126209Sache#endif
5086218Sconklin
5087131543Stjr#ifdef MBS_SUPPORT
5088131543Stjr/* This converts PTR, a pointer into one of the search wchar_t strings
5089131543Stjr   `string1' and `string2' into an multibyte string offset from the
5090131543Stjr   beginning of that string. We use mbs_offset to optimize.
5091131543Stjr   See convert_mbs_to_wcs.  */
5092131543Stjr# define POINTER_TO_OFFSET(ptr)						\
5093131543Stjr  (FIRST_STRING_P (ptr)							\
5094131543Stjr   ? ((regoff_t)(mbs_offset1 != NULL? mbs_offset1[(ptr)-string1] : 0))	\
5095131543Stjr   : ((regoff_t)((mbs_offset2 != NULL? mbs_offset2[(ptr)-string2] : 0)	\
5096131543Stjr		 + csize1)))
5097131543Stjr#else
5098218Sconklin/* This converts PTR, a pointer into one of the search strings `string1'
5099218Sconklin   and `string2' into an offset from the beginning of that string.  */
5100131543Stjr# define POINTER_TO_OFFSET(ptr)			\
5101126209Sache  (FIRST_STRING_P (ptr)				\
5102126209Sache   ? ((regoff_t) ((ptr) - string1))		\
5103126209Sache   : ((regoff_t) ((ptr) - string2 + size1)))
5104131543Stjr#endif /* MBS_SUPPORT */
5105218Sconklin
5106218Sconklin/* Macros for dealing with the split strings in re_match_2.  */
5107218Sconklin
5108218Sconklin#define MATCHING_IN_FIRST_STRING  (dend == end_match_1)
5109218Sconklin
5110218Sconklin/* Call before fetching a character with *d.  This switches over to
5111218Sconklin   string2 if necessary.  */
5112218Sconklin#define PREFETCH()							\
5113218Sconklin  while (d == dend)						    	\
5114218Sconklin    {									\
5115218Sconklin      /* End of string2 => fail.  */					\
5116218Sconklin      if (dend == end_match_2) 						\
5117218Sconklin        goto fail;							\
5118218Sconklin      /* End of string1 => advance to string2.  */ 			\
5119218Sconklin      d = string2;						        \
5120218Sconklin      dend = end_match_2;						\
5121218Sconklin    }
5122218Sconklin
5123218Sconklin
5124218Sconklin/* Test if at very beginning or at very end of the virtual concatenation
5125218Sconklin   of `string1' and `string2'.  If only one string, it's `string2'.  */
5126218Sconklin#define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
5127126209Sache#define AT_STRINGS_END(d) ((d) == end2)
5128218Sconklin
5129218Sconklin
5130218Sconklin/* Test if D points to a character which is word-constituent.  We have
5131218Sconklin   two special cases to check for: if past the end of string1, look at
5132218Sconklin   the first character in string2; and if before the beginning of
5133218Sconklin   string2, look at the last character in string1.  */
5134131543Stjr#ifdef MBS_SUPPORT
5135131543Stjr/* Use internationalized API instead of SYNTAX.  */
5136131543Stjr# define WORDCHAR_P(d)							\
5137131543Stjr  (iswalnum ((wint_t)((d) == end1 ? *string2				\
5138131543Stjr           : (d) == string2 - 1 ? *(end1 - 1) : *(d))) != 0)
5139131543Stjr#else
5140131543Stjr# define WORDCHAR_P(d)							\
5141218Sconklin  (SYNTAX ((d) == end1 ? *string2					\
5142218Sconklin           : (d) == string2 - 1 ? *(end1 - 1) : *(d))			\
5143218Sconklin   == Sword)
5144131543Stjr#endif /* MBS_SUPPORT */
5145218Sconklin
5146126209Sache/* Disabled due to a compiler bug -- see comment at case wordbound */
5147126209Sache#if 0
5148218Sconklin/* Test if the character before D and the one at D differ with respect
5149218Sconklin   to being word-constituent.  */
5150218Sconklin#define AT_WORD_BOUNDARY(d)						\
5151218Sconklin  (AT_STRINGS_BEG (d) || AT_STRINGS_END (d)				\
5152218Sconklin   || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
5153126209Sache#endif
5154218Sconklin
5155218Sconklin/* Free everything we malloc.  */
5156126209Sache#ifdef MATCH_MAY_ALLOCATE
5157126209Sache# define FREE_VAR(var) if (var) REGEX_FREE (var); var = NULL
5158131543Stjr# ifdef MBS_SUPPORT
5159131543Stjr#  define FREE_VARIABLES()						\
5160218Sconklin  do {									\
5161126209Sache    REGEX_FREE_STACK (fail_stack.stack);				\
5162218Sconklin    FREE_VAR (regstart);						\
5163218Sconklin    FREE_VAR (regend);							\
5164218Sconklin    FREE_VAR (old_regstart);						\
5165218Sconklin    FREE_VAR (old_regend);						\
5166218Sconklin    FREE_VAR (best_regstart);						\
5167218Sconklin    FREE_VAR (best_regend);						\
5168218Sconklin    FREE_VAR (reg_info);						\
5169218Sconklin    FREE_VAR (reg_dummy);						\
5170218Sconklin    FREE_VAR (reg_info_dummy);						\
5171131543Stjr    FREE_VAR (string1);							\
5172131543Stjr    FREE_VAR (string2);							\
5173131543Stjr    FREE_VAR (mbs_offset1);						\
5174131543Stjr    FREE_VAR (mbs_offset2);						\
5175218Sconklin  } while (0)
5176131543Stjr# else /* not MBS_SUPPORT */
5177131543Stjr#  define FREE_VARIABLES()						\
5178131543Stjr  do {									\
5179131543Stjr    REGEX_FREE_STACK (fail_stack.stack);				\
5180131543Stjr    FREE_VAR (regstart);						\
5181131543Stjr    FREE_VAR (regend);							\
5182131543Stjr    FREE_VAR (old_regstart);						\
5183131543Stjr    FREE_VAR (old_regend);						\
5184131543Stjr    FREE_VAR (best_regstart);						\
5185131543Stjr    FREE_VAR (best_regend);						\
5186131543Stjr    FREE_VAR (reg_info);						\
5187131543Stjr    FREE_VAR (reg_dummy);						\
5188131543Stjr    FREE_VAR (reg_info_dummy);						\
5189131543Stjr  } while (0)
5190131543Stjr# endif /* MBS_SUPPORT */
5191126209Sache#else
5192131543Stjr# define FREE_VAR(var) if (var) free (var); var = NULL
5193131543Stjr# ifdef MBS_SUPPORT
5194131543Stjr#  define FREE_VARIABLES()						\
5195131543Stjr  do {									\
5196131543Stjr    FREE_VAR (string1);							\
5197131543Stjr    FREE_VAR (string2);							\
5198131543Stjr    FREE_VAR (mbs_offset1);						\
5199131543Stjr    FREE_VAR (mbs_offset2);						\
5200131543Stjr  } while (0)
5201131543Stjr# else
5202131543Stjr#  define FREE_VARIABLES() ((void)0) /* Do nothing!  But inhibit gcc warning. */
5203131543Stjr# endif /* MBS_SUPPORT */
5204126209Sache#endif /* not MATCH_MAY_ALLOCATE */
5205218Sconklin
5206218Sconklin/* These values must meet several constraints.  They must not be valid
5207218Sconklin   register values; since we have a limit of 255 registers (because
5208218Sconklin   we use only one byte in the pattern for the register number), we can
5209218Sconklin   use numbers larger than 255.  They must differ by 1, because of
5210218Sconklin   NUM_FAILURE_ITEMS above.  And the value for the lowest register must
5211218Sconklin   be larger than the value for the highest register, so we do not try
5212218Sconklin   to actually save any registers when none are active.  */
5213218Sconklin#define NO_HIGHEST_ACTIVE_REG (1 << BYTEWIDTH)
5214218Sconklin#define NO_LOWEST_ACTIVE_REG (NO_HIGHEST_ACTIVE_REG + 1)
5215218Sconklin
5216218Sconklin/* Matching routines.  */
5217218Sconklin
5218218Sconklin#ifndef emacs   /* Emacs never uses this.  */
5219218Sconklin/* re_match is like re_match_2 except it takes only a single string.  */
5220218Sconklin
5221218Sconklinint
5222218Sconklinre_match (bufp, string, size, pos, regs)
5223218Sconklin     struct re_pattern_buffer *bufp;
5224218Sconklin     const char *string;
5225218Sconklin     int size, pos;
5226218Sconklin     struct re_registers *regs;
5227126209Sache{
5228126209Sache  int result = re_match_2_internal (bufp, NULL, 0, string, size,
5229126209Sache				    pos, regs, size);
5230126209Sache# ifndef REGEX_MALLOC
5231126209Sache#  ifdef C_ALLOCA
5232126209Sache  alloca (0);
5233126209Sache#  endif
5234126209Sache# endif
5235126209Sache  return result;
5236218Sconklin}
5237126209Sache# ifdef _LIBC
5238126209Sacheweak_alias (__re_match, re_match)
5239126209Sache# endif
5240218Sconklin#endif /* not emacs */
5241218Sconklin
5242131543Stjrstatic boolean group_match_null_string_p _RE_ARGS ((US_CHAR_TYPE **p,
5243131543Stjr						    US_CHAR_TYPE *end,
5244126209Sache						register_info_type *reg_info));
5245131543Stjrstatic boolean alt_match_null_string_p _RE_ARGS ((US_CHAR_TYPE *p,
5246131543Stjr						  US_CHAR_TYPE *end,
5247126209Sache						register_info_type *reg_info));
5248131543Stjrstatic boolean common_op_match_null_string_p _RE_ARGS ((US_CHAR_TYPE **p,
5249131543Stjr							US_CHAR_TYPE *end,
5250126209Sache						register_info_type *reg_info));
5251131543Stjrstatic int bcmp_translate _RE_ARGS ((const CHAR_TYPE *s1, const CHAR_TYPE *s2,
5252126209Sache				     int len, char *translate));
5253218Sconklin
5254218Sconklin/* re_match_2 matches the compiled pattern in BUFP against the
5255218Sconklin   the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
5256218Sconklin   and SIZE2, respectively).  We start matching at POS, and stop
5257218Sconklin   matching at STOP.
5258126209Sache
5259218Sconklin   If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
5260218Sconklin   store offsets for the substring each group matched in REGS.  See the
5261218Sconklin   documentation for exactly how many groups we fill.
5262218Sconklin
5263218Sconklin   We return -1 if no match, -2 if an internal error (such as the
5264218Sconklin   failure stack overflowing).  Otherwise, we return the length of the
5265218Sconklin   matched substring.  */
5266218Sconklin
5267218Sconklinint
5268218Sconklinre_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
5269218Sconklin     struct re_pattern_buffer *bufp;
5270218Sconklin     const char *string1, *string2;
5271218Sconklin     int size1, size2;
5272218Sconklin     int pos;
5273218Sconklin     struct re_registers *regs;
5274218Sconklin     int stop;
5275218Sconklin{
5276126209Sache  int result = re_match_2_internal (bufp, string1, size1, string2, size2,
5277126209Sache				    pos, regs, stop);
5278126209Sache#ifndef REGEX_MALLOC
5279126209Sache# ifdef C_ALLOCA
5280126209Sache  alloca (0);
5281126209Sache# endif
5282126209Sache#endif
5283126209Sache  return result;
5284126209Sache}
5285126209Sache#ifdef _LIBC
5286126209Sacheweak_alias (__re_match_2, re_match_2)
5287126209Sache#endif
5288126209Sache
5289131543Stjr#ifdef MBS_SUPPORT
5290131543Stjr
5291131543Stjrstatic int count_mbs_length PARAMS ((int *, int));
5292131543Stjr
5293131543Stjr/* This check the substring (from 0, to length) of the multibyte string,
5294131543Stjr   to which offset_buffer correspond. And count how many wchar_t_characters
5295131543Stjr   the substring occupy. We use offset_buffer to optimization.
5296131543Stjr   See convert_mbs_to_wcs.  */
5297131543Stjr
5298131543Stjrstatic int
5299131543Stjrcount_mbs_length(offset_buffer, length)
5300131543Stjr     int *offset_buffer;
5301131543Stjr     int length;
5302131543Stjr{
5303131543Stjr  int wcs_size;
5304131543Stjr
5305131543Stjr  /* Check whether the size is valid.  */
5306131543Stjr  if (length < 0)
5307131543Stjr    return -1;
5308131543Stjr
5309131543Stjr  if (offset_buffer == NULL)
5310131543Stjr    return 0;
5311131543Stjr
5312131543Stjr  for (wcs_size = 0 ; offset_buffer[wcs_size] != -1 ; wcs_size++)
5313131543Stjr    {
5314131543Stjr      if (offset_buffer[wcs_size] == length)
5315131543Stjr	return wcs_size;
5316131543Stjr      if (offset_buffer[wcs_size] > length)
5317131543Stjr	/* It is a fragment of a wide character.  */
5318131543Stjr	return -1;
5319131543Stjr    }
5320131543Stjr
5321131543Stjr  /* We reached at the sentinel.  */
5322131543Stjr  return -1;
5323131543Stjr}
5324131543Stjr#endif /* MBS_SUPPORT */
5325131543Stjr
5326126209Sache/* This is a separate function so that we can force an alloca cleanup
5327126209Sache   afterwards.  */
5328126209Sachestatic int
5329131543Stjr#ifdef MBS_SUPPORT
5330131543Stjrre_match_2_internal (bufp, cstring1, csize1, cstring2, csize2, pos, regs, stop)
5331131543Stjr     struct re_pattern_buffer *bufp;
5332131543Stjr     const char *cstring1, *cstring2;
5333131543Stjr     int csize1, csize2;
5334131543Stjr#else
5335126209Sachere_match_2_internal (bufp, string1, size1, string2, size2, pos, regs, stop)
5336126209Sache     struct re_pattern_buffer *bufp;
5337126209Sache     const char *string1, *string2;
5338126209Sache     int size1, size2;
5339131543Stjr#endif
5340126209Sache     int pos;
5341126209Sache     struct re_registers *regs;
5342126209Sache     int stop;
5343126209Sache{
5344218Sconklin  /* General temporaries.  */
5345218Sconklin  int mcnt;
5346131543Stjr  US_CHAR_TYPE *p1;
5347131543Stjr#ifdef MBS_SUPPORT
5348131543Stjr  /* We need wchar_t* buffers correspond to string1, string2.  */
5349131543Stjr  CHAR_TYPE *string1 = NULL, *string2 = NULL;
5350131543Stjr  /* We need the size of wchar_t buffers correspond to csize1, csize2.  */
5351131543Stjr  int size1 = 0, size2 = 0;
5352131543Stjr  /* offset buffer for optimizatoin. See convert_mbs_to_wc.  */
5353131543Stjr  int *mbs_offset1 = NULL, *mbs_offset2 = NULL;
5354131543Stjr  /* They hold whether each wchar_t is binary data or not.  */
5355131543Stjr  char *is_binary = NULL;
5356131543Stjr#endif /* MBS_SUPPORT */
5357218Sconklin
5358218Sconklin  /* Just past the end of the corresponding string.  */
5359131543Stjr  const CHAR_TYPE *end1, *end2;
5360218Sconklin
5361218Sconklin  /* Pointers into string1 and string2, just past the last characters in
5362218Sconklin     each to consider matching.  */
5363131543Stjr  const CHAR_TYPE *end_match_1, *end_match_2;
5364218Sconklin
5365218Sconklin  /* Where we are in the data, and the end of the current string.  */
5366131543Stjr  const CHAR_TYPE *d, *dend;
5367126209Sache
5368218Sconklin  /* Where we are in the pattern, and the end of the pattern.  */
5369131543Stjr#ifdef MBS_SUPPORT
5370131543Stjr  US_CHAR_TYPE *pattern, *p;
5371131543Stjr  register US_CHAR_TYPE *pend;
5372131543Stjr#else
5373131543Stjr  US_CHAR_TYPE *p = bufp->buffer;
5374131543Stjr  register US_CHAR_TYPE *pend = p + bufp->used;
5375131543Stjr#endif /* MBS_SUPPORT */
5376218Sconklin
5377126209Sache  /* Mark the opcode just after a start_memory, so we can test for an
5378126209Sache     empty subpattern when we get to the stop_memory.  */
5379131543Stjr  US_CHAR_TYPE *just_past_start_mem = 0;
5380126209Sache
5381218Sconklin  /* We use this to map every character in the string.  */
5382126209Sache  RE_TRANSLATE_TYPE translate = bufp->translate;
5383218Sconklin
5384218Sconklin  /* Failure point stack.  Each place that can handle a failure further
5385218Sconklin     down the line pushes a failure point on this stack.  It consists of
5386218Sconklin     restart, regend, and reg_info for all registers corresponding to
5387218Sconklin     the subexpressions we're currently inside, plus the number of such
5388218Sconklin     registers, and, finally, two char *'s.  The first char * is where
5389218Sconklin     to resume scanning the pattern; the second one is where to resume
5390218Sconklin     scanning the strings.  If the latter is zero, the failure point is
5391218Sconklin     a ``dummy''; if a failure happens and the failure point is a dummy,
5392218Sconklin     it gets discarded and the next next one is tried.  */
5393126209Sache#ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global.  */
5394218Sconklin  fail_stack_type fail_stack;
5395126209Sache#endif
5396218Sconklin#ifdef DEBUG
5397126209Sache  static unsigned failure_id;
5398218Sconklin  unsigned nfailure_points_pushed = 0, nfailure_points_popped = 0;
5399218Sconklin#endif
5400218Sconklin
5401126209Sache#ifdef REL_ALLOC
5402126209Sache  /* This holds the pointer to the failure stack, when
5403126209Sache     it is allocated relocatably.  */
5404126209Sache  fail_stack_elt_t *failure_stack_ptr;
5405126209Sache#endif
5406126209Sache
5407218Sconklin  /* We fill all the registers internally, independent of what we
5408218Sconklin     return, for use in backreferences.  The number here includes
5409218Sconklin     an element for register zero.  */
5410126209Sache  size_t num_regs = bufp->re_nsub + 1;
5411126209Sache
5412218Sconklin  /* The currently active registers.  */
5413126209Sache  active_reg_t lowest_active_reg = NO_LOWEST_ACTIVE_REG;
5414126209Sache  active_reg_t highest_active_reg = NO_HIGHEST_ACTIVE_REG;
5415218Sconklin
5416218Sconklin  /* Information on the contents of registers. These are pointers into
5417218Sconklin     the input strings; they record just what was matched (on this
5418218Sconklin     attempt) by a subexpression part of the pattern, that is, the
5419218Sconklin     regnum-th regstart pointer points to where in the pattern we began
5420218Sconklin     matching and the regnum-th regend points to right after where we
5421218Sconklin     stopped matching the regnum-th subexpression.  (The zeroth register
5422218Sconklin     keeps track of what the whole pattern matches.)  */
5423126209Sache#ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global.  */
5424131543Stjr  const CHAR_TYPE **regstart, **regend;
5425126209Sache#endif
5426218Sconklin
5427218Sconklin  /* If a group that's operated upon by a repetition operator fails to
5428218Sconklin     match anything, then the register for its start will need to be
5429218Sconklin     restored because it will have been set to wherever in the string we
5430218Sconklin     are when we last see its open-group operator.  Similarly for a
5431218Sconklin     register's end.  */
5432126209Sache#ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global.  */
5433131543Stjr  const CHAR_TYPE **old_regstart, **old_regend;
5434126209Sache#endif
5435218Sconklin
5436218Sconklin  /* The is_active field of reg_info helps us keep track of which (possibly
5437218Sconklin     nested) subexpressions we are currently in. The matched_something
5438218Sconklin     field of reg_info[reg_num] helps us tell whether or not we have
5439218Sconklin     matched any of the pattern so far this time through the reg_num-th
5440218Sconklin     subexpression.  These two fields get reset each time through any
5441218Sconklin     loop their register is in.  */
5442126209Sache#ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global.  */
5443126209Sache  register_info_type *reg_info;
5444126209Sache#endif
5445218Sconklin
5446218Sconklin  /* The following record the register info as found in the above
5447126209Sache     variables when we find a match better than any we've seen before.
5448218Sconklin     This happens as we backtrack through the failure points, which in
5449218Sconklin     turn happens only if we have not yet matched the entire string. */
5450218Sconklin  unsigned best_regs_set = false;
5451126209Sache#ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global.  */
5452131543Stjr  const CHAR_TYPE **best_regstart, **best_regend;
5453126209Sache#endif
5454126209Sache
5455218Sconklin  /* Logically, this is `best_regend[0]'.  But we don't want to have to
5456218Sconklin     allocate space for that if we're not allocating space for anything
5457218Sconklin     else (see below).  Also, we never need info about register 0 for
5458218Sconklin     any of the other register vectors, and it seems rather a kludge to
5459218Sconklin     treat `best_regend' differently than the rest.  So we keep track of
5460218Sconklin     the end of the best match so far in a separate variable.  We
5461218Sconklin     initialize this to NULL so that when we backtrack the first time
5462218Sconklin     and need to test it, it's not garbage.  */
5463131543Stjr  const CHAR_TYPE *match_end = NULL;
5464218Sconklin
5465126209Sache  /* This helps SET_REGS_MATCHED avoid doing redundant work.  */
5466126209Sache  int set_regs_matched_done = 0;
5467126209Sache
5468218Sconklin  /* Used when we pop values we don't care about.  */
5469126209Sache#ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global.  */
5470131543Stjr  const CHAR_TYPE **reg_dummy;
5471218Sconklin  register_info_type *reg_info_dummy;
5472126209Sache#endif
5473218Sconklin
5474218Sconklin#ifdef DEBUG
5475218Sconklin  /* Counts the total number of registers pushed.  */
5476126209Sache  unsigned num_regs_pushed = 0;
5477218Sconklin#endif
5478218Sconklin
5479218Sconklin  DEBUG_PRINT1 ("\n\nEntering re_match_2.\n");
5480126209Sache
5481218Sconklin  INIT_FAIL_STACK ();
5482126209Sache
5483126209Sache#ifdef MATCH_MAY_ALLOCATE
5484218Sconklin  /* Do not bother to initialize all the register variables if there are
5485218Sconklin     no groups in the pattern, as it takes a fair amount of time.  If
5486218Sconklin     there are groups, we include space for register 0 (the whole
5487218Sconklin     pattern), even though we never use it, since it simplifies the
5488218Sconklin     array indexing.  We should fix this.  */
5489218Sconklin  if (bufp->re_nsub)
5490218Sconklin    {
5491131543Stjr      regstart = REGEX_TALLOC (num_regs, const CHAR_TYPE *);
5492131543Stjr      regend = REGEX_TALLOC (num_regs, const CHAR_TYPE *);
5493131543Stjr      old_regstart = REGEX_TALLOC (num_regs, const CHAR_TYPE *);
5494131543Stjr      old_regend = REGEX_TALLOC (num_regs, const CHAR_TYPE *);
5495131543Stjr      best_regstart = REGEX_TALLOC (num_regs, const CHAR_TYPE *);
5496131543Stjr      best_regend = REGEX_TALLOC (num_regs, const CHAR_TYPE *);
5497218Sconklin      reg_info = REGEX_TALLOC (num_regs, register_info_type);
5498131543Stjr      reg_dummy = REGEX_TALLOC (num_regs, const CHAR_TYPE *);
5499218Sconklin      reg_info_dummy = REGEX_TALLOC (num_regs, register_info_type);
5500218Sconklin
5501126209Sache      if (!(regstart && regend && old_regstart && old_regend && reg_info
5502126209Sache            && best_regstart && best_regend && reg_dummy && reg_info_dummy))
5503218Sconklin        {
5504218Sconklin          FREE_VARIABLES ();
5505218Sconklin          return -2;
5506218Sconklin        }
5507218Sconklin    }
5508218Sconklin  else
5509218Sconklin    {
5510218Sconklin      /* We must initialize all our variables to NULL, so that
5511218Sconklin         `FREE_VARIABLES' doesn't try to free them.  */
5512218Sconklin      regstart = regend = old_regstart = old_regend = best_regstart
5513218Sconklin        = best_regend = reg_dummy = NULL;
5514218Sconklin      reg_info = reg_info_dummy = (register_info_type *) NULL;
5515218Sconklin    }
5516126209Sache#endif /* MATCH_MAY_ALLOCATE */
5517218Sconklin
5518218Sconklin  /* The starting position is bogus.  */
5519131543Stjr#ifdef MBS_SUPPORT
5520131543Stjr  if (pos < 0 || pos > csize1 + csize2)
5521131543Stjr#else
5522218Sconklin  if (pos < 0 || pos > size1 + size2)
5523131543Stjr#endif
5524218Sconklin    {
5525218Sconklin      FREE_VARIABLES ();
5526218Sconklin      return -1;
5527218Sconklin    }
5528126209Sache
5529131543Stjr#ifdef MBS_SUPPORT
5530131543Stjr  /* Allocate wchar_t array for string1 and string2 and
5531131543Stjr     fill them with converted string.  */
5532131543Stjr  if (csize1 != 0)
5533131543Stjr    {
5534131543Stjr      string1 = REGEX_TALLOC (csize1 + 1, CHAR_TYPE);
5535131543Stjr      mbs_offset1 = REGEX_TALLOC (csize1 + 1, int);
5536131543Stjr      is_binary = REGEX_TALLOC (csize1 + 1, char);
5537131543Stjr      if (!string1 || !mbs_offset1 || !is_binary)
5538131543Stjr	{
5539131543Stjr	  FREE_VAR (string1);
5540131543Stjr	  FREE_VAR (mbs_offset1);
5541131543Stjr	  FREE_VAR (is_binary);
5542131543Stjr	  return -2;
5543131543Stjr	}
5544131543Stjr      size1 = convert_mbs_to_wcs(string1, cstring1, csize1,
5545131543Stjr				 mbs_offset1, is_binary);
5546131543Stjr      string1[size1] = L'\0'; /* for a sentinel  */
5547131543Stjr      FREE_VAR (is_binary);
5548131543Stjr    }
5549131543Stjr  if (csize2 != 0)
5550131543Stjr    {
5551131543Stjr      string2 = REGEX_TALLOC (csize2 + 1, CHAR_TYPE);
5552131543Stjr      mbs_offset2 = REGEX_TALLOC (csize2 + 1, int);
5553131543Stjr      is_binary = REGEX_TALLOC (csize2 + 1, char);
5554131543Stjr      if (!string2 || !mbs_offset2 || !is_binary)
5555131543Stjr	{
5556131543Stjr	  FREE_VAR (string1);
5557131543Stjr	  FREE_VAR (mbs_offset1);
5558131543Stjr	  FREE_VAR (string2);
5559131543Stjr	  FREE_VAR (mbs_offset2);
5560131543Stjr	  FREE_VAR (is_binary);
5561131543Stjr	  return -2;
5562131543Stjr	}
5563131543Stjr      size2 = convert_mbs_to_wcs(string2, cstring2, csize2,
5564131543Stjr				 mbs_offset2, is_binary);
5565131543Stjr      string2[size2] = L'\0'; /* for a sentinel  */
5566131543Stjr      FREE_VAR (is_binary);
5567131543Stjr    }
5568131543Stjr
5569131543Stjr  /* We need to cast pattern to (wchar_t*), because we casted this compiled
5570131543Stjr     pattern to (char*) in regex_compile.  */
5571131543Stjr  p = pattern = (CHAR_TYPE*)bufp->buffer;
5572131543Stjr  pend = (CHAR_TYPE*)(bufp->buffer + bufp->used);
5573131543Stjr
5574131543Stjr#endif /* MBS_SUPPORT */
5575131543Stjr
5576218Sconklin  /* Initialize subexpression text positions to -1 to mark ones that no
5577218Sconklin     start_memory/stop_memory has been seen for. Also initialize the
5578218Sconklin     register information struct.  */
5579126209Sache  for (mcnt = 1; (unsigned) mcnt < num_regs; mcnt++)
5580218Sconklin    {
5581126209Sache      regstart[mcnt] = regend[mcnt]
5582218Sconklin        = old_regstart[mcnt] = old_regend[mcnt] = REG_UNSET_VALUE;
5583126209Sache
5584218Sconklin      REG_MATCH_NULL_STRING_P (reg_info[mcnt]) = MATCH_NULL_UNSET_VALUE;
5585218Sconklin      IS_ACTIVE (reg_info[mcnt]) = 0;
5586218Sconklin      MATCHED_SOMETHING (reg_info[mcnt]) = 0;
5587218Sconklin      EVER_MATCHED_SOMETHING (reg_info[mcnt]) = 0;
5588218Sconklin    }
5589126209Sache
5590218Sconklin  /* We move `string1' into `string2' if the latter's empty -- but not if
5591218Sconklin     `string1' is null.  */
5592218Sconklin  if (size2 == 0 && string1 != NULL)
5593218Sconklin    {
5594218Sconklin      string2 = string1;
5595218Sconklin      size2 = size1;
5596218Sconklin      string1 = 0;
5597218Sconklin      size1 = 0;
5598218Sconklin    }
5599218Sconklin  end1 = string1 + size1;
5600218Sconklin  end2 = string2 + size2;
5601218Sconklin
5602218Sconklin  /* Compute where to stop matching, within the two strings.  */
5603131543Stjr#ifdef MBS_SUPPORT
5604131543Stjr  if (stop <= csize1)
5605131543Stjr    {
5606131543Stjr      mcnt = count_mbs_length(mbs_offset1, stop);
5607131543Stjr      end_match_1 = string1 + mcnt;
5608131543Stjr      end_match_2 = string2;
5609131543Stjr    }
5610131543Stjr  else
5611131543Stjr    {
5612131543Stjr      end_match_1 = end1;
5613131543Stjr      mcnt = count_mbs_length(mbs_offset2, stop-csize1);
5614131543Stjr      end_match_2 = string2 + mcnt;
5615131543Stjr    }
5616131543Stjr  if (mcnt < 0)
5617131543Stjr    { /* count_mbs_length return error.  */
5618131543Stjr      FREE_VARIABLES ();
5619131543Stjr      return -1;
5620131543Stjr    }
5621131543Stjr#else
5622218Sconklin  if (stop <= size1)
5623218Sconklin    {
5624218Sconklin      end_match_1 = string1 + stop;
5625218Sconklin      end_match_2 = string2;
5626218Sconklin    }
5627218Sconklin  else
5628218Sconklin    {
5629218Sconklin      end_match_1 = end1;
5630218Sconklin      end_match_2 = string2 + stop - size1;
5631218Sconklin    }
5632131543Stjr#endif /* MBS_SUPPORT */
5633218Sconklin
5634126209Sache  /* `p' scans through the pattern as `d' scans through the data.
5635218Sconklin     `dend' is the end of the input string that `d' points within.  `d'
5636218Sconklin     is advanced into the following input string whenever necessary, but
5637218Sconklin     this happens before fetching; therefore, at the beginning of the
5638218Sconklin     loop, `d' can be pointing at the end of a string, but it cannot
5639218Sconklin     equal `string2'.  */
5640131543Stjr#ifdef MBS_SUPPORT
5641131543Stjr  if (size1 > 0 && pos <= csize1)
5642131543Stjr    {
5643131543Stjr      mcnt = count_mbs_length(mbs_offset1, pos);
5644131543Stjr      d = string1 + mcnt;
5645131543Stjr      dend = end_match_1;
5646131543Stjr    }
5647131543Stjr  else
5648131543Stjr    {
5649131543Stjr      mcnt = count_mbs_length(mbs_offset2, pos-csize1);
5650131543Stjr      d = string2 + mcnt;
5651131543Stjr      dend = end_match_2;
5652131543Stjr    }
5653131543Stjr
5654131543Stjr  if (mcnt < 0)
5655131543Stjr    { /* count_mbs_length return error.  */
5656131543Stjr      FREE_VARIABLES ();
5657131543Stjr      return -1;
5658131543Stjr    }
5659131543Stjr#else
5660218Sconklin  if (size1 > 0 && pos <= size1)
5661218Sconklin    {
5662218Sconklin      d = string1 + pos;
5663218Sconklin      dend = end_match_1;
5664218Sconklin    }
5665218Sconklin  else
5666218Sconklin    {
5667218Sconklin      d = string2 + pos - size1;
5668218Sconklin      dend = end_match_2;
5669218Sconklin    }
5670131543Stjr#endif /* MBS_SUPPORT */
5671218Sconklin
5672126209Sache  DEBUG_PRINT1 ("The compiled pattern is:\n");
5673218Sconklin  DEBUG_PRINT_COMPILED_PATTERN (bufp, p, pend);
5674218Sconklin  DEBUG_PRINT1 ("The string to match is: `");
5675218Sconklin  DEBUG_PRINT_DOUBLE_STRING (d, string1, size1, string2, size2);
5676218Sconklin  DEBUG_PRINT1 ("'\n");
5677126209Sache
5678218Sconklin  /* This loops over pattern commands.  It exits by returning from the
5679218Sconklin     function if the match is complete, or it drops through if the match
5680218Sconklin     fails at this starting point in the input data.  */
5681218Sconklin  for (;;)
5682218Sconklin    {
5683126209Sache#ifdef _LIBC
5684126209Sache      DEBUG_PRINT2 ("\n%p: ", p);
5685126209Sache#else
5686218Sconklin      DEBUG_PRINT2 ("\n0x%x: ", p);
5687126209Sache#endif
5688218Sconklin
5689218Sconklin      if (p == pend)
5690218Sconklin	{ /* End of pattern means we might have succeeded.  */
5691218Sconklin          DEBUG_PRINT1 ("end of pattern ... ");
5692126209Sache
5693218Sconklin	  /* If we haven't matched the entire string, and we want the
5694218Sconklin             longest match, try backtracking.  */
5695218Sconklin          if (d != end_match_2)
5696218Sconklin	    {
5697126209Sache	      /* 1 if this match ends in the same string (string1 or string2)
5698126209Sache		 as the best previous match.  */
5699126209Sache	      boolean same_str_p = (FIRST_STRING_P (match_end)
5700126209Sache				    == MATCHING_IN_FIRST_STRING);
5701126209Sache	      /* 1 if this match is the best seen so far.  */
5702126209Sache	      boolean best_match_p;
5703126209Sache
5704126209Sache	      /* AIX compiler got confused when this was combined
5705126209Sache		 with the previous declaration.  */
5706126209Sache	      if (same_str_p)
5707126209Sache		best_match_p = d > match_end;
5708126209Sache	      else
5709126209Sache		best_match_p = !MATCHING_IN_FIRST_STRING;
5710126209Sache
5711218Sconklin              DEBUG_PRINT1 ("backtracking.\n");
5712126209Sache
5713218Sconklin              if (!FAIL_STACK_EMPTY ())
5714218Sconklin                { /* More failure points to try.  */
5715218Sconklin
5716218Sconklin                  /* If exceeds best match so far, save it.  */
5717126209Sache                  if (!best_regs_set || best_match_p)
5718218Sconklin                    {
5719218Sconklin                      best_regs_set = true;
5720218Sconklin                      match_end = d;
5721126209Sache
5722218Sconklin                      DEBUG_PRINT1 ("\nSAVING match as best so far.\n");
5723126209Sache
5724126209Sache                      for (mcnt = 1; (unsigned) mcnt < num_regs; mcnt++)
5725218Sconklin                        {
5726218Sconklin                          best_regstart[mcnt] = regstart[mcnt];
5727218Sconklin                          best_regend[mcnt] = regend[mcnt];
5728218Sconklin                        }
5729218Sconklin                    }
5730126209Sache                  goto fail;
5731218Sconklin                }
5732218Sconklin
5733126209Sache              /* If no failure points, don't restore garbage.  And if
5734126209Sache                 last match is real best match, don't restore second
5735126209Sache                 best one. */
5736126209Sache              else if (best_regs_set && !best_match_p)
5737218Sconklin                {
5738218Sconklin  	        restore_best_regs:
5739218Sconklin                  /* Restore best match.  It may happen that `dend ==
5740218Sconklin                     end_match_1' while the restored d is in string2.
5741218Sconklin                     For example, the pattern `x.*y.*z' against the
5742218Sconklin                     strings `x-' and `y-z-', if the two strings are
5743218Sconklin                     not consecutive in memory.  */
5744218Sconklin                  DEBUG_PRINT1 ("Restoring best registers.\n");
5745126209Sache
5746218Sconklin                  d = match_end;
5747218Sconklin                  dend = ((d >= string1 && d <= end1)
5748218Sconklin		           ? end_match_1 : end_match_2);
5749218Sconklin
5750126209Sache		  for (mcnt = 1; (unsigned) mcnt < num_regs; mcnt++)
5751218Sconklin		    {
5752218Sconklin		      regstart[mcnt] = best_regstart[mcnt];
5753218Sconklin		      regend[mcnt] = best_regend[mcnt];
5754218Sconklin		    }
5755218Sconklin                }
5756218Sconklin            } /* d != end_match_2 */
5757218Sconklin
5758126209Sache	succeed_label:
5759218Sconklin          DEBUG_PRINT1 ("Accepting match.\n");
5760218Sconklin          /* If caller wants register contents data back, do it.  */
5761218Sconklin          if (regs && !bufp->no_sub)
5762218Sconklin	    {
5763131543Stjr	      /* Have the register data arrays been allocated?  */
5764218Sconklin              if (bufp->regs_allocated == REGS_UNALLOCATED)
5765218Sconklin                { /* No.  So allocate them with malloc.  We need one
5766218Sconklin                     extra element beyond `num_regs' for the `-1' marker
5767218Sconklin                     GNU code uses.  */
5768218Sconklin                  regs->num_regs = MAX (RE_NREGS, num_regs + 1);
5769218Sconklin                  regs->start = TALLOC (regs->num_regs, regoff_t);
5770218Sconklin                  regs->end = TALLOC (regs->num_regs, regoff_t);
5771218Sconklin                  if (regs->start == NULL || regs->end == NULL)
5772126209Sache		    {
5773126209Sache		      FREE_VARIABLES ();
5774126209Sache		      return -2;
5775126209Sache		    }
5776218Sconklin                  bufp->regs_allocated = REGS_REALLOCATE;
5777218Sconklin                }
5778218Sconklin              else if (bufp->regs_allocated == REGS_REALLOCATE)
5779218Sconklin                { /* Yes.  If we need more elements than were already
5780218Sconklin                     allocated, reallocate them.  If we need fewer, just
5781218Sconklin                     leave it alone.  */
5782218Sconklin                  if (regs->num_regs < num_regs + 1)
5783218Sconklin                    {
5784218Sconklin                      regs->num_regs = num_regs + 1;
5785218Sconklin                      RETALLOC (regs->start, regs->num_regs, regoff_t);
5786218Sconklin                      RETALLOC (regs->end, regs->num_regs, regoff_t);
5787218Sconklin                      if (regs->start == NULL || regs->end == NULL)
5788126209Sache			{
5789126209Sache			  FREE_VARIABLES ();
5790126209Sache			  return -2;
5791126209Sache			}
5792218Sconklin                    }
5793218Sconklin                }
5794218Sconklin              else
5795126209Sache		{
5796126209Sache		  /* These braces fend off a "empty body in an else-statement"
5797126209Sache		     warning under GCC when assert expands to nothing.  */
5798126209Sache		  assert (bufp->regs_allocated == REGS_FIXED);
5799126209Sache		}
5800218Sconklin
5801218Sconklin              /* Convert the pointer data in `regstart' and `regend' to
5802218Sconklin                 indices.  Register zero has to be set differently,
5803218Sconklin                 since we haven't kept track of any info for it.  */
5804218Sconklin              if (regs->num_regs > 0)
5805218Sconklin                {
5806218Sconklin                  regs->start[0] = pos;
5807131543Stjr#ifdef MBS_SUPPORT
5808131543Stjr		  if (MATCHING_IN_FIRST_STRING)
5809131543Stjr		    regs->end[0] = mbs_offset1 != NULL ?
5810131543Stjr					mbs_offset1[d-string1] : 0;
5811131543Stjr		  else
5812131543Stjr		    regs->end[0] = csize1 + (mbs_offset2 != NULL ?
5813131543Stjr					     mbs_offset2[d-string2] : 0);
5814131543Stjr#else
5815126209Sache                  regs->end[0] = (MATCHING_IN_FIRST_STRING
5816126209Sache				  ? ((regoff_t) (d - string1))
5817126209Sache			          : ((regoff_t) (d - string2 + size1)));
5818131543Stjr#endif /* MBS_SUPPORT */
5819218Sconklin                }
5820126209Sache
5821218Sconklin              /* Go through the first `min (num_regs, regs->num_regs)'
5822218Sconklin                 registers, since that is all we initialized.  */
5823126209Sache	      for (mcnt = 1; (unsigned) mcnt < MIN (num_regs, regs->num_regs);
5824126209Sache		   mcnt++)
5825218Sconklin		{
5826218Sconklin                  if (REG_UNSET (regstart[mcnt]) || REG_UNSET (regend[mcnt]))
5827218Sconklin                    regs->start[mcnt] = regs->end[mcnt] = -1;
5828218Sconklin                  else
5829218Sconklin                    {
5830126209Sache		      regs->start[mcnt]
5831126209Sache			= (regoff_t) POINTER_TO_OFFSET (regstart[mcnt]);
5832126209Sache                      regs->end[mcnt]
5833126209Sache			= (regoff_t) POINTER_TO_OFFSET (regend[mcnt]);
5834218Sconklin                    }
5835218Sconklin		}
5836126209Sache
5837218Sconklin              /* If the regs structure we return has more elements than
5838218Sconklin                 were in the pattern, set the extra elements to -1.  If
5839218Sconklin                 we (re)allocated the registers, this is the case,
5840218Sconklin                 because we always allocate enough to have at least one
5841218Sconklin                 -1 at the end.  */
5842126209Sache              for (mcnt = num_regs; (unsigned) mcnt < regs->num_regs; mcnt++)
5843218Sconklin                regs->start[mcnt] = regs->end[mcnt] = -1;
5844218Sconklin	    } /* regs && !bufp->no_sub */
5845218Sconklin
5846218Sconklin          DEBUG_PRINT4 ("%u failure points pushed, %u popped (%u remain).\n",
5847218Sconklin                        nfailure_points_pushed, nfailure_points_popped,
5848218Sconklin                        nfailure_points_pushed - nfailure_points_popped);
5849218Sconklin          DEBUG_PRINT2 ("%u registers pushed.\n", num_regs_pushed);
5850218Sconklin
5851131543Stjr#ifdef MBS_SUPPORT
5852131543Stjr	  if (MATCHING_IN_FIRST_STRING)
5853131543Stjr	    mcnt = mbs_offset1 != NULL ? mbs_offset1[d-string1] : 0;
5854131543Stjr	  else
5855131543Stjr	    mcnt = (mbs_offset2 != NULL ? mbs_offset2[d-string2] : 0) +
5856131543Stjr			csize1;
5857131543Stjr          mcnt -= pos;
5858131543Stjr#else
5859126209Sache          mcnt = d - pos - (MATCHING_IN_FIRST_STRING
5860126209Sache			    ? string1
5861218Sconklin			    : string2 - size1);
5862131543Stjr#endif /* MBS_SUPPORT */
5863218Sconklin
5864218Sconklin          DEBUG_PRINT2 ("Returning %d from re_match_2.\n", mcnt);
5865218Sconklin
5866126209Sache          FREE_VARIABLES ();
5867218Sconklin          return mcnt;
5868218Sconklin        }
5869218Sconklin
5870218Sconklin      /* Otherwise match next pattern command.  */
5871126209Sache      switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
5872218Sconklin	{
5873218Sconklin        /* Ignore these.  Used to ignore the n of succeed_n's which
5874218Sconklin           currently have n == 0.  */
5875218Sconklin        case no_op:
5876218Sconklin          DEBUG_PRINT1 ("EXECUTING no_op.\n");
5877218Sconklin          break;
5878218Sconklin
5879126209Sache	case succeed:
5880126209Sache          DEBUG_PRINT1 ("EXECUTING succeed.\n");
5881126209Sache	  goto succeed_label;
5882218Sconklin
5883218Sconklin        /* Match the next n pattern characters exactly.  The following
5884218Sconklin           byte in the pattern defines n, and the n bytes after that
5885218Sconklin           are the characters to match.  */
5886218Sconklin	case exactn:
5887131543Stjr#ifdef MBS_SUPPORT
5888131543Stjr	case exactn_bin:
5889131543Stjr#endif
5890218Sconklin	  mcnt = *p++;
5891218Sconklin          DEBUG_PRINT2 ("EXECUTING exactn %d.\n", mcnt);
5892218Sconklin
5893218Sconklin          /* This is written out as an if-else so we don't waste time
5894218Sconklin             testing `translate' inside the loop.  */
5895218Sconklin          if (translate)
5896218Sconklin	    {
5897218Sconklin	      do
5898218Sconklin		{
5899218Sconklin		  PREFETCH ();
5900131543Stjr#ifdef MBS_SUPPORT
5901131543Stjr		  if (*d <= 0xff)
5902131543Stjr		    {
5903131543Stjr		      if ((US_CHAR_TYPE) translate[(unsigned char) *d++]
5904131543Stjr			  != (US_CHAR_TYPE) *p++)
5905131543Stjr			goto fail;
5906131543Stjr		    }
5907131543Stjr		  else
5908131543Stjr		    {
5909131543Stjr		      if (*d++ != (CHAR_TYPE) *p++)
5910131543Stjr			goto fail;
5911131543Stjr		    }
5912131543Stjr#else
5913131543Stjr		  if ((US_CHAR_TYPE) translate[(unsigned char) *d++]
5914131543Stjr		      != (US_CHAR_TYPE) *p++)
5915218Sconklin                    goto fail;
5916131543Stjr#endif /* MBS_SUPPORT */
5917218Sconklin		}
5918218Sconklin	      while (--mcnt);
5919218Sconklin	    }
5920218Sconklin	  else
5921218Sconklin	    {
5922218Sconklin	      do
5923218Sconklin		{
5924218Sconklin		  PREFETCH ();
5925131543Stjr		  if (*d++ != (CHAR_TYPE) *p++) goto fail;
5926218Sconklin		}
5927218Sconklin	      while (--mcnt);
5928218Sconklin	    }
5929218Sconklin	  SET_REGS_MATCHED ();
5930218Sconklin          break;
5931218Sconklin
5932218Sconklin
5933218Sconklin        /* Match any character except possibly a newline or a null.  */
5934218Sconklin	case anychar:
5935218Sconklin          DEBUG_PRINT1 ("EXECUTING anychar.\n");
5936218Sconklin
5937218Sconklin          PREFETCH ();
5938218Sconklin
5939218Sconklin          if ((!(bufp->syntax & RE_DOT_NEWLINE) && TRANSLATE (*d) == '\n')
5940218Sconklin              || (bufp->syntax & RE_DOT_NOT_NULL && TRANSLATE (*d) == '\000'))
5941218Sconklin	    goto fail;
5942218Sconklin
5943218Sconklin          SET_REGS_MATCHED ();
5944131543Stjr          DEBUG_PRINT2 ("  Matched `%ld'.\n", (long int) *d);
5945218Sconklin          d++;
5946218Sconklin	  break;
5947218Sconklin
5948218Sconklin
5949218Sconklin	case charset:
5950218Sconklin	case charset_not:
5951218Sconklin	  {
5952131543Stjr	    register US_CHAR_TYPE c;
5953131543Stjr#ifdef MBS_SUPPORT
5954131543Stjr	    unsigned int i, char_class_length, coll_symbol_length,
5955131543Stjr              equiv_class_length, ranges_length, chars_length, length;
5956131543Stjr	    CHAR_TYPE *workp, *workp2, *charset_top;
5957131543Stjr#define WORK_BUFFER_SIZE 128
5958131543Stjr            CHAR_TYPE str_buf[WORK_BUFFER_SIZE];
5959131543Stjr# ifdef _LIBC
5960131543Stjr	    uint32_t nrules;
5961131543Stjr# endif /* _LIBC */
5962131543Stjr#endif /* MBS_SUPPORT */
5963218Sconklin	    boolean not = (re_opcode_t) *(p - 1) == charset_not;
5964218Sconklin
5965218Sconklin            DEBUG_PRINT2 ("EXECUTING charset%s.\n", not ? "_not" : "");
5966218Sconklin	    PREFETCH ();
5967218Sconklin	    c = TRANSLATE (*d); /* The character to match.  */
5968131543Stjr#ifdef MBS_SUPPORT
5969131543Stjr# ifdef _LIBC
5970131543Stjr	    nrules = _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
5971131543Stjr# endif /* _LIBC */
5972131543Stjr	    charset_top = p - 1;
5973131543Stjr	    char_class_length = *p++;
5974131543Stjr	    coll_symbol_length = *p++;
5975131543Stjr	    equiv_class_length = *p++;
5976131543Stjr	    ranges_length = *p++;
5977131543Stjr	    chars_length = *p++;
5978131543Stjr	    /* p points charset[6], so the address of the next instruction
5979131543Stjr	       (charset[l+m+n+2o+k+p']) equals p[l+m+n+2*o+p'],
5980131543Stjr	       where l=length of char_classes, m=length of collating_symbol,
5981131543Stjr	       n=equivalence_class, o=length of char_range,
5982131543Stjr	       p'=length of character.  */
5983131543Stjr	    workp = p;
5984131543Stjr	    /* Update p to indicate the next instruction.  */
5985131543Stjr	    p += char_class_length + coll_symbol_length+ equiv_class_length +
5986131543Stjr              2*ranges_length + chars_length;
5987218Sconklin
5988131543Stjr            /* match with char_class?  */
5989131543Stjr	    for (i = 0; i < char_class_length ; i += CHAR_CLASS_SIZE)
5990131543Stjr	      {
5991131543Stjr		wctype_t wctype;
5992131543Stjr		uintptr_t alignedp = ((uintptr_t)workp
5993131543Stjr				      + __alignof__(wctype_t) - 1)
5994131543Stjr		  		      & ~(uintptr_t)(__alignof__(wctype_t) - 1);
5995131543Stjr		wctype = *((wctype_t*)alignedp);
5996131543Stjr		workp += CHAR_CLASS_SIZE;
5997131543Stjr		if (iswctype((wint_t)c, wctype))
5998131543Stjr		  goto char_set_matched;
5999131543Stjr	      }
6000131543Stjr
6001131543Stjr            /* match with collating_symbol?  */
6002131543Stjr# ifdef _LIBC
6003131543Stjr	    if (nrules != 0)
6004131543Stjr	      {
6005131543Stjr		const unsigned char *extra = (const unsigned char *)
6006131543Stjr		  _NL_CURRENT (LC_COLLATE, _NL_COLLATE_SYMB_EXTRAMB);
6007131543Stjr
6008131543Stjr		for (workp2 = workp + coll_symbol_length ; workp < workp2 ;
6009131543Stjr		     workp++)
6010131543Stjr		  {
6011131543Stjr		    int32_t *wextra;
6012131543Stjr		    wextra = (int32_t*)(extra + *workp++);
6013131543Stjr		    for (i = 0; i < *wextra; ++i)
6014131543Stjr		      if (TRANSLATE(d[i]) != wextra[1 + i])
6015131543Stjr			break;
6016131543Stjr
6017131543Stjr		    if (i == *wextra)
6018131543Stjr		      {
6019131543Stjr			/* Update d, however d will be incremented at
6020131543Stjr			   char_set_matched:, we decrement d here.  */
6021131543Stjr			d += i - 1;
6022131543Stjr			goto char_set_matched;
6023131543Stjr		      }
6024131543Stjr		  }
6025131543Stjr	      }
6026131543Stjr	    else /* (nrules == 0) */
6027131543Stjr# endif
6028131543Stjr	      /* If we can't look up collation data, we use wcscoll
6029131543Stjr		 instead.  */
6030131543Stjr	      {
6031131543Stjr		for (workp2 = workp + coll_symbol_length ; workp < workp2 ;)
6032131543Stjr		  {
6033131543Stjr		    const CHAR_TYPE *backup_d = d, *backup_dend = dend;
6034131543Stjr		    length = wcslen(workp);
6035131543Stjr
6036131543Stjr		    /* If wcscoll(the collating symbol, whole string) > 0,
6037131543Stjr		       any substring of the string never match with the
6038131543Stjr		       collating symbol.  */
6039131543Stjr		    if (wcscoll(workp, d) > 0)
6040131543Stjr		      {
6041131543Stjr			workp += length + 1;
6042131543Stjr			continue;
6043131543Stjr		      }
6044131543Stjr
6045131543Stjr		    /* First, we compare the collating symbol with
6046131543Stjr		       the first character of the string.
6047131543Stjr		       If it don't match, we add the next character to
6048131543Stjr		       the compare buffer in turn.  */
6049131543Stjr		    for (i = 0 ; i < WORK_BUFFER_SIZE-1 ; i++, d++)
6050131543Stjr		      {
6051131543Stjr			int match;
6052131543Stjr			if (d == dend)
6053131543Stjr			  {
6054131543Stjr			    if (dend == end_match_2)
6055131543Stjr			      break;
6056131543Stjr			    d = string2;
6057131543Stjr			    dend = end_match_2;
6058131543Stjr			  }
6059131543Stjr
6060131543Stjr			/* add next character to the compare buffer.  */
6061131543Stjr			str_buf[i] = TRANSLATE(*d);
6062131543Stjr			str_buf[i+1] = '\0';
6063131543Stjr
6064131543Stjr			match = wcscoll(workp, str_buf);
6065131543Stjr			if (match == 0)
6066131543Stjr			  goto char_set_matched;
6067131543Stjr
6068131543Stjr			if (match < 0)
6069131543Stjr			  /* (str_buf > workp) indicate (str_buf + X > workp),
6070131543Stjr			     because for all X (str_buf + X > str_buf).
6071131543Stjr			     So we don't need continue this loop.  */
6072131543Stjr			  break;
6073131543Stjr
6074131543Stjr			/* Otherwise(str_buf < workp),
6075131543Stjr			   (str_buf+next_character) may equals (workp).
6076131543Stjr			   So we continue this loop.  */
6077131543Stjr		      }
6078131543Stjr		    /* not matched */
6079131543Stjr		    d = backup_d;
6080131543Stjr		    dend = backup_dend;
6081131543Stjr		    workp += length + 1;
6082131543Stjr		  }
6083131543Stjr              }
6084131543Stjr            /* match with equivalence_class?  */
6085131543Stjr# ifdef _LIBC
6086131543Stjr	    if (nrules != 0)
6087131543Stjr	      {
6088131543Stjr                const CHAR_TYPE *backup_d = d, *backup_dend = dend;
6089131543Stjr		/* Try to match the equivalence class against
6090131543Stjr		   those known to the collate implementation.  */
6091131543Stjr		const int32_t *table;
6092131543Stjr		const int32_t *weights;
6093131543Stjr		const int32_t *extra;
6094131543Stjr		const int32_t *indirect;
6095131543Stjr		int32_t idx, idx2;
6096131543Stjr		wint_t *cp;
6097131543Stjr		size_t len;
6098131543Stjr
6099131543Stjr		/* This #include defines a local function!  */
6100131543Stjr#  include <locale/weightwc.h>
6101131543Stjr
6102131543Stjr		table = (const int32_t *)
6103131543Stjr		  _NL_CURRENT (LC_COLLATE, _NL_COLLATE_TABLEWC);
6104131543Stjr		weights = (const wint_t *)
6105131543Stjr		  _NL_CURRENT (LC_COLLATE, _NL_COLLATE_WEIGHTWC);
6106131543Stjr		extra = (const wint_t *)
6107131543Stjr		  _NL_CURRENT (LC_COLLATE, _NL_COLLATE_EXTRAWC);
6108131543Stjr		indirect = (const int32_t *)
6109131543Stjr		  _NL_CURRENT (LC_COLLATE, _NL_COLLATE_INDIRECTWC);
6110131543Stjr
6111131543Stjr		/* Write 1 collating element to str_buf, and
6112131543Stjr		   get its index.  */
6113131543Stjr		idx2 = 0;
6114131543Stjr
6115131543Stjr		for (i = 0 ; idx2 == 0 && i < WORK_BUFFER_SIZE - 1; i++)
6116131543Stjr		  {
6117131543Stjr		    cp = (wint_t*)str_buf;
6118131543Stjr		    if (d == dend)
6119131543Stjr		      {
6120131543Stjr			if (dend == end_match_2)
6121131543Stjr			  break;
6122131543Stjr			d = string2;
6123131543Stjr			dend = end_match_2;
6124131543Stjr		      }
6125131543Stjr		    str_buf[i] = TRANSLATE(*(d+i));
6126131543Stjr		    str_buf[i+1] = '\0'; /* sentinel */
6127131543Stjr		    idx2 = findidx ((const wint_t**)&cp);
6128131543Stjr		  }
6129131543Stjr
6130131543Stjr		/* Update d, however d will be incremented at
6131131543Stjr		   char_set_matched:, we decrement d here.  */
6132131543Stjr		d = backup_d + ((wchar_t*)cp - (wchar_t*)str_buf - 1);
6133131543Stjr		if (d >= dend)
6134131543Stjr		  {
6135131543Stjr		    if (dend == end_match_2)
6136131543Stjr			d = dend;
6137131543Stjr		    else
6138131543Stjr		      {
6139131543Stjr			d = string2;
6140131543Stjr			dend = end_match_2;
6141131543Stjr		      }
6142131543Stjr		  }
6143131543Stjr
6144131543Stjr		len = weights[idx2];
6145131543Stjr
6146131543Stjr		for (workp2 = workp + equiv_class_length ; workp < workp2 ;
6147131543Stjr		     workp++)
6148131543Stjr		  {
6149131543Stjr		    idx = (int32_t)*workp;
6150131543Stjr		    /* We already checked idx != 0 in regex_compile. */
6151131543Stjr
6152131543Stjr		    if (idx2 != 0 && len == weights[idx])
6153131543Stjr		      {
6154131543Stjr			int cnt = 0;
6155131543Stjr			while (cnt < len && (weights[idx + 1 + cnt]
6156131543Stjr					     == weights[idx2 + 1 + cnt]))
6157131543Stjr			  ++cnt;
6158131543Stjr
6159131543Stjr			if (cnt == len)
6160131543Stjr			  goto char_set_matched;
6161131543Stjr		      }
6162131543Stjr		  }
6163131543Stjr		/* not matched */
6164131543Stjr                d = backup_d;
6165131543Stjr                dend = backup_dend;
6166131543Stjr	      }
6167131543Stjr	    else /* (nrules == 0) */
6168131543Stjr# endif
6169131543Stjr	      /* If we can't look up collation data, we use wcscoll
6170131543Stjr		 instead.  */
6171131543Stjr	      {
6172131543Stjr		for (workp2 = workp + equiv_class_length ; workp < workp2 ;)
6173131543Stjr		  {
6174131543Stjr		    const CHAR_TYPE *backup_d = d, *backup_dend = dend;
6175131543Stjr		    length = wcslen(workp);
6176131543Stjr
6177131543Stjr		    /* If wcscoll(the collating symbol, whole string) > 0,
6178131543Stjr		       any substring of the string never match with the
6179131543Stjr		       collating symbol.  */
6180131543Stjr		    if (wcscoll(workp, d) > 0)
6181131543Stjr		      {
6182131543Stjr			workp += length + 1;
6183131543Stjr			break;
6184131543Stjr		      }
6185131543Stjr
6186131543Stjr		    /* First, we compare the equivalence class with
6187131543Stjr		       the first character of the string.
6188131543Stjr		       If it don't match, we add the next character to
6189131543Stjr		       the compare buffer in turn.  */
6190131543Stjr		    for (i = 0 ; i < WORK_BUFFER_SIZE - 1 ; i++, d++)
6191131543Stjr		      {
6192131543Stjr			int match;
6193131543Stjr			if (d == dend)
6194131543Stjr			  {
6195131543Stjr			    if (dend == end_match_2)
6196131543Stjr			      break;
6197131543Stjr			    d = string2;
6198131543Stjr			    dend = end_match_2;
6199131543Stjr			  }
6200131543Stjr
6201131543Stjr			/* add next character to the compare buffer.  */
6202131543Stjr			str_buf[i] = TRANSLATE(*d);
6203131543Stjr			str_buf[i+1] = '\0';
6204131543Stjr
6205131543Stjr			match = wcscoll(workp, str_buf);
6206131543Stjr
6207131543Stjr			if (match == 0)
6208131543Stjr			  goto char_set_matched;
6209131543Stjr
6210131543Stjr			if (match < 0)
6211131543Stjr			/* (str_buf > workp) indicate (str_buf + X > workp),
6212131543Stjr			   because for all X (str_buf + X > str_buf).
6213131543Stjr			   So we don't need continue this loop.  */
6214131543Stjr			  break;
6215131543Stjr
6216131543Stjr			/* Otherwise(str_buf < workp),
6217131543Stjr			   (str_buf+next_character) may equals (workp).
6218131543Stjr			   So we continue this loop.  */
6219131543Stjr		      }
6220131543Stjr		    /* not matched */
6221131543Stjr		    d = backup_d;
6222131543Stjr		    dend = backup_dend;
6223131543Stjr		    workp += length + 1;
6224131543Stjr		  }
6225131543Stjr	      }
6226131543Stjr
6227131543Stjr            /* match with char_range?  */
6228131543Stjr#ifdef _LIBC
6229131543Stjr	    if (nrules != 0)
6230131543Stjr	      {
6231131543Stjr		uint32_t collseqval;
6232131543Stjr		const char *collseq = (const char *)
6233131543Stjr		  _NL_CURRENT(LC_COLLATE, _NL_COLLATE_COLLSEQWC);
6234131543Stjr
6235131543Stjr		collseqval = collseq_table_lookup (collseq, c);
6236131543Stjr
6237131543Stjr		for (; workp < p - chars_length ;)
6238131543Stjr		  {
6239131543Stjr		    uint32_t start_val, end_val;
6240131543Stjr
6241131543Stjr		    /* We already compute the collation sequence value
6242131543Stjr		       of the characters (or collating symbols).  */
6243131543Stjr		    start_val = (uint32_t) *workp++; /* range_start */
6244131543Stjr		    end_val = (uint32_t) *workp++; /* range_end */
6245131543Stjr
6246131543Stjr		    if (start_val <= collseqval && collseqval <= end_val)
6247131543Stjr		      goto char_set_matched;
6248131543Stjr		  }
6249131543Stjr	      }
6250131543Stjr	    else
6251131543Stjr#endif
6252131543Stjr	      {
6253131543Stjr		/* We set range_start_char at str_buf[0], range_end_char
6254131543Stjr		   at str_buf[4], and compared char at str_buf[2].  */
6255131543Stjr		str_buf[1] = 0;
6256131543Stjr		str_buf[2] = c;
6257131543Stjr		str_buf[3] = 0;
6258131543Stjr		str_buf[5] = 0;
6259131543Stjr		for (; workp < p - chars_length ;)
6260131543Stjr		  {
6261131543Stjr		    wchar_t *range_start_char, *range_end_char;
6262131543Stjr
6263131543Stjr		    /* match if (range_start_char <= c <= range_end_char).  */
6264131543Stjr
6265131543Stjr		    /* If range_start(or end) < 0, we assume -range_start(end)
6266131543Stjr		       is the offset of the collating symbol which is specified
6267131543Stjr		       as the character of the range start(end).  */
6268131543Stjr
6269131543Stjr		    /* range_start */
6270131543Stjr		    if (*workp < 0)
6271131543Stjr		      range_start_char = charset_top - (*workp++);
6272131543Stjr		    else
6273131543Stjr		      {
6274131543Stjr			str_buf[0] = *workp++;
6275131543Stjr			range_start_char = str_buf;
6276131543Stjr		      }
6277131543Stjr
6278131543Stjr		    /* range_end */
6279131543Stjr		    if (*workp < 0)
6280131543Stjr		      range_end_char = charset_top - (*workp++);
6281131543Stjr		    else
6282131543Stjr		      {
6283131543Stjr			str_buf[4] = *workp++;
6284131543Stjr			range_end_char = str_buf + 4;
6285131543Stjr		      }
6286131543Stjr
6287131543Stjr		    if (wcscoll(range_start_char, str_buf+2) <= 0 &&
6288131543Stjr			wcscoll(str_buf+2, range_end_char) <= 0)
6289131543Stjr
6290131543Stjr		      goto char_set_matched;
6291131543Stjr		  }
6292131543Stjr	      }
6293131543Stjr
6294131543Stjr            /* match with char?  */
6295131543Stjr	    for (; workp < p ; workp++)
6296131543Stjr	      if (c == *workp)
6297131543Stjr		goto char_set_matched;
6298131543Stjr
6299131543Stjr	    not = !not;
6300131543Stjr
6301131543Stjr	  char_set_matched:
6302131543Stjr	    if (not) goto fail;
6303131543Stjr#else
6304218Sconklin            /* Cast to `unsigned' instead of `unsigned char' in case the
6305218Sconklin               bit list is a full 32 bytes long.  */
6306218Sconklin	    if (c < (unsigned) (*p * BYTEWIDTH)
6307218Sconklin		&& p[1 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
6308218Sconklin	      not = !not;
6309218Sconklin
6310218Sconklin	    p += 1 + *p;
6311218Sconklin
6312218Sconklin	    if (!not) goto fail;
6313131543Stjr#undef WORK_BUFFER_SIZE
6314131543Stjr#endif /* MBS_SUPPORT */
6315218Sconklin	    SET_REGS_MATCHED ();
6316218Sconklin            d++;
6317218Sconklin	    break;
6318218Sconklin	  }
6319218Sconklin
6320218Sconklin
6321218Sconklin        /* The beginning of a group is represented by start_memory.
6322218Sconklin           The arguments are the register number in the next byte, and the
6323218Sconklin           number of groups inner to this one in the next.  The text
6324218Sconklin           matched within the group is recorded (in the internal
6325218Sconklin           registers data structure) under the register number.  */
6326218Sconklin        case start_memory:
6327131543Stjr	  DEBUG_PRINT3 ("EXECUTING start_memory %ld (%ld):\n",
6328131543Stjr			(long int) *p, (long int) p[1]);
6329218Sconklin
6330218Sconklin          /* Find out if this group can match the empty string.  */
6331218Sconklin	  p1 = p;		/* To send to group_match_null_string_p.  */
6332126209Sache
6333218Sconklin          if (REG_MATCH_NULL_STRING_P (reg_info[*p]) == MATCH_NULL_UNSET_VALUE)
6334126209Sache            REG_MATCH_NULL_STRING_P (reg_info[*p])
6335218Sconklin              = group_match_null_string_p (&p1, pend, reg_info);
6336218Sconklin
6337218Sconklin          /* Save the position in the string where we were the last time
6338218Sconklin             we were at this open-group operator in case the group is
6339218Sconklin             operated upon by a repetition operator, e.g., with `(a*)*b'
6340218Sconklin             against `ab'; then we want to ignore where we are now in
6341218Sconklin             the string in case this attempt to match fails.  */
6342218Sconklin          old_regstart[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
6343218Sconklin                             ? REG_UNSET (regstart[*p]) ? d : regstart[*p]
6344218Sconklin                             : regstart[*p];
6345126209Sache	  DEBUG_PRINT2 ("  old_regstart: %d\n",
6346218Sconklin			 POINTER_TO_OFFSET (old_regstart[*p]));
6347218Sconklin
6348218Sconklin          regstart[*p] = d;
6349218Sconklin	  DEBUG_PRINT2 ("  regstart: %d\n", POINTER_TO_OFFSET (regstart[*p]));
6350218Sconklin
6351218Sconklin          IS_ACTIVE (reg_info[*p]) = 1;
6352218Sconklin          MATCHED_SOMETHING (reg_info[*p]) = 0;
6353126209Sache
6354126209Sache	  /* Clear this whenever we change the register activity status.  */
6355126209Sache	  set_regs_matched_done = 0;
6356126209Sache
6357218Sconklin          /* This is the new highest active register.  */
6358218Sconklin          highest_active_reg = *p;
6359126209Sache
6360218Sconklin          /* If nothing was active before, this is the new lowest active
6361218Sconklin             register.  */
6362218Sconklin          if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
6363218Sconklin            lowest_active_reg = *p;
6364218Sconklin
6365218Sconklin          /* Move past the register number and inner group count.  */
6366218Sconklin          p += 2;
6367126209Sache	  just_past_start_mem = p;
6368126209Sache
6369218Sconklin          break;
6370218Sconklin
6371218Sconklin
6372218Sconklin        /* The stop_memory opcode represents the end of a group.  Its
6373218Sconklin           arguments are the same as start_memory's: the register
6374218Sconklin           number, and the number of inner groups.  */
6375218Sconklin	case stop_memory:
6376131543Stjr	  DEBUG_PRINT3 ("EXECUTING stop_memory %ld (%ld):\n",
6377131543Stjr			(long int) *p, (long int) p[1]);
6378126209Sache
6379218Sconklin          /* We need to save the string position the last time we were at
6380218Sconklin             this close-group operator in case the group is operated
6381218Sconklin             upon by a repetition operator, e.g., with `((a*)*(b*)*)*'
6382218Sconklin             against `aba'; then we want to ignore where we are now in
6383218Sconklin             the string in case this attempt to match fails.  */
6384218Sconklin          old_regend[*p] = REG_MATCH_NULL_STRING_P (reg_info[*p])
6385218Sconklin                           ? REG_UNSET (regend[*p]) ? d : regend[*p]
6386218Sconklin			   : regend[*p];
6387126209Sache	  DEBUG_PRINT2 ("      old_regend: %d\n",
6388218Sconklin			 POINTER_TO_OFFSET (old_regend[*p]));
6389218Sconklin
6390218Sconklin          regend[*p] = d;
6391218Sconklin	  DEBUG_PRINT2 ("      regend: %d\n", POINTER_TO_OFFSET (regend[*p]));
6392218Sconklin
6393218Sconklin          /* This register isn't active anymore.  */
6394218Sconklin          IS_ACTIVE (reg_info[*p]) = 0;
6395126209Sache
6396126209Sache	  /* Clear this whenever we change the register activity status.  */
6397126209Sache	  set_regs_matched_done = 0;
6398126209Sache
6399218Sconklin          /* If this was the only register active, nothing is active
6400218Sconklin             anymore.  */
6401218Sconklin          if (lowest_active_reg == highest_active_reg)
6402218Sconklin            {
6403218Sconklin              lowest_active_reg = NO_LOWEST_ACTIVE_REG;
6404218Sconklin              highest_active_reg = NO_HIGHEST_ACTIVE_REG;
6405218Sconklin            }
6406218Sconklin          else
6407218Sconklin            { /* We must scan for the new highest active register, since
6408218Sconklin                 it isn't necessarily one less than now: consider
6409218Sconklin                 (a(b)c(d(e)f)g).  When group 3 ends, after the f), the
6410218Sconklin                 new highest active register is 1.  */
6411131543Stjr              US_CHAR_TYPE r = *p - 1;
6412218Sconklin              while (r > 0 && !IS_ACTIVE (reg_info[r]))
6413218Sconklin                r--;
6414126209Sache
6415218Sconklin              /* If we end up at register zero, that means that we saved
6416218Sconklin                 the registers as the result of an `on_failure_jump', not
6417218Sconklin                 a `start_memory', and we jumped to past the innermost
6418218Sconklin                 `stop_memory'.  For example, in ((.)*) we save
6419218Sconklin                 registers 1 and 2 as a result of the *, but when we pop
6420218Sconklin                 back to the second ), we are at the stop_memory 1.
6421218Sconklin                 Thus, nothing is active.  */
6422218Sconklin	      if (r == 0)
6423218Sconklin                {
6424218Sconklin                  lowest_active_reg = NO_LOWEST_ACTIVE_REG;
6425218Sconklin                  highest_active_reg = NO_HIGHEST_ACTIVE_REG;
6426218Sconklin                }
6427218Sconklin              else
6428218Sconklin                highest_active_reg = r;
6429218Sconklin            }
6430126209Sache
6431218Sconklin          /* If just failed to match something this time around with a
6432218Sconklin             group that's operated on by a repetition operator, try to
6433218Sconklin             force exit from the ``loop'', and restore the register
6434218Sconklin             information for this group that we had before trying this
6435218Sconklin             last match.  */
6436218Sconklin          if ((!MATCHED_SOMETHING (reg_info[*p])
6437126209Sache               || just_past_start_mem == p - 1)
6438126209Sache	      && (p + 2) < pend)
6439218Sconklin            {
6440218Sconklin              boolean is_a_jump_n = false;
6441126209Sache
6442218Sconklin              p1 = p + 2;
6443218Sconklin              mcnt = 0;
6444218Sconklin              switch ((re_opcode_t) *p1++)
6445218Sconklin                {
6446218Sconklin                  case jump_n:
6447218Sconklin		    is_a_jump_n = true;
6448218Sconklin                  case pop_failure_jump:
6449218Sconklin		  case maybe_pop_jump:
6450218Sconklin		  case jump:
6451218Sconklin		  case dummy_failure_jump:
6452218Sconklin                    EXTRACT_NUMBER_AND_INCR (mcnt, p1);
6453218Sconklin		    if (is_a_jump_n)
6454131543Stjr		      p1 += OFFSET_ADDRESS_SIZE;
6455218Sconklin                    break;
6456126209Sache
6457218Sconklin                  default:
6458218Sconklin                    /* do nothing */ ;
6459218Sconklin                }
6460218Sconklin	      p1 += mcnt;
6461126209Sache
6462218Sconklin              /* If the next operation is a jump backwards in the pattern
6463218Sconklin	         to an on_failure_jump right before the start_memory
6464218Sconklin                 corresponding to this stop_memory, exit from the loop
6465218Sconklin                 by forcing a failure after pushing on the stack the
6466218Sconklin                 on_failure_jump's jump in the pattern, and d.  */
6467218Sconklin              if (mcnt < 0 && (re_opcode_t) *p1 == on_failure_jump
6468131543Stjr                  && (re_opcode_t) p1[1+OFFSET_ADDRESS_SIZE] == start_memory
6469131543Stjr		  && p1[2+OFFSET_ADDRESS_SIZE] == *p)
6470218Sconklin		{
6471218Sconklin                  /* If this group ever matched anything, then restore
6472218Sconklin                     what its registers were before trying this last
6473218Sconklin                     failed match, e.g., with `(a*)*b' against `ab' for
6474218Sconklin                     regstart[1], and, e.g., with `((a*)*(b*)*)*'
6475218Sconklin                     against `aba' for regend[3].
6476126209Sache
6477218Sconklin                     Also restore the registers for inner groups for,
6478218Sconklin                     e.g., `((a*)(b*))*' against `aba' (register 3 would
6479218Sconklin                     otherwise get trashed).  */
6480126209Sache
6481218Sconklin                  if (EVER_MATCHED_SOMETHING (reg_info[*p]))
6482218Sconklin		    {
6483126209Sache		      unsigned r;
6484126209Sache
6485218Sconklin                      EVER_MATCHED_SOMETHING (reg_info[*p]) = 0;
6486126209Sache
6487218Sconklin		      /* Restore this and inner groups' (if any) registers.  */
6488126209Sache                      for (r = *p; r < (unsigned) *p + (unsigned) *(p + 1);
6489126209Sache			   r++)
6490218Sconklin                        {
6491218Sconklin                          regstart[r] = old_regstart[r];
6492218Sconklin
6493218Sconklin                          /* xx why this test?  */
6494126209Sache                          if (old_regend[r] >= regstart[r])
6495218Sconklin                            regend[r] = old_regend[r];
6496126209Sache                        }
6497218Sconklin                    }
6498218Sconklin		  p1++;
6499218Sconklin                  EXTRACT_NUMBER_AND_INCR (mcnt, p1);
6500218Sconklin                  PUSH_FAILURE_POINT (p1 + mcnt, d, -2);
6501218Sconklin
6502218Sconklin                  goto fail;
6503218Sconklin                }
6504218Sconklin            }
6505126209Sache
6506218Sconklin          /* Move past the register number and the inner group count.  */
6507218Sconklin          p += 2;
6508218Sconklin          break;
6509218Sconklin
6510218Sconklin
6511218Sconklin	/* \<digit> has been turned into a `duplicate' command which is
6512218Sconklin           followed by the numeric value of <digit> as the register number.  */
6513218Sconklin        case duplicate:
6514218Sconklin	  {
6515131543Stjr	    register const CHAR_TYPE *d2, *dend2;
6516218Sconklin	    int regno = *p++;   /* Get which register to match against.  */
6517218Sconklin	    DEBUG_PRINT2 ("EXECUTING duplicate %d.\n", regno);
6518218Sconklin
6519218Sconklin	    /* Can't back reference a group which we've never matched.  */
6520218Sconklin            if (REG_UNSET (regstart[regno]) || REG_UNSET (regend[regno]))
6521218Sconklin              goto fail;
6522126209Sache
6523218Sconklin            /* Where in input to try to start matching.  */
6524218Sconklin            d2 = regstart[regno];
6525126209Sache
6526218Sconklin            /* Where to stop matching; if both the place to start and
6527218Sconklin               the place to stop matching are in the same string, then
6528218Sconklin               set to the place to stop, otherwise, for now have to use
6529218Sconklin               the end of the first string.  */
6530218Sconklin
6531126209Sache            dend2 = ((FIRST_STRING_P (regstart[regno])
6532218Sconklin		      == FIRST_STRING_P (regend[regno]))
6533218Sconklin		     ? regend[regno] : end_match_1);
6534218Sconklin	    for (;;)
6535218Sconklin	      {
6536218Sconklin		/* If necessary, advance to next segment in register
6537218Sconklin                   contents.  */
6538218Sconklin		while (d2 == dend2)
6539218Sconklin		  {
6540218Sconklin		    if (dend2 == end_match_2) break;
6541218Sconklin		    if (dend2 == regend[regno]) break;
6542218Sconklin
6543218Sconklin                    /* End of string1 => advance to string2. */
6544218Sconklin                    d2 = string2;
6545218Sconklin                    dend2 = regend[regno];
6546218Sconklin		  }
6547218Sconklin		/* At end of register contents => success */
6548218Sconklin		if (d2 == dend2) break;
6549218Sconklin
6550218Sconklin		/* If necessary, advance to next segment in data.  */
6551218Sconklin		PREFETCH ();
6552218Sconklin
6553218Sconklin		/* How many characters left in this segment to match.  */
6554218Sconklin		mcnt = dend - d;
6555126209Sache
6556218Sconklin		/* Want how many consecutive characters we can match in
6557218Sconklin                   one shot, so, if necessary, adjust the count.  */
6558218Sconklin                if (mcnt > dend2 - d2)
6559218Sconklin		  mcnt = dend2 - d2;
6560126209Sache
6561218Sconklin		/* Compare that many; failure if mismatch, else move
6562218Sconklin                   past them.  */
6563126209Sache		if (translate
6564126209Sache                    ? bcmp_translate (d, d2, mcnt, translate)
6565131543Stjr                    : memcmp (d, d2, mcnt*sizeof(US_CHAR_TYPE)))
6566218Sconklin		  goto fail;
6567218Sconklin		d += mcnt, d2 += mcnt;
6568126209Sache
6569126209Sache		/* Do this because we've match some characters.  */
6570126209Sache		SET_REGS_MATCHED ();
6571218Sconklin	      }
6572218Sconklin	  }
6573218Sconklin	  break;
6574218Sconklin
6575218Sconklin
6576218Sconklin        /* begline matches the empty string at the beginning of the string
6577218Sconklin           (unless `not_bol' is set in `bufp'), and, if
6578218Sconklin           `newline_anchor' is set, after newlines.  */
6579218Sconklin	case begline:
6580218Sconklin          DEBUG_PRINT1 ("EXECUTING begline.\n");
6581126209Sache
6582218Sconklin          if (AT_STRINGS_BEG (d))
6583218Sconklin            {
6584218Sconklin              if (!bufp->not_bol) break;
6585218Sconklin            }
6586218Sconklin          else if (d[-1] == '\n' && bufp->newline_anchor)
6587218Sconklin            {
6588218Sconklin              break;
6589218Sconklin            }
6590218Sconklin          /* In all other cases, we fail.  */
6591218Sconklin          goto fail;
6592218Sconklin
6593218Sconklin
6594218Sconklin        /* endline is the dual of begline.  */
6595218Sconklin	case endline:
6596218Sconklin          DEBUG_PRINT1 ("EXECUTING endline.\n");
6597218Sconklin
6598218Sconklin          if (AT_STRINGS_END (d))
6599218Sconklin            {
6600218Sconklin              if (!bufp->not_eol) break;
6601218Sconklin            }
6602126209Sache
6603218Sconklin          /* We have to ``prefetch'' the next character.  */
6604218Sconklin          else if ((d == end1 ? *string2 : *d) == '\n'
6605218Sconklin                   && bufp->newline_anchor)
6606218Sconklin            {
6607218Sconklin              break;
6608218Sconklin            }
6609218Sconklin          goto fail;
6610218Sconklin
6611218Sconklin
6612218Sconklin	/* Match at the very beginning of the data.  */
6613218Sconklin        case begbuf:
6614218Sconklin          DEBUG_PRINT1 ("EXECUTING begbuf.\n");
6615218Sconklin          if (AT_STRINGS_BEG (d))
6616218Sconklin            break;
6617218Sconklin          goto fail;
6618218Sconklin
6619218Sconklin
6620218Sconklin	/* Match at the very end of the data.  */
6621218Sconklin        case endbuf:
6622218Sconklin          DEBUG_PRINT1 ("EXECUTING endbuf.\n");
6623218Sconklin	  if (AT_STRINGS_END (d))
6624218Sconklin	    break;
6625218Sconklin          goto fail;
6626218Sconklin
6627218Sconklin
6628218Sconklin        /* on_failure_keep_string_jump is used to optimize `.*\n'.  It
6629218Sconklin           pushes NULL as the value for the string on the stack.  Then
6630218Sconklin           `pop_failure_point' will keep the current value for the
6631218Sconklin           string, instead of restoring it.  To see why, consider
6632218Sconklin           matching `foo\nbar' against `.*\n'.  The .* matches the foo;
6633218Sconklin           then the . fails against the \n.  But the next thing we want
6634218Sconklin           to do is match the \n against the \n; if we restored the
6635218Sconklin           string value, we would be back at the foo.
6636126209Sache
6637218Sconklin           Because this is used only in specific cases, we don't need to
6638218Sconklin           check all the things that `on_failure_jump' does, to make
6639218Sconklin           sure the right things get saved on the stack.  Hence we don't
6640218Sconklin           share its code.  The only reason to push anything on the
6641218Sconklin           stack at all is that otherwise we would have to change
6642218Sconklin           `anychar's code to do something besides goto fail in this
6643218Sconklin           case; that seems worse than this.  */
6644218Sconklin        case on_failure_keep_string_jump:
6645218Sconklin          DEBUG_PRINT1 ("EXECUTING on_failure_keep_string_jump");
6646126209Sache
6647218Sconklin          EXTRACT_NUMBER_AND_INCR (mcnt, p);
6648126209Sache#ifdef _LIBC
6649126209Sache          DEBUG_PRINT3 (" %d (to %p):\n", mcnt, p + mcnt);
6650126209Sache#else
6651218Sconklin          DEBUG_PRINT3 (" %d (to 0x%x):\n", mcnt, p + mcnt);
6652126209Sache#endif
6653218Sconklin
6654218Sconklin          PUSH_FAILURE_POINT (p + mcnt, NULL, -2);
6655218Sconklin          break;
6656218Sconklin
6657218Sconklin
6658218Sconklin	/* Uses of on_failure_jump:
6659126209Sache
6660218Sconklin           Each alternative starts with an on_failure_jump that points
6661218Sconklin           to the beginning of the next alternative.  Each alternative
6662218Sconklin           except the last ends with a jump that in effect jumps past
6663218Sconklin           the rest of the alternatives.  (They really jump to the
6664218Sconklin           ending jump of the following alternative, because tensioning
6665218Sconklin           these jumps is a hassle.)
6666218Sconklin
6667218Sconklin           Repeats start with an on_failure_jump that points past both
6668218Sconklin           the repetition text and either the following jump or
6669218Sconklin           pop_failure_jump back to this on_failure_jump.  */
6670218Sconklin	case on_failure_jump:
6671218Sconklin        on_failure:
6672218Sconklin          DEBUG_PRINT1 ("EXECUTING on_failure_jump");
6673218Sconklin
6674218Sconklin          EXTRACT_NUMBER_AND_INCR (mcnt, p);
6675126209Sache#ifdef _LIBC
6676126209Sache          DEBUG_PRINT3 (" %d (to %p)", mcnt, p + mcnt);
6677126209Sache#else
6678218Sconklin          DEBUG_PRINT3 (" %d (to 0x%x)", mcnt, p + mcnt);
6679126209Sache#endif
6680218Sconklin
6681218Sconklin          /* If this on_failure_jump comes right before a group (i.e.,
6682218Sconklin             the original * applied to a group), save the information
6683218Sconklin             for that group and all inner ones, so that if we fail back
6684218Sconklin             to this point, the group's information will be correct.
6685218Sconklin             For example, in \(a*\)*\1, we need the preceding group,
6686126209Sache             and in \(zz\(a*\)b*\)\2, we need the inner group.  */
6687218Sconklin
6688218Sconklin          /* We can't use `p' to check ahead because we push
6689218Sconklin             a failure point to `p + mcnt' after we do this.  */
6690218Sconklin          p1 = p;
6691218Sconklin
6692218Sconklin          /* We need to skip no_op's before we look for the
6693218Sconklin             start_memory in case this on_failure_jump is happening as
6694218Sconklin             the result of a completed succeed_n, as in \(a\)\{1,3\}b\1
6695218Sconklin             against aba.  */
6696218Sconklin          while (p1 < pend && (re_opcode_t) *p1 == no_op)
6697218Sconklin            p1++;
6698218Sconklin
6699218Sconklin          if (p1 < pend && (re_opcode_t) *p1 == start_memory)
6700218Sconklin            {
6701218Sconklin              /* We have a new highest active register now.  This will
6702218Sconklin                 get reset at the start_memory we are about to get to,
6703218Sconklin                 but we will have saved all the registers relevant to
6704218Sconklin                 this repetition op, as described above.  */
6705218Sconklin              highest_active_reg = *(p1 + 1) + *(p1 + 2);
6706218Sconklin              if (lowest_active_reg == NO_LOWEST_ACTIVE_REG)
6707218Sconklin                lowest_active_reg = *(p1 + 1);
6708218Sconklin            }
6709218Sconklin
6710218Sconklin          DEBUG_PRINT1 (":\n");
6711218Sconklin          PUSH_FAILURE_POINT (p + mcnt, d, -2);
6712218Sconklin          break;
6713218Sconklin
6714218Sconklin
6715218Sconklin        /* A smart repeat ends with `maybe_pop_jump'.
6716218Sconklin	   We change it to either `pop_failure_jump' or `jump'.  */
6717218Sconklin        case maybe_pop_jump:
6718218Sconklin          EXTRACT_NUMBER_AND_INCR (mcnt, p);
6719218Sconklin          DEBUG_PRINT2 ("EXECUTING maybe_pop_jump %d.\n", mcnt);
6720218Sconklin          {
6721131543Stjr	    register US_CHAR_TYPE *p2 = p;
6722218Sconklin
6723218Sconklin            /* Compare the beginning of the repeat with what in the
6724218Sconklin               pattern follows its end. If we can establish that there
6725218Sconklin               is nothing that they would both match, i.e., that we
6726218Sconklin               would have to backtrack because of (as in, e.g., `a*a')
6727218Sconklin               then we can change to pop_failure_jump, because we'll
6728218Sconklin               never have to backtrack.
6729126209Sache
6730218Sconklin               This is not true in the case of alternatives: in
6731218Sconklin               `(a|ab)*' we do need to backtrack to the `ab' alternative
6732218Sconklin               (e.g., if the string was `ab').  But instead of trying to
6733218Sconklin               detect that here, the alternative has put on a dummy
6734218Sconklin               failure point which is what we will end up popping.  */
6735218Sconklin
6736126209Sache	    /* Skip over open/close-group commands.
6737126209Sache	       If what follows this loop is a ...+ construct,
6738126209Sache	       look at what begins its body, since we will have to
6739126209Sache	       match at least one of that.  */
6740126209Sache	    while (1)
6741126209Sache	      {
6742126209Sache		if (p2 + 2 < pend
6743126209Sache		    && ((re_opcode_t) *p2 == stop_memory
6744126209Sache			|| (re_opcode_t) *p2 == start_memory))
6745126209Sache		  p2 += 3;
6746131543Stjr		else if (p2 + 2 + 2 * OFFSET_ADDRESS_SIZE < pend
6747126209Sache			 && (re_opcode_t) *p2 == dummy_failure_jump)
6748131543Stjr		  p2 += 2 + 2 * OFFSET_ADDRESS_SIZE;
6749126209Sache		else
6750126209Sache		  break;
6751126209Sache	      }
6752218Sconklin
6753126209Sache	    p1 = p + mcnt;
6754126209Sache	    /* p1[0] ... p1[2] are the `on_failure_jump' corresponding
6755126209Sache	       to the `maybe_finalize_jump' of this case.  Examine what
6756126209Sache	       follows.  */
6757126209Sache
6758218Sconklin            /* If we're at the end of the pattern, we can change.  */
6759218Sconklin            if (p2 == pend)
6760218Sconklin	      {
6761218Sconklin		/* Consider what happens when matching ":\(.*\)"
6762218Sconklin		   against ":/".  I don't really understand this code
6763218Sconklin		   yet.  */
6764131543Stjr  	        p[-(1+OFFSET_ADDRESS_SIZE)] = (US_CHAR_TYPE)
6765131543Stjr		  pop_failure_jump;
6766218Sconklin                DEBUG_PRINT1
6767218Sconklin                  ("  End of pattern: change to `pop_failure_jump'.\n");
6768218Sconklin              }
6769218Sconklin
6770218Sconklin            else if ((re_opcode_t) *p2 == exactn
6771131543Stjr#ifdef MBS_SUPPORT
6772131543Stjr		     || (re_opcode_t) *p2 == exactn_bin
6773131543Stjr#endif
6774218Sconklin		     || (bufp->newline_anchor && (re_opcode_t) *p2 == endline))
6775218Sconklin	      {
6776131543Stjr		register US_CHAR_TYPE c
6777131543Stjr                  = *p2 == (US_CHAR_TYPE) endline ? '\n' : p2[2];
6778218Sconklin
6779131543Stjr                if (((re_opcode_t) p1[1+OFFSET_ADDRESS_SIZE] == exactn
6780131543Stjr#ifdef MBS_SUPPORT
6781131543Stjr		     || (re_opcode_t) p1[1+OFFSET_ADDRESS_SIZE] == exactn_bin
6782131543Stjr#endif
6783131543Stjr		    ) && p1[3+OFFSET_ADDRESS_SIZE] != c)
6784218Sconklin                  {
6785131543Stjr  		    p[-(1+OFFSET_ADDRESS_SIZE)] = (US_CHAR_TYPE)
6786131543Stjr		      pop_failure_jump;
6787131543Stjr#ifdef MBS_SUPPORT
6788131543Stjr		    if (MB_CUR_MAX != 1)
6789131543Stjr		      DEBUG_PRINT3 ("  %C != %C => pop_failure_jump.\n",
6790131543Stjr				    (wint_t) c,
6791131543Stjr				    (wint_t) p1[3+OFFSET_ADDRESS_SIZE]);
6792131543Stjr		    else
6793131543Stjr#endif
6794131543Stjr		      DEBUG_PRINT3 ("  %c != %c => pop_failure_jump.\n",
6795131543Stjr				    (char) c,
6796131543Stjr				    (char) p1[3+OFFSET_ADDRESS_SIZE]);
6797218Sconklin                  }
6798126209Sache
6799131543Stjr#ifndef MBS_SUPPORT
6800218Sconklin		else if ((re_opcode_t) p1[3] == charset
6801218Sconklin			 || (re_opcode_t) p1[3] == charset_not)
6802218Sconklin		  {
6803218Sconklin		    int not = (re_opcode_t) p1[3] == charset_not;
6804126209Sache
6805131543Stjr		    if (c < (unsigned) (p1[4] * BYTEWIDTH)
6806218Sconklin			&& p1[5 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
6807218Sconklin		      not = !not;
6808218Sconklin
6809218Sconklin                    /* `not' is equal to 1 if c would match, which means
6810218Sconklin                        that we can't change to pop_failure_jump.  */
6811218Sconklin		    if (!not)
6812218Sconklin                      {
6813218Sconklin  		        p[-3] = (unsigned char) pop_failure_jump;
6814218Sconklin                        DEBUG_PRINT1 ("  No match => pop_failure_jump.\n");
6815218Sconklin                      }
6816218Sconklin		  }
6817131543Stjr#endif /* not MBS_SUPPORT */
6818218Sconklin	      }
6819131543Stjr#ifndef MBS_SUPPORT
6820126209Sache            else if ((re_opcode_t) *p2 == charset)
6821126209Sache	      {
6822126209Sache		/* We win if the first character of the loop is not part
6823126209Sache                   of the charset.  */
6824126209Sache                if ((re_opcode_t) p1[3] == exactn
6825126209Sache 		    && ! ((int) p2[1] * BYTEWIDTH > (int) p1[5]
6826126209Sache 			  && (p2[2 + p1[5] / BYTEWIDTH]
6827126209Sache 			      & (1 << (p1[5] % BYTEWIDTH)))))
6828126209Sache		  {
6829126209Sache		    p[-3] = (unsigned char) pop_failure_jump;
6830126209Sache		    DEBUG_PRINT1 ("  No match => pop_failure_jump.\n");
6831126209Sache                  }
6832126209Sache
6833126209Sache		else if ((re_opcode_t) p1[3] == charset_not)
6834126209Sache		  {
6835126209Sache		    int idx;
6836126209Sache		    /* We win if the charset_not inside the loop
6837126209Sache		       lists every character listed in the charset after.  */
6838126209Sache		    for (idx = 0; idx < (int) p2[1]; idx++)
6839126209Sache		      if (! (p2[2 + idx] == 0
6840126209Sache			     || (idx < (int) p1[4]
6841126209Sache				 && ((p2[2 + idx] & ~ p1[5 + idx]) == 0))))
6842126209Sache			break;
6843126209Sache
6844126209Sache		    if (idx == p2[1])
6845126209Sache                      {
6846126209Sache  		        p[-3] = (unsigned char) pop_failure_jump;
6847126209Sache                        DEBUG_PRINT1 ("  No match => pop_failure_jump.\n");
6848126209Sache                      }
6849126209Sache		  }
6850126209Sache		else if ((re_opcode_t) p1[3] == charset)
6851126209Sache		  {
6852126209Sache		    int idx;
6853126209Sache		    /* We win if the charset inside the loop
6854126209Sache		       has no overlap with the one after the loop.  */
6855126209Sache		    for (idx = 0;
6856126209Sache			 idx < (int) p2[1] && idx < (int) p1[4];
6857126209Sache			 idx++)
6858126209Sache		      if ((p2[2 + idx] & p1[5 + idx]) != 0)
6859126209Sache			break;
6860126209Sache
6861126209Sache		    if (idx == p2[1] || idx == p1[4])
6862126209Sache                      {
6863126209Sache  		        p[-3] = (unsigned char) pop_failure_jump;
6864126209Sache                        DEBUG_PRINT1 ("  No match => pop_failure_jump.\n");
6865126209Sache                      }
6866126209Sache		  }
6867126209Sache	      }
6868131543Stjr#endif /* not MBS_SUPPORT */
6869218Sconklin	  }
6870131543Stjr	  p -= OFFSET_ADDRESS_SIZE;	/* Point at relative address again.  */
6871218Sconklin	  if ((re_opcode_t) p[-1] != pop_failure_jump)
6872218Sconklin	    {
6873131543Stjr	      p[-1] = (US_CHAR_TYPE) jump;
6874218Sconklin              DEBUG_PRINT1 ("  Match => jump.\n");
6875218Sconklin	      goto unconditional_jump;
6876218Sconklin	    }
6877218Sconklin        /* Note fall through.  */
6878218Sconklin
6879218Sconklin
6880218Sconklin	/* The end of a simple repeat has a pop_failure_jump back to
6881218Sconklin           its matching on_failure_jump, where the latter will push a
6882218Sconklin           failure point.  The pop_failure_jump takes off failure
6883218Sconklin           points put on by this pop_failure_jump's matching
6884218Sconklin           on_failure_jump; we got through the pattern to here from the
6885218Sconklin           matching on_failure_jump, so didn't fail.  */
6886218Sconklin        case pop_failure_jump:
6887218Sconklin          {
6888218Sconklin            /* We need to pass separate storage for the lowest and
6889218Sconklin               highest registers, even though we don't care about the
6890218Sconklin               actual values.  Otherwise, we will restore only one
6891218Sconklin               register from the stack, since lowest will == highest in
6892218Sconklin               `pop_failure_point'.  */
6893126209Sache            active_reg_t dummy_low_reg, dummy_high_reg;
6894131543Stjr            US_CHAR_TYPE *pdummy = NULL;
6895131543Stjr            const CHAR_TYPE *sdummy = NULL;
6896218Sconklin
6897218Sconklin            DEBUG_PRINT1 ("EXECUTING pop_failure_jump.\n");
6898218Sconklin            POP_FAILURE_POINT (sdummy, pdummy,
6899218Sconklin                               dummy_low_reg, dummy_high_reg,
6900218Sconklin                               reg_dummy, reg_dummy, reg_info_dummy);
6901218Sconklin          }
6902126209Sache	  /* Note fall through.  */
6903126209Sache
6904126209Sache	unconditional_jump:
6905126209Sache#ifdef _LIBC
6906126209Sache	  DEBUG_PRINT2 ("\n%p: ", p);
6907126209Sache#else
6908126209Sache	  DEBUG_PRINT2 ("\n0x%x: ", p);
6909126209Sache#endif
6910218Sconklin          /* Note fall through.  */
6911218Sconklin
6912218Sconklin        /* Unconditionally jump (without popping any failure points).  */
6913218Sconklin        case jump:
6914218Sconklin	  EXTRACT_NUMBER_AND_INCR (mcnt, p);	/* Get the amount to jump.  */
6915218Sconklin          DEBUG_PRINT2 ("EXECUTING jump %d ", mcnt);
6916218Sconklin	  p += mcnt;				/* Do the jump.  */
6917126209Sache#ifdef _LIBC
6918126209Sache          DEBUG_PRINT2 ("(to %p).\n", p);
6919126209Sache#else
6920218Sconklin          DEBUG_PRINT2 ("(to 0x%x).\n", p);
6921126209Sache#endif
6922218Sconklin	  break;
6923218Sconklin
6924126209Sache
6925218Sconklin        /* We need this opcode so we can detect where alternatives end
6926218Sconklin           in `group_match_null_string_p' et al.  */
6927218Sconklin        case jump_past_alt:
6928218Sconklin          DEBUG_PRINT1 ("EXECUTING jump_past_alt.\n");
6929218Sconklin          goto unconditional_jump;
6930218Sconklin
6931218Sconklin
6932218Sconklin        /* Normally, the on_failure_jump pushes a failure point, which
6933218Sconklin           then gets popped at pop_failure_jump.  We will end up at
6934218Sconklin           pop_failure_jump, also, and with a pattern of, say, `a+', we
6935218Sconklin           are skipping over the on_failure_jump, so we have to push
6936218Sconklin           something meaningless for pop_failure_jump to pop.  */
6937218Sconklin        case dummy_failure_jump:
6938218Sconklin          DEBUG_PRINT1 ("EXECUTING dummy_failure_jump.\n");
6939218Sconklin          /* It doesn't matter what we push for the string here.  What
6940218Sconklin             the code at `fail' tests is the value for the pattern.  */
6941126209Sache          PUSH_FAILURE_POINT (NULL, NULL, -2);
6942218Sconklin          goto unconditional_jump;
6943218Sconklin
6944218Sconklin
6945218Sconklin        /* At the end of an alternative, we need to push a dummy failure
6946218Sconklin           point in case we are followed by a `pop_failure_jump', because
6947218Sconklin           we don't want the failure point for the alternative to be
6948218Sconklin           popped.  For example, matching `(a|ab)*' against `aab'
6949218Sconklin           requires that we match the `ab' alternative.  */
6950218Sconklin        case push_dummy_failure:
6951218Sconklin          DEBUG_PRINT1 ("EXECUTING push_dummy_failure.\n");
6952218Sconklin          /* See comments just above at `dummy_failure_jump' about the
6953218Sconklin             two zeroes.  */
6954126209Sache          PUSH_FAILURE_POINT (NULL, NULL, -2);
6955218Sconklin          break;
6956218Sconklin
6957218Sconklin        /* Have to succeed matching what follows at least n times.
6958218Sconklin           After that, handle like `on_failure_jump'.  */
6959126209Sache        case succeed_n:
6960131543Stjr          EXTRACT_NUMBER (mcnt, p + OFFSET_ADDRESS_SIZE);
6961218Sconklin          DEBUG_PRINT2 ("EXECUTING succeed_n %d.\n", mcnt);
6962218Sconklin
6963218Sconklin          assert (mcnt >= 0);
6964218Sconklin          /* Originally, this is how many times we HAVE to succeed.  */
6965218Sconklin          if (mcnt > 0)
6966218Sconklin            {
6967218Sconklin               mcnt--;
6968131543Stjr	       p += OFFSET_ADDRESS_SIZE;
6969218Sconklin               STORE_NUMBER_AND_INCR (p, mcnt);
6970126209Sache#ifdef _LIBC
6971131543Stjr               DEBUG_PRINT3 ("  Setting %p to %d.\n", p - OFFSET_ADDRESS_SIZE
6972131543Stjr			     , mcnt);
6973126209Sache#else
6974131543Stjr               DEBUG_PRINT3 ("  Setting 0x%x to %d.\n", p - OFFSET_ADDRESS_SIZE
6975131543Stjr			     , mcnt);
6976126209Sache#endif
6977218Sconklin            }
6978218Sconklin	  else if (mcnt == 0)
6979218Sconklin            {
6980126209Sache#ifdef _LIBC
6981131543Stjr              DEBUG_PRINT2 ("  Setting two bytes from %p to no_op.\n",
6982131543Stjr			    p + OFFSET_ADDRESS_SIZE);
6983126209Sache#else
6984131543Stjr              DEBUG_PRINT2 ("  Setting two bytes from 0x%x to no_op.\n",
6985131543Stjr			    p + OFFSET_ADDRESS_SIZE);
6986131543Stjr#endif /* _LIBC */
6987131543Stjr
6988131543Stjr#ifdef MBS_SUPPORT
6989131543Stjr	      p[1] = (US_CHAR_TYPE) no_op;
6990131543Stjr#else
6991131543Stjr	      p[2] = (US_CHAR_TYPE) no_op;
6992131543Stjr              p[3] = (US_CHAR_TYPE) no_op;
6993131543Stjr#endif /* MBS_SUPPORT */
6994218Sconklin              goto on_failure;
6995218Sconklin            }
6996218Sconklin          break;
6997126209Sache
6998126209Sache        case jump_n:
6999131543Stjr          EXTRACT_NUMBER (mcnt, p + OFFSET_ADDRESS_SIZE);
7000218Sconklin          DEBUG_PRINT2 ("EXECUTING jump_n %d.\n", mcnt);
7001218Sconklin
7002218Sconklin          /* Originally, this is how many times we CAN jump.  */
7003218Sconklin          if (mcnt)
7004218Sconklin            {
7005218Sconklin               mcnt--;
7006131543Stjr               STORE_NUMBER (p + OFFSET_ADDRESS_SIZE, mcnt);
7007131543Stjr
7008126209Sache#ifdef _LIBC
7009131543Stjr               DEBUG_PRINT3 ("  Setting %p to %d.\n", p + OFFSET_ADDRESS_SIZE,
7010131543Stjr			     mcnt);
7011126209Sache#else
7012131543Stjr               DEBUG_PRINT3 ("  Setting 0x%x to %d.\n", p + OFFSET_ADDRESS_SIZE,
7013131543Stjr			     mcnt);
7014131543Stjr#endif /* _LIBC */
7015126209Sache	       goto unconditional_jump;
7016218Sconklin            }
7017218Sconklin          /* If don't have to jump any more, skip over the rest of command.  */
7018126209Sache	  else
7019131543Stjr	    p += 2 * OFFSET_ADDRESS_SIZE;
7020218Sconklin          break;
7021126209Sache
7022218Sconklin	case set_number_at:
7023218Sconklin	  {
7024218Sconklin            DEBUG_PRINT1 ("EXECUTING set_number_at.\n");
7025218Sconklin
7026218Sconklin            EXTRACT_NUMBER_AND_INCR (mcnt, p);
7027218Sconklin            p1 = p + mcnt;
7028218Sconklin            EXTRACT_NUMBER_AND_INCR (mcnt, p);
7029126209Sache#ifdef _LIBC
7030126209Sache            DEBUG_PRINT3 ("  Setting %p to %d.\n", p1, mcnt);
7031126209Sache#else
7032218Sconklin            DEBUG_PRINT3 ("  Setting 0x%x to %d.\n", p1, mcnt);
7033126209Sache#endif
7034218Sconklin	    STORE_NUMBER (p1, mcnt);
7035218Sconklin            break;
7036218Sconklin          }
7037218Sconklin
7038126209Sache#if 0
7039126209Sache	/* The DEC Alpha C compiler 3.x generates incorrect code for the
7040126209Sache	   test  WORDCHAR_P (d - 1) != WORDCHAR_P (d)  in the expansion of
7041126209Sache	   AT_WORD_BOUNDARY, so this code is disabled.  Expanding the
7042126209Sache	   macro and introducing temporary variables works around the bug.  */
7043126209Sache
7044126209Sache	case wordbound:
7045126209Sache	  DEBUG_PRINT1 ("EXECUTING wordbound.\n");
7046126209Sache	  if (AT_WORD_BOUNDARY (d))
7047218Sconklin	    break;
7048126209Sache	  goto fail;
7049218Sconklin
7050218Sconklin	case notwordbound:
7051126209Sache	  DEBUG_PRINT1 ("EXECUTING notwordbound.\n");
7052218Sconklin	  if (AT_WORD_BOUNDARY (d))
7053218Sconklin	    goto fail;
7054126209Sache	  break;
7055126209Sache#else
7056126209Sache	case wordbound:
7057126209Sache	{
7058126209Sache	  boolean prevchar, thischar;
7059218Sconklin
7060126209Sache	  DEBUG_PRINT1 ("EXECUTING wordbound.\n");
7061126209Sache	  if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
7062126209Sache	    break;
7063126209Sache
7064126209Sache	  prevchar = WORDCHAR_P (d - 1);
7065126209Sache	  thischar = WORDCHAR_P (d);
7066126209Sache	  if (prevchar != thischar)
7067126209Sache	    break;
7068126209Sache	  goto fail;
7069126209Sache	}
7070126209Sache
7071126209Sache      case notwordbound:
7072126209Sache	{
7073126209Sache	  boolean prevchar, thischar;
7074126209Sache
7075126209Sache	  DEBUG_PRINT1 ("EXECUTING notwordbound.\n");
7076126209Sache	  if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
7077126209Sache	    goto fail;
7078126209Sache
7079126209Sache	  prevchar = WORDCHAR_P (d - 1);
7080126209Sache	  thischar = WORDCHAR_P (d);
7081126209Sache	  if (prevchar != thischar)
7082126209Sache	    goto fail;
7083126209Sache	  break;
7084126209Sache	}
7085126209Sache#endif
7086126209Sache
7087218Sconklin	case wordbeg:
7088218Sconklin          DEBUG_PRINT1 ("EXECUTING wordbeg.\n");
7089218Sconklin	  if (WORDCHAR_P (d) && (AT_STRINGS_BEG (d) || !WORDCHAR_P (d - 1)))
7090218Sconklin	    break;
7091218Sconklin          goto fail;
7092218Sconklin
7093218Sconklin	case wordend:
7094218Sconklin          DEBUG_PRINT1 ("EXECUTING wordend.\n");
7095218Sconklin	  if (!AT_STRINGS_BEG (d) && WORDCHAR_P (d - 1)
7096218Sconklin              && (!WORDCHAR_P (d) || AT_STRINGS_END (d)))
7097218Sconklin	    break;
7098218Sconklin          goto fail;
7099218Sconklin
7100218Sconklin#ifdef emacs
7101218Sconklin  	case before_dot:
7102218Sconklin          DEBUG_PRINT1 ("EXECUTING before_dot.\n");
7103218Sconklin 	  if (PTR_CHAR_POS ((unsigned char *) d) >= point)
7104218Sconklin  	    goto fail;
7105218Sconklin  	  break;
7106126209Sache
7107218Sconklin  	case at_dot:
7108218Sconklin          DEBUG_PRINT1 ("EXECUTING at_dot.\n");
7109218Sconklin 	  if (PTR_CHAR_POS ((unsigned char *) d) != point)
7110218Sconklin  	    goto fail;
7111218Sconklin  	  break;
7112126209Sache
7113218Sconklin  	case after_dot:
7114218Sconklin          DEBUG_PRINT1 ("EXECUTING after_dot.\n");
7115218Sconklin          if (PTR_CHAR_POS ((unsigned char *) d) <= point)
7116218Sconklin  	    goto fail;
7117218Sconklin  	  break;
7118218Sconklin
7119218Sconklin	case syntaxspec:
7120218Sconklin          DEBUG_PRINT2 ("EXECUTING syntaxspec %d.\n", mcnt);
7121218Sconklin	  mcnt = *p++;
7122218Sconklin	  goto matchsyntax;
7123218Sconklin
7124218Sconklin        case wordchar:
7125218Sconklin          DEBUG_PRINT1 ("EXECUTING Emacs wordchar.\n");
7126218Sconklin	  mcnt = (int) Sword;
7127218Sconklin        matchsyntax:
7128218Sconklin	  PREFETCH ();
7129126209Sache	  /* Can't use *d++ here; SYNTAX may be an unsafe macro.  */
7130126209Sache	  d++;
7131126209Sache	  if (SYNTAX (d[-1]) != (enum syntaxcode) mcnt)
7132126209Sache	    goto fail;
7133218Sconklin          SET_REGS_MATCHED ();
7134218Sconklin	  break;
7135218Sconklin
7136218Sconklin	case notsyntaxspec:
7137218Sconklin          DEBUG_PRINT2 ("EXECUTING notsyntaxspec %d.\n", mcnt);
7138218Sconklin	  mcnt = *p++;
7139218Sconklin	  goto matchnotsyntax;
7140218Sconklin
7141218Sconklin        case notwordchar:
7142218Sconklin          DEBUG_PRINT1 ("EXECUTING Emacs notwordchar.\n");
7143218Sconklin	  mcnt = (int) Sword;
7144218Sconklin        matchnotsyntax:
7145218Sconklin	  PREFETCH ();
7146126209Sache	  /* Can't use *d++ here; SYNTAX may be an unsafe macro.  */
7147126209Sache	  d++;
7148126209Sache	  if (SYNTAX (d[-1]) == (enum syntaxcode) mcnt)
7149126209Sache	    goto fail;
7150218Sconklin	  SET_REGS_MATCHED ();
7151218Sconklin          break;
7152218Sconklin
7153218Sconklin#else /* not emacs */
7154218Sconklin	case wordchar:
7155218Sconklin          DEBUG_PRINT1 ("EXECUTING non-Emacs wordchar.\n");
7156218Sconklin	  PREFETCH ();
7157218Sconklin          if (!WORDCHAR_P (d))
7158218Sconklin            goto fail;
7159218Sconklin	  SET_REGS_MATCHED ();
7160218Sconklin          d++;
7161218Sconklin	  break;
7162126209Sache
7163218Sconklin	case notwordchar:
7164218Sconklin          DEBUG_PRINT1 ("EXECUTING non-Emacs notwordchar.\n");
7165218Sconklin	  PREFETCH ();
7166218Sconklin	  if (WORDCHAR_P (d))
7167218Sconklin            goto fail;
7168218Sconklin          SET_REGS_MATCHED ();
7169218Sconklin          d++;
7170218Sconklin	  break;
7171218Sconklin#endif /* not emacs */
7172126209Sache
7173218Sconklin        default:
7174218Sconklin          abort ();
7175218Sconklin	}
7176218Sconklin      continue;  /* Successfully executed one pattern command; keep going.  */
7177218Sconklin
7178218Sconklin
7179218Sconklin    /* We goto here if a matching operation fails. */
7180218Sconklin    fail:
7181218Sconklin      if (!FAIL_STACK_EMPTY ())
7182218Sconklin	{ /* A restart point is known.  Restore to that state.  */
7183218Sconklin          DEBUG_PRINT1 ("\nFAIL:\n");
7184218Sconklin          POP_FAILURE_POINT (d, p,
7185218Sconklin                             lowest_active_reg, highest_active_reg,
7186218Sconklin                             regstart, regend, reg_info);
7187218Sconklin
7188218Sconklin          /* If this failure point is a dummy, try the next one.  */
7189218Sconklin          if (!p)
7190218Sconklin	    goto fail;
7191218Sconklin
7192218Sconklin          /* If we failed to the end of the pattern, don't examine *p.  */
7193218Sconklin	  assert (p <= pend);
7194218Sconklin          if (p < pend)
7195218Sconklin            {
7196218Sconklin              boolean is_a_jump_n = false;
7197126209Sache
7198218Sconklin              /* If failed to a backwards jump that's part of a repetition
7199218Sconklin                 loop, need to pop this failure point and use the next one.  */
7200218Sconklin              switch ((re_opcode_t) *p)
7201218Sconklin                {
7202218Sconklin                case jump_n:
7203218Sconklin                  is_a_jump_n = true;
7204218Sconklin                case maybe_pop_jump:
7205218Sconklin                case pop_failure_jump:
7206218Sconklin                case jump:
7207218Sconklin                  p1 = p + 1;
7208218Sconklin                  EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7209126209Sache                  p1 += mcnt;
7210218Sconklin
7211218Sconklin                  if ((is_a_jump_n && (re_opcode_t) *p1 == succeed_n)
7212218Sconklin                      || (!is_a_jump_n
7213218Sconklin                          && (re_opcode_t) *p1 == on_failure_jump))
7214218Sconklin                    goto fail;
7215218Sconklin                  break;
7216218Sconklin                default:
7217218Sconklin                  /* do nothing */ ;
7218218Sconklin                }
7219218Sconklin            }
7220218Sconklin
7221218Sconklin          if (d >= string1 && d <= end1)
7222218Sconklin	    dend = end_match_1;
7223218Sconklin        }
7224218Sconklin      else
7225218Sconklin        break;   /* Matching at this starting point really fails.  */
7226218Sconklin    } /* for (;;) */
7227218Sconklin
7228218Sconklin  if (best_regs_set)
7229218Sconklin    goto restore_best_regs;
7230218Sconklin
7231218Sconklin  FREE_VARIABLES ();
7232218Sconklin
7233218Sconklin  return -1;         			/* Failure to match.  */
7234218Sconklin} /* re_match_2 */
7235218Sconklin
7236218Sconklin/* Subroutine definitions for re_match_2.  */
7237218Sconklin
7238218Sconklin
7239218Sconklin/* We are passed P pointing to a register number after a start_memory.
7240126209Sache
7241218Sconklin   Return true if the pattern up to the corresponding stop_memory can
7242218Sconklin   match the empty string, and false otherwise.
7243126209Sache
7244218Sconklin   If we find the matching stop_memory, sets P to point to one past its number.
7245218Sconklin   Otherwise, sets P to an undefined byte less than or equal to END.
7246218Sconklin
7247218Sconklin   We don't handle duplicates properly (yet).  */
7248218Sconklin
7249218Sconklinstatic boolean
7250218Sconklingroup_match_null_string_p (p, end, reg_info)
7251131543Stjr    US_CHAR_TYPE **p, *end;
7252218Sconklin    register_info_type *reg_info;
7253218Sconklin{
7254218Sconklin  int mcnt;
7255218Sconklin  /* Point to after the args to the start_memory.  */
7256131543Stjr  US_CHAR_TYPE *p1 = *p + 2;
7257126209Sache
7258218Sconklin  while (p1 < end)
7259218Sconklin    {
7260218Sconklin      /* Skip over opcodes that can match nothing, and return true or
7261218Sconklin	 false, as appropriate, when we get to one that can't, or to the
7262218Sconklin         matching stop_memory.  */
7263126209Sache
7264218Sconklin      switch ((re_opcode_t) *p1)
7265218Sconklin        {
7266218Sconklin        /* Could be either a loop or a series of alternatives.  */
7267218Sconklin        case on_failure_jump:
7268218Sconklin          p1++;
7269218Sconklin          EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7270126209Sache
7271218Sconklin          /* If the next operation is not a jump backwards in the
7272218Sconklin	     pattern.  */
7273218Sconklin
7274218Sconklin	  if (mcnt >= 0)
7275218Sconklin	    {
7276218Sconklin              /* Go through the on_failure_jumps of the alternatives,
7277218Sconklin                 seeing if any of the alternatives cannot match nothing.
7278218Sconklin                 The last alternative starts with only a jump,
7279218Sconklin                 whereas the rest start with on_failure_jump and end
7280218Sconklin                 with a jump, e.g., here is the pattern for `a|b|c':
7281218Sconklin
7282218Sconklin                 /on_failure_jump/0/6/exactn/1/a/jump_past_alt/0/6
7283218Sconklin                 /on_failure_jump/0/6/exactn/1/b/jump_past_alt/0/3
7284126209Sache                 /exactn/1/c
7285218Sconklin
7286218Sconklin                 So, we have to first go through the first (n-1)
7287218Sconklin                 alternatives and then deal with the last one separately.  */
7288218Sconklin
7289218Sconklin
7290218Sconklin              /* Deal with the first (n-1) alternatives, which start
7291218Sconklin                 with an on_failure_jump (see above) that jumps to right
7292218Sconklin                 past a jump_past_alt.  */
7293218Sconklin
7294131543Stjr              while ((re_opcode_t) p1[mcnt-(1+OFFSET_ADDRESS_SIZE)] ==
7295131543Stjr		     jump_past_alt)
7296218Sconklin                {
7297218Sconklin                  /* `mcnt' holds how many bytes long the alternative
7298218Sconklin                     is, including the ending `jump_past_alt' and
7299218Sconklin                     its number.  */
7300218Sconklin
7301131543Stjr                  if (!alt_match_null_string_p (p1, p1 + mcnt -
7302131543Stjr						(1 + OFFSET_ADDRESS_SIZE),
7303131543Stjr						reg_info))
7304218Sconklin                    return false;
7305218Sconklin
7306218Sconklin                  /* Move to right after this alternative, including the
7307218Sconklin		     jump_past_alt.  */
7308126209Sache                  p1 += mcnt;
7309218Sconklin
7310218Sconklin                  /* Break if it's the beginning of an n-th alternative
7311218Sconklin                     that doesn't begin with an on_failure_jump.  */
7312218Sconklin                  if ((re_opcode_t) *p1 != on_failure_jump)
7313218Sconklin                    break;
7314126209Sache
7315218Sconklin		  /* Still have to check that it's not an n-th
7316218Sconklin		     alternative that starts with an on_failure_jump.  */
7317218Sconklin		  p1++;
7318218Sconklin                  EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7319131543Stjr                  if ((re_opcode_t) p1[mcnt-(1+OFFSET_ADDRESS_SIZE)] !=
7320131543Stjr		      jump_past_alt)
7321218Sconklin                    {
7322218Sconklin		      /* Get to the beginning of the n-th alternative.  */
7323131543Stjr                      p1 -= 1 + OFFSET_ADDRESS_SIZE;
7324218Sconklin                      break;
7325218Sconklin                    }
7326218Sconklin                }
7327218Sconklin
7328218Sconklin              /* Deal with the last alternative: go back and get number
7329218Sconklin                 of the `jump_past_alt' just before it.  `mcnt' contains
7330218Sconklin                 the length of the alternative.  */
7331131543Stjr              EXTRACT_NUMBER (mcnt, p1 - OFFSET_ADDRESS_SIZE);
7332218Sconklin
7333218Sconklin              if (!alt_match_null_string_p (p1, p1 + mcnt, reg_info))
7334218Sconklin                return false;
7335218Sconklin
7336218Sconklin              p1 += mcnt;	/* Get past the n-th alternative.  */
7337218Sconklin            } /* if mcnt > 0 */
7338218Sconklin          break;
7339218Sconklin
7340126209Sache
7341218Sconklin        case stop_memory:
7342218Sconklin	  assert (p1[1] == **p);
7343218Sconklin          *p = p1 + 2;
7344218Sconklin          return true;
7345218Sconklin
7346126209Sache
7347126209Sache        default:
7348218Sconklin          if (!common_op_match_null_string_p (&p1, end, reg_info))
7349218Sconklin            return false;
7350218Sconklin        }
7351218Sconklin    } /* while p1 < end */
7352218Sconklin
7353218Sconklin  return false;
7354218Sconklin} /* group_match_null_string_p */
7355218Sconklin
7356218Sconklin
7357218Sconklin/* Similar to group_match_null_string_p, but doesn't deal with alternatives:
7358218Sconklin   It expects P to be the first byte of a single alternative and END one
7359218Sconklin   byte past the last. The alternative can contain groups.  */
7360126209Sache
7361218Sconklinstatic boolean
7362218Sconklinalt_match_null_string_p (p, end, reg_info)
7363131543Stjr    US_CHAR_TYPE *p, *end;
7364218Sconklin    register_info_type *reg_info;
7365218Sconklin{
7366218Sconklin  int mcnt;
7367131543Stjr  US_CHAR_TYPE *p1 = p;
7368126209Sache
7369218Sconklin  while (p1 < end)
7370218Sconklin    {
7371126209Sache      /* Skip over opcodes that can match nothing, and break when we get
7372218Sconklin         to one that can't.  */
7373126209Sache
7374218Sconklin      switch ((re_opcode_t) *p1)
7375218Sconklin        {
7376218Sconklin	/* It's a loop.  */
7377218Sconklin        case on_failure_jump:
7378218Sconklin          p1++;
7379218Sconklin          EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7380218Sconklin          p1 += mcnt;
7381218Sconklin          break;
7382126209Sache
7383126209Sache	default:
7384218Sconklin          if (!common_op_match_null_string_p (&p1, end, reg_info))
7385218Sconklin            return false;
7386218Sconklin        }
7387218Sconklin    }  /* while p1 < end */
7388218Sconklin
7389218Sconklin  return true;
7390218Sconklin} /* alt_match_null_string_p */
7391218Sconklin
7392218Sconklin
7393218Sconklin/* Deals with the ops common to group_match_null_string_p and
7394126209Sache   alt_match_null_string_p.
7395126209Sache
7396218Sconklin   Sets P to one after the op and its arguments, if any.  */
7397218Sconklin
7398218Sconklinstatic boolean
7399218Sconklincommon_op_match_null_string_p (p, end, reg_info)
7400131543Stjr    US_CHAR_TYPE **p, *end;
7401218Sconklin    register_info_type *reg_info;
7402218Sconklin{
7403218Sconklin  int mcnt;
7404218Sconklin  boolean ret;
7405218Sconklin  int reg_no;
7406131543Stjr  US_CHAR_TYPE *p1 = *p;
7407218Sconklin
7408218Sconklin  switch ((re_opcode_t) *p1++)
7409218Sconklin    {
7410218Sconklin    case no_op:
7411218Sconklin    case begline:
7412218Sconklin    case endline:
7413218Sconklin    case begbuf:
7414218Sconklin    case endbuf:
7415218Sconklin    case wordbeg:
7416218Sconklin    case wordend:
7417218Sconklin    case wordbound:
7418218Sconklin    case notwordbound:
7419218Sconklin#ifdef emacs
7420218Sconklin    case before_dot:
7421218Sconklin    case at_dot:
7422218Sconklin    case after_dot:
7423218Sconklin#endif
7424218Sconklin      break;
7425218Sconklin
7426218Sconklin    case start_memory:
7427218Sconklin      reg_no = *p1;
7428218Sconklin      assert (reg_no > 0 && reg_no <= MAX_REGNUM);
7429218Sconklin      ret = group_match_null_string_p (&p1, end, reg_info);
7430126209Sache
7431218Sconklin      /* Have to set this here in case we're checking a group which
7432218Sconklin         contains a group and a back reference to it.  */
7433218Sconklin
7434218Sconklin      if (REG_MATCH_NULL_STRING_P (reg_info[reg_no]) == MATCH_NULL_UNSET_VALUE)
7435218Sconklin        REG_MATCH_NULL_STRING_P (reg_info[reg_no]) = ret;
7436218Sconklin
7437218Sconklin      if (!ret)
7438218Sconklin        return false;
7439218Sconklin      break;
7440126209Sache
7441218Sconklin    /* If this is an optimized succeed_n for zero times, make the jump.  */
7442218Sconklin    case jump:
7443218Sconklin      EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7444218Sconklin      if (mcnt >= 0)
7445218Sconklin        p1 += mcnt;
7446218Sconklin      else
7447218Sconklin        return false;
7448218Sconklin      break;
7449218Sconklin
7450218Sconklin    case succeed_n:
7451218Sconklin      /* Get to the number of times to succeed.  */
7452131543Stjr      p1 += OFFSET_ADDRESS_SIZE;
7453218Sconklin      EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7454218Sconklin
7455218Sconklin      if (mcnt == 0)
7456218Sconklin        {
7457131543Stjr          p1 -= 2 * OFFSET_ADDRESS_SIZE;
7458218Sconklin          EXTRACT_NUMBER_AND_INCR (mcnt, p1);
7459218Sconklin          p1 += mcnt;
7460218Sconklin        }
7461218Sconklin      else
7462218Sconklin        return false;
7463218Sconklin      break;
7464218Sconklin
7465126209Sache    case duplicate:
7466218Sconklin      if (!REG_MATCH_NULL_STRING_P (reg_info[*p1]))
7467218Sconklin        return false;
7468218Sconklin      break;
7469218Sconklin
7470218Sconklin    case set_number_at:
7471131543Stjr      p1 += 2 * OFFSET_ADDRESS_SIZE;
7472218Sconklin
7473218Sconklin    default:
7474218Sconklin      /* All other opcodes mean we cannot match the empty string.  */
7475218Sconklin      return false;
7476218Sconklin  }
7477218Sconklin
7478218Sconklin  *p = p1;
7479218Sconklin  return true;
7480218Sconklin} /* common_op_match_null_string_p */
7481218Sconklin
7482218Sconklin
7483218Sconklin/* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
7484218Sconklin   bytes; nonzero otherwise.  */
7485126209Sache
7486218Sconklinstatic int
7487218Sconklinbcmp_translate (s1, s2, len, translate)
7488131543Stjr     const CHAR_TYPE *s1, *s2;
7489218Sconklin     register int len;
7490126209Sache     RE_TRANSLATE_TYPE translate;
7491218Sconklin{
7492131543Stjr  register const US_CHAR_TYPE *p1 = (const US_CHAR_TYPE *) s1;
7493131543Stjr  register const US_CHAR_TYPE *p2 = (const US_CHAR_TYPE *) s2;
7494218Sconklin  while (len)
7495218Sconklin    {
7496131543Stjr#ifdef MBS_SUPPORT
7497131543Stjr      if (((*p1<=0xff)?translate[*p1++]:*p1++)
7498131543Stjr	  != ((*p2<=0xff)?translate[*p2++]:*p2++))
7499131543Stjr	return 1;
7500131543Stjr#else
7501218Sconklin      if (translate[*p1++] != translate[*p2++]) return 1;
7502131543Stjr#endif /* MBS_SUPPORT */
7503218Sconklin      len--;
7504218Sconklin    }
7505218Sconklin  return 0;
7506218Sconklin}
7507218Sconklin
7508218Sconklin/* Entry points for GNU code.  */
7509218Sconklin
7510218Sconklin/* re_compile_pattern is the GNU regular expression compiler: it
7511218Sconklin   compiles PATTERN (of length SIZE) and puts the result in BUFP.
7512218Sconklin   Returns 0 if the pattern was valid, otherwise an error string.
7513126209Sache
7514218Sconklin   Assumes the `allocated' (and perhaps `buffer') and `translate' fields
7515218Sconklin   are set in BUFP on entry.
7516126209Sache
7517218Sconklin   We call regex_compile to do the actual compilation.  */
7518218Sconklin
7519218Sconklinconst char *
7520218Sconklinre_compile_pattern (pattern, length, bufp)
7521218Sconklin     const char *pattern;
7522126209Sache     size_t length;
7523218Sconklin     struct re_pattern_buffer *bufp;
7524218Sconklin{
7525218Sconklin  reg_errcode_t ret;
7526126209Sache
7527218Sconklin  /* GNU code is written to assume at least RE_NREGS registers will be set
7528218Sconklin     (and at least one extra will be -1).  */
7529218Sconklin  bufp->regs_allocated = REGS_UNALLOCATED;
7530126209Sache
7531218Sconklin  /* And GNU code determines whether or not to get register information
7532218Sconklin     by passing null for the REGS argument to re_match, etc., not by
7533218Sconklin     setting no_sub.  */
7534218Sconklin  bufp->no_sub = 0;
7535126209Sache
7536218Sconklin  /* Match anchors at newline.  */
7537218Sconklin  bufp->newline_anchor = 1;
7538126209Sache
7539218Sconklin  ret = regex_compile (pattern, length, re_syntax_options, bufp);
7540218Sconklin
7541126209Sache  if (!ret)
7542126209Sache    return NULL;
7543126209Sache  return gettext (re_error_msgid + re_error_msgid_idx[(int) ret]);
7544126209Sache}
7545126209Sache#ifdef _LIBC
7546126209Sacheweak_alias (__re_compile_pattern, re_compile_pattern)
7547126209Sache#endif
7548218Sconklin
7549218Sconklin/* Entry points compatible with 4.2 BSD regex library.  We don't define
7550126209Sache   them unless specifically requested.  */
7551218Sconklin
7552126209Sache#if defined _REGEX_RE_COMP || defined _LIBC
7553218Sconklin
7554218Sconklin/* BSD has one and only one pattern buffer.  */
7555218Sconklinstatic struct re_pattern_buffer re_comp_buf;
7556218Sconklin
7557218Sconklinchar *
7558126209Sache#ifdef _LIBC
7559126209Sache/* Make these definitions weak in libc, so POSIX programs can redefine
7560126209Sache   these names if they don't use our functions, and still use
7561126209Sache   regcomp/regexec below without link errors.  */
7562126209Sacheweak_function
7563126209Sache#endif
7564218Sconklinre_comp (s)
7565218Sconklin    const char *s;
7566218Sconklin{
7567218Sconklin  reg_errcode_t ret;
7568126209Sache
7569218Sconklin  if (!s)
7570218Sconklin    {
7571218Sconklin      if (!re_comp_buf.buffer)
7572126209Sache	return gettext ("No previous regular expression");
7573218Sconklin      return 0;
7574218Sconklin    }
7575218Sconklin
7576218Sconklin  if (!re_comp_buf.buffer)
7577218Sconklin    {
7578218Sconklin      re_comp_buf.buffer = (unsigned char *) malloc (200);
7579218Sconklin      if (re_comp_buf.buffer == NULL)
7580126209Sache        return (char *) gettext (re_error_msgid
7581126209Sache				 + re_error_msgid_idx[(int) REG_ESPACE]);
7582218Sconklin      re_comp_buf.allocated = 200;
7583218Sconklin
7584218Sconklin      re_comp_buf.fastmap = (char *) malloc (1 << BYTEWIDTH);
7585218Sconklin      if (re_comp_buf.fastmap == NULL)
7586126209Sache	return (char *) gettext (re_error_msgid
7587126209Sache				 + re_error_msgid_idx[(int) REG_ESPACE]);
7588218Sconklin    }
7589218Sconklin
7590218Sconklin  /* Since `re_exec' always passes NULL for the `regs' argument, we
7591218Sconklin     don't need to initialize the pattern buffer fields which affect it.  */
7592218Sconklin
7593218Sconklin  /* Match anchors at newlines.  */
7594218Sconklin  re_comp_buf.newline_anchor = 1;
7595218Sconklin
7596218Sconklin  ret = regex_compile (s, strlen (s), re_syntax_options, &re_comp_buf);
7597126209Sache
7598126209Sache  if (!ret)
7599126209Sache    return NULL;
7600126209Sache
7601126209Sache  /* Yes, we're discarding `const' here if !HAVE_LIBINTL.  */
7602126209Sache  return (char *) gettext (re_error_msgid + re_error_msgid_idx[(int) ret]);
7603218Sconklin}
7604218Sconklin
7605218Sconklin
7606218Sconklinint
7607126209Sache#ifdef _LIBC
7608126209Sacheweak_function
7609126209Sache#endif
7610218Sconklinre_exec (s)
7611218Sconklin    const char *s;
7612218Sconklin{
7613218Sconklin  const int len = strlen (s);
7614218Sconklin  return
7615218Sconklin    0 <= re_search (&re_comp_buf, s, len, 0, len, (struct re_registers *) 0);
7616218Sconklin}
7617126209Sache
7618126209Sache#endif /* _REGEX_RE_COMP */
7619218Sconklin
7620218Sconklin/* POSIX.2 functions.  Don't define these for Emacs.  */
7621218Sconklin
7622218Sconklin#ifndef emacs
7623218Sconklin
7624218Sconklin/* regcomp takes a regular expression as a string and compiles it.
7625218Sconklin
7626218Sconklin   PREG is a regex_t *.  We do not expect any fields to be initialized,
7627218Sconklin   since POSIX says we shouldn't.  Thus, we set
7628218Sconklin
7629218Sconklin     `buffer' to the compiled pattern;
7630218Sconklin     `used' to the length of the compiled pattern;
7631218Sconklin     `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
7632218Sconklin       REG_EXTENDED bit in CFLAGS is set; otherwise, to
7633218Sconklin       RE_SYNTAX_POSIX_BASIC;
7634218Sconklin     `newline_anchor' to REG_NEWLINE being set in CFLAGS;
7635126209Sache     `fastmap' to an allocated space for the fastmap;
7636126209Sache     `fastmap_accurate' to zero;
7637218Sconklin     `re_nsub' to the number of subexpressions in PATTERN.
7638218Sconklin
7639218Sconklin   PATTERN is the address of the pattern string.
7640218Sconklin
7641218Sconklin   CFLAGS is a series of bits which affect compilation.
7642218Sconklin
7643218Sconklin     If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
7644218Sconklin     use POSIX basic syntax.
7645218Sconklin
7646218Sconklin     If REG_NEWLINE is set, then . and [^...] don't match newline.
7647218Sconklin     Also, regexec will try a match beginning after every newline.
7648218Sconklin
7649218Sconklin     If REG_ICASE is set, then we considers upper- and lowercase
7650218Sconklin     versions of letters to be equivalent when matching.
7651218Sconklin
7652218Sconklin     If REG_NOSUB is set, then when PREG is passed to regexec, that
7653218Sconklin     routine will report only success or failure, and nothing about the
7654218Sconklin     registers.
7655218Sconklin
7656218Sconklin   It returns 0 if it succeeds, nonzero if it doesn't.  (See regex.h for
7657218Sconklin   the return codes and their meanings.)  */
7658218Sconklin
7659218Sconklinint
7660218Sconklinregcomp (preg, pattern, cflags)
7661218Sconklin    regex_t *preg;
7662126209Sache    const char *pattern;
7663218Sconklin    int cflags;
7664218Sconklin{
7665218Sconklin  reg_errcode_t ret;
7666126209Sache  reg_syntax_t syntax
7667218Sconklin    = (cflags & REG_EXTENDED) ?
7668218Sconklin      RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC;
7669218Sconklin
7670218Sconklin  /* regex_compile will allocate the space for the compiled pattern.  */
7671218Sconklin  preg->buffer = 0;
7672218Sconklin  preg->allocated = 0;
7673126209Sache  preg->used = 0;
7674126209Sache
7675126209Sache  /* Try to allocate space for the fastmap.  */
7676126209Sache  preg->fastmap = (char *) malloc (1 << BYTEWIDTH);
7677126209Sache
7678218Sconklin  if (cflags & REG_ICASE)
7679218Sconklin    {
7680218Sconklin      unsigned i;
7681126209Sache
7682126209Sache      preg->translate
7683126209Sache	= (RE_TRANSLATE_TYPE) malloc (CHAR_SET_SIZE
7684126209Sache				      * sizeof (*(RE_TRANSLATE_TYPE)0));
7685218Sconklin      if (preg->translate == NULL)
7686218Sconklin        return (int) REG_ESPACE;
7687218Sconklin
7688218Sconklin      /* Map uppercase characters to corresponding lowercase ones.  */
7689218Sconklin      for (i = 0; i < CHAR_SET_SIZE; i++)
7690126209Sache        preg->translate[i] = ISUPPER (i) ? TOLOWER (i) : i;
7691218Sconklin    }
7692218Sconklin  else
7693218Sconklin    preg->translate = NULL;
7694218Sconklin
7695218Sconklin  /* If REG_NEWLINE is set, newlines are treated differently.  */
7696218Sconklin  if (cflags & REG_NEWLINE)
7697218Sconklin    { /* REG_NEWLINE implies neither . nor [^...] match newline.  */
7698218Sconklin      syntax &= ~RE_DOT_NEWLINE;
7699218Sconklin      syntax |= RE_HAT_LISTS_NOT_NEWLINE;
7700218Sconklin      /* It also changes the matching behavior.  */
7701218Sconklin      preg->newline_anchor = 1;
7702218Sconklin    }
7703218Sconklin  else
7704218Sconklin    preg->newline_anchor = 0;
7705218Sconklin
7706218Sconklin  preg->no_sub = !!(cflags & REG_NOSUB);
7707218Sconklin
7708126209Sache  /* POSIX says a null character in the pattern terminates it, so we
7709218Sconklin     can use strlen here in compiling the pattern.  */
7710218Sconklin  ret = regex_compile (pattern, strlen (pattern), syntax, preg);
7711126209Sache
7712218Sconklin  /* POSIX doesn't distinguish between an unmatched open-group and an
7713218Sconklin     unmatched close-group: both are REG_EPAREN.  */
7714218Sconklin  if (ret == REG_ERPAREN) ret = REG_EPAREN;
7715126209Sache
7716126209Sache  if (ret == REG_NOERROR && preg->fastmap)
7717126209Sache    {
7718126209Sache      /* Compute the fastmap now, since regexec cannot modify the pattern
7719126209Sache	 buffer.  */
7720126209Sache      if (re_compile_fastmap (preg) == -2)
7721126209Sache	{
7722131543Stjr	  /* Some error occurred while computing the fastmap, just forget
7723126209Sache	     about it.  */
7724126209Sache	  free (preg->fastmap);
7725126209Sache	  preg->fastmap = NULL;
7726126209Sache	}
7727126209Sache    }
7728126209Sache
7729218Sconklin  return (int) ret;
7730218Sconklin}
7731126209Sache#ifdef _LIBC
7732126209Sacheweak_alias (__regcomp, regcomp)
7733126209Sache#endif
7734218Sconklin
7735218Sconklin
7736218Sconklin/* regexec searches for a given pattern, specified by PREG, in the
7737218Sconklin   string STRING.
7738126209Sache
7739218Sconklin   If NMATCH is zero or REG_NOSUB was set in the cflags argument to
7740218Sconklin   `regcomp', we ignore PMATCH.  Otherwise, we assume PMATCH has at
7741218Sconklin   least NMATCH elements, and we set them to the offsets of the
7742218Sconklin   corresponding matched substrings.
7743126209Sache
7744218Sconklin   EFLAGS specifies `execution flags' which affect matching: if
7745218Sconklin   REG_NOTBOL is set, then ^ does not match at the beginning of the
7746218Sconklin   string; if REG_NOTEOL is set, then $ does not match at the end.
7747126209Sache
7748218Sconklin   We return 0 if we find a match and REG_NOMATCH if not.  */
7749218Sconklin
7750218Sconklinint
7751218Sconklinregexec (preg, string, nmatch, pmatch, eflags)
7752218Sconklin    const regex_t *preg;
7753126209Sache    const char *string;
7754126209Sache    size_t nmatch;
7755126209Sache    regmatch_t pmatch[];
7756218Sconklin    int eflags;
7757218Sconklin{
7758218Sconklin  int ret;
7759218Sconklin  struct re_registers regs;
7760218Sconklin  regex_t private_preg;
7761218Sconklin  int len = strlen (string);
7762218Sconklin  boolean want_reg_info = !preg->no_sub && nmatch > 0;
7763218Sconklin
7764218Sconklin  private_preg = *preg;
7765126209Sache
7766218Sconklin  private_preg.not_bol = !!(eflags & REG_NOTBOL);
7767218Sconklin  private_preg.not_eol = !!(eflags & REG_NOTEOL);
7768126209Sache
7769218Sconklin  /* The user has told us exactly how many registers to return
7770218Sconklin     information about, via `nmatch'.  We have to pass that on to the
7771218Sconklin     matching routines.  */
7772218Sconklin  private_preg.regs_allocated = REGS_FIXED;
7773126209Sache
7774218Sconklin  if (want_reg_info)
7775218Sconklin    {
7776218Sconklin      regs.num_regs = nmatch;
7777126209Sache      regs.start = TALLOC (nmatch * 2, regoff_t);
7778126209Sache      if (regs.start == NULL)
7779218Sconklin        return (int) REG_NOMATCH;
7780126209Sache      regs.end = regs.start + nmatch;
7781218Sconklin    }
7782218Sconklin
7783218Sconklin  /* Perform the searching operation.  */
7784218Sconklin  ret = re_search (&private_preg, string, len,
7785218Sconklin                   /* start: */ 0, /* range: */ len,
7786218Sconklin                   want_reg_info ? &regs : (struct re_registers *) 0);
7787126209Sache
7788218Sconklin  /* Copy the register information to the POSIX structure.  */
7789218Sconklin  if (want_reg_info)
7790218Sconklin    {
7791218Sconklin      if (ret >= 0)
7792218Sconklin        {
7793218Sconklin          unsigned r;
7794218Sconklin
7795218Sconklin          for (r = 0; r < nmatch; r++)
7796218Sconklin            {
7797218Sconklin              pmatch[r].rm_so = regs.start[r];
7798218Sconklin              pmatch[r].rm_eo = regs.end[r];
7799218Sconklin            }
7800218Sconklin        }
7801218Sconklin
7802218Sconklin      /* If we needed the temporary register info, free the space now.  */
7803218Sconklin      free (regs.start);
7804218Sconklin    }
7805218Sconklin
7806218Sconklin  /* We want zero return to mean success, unlike `re_search'.  */
7807218Sconklin  return ret >= 0 ? (int) REG_NOERROR : (int) REG_NOMATCH;
7808218Sconklin}
7809126209Sache#ifdef _LIBC
7810126209Sacheweak_alias (__regexec, regexec)
7811126209Sache#endif
7812218Sconklin
7813218Sconklin
7814218Sconklin/* Returns a message corresponding to an error code, ERRCODE, returned
7815218Sconklin   from either regcomp or regexec.   We don't use PREG here.  */
7816218Sconklin
7817218Sconklinsize_t
7818218Sconklinregerror (errcode, preg, errbuf, errbuf_size)
7819218Sconklin    int errcode;
7820218Sconklin    const regex_t *preg;
7821218Sconklin    char *errbuf;
7822218Sconklin    size_t errbuf_size;
7823218Sconklin{
7824218Sconklin  const char *msg;
7825218Sconklin  size_t msg_size;
7826218Sconklin
7827218Sconklin  if (errcode < 0
7828126209Sache      || errcode >= (int) (sizeof (re_error_msgid_idx)
7829126209Sache			   / sizeof (re_error_msgid_idx[0])))
7830126209Sache    /* Only error codes returned by the rest of the code should be passed
7831218Sconklin       to this routine.  If we are given anything else, or if other regex
7832218Sconklin       code generates an invalid error code, then the program has a bug.
7833218Sconklin       Dump core so we can fix it.  */
7834218Sconklin    abort ();
7835218Sconklin
7836126209Sache  msg = gettext (re_error_msgid + re_error_msgid_idx[errcode]);
7837218Sconklin
7838126209Sache  msg_size = strlen (msg) + 1; /* Includes the null.  */
7839218Sconklin
7840218Sconklin  if (errbuf_size != 0)
7841218Sconklin    {
7842218Sconklin      if (msg_size > errbuf_size)
7843218Sconklin        {
7844126209Sache#if defined HAVE_MEMPCPY || defined _LIBC
7845126209Sache	  *((char *) __mempcpy (errbuf, msg, errbuf_size - 1)) = '\0';
7846126209Sache#else
7847126209Sache          memcpy (errbuf, msg, errbuf_size - 1);
7848218Sconklin          errbuf[errbuf_size - 1] = 0;
7849126209Sache#endif
7850218Sconklin        }
7851218Sconklin      else
7852126209Sache        memcpy (errbuf, msg, msg_size);
7853218Sconklin    }
7854218Sconklin
7855218Sconklin  return msg_size;
7856218Sconklin}
7857126209Sache#ifdef _LIBC
7858126209Sacheweak_alias (__regerror, regerror)
7859126209Sache#endif
7860218Sconklin
7861218Sconklin
7862218Sconklin/* Free dynamically allocated space used by PREG.  */
7863218Sconklin
7864218Sconklinvoid
7865218Sconklinregfree (preg)
7866218Sconklin    regex_t *preg;
7867218Sconklin{
7868218Sconklin  if (preg->buffer != NULL)
7869218Sconklin    free (preg->buffer);
7870218Sconklin  preg->buffer = NULL;
7871126209Sache
7872218Sconklin  preg->allocated = 0;
7873218Sconklin  preg->used = 0;
7874218Sconklin
7875218Sconklin  if (preg->fastmap != NULL)
7876218Sconklin    free (preg->fastmap);
7877218Sconklin  preg->fastmap = NULL;
7878218Sconklin  preg->fastmap_accurate = 0;
7879218Sconklin
7880218Sconklin  if (preg->translate != NULL)
7881218Sconklin    free (preg->translate);
7882218Sconklin  preg->translate = NULL;
7883218Sconklin}
7884126209Sache#ifdef _LIBC
7885126209Sacheweak_alias (__regfree, regfree)
7886126209Sache#endif
7887218Sconklin
7888218Sconklin#endif /* not emacs  */
7889