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