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