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