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