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