* lisp/emacs-lisp/unsafep.el (unsafep): Handle backquoted forms.
[emacs.git] / src / regex.c
blob31f188efa9983fe7b5672eb3c1223a8f8e75ae21
1 /* Extended regular expression matching and search library, version
2 0.12. (Implements POSIX draft P1003.2/D11.2, except for some of the
3 internationalization features.)
5 Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001,
6 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
7 Free Software Foundation, Inc.
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 3, or (at your option)
12 any later version.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with this program; if not, write to the Free Software
21 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
22 USA. */
24 /* TODO:
25 - structure the opcode space into opcode+flag.
26 - merge with glibc's regex.[ch].
27 - replace (succeed_n + jump_n + set_number_at) with something that doesn't
28 need to modify the compiled regexp so that re_match can be reentrant.
29 - get rid of on_failure_jump_smart by doing the optimization in re_comp
30 rather than at run-time, so that re_match can be reentrant.
33 /* AIX requires this to be the first thing in the file. */
34 #if defined _AIX && !defined REGEX_MALLOC
35 #pragma alloca
36 #endif
38 #ifdef HAVE_CONFIG_H
39 # include <config.h>
40 #endif
42 #if defined STDC_HEADERS && !defined emacs
43 # include <stddef.h>
44 #else
45 /* We need this for `regex.h', and perhaps for the Emacs include files. */
46 # include <sys/types.h>
47 #endif
49 /* Whether to use ISO C Amendment 1 wide char functions.
50 Those should not be used for Emacs since it uses its own. */
51 #if defined _LIBC
52 #define WIDE_CHAR_SUPPORT 1
53 #else
54 #define WIDE_CHAR_SUPPORT \
55 (HAVE_WCTYPE_H && HAVE_WCHAR_H && HAVE_BTOWC && !emacs)
56 #endif
58 /* For platform which support the ISO C amendement 1 functionality we
59 support user defined character classes. */
60 #if WIDE_CHAR_SUPPORT
61 /* Solaris 2.5 has a bug: <wchar.h> must be included before <wctype.h>. */
62 # include <wchar.h>
63 # include <wctype.h>
64 #endif
66 #ifdef _LIBC
67 /* We have to keep the namespace clean. */
68 # define regfree(preg) __regfree (preg)
69 # define regexec(pr, st, nm, pm, ef) __regexec (pr, st, nm, pm, ef)
70 # define regcomp(preg, pattern, cflags) __regcomp (preg, pattern, cflags)
71 # define regerror(err_code, preg, errbuf, errbuf_size) \
72 __regerror(err_code, preg, errbuf, errbuf_size)
73 # define re_set_registers(bu, re, nu, st, en) \
74 __re_set_registers (bu, re, nu, st, en)
75 # define re_match_2(bufp, string1, size1, string2, size2, pos, regs, stop) \
76 __re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
77 # define re_match(bufp, string, size, pos, regs) \
78 __re_match (bufp, string, size, pos, regs)
79 # define re_search(bufp, string, size, startpos, range, regs) \
80 __re_search (bufp, string, size, startpos, range, regs)
81 # define re_compile_pattern(pattern, length, bufp) \
82 __re_compile_pattern (pattern, length, bufp)
83 # define re_set_syntax(syntax) __re_set_syntax (syntax)
84 # define re_search_2(bufp, st1, s1, st2, s2, startpos, range, regs, stop) \
85 __re_search_2 (bufp, st1, s1, st2, s2, startpos, range, regs, stop)
86 # define re_compile_fastmap(bufp) __re_compile_fastmap (bufp)
88 /* Make sure we call libc's function even if the user overrides them. */
89 # define btowc __btowc
90 # define iswctype __iswctype
91 # define wctype __wctype
93 # define WEAK_ALIAS(a,b) weak_alias (a, b)
95 /* We are also using some library internals. */
96 # include <locale/localeinfo.h>
97 # include <locale/elem-hash.h>
98 # include <langinfo.h>
99 #else
100 # define WEAK_ALIAS(a,b)
101 #endif
103 /* This is for other GNU distributions with internationalized messages. */
104 #if HAVE_LIBINTL_H || defined _LIBC
105 # include <libintl.h>
106 #else
107 # define gettext(msgid) (msgid)
108 #endif
110 #ifndef gettext_noop
111 /* This define is so xgettext can find the internationalizable
112 strings. */
113 # define gettext_noop(String) String
114 #endif
116 /* The `emacs' switch turns on certain matching commands
117 that make sense only in Emacs. */
118 #ifdef emacs
120 # include <setjmp.h>
121 # include "lisp.h"
122 # include "buffer.h"
124 /* Make syntax table lookup grant data in gl_state. */
125 # define SYNTAX_ENTRY_VIA_PROPERTY
127 # include "syntax.h"
128 # include "character.h"
129 # include "category.h"
131 # ifdef malloc
132 # undef malloc
133 # endif
134 # define malloc xmalloc
135 # ifdef realloc
136 # undef realloc
137 # endif
138 # define realloc xrealloc
139 # ifdef free
140 # undef free
141 # endif
142 # define free xfree
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)))
148 # define RE_MULTIBYTE_P(bufp) ((bufp)->multibyte)
149 # define RE_TARGET_MULTIBYTE_P(bufp) ((bufp)->target_multibyte)
150 # define RE_STRING_CHAR(p, multibyte) \
151 (multibyte ? (STRING_CHAR (p)) : (*(p)))
152 # define RE_STRING_CHAR_AND_LENGTH(p, len, multibyte) \
153 (multibyte ? (STRING_CHAR_AND_LENGTH (p, len)) : ((len) = 1, *(p)))
155 # define RE_CHAR_TO_MULTIBYTE(c) UNIBYTE_TO_CHAR (c)
157 # define RE_CHAR_TO_UNIBYTE(c) CHAR_TO_BYTE_SAFE (c)
159 /* Set C a (possibly converted to multibyte) character before P. P
160 points into a string which is the virtual concatenation of STR1
161 (which ends at END1) or STR2 (which ends at END2). */
162 # define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
163 do { \
164 if (target_multibyte) \
166 re_char *dtemp = (p) == (str2) ? (end1) : (p); \
167 re_char *dlimit = ((p) > (str2) && (p) <= (end2)) ? (str2) : (str1); \
168 while (dtemp-- > dlimit && !CHAR_HEAD_P (*dtemp)); \
169 c = STRING_CHAR (dtemp); \
171 else \
173 (c = ((p) == (str2) ? (end1) : (p))[-1]); \
174 (c) = RE_CHAR_TO_MULTIBYTE (c); \
176 } while (0)
178 /* Set C a (possibly converted to multibyte) character at P, and set
179 LEN to the byte length of that character. */
180 # define GET_CHAR_AFTER(c, p, len) \
181 do { \
182 if (target_multibyte) \
183 (c) = STRING_CHAR_AND_LENGTH (p, len); \
184 else \
186 (c) = *p; \
187 len = 1; \
188 (c) = RE_CHAR_TO_MULTIBYTE (c); \
190 } while (0)
192 #else /* not emacs */
194 /* If we are not linking with Emacs proper,
195 we can't use the relocating allocator
196 even if config.h says that we can. */
197 # undef REL_ALLOC
199 # ifdef HAVE_UNISTD_H
200 # include <unistd.h>
201 # endif
203 /* When used in Emacs's lib-src, we need xmalloc and xrealloc. */
205 void *
206 xmalloc (size_t size)
208 register void *val;
209 val = (void *) malloc (size);
210 if (!val && size)
212 write (2, "virtual memory exhausted\n", 25);
213 exit (1);
215 return val;
218 void *
219 xrealloc (void *block, size_t size)
221 register void *val;
222 /* We must call malloc explicitly when BLOCK is 0, since some
223 reallocs don't do this. */
224 if (! block)
225 val = (void *) malloc (size);
226 else
227 val = (void *) realloc (block, size);
228 if (!val && size)
230 write (2, "virtual memory exhausted\n", 25);
231 exit (1);
233 return val;
236 # ifdef malloc
237 # undef malloc
238 # endif
239 # define malloc xmalloc
240 # ifdef realloc
241 # undef realloc
242 # endif
243 # define realloc xrealloc
245 /* This is the normal way of making sure we have memcpy, memcmp and memset. */
246 # if defined HAVE_STRING_H || defined STDC_HEADERS || defined _LIBC
247 # include <string.h>
248 # else
249 # include <strings.h>
250 # ifndef memcmp
251 # define memcmp(s1, s2, n) bcmp (s1, s2, n)
252 # endif
253 # ifndef memcpy
254 # define memcpy(d, s, n) (bcopy (s, d, n), (d))
255 # endif
256 # endif
258 /* Define the syntax stuff for \<, \>, etc. */
260 /* Sword must be nonzero for the wordchar pattern commands in re_match_2. */
261 enum syntaxcode { Swhitespace = 0, Sword = 1, Ssymbol = 2 };
263 # define SWITCH_ENUM_CAST(x) (x)
265 /* Dummy macros for non-Emacs environments. */
266 # define CHAR_CHARSET(c) 0
267 # define CHARSET_LEADING_CODE_BASE(c) 0
268 # define MAX_MULTIBYTE_LENGTH 1
269 # define RE_MULTIBYTE_P(x) 0
270 # define RE_TARGET_MULTIBYTE_P(x) 0
271 # define WORD_BOUNDARY_P(c1, c2) (0)
272 # define CHAR_HEAD_P(p) (1)
273 # define SINGLE_BYTE_CHAR_P(c) (1)
274 # define SAME_CHARSET_P(c1, c2) (1)
275 # define BYTES_BY_CHAR_HEAD(p) (1)
276 # define PREV_CHAR_BOUNDARY(p, limit) ((p)--)
277 # define STRING_CHAR(p) (*(p))
278 # define RE_STRING_CHAR(p, multibyte) STRING_CHAR (p)
279 # define CHAR_STRING(c, s) (*(s) = (c), 1)
280 # define STRING_CHAR_AND_LENGTH(p, actual_len) ((actual_len) = 1, *(p))
281 # define RE_STRING_CHAR_AND_LENGTH(p, len, multibyte) STRING_CHAR_AND_LENGTH (p, len)
282 # define RE_CHAR_TO_MULTIBYTE(c) (c)
283 # define RE_CHAR_TO_UNIBYTE(c) (c)
284 # define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
285 (c = ((p) == (str2) ? *((end1) - 1) : *((p) - 1)))
286 # define GET_CHAR_AFTER(c, p, len) \
287 (c = *p, len = 1)
288 # define MAKE_CHAR(charset, c1, c2) (c1)
289 # define BYTE8_TO_CHAR(c) (c)
290 # define CHAR_BYTE8_P(c) (0)
291 # define CHAR_LEADING_CODE(c) (c)
293 #endif /* not emacs */
295 #ifndef RE_TRANSLATE
296 # define RE_TRANSLATE(TBL, C) ((unsigned char)(TBL)[C])
297 # define RE_TRANSLATE_P(TBL) (TBL)
298 #endif
300 /* Get the interface, including the syntax bits. */
301 #include "regex.h"
303 /* isalpha etc. are used for the character classes. */
304 #include <ctype.h>
306 #ifdef emacs
308 /* 1 if C is an ASCII character. */
309 # define IS_REAL_ASCII(c) ((c) < 0200)
311 /* 1 if C is a unibyte character. */
312 # define ISUNIBYTE(c) (SINGLE_BYTE_CHAR_P ((c)))
314 /* The Emacs definitions should not be directly affected by locales. */
316 /* In Emacs, these are only used for single-byte characters. */
317 # define ISDIGIT(c) ((c) >= '0' && (c) <= '9')
318 # define ISCNTRL(c) ((c) < ' ')
319 # define ISXDIGIT(c) (((c) >= '0' && (c) <= '9') \
320 || ((c) >= 'a' && (c) <= 'f') \
321 || ((c) >= 'A' && (c) <= 'F'))
323 /* This is only used for single-byte characters. */
324 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
326 /* The rest must handle multibyte characters. */
328 # define ISGRAPH(c) (SINGLE_BYTE_CHAR_P (c) \
329 ? (c) > ' ' && !((c) >= 0177 && (c) <= 0237) \
330 : 1)
332 # define ISPRINT(c) (SINGLE_BYTE_CHAR_P (c) \
333 ? (c) >= ' ' && !((c) >= 0177 && (c) <= 0237) \
334 : 1)
336 # define ISALNUM(c) (IS_REAL_ASCII (c) \
337 ? (((c) >= 'a' && (c) <= 'z') \
338 || ((c) >= 'A' && (c) <= 'Z') \
339 || ((c) >= '0' && (c) <= '9')) \
340 : SYNTAX (c) == Sword)
342 # define ISALPHA(c) (IS_REAL_ASCII (c) \
343 ? (((c) >= 'a' && (c) <= 'z') \
344 || ((c) >= 'A' && (c) <= 'Z')) \
345 : SYNTAX (c) == Sword)
347 # define ISLOWER(c) (LOWERCASEP (c))
349 # define ISPUNCT(c) (IS_REAL_ASCII (c) \
350 ? ((c) > ' ' && (c) < 0177 \
351 && !(((c) >= 'a' && (c) <= 'z') \
352 || ((c) >= 'A' && (c) <= 'Z') \
353 || ((c) >= '0' && (c) <= '9'))) \
354 : SYNTAX (c) != Sword)
356 # define ISSPACE(c) (SYNTAX (c) == Swhitespace)
358 # define ISUPPER(c) (UPPERCASEP (c))
360 # define ISWORD(c) (SYNTAX (c) == Sword)
362 #else /* not emacs */
364 /* Jim Meyering writes:
366 "... Some ctype macros are valid only for character codes that
367 isascii says are ASCII (SGI's IRIX-4.0.5 is one such system --when
368 using /bin/cc or gcc but without giving an ansi option). So, all
369 ctype uses should be through macros like ISPRINT... If
370 STDC_HEADERS is defined, then autoconf has verified that the ctype
371 macros don't need to be guarded with references to isascii. ...
372 Defining isascii to 1 should let any compiler worth its salt
373 eliminate the && through constant folding."
374 Solaris defines some of these symbols so we must undefine them first. */
376 # undef ISASCII
377 # if defined STDC_HEADERS || (!defined isascii && !defined HAVE_ISASCII)
378 # define ISASCII(c) 1
379 # else
380 # define ISASCII(c) isascii(c)
381 # endif
383 /* 1 if C is an ASCII character. */
384 # define IS_REAL_ASCII(c) ((c) < 0200)
386 /* This distinction is not meaningful, except in Emacs. */
387 # define ISUNIBYTE(c) 1
389 # ifdef isblank
390 # define ISBLANK(c) (ISASCII (c) && isblank (c))
391 # else
392 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
393 # endif
394 # ifdef isgraph
395 # define ISGRAPH(c) (ISASCII (c) && isgraph (c))
396 # else
397 # define ISGRAPH(c) (ISASCII (c) && isprint (c) && !isspace (c))
398 # endif
400 # undef ISPRINT
401 # define ISPRINT(c) (ISASCII (c) && isprint (c))
402 # define ISDIGIT(c) (ISASCII (c) && isdigit (c))
403 # define ISALNUM(c) (ISASCII (c) && isalnum (c))
404 # define ISALPHA(c) (ISASCII (c) && isalpha (c))
405 # define ISCNTRL(c) (ISASCII (c) && iscntrl (c))
406 # define ISLOWER(c) (ISASCII (c) && islower (c))
407 # define ISPUNCT(c) (ISASCII (c) && ispunct (c))
408 # define ISSPACE(c) (ISASCII (c) && isspace (c))
409 # define ISUPPER(c) (ISASCII (c) && isupper (c))
410 # define ISXDIGIT(c) (ISASCII (c) && isxdigit (c))
412 # define ISWORD(c) ISALPHA(c)
414 # ifdef _tolower
415 # define TOLOWER(c) _tolower(c)
416 # else
417 # define TOLOWER(c) tolower(c)
418 # endif
420 /* How many characters in the character set. */
421 # define CHAR_SET_SIZE 256
423 # ifdef SYNTAX_TABLE
425 extern char *re_syntax_table;
427 # else /* not SYNTAX_TABLE */
429 static char re_syntax_table[CHAR_SET_SIZE];
431 static void
432 init_syntax_once (void)
434 register int c;
435 static int done = 0;
437 if (done)
438 return;
440 memset (re_syntax_table, 0, sizeof re_syntax_table);
442 for (c = 0; c < CHAR_SET_SIZE; ++c)
443 if (ISALNUM (c))
444 re_syntax_table[c] = Sword;
446 re_syntax_table['_'] = Ssymbol;
448 done = 1;
451 # endif /* not SYNTAX_TABLE */
453 # define SYNTAX(c) re_syntax_table[(c)]
455 #endif /* not emacs */
457 #ifndef NULL
458 # define NULL (void *)0
459 #endif
461 /* We remove any previous definition of `SIGN_EXTEND_CHAR',
462 since ours (we hope) works properly with all combinations of
463 machines, compilers, `char' and `unsigned char' argument types.
464 (Per Bothner suggested the basic approach.) */
465 #undef SIGN_EXTEND_CHAR
466 #if __STDC__
467 # define SIGN_EXTEND_CHAR(c) ((signed char) (c))
468 #else /* not __STDC__ */
469 /* As in Harbison and Steele. */
470 # define SIGN_EXTEND_CHAR(c) ((((unsigned char) (c)) ^ 128) - 128)
471 #endif
473 /* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we
474 use `alloca' instead of `malloc'. This is because using malloc in
475 re_search* or re_match* could cause memory leaks when C-g is used in
476 Emacs; also, malloc is slower and causes storage fragmentation. On
477 the other hand, malloc is more portable, and easier to debug.
479 Because we sometimes use alloca, some routines have to be macros,
480 not functions -- `alloca'-allocated space disappears at the end of the
481 function it is called in. */
483 #ifdef REGEX_MALLOC
485 # define REGEX_ALLOCATE malloc
486 # define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
487 # define REGEX_FREE free
489 #else /* not REGEX_MALLOC */
491 /* Emacs already defines alloca, sometimes. */
492 # ifndef alloca
494 /* Make alloca work the best possible way. */
495 # ifdef __GNUC__
496 # define alloca __builtin_alloca
497 # else /* not __GNUC__ */
498 # ifdef HAVE_ALLOCA_H
499 # include <alloca.h>
500 # endif /* HAVE_ALLOCA_H */
501 # endif /* not __GNUC__ */
503 # endif /* not alloca */
505 # define REGEX_ALLOCATE alloca
507 /* Assumes a `char *destination' variable. */
508 # define REGEX_REALLOCATE(source, osize, nsize) \
509 (destination = (char *) alloca (nsize), \
510 memcpy (destination, source, osize))
512 /* No need to do anything to free, after alloca. */
513 # define REGEX_FREE(arg) ((void)0) /* Do nothing! But inhibit gcc warning. */
515 #endif /* not REGEX_MALLOC */
517 /* Define how to allocate the failure stack. */
519 #if defined REL_ALLOC && defined REGEX_MALLOC
521 # define REGEX_ALLOCATE_STACK(size) \
522 r_alloc (&failure_stack_ptr, (size))
523 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
524 r_re_alloc (&failure_stack_ptr, (nsize))
525 # define REGEX_FREE_STACK(ptr) \
526 r_alloc_free (&failure_stack_ptr)
528 #else /* not using relocating allocator */
530 # ifdef REGEX_MALLOC
532 # define REGEX_ALLOCATE_STACK malloc
533 # define REGEX_REALLOCATE_STACK(source, osize, nsize) realloc (source, nsize)
534 # define REGEX_FREE_STACK free
536 # else /* not REGEX_MALLOC */
538 # define REGEX_ALLOCATE_STACK alloca
540 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
541 REGEX_REALLOCATE (source, osize, nsize)
542 /* No need to explicitly free anything. */
543 # define REGEX_FREE_STACK(arg) ((void)0)
545 # endif /* not REGEX_MALLOC */
546 #endif /* not using relocating allocator */
549 /* True if `size1' is non-NULL and PTR is pointing anywhere inside
550 `string1' or just past its end. This works if PTR is NULL, which is
551 a good thing. */
552 #define FIRST_STRING_P(ptr) \
553 (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
555 /* (Re)Allocate N items of type T using malloc, or fail. */
556 #define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
557 #define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
558 #define RETALLOC_IF(addr, n, t) \
559 if (addr) RETALLOC((addr), (n), t); else (addr) = TALLOC ((n), t)
560 #define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
562 #define BYTEWIDTH 8 /* In bits. */
564 #define STREQ(s1, s2) ((strcmp (s1, s2) == 0))
566 #undef MAX
567 #undef MIN
568 #define MAX(a, b) ((a) > (b) ? (a) : (b))
569 #define MIN(a, b) ((a) < (b) ? (a) : (b))
571 /* Type of source-pattern and string chars. */
572 typedef const unsigned char re_char;
574 typedef char boolean;
575 #define false 0
576 #define true 1
578 static int re_match_2_internal _RE_ARGS ((struct re_pattern_buffer *bufp,
579 re_char *string1, int size1,
580 re_char *string2, int size2,
581 int pos,
582 struct re_registers *regs,
583 int stop));
585 /* These are the command codes that appear in compiled regular
586 expressions. Some opcodes are followed by argument bytes. A
587 command code can specify any interpretation whatsoever for its
588 arguments. Zero bytes may appear in the compiled regular expression. */
590 typedef enum
592 no_op = 0,
594 /* Succeed right away--no more backtracking. */
595 succeed,
597 /* Followed by one byte giving n, then by n literal bytes. */
598 exactn,
600 /* Matches any (more or less) character. */
601 anychar,
603 /* Matches any one char belonging to specified set. First
604 following byte is number of bitmap bytes. Then come bytes
605 for a bitmap saying which chars are in. Bits in each byte
606 are ordered low-bit-first. A character is in the set if its
607 bit is 1. A character too large to have a bit in the map is
608 automatically not in the set.
610 If the length byte has the 0x80 bit set, then that stuff
611 is followed by a range table:
612 2 bytes of flags for character sets (low 8 bits, high 8 bits)
613 See RANGE_TABLE_WORK_BITS below.
614 2 bytes, the number of pairs that follow (upto 32767)
615 pairs, each 2 multibyte characters,
616 each multibyte character represented as 3 bytes. */
617 charset,
619 /* Same parameters as charset, but match any character that is
620 not one of those specified. */
621 charset_not,
623 /* Start remembering the text that is matched, for storing in a
624 register. Followed by one byte with the register number, in
625 the range 0 to one less than the pattern buffer's re_nsub
626 field. */
627 start_memory,
629 /* Stop remembering the text that is matched and store it in a
630 memory register. Followed by one byte with the register
631 number, in the range 0 to one less than `re_nsub' in the
632 pattern buffer. */
633 stop_memory,
635 /* Match a duplicate of something remembered. Followed by one
636 byte containing the register number. */
637 duplicate,
639 /* Fail unless at beginning of line. */
640 begline,
642 /* Fail unless at end of line. */
643 endline,
645 /* Succeeds if at beginning of buffer (if emacs) or at beginning
646 of string to be matched (if not). */
647 begbuf,
649 /* Analogously, for end of buffer/string. */
650 endbuf,
652 /* Followed by two byte relative address to which to jump. */
653 jump,
655 /* Followed by two-byte relative address of place to resume at
656 in case of failure. */
657 on_failure_jump,
659 /* Like on_failure_jump, but pushes a placeholder instead of the
660 current string position when executed. */
661 on_failure_keep_string_jump,
663 /* Just like `on_failure_jump', except that it checks that we
664 don't get stuck in an infinite loop (matching an empty string
665 indefinitely). */
666 on_failure_jump_loop,
668 /* Just like `on_failure_jump_loop', except that it checks for
669 a different kind of loop (the kind that shows up with non-greedy
670 operators). This operation has to be immediately preceded
671 by a `no_op'. */
672 on_failure_jump_nastyloop,
674 /* A smart `on_failure_jump' used for greedy * and + operators.
675 It analyses the loop before which it is put and if the
676 loop does not require backtracking, it changes itself to
677 `on_failure_keep_string_jump' and short-circuits the loop,
678 else it just defaults to changing itself into `on_failure_jump'.
679 It assumes that it is pointing to just past a `jump'. */
680 on_failure_jump_smart,
682 /* Followed by two-byte relative address and two-byte number n.
683 After matching N times, jump to the address upon failure.
684 Does not work if N starts at 0: use on_failure_jump_loop
685 instead. */
686 succeed_n,
688 /* Followed by two-byte relative address, and two-byte number n.
689 Jump to the address N times, then fail. */
690 jump_n,
692 /* Set the following two-byte relative address to the
693 subsequent two-byte number. The address *includes* the two
694 bytes of number. */
695 set_number_at,
697 wordbeg, /* Succeeds if at word beginning. */
698 wordend, /* Succeeds if at word end. */
700 wordbound, /* Succeeds if at a word boundary. */
701 notwordbound, /* Succeeds if not at a word boundary. */
703 symbeg, /* Succeeds if at symbol beginning. */
704 symend, /* Succeeds if at symbol end. */
706 /* Matches any character whose syntax is specified. Followed by
707 a byte which contains a syntax code, e.g., Sword. */
708 syntaxspec,
710 /* Matches any character whose syntax is not that specified. */
711 notsyntaxspec
713 #ifdef emacs
714 ,before_dot, /* Succeeds if before point. */
715 at_dot, /* Succeeds if at point. */
716 after_dot, /* Succeeds if after point. */
718 /* Matches any character whose category-set contains the specified
719 category. The operator is followed by a byte which contains a
720 category code (mnemonic ASCII character). */
721 categoryspec,
723 /* Matches any character whose category-set does not contain the
724 specified category. The operator is followed by a byte which
725 contains the category code (mnemonic ASCII character). */
726 notcategoryspec
727 #endif /* emacs */
728 } re_opcode_t;
730 /* Common operations on the compiled pattern. */
732 /* Store NUMBER in two contiguous bytes starting at DESTINATION. */
734 #define STORE_NUMBER(destination, number) \
735 do { \
736 (destination)[0] = (number) & 0377; \
737 (destination)[1] = (number) >> 8; \
738 } while (0)
740 /* Same as STORE_NUMBER, except increment DESTINATION to
741 the byte after where the number is stored. Therefore, DESTINATION
742 must be an lvalue. */
744 #define STORE_NUMBER_AND_INCR(destination, number) \
745 do { \
746 STORE_NUMBER (destination, number); \
747 (destination) += 2; \
748 } while (0)
750 /* Put into DESTINATION a number stored in two contiguous bytes starting
751 at SOURCE. */
753 #define EXTRACT_NUMBER(destination, source) \
754 do { \
755 (destination) = *(source) & 0377; \
756 (destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8; \
757 } while (0)
759 #ifdef DEBUG
760 static void extract_number _RE_ARGS ((int *dest, re_char *source));
761 static void
762 extract_number (dest, source)
763 int *dest;
764 re_char *source;
766 int temp = SIGN_EXTEND_CHAR (*(source + 1));
767 *dest = *source & 0377;
768 *dest += temp << 8;
771 # ifndef EXTRACT_MACROS /* To debug the macros. */
772 # undef EXTRACT_NUMBER
773 # define EXTRACT_NUMBER(dest, src) extract_number (&dest, src)
774 # endif /* not EXTRACT_MACROS */
776 #endif /* DEBUG */
778 /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
779 SOURCE must be an lvalue. */
781 #define EXTRACT_NUMBER_AND_INCR(destination, source) \
782 do { \
783 EXTRACT_NUMBER (destination, source); \
784 (source) += 2; \
785 } while (0)
787 #ifdef DEBUG
788 static void extract_number_and_incr _RE_ARGS ((int *destination,
789 re_char **source));
790 static void
791 extract_number_and_incr (destination, source)
792 int *destination;
793 re_char **source;
795 extract_number (destination, *source);
796 *source += 2;
799 # ifndef EXTRACT_MACROS
800 # undef EXTRACT_NUMBER_AND_INCR
801 # define EXTRACT_NUMBER_AND_INCR(dest, src) \
802 extract_number_and_incr (&dest, &src)
803 # endif /* not EXTRACT_MACROS */
805 #endif /* DEBUG */
807 /* Store a multibyte character in three contiguous bytes starting
808 DESTINATION, and increment DESTINATION to the byte after where the
809 character is stored. Therefore, DESTINATION must be an lvalue. */
811 #define STORE_CHARACTER_AND_INCR(destination, character) \
812 do { \
813 (destination)[0] = (character) & 0377; \
814 (destination)[1] = ((character) >> 8) & 0377; \
815 (destination)[2] = (character) >> 16; \
816 (destination) += 3; \
817 } while (0)
819 /* Put into DESTINATION a character stored in three contiguous bytes
820 starting at SOURCE. */
822 #define EXTRACT_CHARACTER(destination, source) \
823 do { \
824 (destination) = ((source)[0] \
825 | ((source)[1] << 8) \
826 | ((source)[2] << 16)); \
827 } while (0)
830 /* Macros for charset. */
832 /* Size of bitmap of charset P in bytes. P is a start of charset,
833 i.e. *P is (re_opcode_t) charset or (re_opcode_t) charset_not. */
834 #define CHARSET_BITMAP_SIZE(p) ((p)[1] & 0x7F)
836 /* Nonzero if charset P has range table. */
837 #define CHARSET_RANGE_TABLE_EXISTS_P(p) ((p)[1] & 0x80)
839 /* Return the address of range table of charset P. But not the start
840 of table itself, but the before where the number of ranges is
841 stored. `2 +' means to skip re_opcode_t and size of bitmap,
842 and the 2 bytes of flags at the start of the range table. */
843 #define CHARSET_RANGE_TABLE(p) (&(p)[4 + CHARSET_BITMAP_SIZE (p)])
845 /* Extract the bit flags that start a range table. */
846 #define CHARSET_RANGE_TABLE_BITS(p) \
847 ((p)[2 + CHARSET_BITMAP_SIZE (p)] \
848 + (p)[3 + CHARSET_BITMAP_SIZE (p)] * 0x100)
850 /* Test if C is listed in the bitmap of charset P. */
851 #define CHARSET_LOOKUP_BITMAP(p, c) \
852 ((c) < CHARSET_BITMAP_SIZE (p) * BYTEWIDTH \
853 && (p)[2 + (c) / BYTEWIDTH] & (1 << ((c) % BYTEWIDTH)))
855 /* Return the address of end of RANGE_TABLE. COUNT is number of
856 ranges (which is a pair of (start, end)) in the RANGE_TABLE. `* 2'
857 is start of range and end of range. `* 3' is size of each start
858 and end. */
859 #define CHARSET_RANGE_TABLE_END(range_table, count) \
860 ((range_table) + (count) * 2 * 3)
862 /* Test if C is in RANGE_TABLE. A flag NOT is negated if C is in.
863 COUNT is number of ranges in RANGE_TABLE. */
864 #define CHARSET_LOOKUP_RANGE_TABLE_RAW(not, c, range_table, count) \
865 do \
867 re_wchar_t range_start, range_end; \
868 re_char *p; \
869 re_char *range_table_end \
870 = CHARSET_RANGE_TABLE_END ((range_table), (count)); \
872 for (p = (range_table); p < range_table_end; p += 2 * 3) \
874 EXTRACT_CHARACTER (range_start, p); \
875 EXTRACT_CHARACTER (range_end, p + 3); \
877 if (range_start <= (c) && (c) <= range_end) \
879 (not) = !(not); \
880 break; \
884 while (0)
886 /* Test if C is in range table of CHARSET. The flag NOT is negated if
887 C is listed in it. */
888 #define CHARSET_LOOKUP_RANGE_TABLE(not, c, charset) \
889 do \
891 /* Number of ranges in range table. */ \
892 int count; \
893 re_char *range_table = CHARSET_RANGE_TABLE (charset); \
895 EXTRACT_NUMBER_AND_INCR (count, range_table); \
896 CHARSET_LOOKUP_RANGE_TABLE_RAW ((not), (c), range_table, count); \
898 while (0)
900 /* If DEBUG is defined, Regex prints many voluminous messages about what
901 it is doing (if the variable `debug' is nonzero). If linked with the
902 main program in `iregex.c', you can enter patterns and strings
903 interactively. And if linked with the main program in `main.c' and
904 the other test files, you can run the already-written tests. */
906 #ifdef DEBUG
908 /* We use standard I/O for debugging. */
909 # include <stdio.h>
911 /* It is useful to test things that ``must'' be true when debugging. */
912 # include <assert.h>
914 static int debug = -100000;
916 # define DEBUG_STATEMENT(e) e
917 # define DEBUG_PRINT1(x) if (debug > 0) printf (x)
918 # define DEBUG_PRINT2(x1, x2) if (debug > 0) printf (x1, x2)
919 # define DEBUG_PRINT3(x1, x2, x3) if (debug > 0) printf (x1, x2, x3)
920 # define DEBUG_PRINT4(x1, x2, x3, x4) if (debug > 0) printf (x1, x2, x3, x4)
921 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
922 if (debug > 0) print_partial_compiled_pattern (s, e)
923 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
924 if (debug > 0) print_double_string (w, s1, sz1, s2, sz2)
927 /* Print the fastmap in human-readable form. */
929 void
930 print_fastmap (fastmap)
931 char *fastmap;
933 unsigned was_a_range = 0;
934 unsigned i = 0;
936 while (i < (1 << BYTEWIDTH))
938 if (fastmap[i++])
940 was_a_range = 0;
941 putchar (i - 1);
942 while (i < (1 << BYTEWIDTH) && fastmap[i])
944 was_a_range = 1;
945 i++;
947 if (was_a_range)
949 printf ("-");
950 putchar (i - 1);
954 putchar ('\n');
958 /* Print a compiled pattern string in human-readable form, starting at
959 the START pointer into it and ending just before the pointer END. */
961 void
962 print_partial_compiled_pattern (start, end)
963 re_char *start;
964 re_char *end;
966 int mcnt, mcnt2;
967 re_char *p = start;
968 re_char *pend = end;
970 if (start == NULL)
972 fprintf (stderr, "(null)\n");
973 return;
976 /* Loop over pattern commands. */
977 while (p < pend)
979 fprintf (stderr, "%d:\t", p - start);
981 switch ((re_opcode_t) *p++)
983 case no_op:
984 fprintf (stderr, "/no_op");
985 break;
987 case succeed:
988 fprintf (stderr, "/succeed");
989 break;
991 case exactn:
992 mcnt = *p++;
993 fprintf (stderr, "/exactn/%d", mcnt);
996 fprintf (stderr, "/%c", *p++);
998 while (--mcnt);
999 break;
1001 case start_memory:
1002 fprintf (stderr, "/start_memory/%d", *p++);
1003 break;
1005 case stop_memory:
1006 fprintf (stderr, "/stop_memory/%d", *p++);
1007 break;
1009 case duplicate:
1010 fprintf (stderr, "/duplicate/%d", *p++);
1011 break;
1013 case anychar:
1014 fprintf (stderr, "/anychar");
1015 break;
1017 case charset:
1018 case charset_not:
1020 register int c, last = -100;
1021 register int in_range = 0;
1022 int length = CHARSET_BITMAP_SIZE (p - 1);
1023 int has_range_table = CHARSET_RANGE_TABLE_EXISTS_P (p - 1);
1025 fprintf (stderr, "/charset [%s",
1026 (re_opcode_t) *(p - 1) == charset_not ? "^" : "");
1028 if (p + *p >= pend)
1029 fprintf (stderr, " !extends past end of pattern! ");
1031 for (c = 0; c < 256; c++)
1032 if (c / 8 < length
1033 && (p[1 + (c/8)] & (1 << (c % 8))))
1035 /* Are we starting a range? */
1036 if (last + 1 == c && ! in_range)
1038 fprintf (stderr, "-");
1039 in_range = 1;
1041 /* Have we broken a range? */
1042 else if (last + 1 != c && in_range)
1044 fprintf (stderr, "%c", last);
1045 in_range = 0;
1048 if (! in_range)
1049 fprintf (stderr, "%c", c);
1051 last = c;
1054 if (in_range)
1055 fprintf (stderr, "%c", last);
1057 fprintf (stderr, "]");
1059 p += 1 + length;
1061 if (has_range_table)
1063 int count;
1064 fprintf (stderr, "has-range-table");
1066 /* ??? Should print the range table; for now, just skip it. */
1067 p += 2; /* skip range table bits */
1068 EXTRACT_NUMBER_AND_INCR (count, p);
1069 p = CHARSET_RANGE_TABLE_END (p, count);
1072 break;
1074 case begline:
1075 fprintf (stderr, "/begline");
1076 break;
1078 case endline:
1079 fprintf (stderr, "/endline");
1080 break;
1082 case on_failure_jump:
1083 extract_number_and_incr (&mcnt, &p);
1084 fprintf (stderr, "/on_failure_jump to %d", p + mcnt - start);
1085 break;
1087 case on_failure_keep_string_jump:
1088 extract_number_and_incr (&mcnt, &p);
1089 fprintf (stderr, "/on_failure_keep_string_jump to %d", p + mcnt - start);
1090 break;
1092 case on_failure_jump_nastyloop:
1093 extract_number_and_incr (&mcnt, &p);
1094 fprintf (stderr, "/on_failure_jump_nastyloop to %d", p + mcnt - start);
1095 break;
1097 case on_failure_jump_loop:
1098 extract_number_and_incr (&mcnt, &p);
1099 fprintf (stderr, "/on_failure_jump_loop to %d", p + mcnt - start);
1100 break;
1102 case on_failure_jump_smart:
1103 extract_number_and_incr (&mcnt, &p);
1104 fprintf (stderr, "/on_failure_jump_smart to %d", p + mcnt - start);
1105 break;
1107 case jump:
1108 extract_number_and_incr (&mcnt, &p);
1109 fprintf (stderr, "/jump to %d", p + mcnt - start);
1110 break;
1112 case succeed_n:
1113 extract_number_and_incr (&mcnt, &p);
1114 extract_number_and_incr (&mcnt2, &p);
1115 fprintf (stderr, "/succeed_n to %d, %d times", p - 2 + mcnt - start, mcnt2);
1116 break;
1118 case jump_n:
1119 extract_number_and_incr (&mcnt, &p);
1120 extract_number_and_incr (&mcnt2, &p);
1121 fprintf (stderr, "/jump_n to %d, %d times", p - 2 + mcnt - start, mcnt2);
1122 break;
1124 case set_number_at:
1125 extract_number_and_incr (&mcnt, &p);
1126 extract_number_and_incr (&mcnt2, &p);
1127 fprintf (stderr, "/set_number_at location %d to %d", p - 2 + mcnt - start, mcnt2);
1128 break;
1130 case wordbound:
1131 fprintf (stderr, "/wordbound");
1132 break;
1134 case notwordbound:
1135 fprintf (stderr, "/notwordbound");
1136 break;
1138 case wordbeg:
1139 fprintf (stderr, "/wordbeg");
1140 break;
1142 case wordend:
1143 fprintf (stderr, "/wordend");
1144 break;
1146 case symbeg:
1147 fprintf (stderr, "/symbeg");
1148 break;
1150 case symend:
1151 fprintf (stderr, "/symend");
1152 break;
1154 case syntaxspec:
1155 fprintf (stderr, "/syntaxspec");
1156 mcnt = *p++;
1157 fprintf (stderr, "/%d", mcnt);
1158 break;
1160 case notsyntaxspec:
1161 fprintf (stderr, "/notsyntaxspec");
1162 mcnt = *p++;
1163 fprintf (stderr, "/%d", mcnt);
1164 break;
1166 # ifdef emacs
1167 case before_dot:
1168 fprintf (stderr, "/before_dot");
1169 break;
1171 case at_dot:
1172 fprintf (stderr, "/at_dot");
1173 break;
1175 case after_dot:
1176 fprintf (stderr, "/after_dot");
1177 break;
1179 case categoryspec:
1180 fprintf (stderr, "/categoryspec");
1181 mcnt = *p++;
1182 fprintf (stderr, "/%d", mcnt);
1183 break;
1185 case notcategoryspec:
1186 fprintf (stderr, "/notcategoryspec");
1187 mcnt = *p++;
1188 fprintf (stderr, "/%d", mcnt);
1189 break;
1190 # endif /* emacs */
1192 case begbuf:
1193 fprintf (stderr, "/begbuf");
1194 break;
1196 case endbuf:
1197 fprintf (stderr, "/endbuf");
1198 break;
1200 default:
1201 fprintf (stderr, "?%d", *(p-1));
1204 fprintf (stderr, "\n");
1207 fprintf (stderr, "%d:\tend of pattern.\n", p - start);
1211 void
1212 print_compiled_pattern (bufp)
1213 struct re_pattern_buffer *bufp;
1215 re_char *buffer = bufp->buffer;
1217 print_partial_compiled_pattern (buffer, buffer + bufp->used);
1218 printf ("%ld bytes used/%ld bytes allocated.\n",
1219 bufp->used, bufp->allocated);
1221 if (bufp->fastmap_accurate && bufp->fastmap)
1223 printf ("fastmap: ");
1224 print_fastmap (bufp->fastmap);
1227 printf ("re_nsub: %d\t", bufp->re_nsub);
1228 printf ("regs_alloc: %d\t", bufp->regs_allocated);
1229 printf ("can_be_null: %d\t", bufp->can_be_null);
1230 printf ("no_sub: %d\t", bufp->no_sub);
1231 printf ("not_bol: %d\t", bufp->not_bol);
1232 printf ("not_eol: %d\t", bufp->not_eol);
1233 printf ("syntax: %lx\n", bufp->syntax);
1234 fflush (stdout);
1235 /* Perhaps we should print the translate table? */
1239 void
1240 print_double_string (where, string1, size1, string2, size2)
1241 re_char *where;
1242 re_char *string1;
1243 re_char *string2;
1244 int size1;
1245 int size2;
1247 int this_char;
1249 if (where == NULL)
1250 printf ("(null)");
1251 else
1253 if (FIRST_STRING_P (where))
1255 for (this_char = where - string1; this_char < size1; this_char++)
1256 putchar (string1[this_char]);
1258 where = string2;
1261 for (this_char = where - string2; this_char < size2; this_char++)
1262 putchar (string2[this_char]);
1266 #else /* not DEBUG */
1268 # undef assert
1269 # define assert(e)
1271 # define DEBUG_STATEMENT(e)
1272 # define DEBUG_PRINT1(x)
1273 # define DEBUG_PRINT2(x1, x2)
1274 # define DEBUG_PRINT3(x1, x2, x3)
1275 # define DEBUG_PRINT4(x1, x2, x3, x4)
1276 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
1277 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
1279 #endif /* not DEBUG */
1281 /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
1282 also be assigned to arbitrarily: each pattern buffer stores its own
1283 syntax, so it can be changed between regex compilations. */
1284 /* This has no initializer because initialized variables in Emacs
1285 become read-only after dumping. */
1286 reg_syntax_t re_syntax_options;
1289 /* Specify the precise syntax of regexps for compilation. This provides
1290 for compatibility for various utilities which historically have
1291 different, incompatible syntaxes.
1293 The argument SYNTAX is a bit mask comprised of the various bits
1294 defined in regex.h. We return the old syntax. */
1296 reg_syntax_t
1297 re_set_syntax (reg_syntax_t syntax)
1299 reg_syntax_t ret = re_syntax_options;
1301 re_syntax_options = syntax;
1302 return ret;
1304 WEAK_ALIAS (__re_set_syntax, re_set_syntax)
1306 /* Regexp to use to replace spaces, or NULL meaning don't. */
1307 static re_char *whitespace_regexp;
1309 void
1310 re_set_whitespace_regexp (const char *regexp)
1312 whitespace_regexp = (re_char *) regexp;
1314 WEAK_ALIAS (__re_set_syntax, re_set_syntax)
1316 /* This table gives an error message for each of the error codes listed
1317 in regex.h. Obviously the order here has to be same as there.
1318 POSIX doesn't require that we do anything for REG_NOERROR,
1319 but why not be nice? */
1321 static const char *re_error_msgid[] =
1323 gettext_noop ("Success"), /* REG_NOERROR */
1324 gettext_noop ("No match"), /* REG_NOMATCH */
1325 gettext_noop ("Invalid regular expression"), /* REG_BADPAT */
1326 gettext_noop ("Invalid collation character"), /* REG_ECOLLATE */
1327 gettext_noop ("Invalid character class name"), /* REG_ECTYPE */
1328 gettext_noop ("Trailing backslash"), /* REG_EESCAPE */
1329 gettext_noop ("Invalid back reference"), /* REG_ESUBREG */
1330 gettext_noop ("Unmatched [ or [^"), /* REG_EBRACK */
1331 gettext_noop ("Unmatched ( or \\("), /* REG_EPAREN */
1332 gettext_noop ("Unmatched \\{"), /* REG_EBRACE */
1333 gettext_noop ("Invalid content of \\{\\}"), /* REG_BADBR */
1334 gettext_noop ("Invalid range end"), /* REG_ERANGE */
1335 gettext_noop ("Memory exhausted"), /* REG_ESPACE */
1336 gettext_noop ("Invalid preceding regular expression"), /* REG_BADRPT */
1337 gettext_noop ("Premature end of regular expression"), /* REG_EEND */
1338 gettext_noop ("Regular expression too big"), /* REG_ESIZE */
1339 gettext_noop ("Unmatched ) or \\)"), /* REG_ERPAREN */
1340 gettext_noop ("Range striding over charsets") /* REG_ERANGEX */
1343 /* Avoiding alloca during matching, to placate r_alloc. */
1345 /* Define MATCH_MAY_ALLOCATE unless we need to make sure that the
1346 searching and matching functions should not call alloca. On some
1347 systems, alloca is implemented in terms of malloc, and if we're
1348 using the relocating allocator routines, then malloc could cause a
1349 relocation, which might (if the strings being searched are in the
1350 ralloc heap) shift the data out from underneath the regexp
1351 routines.
1353 Here's another reason to avoid allocation: Emacs
1354 processes input from X in a signal handler; processing X input may
1355 call malloc; if input arrives while a matching routine is calling
1356 malloc, then we're scrod. But Emacs can't just block input while
1357 calling matching routines; then we don't notice interrupts when
1358 they come in. So, Emacs blocks input around all regexp calls
1359 except the matching calls, which it leaves unprotected, in the
1360 faith that they will not malloc. */
1362 /* Normally, this is fine. */
1363 #define MATCH_MAY_ALLOCATE
1365 /* The match routines may not allocate if (1) they would do it with malloc
1366 and (2) it's not safe for them to use malloc.
1367 Note that if REL_ALLOC is defined, matching would not use malloc for the
1368 failure stack, but we would still use it for the register vectors;
1369 so REL_ALLOC should not affect this. */
1370 #if defined REGEX_MALLOC && defined emacs
1371 # undef MATCH_MAY_ALLOCATE
1372 #endif
1375 /* Failure stack declarations and macros; both re_compile_fastmap and
1376 re_match_2 use a failure stack. These have to be macros because of
1377 REGEX_ALLOCATE_STACK. */
1380 /* Approximate number of failure points for which to initially allocate space
1381 when matching. If this number is exceeded, we allocate more
1382 space, so it is not a hard limit. */
1383 #ifndef INIT_FAILURE_ALLOC
1384 # define INIT_FAILURE_ALLOC 20
1385 #endif
1387 /* Roughly the maximum number of failure points on the stack. Would be
1388 exactly that if always used TYPICAL_FAILURE_SIZE items each time we failed.
1389 This is a variable only so users of regex can assign to it; we never
1390 change it ourselves. We always multiply it by TYPICAL_FAILURE_SIZE
1391 before using it, so it should probably be a byte-count instead. */
1392 # if defined MATCH_MAY_ALLOCATE
1393 /* Note that 4400 was enough to cause a crash on Alpha OSF/1,
1394 whose default stack limit is 2mb. In order for a larger
1395 value to work reliably, you have to try to make it accord
1396 with the process stack limit. */
1397 size_t re_max_failures = 40000;
1398 # else
1399 size_t re_max_failures = 4000;
1400 # endif
1402 union fail_stack_elt
1404 re_char *pointer;
1405 /* This should be the biggest `int' that's no bigger than a pointer. */
1406 long integer;
1409 typedef union fail_stack_elt fail_stack_elt_t;
1411 typedef struct
1413 fail_stack_elt_t *stack;
1414 size_t size;
1415 size_t avail; /* Offset of next open position. */
1416 size_t frame; /* Offset of the cur constructed frame. */
1417 } fail_stack_type;
1419 #define FAIL_STACK_EMPTY() (fail_stack.frame == 0)
1420 #define FAIL_STACK_FULL() (fail_stack.avail == fail_stack.size)
1423 /* Define macros to initialize and free the failure stack.
1424 Do `return -2' if the alloc fails. */
1426 #ifdef MATCH_MAY_ALLOCATE
1427 # define INIT_FAIL_STACK() \
1428 do { \
1429 fail_stack.stack = (fail_stack_elt_t *) \
1430 REGEX_ALLOCATE_STACK (INIT_FAILURE_ALLOC * TYPICAL_FAILURE_SIZE \
1431 * sizeof (fail_stack_elt_t)); \
1433 if (fail_stack.stack == NULL) \
1434 return -2; \
1436 fail_stack.size = INIT_FAILURE_ALLOC; \
1437 fail_stack.avail = 0; \
1438 fail_stack.frame = 0; \
1439 } while (0)
1441 # define RESET_FAIL_STACK() REGEX_FREE_STACK (fail_stack.stack)
1442 #else
1443 # define INIT_FAIL_STACK() \
1444 do { \
1445 fail_stack.avail = 0; \
1446 fail_stack.frame = 0; \
1447 } while (0)
1449 # define RESET_FAIL_STACK() ((void)0)
1450 #endif
1453 /* Double the size of FAIL_STACK, up to a limit
1454 which allows approximately `re_max_failures' items.
1456 Return 1 if succeeds, and 0 if either ran out of memory
1457 allocating space for it or it was already too large.
1459 REGEX_REALLOCATE_STACK requires `destination' be declared. */
1461 /* Factor to increase the failure stack size by
1462 when we increase it.
1463 This used to be 2, but 2 was too wasteful
1464 because the old discarded stacks added up to as much space
1465 were as ultimate, maximum-size stack. */
1466 #define FAIL_STACK_GROWTH_FACTOR 4
1468 #define GROW_FAIL_STACK(fail_stack) \
1469 (((fail_stack).size * sizeof (fail_stack_elt_t) \
1470 >= re_max_failures * TYPICAL_FAILURE_SIZE) \
1471 ? 0 \
1472 : ((fail_stack).stack \
1473 = (fail_stack_elt_t *) \
1474 REGEX_REALLOCATE_STACK ((fail_stack).stack, \
1475 (fail_stack).size * sizeof (fail_stack_elt_t), \
1476 MIN (re_max_failures * TYPICAL_FAILURE_SIZE, \
1477 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1478 * FAIL_STACK_GROWTH_FACTOR))), \
1480 (fail_stack).stack == NULL \
1481 ? 0 \
1482 : ((fail_stack).size \
1483 = (MIN (re_max_failures * TYPICAL_FAILURE_SIZE, \
1484 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1485 * FAIL_STACK_GROWTH_FACTOR)) \
1486 / sizeof (fail_stack_elt_t)), \
1487 1)))
1490 /* Push a pointer value onto the failure stack.
1491 Assumes the variable `fail_stack'. Probably should only
1492 be called from within `PUSH_FAILURE_POINT'. */
1493 #define PUSH_FAILURE_POINTER(item) \
1494 fail_stack.stack[fail_stack.avail++].pointer = (item)
1496 /* This pushes an integer-valued item onto the failure stack.
1497 Assumes the variable `fail_stack'. Probably should only
1498 be called from within `PUSH_FAILURE_POINT'. */
1499 #define PUSH_FAILURE_INT(item) \
1500 fail_stack.stack[fail_stack.avail++].integer = (item)
1502 /* Push a fail_stack_elt_t value onto the failure stack.
1503 Assumes the variable `fail_stack'. Probably should only
1504 be called from within `PUSH_FAILURE_POINT'. */
1505 #define PUSH_FAILURE_ELT(item) \
1506 fail_stack.stack[fail_stack.avail++] = (item)
1508 /* These three POP... operations complement the three PUSH... operations.
1509 All assume that `fail_stack' is nonempty. */
1510 #define POP_FAILURE_POINTER() fail_stack.stack[--fail_stack.avail].pointer
1511 #define POP_FAILURE_INT() fail_stack.stack[--fail_stack.avail].integer
1512 #define POP_FAILURE_ELT() fail_stack.stack[--fail_stack.avail]
1514 /* Individual items aside from the registers. */
1515 #define NUM_NONREG_ITEMS 3
1517 /* Used to examine the stack (to detect infinite loops). */
1518 #define FAILURE_PAT(h) fail_stack.stack[(h) - 1].pointer
1519 #define FAILURE_STR(h) (fail_stack.stack[(h) - 2].pointer)
1520 #define NEXT_FAILURE_HANDLE(h) fail_stack.stack[(h) - 3].integer
1521 #define TOP_FAILURE_HANDLE() fail_stack.frame
1524 #define ENSURE_FAIL_STACK(space) \
1525 while (REMAINING_AVAIL_SLOTS <= space) { \
1526 if (!GROW_FAIL_STACK (fail_stack)) \
1527 return -2; \
1528 DEBUG_PRINT2 ("\n Doubled stack; size now: %d\n", (fail_stack).size);\
1529 DEBUG_PRINT2 (" slots available: %d\n", REMAINING_AVAIL_SLOTS);\
1532 /* Push register NUM onto the stack. */
1533 #define PUSH_FAILURE_REG(num) \
1534 do { \
1535 char *destination; \
1536 ENSURE_FAIL_STACK(3); \
1537 DEBUG_PRINT4 (" Push reg %d (spanning %p -> %p)\n", \
1538 num, regstart[num], regend[num]); \
1539 PUSH_FAILURE_POINTER (regstart[num]); \
1540 PUSH_FAILURE_POINTER (regend[num]); \
1541 PUSH_FAILURE_INT (num); \
1542 } while (0)
1544 /* Change the counter's value to VAL, but make sure that it will
1545 be reset when backtracking. */
1546 #define PUSH_NUMBER(ptr,val) \
1547 do { \
1548 char *destination; \
1549 int c; \
1550 ENSURE_FAIL_STACK(3); \
1551 EXTRACT_NUMBER (c, ptr); \
1552 DEBUG_PRINT4 (" Push number %p = %d -> %d\n", ptr, c, val); \
1553 PUSH_FAILURE_INT (c); \
1554 PUSH_FAILURE_POINTER (ptr); \
1555 PUSH_FAILURE_INT (-1); \
1556 STORE_NUMBER (ptr, val); \
1557 } while (0)
1559 /* Pop a saved register off the stack. */
1560 #define POP_FAILURE_REG_OR_COUNT() \
1561 do { \
1562 int reg = POP_FAILURE_INT (); \
1563 if (reg == -1) \
1565 /* It's a counter. */ \
1566 /* Here, we discard `const', making re_match non-reentrant. */ \
1567 unsigned char *ptr = (unsigned char*) POP_FAILURE_POINTER (); \
1568 reg = POP_FAILURE_INT (); \
1569 STORE_NUMBER (ptr, reg); \
1570 DEBUG_PRINT3 (" Pop counter %p = %d\n", ptr, reg); \
1572 else \
1574 regend[reg] = POP_FAILURE_POINTER (); \
1575 regstart[reg] = POP_FAILURE_POINTER (); \
1576 DEBUG_PRINT4 (" Pop reg %d (spanning %p -> %p)\n", \
1577 reg, regstart[reg], regend[reg]); \
1579 } while (0)
1581 /* Check that we are not stuck in an infinite loop. */
1582 #define CHECK_INFINITE_LOOP(pat_cur, string_place) \
1583 do { \
1584 int failure = TOP_FAILURE_HANDLE (); \
1585 /* Check for infinite matching loops */ \
1586 while (failure > 0 \
1587 && (FAILURE_STR (failure) == string_place \
1588 || FAILURE_STR (failure) == NULL)) \
1590 assert (FAILURE_PAT (failure) >= bufp->buffer \
1591 && FAILURE_PAT (failure) <= bufp->buffer + bufp->used); \
1592 if (FAILURE_PAT (failure) == pat_cur) \
1594 cycle = 1; \
1595 break; \
1597 DEBUG_PRINT2 (" Other pattern: %p\n", FAILURE_PAT (failure)); \
1598 failure = NEXT_FAILURE_HANDLE(failure); \
1600 DEBUG_PRINT2 (" Other string: %p\n", FAILURE_STR (failure)); \
1601 } while (0)
1603 /* Push the information about the state we will need
1604 if we ever fail back to it.
1606 Requires variables fail_stack, regstart, regend and
1607 num_regs be declared. GROW_FAIL_STACK requires `destination' be
1608 declared.
1610 Does `return FAILURE_CODE' if runs out of memory. */
1612 #define PUSH_FAILURE_POINT(pattern, string_place) \
1613 do { \
1614 char *destination; \
1615 /* Must be int, so when we don't save any registers, the arithmetic \
1616 of 0 + -1 isn't done as unsigned. */ \
1618 DEBUG_STATEMENT (nfailure_points_pushed++); \
1619 DEBUG_PRINT1 ("\nPUSH_FAILURE_POINT:\n"); \
1620 DEBUG_PRINT2 (" Before push, next avail: %d\n", (fail_stack).avail); \
1621 DEBUG_PRINT2 (" size: %d\n", (fail_stack).size);\
1623 ENSURE_FAIL_STACK (NUM_NONREG_ITEMS); \
1625 DEBUG_PRINT1 ("\n"); \
1627 DEBUG_PRINT2 (" Push frame index: %d\n", fail_stack.frame); \
1628 PUSH_FAILURE_INT (fail_stack.frame); \
1630 DEBUG_PRINT2 (" Push string %p: `", string_place); \
1631 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, size2);\
1632 DEBUG_PRINT1 ("'\n"); \
1633 PUSH_FAILURE_POINTER (string_place); \
1635 DEBUG_PRINT2 (" Push pattern %p: ", pattern); \
1636 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern, pend); \
1637 PUSH_FAILURE_POINTER (pattern); \
1639 /* Close the frame by moving the frame pointer past it. */ \
1640 fail_stack.frame = fail_stack.avail; \
1641 } while (0)
1643 /* Estimate the size of data pushed by a typical failure stack entry.
1644 An estimate is all we need, because all we use this for
1645 is to choose a limit for how big to make the failure stack. */
1646 /* BEWARE, the value `20' is hard-coded in emacs.c:main(). */
1647 #define TYPICAL_FAILURE_SIZE 20
1649 /* How many items can still be added to the stack without overflowing it. */
1650 #define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
1653 /* Pops what PUSH_FAIL_STACK pushes.
1655 We restore into the parameters, all of which should be lvalues:
1656 STR -- the saved data position.
1657 PAT -- the saved pattern position.
1658 REGSTART, REGEND -- arrays of string positions.
1660 Also assumes the variables `fail_stack' and (if debugging), `bufp',
1661 `pend', `string1', `size1', `string2', and `size2'. */
1663 #define POP_FAILURE_POINT(str, pat) \
1664 do { \
1665 assert (!FAIL_STACK_EMPTY ()); \
1667 /* Remove failure points and point to how many regs pushed. */ \
1668 DEBUG_PRINT1 ("POP_FAILURE_POINT:\n"); \
1669 DEBUG_PRINT2 (" Before pop, next avail: %d\n", fail_stack.avail); \
1670 DEBUG_PRINT2 (" size: %d\n", fail_stack.size); \
1672 /* Pop the saved registers. */ \
1673 while (fail_stack.frame < fail_stack.avail) \
1674 POP_FAILURE_REG_OR_COUNT (); \
1676 pat = POP_FAILURE_POINTER (); \
1677 DEBUG_PRINT2 (" Popping pattern %p: ", pat); \
1678 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
1680 /* If the saved string location is NULL, it came from an \
1681 on_failure_keep_string_jump opcode, and we want to throw away the \
1682 saved NULL, thus retaining our current position in the string. */ \
1683 str = POP_FAILURE_POINTER (); \
1684 DEBUG_PRINT2 (" Popping string %p: `", str); \
1685 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
1686 DEBUG_PRINT1 ("'\n"); \
1688 fail_stack.frame = POP_FAILURE_INT (); \
1689 DEBUG_PRINT2 (" Popping frame index: %d\n", fail_stack.frame); \
1691 assert (fail_stack.avail >= 0); \
1692 assert (fail_stack.frame <= fail_stack.avail); \
1694 DEBUG_STATEMENT (nfailure_points_popped++); \
1695 } while (0) /* POP_FAILURE_POINT */
1699 /* Registers are set to a sentinel when they haven't yet matched. */
1700 #define REG_UNSET(e) ((e) == NULL)
1702 /* Subroutine declarations and macros for regex_compile. */
1704 static reg_errcode_t regex_compile _RE_ARGS ((re_char *pattern, size_t size,
1705 reg_syntax_t syntax,
1706 struct re_pattern_buffer *bufp));
1707 static void store_op1 _RE_ARGS ((re_opcode_t op, unsigned char *loc, int arg));
1708 static void store_op2 _RE_ARGS ((re_opcode_t op, unsigned char *loc,
1709 int arg1, int arg2));
1710 static void insert_op1 _RE_ARGS ((re_opcode_t op, unsigned char *loc,
1711 int arg, unsigned char *end));
1712 static void insert_op2 _RE_ARGS ((re_opcode_t op, unsigned char *loc,
1713 int arg1, int arg2, unsigned char *end));
1714 static boolean at_begline_loc_p _RE_ARGS ((re_char *pattern,
1715 re_char *p,
1716 reg_syntax_t syntax));
1717 static boolean at_endline_loc_p _RE_ARGS ((re_char *p,
1718 re_char *pend,
1719 reg_syntax_t syntax));
1720 static re_char *skip_one_char _RE_ARGS ((re_char *p));
1721 static int analyse_first _RE_ARGS ((re_char *p, re_char *pend,
1722 char *fastmap, const int multibyte));
1724 /* Fetch the next character in the uncompiled pattern, with no
1725 translation. */
1726 #define PATFETCH(c) \
1727 do { \
1728 int len; \
1729 if (p == pend) return REG_EEND; \
1730 c = RE_STRING_CHAR_AND_LENGTH (p, len, multibyte); \
1731 p += len; \
1732 } while (0)
1735 /* If `translate' is non-null, return translate[D], else just D. We
1736 cast the subscript to translate because some data is declared as
1737 `char *', to avoid warnings when a string constant is passed. But
1738 when we use a character as a subscript we must make it unsigned. */
1739 #ifndef TRANSLATE
1740 # define TRANSLATE(d) \
1741 (RE_TRANSLATE_P (translate) ? RE_TRANSLATE (translate, (d)) : (d))
1742 #endif
1745 /* Macros for outputting the compiled pattern into `buffer'. */
1747 /* If the buffer isn't allocated when it comes in, use this. */
1748 #define INIT_BUF_SIZE 32
1750 /* Make sure we have at least N more bytes of space in buffer. */
1751 #define GET_BUFFER_SPACE(n) \
1752 while ((size_t) (b - bufp->buffer + (n)) > bufp->allocated) \
1753 EXTEND_BUFFER ()
1755 /* Make sure we have one more byte of buffer space and then add C to it. */
1756 #define BUF_PUSH(c) \
1757 do { \
1758 GET_BUFFER_SPACE (1); \
1759 *b++ = (unsigned char) (c); \
1760 } while (0)
1763 /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
1764 #define BUF_PUSH_2(c1, c2) \
1765 do { \
1766 GET_BUFFER_SPACE (2); \
1767 *b++ = (unsigned char) (c1); \
1768 *b++ = (unsigned char) (c2); \
1769 } while (0)
1772 /* As with BUF_PUSH_2, except for three bytes. */
1773 #define BUF_PUSH_3(c1, c2, c3) \
1774 do { \
1775 GET_BUFFER_SPACE (3); \
1776 *b++ = (unsigned char) (c1); \
1777 *b++ = (unsigned char) (c2); \
1778 *b++ = (unsigned char) (c3); \
1779 } while (0)
1782 /* Store a jump with opcode OP at LOC to location TO. We store a
1783 relative address offset by the three bytes the jump itself occupies. */
1784 #define STORE_JUMP(op, loc, to) \
1785 store_op1 (op, loc, (to) - (loc) - 3)
1787 /* Likewise, for a two-argument jump. */
1788 #define STORE_JUMP2(op, loc, to, arg) \
1789 store_op2 (op, loc, (to) - (loc) - 3, arg)
1791 /* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
1792 #define INSERT_JUMP(op, loc, to) \
1793 insert_op1 (op, loc, (to) - (loc) - 3, b)
1795 /* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
1796 #define INSERT_JUMP2(op, loc, to, arg) \
1797 insert_op2 (op, loc, (to) - (loc) - 3, arg, b)
1800 /* This is not an arbitrary limit: the arguments which represent offsets
1801 into the pattern are two bytes long. So if 2^15 bytes turns out to
1802 be too small, many things would have to change. */
1803 # define MAX_BUF_SIZE (1L << 15)
1805 #if 0 /* This is when we thought it could be 2^16 bytes. */
1806 /* Any other compiler which, like MSC, has allocation limit below 2^16
1807 bytes will have to use approach similar to what was done below for
1808 MSC and drop MAX_BUF_SIZE a bit. Otherwise you may end up
1809 reallocating to 0 bytes. Such thing is not going to work too well.
1810 You have been warned!! */
1811 #if defined _MSC_VER && !defined WIN32
1812 /* Microsoft C 16-bit versions limit malloc to approx 65512 bytes. */
1813 # define MAX_BUF_SIZE 65500L
1814 #else
1815 # define MAX_BUF_SIZE (1L << 16)
1816 #endif
1817 #endif /* 0 */
1819 /* Extend the buffer by twice its current size via realloc and
1820 reset the pointers that pointed into the old block to point to the
1821 correct places in the new one. If extending the buffer results in it
1822 being larger than MAX_BUF_SIZE, then flag memory exhausted. */
1823 #if __BOUNDED_POINTERS__
1824 # define SET_HIGH_BOUND(P) (__ptrhigh (P) = __ptrlow (P) + bufp->allocated)
1825 # define MOVE_BUFFER_POINTER(P) \
1826 (__ptrlow (P) = new_buffer + (__ptrlow (P) - old_buffer), \
1827 SET_HIGH_BOUND (P), \
1828 __ptrvalue (P) = new_buffer + (__ptrvalue (P) - old_buffer))
1829 # define ELSE_EXTEND_BUFFER_HIGH_BOUND \
1830 else \
1832 SET_HIGH_BOUND (b); \
1833 SET_HIGH_BOUND (begalt); \
1834 if (fixup_alt_jump) \
1835 SET_HIGH_BOUND (fixup_alt_jump); \
1836 if (laststart) \
1837 SET_HIGH_BOUND (laststart); \
1838 if (pending_exact) \
1839 SET_HIGH_BOUND (pending_exact); \
1841 #else
1842 # define MOVE_BUFFER_POINTER(P) ((P) = new_buffer + ((P) - old_buffer))
1843 # define ELSE_EXTEND_BUFFER_HIGH_BOUND
1844 #endif
1845 #define EXTEND_BUFFER() \
1846 do { \
1847 unsigned char *old_buffer = bufp->buffer; \
1848 if (bufp->allocated == MAX_BUF_SIZE) \
1849 return REG_ESIZE; \
1850 bufp->allocated <<= 1; \
1851 if (bufp->allocated > MAX_BUF_SIZE) \
1852 bufp->allocated = MAX_BUF_SIZE; \
1853 RETALLOC (bufp->buffer, bufp->allocated, unsigned char); \
1854 if (bufp->buffer == NULL) \
1855 return REG_ESPACE; \
1856 /* If the buffer moved, move all the pointers into it. */ \
1857 if (old_buffer != bufp->buffer) \
1859 unsigned char *new_buffer = bufp->buffer; \
1860 MOVE_BUFFER_POINTER (b); \
1861 MOVE_BUFFER_POINTER (begalt); \
1862 if (fixup_alt_jump) \
1863 MOVE_BUFFER_POINTER (fixup_alt_jump); \
1864 if (laststart) \
1865 MOVE_BUFFER_POINTER (laststart); \
1866 if (pending_exact) \
1867 MOVE_BUFFER_POINTER (pending_exact); \
1869 ELSE_EXTEND_BUFFER_HIGH_BOUND \
1870 } while (0)
1873 /* Since we have one byte reserved for the register number argument to
1874 {start,stop}_memory, the maximum number of groups we can report
1875 things about is what fits in that byte. */
1876 #define MAX_REGNUM 255
1878 /* But patterns can have more than `MAX_REGNUM' registers. We just
1879 ignore the excess. */
1880 typedef int regnum_t;
1883 /* Macros for the compile stack. */
1885 /* Since offsets can go either forwards or backwards, this type needs to
1886 be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
1887 /* int may be not enough when sizeof(int) == 2. */
1888 typedef long pattern_offset_t;
1890 typedef struct
1892 pattern_offset_t begalt_offset;
1893 pattern_offset_t fixup_alt_jump;
1894 pattern_offset_t laststart_offset;
1895 regnum_t regnum;
1896 } compile_stack_elt_t;
1899 typedef struct
1901 compile_stack_elt_t *stack;
1902 unsigned size;
1903 unsigned avail; /* Offset of next open position. */
1904 } compile_stack_type;
1907 #define INIT_COMPILE_STACK_SIZE 32
1909 #define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
1910 #define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
1912 /* The next available element. */
1913 #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
1915 /* Explicit quit checking is only used on NTemacs and whenever we
1916 use polling to process input events. */
1917 #if defined emacs && (defined WINDOWSNT || defined SYNC_INPUT) && defined QUIT
1918 extern int immediate_quit;
1919 # define IMMEDIATE_QUIT_CHECK \
1920 do { \
1921 if (immediate_quit) QUIT; \
1922 } while (0)
1923 #else
1924 # define IMMEDIATE_QUIT_CHECK ((void)0)
1925 #endif
1927 /* Structure to manage work area for range table. */
1928 struct range_table_work_area
1930 int *table; /* actual work area. */
1931 int allocated; /* allocated size for work area in bytes. */
1932 int used; /* actually used size in words. */
1933 int bits; /* flag to record character classes */
1936 /* Make sure that WORK_AREA can hold more N multibyte characters.
1937 This is used only in set_image_of_range and set_image_of_range_1.
1938 It expects WORK_AREA to be a pointer.
1939 If it can't get the space, it returns from the surrounding function. */
1941 #define EXTEND_RANGE_TABLE(work_area, n) \
1942 do { \
1943 if (((work_area).used + (n)) * sizeof (int) > (work_area).allocated) \
1945 extend_range_table_work_area (&work_area); \
1946 if ((work_area).table == 0) \
1947 return (REG_ESPACE); \
1949 } while (0)
1951 #define SET_RANGE_TABLE_WORK_AREA_BIT(work_area, bit) \
1952 (work_area).bits |= (bit)
1954 /* Bits used to implement the multibyte-part of the various character classes
1955 such as [:alnum:] in a charset's range table. */
1956 #define BIT_WORD 0x1
1957 #define BIT_LOWER 0x2
1958 #define BIT_PUNCT 0x4
1959 #define BIT_SPACE 0x8
1960 #define BIT_UPPER 0x10
1961 #define BIT_MULTIBYTE 0x20
1963 /* Set a range (RANGE_START, RANGE_END) to WORK_AREA. */
1964 #define SET_RANGE_TABLE_WORK_AREA(work_area, range_start, range_end) \
1965 do { \
1966 EXTEND_RANGE_TABLE ((work_area), 2); \
1967 (work_area).table[(work_area).used++] = (range_start); \
1968 (work_area).table[(work_area).used++] = (range_end); \
1969 } while (0)
1971 /* Free allocated memory for WORK_AREA. */
1972 #define FREE_RANGE_TABLE_WORK_AREA(work_area) \
1973 do { \
1974 if ((work_area).table) \
1975 free ((work_area).table); \
1976 } while (0)
1978 #define CLEAR_RANGE_TABLE_WORK_USED(work_area) ((work_area).used = 0, (work_area).bits = 0)
1979 #define RANGE_TABLE_WORK_USED(work_area) ((work_area).used)
1980 #define RANGE_TABLE_WORK_BITS(work_area) ((work_area).bits)
1981 #define RANGE_TABLE_WORK_ELT(work_area, i) ((work_area).table[i])
1984 /* Set the bit for character C in a list. */
1985 #define SET_LIST_BIT(c) (b[((c)) / BYTEWIDTH] |= 1 << ((c) % BYTEWIDTH))
1988 #ifdef emacs
1990 /* Store characters in the range FROM to TO in the bitmap at B (for
1991 ASCII and unibyte characters) and WORK_AREA (for multibyte
1992 characters) while translating them and paying attention to the
1993 continuity of translated characters.
1995 Implementation note: It is better to implement these fairly big
1996 macros by a function, but it's not that easy because macros called
1997 in this macro assume various local variables already declared. */
1999 /* Both FROM and TO are ASCII characters. */
2001 #define SETUP_ASCII_RANGE(work_area, FROM, TO) \
2002 do { \
2003 int C0, C1; \
2005 for (C0 = (FROM); C0 <= (TO); C0++) \
2007 C1 = TRANSLATE (C0); \
2008 if (! ASCII_CHAR_P (C1)) \
2010 SET_RANGE_TABLE_WORK_AREA ((work_area), C1, C1); \
2011 if ((C1 = RE_CHAR_TO_UNIBYTE (C1)) < 0) \
2012 C1 = C0; \
2014 SET_LIST_BIT (C1); \
2016 } while (0)
2019 /* Both FROM and TO are unibyte characters (0x80..0xFF). */
2021 #define SETUP_UNIBYTE_RANGE(work_area, FROM, TO) \
2022 do { \
2023 int C0, C1, C2, I; \
2024 int USED = RANGE_TABLE_WORK_USED (work_area); \
2026 for (C0 = (FROM); C0 <= (TO); C0++) \
2028 C1 = RE_CHAR_TO_MULTIBYTE (C0); \
2029 if (CHAR_BYTE8_P (C1)) \
2030 SET_LIST_BIT (C0); \
2031 else \
2033 C2 = TRANSLATE (C1); \
2034 if (C2 == C1 \
2035 || (C1 = RE_CHAR_TO_UNIBYTE (C2)) < 0) \
2036 C1 = C0; \
2037 SET_LIST_BIT (C1); \
2038 for (I = RANGE_TABLE_WORK_USED (work_area) - 2; I >= USED; I -= 2) \
2040 int from = RANGE_TABLE_WORK_ELT (work_area, I); \
2041 int to = RANGE_TABLE_WORK_ELT (work_area, I + 1); \
2043 if (C2 >= from - 1 && C2 <= to + 1) \
2045 if (C2 == from - 1) \
2046 RANGE_TABLE_WORK_ELT (work_area, I)--; \
2047 else if (C2 == to + 1) \
2048 RANGE_TABLE_WORK_ELT (work_area, I + 1)++; \
2049 break; \
2052 if (I < USED) \
2053 SET_RANGE_TABLE_WORK_AREA ((work_area), C2, C2); \
2056 } while (0)
2059 /* Both FROM and TO are multibyte characters. */
2061 #define SETUP_MULTIBYTE_RANGE(work_area, FROM, TO) \
2062 do { \
2063 int C0, C1, C2, I, USED = RANGE_TABLE_WORK_USED (work_area); \
2065 SET_RANGE_TABLE_WORK_AREA ((work_area), (FROM), (TO)); \
2066 for (C0 = (FROM); C0 <= (TO); C0++) \
2068 C1 = TRANSLATE (C0); \
2069 if ((C2 = RE_CHAR_TO_UNIBYTE (C1)) >= 0 \
2070 || (C1 != C0 && (C2 = RE_CHAR_TO_UNIBYTE (C0)) >= 0)) \
2071 SET_LIST_BIT (C2); \
2072 if (C1 >= (FROM) && C1 <= (TO)) \
2073 continue; \
2074 for (I = RANGE_TABLE_WORK_USED (work_area) - 2; I >= USED; I -= 2) \
2076 int from = RANGE_TABLE_WORK_ELT (work_area, I); \
2077 int to = RANGE_TABLE_WORK_ELT (work_area, I + 1); \
2079 if (C1 >= from - 1 && C1 <= to + 1) \
2081 if (C1 == from - 1) \
2082 RANGE_TABLE_WORK_ELT (work_area, I)--; \
2083 else if (C1 == to + 1) \
2084 RANGE_TABLE_WORK_ELT (work_area, I + 1)++; \
2085 break; \
2088 if (I < USED) \
2089 SET_RANGE_TABLE_WORK_AREA ((work_area), C1, C1); \
2091 } while (0)
2093 #endif /* emacs */
2095 /* Get the next unsigned number in the uncompiled pattern. */
2096 #define GET_UNSIGNED_NUMBER(num) \
2097 do { \
2098 if (p == pend) \
2099 FREE_STACK_RETURN (REG_EBRACE); \
2100 else \
2102 PATFETCH (c); \
2103 while ('0' <= c && c <= '9') \
2105 int prev; \
2106 if (num < 0) \
2107 num = 0; \
2108 prev = num; \
2109 num = num * 10 + c - '0'; \
2110 if (num / 10 != prev) \
2111 FREE_STACK_RETURN (REG_BADBR); \
2112 if (p == pend) \
2113 FREE_STACK_RETURN (REG_EBRACE); \
2114 PATFETCH (c); \
2117 } while (0)
2119 #if ! WIDE_CHAR_SUPPORT
2121 /* Map a string to the char class it names (if any). */
2122 re_wctype_t
2123 re_wctype (const re_char *str)
2125 const char *string = str;
2126 if (STREQ (string, "alnum")) return RECC_ALNUM;
2127 else if (STREQ (string, "alpha")) return RECC_ALPHA;
2128 else if (STREQ (string, "word")) return RECC_WORD;
2129 else if (STREQ (string, "ascii")) return RECC_ASCII;
2130 else if (STREQ (string, "nonascii")) return RECC_NONASCII;
2131 else if (STREQ (string, "graph")) return RECC_GRAPH;
2132 else if (STREQ (string, "lower")) return RECC_LOWER;
2133 else if (STREQ (string, "print")) return RECC_PRINT;
2134 else if (STREQ (string, "punct")) return RECC_PUNCT;
2135 else if (STREQ (string, "space")) return RECC_SPACE;
2136 else if (STREQ (string, "upper")) return RECC_UPPER;
2137 else if (STREQ (string, "unibyte")) return RECC_UNIBYTE;
2138 else if (STREQ (string, "multibyte")) return RECC_MULTIBYTE;
2139 else if (STREQ (string, "digit")) return RECC_DIGIT;
2140 else if (STREQ (string, "xdigit")) return RECC_XDIGIT;
2141 else if (STREQ (string, "cntrl")) return RECC_CNTRL;
2142 else if (STREQ (string, "blank")) return RECC_BLANK;
2143 else return 0;
2146 /* True if CH is in the char class CC. */
2147 boolean
2148 re_iswctype (int ch, re_wctype_t cc)
2150 switch (cc)
2152 case RECC_ALNUM: return ISALNUM (ch);
2153 case RECC_ALPHA: return ISALPHA (ch);
2154 case RECC_BLANK: return ISBLANK (ch);
2155 case RECC_CNTRL: return ISCNTRL (ch);
2156 case RECC_DIGIT: return ISDIGIT (ch);
2157 case RECC_GRAPH: return ISGRAPH (ch);
2158 case RECC_LOWER: return ISLOWER (ch);
2159 case RECC_PRINT: return ISPRINT (ch);
2160 case RECC_PUNCT: return ISPUNCT (ch);
2161 case RECC_SPACE: return ISSPACE (ch);
2162 case RECC_UPPER: return ISUPPER (ch);
2163 case RECC_XDIGIT: return ISXDIGIT (ch);
2164 case RECC_ASCII: return IS_REAL_ASCII (ch);
2165 case RECC_NONASCII: return !IS_REAL_ASCII (ch);
2166 case RECC_UNIBYTE: return ISUNIBYTE (ch);
2167 case RECC_MULTIBYTE: return !ISUNIBYTE (ch);
2168 case RECC_WORD: return ISWORD (ch);
2169 case RECC_ERROR: return false;
2170 default:
2171 abort();
2175 /* Return a bit-pattern to use in the range-table bits to match multibyte
2176 chars of class CC. */
2177 static int
2178 re_wctype_to_bit (re_wctype_t cc)
2180 switch (cc)
2182 case RECC_NONASCII: case RECC_PRINT: case RECC_GRAPH:
2183 case RECC_MULTIBYTE: return BIT_MULTIBYTE;
2184 case RECC_ALPHA: case RECC_ALNUM: case RECC_WORD: return BIT_WORD;
2185 case RECC_LOWER: return BIT_LOWER;
2186 case RECC_UPPER: return BIT_UPPER;
2187 case RECC_PUNCT: return BIT_PUNCT;
2188 case RECC_SPACE: return BIT_SPACE;
2189 case RECC_ASCII: case RECC_DIGIT: case RECC_XDIGIT: case RECC_CNTRL:
2190 case RECC_BLANK: case RECC_UNIBYTE: case RECC_ERROR: return 0;
2191 default:
2192 abort();
2195 #endif
2197 /* Filling in the work area of a range. */
2199 /* Actually extend the space in WORK_AREA. */
2201 static void
2202 extend_range_table_work_area (struct range_table_work_area *work_area)
2204 work_area->allocated += 16 * sizeof (int);
2205 if (work_area->table)
2206 work_area->table
2207 = (int *) realloc (work_area->table, work_area->allocated);
2208 else
2209 work_area->table
2210 = (int *) malloc (work_area->allocated);
2213 #if 0
2214 #ifdef emacs
2216 /* Carefully find the ranges of codes that are equivalent
2217 under case conversion to the range start..end when passed through
2218 TRANSLATE. Handle the case where non-letters can come in between
2219 two upper-case letters (which happens in Latin-1).
2220 Also handle the case of groups of more than 2 case-equivalent chars.
2222 The basic method is to look at consecutive characters and see
2223 if they can form a run that can be handled as one.
2225 Returns -1 if successful, REG_ESPACE if ran out of space. */
2227 static int
2228 set_image_of_range_1 (work_area, start, end, translate)
2229 RE_TRANSLATE_TYPE translate;
2230 struct range_table_work_area *work_area;
2231 re_wchar_t start, end;
2233 /* `one_case' indicates a character, or a run of characters,
2234 each of which is an isolate (no case-equivalents).
2235 This includes all ASCII non-letters.
2237 `two_case' indicates a character, or a run of characters,
2238 each of which has two case-equivalent forms.
2239 This includes all ASCII letters.
2241 `strange' indicates a character that has more than one
2242 case-equivalent. */
2244 enum case_type {one_case, two_case, strange};
2246 /* Describe the run that is in progress,
2247 which the next character can try to extend.
2248 If run_type is strange, that means there really is no run.
2249 If run_type is one_case, then run_start...run_end is the run.
2250 If run_type is two_case, then the run is run_start...run_end,
2251 and the case-equivalents end at run_eqv_end. */
2253 enum case_type run_type = strange;
2254 int run_start, run_end, run_eqv_end;
2256 Lisp_Object eqv_table;
2258 if (!RE_TRANSLATE_P (translate))
2260 EXTEND_RANGE_TABLE (work_area, 2);
2261 work_area->table[work_area->used++] = (start);
2262 work_area->table[work_area->used++] = (end);
2263 return -1;
2266 eqv_table = XCHAR_TABLE (translate)->extras[2];
2268 for (; start <= end; start++)
2270 enum case_type this_type;
2271 int eqv = RE_TRANSLATE (eqv_table, start);
2272 int minchar, maxchar;
2274 /* Classify this character */
2275 if (eqv == start)
2276 this_type = one_case;
2277 else if (RE_TRANSLATE (eqv_table, eqv) == start)
2278 this_type = two_case;
2279 else
2280 this_type = strange;
2282 if (start < eqv)
2283 minchar = start, maxchar = eqv;
2284 else
2285 minchar = eqv, maxchar = start;
2287 /* Can this character extend the run in progress? */
2288 if (this_type == strange || this_type != run_type
2289 || !(minchar == run_end + 1
2290 && (run_type == two_case
2291 ? maxchar == run_eqv_end + 1 : 1)))
2293 /* No, end the run.
2294 Record each of its equivalent ranges. */
2295 if (run_type == one_case)
2297 EXTEND_RANGE_TABLE (work_area, 2);
2298 work_area->table[work_area->used++] = run_start;
2299 work_area->table[work_area->used++] = run_end;
2301 else if (run_type == two_case)
2303 EXTEND_RANGE_TABLE (work_area, 4);
2304 work_area->table[work_area->used++] = run_start;
2305 work_area->table[work_area->used++] = run_end;
2306 work_area->table[work_area->used++]
2307 = RE_TRANSLATE (eqv_table, run_start);
2308 work_area->table[work_area->used++]
2309 = RE_TRANSLATE (eqv_table, run_end);
2311 run_type = strange;
2314 if (this_type == strange)
2316 /* For a strange character, add each of its equivalents, one
2317 by one. Don't start a range. */
2320 EXTEND_RANGE_TABLE (work_area, 2);
2321 work_area->table[work_area->used++] = eqv;
2322 work_area->table[work_area->used++] = eqv;
2323 eqv = RE_TRANSLATE (eqv_table, eqv);
2325 while (eqv != start);
2328 /* Add this char to the run, or start a new run. */
2329 else if (run_type == strange)
2331 /* Initialize a new range. */
2332 run_type = this_type;
2333 run_start = start;
2334 run_end = start;
2335 run_eqv_end = RE_TRANSLATE (eqv_table, run_end);
2337 else
2339 /* Extend a running range. */
2340 run_end = minchar;
2341 run_eqv_end = RE_TRANSLATE (eqv_table, run_end);
2345 /* If a run is still in progress at the end, finish it now
2346 by recording its equivalent ranges. */
2347 if (run_type == one_case)
2349 EXTEND_RANGE_TABLE (work_area, 2);
2350 work_area->table[work_area->used++] = run_start;
2351 work_area->table[work_area->used++] = run_end;
2353 else if (run_type == two_case)
2355 EXTEND_RANGE_TABLE (work_area, 4);
2356 work_area->table[work_area->used++] = run_start;
2357 work_area->table[work_area->used++] = run_end;
2358 work_area->table[work_area->used++]
2359 = RE_TRANSLATE (eqv_table, run_start);
2360 work_area->table[work_area->used++]
2361 = RE_TRANSLATE (eqv_table, run_end);
2364 return -1;
2367 #endif /* emacs */
2369 /* Record the image of the range start..end when passed through
2370 TRANSLATE. This is not necessarily TRANSLATE(start)..TRANSLATE(end)
2371 and is not even necessarily contiguous.
2372 Normally we approximate it with the smallest contiguous range that contains
2373 all the chars we need. However, for Latin-1 we go to extra effort
2374 to do a better job.
2376 This function is not called for ASCII ranges.
2378 Returns -1 if successful, REG_ESPACE if ran out of space. */
2380 static int
2381 set_image_of_range (work_area, start, end, translate)
2382 RE_TRANSLATE_TYPE translate;
2383 struct range_table_work_area *work_area;
2384 re_wchar_t start, end;
2386 re_wchar_t cmin, cmax;
2388 #ifdef emacs
2389 /* For Latin-1 ranges, use set_image_of_range_1
2390 to get proper handling of ranges that include letters and nonletters.
2391 For a range that includes the whole of Latin-1, this is not necessary.
2392 For other character sets, we don't bother to get this right. */
2393 if (RE_TRANSLATE_P (translate) && start < 04400
2394 && !(start < 04200 && end >= 04377))
2396 int newend;
2397 int tem;
2398 newend = end;
2399 if (newend > 04377)
2400 newend = 04377;
2401 tem = set_image_of_range_1 (work_area, start, newend, translate);
2402 if (tem > 0)
2403 return tem;
2405 start = 04400;
2406 if (end < 04400)
2407 return -1;
2409 #endif
2411 EXTEND_RANGE_TABLE (work_area, 2);
2412 work_area->table[work_area->used++] = (start);
2413 work_area->table[work_area->used++] = (end);
2415 cmin = -1, cmax = -1;
2417 if (RE_TRANSLATE_P (translate))
2419 int ch;
2421 for (ch = start; ch <= end; ch++)
2423 re_wchar_t c = TRANSLATE (ch);
2424 if (! (start <= c && c <= end))
2426 if (cmin == -1)
2427 cmin = c, cmax = c;
2428 else
2430 cmin = MIN (cmin, c);
2431 cmax = MAX (cmax, c);
2436 if (cmin != -1)
2438 EXTEND_RANGE_TABLE (work_area, 2);
2439 work_area->table[work_area->used++] = (cmin);
2440 work_area->table[work_area->used++] = (cmax);
2444 return -1;
2446 #endif /* 0 */
2448 #ifndef MATCH_MAY_ALLOCATE
2450 /* If we cannot allocate large objects within re_match_2_internal,
2451 we make the fail stack and register vectors global.
2452 The fail stack, we grow to the maximum size when a regexp
2453 is compiled.
2454 The register vectors, we adjust in size each time we
2455 compile a regexp, according to the number of registers it needs. */
2457 static fail_stack_type fail_stack;
2459 /* Size with which the following vectors are currently allocated.
2460 That is so we can make them bigger as needed,
2461 but never make them smaller. */
2462 static int regs_allocated_size;
2464 static re_char ** regstart, ** regend;
2465 static re_char **best_regstart, **best_regend;
2467 /* Make the register vectors big enough for NUM_REGS registers,
2468 but don't make them smaller. */
2470 static
2471 regex_grow_registers (num_regs)
2472 int num_regs;
2474 if (num_regs > regs_allocated_size)
2476 RETALLOC_IF (regstart, num_regs, re_char *);
2477 RETALLOC_IF (regend, num_regs, re_char *);
2478 RETALLOC_IF (best_regstart, num_regs, re_char *);
2479 RETALLOC_IF (best_regend, num_regs, re_char *);
2481 regs_allocated_size = num_regs;
2485 #endif /* not MATCH_MAY_ALLOCATE */
2487 static boolean group_in_compile_stack _RE_ARGS ((compile_stack_type
2488 compile_stack,
2489 regnum_t regnum));
2491 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
2492 Returns one of error codes defined in `regex.h', or zero for success.
2494 Assumes the `allocated' (and perhaps `buffer') and `translate'
2495 fields are set in BUFP on entry.
2497 If it succeeds, results are put in BUFP (if it returns an error, the
2498 contents of BUFP are undefined):
2499 `buffer' is the compiled pattern;
2500 `syntax' is set to SYNTAX;
2501 `used' is set to the length of the compiled pattern;
2502 `fastmap_accurate' is zero;
2503 `re_nsub' is the number of subexpressions in PATTERN;
2504 `not_bol' and `not_eol' are zero;
2506 The `fastmap' field is neither examined nor set. */
2508 /* Insert the `jump' from the end of last alternative to "here".
2509 The space for the jump has already been allocated. */
2510 #define FIXUP_ALT_JUMP() \
2511 do { \
2512 if (fixup_alt_jump) \
2513 STORE_JUMP (jump, fixup_alt_jump, b); \
2514 } while (0)
2517 /* Return, freeing storage we allocated. */
2518 #define FREE_STACK_RETURN(value) \
2519 do { \
2520 FREE_RANGE_TABLE_WORK_AREA (range_table_work); \
2521 free (compile_stack.stack); \
2522 return value; \
2523 } while (0)
2525 static reg_errcode_t
2526 regex_compile (const re_char *pattern, size_t size, reg_syntax_t syntax, struct re_pattern_buffer *bufp)
2528 /* We fetch characters from PATTERN here. */
2529 register re_wchar_t c, c1;
2531 /* A random temporary spot in PATTERN. */
2532 re_char *p1;
2534 /* Points to the end of the buffer, where we should append. */
2535 register unsigned char *b;
2537 /* Keeps track of unclosed groups. */
2538 compile_stack_type compile_stack;
2540 /* Points to the current (ending) position in the pattern. */
2541 #ifdef AIX
2542 /* `const' makes AIX compiler fail. */
2543 unsigned char *p = pattern;
2544 #else
2545 re_char *p = pattern;
2546 #endif
2547 re_char *pend = pattern + size;
2549 /* How to translate the characters in the pattern. */
2550 RE_TRANSLATE_TYPE translate = bufp->translate;
2552 /* Address of the count-byte of the most recently inserted `exactn'
2553 command. This makes it possible to tell if a new exact-match
2554 character can be added to that command or if the character requires
2555 a new `exactn' command. */
2556 unsigned char *pending_exact = 0;
2558 /* Address of start of the most recently finished expression.
2559 This tells, e.g., postfix * where to find the start of its
2560 operand. Reset at the beginning of groups and alternatives. */
2561 unsigned char *laststart = 0;
2563 /* Address of beginning of regexp, or inside of last group. */
2564 unsigned char *begalt;
2566 /* Place in the uncompiled pattern (i.e., the {) to
2567 which to go back if the interval is invalid. */
2568 re_char *beg_interval;
2570 /* Address of the place where a forward jump should go to the end of
2571 the containing expression. Each alternative of an `or' -- except the
2572 last -- ends with a forward jump of this sort. */
2573 unsigned char *fixup_alt_jump = 0;
2575 /* Work area for range table of charset. */
2576 struct range_table_work_area range_table_work;
2578 /* If the object matched can contain multibyte characters. */
2579 const boolean multibyte = RE_MULTIBYTE_P (bufp);
2581 /* If a target of matching can contain multibyte characters. */
2582 const boolean target_multibyte = RE_TARGET_MULTIBYTE_P (bufp);
2584 /* Nonzero if we have pushed down into a subpattern. */
2585 int in_subpattern = 0;
2587 /* These hold the values of p, pattern, and pend from the main
2588 pattern when we have pushed into a subpattern. */
2589 re_char *main_p;
2590 re_char *main_pattern;
2591 re_char *main_pend;
2593 #ifdef DEBUG
2594 debug++;
2595 DEBUG_PRINT1 ("\nCompiling pattern: ");
2596 if (debug > 0)
2598 unsigned debug_count;
2600 for (debug_count = 0; debug_count < size; debug_count++)
2601 putchar (pattern[debug_count]);
2602 putchar ('\n');
2604 #endif /* DEBUG */
2606 /* Initialize the compile stack. */
2607 compile_stack.stack = TALLOC (INIT_COMPILE_STACK_SIZE, compile_stack_elt_t);
2608 if (compile_stack.stack == NULL)
2609 return REG_ESPACE;
2611 compile_stack.size = INIT_COMPILE_STACK_SIZE;
2612 compile_stack.avail = 0;
2614 range_table_work.table = 0;
2615 range_table_work.allocated = 0;
2617 /* Initialize the pattern buffer. */
2618 bufp->syntax = syntax;
2619 bufp->fastmap_accurate = 0;
2620 bufp->not_bol = bufp->not_eol = 0;
2621 bufp->used_syntax = 0;
2623 /* Set `used' to zero, so that if we return an error, the pattern
2624 printer (for debugging) will think there's no pattern. We reset it
2625 at the end. */
2626 bufp->used = 0;
2628 /* Always count groups, whether or not bufp->no_sub is set. */
2629 bufp->re_nsub = 0;
2631 #if !defined emacs && !defined SYNTAX_TABLE
2632 /* Initialize the syntax table. */
2633 init_syntax_once ();
2634 #endif
2636 if (bufp->allocated == 0)
2638 if (bufp->buffer)
2639 { /* If zero allocated, but buffer is non-null, try to realloc
2640 enough space. This loses if buffer's address is bogus, but
2641 that is the user's responsibility. */
2642 RETALLOC (bufp->buffer, INIT_BUF_SIZE, unsigned char);
2644 else
2645 { /* Caller did not allocate a buffer. Do it for them. */
2646 bufp->buffer = TALLOC (INIT_BUF_SIZE, unsigned char);
2648 if (!bufp->buffer) FREE_STACK_RETURN (REG_ESPACE);
2650 bufp->allocated = INIT_BUF_SIZE;
2653 begalt = b = bufp->buffer;
2655 /* Loop through the uncompiled pattern until we're at the end. */
2656 while (1)
2658 if (p == pend)
2660 /* If this is the end of an included regexp,
2661 pop back to the main regexp and try again. */
2662 if (in_subpattern)
2664 in_subpattern = 0;
2665 pattern = main_pattern;
2666 p = main_p;
2667 pend = main_pend;
2668 continue;
2670 /* If this is the end of the main regexp, we are done. */
2671 break;
2674 PATFETCH (c);
2676 switch (c)
2678 case ' ':
2680 re_char *p1 = p;
2682 /* If there's no special whitespace regexp, treat
2683 spaces normally. And don't try to do this recursively. */
2684 if (!whitespace_regexp || in_subpattern)
2685 goto normal_char;
2687 /* Peek past following spaces. */
2688 while (p1 != pend)
2690 if (*p1 != ' ')
2691 break;
2692 p1++;
2694 /* If the spaces are followed by a repetition op,
2695 treat them normally. */
2696 if (p1 != pend
2697 && (*p1 == '*' || *p1 == '+' || *p1 == '?'
2698 || (*p1 == '\\' && p1 + 1 != pend && p1[1] == '{')))
2699 goto normal_char;
2701 /* Replace the spaces with the whitespace regexp. */
2702 in_subpattern = 1;
2703 main_p = p1;
2704 main_pend = pend;
2705 main_pattern = pattern;
2706 p = pattern = whitespace_regexp;
2707 pend = p + strlen (p);
2708 break;
2711 case '^':
2713 if ( /* If at start of pattern, it's an operator. */
2714 p == pattern + 1
2715 /* If context independent, it's an operator. */
2716 || syntax & RE_CONTEXT_INDEP_ANCHORS
2717 /* Otherwise, depends on what's come before. */
2718 || at_begline_loc_p (pattern, p, syntax))
2719 BUF_PUSH ((syntax & RE_NO_NEWLINE_ANCHOR) ? begbuf : begline);
2720 else
2721 goto normal_char;
2723 break;
2726 case '$':
2728 if ( /* If at end of pattern, it's an operator. */
2729 p == pend
2730 /* If context independent, it's an operator. */
2731 || syntax & RE_CONTEXT_INDEP_ANCHORS
2732 /* Otherwise, depends on what's next. */
2733 || at_endline_loc_p (p, pend, syntax))
2734 BUF_PUSH ((syntax & RE_NO_NEWLINE_ANCHOR) ? endbuf : endline);
2735 else
2736 goto normal_char;
2738 break;
2741 case '+':
2742 case '?':
2743 if ((syntax & RE_BK_PLUS_QM)
2744 || (syntax & RE_LIMITED_OPS))
2745 goto normal_char;
2746 handle_plus:
2747 case '*':
2748 /* If there is no previous pattern... */
2749 if (!laststart)
2751 if (syntax & RE_CONTEXT_INVALID_OPS)
2752 FREE_STACK_RETURN (REG_BADRPT);
2753 else if (!(syntax & RE_CONTEXT_INDEP_OPS))
2754 goto normal_char;
2758 /* 1 means zero (many) matches is allowed. */
2759 boolean zero_times_ok = 0, many_times_ok = 0;
2760 boolean greedy = 1;
2762 /* If there is a sequence of repetition chars, collapse it
2763 down to just one (the right one). We can't combine
2764 interval operators with these because of, e.g., `a{2}*',
2765 which should only match an even number of `a's. */
2767 for (;;)
2769 if ((syntax & RE_FRUGAL)
2770 && c == '?' && (zero_times_ok || many_times_ok))
2771 greedy = 0;
2772 else
2774 zero_times_ok |= c != '+';
2775 many_times_ok |= c != '?';
2778 if (p == pend)
2779 break;
2780 else if (*p == '*'
2781 || (!(syntax & RE_BK_PLUS_QM)
2782 && (*p == '+' || *p == '?')))
2784 else if (syntax & RE_BK_PLUS_QM && *p == '\\')
2786 if (p+1 == pend)
2787 FREE_STACK_RETURN (REG_EESCAPE);
2788 if (p[1] == '+' || p[1] == '?')
2789 PATFETCH (c); /* Gobble up the backslash. */
2790 else
2791 break;
2793 else
2794 break;
2795 /* If we get here, we found another repeat character. */
2796 PATFETCH (c);
2799 /* Star, etc. applied to an empty pattern is equivalent
2800 to an empty pattern. */
2801 if (!laststart || laststart == b)
2802 break;
2804 /* Now we know whether or not zero matches is allowed
2805 and also whether or not two or more matches is allowed. */
2806 if (greedy)
2808 if (many_times_ok)
2810 boolean simple = skip_one_char (laststart) == b;
2811 unsigned int startoffset = 0;
2812 re_opcode_t ofj =
2813 /* Check if the loop can match the empty string. */
2814 (simple || !analyse_first (laststart, b, NULL, 0))
2815 ? on_failure_jump : on_failure_jump_loop;
2816 assert (skip_one_char (laststart) <= b);
2818 if (!zero_times_ok && simple)
2819 { /* Since simple * loops can be made faster by using
2820 on_failure_keep_string_jump, we turn simple P+
2821 into PP* if P is simple. */
2822 unsigned char *p1, *p2;
2823 startoffset = b - laststart;
2824 GET_BUFFER_SPACE (startoffset);
2825 p1 = b; p2 = laststart;
2826 while (p2 < p1)
2827 *b++ = *p2++;
2828 zero_times_ok = 1;
2831 GET_BUFFER_SPACE (6);
2832 if (!zero_times_ok)
2833 /* A + loop. */
2834 STORE_JUMP (ofj, b, b + 6);
2835 else
2836 /* Simple * loops can use on_failure_keep_string_jump
2837 depending on what follows. But since we don't know
2838 that yet, we leave the decision up to
2839 on_failure_jump_smart. */
2840 INSERT_JUMP (simple ? on_failure_jump_smart : ofj,
2841 laststart + startoffset, b + 6);
2842 b += 3;
2843 STORE_JUMP (jump, b, laststart + startoffset);
2844 b += 3;
2846 else
2848 /* A simple ? pattern. */
2849 assert (zero_times_ok);
2850 GET_BUFFER_SPACE (3);
2851 INSERT_JUMP (on_failure_jump, laststart, b + 3);
2852 b += 3;
2855 else /* not greedy */
2856 { /* I wish the greedy and non-greedy cases could be merged. */
2858 GET_BUFFER_SPACE (7); /* We might use less. */
2859 if (many_times_ok)
2861 boolean emptyp = analyse_first (laststart, b, NULL, 0);
2863 /* The non-greedy multiple match looks like
2864 a repeat..until: we only need a conditional jump
2865 at the end of the loop. */
2866 if (emptyp) BUF_PUSH (no_op);
2867 STORE_JUMP (emptyp ? on_failure_jump_nastyloop
2868 : on_failure_jump, b, laststart);
2869 b += 3;
2870 if (zero_times_ok)
2872 /* The repeat...until naturally matches one or more.
2873 To also match zero times, we need to first jump to
2874 the end of the loop (its conditional jump). */
2875 INSERT_JUMP (jump, laststart, b);
2876 b += 3;
2879 else
2881 /* non-greedy a?? */
2882 INSERT_JUMP (jump, laststart, b + 3);
2883 b += 3;
2884 INSERT_JUMP (on_failure_jump, laststart, laststart + 6);
2885 b += 3;
2889 pending_exact = 0;
2890 break;
2893 case '.':
2894 laststart = b;
2895 BUF_PUSH (anychar);
2896 break;
2899 case '[':
2901 CLEAR_RANGE_TABLE_WORK_USED (range_table_work);
2903 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2905 /* Ensure that we have enough space to push a charset: the
2906 opcode, the length count, and the bitset; 34 bytes in all. */
2907 GET_BUFFER_SPACE (34);
2909 laststart = b;
2911 /* We test `*p == '^' twice, instead of using an if
2912 statement, so we only need one BUF_PUSH. */
2913 BUF_PUSH (*p == '^' ? charset_not : charset);
2914 if (*p == '^')
2915 p++;
2917 /* Remember the first position in the bracket expression. */
2918 p1 = p;
2920 /* Push the number of bytes in the bitmap. */
2921 BUF_PUSH ((1 << BYTEWIDTH) / BYTEWIDTH);
2923 /* Clear the whole map. */
2924 memset (b, 0, (1 << BYTEWIDTH) / BYTEWIDTH);
2926 /* charset_not matches newline according to a syntax bit. */
2927 if ((re_opcode_t) b[-2] == charset_not
2928 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
2929 SET_LIST_BIT ('\n');
2931 /* Read in characters and ranges, setting map bits. */
2932 for (;;)
2934 boolean escaped_char = false;
2935 const unsigned char *p2 = p;
2936 re_wchar_t ch, c2;
2938 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2940 /* Don't translate yet. The range TRANSLATE(X..Y) cannot
2941 always be determined from TRANSLATE(X) and TRANSLATE(Y)
2942 So the translation is done later in a loop. Example:
2943 (let ((case-fold-search t)) (string-match "[A-_]" "A")) */
2944 PATFETCH (c);
2946 /* \ might escape characters inside [...] and [^...]. */
2947 if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
2949 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2951 PATFETCH (c);
2952 escaped_char = true;
2954 else
2956 /* Could be the end of the bracket expression. If it's
2957 not (i.e., when the bracket expression is `[]' so
2958 far), the ']' character bit gets set way below. */
2959 if (c == ']' && p2 != p1)
2960 break;
2963 /* See if we're at the beginning of a possible character
2964 class. */
2966 if (!escaped_char &&
2967 syntax & RE_CHAR_CLASSES && c == '[' && *p == ':')
2969 /* Leave room for the null. */
2970 unsigned char str[CHAR_CLASS_MAX_LENGTH + 1];
2971 const unsigned char *class_beg;
2973 PATFETCH (c);
2974 c1 = 0;
2975 class_beg = p;
2977 /* If pattern is `[[:'. */
2978 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2980 for (;;)
2982 PATFETCH (c);
2983 if ((c == ':' && *p == ']') || p == pend)
2984 break;
2985 if (c1 < CHAR_CLASS_MAX_LENGTH)
2986 str[c1++] = c;
2987 else
2988 /* This is in any case an invalid class name. */
2989 str[0] = '\0';
2991 str[c1] = '\0';
2993 /* If isn't a word bracketed by `[:' and `:]':
2994 undo the ending character, the letters, and
2995 leave the leading `:' and `[' (but set bits for
2996 them). */
2997 if (c == ':' && *p == ']')
2999 re_wctype_t cc;
3000 int limit;
3002 cc = re_wctype (str);
3004 if (cc == 0)
3005 FREE_STACK_RETURN (REG_ECTYPE);
3007 /* Throw away the ] at the end of the character
3008 class. */
3009 PATFETCH (c);
3011 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
3013 #ifndef emacs
3014 for (ch = 0; ch < (1 << BYTEWIDTH); ++ch)
3015 if (re_iswctype (btowc (ch), cc))
3017 c = TRANSLATE (ch);
3018 if (c < (1 << BYTEWIDTH))
3019 SET_LIST_BIT (c);
3021 #else /* emacs */
3022 /* Most character classes in a multibyte match
3023 just set a flag. Exceptions are is_blank,
3024 is_digit, is_cntrl, and is_xdigit, since
3025 they can only match ASCII characters. We
3026 don't need to handle them for multibyte.
3027 They are distinguished by a negative wctype. */
3029 /* Setup the gl_state object to its buffer-defined
3030 value. This hardcodes the buffer-global
3031 syntax-table for ASCII chars, while the other chars
3032 will obey syntax-table properties. It's not ideal,
3033 but it's the way it's been done until now. */
3034 SETUP_BUFFER_SYNTAX_TABLE ();
3036 for (ch = 0; ch < 256; ++ch)
3038 c = RE_CHAR_TO_MULTIBYTE (ch);
3039 if (! CHAR_BYTE8_P (c)
3040 && re_iswctype (c, cc))
3042 SET_LIST_BIT (ch);
3043 c1 = TRANSLATE (c);
3044 if (c1 == c)
3045 continue;
3046 if (ASCII_CHAR_P (c1))
3047 SET_LIST_BIT (c1);
3048 else if ((c1 = RE_CHAR_TO_UNIBYTE (c1)) >= 0)
3049 SET_LIST_BIT (c1);
3052 SET_RANGE_TABLE_WORK_AREA_BIT
3053 (range_table_work, re_wctype_to_bit (cc));
3054 #endif /* emacs */
3055 /* In most cases the matching rule for char classes
3056 only uses the syntax table for multibyte chars,
3057 so that the content of the syntax-table it is not
3058 hardcoded in the range_table. SPACE and WORD are
3059 the two exceptions. */
3060 if ((1 << cc) & ((1 << RECC_SPACE) | (1 << RECC_WORD)))
3061 bufp->used_syntax = 1;
3063 /* Repeat the loop. */
3064 continue;
3066 else
3068 /* Go back to right after the "[:". */
3069 p = class_beg;
3070 SET_LIST_BIT ('[');
3072 /* Because the `:' may starts the range, we
3073 can't simply set bit and repeat the loop.
3074 Instead, just set it to C and handle below. */
3075 c = ':';
3079 if (p < pend && p[0] == '-' && p[1] != ']')
3082 /* Discard the `-'. */
3083 PATFETCH (c1);
3085 /* Fetch the character which ends the range. */
3086 PATFETCH (c1);
3087 #ifdef emacs
3088 if (CHAR_BYTE8_P (c1)
3089 && ! ASCII_CHAR_P (c) && ! CHAR_BYTE8_P (c))
3090 /* Treat the range from a multibyte character to
3091 raw-byte character as empty. */
3092 c = c1 + 1;
3093 #endif /* emacs */
3095 else
3096 /* Range from C to C. */
3097 c1 = c;
3099 if (c > c1)
3101 if (syntax & RE_NO_EMPTY_RANGES)
3102 FREE_STACK_RETURN (REG_ERANGEX);
3103 /* Else, repeat the loop. */
3105 else
3107 #ifndef emacs
3108 /* Set the range into bitmap */
3109 for (; c <= c1; c++)
3111 ch = TRANSLATE (c);
3112 if (ch < (1 << BYTEWIDTH))
3113 SET_LIST_BIT (ch);
3115 #else /* emacs */
3116 if (c < 128)
3118 ch = MIN (127, c1);
3119 SETUP_ASCII_RANGE (range_table_work, c, ch);
3120 c = ch + 1;
3121 if (CHAR_BYTE8_P (c1))
3122 c = BYTE8_TO_CHAR (128);
3124 if (c <= c1)
3126 if (CHAR_BYTE8_P (c))
3128 c = CHAR_TO_BYTE8 (c);
3129 c1 = CHAR_TO_BYTE8 (c1);
3130 for (; c <= c1; c++)
3131 SET_LIST_BIT (c);
3133 else if (multibyte)
3135 SETUP_MULTIBYTE_RANGE (range_table_work, c, c1);
3137 else
3139 SETUP_UNIBYTE_RANGE (range_table_work, c, c1);
3142 #endif /* emacs */
3146 /* Discard any (non)matching list bytes that are all 0 at the
3147 end of the map. Decrease the map-length byte too. */
3148 while ((int) b[-1] > 0 && b[b[-1] - 1] == 0)
3149 b[-1]--;
3150 b += b[-1];
3152 /* Build real range table from work area. */
3153 if (RANGE_TABLE_WORK_USED (range_table_work)
3154 || RANGE_TABLE_WORK_BITS (range_table_work))
3156 int i;
3157 int used = RANGE_TABLE_WORK_USED (range_table_work);
3159 /* Allocate space for COUNT + RANGE_TABLE. Needs two
3160 bytes for flags, two for COUNT, and three bytes for
3161 each character. */
3162 GET_BUFFER_SPACE (4 + used * 3);
3164 /* Indicate the existence of range table. */
3165 laststart[1] |= 0x80;
3167 /* Store the character class flag bits into the range table.
3168 If not in emacs, these flag bits are always 0. */
3169 *b++ = RANGE_TABLE_WORK_BITS (range_table_work) & 0xff;
3170 *b++ = RANGE_TABLE_WORK_BITS (range_table_work) >> 8;
3172 STORE_NUMBER_AND_INCR (b, used / 2);
3173 for (i = 0; i < used; i++)
3174 STORE_CHARACTER_AND_INCR
3175 (b, RANGE_TABLE_WORK_ELT (range_table_work, i));
3178 break;
3181 case '(':
3182 if (syntax & RE_NO_BK_PARENS)
3183 goto handle_open;
3184 else
3185 goto normal_char;
3188 case ')':
3189 if (syntax & RE_NO_BK_PARENS)
3190 goto handle_close;
3191 else
3192 goto normal_char;
3195 case '\n':
3196 if (syntax & RE_NEWLINE_ALT)
3197 goto handle_alt;
3198 else
3199 goto normal_char;
3202 case '|':
3203 if (syntax & RE_NO_BK_VBAR)
3204 goto handle_alt;
3205 else
3206 goto normal_char;
3209 case '{':
3210 if (syntax & RE_INTERVALS && syntax & RE_NO_BK_BRACES)
3211 goto handle_interval;
3212 else
3213 goto normal_char;
3216 case '\\':
3217 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
3219 /* Do not translate the character after the \, so that we can
3220 distinguish, e.g., \B from \b, even if we normally would
3221 translate, e.g., B to b. */
3222 PATFETCH (c);
3224 switch (c)
3226 case '(':
3227 if (syntax & RE_NO_BK_PARENS)
3228 goto normal_backslash;
3230 handle_open:
3232 int shy = 0;
3233 regnum_t regnum = 0;
3234 if (p+1 < pend)
3236 /* Look for a special (?...) construct */
3237 if ((syntax & RE_SHY_GROUPS) && *p == '?')
3239 PATFETCH (c); /* Gobble up the '?'. */
3240 while (!shy)
3242 PATFETCH (c);
3243 switch (c)
3245 case ':': shy = 1; break;
3246 case '0':
3247 /* An explicitly specified regnum must start
3248 with non-0. */
3249 if (regnum == 0)
3250 FREE_STACK_RETURN (REG_BADPAT);
3251 case '1': case '2': case '3': case '4':
3252 case '5': case '6': case '7': case '8': case '9':
3253 regnum = 10*regnum + (c - '0'); break;
3254 default:
3255 /* Only (?:...) is supported right now. */
3256 FREE_STACK_RETURN (REG_BADPAT);
3262 if (!shy)
3263 regnum = ++bufp->re_nsub;
3264 else if (regnum)
3265 { /* It's actually not shy, but explicitly numbered. */
3266 shy = 0;
3267 if (regnum > bufp->re_nsub)
3268 bufp->re_nsub = regnum;
3269 else if (regnum > bufp->re_nsub
3270 /* Ideally, we'd want to check that the specified
3271 group can't have matched (i.e. all subgroups
3272 using the same regnum are in other branches of
3273 OR patterns), but we don't currently keep track
3274 of enough info to do that easily. */
3275 || group_in_compile_stack (compile_stack, regnum))
3276 FREE_STACK_RETURN (REG_BADPAT);
3278 else
3279 /* It's really shy. */
3280 regnum = - bufp->re_nsub;
3282 if (COMPILE_STACK_FULL)
3284 RETALLOC (compile_stack.stack, compile_stack.size << 1,
3285 compile_stack_elt_t);
3286 if (compile_stack.stack == NULL) return REG_ESPACE;
3288 compile_stack.size <<= 1;
3291 /* These are the values to restore when we hit end of this
3292 group. They are all relative offsets, so that if the
3293 whole pattern moves because of realloc, they will still
3294 be valid. */
3295 COMPILE_STACK_TOP.begalt_offset = begalt - bufp->buffer;
3296 COMPILE_STACK_TOP.fixup_alt_jump
3297 = fixup_alt_jump ? fixup_alt_jump - bufp->buffer + 1 : 0;
3298 COMPILE_STACK_TOP.laststart_offset = b - bufp->buffer;
3299 COMPILE_STACK_TOP.regnum = regnum;
3301 /* Do not push a start_memory for groups beyond the last one
3302 we can represent in the compiled pattern. */
3303 if (regnum <= MAX_REGNUM && regnum > 0)
3304 BUF_PUSH_2 (start_memory, regnum);
3306 compile_stack.avail++;
3308 fixup_alt_jump = 0;
3309 laststart = 0;
3310 begalt = b;
3311 /* If we've reached MAX_REGNUM groups, then this open
3312 won't actually generate any code, so we'll have to
3313 clear pending_exact explicitly. */
3314 pending_exact = 0;
3315 break;
3318 case ')':
3319 if (syntax & RE_NO_BK_PARENS) goto normal_backslash;
3321 if (COMPILE_STACK_EMPTY)
3323 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
3324 goto normal_backslash;
3325 else
3326 FREE_STACK_RETURN (REG_ERPAREN);
3329 handle_close:
3330 FIXUP_ALT_JUMP ();
3332 /* See similar code for backslashed left paren above. */
3333 if (COMPILE_STACK_EMPTY)
3335 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
3336 goto normal_char;
3337 else
3338 FREE_STACK_RETURN (REG_ERPAREN);
3341 /* Since we just checked for an empty stack above, this
3342 ``can't happen''. */
3343 assert (compile_stack.avail != 0);
3345 /* We don't just want to restore into `regnum', because
3346 later groups should continue to be numbered higher,
3347 as in `(ab)c(de)' -- the second group is #2. */
3348 regnum_t regnum;
3350 compile_stack.avail--;
3351 begalt = bufp->buffer + COMPILE_STACK_TOP.begalt_offset;
3352 fixup_alt_jump
3353 = COMPILE_STACK_TOP.fixup_alt_jump
3354 ? bufp->buffer + COMPILE_STACK_TOP.fixup_alt_jump - 1
3355 : 0;
3356 laststart = bufp->buffer + COMPILE_STACK_TOP.laststart_offset;
3357 regnum = COMPILE_STACK_TOP.regnum;
3358 /* If we've reached MAX_REGNUM groups, then this open
3359 won't actually generate any code, so we'll have to
3360 clear pending_exact explicitly. */
3361 pending_exact = 0;
3363 /* We're at the end of the group, so now we know how many
3364 groups were inside this one. */
3365 if (regnum <= MAX_REGNUM && regnum > 0)
3366 BUF_PUSH_2 (stop_memory, regnum);
3368 break;
3371 case '|': /* `\|'. */
3372 if (syntax & RE_LIMITED_OPS || syntax & RE_NO_BK_VBAR)
3373 goto normal_backslash;
3374 handle_alt:
3375 if (syntax & RE_LIMITED_OPS)
3376 goto normal_char;
3378 /* Insert before the previous alternative a jump which
3379 jumps to this alternative if the former fails. */
3380 GET_BUFFER_SPACE (3);
3381 INSERT_JUMP (on_failure_jump, begalt, b + 6);
3382 pending_exact = 0;
3383 b += 3;
3385 /* The alternative before this one has a jump after it
3386 which gets executed if it gets matched. Adjust that
3387 jump so it will jump to this alternative's analogous
3388 jump (put in below, which in turn will jump to the next
3389 (if any) alternative's such jump, etc.). The last such
3390 jump jumps to the correct final destination. A picture:
3391 _____ _____
3392 | | | |
3393 | v | v
3394 a | b | c
3396 If we are at `b', then fixup_alt_jump right now points to a
3397 three-byte space after `a'. We'll put in the jump, set
3398 fixup_alt_jump to right after `b', and leave behind three
3399 bytes which we'll fill in when we get to after `c'. */
3401 FIXUP_ALT_JUMP ();
3403 /* Mark and leave space for a jump after this alternative,
3404 to be filled in later either by next alternative or
3405 when know we're at the end of a series of alternatives. */
3406 fixup_alt_jump = b;
3407 GET_BUFFER_SPACE (3);
3408 b += 3;
3410 laststart = 0;
3411 begalt = b;
3412 break;
3415 case '{':
3416 /* If \{ is a literal. */
3417 if (!(syntax & RE_INTERVALS)
3418 /* If we're at `\{' and it's not the open-interval
3419 operator. */
3420 || (syntax & RE_NO_BK_BRACES))
3421 goto normal_backslash;
3423 handle_interval:
3425 /* If got here, then the syntax allows intervals. */
3427 /* At least (most) this many matches must be made. */
3428 int lower_bound = 0, upper_bound = -1;
3430 beg_interval = p;
3432 GET_UNSIGNED_NUMBER (lower_bound);
3434 if (c == ',')
3435 GET_UNSIGNED_NUMBER (upper_bound);
3436 else
3437 /* Interval such as `{1}' => match exactly once. */
3438 upper_bound = lower_bound;
3440 if (lower_bound < 0 || upper_bound > RE_DUP_MAX
3441 || (upper_bound >= 0 && lower_bound > upper_bound))
3442 FREE_STACK_RETURN (REG_BADBR);
3444 if (!(syntax & RE_NO_BK_BRACES))
3446 if (c != '\\')
3447 FREE_STACK_RETURN (REG_BADBR);
3448 if (p == pend)
3449 FREE_STACK_RETURN (REG_EESCAPE);
3450 PATFETCH (c);
3453 if (c != '}')
3454 FREE_STACK_RETURN (REG_BADBR);
3456 /* We just parsed a valid interval. */
3458 /* If it's invalid to have no preceding re. */
3459 if (!laststart)
3461 if (syntax & RE_CONTEXT_INVALID_OPS)
3462 FREE_STACK_RETURN (REG_BADRPT);
3463 else if (syntax & RE_CONTEXT_INDEP_OPS)
3464 laststart = b;
3465 else
3466 goto unfetch_interval;
3469 if (upper_bound == 0)
3470 /* If the upper bound is zero, just drop the sub pattern
3471 altogether. */
3472 b = laststart;
3473 else if (lower_bound == 1 && upper_bound == 1)
3474 /* Just match it once: nothing to do here. */
3477 /* Otherwise, we have a nontrivial interval. When
3478 we're all done, the pattern will look like:
3479 set_number_at <jump count> <upper bound>
3480 set_number_at <succeed_n count> <lower bound>
3481 succeed_n <after jump addr> <succeed_n count>
3482 <body of loop>
3483 jump_n <succeed_n addr> <jump count>
3484 (The upper bound and `jump_n' are omitted if
3485 `upper_bound' is 1, though.) */
3486 else
3487 { /* If the upper bound is > 1, we need to insert
3488 more at the end of the loop. */
3489 unsigned int nbytes = (upper_bound < 0 ? 3
3490 : upper_bound > 1 ? 5 : 0);
3491 unsigned int startoffset = 0;
3493 GET_BUFFER_SPACE (20); /* We might use less. */
3495 if (lower_bound == 0)
3497 /* A succeed_n that starts with 0 is really a
3498 a simple on_failure_jump_loop. */
3499 INSERT_JUMP (on_failure_jump_loop, laststart,
3500 b + 3 + nbytes);
3501 b += 3;
3503 else
3505 /* Initialize lower bound of the `succeed_n', even
3506 though it will be set during matching by its
3507 attendant `set_number_at' (inserted next),
3508 because `re_compile_fastmap' needs to know.
3509 Jump to the `jump_n' we might insert below. */
3510 INSERT_JUMP2 (succeed_n, laststart,
3511 b + 5 + nbytes,
3512 lower_bound);
3513 b += 5;
3515 /* Code to initialize the lower bound. Insert
3516 before the `succeed_n'. The `5' is the last two
3517 bytes of this `set_number_at', plus 3 bytes of
3518 the following `succeed_n'. */
3519 insert_op2 (set_number_at, laststart, 5, lower_bound, b);
3520 b += 5;
3521 startoffset += 5;
3524 if (upper_bound < 0)
3526 /* A negative upper bound stands for infinity,
3527 in which case it degenerates to a plain jump. */
3528 STORE_JUMP (jump, b, laststart + startoffset);
3529 b += 3;
3531 else if (upper_bound > 1)
3532 { /* More than one repetition is allowed, so
3533 append a backward jump to the `succeed_n'
3534 that starts this interval.
3536 When we've reached this during matching,
3537 we'll have matched the interval once, so
3538 jump back only `upper_bound - 1' times. */
3539 STORE_JUMP2 (jump_n, b, laststart + startoffset,
3540 upper_bound - 1);
3541 b += 5;
3543 /* The location we want to set is the second
3544 parameter of the `jump_n'; that is `b-2' as
3545 an absolute address. `laststart' will be
3546 the `set_number_at' we're about to insert;
3547 `laststart+3' the number to set, the source
3548 for the relative address. But we are
3549 inserting into the middle of the pattern --
3550 so everything is getting moved up by 5.
3551 Conclusion: (b - 2) - (laststart + 3) + 5,
3552 i.e., b - laststart.
3554 We insert this at the beginning of the loop
3555 so that if we fail during matching, we'll
3556 reinitialize the bounds. */
3557 insert_op2 (set_number_at, laststart, b - laststart,
3558 upper_bound - 1, b);
3559 b += 5;
3562 pending_exact = 0;
3563 beg_interval = NULL;
3565 break;
3567 unfetch_interval:
3568 /* If an invalid interval, match the characters as literals. */
3569 assert (beg_interval);
3570 p = beg_interval;
3571 beg_interval = NULL;
3573 /* normal_char and normal_backslash need `c'. */
3574 c = '{';
3576 if (!(syntax & RE_NO_BK_BRACES))
3578 assert (p > pattern && p[-1] == '\\');
3579 goto normal_backslash;
3581 else
3582 goto normal_char;
3584 #ifdef emacs
3585 /* There is no way to specify the before_dot and after_dot
3586 operators. rms says this is ok. --karl */
3587 case '=':
3588 BUF_PUSH (at_dot);
3589 break;
3591 case 's':
3592 laststart = b;
3593 PATFETCH (c);
3594 BUF_PUSH_2 (syntaxspec, syntax_spec_code[c]);
3595 break;
3597 case 'S':
3598 laststart = b;
3599 PATFETCH (c);
3600 BUF_PUSH_2 (notsyntaxspec, syntax_spec_code[c]);
3601 break;
3603 case 'c':
3604 laststart = b;
3605 PATFETCH (c);
3606 BUF_PUSH_2 (categoryspec, c);
3607 break;
3609 case 'C':
3610 laststart = b;
3611 PATFETCH (c);
3612 BUF_PUSH_2 (notcategoryspec, c);
3613 break;
3614 #endif /* emacs */
3617 case 'w':
3618 if (syntax & RE_NO_GNU_OPS)
3619 goto normal_char;
3620 laststart = b;
3621 BUF_PUSH_2 (syntaxspec, Sword);
3622 break;
3625 case 'W':
3626 if (syntax & RE_NO_GNU_OPS)
3627 goto normal_char;
3628 laststart = b;
3629 BUF_PUSH_2 (notsyntaxspec, Sword);
3630 break;
3633 case '<':
3634 if (syntax & RE_NO_GNU_OPS)
3635 goto normal_char;
3636 BUF_PUSH (wordbeg);
3637 break;
3639 case '>':
3640 if (syntax & RE_NO_GNU_OPS)
3641 goto normal_char;
3642 BUF_PUSH (wordend);
3643 break;
3645 case '_':
3646 if (syntax & RE_NO_GNU_OPS)
3647 goto normal_char;
3648 laststart = b;
3649 PATFETCH (c);
3650 if (c == '<')
3651 BUF_PUSH (symbeg);
3652 else if (c == '>')
3653 BUF_PUSH (symend);
3654 else
3655 FREE_STACK_RETURN (REG_BADPAT);
3656 break;
3658 case 'b':
3659 if (syntax & RE_NO_GNU_OPS)
3660 goto normal_char;
3661 BUF_PUSH (wordbound);
3662 break;
3664 case 'B':
3665 if (syntax & RE_NO_GNU_OPS)
3666 goto normal_char;
3667 BUF_PUSH (notwordbound);
3668 break;
3670 case '`':
3671 if (syntax & RE_NO_GNU_OPS)
3672 goto normal_char;
3673 BUF_PUSH (begbuf);
3674 break;
3676 case '\'':
3677 if (syntax & RE_NO_GNU_OPS)
3678 goto normal_char;
3679 BUF_PUSH (endbuf);
3680 break;
3682 case '1': case '2': case '3': case '4': case '5':
3683 case '6': case '7': case '8': case '9':
3685 regnum_t reg;
3687 if (syntax & RE_NO_BK_REFS)
3688 goto normal_backslash;
3690 reg = c - '0';
3692 if (reg > bufp->re_nsub || reg < 1
3693 /* Can't back reference to a subexp before its end. */
3694 || group_in_compile_stack (compile_stack, reg))
3695 FREE_STACK_RETURN (REG_ESUBREG);
3697 laststart = b;
3698 BUF_PUSH_2 (duplicate, reg);
3700 break;
3703 case '+':
3704 case '?':
3705 if (syntax & RE_BK_PLUS_QM)
3706 goto handle_plus;
3707 else
3708 goto normal_backslash;
3710 default:
3711 normal_backslash:
3712 /* You might think it would be useful for \ to mean
3713 not to translate; but if we don't translate it
3714 it will never match anything. */
3715 goto normal_char;
3717 break;
3720 default:
3721 /* Expects the character in `c'. */
3722 normal_char:
3723 /* If no exactn currently being built. */
3724 if (!pending_exact
3726 /* If last exactn not at current position. */
3727 || pending_exact + *pending_exact + 1 != b
3729 /* We have only one byte following the exactn for the count. */
3730 || *pending_exact >= (1 << BYTEWIDTH) - MAX_MULTIBYTE_LENGTH
3732 /* If followed by a repetition operator. */
3733 || (p != pend && (*p == '*' || *p == '^'))
3734 || ((syntax & RE_BK_PLUS_QM)
3735 ? p + 1 < pend && *p == '\\' && (p[1] == '+' || p[1] == '?')
3736 : p != pend && (*p == '+' || *p == '?'))
3737 || ((syntax & RE_INTERVALS)
3738 && ((syntax & RE_NO_BK_BRACES)
3739 ? p != pend && *p == '{'
3740 : p + 1 < pend && p[0] == '\\' && p[1] == '{')))
3742 /* Start building a new exactn. */
3744 laststart = b;
3746 BUF_PUSH_2 (exactn, 0);
3747 pending_exact = b - 1;
3750 GET_BUFFER_SPACE (MAX_MULTIBYTE_LENGTH);
3752 int len;
3754 if (multibyte)
3756 c = TRANSLATE (c);
3757 len = CHAR_STRING (c, b);
3758 b += len;
3760 else
3762 c1 = RE_CHAR_TO_MULTIBYTE (c);
3763 if (! CHAR_BYTE8_P (c1))
3765 re_wchar_t c2 = TRANSLATE (c1);
3767 if (c1 != c2 && (c1 = RE_CHAR_TO_UNIBYTE (c2)) >= 0)
3768 c = c1;
3770 *b++ = c;
3771 len = 1;
3773 (*pending_exact) += len;
3776 break;
3777 } /* switch (c) */
3778 } /* while p != pend */
3781 /* Through the pattern now. */
3783 FIXUP_ALT_JUMP ();
3785 if (!COMPILE_STACK_EMPTY)
3786 FREE_STACK_RETURN (REG_EPAREN);
3788 /* If we don't want backtracking, force success
3789 the first time we reach the end of the compiled pattern. */
3790 if (syntax & RE_NO_POSIX_BACKTRACKING)
3791 BUF_PUSH (succeed);
3793 /* We have succeeded; set the length of the buffer. */
3794 bufp->used = b - bufp->buffer;
3796 #ifdef DEBUG
3797 if (debug > 0)
3799 re_compile_fastmap (bufp);
3800 DEBUG_PRINT1 ("\nCompiled pattern: \n");
3801 print_compiled_pattern (bufp);
3803 debug--;
3804 #endif /* DEBUG */
3806 #ifndef MATCH_MAY_ALLOCATE
3807 /* Initialize the failure stack to the largest possible stack. This
3808 isn't necessary unless we're trying to avoid calling alloca in
3809 the search and match routines. */
3811 int num_regs = bufp->re_nsub + 1;
3813 if (fail_stack.size < re_max_failures * TYPICAL_FAILURE_SIZE)
3815 fail_stack.size = re_max_failures * TYPICAL_FAILURE_SIZE;
3817 if (! fail_stack.stack)
3818 fail_stack.stack
3819 = (fail_stack_elt_t *) malloc (fail_stack.size
3820 * sizeof (fail_stack_elt_t));
3821 else
3822 fail_stack.stack
3823 = (fail_stack_elt_t *) realloc (fail_stack.stack,
3824 (fail_stack.size
3825 * sizeof (fail_stack_elt_t)));
3828 regex_grow_registers (num_regs);
3830 #endif /* not MATCH_MAY_ALLOCATE */
3832 FREE_STACK_RETURN (REG_NOERROR);
3833 } /* regex_compile */
3835 /* Subroutines for `regex_compile'. */
3837 /* Store OP at LOC followed by two-byte integer parameter ARG. */
3839 static void
3840 store_op1 (re_opcode_t op, unsigned char *loc, int arg)
3842 *loc = (unsigned char) op;
3843 STORE_NUMBER (loc + 1, arg);
3847 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
3849 static void
3850 store_op2 (re_opcode_t op, unsigned char *loc, int arg1, int arg2)
3852 *loc = (unsigned char) op;
3853 STORE_NUMBER (loc + 1, arg1);
3854 STORE_NUMBER (loc + 3, arg2);
3858 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
3859 for OP followed by two-byte integer parameter ARG. */
3861 static void
3862 insert_op1 (re_opcode_t op, unsigned char *loc, int arg, unsigned char *end)
3864 register unsigned char *pfrom = end;
3865 register unsigned char *pto = end + 3;
3867 while (pfrom != loc)
3868 *--pto = *--pfrom;
3870 store_op1 (op, loc, arg);
3874 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
3876 static void
3877 insert_op2 (re_opcode_t op, unsigned char *loc, int arg1, int arg2, unsigned char *end)
3879 register unsigned char *pfrom = end;
3880 register unsigned char *pto = end + 5;
3882 while (pfrom != loc)
3883 *--pto = *--pfrom;
3885 store_op2 (op, loc, arg1, arg2);
3889 /* P points to just after a ^ in PATTERN. Return true if that ^ comes
3890 after an alternative or a begin-subexpression. We assume there is at
3891 least one character before the ^. */
3893 static boolean
3894 at_begline_loc_p (const re_char *pattern, const re_char *p, reg_syntax_t syntax)
3896 re_char *prev = p - 2;
3897 boolean prev_prev_backslash = prev > pattern && prev[-1] == '\\';
3899 return
3900 /* After a subexpression? */
3901 (*prev == '(' && (syntax & RE_NO_BK_PARENS || prev_prev_backslash))
3902 /* After an alternative? */
3903 || (*prev == '|' && (syntax & RE_NO_BK_VBAR || prev_prev_backslash))
3904 /* After a shy subexpression? */
3905 || ((syntax & RE_SHY_GROUPS) && prev - 2 >= pattern
3906 && prev[-1] == '?' && prev[-2] == '('
3907 && (syntax & RE_NO_BK_PARENS
3908 || (prev - 3 >= pattern && prev[-3] == '\\')));
3912 /* The dual of at_begline_loc_p. This one is for $. We assume there is
3913 at least one character after the $, i.e., `P < PEND'. */
3915 static boolean
3916 at_endline_loc_p (const re_char *p, const re_char *pend, reg_syntax_t syntax)
3918 re_char *next = p;
3919 boolean next_backslash = *next == '\\';
3920 re_char *next_next = p + 1 < pend ? p + 1 : 0;
3922 return
3923 /* Before a subexpression? */
3924 (syntax & RE_NO_BK_PARENS ? *next == ')'
3925 : next_backslash && next_next && *next_next == ')')
3926 /* Before an alternative? */
3927 || (syntax & RE_NO_BK_VBAR ? *next == '|'
3928 : next_backslash && next_next && *next_next == '|');
3932 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
3933 false if it's not. */
3935 static boolean
3936 group_in_compile_stack (compile_stack_type compile_stack, regnum_t regnum)
3938 int this_element;
3940 for (this_element = compile_stack.avail - 1;
3941 this_element >= 0;
3942 this_element--)
3943 if (compile_stack.stack[this_element].regnum == regnum)
3944 return true;
3946 return false;
3949 /* analyse_first.
3950 If fastmap is non-NULL, go through the pattern and fill fastmap
3951 with all the possible leading chars. If fastmap is NULL, don't
3952 bother filling it up (obviously) and only return whether the
3953 pattern could potentially match the empty string.
3955 Return 1 if p..pend might match the empty string.
3956 Return 0 if p..pend matches at least one char.
3957 Return -1 if fastmap was not updated accurately. */
3959 static int
3960 analyse_first (const re_char *p, const re_char *pend, char *fastmap, const int multibyte)
3962 int j, k;
3963 boolean not;
3965 /* If all elements for base leading-codes in fastmap is set, this
3966 flag is set true. */
3967 boolean match_any_multibyte_characters = false;
3969 assert (p);
3971 /* The loop below works as follows:
3972 - It has a working-list kept in the PATTERN_STACK and which basically
3973 starts by only containing a pointer to the first operation.
3974 - If the opcode we're looking at is a match against some set of
3975 chars, then we add those chars to the fastmap and go on to the
3976 next work element from the worklist (done via `break').
3977 - If the opcode is a control operator on the other hand, we either
3978 ignore it (if it's meaningless at this point, such as `start_memory')
3979 or execute it (if it's a jump). If the jump has several destinations
3980 (i.e. `on_failure_jump'), then we push the other destination onto the
3981 worklist.
3982 We guarantee termination by ignoring backward jumps (more or less),
3983 so that `p' is monotonically increasing. More to the point, we
3984 never set `p' (or push) anything `<= p1'. */
3986 while (p < pend)
3988 /* `p1' is used as a marker of how far back a `on_failure_jump'
3989 can go without being ignored. It is normally equal to `p'
3990 (which prevents any backward `on_failure_jump') except right
3991 after a plain `jump', to allow patterns such as:
3992 0: jump 10
3993 3..9: <body>
3994 10: on_failure_jump 3
3995 as used for the *? operator. */
3996 re_char *p1 = p;
3998 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
4000 case succeed:
4001 return 1;
4002 continue;
4004 case duplicate:
4005 /* If the first character has to match a backreference, that means
4006 that the group was empty (since it already matched). Since this
4007 is the only case that interests us here, we can assume that the
4008 backreference must match the empty string. */
4009 p++;
4010 continue;
4013 /* Following are the cases which match a character. These end
4014 with `break'. */
4016 case exactn:
4017 if (fastmap)
4019 /* If multibyte is nonzero, the first byte of each
4020 character is an ASCII or a leading code. Otherwise,
4021 each byte is a character. Thus, this works in both
4022 cases. */
4023 fastmap[p[1]] = 1;
4024 if (! multibyte)
4026 /* For the case of matching this unibyte regex
4027 against multibyte, we must set a leading code of
4028 the corresponding multibyte character. */
4029 int c = RE_CHAR_TO_MULTIBYTE (p[1]);
4031 fastmap[CHAR_LEADING_CODE (c)] = 1;
4034 break;
4037 case anychar:
4038 /* We could put all the chars except for \n (and maybe \0)
4039 but we don't bother since it is generally not worth it. */
4040 if (!fastmap) break;
4041 return -1;
4044 case charset_not:
4045 if (!fastmap) break;
4047 /* Chars beyond end of bitmap are possible matches. */
4048 for (j = CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH;
4049 j < (1 << BYTEWIDTH); j++)
4050 fastmap[j] = 1;
4053 /* Fallthrough */
4054 case charset:
4055 if (!fastmap) break;
4056 not = (re_opcode_t) *(p - 1) == charset_not;
4057 for (j = CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH - 1, p++;
4058 j >= 0; j--)
4059 if (!!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))) ^ not)
4060 fastmap[j] = 1;
4062 #ifdef emacs
4063 if (/* Any leading code can possibly start a character
4064 which doesn't match the specified set of characters. */
4067 /* If we can match a character class, we can match any
4068 multibyte characters. */
4069 (CHARSET_RANGE_TABLE_EXISTS_P (&p[-2])
4070 && CHARSET_RANGE_TABLE_BITS (&p[-2]) != 0))
4073 if (match_any_multibyte_characters == false)
4075 for (j = MIN_MULTIBYTE_LEADING_CODE;
4076 j <= MAX_MULTIBYTE_LEADING_CODE; j++)
4077 fastmap[j] = 1;
4078 match_any_multibyte_characters = true;
4082 else if (!not && CHARSET_RANGE_TABLE_EXISTS_P (&p[-2])
4083 && match_any_multibyte_characters == false)
4085 /* Set fastmap[I] to 1 where I is a leading code of each
4086 multibyte character in the range table. */
4087 int c, count;
4088 unsigned char lc1, lc2;
4090 /* Make P points the range table. `+ 2' is to skip flag
4091 bits for a character class. */
4092 p += CHARSET_BITMAP_SIZE (&p[-2]) + 2;
4094 /* Extract the number of ranges in range table into COUNT. */
4095 EXTRACT_NUMBER_AND_INCR (count, p);
4096 for (; count > 0; count--, p += 3)
4098 /* Extract the start and end of each range. */
4099 EXTRACT_CHARACTER (c, p);
4100 lc1 = CHAR_LEADING_CODE (c);
4101 p += 3;
4102 EXTRACT_CHARACTER (c, p);
4103 lc2 = CHAR_LEADING_CODE (c);
4104 for (j = lc1; j <= lc2; j++)
4105 fastmap[j] = 1;
4108 #endif
4109 break;
4111 case syntaxspec:
4112 case notsyntaxspec:
4113 if (!fastmap) break;
4114 #ifndef emacs
4115 not = (re_opcode_t)p[-1] == notsyntaxspec;
4116 k = *p++;
4117 for (j = 0; j < (1 << BYTEWIDTH); j++)
4118 if ((SYNTAX (j) == (enum syntaxcode) k) ^ not)
4119 fastmap[j] = 1;
4120 break;
4121 #else /* emacs */
4122 /* This match depends on text properties. These end with
4123 aborting optimizations. */
4124 return -1;
4126 case categoryspec:
4127 case notcategoryspec:
4128 if (!fastmap) break;
4129 not = (re_opcode_t)p[-1] == notcategoryspec;
4130 k = *p++;
4131 for (j = (1 << BYTEWIDTH); j >= 0; j--)
4132 if ((CHAR_HAS_CATEGORY (j, k)) ^ not)
4133 fastmap[j] = 1;
4135 /* Any leading code can possibly start a character which
4136 has or doesn't has the specified category. */
4137 if (match_any_multibyte_characters == false)
4139 for (j = MIN_MULTIBYTE_LEADING_CODE;
4140 j <= MAX_MULTIBYTE_LEADING_CODE; j++)
4141 fastmap[j] = 1;
4142 match_any_multibyte_characters = true;
4144 break;
4146 /* All cases after this match the empty string. These end with
4147 `continue'. */
4149 case before_dot:
4150 case at_dot:
4151 case after_dot:
4152 #endif /* !emacs */
4153 case no_op:
4154 case begline:
4155 case endline:
4156 case begbuf:
4157 case endbuf:
4158 case wordbound:
4159 case notwordbound:
4160 case wordbeg:
4161 case wordend:
4162 case symbeg:
4163 case symend:
4164 continue;
4167 case jump:
4168 EXTRACT_NUMBER_AND_INCR (j, p);
4169 if (j < 0)
4170 /* Backward jumps can only go back to code that we've already
4171 visited. `re_compile' should make sure this is true. */
4172 break;
4173 p += j;
4174 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p))
4176 case on_failure_jump:
4177 case on_failure_keep_string_jump:
4178 case on_failure_jump_loop:
4179 case on_failure_jump_nastyloop:
4180 case on_failure_jump_smart:
4181 p++;
4182 break;
4183 default:
4184 continue;
4186 /* Keep `p1' to allow the `on_failure_jump' we are jumping to
4187 to jump back to "just after here". */
4188 /* Fallthrough */
4190 case on_failure_jump:
4191 case on_failure_keep_string_jump:
4192 case on_failure_jump_nastyloop:
4193 case on_failure_jump_loop:
4194 case on_failure_jump_smart:
4195 EXTRACT_NUMBER_AND_INCR (j, p);
4196 if (p + j <= p1)
4197 ; /* Backward jump to be ignored. */
4198 else
4199 { /* We have to look down both arms.
4200 We first go down the "straight" path so as to minimize
4201 stack usage when going through alternatives. */
4202 int r = analyse_first (p, pend, fastmap, multibyte);
4203 if (r) return r;
4204 p += j;
4206 continue;
4209 case jump_n:
4210 /* This code simply does not properly handle forward jump_n. */
4211 DEBUG_STATEMENT (EXTRACT_NUMBER (j, p); assert (j < 0));
4212 p += 4;
4213 /* jump_n can either jump or fall through. The (backward) jump
4214 case has already been handled, so we only need to look at the
4215 fallthrough case. */
4216 continue;
4218 case succeed_n:
4219 /* If N == 0, it should be an on_failure_jump_loop instead. */
4220 DEBUG_STATEMENT (EXTRACT_NUMBER (j, p + 2); assert (j > 0));
4221 p += 4;
4222 /* We only care about one iteration of the loop, so we don't
4223 need to consider the case where this behaves like an
4224 on_failure_jump. */
4225 continue;
4228 case set_number_at:
4229 p += 4;
4230 continue;
4233 case start_memory:
4234 case stop_memory:
4235 p += 1;
4236 continue;
4239 default:
4240 abort (); /* We have listed all the cases. */
4241 } /* switch *p++ */
4243 /* Getting here means we have found the possible starting
4244 characters for one path of the pattern -- and that the empty
4245 string does not match. We need not follow this path further. */
4246 return 0;
4247 } /* while p */
4249 /* We reached the end without matching anything. */
4250 return 1;
4252 } /* analyse_first */
4254 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
4255 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
4256 characters can start a string that matches the pattern. This fastmap
4257 is used by re_search to skip quickly over impossible starting points.
4259 Character codes above (1 << BYTEWIDTH) are not represented in the
4260 fastmap, but the leading codes are represented. Thus, the fastmap
4261 indicates which character sets could start a match.
4263 The caller must supply the address of a (1 << BYTEWIDTH)-byte data
4264 area as BUFP->fastmap.
4266 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
4267 the pattern buffer.
4269 Returns 0 if we succeed, -2 if an internal error. */
4272 re_compile_fastmap (struct re_pattern_buffer *bufp)
4274 char *fastmap = bufp->fastmap;
4275 int analysis;
4277 assert (fastmap && bufp->buffer);
4279 memset (fastmap, 0, 1 << BYTEWIDTH); /* Assume nothing's valid. */
4280 bufp->fastmap_accurate = 1; /* It will be when we're done. */
4282 analysis = analyse_first (bufp->buffer, bufp->buffer + bufp->used,
4283 fastmap, RE_MULTIBYTE_P (bufp));
4284 bufp->can_be_null = (analysis != 0);
4285 return 0;
4286 } /* re_compile_fastmap */
4288 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
4289 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
4290 this memory for recording register information. STARTS and ENDS
4291 must be allocated using the malloc library routine, and must each
4292 be at least NUM_REGS * sizeof (regoff_t) bytes long.
4294 If NUM_REGS == 0, then subsequent matches should allocate their own
4295 register data.
4297 Unless this function is called, the first search or match using
4298 PATTERN_BUFFER will allocate its own register data, without
4299 freeing the old data. */
4301 void
4302 re_set_registers (struct re_pattern_buffer *bufp, struct re_registers *regs, unsigned int num_regs, regoff_t *starts, regoff_t *ends)
4304 if (num_regs)
4306 bufp->regs_allocated = REGS_REALLOCATE;
4307 regs->num_regs = num_regs;
4308 regs->start = starts;
4309 regs->end = ends;
4311 else
4313 bufp->regs_allocated = REGS_UNALLOCATED;
4314 regs->num_regs = 0;
4315 regs->start = regs->end = (regoff_t *) 0;
4318 WEAK_ALIAS (__re_set_registers, re_set_registers)
4320 /* Searching routines. */
4322 /* Like re_search_2, below, but only one string is specified, and
4323 doesn't let you say where to stop matching. */
4326 re_search (struct re_pattern_buffer *bufp, const char *string, int size, int startpos, int range, struct re_registers *regs)
4328 return re_search_2 (bufp, NULL, 0, string, size, startpos, range,
4329 regs, size);
4331 WEAK_ALIAS (__re_search, re_search)
4333 /* Head address of virtual concatenation of string. */
4334 #define HEAD_ADDR_VSTRING(P) \
4335 (((P) >= size1 ? string2 : string1))
4337 /* End address of virtual concatenation of string. */
4338 #define STOP_ADDR_VSTRING(P) \
4339 (((P) >= size1 ? string2 + size2 : string1 + size1))
4341 /* Address of POS in the concatenation of virtual string. */
4342 #define POS_ADDR_VSTRING(POS) \
4343 (((POS) >= size1 ? string2 - size1 : string1) + (POS))
4345 /* Using the compiled pattern in BUFP->buffer, first tries to match the
4346 virtual concatenation of STRING1 and STRING2, starting first at index
4347 STARTPOS, then at STARTPOS + 1, and so on.
4349 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
4351 RANGE is how far to scan while trying to match. RANGE = 0 means try
4352 only at STARTPOS; in general, the last start tried is STARTPOS +
4353 RANGE.
4355 In REGS, return the indices of the virtual concatenation of STRING1
4356 and STRING2 that matched the entire BUFP->buffer and its contained
4357 subexpressions.
4359 Do not consider matching one past the index STOP in the virtual
4360 concatenation of STRING1 and STRING2.
4362 We return either the position in the strings at which the match was
4363 found, -1 if no match, or -2 if error (such as failure
4364 stack overflow). */
4367 re_search_2 (struct re_pattern_buffer *bufp, const char *str1, int size1, const char *str2, int size2, int startpos, int range, struct re_registers *regs, int stop)
4369 int val;
4370 re_char *string1 = (re_char*) str1;
4371 re_char *string2 = (re_char*) str2;
4372 register char *fastmap = bufp->fastmap;
4373 register RE_TRANSLATE_TYPE translate = bufp->translate;
4374 int total_size = size1 + size2;
4375 int endpos = startpos + range;
4376 boolean anchored_start;
4377 /* Nonzero if we are searching multibyte string. */
4378 const boolean multibyte = RE_TARGET_MULTIBYTE_P (bufp);
4380 /* Check for out-of-range STARTPOS. */
4381 if (startpos < 0 || startpos > total_size)
4382 return -1;
4384 /* Fix up RANGE if it might eventually take us outside
4385 the virtual concatenation of STRING1 and STRING2.
4386 Make sure we won't move STARTPOS below 0 or above TOTAL_SIZE. */
4387 if (endpos < 0)
4388 range = 0 - startpos;
4389 else if (endpos > total_size)
4390 range = total_size - startpos;
4392 /* If the search isn't to be a backwards one, don't waste time in a
4393 search for a pattern anchored at beginning of buffer. */
4394 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == begbuf && range > 0)
4396 if (startpos > 0)
4397 return -1;
4398 else
4399 range = 0;
4402 #ifdef emacs
4403 /* In a forward search for something that starts with \=.
4404 don't keep searching past point. */
4405 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == at_dot && range > 0)
4407 range = PT_BYTE - BEGV_BYTE - startpos;
4408 if (range < 0)
4409 return -1;
4411 #endif /* emacs */
4413 /* Update the fastmap now if not correct already. */
4414 if (fastmap && !bufp->fastmap_accurate)
4415 re_compile_fastmap (bufp);
4417 /* See whether the pattern is anchored. */
4418 anchored_start = (bufp->buffer[0] == begline);
4420 #ifdef emacs
4421 gl_state.object = re_match_object; /* Used by SYNTAX_TABLE_BYTE_TO_CHAR. */
4423 int charpos = SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (startpos));
4425 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object, charpos, 1);
4427 #endif
4429 /* Loop through the string, looking for a place to start matching. */
4430 for (;;)
4432 /* If the pattern is anchored,
4433 skip quickly past places we cannot match.
4434 We don't bother to treat startpos == 0 specially
4435 because that case doesn't repeat. */
4436 if (anchored_start && startpos > 0)
4438 if (! ((startpos <= size1 ? string1[startpos - 1]
4439 : string2[startpos - size1 - 1])
4440 == '\n'))
4441 goto advance;
4444 /* If a fastmap is supplied, skip quickly over characters that
4445 cannot be the start of a match. If the pattern can match the
4446 null string, however, we don't need to skip characters; we want
4447 the first null string. */
4448 if (fastmap && startpos < total_size && !bufp->can_be_null)
4450 register re_char *d;
4451 register re_wchar_t buf_ch;
4453 d = POS_ADDR_VSTRING (startpos);
4455 if (range > 0) /* Searching forwards. */
4457 register int lim = 0;
4458 int irange = range;
4460 if (startpos < size1 && startpos + range >= size1)
4461 lim = range - (size1 - startpos);
4463 /* Written out as an if-else to avoid testing `translate'
4464 inside the loop. */
4465 if (RE_TRANSLATE_P (translate))
4467 if (multibyte)
4468 while (range > lim)
4470 int buf_charlen;
4472 buf_ch = STRING_CHAR_AND_LENGTH (d, buf_charlen);
4473 buf_ch = RE_TRANSLATE (translate, buf_ch);
4474 if (fastmap[CHAR_LEADING_CODE (buf_ch)])
4475 break;
4477 range -= buf_charlen;
4478 d += buf_charlen;
4480 else
4481 while (range > lim)
4483 register re_wchar_t ch, translated;
4485 buf_ch = *d;
4486 ch = RE_CHAR_TO_MULTIBYTE (buf_ch);
4487 translated = RE_TRANSLATE (translate, ch);
4488 if (translated != ch
4489 && (ch = RE_CHAR_TO_UNIBYTE (translated)) >= 0)
4490 buf_ch = ch;
4491 if (fastmap[buf_ch])
4492 break;
4493 d++;
4494 range--;
4497 else
4499 if (multibyte)
4500 while (range > lim)
4502 int buf_charlen;
4504 buf_ch = STRING_CHAR_AND_LENGTH (d, buf_charlen);
4505 if (fastmap[CHAR_LEADING_CODE (buf_ch)])
4506 break;
4507 range -= buf_charlen;
4508 d += buf_charlen;
4510 else
4511 while (range > lim && !fastmap[*d])
4513 d++;
4514 range--;
4517 startpos += irange - range;
4519 else /* Searching backwards. */
4521 if (multibyte)
4523 buf_ch = STRING_CHAR (d);
4524 buf_ch = TRANSLATE (buf_ch);
4525 if (! fastmap[CHAR_LEADING_CODE (buf_ch)])
4526 goto advance;
4528 else
4530 register re_wchar_t ch, translated;
4532 buf_ch = *d;
4533 ch = RE_CHAR_TO_MULTIBYTE (buf_ch);
4534 translated = TRANSLATE (ch);
4535 if (translated != ch
4536 && (ch = RE_CHAR_TO_UNIBYTE (translated)) >= 0)
4537 buf_ch = ch;
4538 if (! fastmap[TRANSLATE (buf_ch)])
4539 goto advance;
4544 /* If can't match the null string, and that's all we have left, fail. */
4545 if (range >= 0 && startpos == total_size && fastmap
4546 && !bufp->can_be_null)
4547 return -1;
4549 val = re_match_2_internal (bufp, string1, size1, string2, size2,
4550 startpos, regs, stop);
4552 if (val >= 0)
4553 return startpos;
4555 if (val == -2)
4556 return -2;
4558 advance:
4559 if (!range)
4560 break;
4561 else if (range > 0)
4563 /* Update STARTPOS to the next character boundary. */
4564 if (multibyte)
4566 re_char *p = POS_ADDR_VSTRING (startpos);
4567 re_char *pend = STOP_ADDR_VSTRING (startpos);
4568 int len = BYTES_BY_CHAR_HEAD (*p);
4570 range -= len;
4571 if (range < 0)
4572 break;
4573 startpos += len;
4575 else
4577 range--;
4578 startpos++;
4581 else
4583 range++;
4584 startpos--;
4586 /* Update STARTPOS to the previous character boundary. */
4587 if (multibyte)
4589 re_char *p = POS_ADDR_VSTRING (startpos) + 1;
4590 re_char *p0 = p;
4591 re_char *phead = HEAD_ADDR_VSTRING (startpos);
4593 /* Find the head of multibyte form. */
4594 PREV_CHAR_BOUNDARY (p, phead);
4595 range += p0 - 1 - p;
4596 if (range > 0)
4597 break;
4599 startpos -= p0 - 1 - p;
4603 return -1;
4604 } /* re_search_2 */
4605 WEAK_ALIAS (__re_search_2, re_search_2)
4607 /* Declarations and macros for re_match_2. */
4609 static int bcmp_translate _RE_ARGS((re_char *s1, re_char *s2,
4610 register int len,
4611 RE_TRANSLATE_TYPE translate,
4612 const int multibyte));
4614 /* This converts PTR, a pointer into one of the search strings `string1'
4615 and `string2' into an offset from the beginning of that string. */
4616 #define POINTER_TO_OFFSET(ptr) \
4617 (FIRST_STRING_P (ptr) \
4618 ? ((regoff_t) ((ptr) - string1)) \
4619 : ((regoff_t) ((ptr) - string2 + size1)))
4621 /* Call before fetching a character with *d. This switches over to
4622 string2 if necessary.
4623 Check re_match_2_internal for a discussion of why end_match_2 might
4624 not be within string2 (but be equal to end_match_1 instead). */
4625 #define PREFETCH() \
4626 while (d == dend) \
4628 /* End of string2 => fail. */ \
4629 if (dend == end_match_2) \
4630 goto fail; \
4631 /* End of string1 => advance to string2. */ \
4632 d = string2; \
4633 dend = end_match_2; \
4636 /* Call before fetching a char with *d if you already checked other limits.
4637 This is meant for use in lookahead operations like wordend, etc..
4638 where we might need to look at parts of the string that might be
4639 outside of the LIMITs (i.e past `stop'). */
4640 #define PREFETCH_NOLIMIT() \
4641 if (d == end1) \
4643 d = string2; \
4644 dend = end_match_2; \
4647 /* Test if at very beginning or at very end of the virtual concatenation
4648 of `string1' and `string2'. If only one string, it's `string2'. */
4649 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
4650 #define AT_STRINGS_END(d) ((d) == end2)
4653 /* Test if D points to a character which is word-constituent. We have
4654 two special cases to check for: if past the end of string1, look at
4655 the first character in string2; and if before the beginning of
4656 string2, look at the last character in string1. */
4657 #define WORDCHAR_P(d) \
4658 (SYNTAX ((d) == end1 ? *string2 \
4659 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
4660 == Sword)
4662 /* Disabled due to a compiler bug -- see comment at case wordbound */
4664 /* The comment at case wordbound is following one, but we don't use
4665 AT_WORD_BOUNDARY anymore to support multibyte form.
4667 The DEC Alpha C compiler 3.x generates incorrect code for the
4668 test WORDCHAR_P (d - 1) != WORDCHAR_P (d) in the expansion of
4669 AT_WORD_BOUNDARY, so this code is disabled. Expanding the
4670 macro and introducing temporary variables works around the bug. */
4672 #if 0
4673 /* Test if the character before D and the one at D differ with respect
4674 to being word-constituent. */
4675 #define AT_WORD_BOUNDARY(d) \
4676 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
4677 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
4678 #endif
4680 /* Free everything we malloc. */
4681 #ifdef MATCH_MAY_ALLOCATE
4682 # define FREE_VAR(var) if (var) { REGEX_FREE (var); var = NULL; } else
4683 # define FREE_VARIABLES() \
4684 do { \
4685 REGEX_FREE_STACK (fail_stack.stack); \
4686 FREE_VAR (regstart); \
4687 FREE_VAR (regend); \
4688 FREE_VAR (best_regstart); \
4689 FREE_VAR (best_regend); \
4690 } while (0)
4691 #else
4692 # define FREE_VARIABLES() ((void)0) /* Do nothing! But inhibit gcc warning. */
4693 #endif /* not MATCH_MAY_ALLOCATE */
4696 /* Optimization routines. */
4698 /* If the operation is a match against one or more chars,
4699 return a pointer to the next operation, else return NULL. */
4700 static re_char *
4701 skip_one_char (const re_char *p)
4703 switch (SWITCH_ENUM_CAST (*p++))
4705 case anychar:
4706 break;
4708 case exactn:
4709 p += *p + 1;
4710 break;
4712 case charset_not:
4713 case charset:
4714 if (CHARSET_RANGE_TABLE_EXISTS_P (p - 1))
4716 int mcnt;
4717 p = CHARSET_RANGE_TABLE (p - 1);
4718 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4719 p = CHARSET_RANGE_TABLE_END (p, mcnt);
4721 else
4722 p += 1 + CHARSET_BITMAP_SIZE (p - 1);
4723 break;
4725 case syntaxspec:
4726 case notsyntaxspec:
4727 #ifdef emacs
4728 case categoryspec:
4729 case notcategoryspec:
4730 #endif /* emacs */
4731 p++;
4732 break;
4734 default:
4735 p = NULL;
4737 return p;
4741 /* Jump over non-matching operations. */
4742 static re_char *
4743 skip_noops (const re_char *p, const re_char *pend)
4745 int mcnt;
4746 while (p < pend)
4748 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p))
4750 case start_memory:
4751 case stop_memory:
4752 p += 2; break;
4753 case no_op:
4754 p += 1; break;
4755 case jump:
4756 p += 1;
4757 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4758 p += mcnt;
4759 break;
4760 default:
4761 return p;
4764 assert (p == pend);
4765 return p;
4768 /* Non-zero if "p1 matches something" implies "p2 fails". */
4769 static int
4770 mutually_exclusive_p (struct re_pattern_buffer *bufp, const re_char *p1, const re_char *p2)
4772 re_opcode_t op2;
4773 const boolean multibyte = RE_MULTIBYTE_P (bufp);
4774 unsigned char *pend = bufp->buffer + bufp->used;
4776 assert (p1 >= bufp->buffer && p1 < pend
4777 && p2 >= bufp->buffer && p2 <= pend);
4779 /* Skip over open/close-group commands.
4780 If what follows this loop is a ...+ construct,
4781 look at what begins its body, since we will have to
4782 match at least one of that. */
4783 p2 = skip_noops (p2, pend);
4784 /* The same skip can be done for p1, except that this function
4785 is only used in the case where p1 is a simple match operator. */
4786 /* p1 = skip_noops (p1, pend); */
4788 assert (p1 >= bufp->buffer && p1 < pend
4789 && p2 >= bufp->buffer && p2 <= pend);
4791 op2 = p2 == pend ? succeed : *p2;
4793 switch (SWITCH_ENUM_CAST (op2))
4795 case succeed:
4796 case endbuf:
4797 /* If we're at the end of the pattern, we can change. */
4798 if (skip_one_char (p1))
4800 DEBUG_PRINT1 (" End of pattern: fast loop.\n");
4801 return 1;
4803 break;
4805 case endline:
4806 case exactn:
4808 register re_wchar_t c
4809 = (re_opcode_t) *p2 == endline ? '\n'
4810 : RE_STRING_CHAR (p2 + 2, multibyte);
4812 if ((re_opcode_t) *p1 == exactn)
4814 if (c != RE_STRING_CHAR (p1 + 2, multibyte))
4816 DEBUG_PRINT3 (" '%c' != '%c' => fast loop.\n", c, p1[2]);
4817 return 1;
4821 else if ((re_opcode_t) *p1 == charset
4822 || (re_opcode_t) *p1 == charset_not)
4824 int not = (re_opcode_t) *p1 == charset_not;
4826 /* Test if C is listed in charset (or charset_not)
4827 at `p1'. */
4828 if (! multibyte || IS_REAL_ASCII (c))
4830 if (c < CHARSET_BITMAP_SIZE (p1) * BYTEWIDTH
4831 && p1[2 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
4832 not = !not;
4834 else if (CHARSET_RANGE_TABLE_EXISTS_P (p1))
4835 CHARSET_LOOKUP_RANGE_TABLE (not, c, p1);
4837 /* `not' is equal to 1 if c would match, which means
4838 that we can't change to pop_failure_jump. */
4839 if (!not)
4841 DEBUG_PRINT1 (" No match => fast loop.\n");
4842 return 1;
4845 else if ((re_opcode_t) *p1 == anychar
4846 && c == '\n')
4848 DEBUG_PRINT1 (" . != \\n => fast loop.\n");
4849 return 1;
4852 break;
4854 case charset:
4856 if ((re_opcode_t) *p1 == exactn)
4857 /* Reuse the code above. */
4858 return mutually_exclusive_p (bufp, p2, p1);
4860 /* It is hard to list up all the character in charset
4861 P2 if it includes multibyte character. Give up in
4862 such case. */
4863 else if (!multibyte || !CHARSET_RANGE_TABLE_EXISTS_P (p2))
4865 /* Now, we are sure that P2 has no range table.
4866 So, for the size of bitmap in P2, `p2[1]' is
4867 enough. But P1 may have range table, so the
4868 size of bitmap table of P1 is extracted by
4869 using macro `CHARSET_BITMAP_SIZE'.
4871 In a multibyte case, we know that all the character
4872 listed in P2 is ASCII. In a unibyte case, P1 has only a
4873 bitmap table. So, in both cases, it is enough to test
4874 only the bitmap table of P1. */
4876 if ((re_opcode_t) *p1 == charset)
4878 int idx;
4879 /* We win if the charset inside the loop
4880 has no overlap with the one after the loop. */
4881 for (idx = 0;
4882 (idx < (int) p2[1]
4883 && idx < CHARSET_BITMAP_SIZE (p1));
4884 idx++)
4885 if ((p2[2 + idx] & p1[2 + idx]) != 0)
4886 break;
4888 if (idx == p2[1]
4889 || idx == CHARSET_BITMAP_SIZE (p1))
4891 DEBUG_PRINT1 (" No match => fast loop.\n");
4892 return 1;
4895 else if ((re_opcode_t) *p1 == charset_not)
4897 int idx;
4898 /* We win if the charset_not inside the loop lists
4899 every character listed in the charset after. */
4900 for (idx = 0; idx < (int) p2[1]; idx++)
4901 if (! (p2[2 + idx] == 0
4902 || (idx < CHARSET_BITMAP_SIZE (p1)
4903 && ((p2[2 + idx] & ~ p1[2 + idx]) == 0))))
4904 break;
4906 if (idx == p2[1])
4908 DEBUG_PRINT1 (" No match => fast loop.\n");
4909 return 1;
4914 break;
4916 case charset_not:
4917 switch (SWITCH_ENUM_CAST (*p1))
4919 case exactn:
4920 case charset:
4921 /* Reuse the code above. */
4922 return mutually_exclusive_p (bufp, p2, p1);
4923 case charset_not:
4924 /* When we have two charset_not, it's very unlikely that
4925 they don't overlap. The union of the two sets of excluded
4926 chars should cover all possible chars, which, as a matter of
4927 fact, is virtually impossible in multibyte buffers. */
4928 break;
4930 break;
4932 case wordend:
4933 return ((re_opcode_t) *p1 == syntaxspec && p1[1] == Sword);
4934 case symend:
4935 return ((re_opcode_t) *p1 == syntaxspec
4936 && (p1[1] == Ssymbol || p1[1] == Sword));
4937 case notsyntaxspec:
4938 return ((re_opcode_t) *p1 == syntaxspec && p1[1] == p2[1]);
4940 case wordbeg:
4941 return ((re_opcode_t) *p1 == notsyntaxspec && p1[1] == Sword);
4942 case symbeg:
4943 return ((re_opcode_t) *p1 == notsyntaxspec
4944 && (p1[1] == Ssymbol || p1[1] == Sword));
4945 case syntaxspec:
4946 return ((re_opcode_t) *p1 == notsyntaxspec && p1[1] == p2[1]);
4948 case wordbound:
4949 return (((re_opcode_t) *p1 == notsyntaxspec
4950 || (re_opcode_t) *p1 == syntaxspec)
4951 && p1[1] == Sword);
4953 #ifdef emacs
4954 case categoryspec:
4955 return ((re_opcode_t) *p1 == notcategoryspec && p1[1] == p2[1]);
4956 case notcategoryspec:
4957 return ((re_opcode_t) *p1 == categoryspec && p1[1] == p2[1]);
4958 #endif /* emacs */
4960 default:
4964 /* Safe default. */
4965 return 0;
4969 /* Matching routines. */
4971 #ifndef emacs /* Emacs never uses this. */
4972 /* re_match is like re_match_2 except it takes only a single string. */
4975 re_match (struct re_pattern_buffer *bufp, const char *string,
4976 int size, int pos, struct re_registers *regs)
4978 int result = re_match_2_internal (bufp, NULL, 0, (re_char*) string, size,
4979 pos, regs, size);
4980 return result;
4982 WEAK_ALIAS (__re_match, re_match)
4983 #endif /* not emacs */
4985 #ifdef emacs
4986 /* In Emacs, this is the string or buffer in which we
4987 are matching. It is used for looking up syntax properties. */
4988 Lisp_Object re_match_object;
4989 #endif
4991 /* re_match_2 matches the compiled pattern in BUFP against the
4992 the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
4993 and SIZE2, respectively). We start matching at POS, and stop
4994 matching at STOP.
4996 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
4997 store offsets for the substring each group matched in REGS. See the
4998 documentation for exactly how many groups we fill.
5000 We return -1 if no match, -2 if an internal error (such as the
5001 failure stack overflowing). Otherwise, we return the length of the
5002 matched substring. */
5005 re_match_2 (struct re_pattern_buffer *bufp, const char *string1, int size1, const char *string2, int size2, int pos, struct re_registers *regs, int stop)
5007 int result;
5009 #ifdef emacs
5010 int charpos;
5011 gl_state.object = re_match_object; /* Used by SYNTAX_TABLE_BYTE_TO_CHAR. */
5012 charpos = SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (pos));
5013 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object, charpos, 1);
5014 #endif
5016 result = re_match_2_internal (bufp, (re_char*) string1, size1,
5017 (re_char*) string2, size2,
5018 pos, regs, stop);
5019 return result;
5021 WEAK_ALIAS (__re_match_2, re_match_2)
5024 /* This is a separate function so that we can force an alloca cleanup
5025 afterwards. */
5026 static int
5027 re_match_2_internal (struct re_pattern_buffer *bufp, const re_char *string1, int size1, const re_char *string2, int size2, int pos, struct re_registers *regs, int stop)
5029 /* General temporaries. */
5030 int mcnt;
5031 size_t reg;
5032 boolean not;
5034 /* Just past the end of the corresponding string. */
5035 re_char *end1, *end2;
5037 /* Pointers into string1 and string2, just past the last characters in
5038 each to consider matching. */
5039 re_char *end_match_1, *end_match_2;
5041 /* Where we are in the data, and the end of the current string. */
5042 re_char *d, *dend;
5044 /* Used sometimes to remember where we were before starting matching
5045 an operator so that we can go back in case of failure. This "atomic"
5046 behavior of matching opcodes is indispensable to the correctness
5047 of the on_failure_keep_string_jump optimization. */
5048 re_char *dfail;
5050 /* Where we are in the pattern, and the end of the pattern. */
5051 re_char *p = bufp->buffer;
5052 re_char *pend = p + bufp->used;
5054 /* We use this to map every character in the string. */
5055 RE_TRANSLATE_TYPE translate = bufp->translate;
5057 /* Nonzero if BUFP is setup from a multibyte regex. */
5058 const boolean multibyte = RE_MULTIBYTE_P (bufp);
5060 /* Nonzero if STRING1/STRING2 are multibyte. */
5061 const boolean target_multibyte = RE_TARGET_MULTIBYTE_P (bufp);
5063 /* Failure point stack. Each place that can handle a failure further
5064 down the line pushes a failure point on this stack. It consists of
5065 regstart, and regend for all registers corresponding to
5066 the subexpressions we're currently inside, plus the number of such
5067 registers, and, finally, two char *'s. The first char * is where
5068 to resume scanning the pattern; the second one is where to resume
5069 scanning the strings. */
5070 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
5071 fail_stack_type fail_stack;
5072 #endif
5073 #ifdef DEBUG
5074 unsigned nfailure_points_pushed = 0, nfailure_points_popped = 0;
5075 #endif
5077 #if defined REL_ALLOC && defined REGEX_MALLOC
5078 /* This holds the pointer to the failure stack, when
5079 it is allocated relocatably. */
5080 fail_stack_elt_t *failure_stack_ptr;
5081 #endif
5083 /* We fill all the registers internally, independent of what we
5084 return, for use in backreferences. The number here includes
5085 an element for register zero. */
5086 size_t num_regs = bufp->re_nsub + 1;
5088 /* Information on the contents of registers. These are pointers into
5089 the input strings; they record just what was matched (on this
5090 attempt) by a subexpression part of the pattern, that is, the
5091 regnum-th regstart pointer points to where in the pattern we began
5092 matching and the regnum-th regend points to right after where we
5093 stopped matching the regnum-th subexpression. (The zeroth register
5094 keeps track of what the whole pattern matches.) */
5095 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5096 re_char **regstart, **regend;
5097 #endif
5099 /* The following record the register info as found in the above
5100 variables when we find a match better than any we've seen before.
5101 This happens as we backtrack through the failure points, which in
5102 turn happens only if we have not yet matched the entire string. */
5103 unsigned best_regs_set = false;
5104 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
5105 re_char **best_regstart, **best_regend;
5106 #endif
5108 /* Logically, this is `best_regend[0]'. But we don't want to have to
5109 allocate space for that if we're not allocating space for anything
5110 else (see below). Also, we never need info about register 0 for
5111 any of the other register vectors, and it seems rather a kludge to
5112 treat `best_regend' differently than the rest. So we keep track of
5113 the end of the best match so far in a separate variable. We
5114 initialize this to NULL so that when we backtrack the first time
5115 and need to test it, it's not garbage. */
5116 re_char *match_end = NULL;
5118 #ifdef DEBUG
5119 /* Counts the total number of registers pushed. */
5120 unsigned num_regs_pushed = 0;
5121 #endif
5123 DEBUG_PRINT1 ("\n\nEntering re_match_2.\n");
5125 INIT_FAIL_STACK ();
5127 #ifdef MATCH_MAY_ALLOCATE
5128 /* Do not bother to initialize all the register variables if there are
5129 no groups in the pattern, as it takes a fair amount of time. If
5130 there are groups, we include space for register 0 (the whole
5131 pattern), even though we never use it, since it simplifies the
5132 array indexing. We should fix this. */
5133 if (bufp->re_nsub)
5135 regstart = REGEX_TALLOC (num_regs, re_char *);
5136 regend = REGEX_TALLOC (num_regs, re_char *);
5137 best_regstart = REGEX_TALLOC (num_regs, re_char *);
5138 best_regend = REGEX_TALLOC (num_regs, re_char *);
5140 if (!(regstart && regend && best_regstart && best_regend))
5142 FREE_VARIABLES ();
5143 return -2;
5146 else
5148 /* We must initialize all our variables to NULL, so that
5149 `FREE_VARIABLES' doesn't try to free them. */
5150 regstart = regend = best_regstart = best_regend = NULL;
5152 #endif /* MATCH_MAY_ALLOCATE */
5154 /* The starting position is bogus. */
5155 if (pos < 0 || pos > size1 + size2)
5157 FREE_VARIABLES ();
5158 return -1;
5161 /* Initialize subexpression text positions to -1 to mark ones that no
5162 start_memory/stop_memory has been seen for. Also initialize the
5163 register information struct. */
5164 for (reg = 1; reg < num_regs; reg++)
5165 regstart[reg] = regend[reg] = NULL;
5167 /* We move `string1' into `string2' if the latter's empty -- but not if
5168 `string1' is null. */
5169 if (size2 == 0 && string1 != NULL)
5171 string2 = string1;
5172 size2 = size1;
5173 string1 = 0;
5174 size1 = 0;
5176 end1 = string1 + size1;
5177 end2 = string2 + size2;
5179 /* `p' scans through the pattern as `d' scans through the data.
5180 `dend' is the end of the input string that `d' points within. `d'
5181 is advanced into the following input string whenever necessary, but
5182 this happens before fetching; therefore, at the beginning of the
5183 loop, `d' can be pointing at the end of a string, but it cannot
5184 equal `string2'. */
5185 if (pos >= size1)
5187 /* Only match within string2. */
5188 d = string2 + pos - size1;
5189 dend = end_match_2 = string2 + stop - size1;
5190 end_match_1 = end1; /* Just to give it a value. */
5192 else
5194 if (stop < size1)
5196 /* Only match within string1. */
5197 end_match_1 = string1 + stop;
5198 /* BEWARE!
5199 When we reach end_match_1, PREFETCH normally switches to string2.
5200 But in the present case, this means that just doing a PREFETCH
5201 makes us jump from `stop' to `gap' within the string.
5202 What we really want here is for the search to stop as
5203 soon as we hit end_match_1. That's why we set end_match_2
5204 to end_match_1 (since PREFETCH fails as soon as we hit
5205 end_match_2). */
5206 end_match_2 = end_match_1;
5208 else
5209 { /* It's important to use this code when stop == size so that
5210 moving `d' from end1 to string2 will not prevent the d == dend
5211 check from catching the end of string. */
5212 end_match_1 = end1;
5213 end_match_2 = string2 + stop - size1;
5215 d = string1 + pos;
5216 dend = end_match_1;
5219 DEBUG_PRINT1 ("The compiled pattern is: ");
5220 DEBUG_PRINT_COMPILED_PATTERN (bufp, p, pend);
5221 DEBUG_PRINT1 ("The string to match is: `");
5222 DEBUG_PRINT_DOUBLE_STRING (d, string1, size1, string2, size2);
5223 DEBUG_PRINT1 ("'\n");
5225 /* This loops over pattern commands. It exits by returning from the
5226 function if the match is complete, or it drops through if the match
5227 fails at this starting point in the input data. */
5228 for (;;)
5230 DEBUG_PRINT2 ("\n%p: ", p);
5232 if (p == pend)
5233 { /* End of pattern means we might have succeeded. */
5234 DEBUG_PRINT1 ("end of pattern ... ");
5236 /* If we haven't matched the entire string, and we want the
5237 longest match, try backtracking. */
5238 if (d != end_match_2)
5240 /* 1 if this match ends in the same string (string1 or string2)
5241 as the best previous match. */
5242 boolean same_str_p = (FIRST_STRING_P (match_end)
5243 == FIRST_STRING_P (d));
5244 /* 1 if this match is the best seen so far. */
5245 boolean best_match_p;
5247 /* AIX compiler got confused when this was combined
5248 with the previous declaration. */
5249 if (same_str_p)
5250 best_match_p = d > match_end;
5251 else
5252 best_match_p = !FIRST_STRING_P (d);
5254 DEBUG_PRINT1 ("backtracking.\n");
5256 if (!FAIL_STACK_EMPTY ())
5257 { /* More failure points to try. */
5259 /* If exceeds best match so far, save it. */
5260 if (!best_regs_set || best_match_p)
5262 best_regs_set = true;
5263 match_end = d;
5265 DEBUG_PRINT1 ("\nSAVING match as best so far.\n");
5267 for (reg = 1; reg < num_regs; reg++)
5269 best_regstart[reg] = regstart[reg];
5270 best_regend[reg] = regend[reg];
5273 goto fail;
5276 /* If no failure points, don't restore garbage. And if
5277 last match is real best match, don't restore second
5278 best one. */
5279 else if (best_regs_set && !best_match_p)
5281 restore_best_regs:
5282 /* Restore best match. It may happen that `dend ==
5283 end_match_1' while the restored d is in string2.
5284 For example, the pattern `x.*y.*z' against the
5285 strings `x-' and `y-z-', if the two strings are
5286 not consecutive in memory. */
5287 DEBUG_PRINT1 ("Restoring best registers.\n");
5289 d = match_end;
5290 dend = ((d >= string1 && d <= end1)
5291 ? end_match_1 : end_match_2);
5293 for (reg = 1; reg < num_regs; reg++)
5295 regstart[reg] = best_regstart[reg];
5296 regend[reg] = best_regend[reg];
5299 } /* d != end_match_2 */
5301 succeed_label:
5302 DEBUG_PRINT1 ("Accepting match.\n");
5304 /* If caller wants register contents data back, do it. */
5305 if (regs && !bufp->no_sub)
5307 /* Have the register data arrays been allocated? */
5308 if (bufp->regs_allocated == REGS_UNALLOCATED)
5309 { /* No. So allocate them with malloc. We need one
5310 extra element beyond `num_regs' for the `-1' marker
5311 GNU code uses. */
5312 regs->num_regs = MAX (RE_NREGS, num_regs + 1);
5313 regs->start = TALLOC (regs->num_regs, regoff_t);
5314 regs->end = TALLOC (regs->num_regs, regoff_t);
5315 if (regs->start == NULL || regs->end == NULL)
5317 FREE_VARIABLES ();
5318 return -2;
5320 bufp->regs_allocated = REGS_REALLOCATE;
5322 else if (bufp->regs_allocated == REGS_REALLOCATE)
5323 { /* Yes. If we need more elements than were already
5324 allocated, reallocate them. If we need fewer, just
5325 leave it alone. */
5326 if (regs->num_regs < num_regs + 1)
5328 regs->num_regs = num_regs + 1;
5329 RETALLOC (regs->start, regs->num_regs, regoff_t);
5330 RETALLOC (regs->end, regs->num_regs, regoff_t);
5331 if (regs->start == NULL || regs->end == NULL)
5333 FREE_VARIABLES ();
5334 return -2;
5338 else
5340 /* These braces fend off a "empty body in an else-statement"
5341 warning under GCC when assert expands to nothing. */
5342 assert (bufp->regs_allocated == REGS_FIXED);
5345 /* Convert the pointer data in `regstart' and `regend' to
5346 indices. Register zero has to be set differently,
5347 since we haven't kept track of any info for it. */
5348 if (regs->num_regs > 0)
5350 regs->start[0] = pos;
5351 regs->end[0] = POINTER_TO_OFFSET (d);
5354 /* Go through the first `min (num_regs, regs->num_regs)'
5355 registers, since that is all we initialized. */
5356 for (reg = 1; reg < MIN (num_regs, regs->num_regs); reg++)
5358 if (REG_UNSET (regstart[reg]) || REG_UNSET (regend[reg]))
5359 regs->start[reg] = regs->end[reg] = -1;
5360 else
5362 regs->start[reg]
5363 = (regoff_t) POINTER_TO_OFFSET (regstart[reg]);
5364 regs->end[reg]
5365 = (regoff_t) POINTER_TO_OFFSET (regend[reg]);
5369 /* If the regs structure we return has more elements than
5370 were in the pattern, set the extra elements to -1. If
5371 we (re)allocated the registers, this is the case,
5372 because we always allocate enough to have at least one
5373 -1 at the end. */
5374 for (reg = num_regs; reg < regs->num_regs; reg++)
5375 regs->start[reg] = regs->end[reg] = -1;
5376 } /* regs && !bufp->no_sub */
5378 DEBUG_PRINT4 ("%u failure points pushed, %u popped (%u remain).\n",
5379 nfailure_points_pushed, nfailure_points_popped,
5380 nfailure_points_pushed - nfailure_points_popped);
5381 DEBUG_PRINT2 ("%u registers pushed.\n", num_regs_pushed);
5383 mcnt = POINTER_TO_OFFSET (d) - pos;
5385 DEBUG_PRINT2 ("Returning %d from re_match_2.\n", mcnt);
5387 FREE_VARIABLES ();
5388 return mcnt;
5391 /* Otherwise match next pattern command. */
5392 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
5394 /* Ignore these. Used to ignore the n of succeed_n's which
5395 currently have n == 0. */
5396 case no_op:
5397 DEBUG_PRINT1 ("EXECUTING no_op.\n");
5398 break;
5400 case succeed:
5401 DEBUG_PRINT1 ("EXECUTING succeed.\n");
5402 goto succeed_label;
5404 /* Match the next n pattern characters exactly. The following
5405 byte in the pattern defines n, and the n bytes after that
5406 are the characters to match. */
5407 case exactn:
5408 mcnt = *p++;
5409 DEBUG_PRINT2 ("EXECUTING exactn %d.\n", mcnt);
5411 /* Remember the start point to rollback upon failure. */
5412 dfail = d;
5414 #ifndef emacs
5415 /* This is written out as an if-else so we don't waste time
5416 testing `translate' inside the loop. */
5417 if (RE_TRANSLATE_P (translate))
5420 PREFETCH ();
5421 if (RE_TRANSLATE (translate, *d) != *p++)
5423 d = dfail;
5424 goto fail;
5426 d++;
5428 while (--mcnt);
5429 else
5432 PREFETCH ();
5433 if (*d++ != *p++)
5435 d = dfail;
5436 goto fail;
5439 while (--mcnt);
5440 #else /* emacs */
5441 /* The cost of testing `translate' is comparatively small. */
5442 if (target_multibyte)
5445 int pat_charlen, buf_charlen;
5446 int pat_ch, buf_ch;
5448 PREFETCH ();
5449 if (multibyte)
5450 pat_ch = STRING_CHAR_AND_LENGTH (p, pat_charlen);
5451 else
5453 pat_ch = RE_CHAR_TO_MULTIBYTE (*p);
5454 pat_charlen = 1;
5456 buf_ch = STRING_CHAR_AND_LENGTH (d, buf_charlen);
5458 if (TRANSLATE (buf_ch) != pat_ch)
5460 d = dfail;
5461 goto fail;
5464 p += pat_charlen;
5465 d += buf_charlen;
5466 mcnt -= pat_charlen;
5468 while (mcnt > 0);
5469 else
5472 int pat_charlen, buf_charlen;
5473 int pat_ch, buf_ch;
5475 PREFETCH ();
5476 if (multibyte)
5478 pat_ch = STRING_CHAR_AND_LENGTH (p, pat_charlen);
5479 pat_ch = RE_CHAR_TO_UNIBYTE (pat_ch);
5481 else
5483 pat_ch = *p;
5484 pat_charlen = 1;
5486 buf_ch = RE_CHAR_TO_MULTIBYTE (*d);
5487 if (! CHAR_BYTE8_P (buf_ch))
5489 buf_ch = TRANSLATE (buf_ch);
5490 buf_ch = RE_CHAR_TO_UNIBYTE (buf_ch);
5491 if (buf_ch < 0)
5492 buf_ch = *d;
5494 else
5495 buf_ch = *d;
5496 if (buf_ch != pat_ch)
5498 d = dfail;
5499 goto fail;
5501 p += pat_charlen;
5502 d++;
5504 while (--mcnt);
5505 #endif
5506 break;
5509 /* Match any character except possibly a newline or a null. */
5510 case anychar:
5512 int buf_charlen;
5513 re_wchar_t buf_ch;
5515 DEBUG_PRINT1 ("EXECUTING anychar.\n");
5517 PREFETCH ();
5518 buf_ch = RE_STRING_CHAR_AND_LENGTH (d, buf_charlen,
5519 target_multibyte);
5520 buf_ch = TRANSLATE (buf_ch);
5522 if ((!(bufp->syntax & RE_DOT_NEWLINE)
5523 && buf_ch == '\n')
5524 || ((bufp->syntax & RE_DOT_NOT_NULL)
5525 && buf_ch == '\000'))
5526 goto fail;
5528 DEBUG_PRINT2 (" Matched `%d'.\n", *d);
5529 d += buf_charlen;
5531 break;
5534 case charset:
5535 case charset_not:
5537 register unsigned int c;
5538 boolean not = (re_opcode_t) *(p - 1) == charset_not;
5539 int len;
5541 /* Start of actual range_table, or end of bitmap if there is no
5542 range table. */
5543 re_char *range_table;
5545 /* Nonzero if there is a range table. */
5546 int range_table_exists;
5548 /* Number of ranges of range table. This is not included
5549 in the initial byte-length of the command. */
5550 int count = 0;
5552 /* Whether matching against a unibyte character. */
5553 boolean unibyte_char = false;
5555 DEBUG_PRINT2 ("EXECUTING charset%s.\n", not ? "_not" : "");
5557 range_table_exists = CHARSET_RANGE_TABLE_EXISTS_P (&p[-1]);
5559 if (range_table_exists)
5561 range_table = CHARSET_RANGE_TABLE (&p[-1]); /* Past the bitmap. */
5562 EXTRACT_NUMBER_AND_INCR (count, range_table);
5565 PREFETCH ();
5566 c = RE_STRING_CHAR_AND_LENGTH (d, len, target_multibyte);
5567 if (target_multibyte)
5569 int c1;
5571 c = TRANSLATE (c);
5572 c1 = RE_CHAR_TO_UNIBYTE (c);
5573 if (c1 >= 0)
5575 unibyte_char = true;
5576 c = c1;
5579 else
5581 int c1 = RE_CHAR_TO_MULTIBYTE (c);
5583 if (! CHAR_BYTE8_P (c1))
5585 c1 = TRANSLATE (c1);
5586 c1 = RE_CHAR_TO_UNIBYTE (c1);
5587 if (c1 >= 0)
5589 unibyte_char = true;
5590 c = c1;
5593 else
5594 unibyte_char = true;
5597 if (unibyte_char && c < (1 << BYTEWIDTH))
5598 { /* Lookup bitmap. */
5599 /* Cast to `unsigned' instead of `unsigned char' in
5600 case the bit list is a full 32 bytes long. */
5601 if (c < (unsigned) (CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH)
5602 && p[1 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
5603 not = !not;
5605 #ifdef emacs
5606 else if (range_table_exists)
5608 int class_bits = CHARSET_RANGE_TABLE_BITS (&p[-1]);
5610 if ( (class_bits & BIT_LOWER && ISLOWER (c))
5611 | (class_bits & BIT_MULTIBYTE)
5612 | (class_bits & BIT_PUNCT && ISPUNCT (c))
5613 | (class_bits & BIT_SPACE && ISSPACE (c))
5614 | (class_bits & BIT_UPPER && ISUPPER (c))
5615 | (class_bits & BIT_WORD && ISWORD (c)))
5616 not = !not;
5617 else
5618 CHARSET_LOOKUP_RANGE_TABLE_RAW (not, c, range_table, count);
5620 #endif /* emacs */
5622 if (range_table_exists)
5623 p = CHARSET_RANGE_TABLE_END (range_table, count);
5624 else
5625 p += CHARSET_BITMAP_SIZE (&p[-1]) + 1;
5627 if (!not) goto fail;
5629 d += len;
5630 break;
5634 /* The beginning of a group is represented by start_memory.
5635 The argument is the register number. The text
5636 matched within the group is recorded (in the internal
5637 registers data structure) under the register number. */
5638 case start_memory:
5639 DEBUG_PRINT2 ("EXECUTING start_memory %d:\n", *p);
5641 /* In case we need to undo this operation (via backtracking). */
5642 PUSH_FAILURE_REG ((unsigned int)*p);
5644 regstart[*p] = d;
5645 regend[*p] = NULL; /* probably unnecessary. -sm */
5646 DEBUG_PRINT2 (" regstart: %d\n", POINTER_TO_OFFSET (regstart[*p]));
5648 /* Move past the register number and inner group count. */
5649 p += 1;
5650 break;
5653 /* The stop_memory opcode represents the end of a group. Its
5654 argument is the same as start_memory's: the register number. */
5655 case stop_memory:
5656 DEBUG_PRINT2 ("EXECUTING stop_memory %d:\n", *p);
5658 assert (!REG_UNSET (regstart[*p]));
5659 /* Strictly speaking, there should be code such as:
5661 assert (REG_UNSET (regend[*p]));
5662 PUSH_FAILURE_REGSTOP ((unsigned int)*p);
5664 But the only info to be pushed is regend[*p] and it is known to
5665 be UNSET, so there really isn't anything to push.
5666 Not pushing anything, on the other hand deprives us from the
5667 guarantee that regend[*p] is UNSET since undoing this operation
5668 will not reset its value properly. This is not important since
5669 the value will only be read on the next start_memory or at
5670 the very end and both events can only happen if this stop_memory
5671 is *not* undone. */
5673 regend[*p] = d;
5674 DEBUG_PRINT2 (" regend: %d\n", POINTER_TO_OFFSET (regend[*p]));
5676 /* Move past the register number and the inner group count. */
5677 p += 1;
5678 break;
5681 /* \<digit> has been turned into a `duplicate' command which is
5682 followed by the numeric value of <digit> as the register number. */
5683 case duplicate:
5685 register re_char *d2, *dend2;
5686 int regno = *p++; /* Get which register to match against. */
5687 DEBUG_PRINT2 ("EXECUTING duplicate %d.\n", regno);
5689 /* Can't back reference a group which we've never matched. */
5690 if (REG_UNSET (regstart[regno]) || REG_UNSET (regend[regno]))
5691 goto fail;
5693 /* Where in input to try to start matching. */
5694 d2 = regstart[regno];
5696 /* Remember the start point to rollback upon failure. */
5697 dfail = d;
5699 /* Where to stop matching; if both the place to start and
5700 the place to stop matching are in the same string, then
5701 set to the place to stop, otherwise, for now have to use
5702 the end of the first string. */
5704 dend2 = ((FIRST_STRING_P (regstart[regno])
5705 == FIRST_STRING_P (regend[regno]))
5706 ? regend[regno] : end_match_1);
5707 for (;;)
5709 /* If necessary, advance to next segment in register
5710 contents. */
5711 while (d2 == dend2)
5713 if (dend2 == end_match_2) break;
5714 if (dend2 == regend[regno]) break;
5716 /* End of string1 => advance to string2. */
5717 d2 = string2;
5718 dend2 = regend[regno];
5720 /* At end of register contents => success */
5721 if (d2 == dend2) break;
5723 /* If necessary, advance to next segment in data. */
5724 PREFETCH ();
5726 /* How many characters left in this segment to match. */
5727 mcnt = dend - d;
5729 /* Want how many consecutive characters we can match in
5730 one shot, so, if necessary, adjust the count. */
5731 if (mcnt > dend2 - d2)
5732 mcnt = dend2 - d2;
5734 /* Compare that many; failure if mismatch, else move
5735 past them. */
5736 if (RE_TRANSLATE_P (translate)
5737 ? bcmp_translate (d, d2, mcnt, translate, target_multibyte)
5738 : memcmp (d, d2, mcnt))
5740 d = dfail;
5741 goto fail;
5743 d += mcnt, d2 += mcnt;
5746 break;
5749 /* begline matches the empty string at the beginning of the string
5750 (unless `not_bol' is set in `bufp'), and after newlines. */
5751 case begline:
5752 DEBUG_PRINT1 ("EXECUTING begline.\n");
5754 if (AT_STRINGS_BEG (d))
5756 if (!bufp->not_bol) break;
5758 else
5760 unsigned c;
5761 GET_CHAR_BEFORE_2 (c, d, string1, end1, string2, end2);
5762 if (c == '\n')
5763 break;
5765 /* In all other cases, we fail. */
5766 goto fail;
5769 /* endline is the dual of begline. */
5770 case endline:
5771 DEBUG_PRINT1 ("EXECUTING endline.\n");
5773 if (AT_STRINGS_END (d))
5775 if (!bufp->not_eol) break;
5777 else
5779 PREFETCH_NOLIMIT ();
5780 if (*d == '\n')
5781 break;
5783 goto fail;
5786 /* Match at the very beginning of the data. */
5787 case begbuf:
5788 DEBUG_PRINT1 ("EXECUTING begbuf.\n");
5789 if (AT_STRINGS_BEG (d))
5790 break;
5791 goto fail;
5794 /* Match at the very end of the data. */
5795 case endbuf:
5796 DEBUG_PRINT1 ("EXECUTING endbuf.\n");
5797 if (AT_STRINGS_END (d))
5798 break;
5799 goto fail;
5802 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
5803 pushes NULL as the value for the string on the stack. Then
5804 `POP_FAILURE_POINT' will keep the current value for the
5805 string, instead of restoring it. To see why, consider
5806 matching `foo\nbar' against `.*\n'. The .* matches the foo;
5807 then the . fails against the \n. But the next thing we want
5808 to do is match the \n against the \n; if we restored the
5809 string value, we would be back at the foo.
5811 Because this is used only in specific cases, we don't need to
5812 check all the things that `on_failure_jump' does, to make
5813 sure the right things get saved on the stack. Hence we don't
5814 share its code. The only reason to push anything on the
5815 stack at all is that otherwise we would have to change
5816 `anychar's code to do something besides goto fail in this
5817 case; that seems worse than this. */
5818 case on_failure_keep_string_jump:
5819 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5820 DEBUG_PRINT3 ("EXECUTING on_failure_keep_string_jump %d (to %p):\n",
5821 mcnt, p + mcnt);
5823 PUSH_FAILURE_POINT (p - 3, NULL);
5824 break;
5826 /* A nasty loop is introduced by the non-greedy *? and +?.
5827 With such loops, the stack only ever contains one failure point
5828 at a time, so that a plain on_failure_jump_loop kind of
5829 cycle detection cannot work. Worse yet, such a detection
5830 can not only fail to detect a cycle, but it can also wrongly
5831 detect a cycle (between different instantiations of the same
5832 loop).
5833 So the method used for those nasty loops is a little different:
5834 We use a special cycle-detection-stack-frame which is pushed
5835 when the on_failure_jump_nastyloop failure-point is *popped*.
5836 This special frame thus marks the beginning of one iteration
5837 through the loop and we can hence easily check right here
5838 whether something matched between the beginning and the end of
5839 the loop. */
5840 case on_failure_jump_nastyloop:
5841 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5842 DEBUG_PRINT3 ("EXECUTING on_failure_jump_nastyloop %d (to %p):\n",
5843 mcnt, p + mcnt);
5845 assert ((re_opcode_t)p[-4] == no_op);
5847 int cycle = 0;
5848 CHECK_INFINITE_LOOP (p - 4, d);
5849 if (!cycle)
5850 /* If there's a cycle, just continue without pushing
5851 this failure point. The failure point is the "try again"
5852 option, which shouldn't be tried.
5853 We want (x?)*?y\1z to match both xxyz and xxyxz. */
5854 PUSH_FAILURE_POINT (p - 3, d);
5856 break;
5858 /* Simple loop detecting on_failure_jump: just check on the
5859 failure stack if the same spot was already hit earlier. */
5860 case on_failure_jump_loop:
5861 on_failure:
5862 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5863 DEBUG_PRINT3 ("EXECUTING on_failure_jump_loop %d (to %p):\n",
5864 mcnt, p + mcnt);
5866 int cycle = 0;
5867 CHECK_INFINITE_LOOP (p - 3, d);
5868 if (cycle)
5869 /* If there's a cycle, get out of the loop, as if the matching
5870 had failed. We used to just `goto fail' here, but that was
5871 aborting the search a bit too early: we want to keep the
5872 empty-loop-match and keep matching after the loop.
5873 We want (x?)*y\1z to match both xxyz and xxyxz. */
5874 p += mcnt;
5875 else
5876 PUSH_FAILURE_POINT (p - 3, d);
5878 break;
5881 /* Uses of on_failure_jump:
5883 Each alternative starts with an on_failure_jump that points
5884 to the beginning of the next alternative. Each alternative
5885 except the last ends with a jump that in effect jumps past
5886 the rest of the alternatives. (They really jump to the
5887 ending jump of the following alternative, because tensioning
5888 these jumps is a hassle.)
5890 Repeats start with an on_failure_jump that points past both
5891 the repetition text and either the following jump or
5892 pop_failure_jump back to this on_failure_jump. */
5893 case on_failure_jump:
5894 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5895 DEBUG_PRINT3 ("EXECUTING on_failure_jump %d (to %p):\n",
5896 mcnt, p + mcnt);
5898 PUSH_FAILURE_POINT (p -3, d);
5899 break;
5901 /* This operation is used for greedy *.
5902 Compare the beginning of the repeat with what in the
5903 pattern follows its end. If we can establish that there
5904 is nothing that they would both match, i.e., that we
5905 would have to backtrack because of (as in, e.g., `a*a')
5906 then we can use a non-backtracking loop based on
5907 on_failure_keep_string_jump instead of on_failure_jump. */
5908 case on_failure_jump_smart:
5909 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5910 DEBUG_PRINT3 ("EXECUTING on_failure_jump_smart %d (to %p).\n",
5911 mcnt, p + mcnt);
5913 re_char *p1 = p; /* Next operation. */
5914 /* Here, we discard `const', making re_match non-reentrant. */
5915 unsigned char *p2 = (unsigned char*) p + mcnt; /* Jump dest. */
5916 unsigned char *p3 = (unsigned char*) p - 3; /* opcode location. */
5918 p -= 3; /* Reset so that we will re-execute the
5919 instruction once it's been changed. */
5921 EXTRACT_NUMBER (mcnt, p2 - 2);
5923 /* Ensure this is a indeed the trivial kind of loop
5924 we are expecting. */
5925 assert (skip_one_char (p1) == p2 - 3);
5926 assert ((re_opcode_t) p2[-3] == jump && p2 + mcnt == p);
5927 DEBUG_STATEMENT (debug += 2);
5928 if (mutually_exclusive_p (bufp, p1, p2))
5930 /* Use a fast `on_failure_keep_string_jump' loop. */
5931 DEBUG_PRINT1 (" smart exclusive => fast loop.\n");
5932 *p3 = (unsigned char) on_failure_keep_string_jump;
5933 STORE_NUMBER (p2 - 2, mcnt + 3);
5935 else
5937 /* Default to a safe `on_failure_jump' loop. */
5938 DEBUG_PRINT1 (" smart default => slow loop.\n");
5939 *p3 = (unsigned char) on_failure_jump;
5941 DEBUG_STATEMENT (debug -= 2);
5943 break;
5945 /* Unconditionally jump (without popping any failure points). */
5946 case jump:
5947 unconditional_jump:
5948 IMMEDIATE_QUIT_CHECK;
5949 EXTRACT_NUMBER_AND_INCR (mcnt, p); /* Get the amount to jump. */
5950 DEBUG_PRINT2 ("EXECUTING jump %d ", mcnt);
5951 p += mcnt; /* Do the jump. */
5952 DEBUG_PRINT2 ("(to %p).\n", p);
5953 break;
5956 /* Have to succeed matching what follows at least n times.
5957 After that, handle like `on_failure_jump'. */
5958 case succeed_n:
5959 /* Signedness doesn't matter since we only compare MCNT to 0. */
5960 EXTRACT_NUMBER (mcnt, p + 2);
5961 DEBUG_PRINT2 ("EXECUTING succeed_n %d.\n", mcnt);
5963 /* Originally, mcnt is how many times we HAVE to succeed. */
5964 if (mcnt != 0)
5966 /* Here, we discard `const', making re_match non-reentrant. */
5967 unsigned char *p2 = (unsigned char*) p + 2; /* counter loc. */
5968 mcnt--;
5969 p += 4;
5970 PUSH_NUMBER (p2, mcnt);
5972 else
5973 /* The two bytes encoding mcnt == 0 are two no_op opcodes. */
5974 goto on_failure;
5975 break;
5977 case jump_n:
5978 /* Signedness doesn't matter since we only compare MCNT to 0. */
5979 EXTRACT_NUMBER (mcnt, p + 2);
5980 DEBUG_PRINT2 ("EXECUTING jump_n %d.\n", mcnt);
5982 /* Originally, this is how many times we CAN jump. */
5983 if (mcnt != 0)
5985 /* Here, we discard `const', making re_match non-reentrant. */
5986 unsigned char *p2 = (unsigned char*) p + 2; /* counter loc. */
5987 mcnt--;
5988 PUSH_NUMBER (p2, mcnt);
5989 goto unconditional_jump;
5991 /* If don't have to jump any more, skip over the rest of command. */
5992 else
5993 p += 4;
5994 break;
5996 case set_number_at:
5998 unsigned char *p2; /* Location of the counter. */
5999 DEBUG_PRINT1 ("EXECUTING set_number_at.\n");
6001 EXTRACT_NUMBER_AND_INCR (mcnt, p);
6002 /* Here, we discard `const', making re_match non-reentrant. */
6003 p2 = (unsigned char*) p + mcnt;
6004 /* Signedness doesn't matter since we only copy MCNT's bits . */
6005 EXTRACT_NUMBER_AND_INCR (mcnt, p);
6006 DEBUG_PRINT3 (" Setting %p to %d.\n", p2, mcnt);
6007 PUSH_NUMBER (p2, mcnt);
6008 break;
6011 case wordbound:
6012 case notwordbound:
6013 not = (re_opcode_t) *(p - 1) == notwordbound;
6014 DEBUG_PRINT2 ("EXECUTING %swordbound.\n", not?"not":"");
6016 /* We SUCCEED (or FAIL) in one of the following cases: */
6018 /* Case 1: D is at the beginning or the end of string. */
6019 if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
6020 not = !not;
6021 else
6023 /* C1 is the character before D, S1 is the syntax of C1, C2
6024 is the character at D, and S2 is the syntax of C2. */
6025 re_wchar_t c1, c2;
6026 int s1, s2;
6027 int dummy;
6028 #ifdef emacs
6029 int offset = PTR_TO_OFFSET (d - 1);
6030 int charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
6031 UPDATE_SYNTAX_TABLE (charpos);
6032 #endif
6033 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
6034 s1 = SYNTAX (c1);
6035 #ifdef emacs
6036 UPDATE_SYNTAX_TABLE_FORWARD (charpos + 1);
6037 #endif
6038 PREFETCH_NOLIMIT ();
6039 GET_CHAR_AFTER (c2, d, dummy);
6040 s2 = SYNTAX (c2);
6042 if (/* Case 2: Only one of S1 and S2 is Sword. */
6043 ((s1 == Sword) != (s2 == Sword))
6044 /* Case 3: Both of S1 and S2 are Sword, and macro
6045 WORD_BOUNDARY_P (C1, C2) returns nonzero. */
6046 || ((s1 == Sword) && WORD_BOUNDARY_P (c1, c2)))
6047 not = !not;
6049 if (not)
6050 break;
6051 else
6052 goto fail;
6054 case wordbeg:
6055 DEBUG_PRINT1 ("EXECUTING wordbeg.\n");
6057 /* We FAIL in one of the following cases: */
6059 /* Case 1: D is at the end of string. */
6060 if (AT_STRINGS_END (d))
6061 goto fail;
6062 else
6064 /* C1 is the character before D, S1 is the syntax of C1, C2
6065 is the character at D, and S2 is the syntax of C2. */
6066 re_wchar_t c1, c2;
6067 int s1, s2;
6068 int dummy;
6069 #ifdef emacs
6070 int offset = PTR_TO_OFFSET (d);
6071 int charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
6072 UPDATE_SYNTAX_TABLE (charpos);
6073 #endif
6074 PREFETCH ();
6075 GET_CHAR_AFTER (c2, d, dummy);
6076 s2 = SYNTAX (c2);
6078 /* Case 2: S2 is not Sword. */
6079 if (s2 != Sword)
6080 goto fail;
6082 /* Case 3: D is not at the beginning of string ... */
6083 if (!AT_STRINGS_BEG (d))
6085 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
6086 #ifdef emacs
6087 UPDATE_SYNTAX_TABLE_BACKWARD (charpos - 1);
6088 #endif
6089 s1 = SYNTAX (c1);
6091 /* ... and S1 is Sword, and WORD_BOUNDARY_P (C1, C2)
6092 returns 0. */
6093 if ((s1 == Sword) && !WORD_BOUNDARY_P (c1, c2))
6094 goto fail;
6097 break;
6099 case wordend:
6100 DEBUG_PRINT1 ("EXECUTING wordend.\n");
6102 /* We FAIL in one of the following cases: */
6104 /* Case 1: D is at the beginning of string. */
6105 if (AT_STRINGS_BEG (d))
6106 goto fail;
6107 else
6109 /* C1 is the character before D, S1 is the syntax of C1, C2
6110 is the character at D, and S2 is the syntax of C2. */
6111 re_wchar_t c1, c2;
6112 int s1, s2;
6113 int dummy;
6114 #ifdef emacs
6115 int offset = PTR_TO_OFFSET (d) - 1;
6116 int charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
6117 UPDATE_SYNTAX_TABLE (charpos);
6118 #endif
6119 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
6120 s1 = SYNTAX (c1);
6122 /* Case 2: S1 is not Sword. */
6123 if (s1 != Sword)
6124 goto fail;
6126 /* Case 3: D is not at the end of string ... */
6127 if (!AT_STRINGS_END (d))
6129 PREFETCH_NOLIMIT ();
6130 GET_CHAR_AFTER (c2, d, dummy);
6131 #ifdef emacs
6132 UPDATE_SYNTAX_TABLE_FORWARD (charpos);
6133 #endif
6134 s2 = SYNTAX (c2);
6136 /* ... and S2 is Sword, and WORD_BOUNDARY_P (C1, C2)
6137 returns 0. */
6138 if ((s2 == Sword) && !WORD_BOUNDARY_P (c1, c2))
6139 goto fail;
6142 break;
6144 case symbeg:
6145 DEBUG_PRINT1 ("EXECUTING symbeg.\n");
6147 /* We FAIL in one of the following cases: */
6149 /* Case 1: D is at the end of string. */
6150 if (AT_STRINGS_END (d))
6151 goto fail;
6152 else
6154 /* C1 is the character before D, S1 is the syntax of C1, C2
6155 is the character at D, and S2 is the syntax of C2. */
6156 re_wchar_t c1, c2;
6157 int s1, s2;
6158 #ifdef emacs
6159 int offset = PTR_TO_OFFSET (d);
6160 int charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
6161 UPDATE_SYNTAX_TABLE (charpos);
6162 #endif
6163 PREFETCH ();
6164 c2 = RE_STRING_CHAR (d, target_multibyte);
6165 s2 = SYNTAX (c2);
6167 /* Case 2: S2 is neither Sword nor Ssymbol. */
6168 if (s2 != Sword && s2 != Ssymbol)
6169 goto fail;
6171 /* Case 3: D is not at the beginning of string ... */
6172 if (!AT_STRINGS_BEG (d))
6174 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
6175 #ifdef emacs
6176 UPDATE_SYNTAX_TABLE_BACKWARD (charpos - 1);
6177 #endif
6178 s1 = SYNTAX (c1);
6180 /* ... and S1 is Sword or Ssymbol. */
6181 if (s1 == Sword || s1 == Ssymbol)
6182 goto fail;
6185 break;
6187 case symend:
6188 DEBUG_PRINT1 ("EXECUTING symend.\n");
6190 /* We FAIL in one of the following cases: */
6192 /* Case 1: D is at the beginning of string. */
6193 if (AT_STRINGS_BEG (d))
6194 goto fail;
6195 else
6197 /* C1 is the character before D, S1 is the syntax of C1, C2
6198 is the character at D, and S2 is the syntax of C2. */
6199 re_wchar_t c1, c2;
6200 int s1, s2;
6201 #ifdef emacs
6202 int offset = PTR_TO_OFFSET (d) - 1;
6203 int charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
6204 UPDATE_SYNTAX_TABLE (charpos);
6205 #endif
6206 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
6207 s1 = SYNTAX (c1);
6209 /* Case 2: S1 is neither Ssymbol nor Sword. */
6210 if (s1 != Sword && s1 != Ssymbol)
6211 goto fail;
6213 /* Case 3: D is not at the end of string ... */
6214 if (!AT_STRINGS_END (d))
6216 PREFETCH_NOLIMIT ();
6217 c2 = RE_STRING_CHAR (d, target_multibyte);
6218 #ifdef emacs
6219 UPDATE_SYNTAX_TABLE_FORWARD (charpos + 1);
6220 #endif
6221 s2 = SYNTAX (c2);
6223 /* ... and S2 is Sword or Ssymbol. */
6224 if (s2 == Sword || s2 == Ssymbol)
6225 goto fail;
6228 break;
6230 case syntaxspec:
6231 case notsyntaxspec:
6232 not = (re_opcode_t) *(p - 1) == notsyntaxspec;
6233 mcnt = *p++;
6234 DEBUG_PRINT3 ("EXECUTING %ssyntaxspec %d.\n", not?"not":"", mcnt);
6235 PREFETCH ();
6236 #ifdef emacs
6238 int offset = PTR_TO_OFFSET (d);
6239 int pos1 = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
6240 UPDATE_SYNTAX_TABLE (pos1);
6242 #endif
6244 int len;
6245 re_wchar_t c;
6247 GET_CHAR_AFTER (c, d, len);
6248 if ((SYNTAX (c) != (enum syntaxcode) mcnt) ^ not)
6249 goto fail;
6250 d += len;
6252 break;
6254 #ifdef emacs
6255 case before_dot:
6256 DEBUG_PRINT1 ("EXECUTING before_dot.\n");
6257 if (PTR_BYTE_POS (d) >= PT_BYTE)
6258 goto fail;
6259 break;
6261 case at_dot:
6262 DEBUG_PRINT1 ("EXECUTING at_dot.\n");
6263 if (PTR_BYTE_POS (d) != PT_BYTE)
6264 goto fail;
6265 break;
6267 case after_dot:
6268 DEBUG_PRINT1 ("EXECUTING after_dot.\n");
6269 if (PTR_BYTE_POS (d) <= PT_BYTE)
6270 goto fail;
6271 break;
6273 case categoryspec:
6274 case notcategoryspec:
6275 not = (re_opcode_t) *(p - 1) == notcategoryspec;
6276 mcnt = *p++;
6277 DEBUG_PRINT3 ("EXECUTING %scategoryspec %d.\n", not?"not":"", mcnt);
6278 PREFETCH ();
6280 int len;
6281 re_wchar_t c;
6283 GET_CHAR_AFTER (c, d, len);
6284 if ((!CHAR_HAS_CATEGORY (c, mcnt)) ^ not)
6285 goto fail;
6286 d += len;
6288 break;
6290 #endif /* emacs */
6292 default:
6293 abort ();
6295 continue; /* Successfully executed one pattern command; keep going. */
6298 /* We goto here if a matching operation fails. */
6299 fail:
6300 IMMEDIATE_QUIT_CHECK;
6301 if (!FAIL_STACK_EMPTY ())
6303 re_char *str, *pat;
6304 /* A restart point is known. Restore to that state. */
6305 DEBUG_PRINT1 ("\nFAIL:\n");
6306 POP_FAILURE_POINT (str, pat);
6307 switch (SWITCH_ENUM_CAST ((re_opcode_t) *pat++))
6309 case on_failure_keep_string_jump:
6310 assert (str == NULL);
6311 goto continue_failure_jump;
6313 case on_failure_jump_nastyloop:
6314 assert ((re_opcode_t)pat[-2] == no_op);
6315 PUSH_FAILURE_POINT (pat - 2, str);
6316 /* Fallthrough */
6318 case on_failure_jump_loop:
6319 case on_failure_jump:
6320 case succeed_n:
6321 d = str;
6322 continue_failure_jump:
6323 EXTRACT_NUMBER_AND_INCR (mcnt, pat);
6324 p = pat + mcnt;
6325 break;
6327 case no_op:
6328 /* A special frame used for nastyloops. */
6329 goto fail;
6331 default:
6332 abort();
6335 assert (p >= bufp->buffer && p <= pend);
6337 if (d >= string1 && d <= end1)
6338 dend = end_match_1;
6340 else
6341 break; /* Matching at this starting point really fails. */
6342 } /* for (;;) */
6344 if (best_regs_set)
6345 goto restore_best_regs;
6347 FREE_VARIABLES ();
6349 return -1; /* Failure to match. */
6350 } /* re_match_2 */
6352 /* Subroutine definitions for re_match_2. */
6354 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
6355 bytes; nonzero otherwise. */
6357 static int
6358 bcmp_translate (const re_char *s1, const re_char *s2, register int len,
6359 RE_TRANSLATE_TYPE translate, const int target_multibyte)
6361 register re_char *p1 = s1, *p2 = s2;
6362 re_char *p1_end = s1 + len;
6363 re_char *p2_end = s2 + len;
6365 /* FIXME: Checking both p1 and p2 presumes that the two strings might have
6366 different lengths, but relying on a single `len' would break this. -sm */
6367 while (p1 < p1_end && p2 < p2_end)
6369 int p1_charlen, p2_charlen;
6370 re_wchar_t p1_ch, p2_ch;
6372 GET_CHAR_AFTER (p1_ch, p1, p1_charlen);
6373 GET_CHAR_AFTER (p2_ch, p2, p2_charlen);
6375 if (RE_TRANSLATE (translate, p1_ch)
6376 != RE_TRANSLATE (translate, p2_ch))
6377 return 1;
6379 p1 += p1_charlen, p2 += p2_charlen;
6382 if (p1 != p1_end || p2 != p2_end)
6383 return 1;
6385 return 0;
6388 /* Entry points for GNU code. */
6390 /* re_compile_pattern is the GNU regular expression compiler: it
6391 compiles PATTERN (of length SIZE) and puts the result in BUFP.
6392 Returns 0 if the pattern was valid, otherwise an error string.
6394 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
6395 are set in BUFP on entry.
6397 We call regex_compile to do the actual compilation. */
6399 const char *
6400 re_compile_pattern (const char *pattern, size_t length, struct re_pattern_buffer *bufp)
6402 reg_errcode_t ret;
6404 /* GNU code is written to assume at least RE_NREGS registers will be set
6405 (and at least one extra will be -1). */
6406 bufp->regs_allocated = REGS_UNALLOCATED;
6408 /* And GNU code determines whether or not to get register information
6409 by passing null for the REGS argument to re_match, etc., not by
6410 setting no_sub. */
6411 bufp->no_sub = 0;
6413 ret = regex_compile ((re_char*) pattern, length, re_syntax_options, bufp);
6415 if (!ret)
6416 return NULL;
6417 return gettext (re_error_msgid[(int) ret]);
6419 WEAK_ALIAS (__re_compile_pattern, re_compile_pattern)
6421 /* Entry points compatible with 4.2 BSD regex library. We don't define
6422 them unless specifically requested. */
6424 #if defined _REGEX_RE_COMP || defined _LIBC
6426 /* BSD has one and only one pattern buffer. */
6427 static struct re_pattern_buffer re_comp_buf;
6429 char *
6430 # ifdef _LIBC
6431 /* Make these definitions weak in libc, so POSIX programs can redefine
6432 these names if they don't use our functions, and still use
6433 regcomp/regexec below without link errors. */
6434 weak_function
6435 # endif
6436 re_comp (s)
6437 const char *s;
6439 reg_errcode_t ret;
6441 if (!s)
6443 if (!re_comp_buf.buffer)
6444 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6445 return (char *) gettext ("No previous regular expression");
6446 return 0;
6449 if (!re_comp_buf.buffer)
6451 re_comp_buf.buffer = (unsigned char *) malloc (200);
6452 if (re_comp_buf.buffer == NULL)
6453 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6454 return (char *) gettext (re_error_msgid[(int) REG_ESPACE]);
6455 re_comp_buf.allocated = 200;
6457 re_comp_buf.fastmap = (char *) malloc (1 << BYTEWIDTH);
6458 if (re_comp_buf.fastmap == NULL)
6459 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6460 return (char *) gettext (re_error_msgid[(int) REG_ESPACE]);
6463 /* Since `re_exec' always passes NULL for the `regs' argument, we
6464 don't need to initialize the pattern buffer fields which affect it. */
6466 ret = regex_compile (s, strlen (s), re_syntax_options, &re_comp_buf);
6468 if (!ret)
6469 return NULL;
6471 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
6472 return (char *) gettext (re_error_msgid[(int) ret]);
6477 # ifdef _LIBC
6478 weak_function
6479 # endif
6480 re_exec (s)
6481 const char *s;
6483 const int len = strlen (s);
6484 return
6485 0 <= re_search (&re_comp_buf, s, len, 0, len, (struct re_registers *) 0);
6487 #endif /* _REGEX_RE_COMP */
6489 /* POSIX.2 functions. Don't define these for Emacs. */
6491 #ifndef emacs
6493 /* regcomp takes a regular expression as a string and compiles it.
6495 PREG is a regex_t *. We do not expect any fields to be initialized,
6496 since POSIX says we shouldn't. Thus, we set
6498 `buffer' to the compiled pattern;
6499 `used' to the length of the compiled pattern;
6500 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
6501 REG_EXTENDED bit in CFLAGS is set; otherwise, to
6502 RE_SYNTAX_POSIX_BASIC;
6503 `fastmap' to an allocated space for the fastmap;
6504 `fastmap_accurate' to zero;
6505 `re_nsub' to the number of subexpressions in PATTERN.
6507 PATTERN is the address of the pattern string.
6509 CFLAGS is a series of bits which affect compilation.
6511 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
6512 use POSIX basic syntax.
6514 If REG_NEWLINE is set, then . and [^...] don't match newline.
6515 Also, regexec will try a match beginning after every newline.
6517 If REG_ICASE is set, then we considers upper- and lowercase
6518 versions of letters to be equivalent when matching.
6520 If REG_NOSUB is set, then when PREG is passed to regexec, that
6521 routine will report only success or failure, and nothing about the
6522 registers.
6524 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
6525 the return codes and their meanings.) */
6528 regcomp (regex_t *__restrict preg, const char *__restrict pattern,
6529 int cflags)
6531 reg_errcode_t ret;
6532 reg_syntax_t syntax
6533 = (cflags & REG_EXTENDED) ?
6534 RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC;
6536 /* regex_compile will allocate the space for the compiled pattern. */
6537 preg->buffer = 0;
6538 preg->allocated = 0;
6539 preg->used = 0;
6541 /* Try to allocate space for the fastmap. */
6542 preg->fastmap = (char *) malloc (1 << BYTEWIDTH);
6544 if (cflags & REG_ICASE)
6546 unsigned i;
6548 preg->translate
6549 = (RE_TRANSLATE_TYPE) malloc (CHAR_SET_SIZE
6550 * sizeof (*(RE_TRANSLATE_TYPE)0));
6551 if (preg->translate == NULL)
6552 return (int) REG_ESPACE;
6554 /* Map uppercase characters to corresponding lowercase ones. */
6555 for (i = 0; i < CHAR_SET_SIZE; i++)
6556 preg->translate[i] = ISUPPER (i) ? TOLOWER (i) : i;
6558 else
6559 preg->translate = NULL;
6561 /* If REG_NEWLINE is set, newlines are treated differently. */
6562 if (cflags & REG_NEWLINE)
6563 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
6564 syntax &= ~RE_DOT_NEWLINE;
6565 syntax |= RE_HAT_LISTS_NOT_NEWLINE;
6567 else
6568 syntax |= RE_NO_NEWLINE_ANCHOR;
6570 preg->no_sub = !!(cflags & REG_NOSUB);
6572 /* POSIX says a null character in the pattern terminates it, so we
6573 can use strlen here in compiling the pattern. */
6574 ret = regex_compile ((re_char*) pattern, strlen (pattern), syntax, preg);
6576 /* POSIX doesn't distinguish between an unmatched open-group and an
6577 unmatched close-group: both are REG_EPAREN. */
6578 if (ret == REG_ERPAREN)
6579 ret = REG_EPAREN;
6581 if (ret == REG_NOERROR && preg->fastmap)
6582 { /* Compute the fastmap now, since regexec cannot modify the pattern
6583 buffer. */
6584 re_compile_fastmap (preg);
6585 if (preg->can_be_null)
6586 { /* The fastmap can't be used anyway. */
6587 free (preg->fastmap);
6588 preg->fastmap = NULL;
6591 return (int) ret;
6593 WEAK_ALIAS (__regcomp, regcomp)
6596 /* regexec searches for a given pattern, specified by PREG, in the
6597 string STRING.
6599 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
6600 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
6601 least NMATCH elements, and we set them to the offsets of the
6602 corresponding matched substrings.
6604 EFLAGS specifies `execution flags' which affect matching: if
6605 REG_NOTBOL is set, then ^ does not match at the beginning of the
6606 string; if REG_NOTEOL is set, then $ does not match at the end.
6608 We return 0 if we find a match and REG_NOMATCH if not. */
6611 regexec (const regex_t *__restrict preg, const char *__restrict string,
6612 size_t nmatch, regmatch_t pmatch[__restrict_arr], int eflags)
6614 int ret;
6615 struct re_registers regs;
6616 regex_t private_preg;
6617 int len = strlen (string);
6618 boolean want_reg_info = !preg->no_sub && nmatch > 0 && pmatch;
6620 private_preg = *preg;
6622 private_preg.not_bol = !!(eflags & REG_NOTBOL);
6623 private_preg.not_eol = !!(eflags & REG_NOTEOL);
6625 /* The user has told us exactly how many registers to return
6626 information about, via `nmatch'. We have to pass that on to the
6627 matching routines. */
6628 private_preg.regs_allocated = REGS_FIXED;
6630 if (want_reg_info)
6632 regs.num_regs = nmatch;
6633 regs.start = TALLOC (nmatch * 2, regoff_t);
6634 if (regs.start == NULL)
6635 return (int) REG_NOMATCH;
6636 regs.end = regs.start + nmatch;
6639 /* Instead of using not_eol to implement REG_NOTEOL, we could simply
6640 pass (&private_preg, string, len + 1, 0, len, ...) pretending the string
6641 was a little bit longer but still only matching the real part.
6642 This works because the `endline' will check for a '\n' and will find a
6643 '\0', correctly deciding that this is not the end of a line.
6644 But it doesn't work out so nicely for REG_NOTBOL, since we don't have
6645 a convenient '\0' there. For all we know, the string could be preceded
6646 by '\n' which would throw things off. */
6648 /* Perform the searching operation. */
6649 ret = re_search (&private_preg, string, len,
6650 /* start: */ 0, /* range: */ len,
6651 want_reg_info ? &regs : (struct re_registers *) 0);
6653 /* Copy the register information to the POSIX structure. */
6654 if (want_reg_info)
6656 if (ret >= 0)
6658 unsigned r;
6660 for (r = 0; r < nmatch; r++)
6662 pmatch[r].rm_so = regs.start[r];
6663 pmatch[r].rm_eo = regs.end[r];
6667 /* If we needed the temporary register info, free the space now. */
6668 free (regs.start);
6671 /* We want zero return to mean success, unlike `re_search'. */
6672 return ret >= 0 ? (int) REG_NOERROR : (int) REG_NOMATCH;
6674 WEAK_ALIAS (__regexec, regexec)
6677 /* Returns a message corresponding to an error code, ERR_CODE, returned
6678 from either regcomp or regexec. We don't use PREG here.
6680 ERR_CODE was previously called ERRCODE, but that name causes an
6681 error with msvc8 compiler. */
6683 size_t
6684 regerror (int err_code, const regex_t *preg, char *errbuf, size_t errbuf_size)
6686 const char *msg;
6687 size_t msg_size;
6689 if (err_code < 0
6690 || err_code >= (sizeof (re_error_msgid) / sizeof (re_error_msgid[0])))
6691 /* Only error codes returned by the rest of the code should be passed
6692 to this routine. If we are given anything else, or if other regex
6693 code generates an invalid error code, then the program has a bug.
6694 Dump core so we can fix it. */
6695 abort ();
6697 msg = gettext (re_error_msgid[err_code]);
6699 msg_size = strlen (msg) + 1; /* Includes the null. */
6701 if (errbuf_size != 0)
6703 if (msg_size > errbuf_size)
6705 strncpy (errbuf, msg, errbuf_size - 1);
6706 errbuf[errbuf_size - 1] = 0;
6708 else
6709 strcpy (errbuf, msg);
6712 return msg_size;
6714 WEAK_ALIAS (__regerror, regerror)
6717 /* Free dynamically allocated space used by PREG. */
6719 void
6720 regfree (regex_t *preg)
6722 free (preg->buffer);
6723 preg->buffer = NULL;
6725 preg->allocated = 0;
6726 preg->used = 0;
6728 free (preg->fastmap);
6729 preg->fastmap = NULL;
6730 preg->fastmap_accurate = 0;
6732 free (preg->translate);
6733 preg->translate = NULL;
6735 WEAK_ALIAS (__regfree, regfree)
6737 #endif /* not emacs */