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,94,95,96,97,98,99,2000 Free Software Foundation, Inc.
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
23 - structure the opcode space into opcode+flag.
24 - merge with glibc's regex.[ch].
25 - replace succeed_n + jump_n with a combined operation so that the counter
26 can simply be decremented when popping the failure_point without having
27 to stack up failure_count entries.
30 /* AIX requires this to be the first thing in the file. */
31 #if defined _AIX && !defined REGEX_MALLOC
42 #if defined STDC_HEADERS && !defined emacs
45 /* We need this for `regex.h', and perhaps for the Emacs include files. */
46 # include <sys/types.h>
49 /* Whether to use ISO C Amendment 1 wide char functions.
50 Those should not be used for Emacs since it uses its own. */
51 #define WIDE_CHAR_SUPPORT \
52 (HAVE_WCTYPE_H && HAVE_WCHAR_H && HAVE_BTOWC && !emacs)
54 /* For platform which support the ISO C amendement 1 functionality we
55 support user defined character classes. */
56 #if defined _LIBC || WIDE_CHAR_SUPPORT
57 /* Solaris 2.5 has a bug: <wchar.h> must be included before <wctype.h>. */
63 /* We have to keep the namespace clean. */
64 # define regfree(preg) __regfree (preg)
65 # define regexec(pr, st, nm, pm, ef) __regexec (pr, st, nm, pm, ef)
66 # define regcomp(preg, pattern, cflags) __regcomp (preg, pattern, cflags)
67 # define regerror(errcode, preg, errbuf, errbuf_size) \
68 __regerror(errcode, preg, errbuf, errbuf_size)
69 # define re_set_registers(bu, re, nu, st, en) \
70 __re_set_registers (bu, re, nu, st, en)
71 # define re_match_2(bufp, string1, size1, string2, size2, pos, regs, stop) \
72 __re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
73 # define re_match(bufp, string, size, pos, regs) \
74 __re_match (bufp, string, size, pos, regs)
75 # define re_search(bufp, string, size, startpos, range, regs) \
76 __re_search (bufp, string, size, startpos, range, regs)
77 # define re_compile_pattern(pattern, length, bufp) \
78 __re_compile_pattern (pattern, length, bufp)
79 # define re_set_syntax(syntax) __re_set_syntax (syntax)
80 # define re_search_2(bufp, st1, s1, st2, s2, startpos, range, regs, stop) \
81 __re_search_2 (bufp, st1, s1, st2, s2, startpos, range, regs, stop)
82 # define re_compile_fastmap(bufp) __re_compile_fastmap (bufp)
84 /* Make sure we call libc's function even if the user overrides them. */
85 # define btowc __btowc
86 # define iswctype __iswctype
87 # define wctype __wctype
89 # define WEAK_ALIAS(a,b) weak_alias (a, b)
91 /* We are also using some library internals. */
92 # include <locale/localeinfo.h>
93 # include <locale/elem-hash.h>
94 # include <langinfo.h>
96 # define WEAK_ALIAS(a,b)
99 /* This is for other GNU distributions with internationalized messages. */
100 #if HAVE_LIBINTL_H || defined _LIBC
101 # include <libintl.h>
103 # define gettext(msgid) (msgid)
107 /* This define is so xgettext can find the internationalizable
109 # define gettext_noop(String) String
112 /* The `emacs' switch turns on certain matching commands
113 that make sense only in Emacs. */
119 /* Make syntax table lookup grant data in gl_state. */
120 # define SYNTAX_ENTRY_VIA_PROPERTY
123 # include "charset.h"
124 # include "category.h"
126 # define malloc xmalloc
127 # define realloc xrealloc
130 /* Converts the pointer to the char to BEG-based offset from the start. */
131 # define PTR_TO_OFFSET(d) POS_AS_IN_BUFFER (POINTER_TO_OFFSET (d))
132 # define POS_AS_IN_BUFFER(p) ((p) + (NILP (re_match_object) || BUFFERP (re_match_object)))
134 # define RE_MULTIBYTE_P(bufp) ((bufp)->multibyte)
135 # define RE_STRING_CHAR(p, s) \
136 (multibyte ? (STRING_CHAR (p, s)) : (*(p)))
137 # define RE_STRING_CHAR_AND_LENGTH(p, s, len) \
138 (multibyte ? (STRING_CHAR_AND_LENGTH (p, s, len)) : ((len) = 1, *(p)))
140 /* Set C a (possibly multibyte) character before P. P points into a
141 string which is the virtual concatenation of STR1 (which ends at
142 END1) or STR2 (which ends at END2). */
143 # define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
147 re_char *dtemp = (p) == (str2) ? (end1) : (p); \
148 re_char *dlimit = ((p) > (str2) && (p) <= (end2)) ? (str2) : (str1); \
149 while (dtemp-- > dlimit && !CHAR_HEAD_P (*dtemp)); \
150 c = STRING_CHAR (dtemp, (p) - dtemp); \
153 (c = ((p) == (str2) ? (end1) : (p))[-1]); \
157 #else /* not emacs */
159 /* If we are not linking with Emacs proper,
160 we can't use the relocating allocator
161 even if config.h says that we can. */
164 # if defined STDC_HEADERS || defined _LIBC
171 /* When used in Emacs's lib-src, we need to get bzero and bcopy somehow.
172 If nothing else has been done, use the method below. */
173 # ifdef INHIBIT_STRING_HEADER
174 # if !(defined HAVE_BZERO && defined HAVE_BCOPY)
175 # if !defined bzero && !defined bcopy
176 # undef INHIBIT_STRING_HEADER
181 /* This is the normal way of making sure we have memcpy, memcmp and bzero.
182 This is used in most programs--a few other programs avoid this
183 by defining INHIBIT_STRING_HEADER. */
184 # ifndef INHIBIT_STRING_HEADER
185 # if defined HAVE_STRING_H || defined STDC_HEADERS || defined _LIBC
189 # define bzero(s, n) (memset (s, '\0', n), (s))
191 # define bzero(s, n) __bzero (s, n)
195 # include <strings.h>
197 # define memcmp(s1, s2, n) bcmp (s1, s2, n)
200 # define memcpy(d, s, n) (bcopy (s, d, n), (d))
205 /* Define the syntax stuff for \<, \>, etc. */
207 /* Sword must be nonzero for the wordchar pattern commands in re_match_2. */
208 enum syntaxcode { Swhitespace = 0, Sword = 1 };
210 # ifdef SWITCH_ENUM_BUG
211 # define SWITCH_ENUM_CAST(x) ((int)(x))
213 # define SWITCH_ENUM_CAST(x) (x)
216 /* Dummy macros for non-Emacs environments. */
217 # define BASE_LEADING_CODE_P(c) (0)
218 # define CHAR_CHARSET(c) 0
219 # define CHARSET_LEADING_CODE_BASE(c) 0
220 # define MAX_MULTIBYTE_LENGTH 1
221 # define RE_MULTIBYTE_P(x) 0
222 # define WORD_BOUNDARY_P(c1, c2) (0)
223 # define CHAR_HEAD_P(p) (1)
224 # define SINGLE_BYTE_CHAR_P(c) (1)
225 # define SAME_CHARSET_P(c1, c2) (1)
226 # define MULTIBYTE_FORM_LENGTH(p, s) (1)
227 # define STRING_CHAR(p, s) (*(p))
228 # define RE_STRING_CHAR STRING_CHAR
229 # define CHAR_STRING(c, s) (*(s) = (c), 1)
230 # define STRING_CHAR_AND_LENGTH(p, s, actual_len) ((actual_len) = 1, *(p))
231 # define RE_STRING_CHAR_AND_LENGTH STRING_CHAR_AND_LENGTH
232 # define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
233 (c = ((p) == (str2) ? *((end1) - 1) : *((p) - 1)))
234 # define MAKE_CHAR(charset, c1, c2) (c1)
235 #endif /* not emacs */
238 # define RE_TRANSLATE(TBL, C) ((unsigned char)(TBL)[C])
239 # define RE_TRANSLATE_P(TBL) (TBL)
242 /* Get the interface, including the syntax bits. */
245 /* isalpha etc. are used for the character classes. */
250 /* 1 if C is an ASCII character. */
251 # define IS_REAL_ASCII(c) ((c) < 0200)
253 /* 1 if C is a unibyte character. */
254 # define ISUNIBYTE(c) (SINGLE_BYTE_CHAR_P ((c)))
256 /* The Emacs definitions should not be directly affected by locales. */
258 /* In Emacs, these are only used for single-byte characters. */
259 # define ISDIGIT(c) ((c) >= '0' && (c) <= '9')
260 # define ISCNTRL(c) ((c) < ' ')
261 # define ISXDIGIT(c) (((c) >= '0' && (c) <= '9') \
262 || ((c) >= 'a' && (c) <= 'f') \
263 || ((c) >= 'A' && (c) <= 'F'))
265 /* This is only used for single-byte characters. */
266 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
268 /* The rest must handle multibyte characters. */
270 # define ISGRAPH(c) (SINGLE_BYTE_CHAR_P (c) \
271 ? (c) > ' ' && !((c) >= 0177 && (c) <= 0237) \
274 # define ISPRINT(c) (SINGLE_BYTE_CHAR_P (c) \
275 ? (c) >= ' ' && !((c) >= 0177 && (c) <= 0237) \
278 # define ISALNUM(c) (IS_REAL_ASCII (c) \
279 ? (((c) >= 'a' && (c) <= 'z') \
280 || ((c) >= 'A' && (c) <= 'Z') \
281 || ((c) >= '0' && (c) <= '9')) \
282 : SYNTAX (c) == Sword)
284 # define ISALPHA(c) (IS_REAL_ASCII (c) \
285 ? (((c) >= 'a' && (c) <= 'z') \
286 || ((c) >= 'A' && (c) <= 'Z')) \
287 : SYNTAX (c) == Sword)
289 # define ISLOWER(c) (LOWERCASEP (c))
291 # define ISPUNCT(c) (IS_REAL_ASCII (c) \
292 ? ((c) > ' ' && (c) < 0177 \
293 && !(((c) >= 'a' && (c) <= 'z') \
294 || ((c) >= 'A' && (c) <= 'Z') \
295 || ((c) >= '0' && (c) <= '9'))) \
296 : SYNTAX (c) != Sword)
298 # define ISSPACE(c) (SYNTAX (c) == Swhitespace)
300 # define ISUPPER(c) (UPPERCASEP (c))
302 # define ISWORD(c) (SYNTAX (c) == Sword)
304 #else /* not emacs */
306 /* Jim Meyering writes:
308 "... Some ctype macros are valid only for character codes that
309 isascii says are ASCII (SGI's IRIX-4.0.5 is one such system --when
310 using /bin/cc or gcc but without giving an ansi option). So, all
311 ctype uses should be through macros like ISPRINT... If
312 STDC_HEADERS is defined, then autoconf has verified that the ctype
313 macros don't need to be guarded with references to isascii. ...
314 Defining isascii to 1 should let any compiler worth its salt
315 eliminate the && through constant folding."
316 Solaris defines some of these symbols so we must undefine them first. */
319 # if defined STDC_HEADERS || (!defined isascii && !defined HAVE_ISASCII)
320 # define ISASCII(c) 1
322 # define ISASCII(c) isascii(c)
325 /* 1 if C is an ASCII character. */
326 # define IS_REAL_ASCII(c) ((c) < 0200)
328 /* This distinction is not meaningful, except in Emacs. */
329 # define ISUNIBYTE(c) 1
332 # define ISBLANK(c) (ISASCII (c) && isblank (c))
334 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
337 # define ISGRAPH(c) (ISASCII (c) && isgraph (c))
339 # define ISGRAPH(c) (ISASCII (c) && isprint (c) && !isspace (c))
343 # define ISPRINT(c) (ISASCII (c) && isprint (c))
344 # define ISDIGIT(c) (ISASCII (c) && isdigit (c))
345 # define ISALNUM(c) (ISASCII (c) && isalnum (c))
346 # define ISALPHA(c) (ISASCII (c) && isalpha (c))
347 # define ISCNTRL(c) (ISASCII (c) && iscntrl (c))
348 # define ISLOWER(c) (ISASCII (c) && islower (c))
349 # define ISPUNCT(c) (ISASCII (c) && ispunct (c))
350 # define ISSPACE(c) (ISASCII (c) && isspace (c))
351 # define ISUPPER(c) (ISASCII (c) && isupper (c))
352 # define ISXDIGIT(c) (ISASCII (c) && isxdigit (c))
354 # define ISWORD(c) ISALPHA(c)
357 # define TOLOWER(c) _tolower(c)
359 # define TOLOWER(c) tolower(c)
362 /* How many characters in the character set. */
363 # define CHAR_SET_SIZE 256
367 extern char *re_syntax_table;
369 # else /* not SYNTAX_TABLE */
371 static char re_syntax_table[CHAR_SET_SIZE];
382 bzero (re_syntax_table, sizeof re_syntax_table);
384 for (c = 0; c < CHAR_SET_SIZE; ++c)
386 re_syntax_table[c] = Sword;
388 re_syntax_table['_'] = Sword;
393 # endif /* not SYNTAX_TABLE */
395 # define SYNTAX(c) re_syntax_table[(c)]
397 #endif /* not emacs */
400 # define NULL (void *)0
403 /* We remove any previous definition of `SIGN_EXTEND_CHAR',
404 since ours (we hope) works properly with all combinations of
405 machines, compilers, `char' and `unsigned char' argument types.
406 (Per Bothner suggested the basic approach.) */
407 #undef SIGN_EXTEND_CHAR
409 # define SIGN_EXTEND_CHAR(c) ((signed char) (c))
410 #else /* not __STDC__ */
411 /* As in Harbison and Steele. */
412 # define SIGN_EXTEND_CHAR(c) ((((unsigned char) (c)) ^ 128) - 128)
415 /* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we
416 use `alloca' instead of `malloc'. This is because using malloc in
417 re_search* or re_match* could cause memory leaks when C-g is used in
418 Emacs; also, malloc is slower and causes storage fragmentation. On
419 the other hand, malloc is more portable, and easier to debug.
421 Because we sometimes use alloca, some routines have to be macros,
422 not functions -- `alloca'-allocated space disappears at the end of the
423 function it is called in. */
427 # define REGEX_ALLOCATE malloc
428 # define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
429 # define REGEX_FREE free
431 #else /* not REGEX_MALLOC */
433 /* Emacs already defines alloca, sometimes. */
436 /* Make alloca work the best possible way. */
438 # define alloca __builtin_alloca
439 # else /* not __GNUC__ */
442 # endif /* HAVE_ALLOCA_H */
443 # endif /* not __GNUC__ */
445 # endif /* not alloca */
447 # define REGEX_ALLOCATE alloca
449 /* Assumes a `char *destination' variable. */
450 # define REGEX_REALLOCATE(source, osize, nsize) \
451 (destination = (char *) alloca (nsize), \
452 memcpy (destination, source, osize))
454 /* No need to do anything to free, after alloca. */
455 # define REGEX_FREE(arg) ((void)0) /* Do nothing! But inhibit gcc warning. */
457 #endif /* not REGEX_MALLOC */
459 /* Define how to allocate the failure stack. */
461 #if defined REL_ALLOC && defined REGEX_MALLOC
463 # define REGEX_ALLOCATE_STACK(size) \
464 r_alloc (&failure_stack_ptr, (size))
465 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
466 r_re_alloc (&failure_stack_ptr, (nsize))
467 # define REGEX_FREE_STACK(ptr) \
468 r_alloc_free (&failure_stack_ptr)
470 #else /* not using relocating allocator */
474 # define REGEX_ALLOCATE_STACK malloc
475 # define REGEX_REALLOCATE_STACK(source, osize, nsize) realloc (source, nsize)
476 # define REGEX_FREE_STACK free
478 # else /* not REGEX_MALLOC */
480 # define REGEX_ALLOCATE_STACK alloca
482 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
483 REGEX_REALLOCATE (source, osize, nsize)
484 /* No need to explicitly free anything. */
485 # define REGEX_FREE_STACK(arg) ((void)0)
487 # endif /* not REGEX_MALLOC */
488 #endif /* not using relocating allocator */
491 /* True if `size1' is non-NULL and PTR is pointing anywhere inside
492 `string1' or just past its end. This works if PTR is NULL, which is
494 #define FIRST_STRING_P(ptr) \
495 (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
497 /* (Re)Allocate N items of type T using malloc, or fail. */
498 #define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
499 #define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
500 #define RETALLOC_IF(addr, n, t) \
501 if (addr) RETALLOC((addr), (n), t); else (addr) = TALLOC ((n), t)
502 #define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
504 #define BYTEWIDTH 8 /* In bits. */
506 #define STREQ(s1, s2) ((strcmp (s1, s2) == 0))
510 #define MAX(a, b) ((a) > (b) ? (a) : (b))
511 #define MIN(a, b) ((a) < (b) ? (a) : (b))
513 /* Type of source-pattern and string chars. */
514 typedef const unsigned char re_char;
516 typedef char boolean;
520 static int re_match_2_internal _RE_ARGS ((struct re_pattern_buffer *bufp,
521 re_char *string1, int size1,
522 re_char *string2, int size2,
524 struct re_registers *regs,
527 /* These are the command codes that appear in compiled regular
528 expressions. Some opcodes are followed by argument bytes. A
529 command code can specify any interpretation whatsoever for its
530 arguments. Zero bytes may appear in the compiled regular expression. */
536 /* Succeed right away--no more backtracking. */
539 /* Followed by one byte giving n, then by n literal bytes. */
542 /* Matches any (more or less) character. */
545 /* Matches any one char belonging to specified set. First
546 following byte is number of bitmap bytes. Then come bytes
547 for a bitmap saying which chars are in. Bits in each byte
548 are ordered low-bit-first. A character is in the set if its
549 bit is 1. A character too large to have a bit in the map is
550 automatically not in the set.
552 If the length byte has the 0x80 bit set, then that stuff
553 is followed by a range table:
554 2 bytes of flags for character sets (low 8 bits, high 8 bits)
555 See RANGE_TABLE_WORK_BITS below.
556 2 bytes, the number of pairs that follow
557 pairs, each 2 multibyte characters,
558 each multibyte character represented as 3 bytes. */
561 /* Same parameters as charset, but match any character that is
562 not one of those specified. */
565 /* Start remembering the text that is matched, for storing in a
566 register. Followed by one byte with the register number, in
567 the range 0 to one less than the pattern buffer's re_nsub
571 /* Stop remembering the text that is matched and store it in a
572 memory register. Followed by one byte with the register
573 number, in the range 0 to one less than `re_nsub' in the
577 /* Match a duplicate of something remembered. Followed by one
578 byte containing the register number. */
581 /* Fail unless at beginning of line. */
584 /* Fail unless at end of line. */
587 /* Succeeds if at beginning of buffer (if emacs) or at beginning
588 of string to be matched (if not). */
591 /* Analogously, for end of buffer/string. */
594 /* Followed by two byte relative address to which to jump. */
597 /* Followed by two-byte relative address of place to resume at
598 in case of failure. */
601 /* Like on_failure_jump, but pushes a placeholder instead of the
602 current string position when executed. */
603 on_failure_keep_string_jump,
605 /* Just like `on_failure_jump', except that it checks that we
606 don't get stuck in an infinite loop (matching an empty string
608 on_failure_jump_loop,
610 /* Just like `on_failure_jump_loop', except that it checks for
611 a different kind of loop (the kind that shows up with non-greedy
612 operators). This operation has to be immediately preceded
614 on_failure_jump_nastyloop,
616 /* A smart `on_failure_jump' used for greedy * and + operators.
617 It analyses the loop before which it is put and if the
618 loop does not require backtracking, it changes itself to
619 `on_failure_keep_string_jump' and short-circuits the loop,
620 else it just defaults to changing itself into `on_failure_jump'.
621 It assumes that it is pointing to just past a `jump'. */
622 on_failure_jump_smart,
624 /* Followed by two-byte relative address and two-byte number n.
625 After matching N times, jump to the address upon failure.
626 Does not work if N starts at 0: use on_failure_jump_loop
630 /* Followed by two-byte relative address, and two-byte number n.
631 Jump to the address N times, then fail. */
634 /* Set the following two-byte relative address to the
635 subsequent two-byte number. The address *includes* the two
639 wordbeg, /* Succeeds if at word beginning. */
640 wordend, /* Succeeds if at word end. */
642 wordbound, /* Succeeds if at a word boundary. */
643 notwordbound, /* Succeeds if not at a word boundary. */
645 /* Matches any character whose syntax is specified. Followed by
646 a byte which contains a syntax code, e.g., Sword. */
649 /* Matches any character whose syntax is not that specified. */
653 ,before_dot, /* Succeeds if before point. */
654 at_dot, /* Succeeds if at point. */
655 after_dot, /* Succeeds if after point. */
657 /* Matches any character whose category-set contains the specified
658 category. The operator is followed by a byte which contains a
659 category code (mnemonic ASCII character). */
662 /* Matches any character whose category-set does not contain the
663 specified category. The operator is followed by a byte which
664 contains the category code (mnemonic ASCII character). */
669 /* Common operations on the compiled pattern. */
671 /* Store NUMBER in two contiguous bytes starting at DESTINATION. */
673 #define STORE_NUMBER(destination, number) \
675 (destination)[0] = (number) & 0377; \
676 (destination)[1] = (number) >> 8; \
679 /* Same as STORE_NUMBER, except increment DESTINATION to
680 the byte after where the number is stored. Therefore, DESTINATION
681 must be an lvalue. */
683 #define STORE_NUMBER_AND_INCR(destination, number) \
685 STORE_NUMBER (destination, number); \
686 (destination) += 2; \
689 /* Put into DESTINATION a number stored in two contiguous bytes starting
692 #define EXTRACT_NUMBER(destination, source) \
694 (destination) = *(source) & 0377; \
695 (destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8; \
699 static void extract_number _RE_ARGS ((int *dest, re_char *source));
701 extract_number (dest, source)
703 unsigned char *source;
705 int temp = SIGN_EXTEND_CHAR (*(source + 1));
706 *dest = *source & 0377;
710 # ifndef EXTRACT_MACROS /* To debug the macros. */
711 # undef EXTRACT_NUMBER
712 # define EXTRACT_NUMBER(dest, src) extract_number (&dest, src)
713 # endif /* not EXTRACT_MACROS */
717 /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
718 SOURCE must be an lvalue. */
720 #define EXTRACT_NUMBER_AND_INCR(destination, source) \
722 EXTRACT_NUMBER (destination, source); \
727 static void extract_number_and_incr _RE_ARGS ((int *destination,
730 extract_number_and_incr (destination, source)
732 unsigned char **source;
734 extract_number (destination, *source);
738 # ifndef EXTRACT_MACROS
739 # undef EXTRACT_NUMBER_AND_INCR
740 # define EXTRACT_NUMBER_AND_INCR(dest, src) \
741 extract_number_and_incr (&dest, &src)
742 # endif /* not EXTRACT_MACROS */
746 /* Store a multibyte character in three contiguous bytes starting
747 DESTINATION, and increment DESTINATION to the byte after where the
748 character is stored. Therefore, DESTINATION must be an lvalue. */
750 #define STORE_CHARACTER_AND_INCR(destination, character) \
752 (destination)[0] = (character) & 0377; \
753 (destination)[1] = ((character) >> 8) & 0377; \
754 (destination)[2] = (character) >> 16; \
755 (destination) += 3; \
758 /* Put into DESTINATION a character stored in three contiguous bytes
759 starting at SOURCE. */
761 #define EXTRACT_CHARACTER(destination, source) \
763 (destination) = ((source)[0] \
764 | ((source)[1] << 8) \
765 | ((source)[2] << 16)); \
769 /* Macros for charset. */
771 /* Size of bitmap of charset P in bytes. P is a start of charset,
772 i.e. *P is (re_opcode_t) charset or (re_opcode_t) charset_not. */
773 #define CHARSET_BITMAP_SIZE(p) ((p)[1] & 0x7F)
775 /* Nonzero if charset P has range table. */
776 #define CHARSET_RANGE_TABLE_EXISTS_P(p) ((p)[1] & 0x80)
778 /* Return the address of range table of charset P. But not the start
779 of table itself, but the before where the number of ranges is
780 stored. `2 +' means to skip re_opcode_t and size of bitmap,
781 and the 2 bytes of flags at the start of the range table. */
782 #define CHARSET_RANGE_TABLE(p) (&(p)[4 + CHARSET_BITMAP_SIZE (p)])
784 /* Extract the bit flags that start a range table. */
785 #define CHARSET_RANGE_TABLE_BITS(p) \
786 ((p)[2 + CHARSET_BITMAP_SIZE (p)] \
787 + (p)[3 + CHARSET_BITMAP_SIZE (p)] * 0x100)
789 /* Test if C is listed in the bitmap of charset P. */
790 #define CHARSET_LOOKUP_BITMAP(p, c) \
791 ((c) < CHARSET_BITMAP_SIZE (p) * BYTEWIDTH \
792 && (p)[2 + (c) / BYTEWIDTH] & (1 << ((c) % BYTEWIDTH)))
794 /* Return the address of end of RANGE_TABLE. COUNT is number of
795 ranges (which is a pair of (start, end)) in the RANGE_TABLE. `* 2'
796 is start of range and end of range. `* 3' is size of each start
798 #define CHARSET_RANGE_TABLE_END(range_table, count) \
799 ((range_table) + (count) * 2 * 3)
801 /* Test if C is in RANGE_TABLE. A flag NOT is negated if C is in.
802 COUNT is number of ranges in RANGE_TABLE. */
803 #define CHARSET_LOOKUP_RANGE_TABLE_RAW(not, c, range_table, count) \
806 int range_start, range_end; \
808 unsigned char *range_table_end \
809 = CHARSET_RANGE_TABLE_END ((range_table), (count)); \
811 for (p = (range_table); p < range_table_end; p += 2 * 3) \
813 EXTRACT_CHARACTER (range_start, p); \
814 EXTRACT_CHARACTER (range_end, p + 3); \
816 if (range_start <= (c) && (c) <= range_end) \
825 /* Test if C is in range table of CHARSET. The flag NOT is negated if
826 C is listed in it. */
827 #define CHARSET_LOOKUP_RANGE_TABLE(not, c, charset) \
830 /* Number of ranges in range table. */ \
832 unsigned char *range_table = CHARSET_RANGE_TABLE (charset); \
834 EXTRACT_NUMBER_AND_INCR (count, range_table); \
835 CHARSET_LOOKUP_RANGE_TABLE_RAW ((not), (c), range_table, count); \
839 /* If DEBUG is defined, Regex prints many voluminous messages about what
840 it is doing (if the variable `debug' is nonzero). If linked with the
841 main program in `iregex.c', you can enter patterns and strings
842 interactively. And if linked with the main program in `main.c' and
843 the other test files, you can run the already-written tests. */
847 /* We use standard I/O for debugging. */
850 /* It is useful to test things that ``must'' be true when debugging. */
853 static int debug = -100000;
855 # define DEBUG_STATEMENT(e) e
856 # define DEBUG_PRINT1(x) if (debug > 0) printf (x)
857 # define DEBUG_PRINT2(x1, x2) if (debug > 0) printf (x1, x2)
858 # define DEBUG_PRINT3(x1, x2, x3) if (debug > 0) printf (x1, x2, x3)
859 # define DEBUG_PRINT4(x1, x2, x3, x4) if (debug > 0) printf (x1, x2, x3, x4)
860 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
861 if (debug > 0) print_partial_compiled_pattern (s, e)
862 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
863 if (debug > 0) print_double_string (w, s1, sz1, s2, sz2)
866 /* Print the fastmap in human-readable form. */
869 print_fastmap (fastmap)
872 unsigned was_a_range = 0;
875 while (i < (1 << BYTEWIDTH))
881 while (i < (1 << BYTEWIDTH) && fastmap[i])
897 /* Print a compiled pattern string in human-readable form, starting at
898 the START pointer into it and ending just before the pointer END. */
901 print_partial_compiled_pattern (start, end)
902 unsigned char *start;
906 unsigned char *p = start;
907 unsigned char *pend = end;
915 /* Loop over pattern commands. */
918 printf ("%d:\t", p - start);
920 switch ((re_opcode_t) *p++)
932 printf ("/exactn/%d", mcnt);
942 printf ("/start_memory/%d", *p++);
946 printf ("/stop_memory/%d", *p++);
950 printf ("/duplicate/%d", *p++);
960 register int c, last = -100;
961 register int in_range = 0;
962 int length = CHARSET_BITMAP_SIZE (p - 1);
963 int has_range_table = CHARSET_RANGE_TABLE_EXISTS_P (p - 1);
965 printf ("/charset [%s",
966 (re_opcode_t) *(p - 1) == charset_not ? "^" : "");
968 assert (p + *p < pend);
970 for (c = 0; c < 256; c++)
972 && (p[1 + (c/8)] & (1 << (c % 8))))
974 /* Are we starting a range? */
975 if (last + 1 == c && ! in_range)
980 /* Have we broken a range? */
981 else if (last + 1 != c && in_range)
1000 if (has_range_table)
1003 printf ("has-range-table");
1005 /* ??? Should print the range table; for now, just skip it. */
1006 p += 2; /* skip range table bits */
1007 EXTRACT_NUMBER_AND_INCR (count, p);
1008 p = CHARSET_RANGE_TABLE_END (p, count);
1014 printf ("/begline");
1018 printf ("/endline");
1021 case on_failure_jump:
1022 extract_number_and_incr (&mcnt, &p);
1023 printf ("/on_failure_jump to %d", p + mcnt - start);
1026 case on_failure_keep_string_jump:
1027 extract_number_and_incr (&mcnt, &p);
1028 printf ("/on_failure_keep_string_jump to %d", p + mcnt - start);
1031 case on_failure_jump_nastyloop:
1032 extract_number_and_incr (&mcnt, &p);
1033 printf ("/on_failure_jump_nastyloop to %d", p + mcnt - start);
1036 case on_failure_jump_loop:
1037 extract_number_and_incr (&mcnt, &p);
1038 printf ("/on_failure_jump_loop to %d", p + mcnt - start);
1041 case on_failure_jump_smart:
1042 extract_number_and_incr (&mcnt, &p);
1043 printf ("/on_failure_jump_smart to %d", p + mcnt - start);
1047 extract_number_and_incr (&mcnt, &p);
1048 printf ("/jump to %d", p + mcnt - start);
1052 extract_number_and_incr (&mcnt, &p);
1053 extract_number_and_incr (&mcnt2, &p);
1054 printf ("/succeed_n to %d, %d times", p - 2 + mcnt - start, mcnt2);
1058 extract_number_and_incr (&mcnt, &p);
1059 extract_number_and_incr (&mcnt2, &p);
1060 printf ("/jump_n to %d, %d times", p - 2 + mcnt - start, mcnt2);
1064 extract_number_and_incr (&mcnt, &p);
1065 extract_number_and_incr (&mcnt2, &p);
1066 printf ("/set_number_at location %d to %d", p - 2 + mcnt - start, mcnt2);
1070 printf ("/wordbound");
1074 printf ("/notwordbound");
1078 printf ("/wordbeg");
1082 printf ("/wordend");
1085 printf ("/syntaxspec");
1087 printf ("/%d", mcnt);
1091 printf ("/notsyntaxspec");
1093 printf ("/%d", mcnt);
1098 printf ("/before_dot");
1106 printf ("/after_dot");
1110 printf ("/categoryspec");
1112 printf ("/%d", mcnt);
1115 case notcategoryspec:
1116 printf ("/notcategoryspec");
1118 printf ("/%d", mcnt);
1131 printf ("?%d", *(p-1));
1137 printf ("%d:\tend of pattern.\n", p - start);
1142 print_compiled_pattern (bufp)
1143 struct re_pattern_buffer *bufp;
1145 unsigned char *buffer = bufp->buffer;
1147 print_partial_compiled_pattern (buffer, buffer + bufp->used);
1148 printf ("%ld bytes used/%ld bytes allocated.\n",
1149 bufp->used, bufp->allocated);
1151 if (bufp->fastmap_accurate && bufp->fastmap)
1153 printf ("fastmap: ");
1154 print_fastmap (bufp->fastmap);
1157 printf ("re_nsub: %d\t", bufp->re_nsub);
1158 printf ("regs_alloc: %d\t", bufp->regs_allocated);
1159 printf ("can_be_null: %d\t", bufp->can_be_null);
1160 printf ("no_sub: %d\t", bufp->no_sub);
1161 printf ("not_bol: %d\t", bufp->not_bol);
1162 printf ("not_eol: %d\t", bufp->not_eol);
1163 printf ("syntax: %lx\n", bufp->syntax);
1165 /* Perhaps we should print the translate table? */
1170 print_double_string (where, string1, size1, string2, size2)
1183 if (FIRST_STRING_P (where))
1185 for (this_char = where - string1; this_char < size1; this_char++)
1186 putchar (string1[this_char]);
1191 for (this_char = where - string2; this_char < size2; this_char++)
1192 putchar (string2[this_char]);
1196 #else /* not DEBUG */
1201 # define DEBUG_STATEMENT(e)
1202 # define DEBUG_PRINT1(x)
1203 # define DEBUG_PRINT2(x1, x2)
1204 # define DEBUG_PRINT3(x1, x2, x3)
1205 # define DEBUG_PRINT4(x1, x2, x3, x4)
1206 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
1207 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
1209 #endif /* not DEBUG */
1211 /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
1212 also be assigned to arbitrarily: each pattern buffer stores its own
1213 syntax, so it can be changed between regex compilations. */
1214 /* This has no initializer because initialized variables in Emacs
1215 become read-only after dumping. */
1216 reg_syntax_t re_syntax_options;
1219 /* Specify the precise syntax of regexps for compilation. This provides
1220 for compatibility for various utilities which historically have
1221 different, incompatible syntaxes.
1223 The argument SYNTAX is a bit mask comprised of the various bits
1224 defined in regex.h. We return the old syntax. */
1227 re_set_syntax (syntax)
1228 reg_syntax_t syntax;
1230 reg_syntax_t ret = re_syntax_options;
1232 re_syntax_options = syntax;
1235 WEAK_ALIAS (__re_set_syntax, re_set_syntax)
1237 /* This table gives an error message for each of the error codes listed
1238 in regex.h. Obviously the order here has to be same as there.
1239 POSIX doesn't require that we do anything for REG_NOERROR,
1240 but why not be nice? */
1242 static const char *re_error_msgid[] =
1244 gettext_noop ("Success"), /* REG_NOERROR */
1245 gettext_noop ("No match"), /* REG_NOMATCH */
1246 gettext_noop ("Invalid regular expression"), /* REG_BADPAT */
1247 gettext_noop ("Invalid collation character"), /* REG_ECOLLATE */
1248 gettext_noop ("Invalid character class name"), /* REG_ECTYPE */
1249 gettext_noop ("Trailing backslash"), /* REG_EESCAPE */
1250 gettext_noop ("Invalid back reference"), /* REG_ESUBREG */
1251 gettext_noop ("Unmatched [ or [^"), /* REG_EBRACK */
1252 gettext_noop ("Unmatched ( or \\("), /* REG_EPAREN */
1253 gettext_noop ("Unmatched \\{"), /* REG_EBRACE */
1254 gettext_noop ("Invalid content of \\{\\}"), /* REG_BADBR */
1255 gettext_noop ("Invalid range end"), /* REG_ERANGE */
1256 gettext_noop ("Memory exhausted"), /* REG_ESPACE */
1257 gettext_noop ("Invalid preceding regular expression"), /* REG_BADRPT */
1258 gettext_noop ("Premature end of regular expression"), /* REG_EEND */
1259 gettext_noop ("Regular expression too big"), /* REG_ESIZE */
1260 gettext_noop ("Unmatched ) or \\)"), /* REG_ERPAREN */
1263 /* Avoiding alloca during matching, to placate r_alloc. */
1265 /* Define MATCH_MAY_ALLOCATE unless we need to make sure that the
1266 searching and matching functions should not call alloca. On some
1267 systems, alloca is implemented in terms of malloc, and if we're
1268 using the relocating allocator routines, then malloc could cause a
1269 relocation, which might (if the strings being searched are in the
1270 ralloc heap) shift the data out from underneath the regexp
1273 Here's another reason to avoid allocation: Emacs
1274 processes input from X in a signal handler; processing X input may
1275 call malloc; if input arrives while a matching routine is calling
1276 malloc, then we're scrod. But Emacs can't just block input while
1277 calling matching routines; then we don't notice interrupts when
1278 they come in. So, Emacs blocks input around all regexp calls
1279 except the matching calls, which it leaves unprotected, in the
1280 faith that they will not malloc. */
1282 /* Normally, this is fine. */
1283 #define MATCH_MAY_ALLOCATE
1285 /* When using GNU C, we are not REALLY using the C alloca, no matter
1286 what config.h may say. So don't take precautions for it. */
1291 /* The match routines may not allocate if (1) they would do it with malloc
1292 and (2) it's not safe for them to use malloc.
1293 Note that if REL_ALLOC is defined, matching would not use malloc for the
1294 failure stack, but we would still use it for the register vectors;
1295 so REL_ALLOC should not affect this. */
1296 #if (defined C_ALLOCA || defined REGEX_MALLOC) && defined emacs
1297 # undef MATCH_MAY_ALLOCATE
1301 /* Failure stack declarations and macros; both re_compile_fastmap and
1302 re_match_2 use a failure stack. These have to be macros because of
1303 REGEX_ALLOCATE_STACK. */
1306 /* Approximate number of failure points for which to initially allocate space
1307 when matching. If this number is exceeded, we allocate more
1308 space, so it is not a hard limit. */
1309 #ifndef INIT_FAILURE_ALLOC
1310 # define INIT_FAILURE_ALLOC 20
1313 /* Roughly the maximum number of failure points on the stack. Would be
1314 exactly that if always used TYPICAL_FAILURE_SIZE items each time we failed.
1315 This is a variable only so users of regex can assign to it; we never
1316 change it ourselves. */
1317 # if defined MATCH_MAY_ALLOCATE
1318 /* Note that 4400 was enough to cause a crash on Alpha OSF/1,
1319 whose default stack limit is 2mb. In order for a larger
1320 value to work reliably, you have to try to make it accord
1321 with the process stack limit. */
1322 size_t re_max_failures = 40000;
1324 size_t re_max_failures = 4000;
1327 union fail_stack_elt
1329 const unsigned char *pointer;
1330 /* This should be the biggest `int' that's no bigger than a pointer. */
1334 typedef union fail_stack_elt fail_stack_elt_t;
1338 fail_stack_elt_t *stack;
1340 size_t avail; /* Offset of next open position. */
1341 size_t frame; /* Offset of the cur constructed frame. */
1344 #define PATTERN_STACK_EMPTY() (fail_stack.avail == 0)
1345 #define FAIL_STACK_EMPTY() (fail_stack.frame == 0)
1346 #define FAIL_STACK_FULL() (fail_stack.avail == fail_stack.size)
1349 /* Define macros to initialize and free the failure stack.
1350 Do `return -2' if the alloc fails. */
1352 #ifdef MATCH_MAY_ALLOCATE
1353 # define INIT_FAIL_STACK() \
1355 fail_stack.stack = (fail_stack_elt_t *) \
1356 REGEX_ALLOCATE_STACK (INIT_FAILURE_ALLOC * TYPICAL_FAILURE_SIZE \
1357 * sizeof (fail_stack_elt_t)); \
1359 if (fail_stack.stack == NULL) \
1362 fail_stack.size = INIT_FAILURE_ALLOC; \
1363 fail_stack.avail = 0; \
1364 fail_stack.frame = 0; \
1367 # define RESET_FAIL_STACK() REGEX_FREE_STACK (fail_stack.stack)
1369 # define INIT_FAIL_STACK() \
1371 fail_stack.avail = 0; \
1372 fail_stack.frame = 0; \
1375 # define RESET_FAIL_STACK() ((void)0)
1379 /* Double the size of FAIL_STACK, up to a limit
1380 which allows approximately `re_max_failures' items.
1382 Return 1 if succeeds, and 0 if either ran out of memory
1383 allocating space for it or it was already too large.
1385 REGEX_REALLOCATE_STACK requires `destination' be declared. */
1387 /* Factor to increase the failure stack size by
1388 when we increase it.
1389 This used to be 2, but 2 was too wasteful
1390 because the old discarded stacks added up to as much space
1391 were as ultimate, maximum-size stack. */
1392 #define FAIL_STACK_GROWTH_FACTOR 4
1394 #define GROW_FAIL_STACK(fail_stack) \
1395 (((fail_stack).size * sizeof (fail_stack_elt_t) \
1396 >= re_max_failures * TYPICAL_FAILURE_SIZE) \
1398 : ((fail_stack).stack \
1399 = (fail_stack_elt_t *) \
1400 REGEX_REALLOCATE_STACK ((fail_stack).stack, \
1401 (fail_stack).size * sizeof (fail_stack_elt_t), \
1402 MIN (re_max_failures * TYPICAL_FAILURE_SIZE, \
1403 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1404 * FAIL_STACK_GROWTH_FACTOR))), \
1406 (fail_stack).stack == NULL \
1408 : ((fail_stack).size \
1409 = (MIN (re_max_failures * TYPICAL_FAILURE_SIZE, \
1410 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1411 * FAIL_STACK_GROWTH_FACTOR)) \
1412 / sizeof (fail_stack_elt_t)), \
1416 /* Push pointer POINTER on FAIL_STACK.
1417 Return 1 if was able to do so and 0 if ran out of memory allocating
1419 #define PUSH_PATTERN_OP(POINTER, FAIL_STACK) \
1420 ((FAIL_STACK_FULL () \
1421 && !GROW_FAIL_STACK (FAIL_STACK)) \
1423 : ((FAIL_STACK).stack[(FAIL_STACK).avail++].pointer = POINTER, \
1425 #define POP_PATTERN_OP() POP_FAILURE_POINTER ()
1427 /* Push a pointer value onto the failure stack.
1428 Assumes the variable `fail_stack'. Probably should only
1429 be called from within `PUSH_FAILURE_POINT'. */
1430 #define PUSH_FAILURE_POINTER(item) \
1431 fail_stack.stack[fail_stack.avail++].pointer = (unsigned char *) (item)
1433 /* This pushes an integer-valued item onto the failure stack.
1434 Assumes the variable `fail_stack'. Probably should only
1435 be called from within `PUSH_FAILURE_POINT'. */
1436 #define PUSH_FAILURE_INT(item) \
1437 fail_stack.stack[fail_stack.avail++].integer = (item)
1439 /* Push a fail_stack_elt_t value onto the failure stack.
1440 Assumes the variable `fail_stack'. Probably should only
1441 be called from within `PUSH_FAILURE_POINT'. */
1442 #define PUSH_FAILURE_ELT(item) \
1443 fail_stack.stack[fail_stack.avail++] = (item)
1445 /* These three POP... operations complement the three PUSH... operations.
1446 All assume that `fail_stack' is nonempty. */
1447 #define POP_FAILURE_POINTER() fail_stack.stack[--fail_stack.avail].pointer
1448 #define POP_FAILURE_INT() fail_stack.stack[--fail_stack.avail].integer
1449 #define POP_FAILURE_ELT() fail_stack.stack[--fail_stack.avail]
1451 /* Individual items aside from the registers. */
1452 #define NUM_NONREG_ITEMS 3
1454 /* Used to examine the stack (to detect infinite loops). */
1455 #define FAILURE_PAT(h) fail_stack.stack[(h) - 1].pointer
1456 #define FAILURE_STR(h) (fail_stack.stack[(h) - 2].pointer)
1457 #define NEXT_FAILURE_HANDLE(h) fail_stack.stack[(h) - 3].integer
1458 #define TOP_FAILURE_HANDLE() fail_stack.frame
1461 #define ENSURE_FAIL_STACK(space) \
1462 while (REMAINING_AVAIL_SLOTS <= space) { \
1463 if (!GROW_FAIL_STACK (fail_stack)) \
1465 DEBUG_PRINT2 ("\n Doubled stack; size now: %d\n", (fail_stack).size);\
1466 DEBUG_PRINT2 (" slots available: %d\n", REMAINING_AVAIL_SLOTS);\
1469 /* Push register NUM onto the stack. */
1470 #define PUSH_FAILURE_REG(num) \
1472 char *destination; \
1473 ENSURE_FAIL_STACK(3); \
1474 DEBUG_PRINT4 (" Push reg %d (spanning %p -> %p)\n", \
1475 num, regstart[num], regend[num]); \
1476 PUSH_FAILURE_POINTER (regstart[num]); \
1477 PUSH_FAILURE_POINTER (regend[num]); \
1478 PUSH_FAILURE_INT (num); \
1481 #define PUSH_FAILURE_COUNT(ptr) \
1483 char *destination; \
1485 ENSURE_FAIL_STACK(3); \
1486 EXTRACT_NUMBER (c, ptr); \
1487 DEBUG_PRINT3 (" Push counter %p = %d\n", ptr, c); \
1488 PUSH_FAILURE_INT (c); \
1489 PUSH_FAILURE_POINTER (ptr); \
1490 PUSH_FAILURE_INT (-1); \
1493 /* Pop a saved register off the stack. */
1494 #define POP_FAILURE_REG_OR_COUNT() \
1496 int reg = POP_FAILURE_INT (); \
1499 /* It's a counter. */ \
1500 unsigned char *ptr = (unsigned char*) POP_FAILURE_POINTER (); \
1501 reg = POP_FAILURE_INT (); \
1502 STORE_NUMBER (ptr, reg); \
1503 DEBUG_PRINT3 (" Pop counter %p = %d\n", ptr, reg); \
1507 regend[reg] = POP_FAILURE_POINTER (); \
1508 regstart[reg] = POP_FAILURE_POINTER (); \
1509 DEBUG_PRINT4 (" Pop reg %d (spanning %p -> %p)\n", \
1510 reg, regstart[reg], regend[reg]); \
1514 /* Check that we are not stuck in an infinite loop. */
1515 #define CHECK_INFINITE_LOOP(pat_cur, string_place) \
1517 int failure = TOP_FAILURE_HANDLE(); \
1518 /* Check for infinite matching loops */ \
1519 while (failure > 0 && \
1520 (FAILURE_STR (failure) == string_place \
1521 || FAILURE_STR (failure) == NULL)) \
1523 assert (FAILURE_PAT (failure) >= bufp->buffer \
1524 && FAILURE_PAT (failure) <= bufp->buffer + bufp->used); \
1525 if (FAILURE_PAT (failure) == pat_cur) \
1527 DEBUG_PRINT2 (" Other pattern: %p\n", FAILURE_PAT (failure)); \
1528 failure = NEXT_FAILURE_HANDLE(failure); \
1530 DEBUG_PRINT2 (" Other string: %p\n", FAILURE_STR (failure)); \
1533 /* Push the information about the state we will need
1534 if we ever fail back to it.
1536 Requires variables fail_stack, regstart, regend and
1537 num_regs be declared. GROW_FAIL_STACK requires `destination' be
1540 Does `return FAILURE_CODE' if runs out of memory. */
1542 #define PUSH_FAILURE_POINT(pattern, string_place) \
1544 char *destination; \
1545 /* Must be int, so when we don't save any registers, the arithmetic \
1546 of 0 + -1 isn't done as unsigned. */ \
1548 DEBUG_STATEMENT (nfailure_points_pushed++); \
1549 DEBUG_PRINT1 ("\nPUSH_FAILURE_POINT:\n"); \
1550 DEBUG_PRINT2 (" Before push, next avail: %d\n", (fail_stack).avail); \
1551 DEBUG_PRINT2 (" size: %d\n", (fail_stack).size);\
1553 ENSURE_FAIL_STACK (NUM_NONREG_ITEMS); \
1555 DEBUG_PRINT1 ("\n"); \
1557 DEBUG_PRINT2 (" Push frame index: %d\n", fail_stack.frame); \
1558 PUSH_FAILURE_INT (fail_stack.frame); \
1560 DEBUG_PRINT2 (" Push string %p: `", string_place); \
1561 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, size2);\
1562 DEBUG_PRINT1 ("'\n"); \
1563 PUSH_FAILURE_POINTER (string_place); \
1565 DEBUG_PRINT2 (" Push pattern %p: ", pattern); \
1566 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern, pend); \
1567 PUSH_FAILURE_POINTER (pattern); \
1569 /* Close the frame by moving the frame pointer past it. */ \
1570 fail_stack.frame = fail_stack.avail; \
1573 /* Estimate the size of data pushed by a typical failure stack entry.
1574 An estimate is all we need, because all we use this for
1575 is to choose a limit for how big to make the failure stack. */
1577 #define TYPICAL_FAILURE_SIZE 20
1579 /* How many items can still be added to the stack without overflowing it. */
1580 #define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
1583 /* Pops what PUSH_FAIL_STACK pushes.
1585 We restore into the parameters, all of which should be lvalues:
1586 STR -- the saved data position.
1587 PAT -- the saved pattern position.
1588 REGSTART, REGEND -- arrays of string positions.
1590 Also assumes the variables `fail_stack' and (if debugging), `bufp',
1591 `pend', `string1', `size1', `string2', and `size2'. */
1593 #define POP_FAILURE_POINT(str, pat) \
1595 assert (!FAIL_STACK_EMPTY ()); \
1597 /* Remove failure points and point to how many regs pushed. */ \
1598 DEBUG_PRINT1 ("POP_FAILURE_POINT:\n"); \
1599 DEBUG_PRINT2 (" Before pop, next avail: %d\n", fail_stack.avail); \
1600 DEBUG_PRINT2 (" size: %d\n", fail_stack.size); \
1602 /* Pop the saved registers. */ \
1603 while (fail_stack.frame < fail_stack.avail) \
1604 POP_FAILURE_REG_OR_COUNT (); \
1606 pat = (unsigned char *) POP_FAILURE_POINTER (); \
1607 DEBUG_PRINT2 (" Popping pattern %p: ", pat); \
1608 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
1610 /* If the saved string location is NULL, it came from an \
1611 on_failure_keep_string_jump opcode, and we want to throw away the \
1612 saved NULL, thus retaining our current position in the string. */ \
1613 str = (re_char *) POP_FAILURE_POINTER (); \
1614 DEBUG_PRINT2 (" Popping string %p: `", str); \
1615 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
1616 DEBUG_PRINT1 ("'\n"); \
1618 fail_stack.frame = POP_FAILURE_INT (); \
1619 DEBUG_PRINT2 (" Popping frame index: %d\n", fail_stack.frame); \
1621 assert (fail_stack.avail >= 0); \
1622 assert (fail_stack.frame <= fail_stack.avail); \
1624 DEBUG_STATEMENT (nfailure_points_popped++); \
1625 } while (0) /* POP_FAILURE_POINT */
1629 /* Registers are set to a sentinel when they haven't yet matched. */
1630 #define REG_UNSET(e) ((e) == NULL)
1632 /* Subroutine declarations and macros for regex_compile. */
1634 static reg_errcode_t regex_compile _RE_ARGS ((re_char *pattern, size_t size,
1635 reg_syntax_t syntax,
1636 struct re_pattern_buffer *bufp));
1637 static void store_op1 _RE_ARGS ((re_opcode_t op, unsigned char *loc, int arg));
1638 static void store_op2 _RE_ARGS ((re_opcode_t op, unsigned char *loc,
1639 int arg1, int arg2));
1640 static void insert_op1 _RE_ARGS ((re_opcode_t op, unsigned char *loc,
1641 int arg, unsigned char *end));
1642 static void insert_op2 _RE_ARGS ((re_opcode_t op, unsigned char *loc,
1643 int arg1, int arg2, unsigned char *end));
1644 static boolean at_begline_loc_p _RE_ARGS ((const unsigned char *pattern,
1645 const unsigned char *p,
1646 reg_syntax_t syntax));
1647 static boolean at_endline_loc_p _RE_ARGS ((const unsigned char *p,
1648 const unsigned char *pend,
1649 reg_syntax_t syntax));
1650 static unsigned char *skip_one_char _RE_ARGS ((unsigned char *p));
1651 static int analyse_first _RE_ARGS ((unsigned char *p, unsigned char *pend,
1652 char *fastmap, const int multibyte));
1654 /* Fetch the next character in the uncompiled pattern---translating it
1655 if necessary. Also cast from a signed character in the constant
1656 string passed to us by the user to an unsigned char that we can use
1657 as an array index (in, e.g., `translate'). */
1658 #define PATFETCH(c) \
1661 c = TRANSLATE (c); \
1664 /* Fetch the next character in the uncompiled pattern, with no
1666 #define PATFETCH_RAW(c) \
1669 if (p == pend) return REG_EEND; \
1670 c = RE_STRING_CHAR_AND_LENGTH (p, pend - p, len); \
1675 /* If `translate' is non-null, return translate[D], else just D. We
1676 cast the subscript to translate because some data is declared as
1677 `char *', to avoid warnings when a string constant is passed. But
1678 when we use a character as a subscript we must make it unsigned. */
1680 # define TRANSLATE(d) \
1681 (RE_TRANSLATE_P (translate) ? RE_TRANSLATE (translate, (d)) : (d))
1685 /* Macros for outputting the compiled pattern into `buffer'. */
1687 /* If the buffer isn't allocated when it comes in, use this. */
1688 #define INIT_BUF_SIZE 32
1690 /* Make sure we have at least N more bytes of space in buffer. */
1691 #define GET_BUFFER_SPACE(n) \
1692 while ((unsigned long) (b - bufp->buffer + (n)) > bufp->allocated) \
1695 /* Make sure we have one more byte of buffer space and then add C to it. */
1696 #define BUF_PUSH(c) \
1698 GET_BUFFER_SPACE (1); \
1699 *b++ = (unsigned char) (c); \
1703 /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
1704 #define BUF_PUSH_2(c1, c2) \
1706 GET_BUFFER_SPACE (2); \
1707 *b++ = (unsigned char) (c1); \
1708 *b++ = (unsigned char) (c2); \
1712 /* As with BUF_PUSH_2, except for three bytes. */
1713 #define BUF_PUSH_3(c1, c2, c3) \
1715 GET_BUFFER_SPACE (3); \
1716 *b++ = (unsigned char) (c1); \
1717 *b++ = (unsigned char) (c2); \
1718 *b++ = (unsigned char) (c3); \
1722 /* Store a jump with opcode OP at LOC to location TO. We store a
1723 relative address offset by the three bytes the jump itself occupies. */
1724 #define STORE_JUMP(op, loc, to) \
1725 store_op1 (op, loc, (to) - (loc) - 3)
1727 /* Likewise, for a two-argument jump. */
1728 #define STORE_JUMP2(op, loc, to, arg) \
1729 store_op2 (op, loc, (to) - (loc) - 3, arg)
1731 /* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
1732 #define INSERT_JUMP(op, loc, to) \
1733 insert_op1 (op, loc, (to) - (loc) - 3, b)
1735 /* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
1736 #define INSERT_JUMP2(op, loc, to, arg) \
1737 insert_op2 (op, loc, (to) - (loc) - 3, arg, b)
1740 /* This is not an arbitrary limit: the arguments which represent offsets
1741 into the pattern are two bytes long. So if 2^16 bytes turns out to
1742 be too small, many things would have to change. */
1743 /* Any other compiler which, like MSC, has allocation limit below 2^16
1744 bytes will have to use approach similar to what was done below for
1745 MSC and drop MAX_BUF_SIZE a bit. Otherwise you may end up
1746 reallocating to 0 bytes. Such thing is not going to work too well.
1747 You have been warned!! */
1748 #if defined _MSC_VER && !defined WIN32
1749 /* Microsoft C 16-bit versions limit malloc to approx 65512 bytes. */
1750 # define MAX_BUF_SIZE 65500L
1752 # define MAX_BUF_SIZE (1L << 16)
1755 /* Extend the buffer by twice its current size via realloc and
1756 reset the pointers that pointed into the old block to point to the
1757 correct places in the new one. If extending the buffer results in it
1758 being larger than MAX_BUF_SIZE, then flag memory exhausted. */
1759 #if __BOUNDED_POINTERS__
1760 # define SET_HIGH_BOUND(P) (__ptrhigh (P) = __ptrlow (P) + bufp->allocated)
1761 # define MOVE_BUFFER_POINTER(P) \
1762 (__ptrlow (P) += incr, SET_HIGH_BOUND (P), __ptrvalue (P) += incr)
1763 # define ELSE_EXTEND_BUFFER_HIGH_BOUND \
1766 SET_HIGH_BOUND (b); \
1767 SET_HIGH_BOUND (begalt); \
1768 if (fixup_alt_jump) \
1769 SET_HIGH_BOUND (fixup_alt_jump); \
1771 SET_HIGH_BOUND (laststart); \
1772 if (pending_exact) \
1773 SET_HIGH_BOUND (pending_exact); \
1776 # define MOVE_BUFFER_POINTER(P) (P) += incr
1777 # define ELSE_EXTEND_BUFFER_HIGH_BOUND
1779 #define EXTEND_BUFFER() \
1781 unsigned char *old_buffer = bufp->buffer; \
1782 if (bufp->allocated == MAX_BUF_SIZE) \
1784 bufp->allocated <<= 1; \
1785 if (bufp->allocated > MAX_BUF_SIZE) \
1786 bufp->allocated = MAX_BUF_SIZE; \
1787 bufp->buffer = (unsigned char *) realloc (bufp->buffer, bufp->allocated);\
1788 if (bufp->buffer == NULL) \
1789 return REG_ESPACE; \
1790 /* If the buffer moved, move all the pointers into it. */ \
1791 if (old_buffer != bufp->buffer) \
1793 int incr = bufp->buffer - old_buffer; \
1794 MOVE_BUFFER_POINTER (b); \
1795 MOVE_BUFFER_POINTER (begalt); \
1796 if (fixup_alt_jump) \
1797 MOVE_BUFFER_POINTER (fixup_alt_jump); \
1799 MOVE_BUFFER_POINTER (laststart); \
1800 if (pending_exact) \
1801 MOVE_BUFFER_POINTER (pending_exact); \
1803 ELSE_EXTEND_BUFFER_HIGH_BOUND \
1807 /* Since we have one byte reserved for the register number argument to
1808 {start,stop}_memory, the maximum number of groups we can report
1809 things about is what fits in that byte. */
1810 #define MAX_REGNUM 255
1812 /* But patterns can have more than `MAX_REGNUM' registers. We just
1813 ignore the excess. */
1814 typedef unsigned regnum_t;
1817 /* Macros for the compile stack. */
1819 /* Since offsets can go either forwards or backwards, this type needs to
1820 be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
1821 /* int may be not enough when sizeof(int) == 2. */
1822 typedef long pattern_offset_t;
1826 pattern_offset_t begalt_offset;
1827 pattern_offset_t fixup_alt_jump;
1828 pattern_offset_t laststart_offset;
1830 } compile_stack_elt_t;
1835 compile_stack_elt_t *stack;
1837 unsigned avail; /* Offset of next open position. */
1838 } compile_stack_type;
1841 #define INIT_COMPILE_STACK_SIZE 32
1843 #define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
1844 #define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
1846 /* The next available element. */
1847 #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
1850 /* Structure to manage work area for range table. */
1851 struct range_table_work_area
1853 int *table; /* actual work area. */
1854 int allocated; /* allocated size for work area in bytes. */
1855 int used; /* actually used size in words. */
1856 int bits; /* flag to record character classes */
1859 /* Make sure that WORK_AREA can hold more N multibyte characters. */
1860 #define EXTEND_RANGE_TABLE_WORK_AREA(work_area, n) \
1862 if (((work_area).used + (n)) * sizeof (int) > (work_area).allocated) \
1864 (work_area).allocated += 16 * sizeof (int); \
1865 if ((work_area).table) \
1867 = (int *) realloc ((work_area).table, (work_area).allocated); \
1870 = (int *) malloc ((work_area).allocated); \
1871 if ((work_area).table == 0) \
1872 FREE_STACK_RETURN (REG_ESPACE); \
1876 #define SET_RANGE_TABLE_WORK_AREA_BIT(work_area, bit) \
1877 (work_area).bits |= (bit)
1879 /* Bits used to implement the multibyte-part of the various character classes
1880 such as [:alnum:] in a charset's range table. */
1881 #define BIT_WORD 0x1
1882 #define BIT_LOWER 0x2
1883 #define BIT_PUNCT 0x4
1884 #define BIT_SPACE 0x8
1885 #define BIT_UPPER 0x10
1886 #define BIT_MULTIBYTE 0x20
1888 /* Set a range (RANGE_START, RANGE_END) to WORK_AREA. */
1889 #define SET_RANGE_TABLE_WORK_AREA(work_area, range_start, range_end) \
1891 EXTEND_RANGE_TABLE_WORK_AREA ((work_area), 2); \
1892 (work_area).table[(work_area).used++] = (range_start); \
1893 (work_area).table[(work_area).used++] = (range_end); \
1896 /* Free allocated memory for WORK_AREA. */
1897 #define FREE_RANGE_TABLE_WORK_AREA(work_area) \
1899 if ((work_area).table) \
1900 free ((work_area).table); \
1903 #define CLEAR_RANGE_TABLE_WORK_USED(work_area) ((work_area).used = 0, (work_area).bits = 0)
1904 #define RANGE_TABLE_WORK_USED(work_area) ((work_area).used)
1905 #define RANGE_TABLE_WORK_BITS(work_area) ((work_area).bits)
1906 #define RANGE_TABLE_WORK_ELT(work_area, i) ((work_area).table[i])
1909 /* Set the bit for character C in a list. */
1910 #define SET_LIST_BIT(c) \
1911 (b[((unsigned char) (c)) / BYTEWIDTH] \
1912 |= 1 << (((unsigned char) c) % BYTEWIDTH))
1915 /* Get the next unsigned number in the uncompiled pattern. */
1916 #define GET_UNSIGNED_NUMBER(num) \
1917 do { if (p != pend) \
1920 while ('0' <= c && c <= '9') \
1924 num = num * 10 + c - '0'; \
1932 #if defined _LIBC || WIDE_CHAR_SUPPORT
1933 /* The GNU C library provides support for user-defined character classes
1934 and the functions from ISO C amendement 1. */
1935 # ifdef CHARCLASS_NAME_MAX
1936 # define CHAR_CLASS_MAX_LENGTH CHARCLASS_NAME_MAX
1938 /* This shouldn't happen but some implementation might still have this
1939 problem. Use a reasonable default value. */
1940 # define CHAR_CLASS_MAX_LENGTH 256
1942 typedef wctype_t re_wctype_t;
1943 # define re_wctype wctype
1944 # define re_iswctype iswctype
1945 # define re_wctype_to_bit(cc) 0
1947 # define CHAR_CLASS_MAX_LENGTH 9 /* Namely, `multibyte'. */
1950 /* Character classes' indices. */
1951 typedef enum { RECC_ERROR = 0,
1952 RECC_ALNUM, RECC_ALPHA, RECC_WORD,
1953 RECC_GRAPH, RECC_PRINT,
1954 RECC_LOWER, RECC_UPPER,
1955 RECC_PUNCT, RECC_CNTRL,
1956 RECC_DIGIT, RECC_XDIGIT,
1957 RECC_BLANK, RECC_SPACE,
1958 RECC_MULTIBYTE, RECC_NONASCII,
1959 RECC_ASCII, RECC_UNIBYTE
1962 /* Map a string to the char class it names (if any). */
1965 unsigned char *string;
1967 if (STREQ (string, "alnum")) return RECC_ALNUM;
1968 else if (STREQ (string, "alpha")) return RECC_ALPHA;
1969 else if (STREQ (string, "word")) return RECC_WORD;
1970 else if (STREQ (string, "ascii")) return RECC_ASCII;
1971 else if (STREQ (string, "nonascii")) return RECC_NONASCII;
1972 else if (STREQ (string, "graph")) return RECC_GRAPH;
1973 else if (STREQ (string, "lower")) return RECC_LOWER;
1974 else if (STREQ (string, "print")) return RECC_PRINT;
1975 else if (STREQ (string, "punct")) return RECC_PUNCT;
1976 else if (STREQ (string, "space")) return RECC_SPACE;
1977 else if (STREQ (string, "upper")) return RECC_UPPER;
1978 else if (STREQ (string, "unibyte")) return RECC_UNIBYTE;
1979 else if (STREQ (string, "multibyte")) return RECC_MULTIBYTE;
1980 else if (STREQ (string, "digit")) return RECC_DIGIT;
1981 else if (STREQ (string, "xdigit")) return RECC_XDIGIT;
1982 else if (STREQ (string, "cntrl")) return RECC_CNTRL;
1983 else if (STREQ (string, "blank")) return RECC_BLANK;
1987 /* True iff CH is in the char class CC. */
1989 re_iswctype (ch, cc)
1995 case RECC_ALNUM: return ISALNUM (ch);
1996 case RECC_ALPHA: return ISALPHA (ch);
1997 case RECC_BLANK: return ISBLANK (ch);
1998 case RECC_CNTRL: return ISCNTRL (ch);
1999 case RECC_DIGIT: return ISDIGIT (ch);
2000 case RECC_GRAPH: return ISGRAPH (ch);
2001 case RECC_LOWER: return ISLOWER (ch);
2002 case RECC_PRINT: return ISPRINT (ch);
2003 case RECC_PUNCT: return ISPUNCT (ch);
2004 case RECC_SPACE: return ISSPACE (ch);
2005 case RECC_UPPER: return ISUPPER (ch);
2006 case RECC_XDIGIT: return ISXDIGIT (ch);
2007 case RECC_ASCII: return IS_REAL_ASCII (ch);
2008 case RECC_NONASCII: return !IS_REAL_ASCII (ch);
2009 case RECC_UNIBYTE: return ISUNIBYTE (ch);
2010 case RECC_MULTIBYTE: return !ISUNIBYTE (ch);
2011 case RECC_WORD: return ISWORD (ch);
2012 case RECC_ERROR: return false;
2016 /* Return a bit-pattern to use in the range-table bits to match multibyte
2017 chars of class CC. */
2019 re_wctype_to_bit (cc)
2024 case RECC_NONASCII: case RECC_PRINT: case RECC_GRAPH:
2025 case RECC_MULTIBYTE: return BIT_MULTIBYTE;
2026 case RECC_ALPHA: case RECC_ALNUM: case RECC_WORD: return BIT_WORD;
2027 case RECC_LOWER: return BIT_LOWER;
2028 case RECC_UPPER: return BIT_UPPER;
2029 case RECC_PUNCT: return BIT_PUNCT;
2030 case RECC_SPACE: return BIT_SPACE;
2031 case RECC_ASCII: case RECC_DIGIT: case RECC_XDIGIT: case RECC_CNTRL:
2032 case RECC_BLANK: case RECC_UNIBYTE: case RECC_ERROR: return 0;
2037 /* QUIT is only used on NTemacs. */
2038 #if !defined WINDOWSNT || !defined emacs || !defined QUIT
2043 #ifndef MATCH_MAY_ALLOCATE
2045 /* If we cannot allocate large objects within re_match_2_internal,
2046 we make the fail stack and register vectors global.
2047 The fail stack, we grow to the maximum size when a regexp
2049 The register vectors, we adjust in size each time we
2050 compile a regexp, according to the number of registers it needs. */
2052 static fail_stack_type fail_stack;
2054 /* Size with which the following vectors are currently allocated.
2055 That is so we can make them bigger as needed,
2056 but never make them smaller. */
2057 static int regs_allocated_size;
2059 static re_char ** regstart, ** regend;
2060 static re_char **best_regstart, **best_regend;
2062 /* Make the register vectors big enough for NUM_REGS registers,
2063 but don't make them smaller. */
2066 regex_grow_registers (num_regs)
2069 if (num_regs > regs_allocated_size)
2071 RETALLOC_IF (regstart, num_regs, re_char *);
2072 RETALLOC_IF (regend, num_regs, re_char *);
2073 RETALLOC_IF (best_regstart, num_regs, re_char *);
2074 RETALLOC_IF (best_regend, num_regs, re_char *);
2076 regs_allocated_size = num_regs;
2080 #endif /* not MATCH_MAY_ALLOCATE */
2082 static boolean group_in_compile_stack _RE_ARGS ((compile_stack_type
2086 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
2087 Returns one of error codes defined in `regex.h', or zero for success.
2089 Assumes the `allocated' (and perhaps `buffer') and `translate'
2090 fields are set in BUFP on entry.
2092 If it succeeds, results are put in BUFP (if it returns an error, the
2093 contents of BUFP are undefined):
2094 `buffer' is the compiled pattern;
2095 `syntax' is set to SYNTAX;
2096 `used' is set to the length of the compiled pattern;
2097 `fastmap_accurate' is zero;
2098 `re_nsub' is the number of subexpressions in PATTERN;
2099 `not_bol' and `not_eol' are zero;
2101 The `fastmap' field is neither examined nor set. */
2103 /* Insert the `jump' from the end of last alternative to "here".
2104 The space for the jump has already been allocated. */
2105 #define FIXUP_ALT_JUMP() \
2107 if (fixup_alt_jump) \
2108 STORE_JUMP (jump, fixup_alt_jump, b); \
2112 /* Return, freeing storage we allocated. */
2113 #define FREE_STACK_RETURN(value) \
2115 FREE_RANGE_TABLE_WORK_AREA (range_table_work); \
2116 free (compile_stack.stack); \
2120 static reg_errcode_t
2121 regex_compile (pattern, size, syntax, bufp)
2124 reg_syntax_t syntax;
2125 struct re_pattern_buffer *bufp;
2127 /* We fetch characters from PATTERN here. Even though PATTERN is
2128 `char *' (i.e., signed), we declare these variables as unsigned, so
2129 they can be reliably used as array indices. */
2130 register unsigned int c, c1;
2132 /* A random temporary spot in PATTERN. */
2135 /* Points to the end of the buffer, where we should append. */
2136 register unsigned char *b;
2138 /* Keeps track of unclosed groups. */
2139 compile_stack_type compile_stack;
2141 /* Points to the current (ending) position in the pattern. */
2143 /* `const' makes AIX compiler fail. */
2144 unsigned char *p = pattern;
2146 re_char *p = pattern;
2148 re_char *pend = pattern + size;
2150 /* How to translate the characters in the pattern. */
2151 RE_TRANSLATE_TYPE translate = bufp->translate;
2153 /* Address of the count-byte of the most recently inserted `exactn'
2154 command. This makes it possible to tell if a new exact-match
2155 character can be added to that command or if the character requires
2156 a new `exactn' command. */
2157 unsigned char *pending_exact = 0;
2159 /* Address of start of the most recently finished expression.
2160 This tells, e.g., postfix * where to find the start of its
2161 operand. Reset at the beginning of groups and alternatives. */
2162 unsigned char *laststart = 0;
2164 /* Address of beginning of regexp, or inside of last group. */
2165 unsigned char *begalt;
2167 /* Place in the uncompiled pattern (i.e., the {) to
2168 which to go back if the interval is invalid. */
2169 re_char *beg_interval;
2171 /* Address of the place where a forward jump should go to the end of
2172 the containing expression. Each alternative of an `or' -- except the
2173 last -- ends with a forward jump of this sort. */
2174 unsigned char *fixup_alt_jump = 0;
2176 /* Counts open-groups as they are encountered. Remembered for the
2177 matching close-group on the compile stack, so the same register
2178 number is put in the stop_memory as the start_memory. */
2179 regnum_t regnum = 0;
2181 /* Work area for range table of charset. */
2182 struct range_table_work_area range_table_work;
2184 /* If the object matched can contain multibyte characters. */
2185 const boolean multibyte = RE_MULTIBYTE_P (bufp);
2189 DEBUG_PRINT1 ("\nCompiling pattern: ");
2192 unsigned debug_count;
2194 for (debug_count = 0; debug_count < size; debug_count++)
2195 putchar (pattern[debug_count]);
2200 /* Initialize the compile stack. */
2201 compile_stack.stack = TALLOC (INIT_COMPILE_STACK_SIZE, compile_stack_elt_t);
2202 if (compile_stack.stack == NULL)
2205 compile_stack.size = INIT_COMPILE_STACK_SIZE;
2206 compile_stack.avail = 0;
2208 range_table_work.table = 0;
2209 range_table_work.allocated = 0;
2211 /* Initialize the pattern buffer. */
2212 bufp->syntax = syntax;
2213 bufp->fastmap_accurate = 0;
2214 bufp->not_bol = bufp->not_eol = 0;
2216 /* Set `used' to zero, so that if we return an error, the pattern
2217 printer (for debugging) will think there's no pattern. We reset it
2221 /* Always count groups, whether or not bufp->no_sub is set. */
2224 #if !defined emacs && !defined SYNTAX_TABLE
2225 /* Initialize the syntax table. */
2226 init_syntax_once ();
2229 if (bufp->allocated == 0)
2232 { /* If zero allocated, but buffer is non-null, try to realloc
2233 enough space. This loses if buffer's address is bogus, but
2234 that is the user's responsibility. */
2235 RETALLOC (bufp->buffer, INIT_BUF_SIZE, unsigned char);
2238 { /* Caller did not allocate a buffer. Do it for them. */
2239 bufp->buffer = TALLOC (INIT_BUF_SIZE, unsigned char);
2241 if (!bufp->buffer) FREE_STACK_RETURN (REG_ESPACE);
2243 bufp->allocated = INIT_BUF_SIZE;
2246 begalt = b = bufp->buffer;
2248 /* Loop through the uncompiled pattern until we're at the end. */
2257 if ( /* If at start of pattern, it's an operator. */
2259 /* If context independent, it's an operator. */
2260 || syntax & RE_CONTEXT_INDEP_ANCHORS
2261 /* Otherwise, depends on what's come before. */
2262 || at_begline_loc_p (pattern, p, syntax))
2263 BUF_PUSH ((syntax & RE_NO_NEWLINE_ANCHOR) ? begbuf : begline);
2272 if ( /* If at end of pattern, it's an operator. */
2274 /* If context independent, it's an operator. */
2275 || syntax & RE_CONTEXT_INDEP_ANCHORS
2276 /* Otherwise, depends on what's next. */
2277 || at_endline_loc_p (p, pend, syntax))
2278 BUF_PUSH ((syntax & RE_NO_NEWLINE_ANCHOR) ? endbuf : endline);
2287 if ((syntax & RE_BK_PLUS_QM)
2288 || (syntax & RE_LIMITED_OPS))
2292 /* If there is no previous pattern... */
2295 if (syntax & RE_CONTEXT_INVALID_OPS)
2296 FREE_STACK_RETURN (REG_BADRPT);
2297 else if (!(syntax & RE_CONTEXT_INDEP_OPS))
2302 /* 1 means zero (many) matches is allowed. */
2303 boolean zero_times_ok = 0, many_times_ok = 0;
2306 /* If there is a sequence of repetition chars, collapse it
2307 down to just one (the right one). We can't combine
2308 interval operators with these because of, e.g., `a{2}*',
2309 which should only match an even number of `a's. */
2313 if ((syntax & RE_FRUGAL)
2314 && c == '?' && (zero_times_ok || many_times_ok))
2318 zero_times_ok |= c != '+';
2319 many_times_ok |= c != '?';
2325 || (!(syntax & RE_BK_PLUS_QM)
2326 && (*p == '+' || *p == '?')))
2328 else if (syntax & RE_BK_PLUS_QM && *p == '\\')
2331 FREE_STACK_RETURN (REG_EESCAPE);
2332 if (p[1] == '+' || p[1] == '?')
2333 PATFETCH (c); /* Gobble up the backslash. */
2339 /* If we get here, we found another repeat character. */
2343 /* Star, etc. applied to an empty pattern is equivalent
2344 to an empty pattern. */
2345 if (!laststart || laststart == b)
2348 /* Now we know whether or not zero matches is allowed
2349 and also whether or not two or more matches is allowed. */
2354 boolean simple = skip_one_char (laststart) == b;
2355 unsigned int startoffset = 0;
2357 (simple || !analyse_first (laststart, b, NULL, 0)) ?
2358 on_failure_jump : on_failure_jump_loop;
2359 assert (skip_one_char (laststart) <= b);
2361 if (!zero_times_ok && simple)
2362 { /* Since simple * loops can be made faster by using
2363 on_failure_keep_string_jump, we turn simple P+
2364 into PP* if P is simple. */
2365 unsigned char *p1, *p2;
2366 startoffset = b - laststart;
2367 GET_BUFFER_SPACE (startoffset);
2368 p1 = b; p2 = laststart;
2374 GET_BUFFER_SPACE (6);
2377 STORE_JUMP (ofj, b, b + 6);
2379 /* Simple * loops can use on_failure_keep_string_jump
2380 depending on what follows. But since we don't know
2381 that yet, we leave the decision up to
2382 on_failure_jump_smart. */
2383 INSERT_JUMP (simple ? on_failure_jump_smart : ofj,
2384 laststart + startoffset, b + 6);
2386 STORE_JUMP (jump, b, laststart + startoffset);
2391 /* A simple ? pattern. */
2392 assert (zero_times_ok);
2393 GET_BUFFER_SPACE (3);
2394 INSERT_JUMP (on_failure_jump, laststart, b + 3);
2398 else /* not greedy */
2399 { /* I wish the greedy and non-greedy cases could be merged. */
2401 GET_BUFFER_SPACE (7); /* We might use less. */
2404 boolean emptyp = analyse_first (laststart, b, NULL, 0);
2406 /* The non-greedy multiple match looks like a repeat..until:
2407 we only need a conditional jump at the end of the loop */
2408 if (emptyp) BUF_PUSH (no_op);
2409 STORE_JUMP (emptyp ? on_failure_jump_nastyloop
2410 : on_failure_jump, b, laststart);
2414 /* The repeat...until naturally matches one or more.
2415 To also match zero times, we need to first jump to
2416 the end of the loop (its conditional jump). */
2417 INSERT_JUMP (jump, laststart, b);
2423 /* non-greedy a?? */
2424 INSERT_JUMP (jump, laststart, b + 3);
2426 INSERT_JUMP (on_failure_jump, laststart, laststart + 6);
2443 CLEAR_RANGE_TABLE_WORK_USED (range_table_work);
2445 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2447 /* Ensure that we have enough space to push a charset: the
2448 opcode, the length count, and the bitset; 34 bytes in all. */
2449 GET_BUFFER_SPACE (34);
2453 /* We test `*p == '^' twice, instead of using an if
2454 statement, so we only need one BUF_PUSH. */
2455 BUF_PUSH (*p == '^' ? charset_not : charset);
2459 /* Remember the first position in the bracket expression. */
2462 /* Push the number of bytes in the bitmap. */
2463 BUF_PUSH ((1 << BYTEWIDTH) / BYTEWIDTH);
2465 /* Clear the whole map. */
2466 bzero (b, (1 << BYTEWIDTH) / BYTEWIDTH);
2468 /* charset_not matches newline according to a syntax bit. */
2469 if ((re_opcode_t) b[-2] == charset_not
2470 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
2471 SET_LIST_BIT ('\n');
2473 /* Read in characters and ranges, setting map bits. */
2476 boolean escaped_char = false;
2477 const unsigned char *p2 = p;
2479 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2483 /* \ might escape characters inside [...] and [^...]. */
2484 if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
2486 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2489 escaped_char = true;
2493 /* Could be the end of the bracket expression. If it's
2494 not (i.e., when the bracket expression is `[]' so
2495 far), the ']' character bit gets set way below. */
2496 if (c == ']' && p2 != p1)
2500 /* What should we do for the character which is
2501 greater than 0x7F, but not BASE_LEADING_CODE_P?
2504 /* See if we're at the beginning of a possible character
2507 if (!escaped_char &&
2508 syntax & RE_CHAR_CLASSES && c == '[' && *p == ':')
2510 /* Leave room for the null. */
2511 unsigned char str[CHAR_CLASS_MAX_LENGTH + 1];
2512 const unsigned char *class_beg;
2518 /* If pattern is `[[:'. */
2519 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2524 if ((c == ':' && *p == ']') || p == pend)
2526 if (c1 < CHAR_CLASS_MAX_LENGTH)
2529 /* This is in any case an invalid class name. */
2534 /* If isn't a word bracketed by `[:' and `:]':
2535 undo the ending character, the letters, and
2536 leave the leading `:' and `[' (but set bits for
2538 if (c == ':' && *p == ']')
2543 cc = re_wctype (str);
2546 FREE_STACK_RETURN (REG_ECTYPE);
2548 /* Throw away the ] at the end of the character
2552 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2554 /* Most character classes in a multibyte match
2555 just set a flag. Exceptions are is_blank,
2556 is_digit, is_cntrl, and is_xdigit, since
2557 they can only match ASCII characters. We
2558 don't need to handle them for multibyte.
2559 They are distinguished by a negative wctype. */
2562 SET_RANGE_TABLE_WORK_AREA_BIT (range_table_work,
2563 re_wctype_to_bit (cc));
2565 for (ch = 0; ch < 1 << BYTEWIDTH; ++ch)
2567 int translated = TRANSLATE (ch);
2568 if (re_iswctype (btowc (ch), cc))
2569 SET_LIST_BIT (translated);
2572 /* Repeat the loop. */
2577 /* Go back to right after the "[:". */
2581 /* Because the `:' may starts the range, we
2582 can't simply set bit and repeat the loop.
2583 Instead, just set it to C and handle below. */
2588 if (p < pend && p[0] == '-' && p[1] != ']')
2591 /* Discard the `-'. */
2594 /* Fetch the character which ends the range. */
2597 if (SINGLE_BYTE_CHAR_P (c))
2599 if (! SINGLE_BYTE_CHAR_P (c1))
2601 /* Handle a range such as \177-\377 in
2602 multibyte mode. Split that into two
2603 ranges, the low one ending at 0237, and
2604 the high one starting at the smallest
2605 character in the charset of C1 and
2607 int charset = CHAR_CHARSET (c1);
2608 int c2 = MAKE_CHAR (charset, 0, 0);
2610 SET_RANGE_TABLE_WORK_AREA (range_table_work,
2615 else if (!SAME_CHARSET_P (c, c1))
2616 FREE_STACK_RETURN (REG_ERANGE);
2619 /* Range from C to C. */
2622 /* Set the range ... */
2623 if (SINGLE_BYTE_CHAR_P (c))
2624 /* ... into bitmap. */
2627 int range_start = c, range_end = c1;
2629 /* If the start is after the end, the range is empty. */
2630 if (range_start > range_end)
2632 if (syntax & RE_NO_EMPTY_RANGES)
2633 FREE_STACK_RETURN (REG_ERANGE);
2634 /* Else, repeat the loop. */
2638 for (this_char = range_start; this_char <= range_end;
2640 SET_LIST_BIT (TRANSLATE (this_char));
2644 /* ... into range table. */
2645 SET_RANGE_TABLE_WORK_AREA (range_table_work, c, c1);
2648 /* Discard any (non)matching list bytes that are all 0 at the
2649 end of the map. Decrease the map-length byte too. */
2650 while ((int) b[-1] > 0 && b[b[-1] - 1] == 0)
2654 /* Build real range table from work area. */
2655 if (RANGE_TABLE_WORK_USED (range_table_work)
2656 || RANGE_TABLE_WORK_BITS (range_table_work))
2659 int used = RANGE_TABLE_WORK_USED (range_table_work);
2661 /* Allocate space for COUNT + RANGE_TABLE. Needs two
2662 bytes for flags, two for COUNT, and three bytes for
2664 GET_BUFFER_SPACE (4 + used * 3);
2666 /* Indicate the existence of range table. */
2667 laststart[1] |= 0x80;
2669 /* Store the character class flag bits into the range table.
2670 If not in emacs, these flag bits are always 0. */
2671 *b++ = RANGE_TABLE_WORK_BITS (range_table_work) & 0xff;
2672 *b++ = RANGE_TABLE_WORK_BITS (range_table_work) >> 8;
2674 STORE_NUMBER_AND_INCR (b, used / 2);
2675 for (i = 0; i < used; i++)
2676 STORE_CHARACTER_AND_INCR
2677 (b, RANGE_TABLE_WORK_ELT (range_table_work, i));
2684 if (syntax & RE_NO_BK_PARENS)
2691 if (syntax & RE_NO_BK_PARENS)
2698 if (syntax & RE_NEWLINE_ALT)
2705 if (syntax & RE_NO_BK_VBAR)
2712 if (syntax & RE_INTERVALS && syntax & RE_NO_BK_BRACES)
2713 goto handle_interval;
2719 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2721 /* Do not translate the character after the \, so that we can
2722 distinguish, e.g., \B from \b, even if we normally would
2723 translate, e.g., B to b. */
2729 if (syntax & RE_NO_BK_PARENS)
2730 goto normal_backslash;
2737 /* Look for a special (?...) construct */
2738 if ((syntax & RE_SHY_GROUPS) && *p == '?')
2740 PATFETCH (c); /* Gobble up the '?'. */
2744 case ':': shy = 1; break;
2746 /* Only (?:...) is supported right now. */
2747 FREE_STACK_RETURN (REG_BADPAT);
2758 if (COMPILE_STACK_FULL)
2760 RETALLOC (compile_stack.stack, compile_stack.size << 1,
2761 compile_stack_elt_t);
2762 if (compile_stack.stack == NULL) return REG_ESPACE;
2764 compile_stack.size <<= 1;
2767 /* These are the values to restore when we hit end of this
2768 group. They are all relative offsets, so that if the
2769 whole pattern moves because of realloc, they will still
2771 COMPILE_STACK_TOP.begalt_offset = begalt - bufp->buffer;
2772 COMPILE_STACK_TOP.fixup_alt_jump
2773 = fixup_alt_jump ? fixup_alt_jump - bufp->buffer + 1 : 0;
2774 COMPILE_STACK_TOP.laststart_offset = b - bufp->buffer;
2775 COMPILE_STACK_TOP.regnum = shy ? -regnum : regnum;
2778 start_memory for groups beyond the last one we can
2779 represent in the compiled pattern. */
2780 if (regnum <= MAX_REGNUM && !shy)
2781 BUF_PUSH_2 (start_memory, regnum);
2783 compile_stack.avail++;
2788 /* If we've reached MAX_REGNUM groups, then this open
2789 won't actually generate any code, so we'll have to
2790 clear pending_exact explicitly. */
2796 if (syntax & RE_NO_BK_PARENS) goto normal_backslash;
2798 if (COMPILE_STACK_EMPTY)
2800 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
2801 goto normal_backslash;
2803 FREE_STACK_RETURN (REG_ERPAREN);
2809 /* See similar code for backslashed left paren above. */
2810 if (COMPILE_STACK_EMPTY)
2812 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
2815 FREE_STACK_RETURN (REG_ERPAREN);
2818 /* Since we just checked for an empty stack above, this
2819 ``can't happen''. */
2820 assert (compile_stack.avail != 0);
2822 /* We don't just want to restore into `regnum', because
2823 later groups should continue to be numbered higher,
2824 as in `(ab)c(de)' -- the second group is #2. */
2825 regnum_t this_group_regnum;
2827 compile_stack.avail--;
2828 begalt = bufp->buffer + COMPILE_STACK_TOP.begalt_offset;
2830 = COMPILE_STACK_TOP.fixup_alt_jump
2831 ? bufp->buffer + COMPILE_STACK_TOP.fixup_alt_jump - 1
2833 laststart = bufp->buffer + COMPILE_STACK_TOP.laststart_offset;
2834 this_group_regnum = COMPILE_STACK_TOP.regnum;
2835 /* If we've reached MAX_REGNUM groups, then this open
2836 won't actually generate any code, so we'll have to
2837 clear pending_exact explicitly. */
2840 /* We're at the end of the group, so now we know how many
2841 groups were inside this one. */
2842 if (this_group_regnum <= MAX_REGNUM && this_group_regnum > 0)
2843 BUF_PUSH_2 (stop_memory, this_group_regnum);
2848 case '|': /* `\|'. */
2849 if (syntax & RE_LIMITED_OPS || syntax & RE_NO_BK_VBAR)
2850 goto normal_backslash;
2852 if (syntax & RE_LIMITED_OPS)
2855 /* Insert before the previous alternative a jump which
2856 jumps to this alternative if the former fails. */
2857 GET_BUFFER_SPACE (3);
2858 INSERT_JUMP (on_failure_jump, begalt, b + 6);
2862 /* The alternative before this one has a jump after it
2863 which gets executed if it gets matched. Adjust that
2864 jump so it will jump to this alternative's analogous
2865 jump (put in below, which in turn will jump to the next
2866 (if any) alternative's such jump, etc.). The last such
2867 jump jumps to the correct final destination. A picture:
2873 If we are at `b', then fixup_alt_jump right now points to a
2874 three-byte space after `a'. We'll put in the jump, set
2875 fixup_alt_jump to right after `b', and leave behind three
2876 bytes which we'll fill in when we get to after `c'. */
2880 /* Mark and leave space for a jump after this alternative,
2881 to be filled in later either by next alternative or
2882 when know we're at the end of a series of alternatives. */
2884 GET_BUFFER_SPACE (3);
2893 /* If \{ is a literal. */
2894 if (!(syntax & RE_INTERVALS)
2895 /* If we're at `\{' and it's not the open-interval
2897 || (syntax & RE_NO_BK_BRACES))
2898 goto normal_backslash;
2902 /* If got here, then the syntax allows intervals. */
2904 /* At least (most) this many matches must be made. */
2905 int lower_bound = 0, upper_bound = -1;
2910 FREE_STACK_RETURN (REG_EBRACE);
2912 GET_UNSIGNED_NUMBER (lower_bound);
2915 GET_UNSIGNED_NUMBER (upper_bound);
2917 /* Interval such as `{1}' => match exactly once. */
2918 upper_bound = lower_bound;
2920 if (lower_bound < 0 || upper_bound > RE_DUP_MAX
2921 || (upper_bound >= 0 && lower_bound > upper_bound))
2922 FREE_STACK_RETURN (REG_BADBR);
2924 if (!(syntax & RE_NO_BK_BRACES))
2927 FREE_STACK_RETURN (REG_BADBR);
2933 FREE_STACK_RETURN (REG_BADBR);
2935 /* We just parsed a valid interval. */
2937 /* If it's invalid to have no preceding re. */
2940 if (syntax & RE_CONTEXT_INVALID_OPS)
2941 FREE_STACK_RETURN (REG_BADRPT);
2942 else if (syntax & RE_CONTEXT_INDEP_OPS)
2945 goto unfetch_interval;
2948 if (upper_bound == 0)
2949 /* If the upper bound is zero, just drop the sub pattern
2952 else if (lower_bound == 1 && upper_bound == 1)
2953 /* Just match it once: nothing to do here. */
2956 /* Otherwise, we have a nontrivial interval. When
2957 we're all done, the pattern will look like:
2958 set_number_at <jump count> <upper bound>
2959 set_number_at <succeed_n count> <lower bound>
2960 succeed_n <after jump addr> <succeed_n count>
2962 jump_n <succeed_n addr> <jump count>
2963 (The upper bound and `jump_n' are omitted if
2964 `upper_bound' is 1, though.) */
2966 { /* If the upper bound is > 1, we need to insert
2967 more at the end of the loop. */
2968 unsigned int nbytes = (upper_bound < 0 ? 3
2969 : upper_bound > 1 ? 5 : 0);
2970 unsigned int startoffset = 0;
2972 GET_BUFFER_SPACE (20); /* We might use less. */
2974 if (lower_bound == 0)
2976 /* A succeed_n that starts with 0 is really a
2977 a simple on_failure_jump_loop. */
2978 INSERT_JUMP (on_failure_jump_loop, laststart,
2984 /* Initialize lower bound of the `succeed_n', even
2985 though it will be set during matching by its
2986 attendant `set_number_at' (inserted next),
2987 because `re_compile_fastmap' needs to know.
2988 Jump to the `jump_n' we might insert below. */
2989 INSERT_JUMP2 (succeed_n, laststart,
2994 /* Code to initialize the lower bound. Insert
2995 before the `succeed_n'. The `5' is the last two
2996 bytes of this `set_number_at', plus 3 bytes of
2997 the following `succeed_n'. */
2998 insert_op2 (set_number_at, laststart, 5, lower_bound, b);
3003 if (upper_bound < 0)
3005 /* A negative upper bound stands for infinity,
3006 in which case it degenerates to a plain jump. */
3007 STORE_JUMP (jump, b, laststart + startoffset);
3010 else if (upper_bound > 1)
3011 { /* More than one repetition is allowed, so
3012 append a backward jump to the `succeed_n'
3013 that starts this interval.
3015 When we've reached this during matching,
3016 we'll have matched the interval once, so
3017 jump back only `upper_bound - 1' times. */
3018 STORE_JUMP2 (jump_n, b, laststart + startoffset,
3022 /* The location we want to set is the second
3023 parameter of the `jump_n'; that is `b-2' as
3024 an absolute address. `laststart' will be
3025 the `set_number_at' we're about to insert;
3026 `laststart+3' the number to set, the source
3027 for the relative address. But we are
3028 inserting into the middle of the pattern --
3029 so everything is getting moved up by 5.
3030 Conclusion: (b - 2) - (laststart + 3) + 5,
3031 i.e., b - laststart.
3033 We insert this at the beginning of the loop
3034 so that if we fail during matching, we'll
3035 reinitialize the bounds. */
3036 insert_op2 (set_number_at, laststart, b - laststart,
3037 upper_bound - 1, b);
3042 beg_interval = NULL;
3047 /* If an invalid interval, match the characters as literals. */
3048 assert (beg_interval);
3050 beg_interval = NULL;
3052 /* normal_char and normal_backslash need `c'. */
3055 if (!(syntax & RE_NO_BK_BRACES))
3057 assert (p > pattern && p[-1] == '\\');
3058 goto normal_backslash;
3064 /* There is no way to specify the before_dot and after_dot
3065 operators. rms says this is ok. --karl */
3073 BUF_PUSH_2 (syntaxspec, syntax_spec_code[c]);
3079 BUF_PUSH_2 (notsyntaxspec, syntax_spec_code[c]);
3085 BUF_PUSH_2 (categoryspec, c);
3091 BUF_PUSH_2 (notcategoryspec, c);
3097 if (syntax & RE_NO_GNU_OPS)
3100 BUF_PUSH_2 (syntaxspec, Sword);
3105 if (syntax & RE_NO_GNU_OPS)
3108 BUF_PUSH_2 (notsyntaxspec, Sword);
3113 if (syntax & RE_NO_GNU_OPS)
3119 if (syntax & RE_NO_GNU_OPS)
3125 if (syntax & RE_NO_GNU_OPS)
3127 BUF_PUSH (wordbound);
3131 if (syntax & RE_NO_GNU_OPS)
3133 BUF_PUSH (notwordbound);
3137 if (syntax & RE_NO_GNU_OPS)
3143 if (syntax & RE_NO_GNU_OPS)
3148 case '1': case '2': case '3': case '4': case '5':
3149 case '6': case '7': case '8': case '9':
3150 if (syntax & RE_NO_BK_REFS)
3156 FREE_STACK_RETURN (REG_ESUBREG);
3158 /* Can't back reference to a subexpression if inside of it. */
3159 if (group_in_compile_stack (compile_stack, (regnum_t) c1))
3163 BUF_PUSH_2 (duplicate, c1);
3169 if (syntax & RE_BK_PLUS_QM)
3172 goto normal_backslash;
3176 /* You might think it would be useful for \ to mean
3177 not to translate; but if we don't translate it
3178 it will never match anything. */
3186 /* Expects the character in `c'. */
3188 /* If no exactn currently being built. */
3191 /* If last exactn not at current position. */
3192 || pending_exact + *pending_exact + 1 != b
3194 /* We have only one byte following the exactn for the count. */
3195 || *pending_exact >= (1 << BYTEWIDTH) - MAX_MULTIBYTE_LENGTH
3197 /* If followed by a repetition operator. */
3198 || (p != pend && (*p == '*' || *p == '^'))
3199 || ((syntax & RE_BK_PLUS_QM)
3200 ? p + 1 < pend && *p == '\\' && (p[1] == '+' || p[1] == '?')
3201 : p != pend && (*p == '+' || *p == '?'))
3202 || ((syntax & RE_INTERVALS)
3203 && ((syntax & RE_NO_BK_BRACES)
3204 ? p != pend && *p == '{'
3205 : p + 1 < pend && p[0] == '\\' && p[1] == '{')))
3207 /* Start building a new exactn. */
3211 BUF_PUSH_2 (exactn, 0);
3212 pending_exact = b - 1;
3215 GET_BUFFER_SPACE (MAX_MULTIBYTE_LENGTH);
3220 len = CHAR_STRING (c, b);
3224 (*pending_exact) += len;
3229 } /* while p != pend */
3232 /* Through the pattern now. */
3236 if (!COMPILE_STACK_EMPTY)
3237 FREE_STACK_RETURN (REG_EPAREN);
3239 /* If we don't want backtracking, force success
3240 the first time we reach the end of the compiled pattern. */
3241 if (syntax & RE_NO_POSIX_BACKTRACKING)
3244 free (compile_stack.stack);
3246 /* We have succeeded; set the length of the buffer. */
3247 bufp->used = b - bufp->buffer;
3252 re_compile_fastmap (bufp);
3253 DEBUG_PRINT1 ("\nCompiled pattern: \n");
3254 print_compiled_pattern (bufp);
3259 #ifndef MATCH_MAY_ALLOCATE
3260 /* Initialize the failure stack to the largest possible stack. This
3261 isn't necessary unless we're trying to avoid calling alloca in
3262 the search and match routines. */
3264 int num_regs = bufp->re_nsub + 1;
3266 if (fail_stack.size < re_max_failures * TYPICAL_FAILURE_SIZE)
3268 fail_stack.size = re_max_failures * TYPICAL_FAILURE_SIZE;
3270 if (! fail_stack.stack)
3272 = (fail_stack_elt_t *) malloc (fail_stack.size
3273 * sizeof (fail_stack_elt_t));
3276 = (fail_stack_elt_t *) realloc (fail_stack.stack,
3278 * sizeof (fail_stack_elt_t)));
3281 regex_grow_registers (num_regs);
3283 #endif /* not MATCH_MAY_ALLOCATE */
3286 } /* regex_compile */
3288 /* Subroutines for `regex_compile'. */
3290 /* Store OP at LOC followed by two-byte integer parameter ARG. */
3293 store_op1 (op, loc, arg)
3298 *loc = (unsigned char) op;
3299 STORE_NUMBER (loc + 1, arg);
3303 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
3306 store_op2 (op, loc, arg1, arg2)
3311 *loc = (unsigned char) op;
3312 STORE_NUMBER (loc + 1, arg1);
3313 STORE_NUMBER (loc + 3, arg2);
3317 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
3318 for OP followed by two-byte integer parameter ARG. */
3321 insert_op1 (op, loc, arg, end)
3327 register unsigned char *pfrom = end;
3328 register unsigned char *pto = end + 3;
3330 while (pfrom != loc)
3333 store_op1 (op, loc, arg);
3337 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
3340 insert_op2 (op, loc, arg1, arg2, end)
3346 register unsigned char *pfrom = end;
3347 register unsigned char *pto = end + 5;
3349 while (pfrom != loc)
3352 store_op2 (op, loc, arg1, arg2);
3356 /* P points to just after a ^ in PATTERN. Return true if that ^ comes
3357 after an alternative or a begin-subexpression. We assume there is at
3358 least one character before the ^. */
3361 at_begline_loc_p (pattern, p, syntax)
3362 const unsigned char *pattern, *p;
3363 reg_syntax_t syntax;
3365 const unsigned char *prev = p - 2;
3366 boolean prev_prev_backslash = prev > pattern && prev[-1] == '\\';
3369 /* After a subexpression? */
3370 (*prev == '(' && (syntax & RE_NO_BK_PARENS || prev_prev_backslash))
3371 /* After an alternative? */
3372 || (*prev == '|' && (syntax & RE_NO_BK_VBAR || prev_prev_backslash))
3373 /* After a shy subexpression? */
3374 || ((syntax & RE_SHY_GROUPS) && prev - 2 >= pattern
3375 && prev[-1] == '?' && prev[-2] == '('
3376 && (syntax & RE_NO_BK_PARENS
3377 || (prev - 3 >= pattern && prev[-3] == '\\')));
3381 /* The dual of at_begline_loc_p. This one is for $. We assume there is
3382 at least one character after the $, i.e., `P < PEND'. */
3385 at_endline_loc_p (p, pend, syntax)
3386 const unsigned char *p, *pend;
3387 reg_syntax_t syntax;
3389 const unsigned char *next = p;
3390 boolean next_backslash = *next == '\\';
3391 const unsigned char *next_next = p + 1 < pend ? p + 1 : 0;
3394 /* Before a subexpression? */
3395 (syntax & RE_NO_BK_PARENS ? *next == ')'
3396 : next_backslash && next_next && *next_next == ')')
3397 /* Before an alternative? */
3398 || (syntax & RE_NO_BK_VBAR ? *next == '|'
3399 : next_backslash && next_next && *next_next == '|');
3403 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
3404 false if it's not. */
3407 group_in_compile_stack (compile_stack, regnum)
3408 compile_stack_type compile_stack;
3413 for (this_element = compile_stack.avail - 1;
3416 if (compile_stack.stack[this_element].regnum == regnum)
3423 If fastmap is non-NULL, go through the pattern and fill fastmap
3424 with all the possible leading chars. If fastmap is NULL, don't
3425 bother filling it up (obviously) and only return whether the
3426 pattern could potentially match the empty string.
3428 Return 1 if p..pend might match the empty string.
3429 Return 0 if p..pend matches at least one char.
3430 Return -1 if p..pend matches at least one char, but fastmap was not
3432 Return -2 if an error occurred. */
3435 analyse_first (p, pend, fastmap, multibyte)
3436 unsigned char *p, *pend;
3438 const int multibyte;
3442 #ifdef MATCH_MAY_ALLOCATE
3443 fail_stack_type fail_stack;
3445 #ifndef REGEX_MALLOC
3449 #if defined REL_ALLOC && defined REGEX_MALLOC
3450 /* This holds the pointer to the failure stack, when
3451 it is allocated relocatably. */
3452 fail_stack_elt_t *failure_stack_ptr;
3455 /* Assume that each path through the pattern can be null until
3456 proven otherwise. We set this false at the bottom of switch
3457 statement, to which we get only if a particular path doesn't
3458 match the empty string. */
3459 boolean path_can_be_null = true;
3461 /* If all elements for base leading-codes in fastmap is set, this
3462 flag is set true. */
3463 boolean match_any_multibyte_characters = false;
3469 /* The loop below works as follows:
3470 - It has a working-list kept in the PATTERN_STACK and which basically
3471 starts by only containing a pointer to the first operation.
3472 - If the opcode we're looking at is a match against some set of
3473 chars, then we add those chars to the fastmap and go on to the
3474 next work element from the worklist (done via `break').
3475 - If the opcode is a control operator on the other hand, we either
3476 ignore it (if it's meaningless at this point, such as `start_memory')
3477 or execute it (if it's a jump). If the jump has several destinations
3478 (i.e. `on_failure_jump'), then we push the other destination onto the
3480 We guarantee termination by ignoring backward jumps (more or less),
3481 so that `p' is monotonically increasing. More to the point, we
3482 never set `p' (or push) anything `<= p1'. */
3486 /* `p1' is used as a marker of how far back a `on_failure_jump'
3487 can go without being ignored. It is normally equal to `p'
3488 (which prevents any backward `on_failure_jump') except right
3489 after a plain `jump', to allow patterns such as:
3492 10: on_failure_jump 3
3493 as used for the *? operator. */
3494 unsigned char *p1 = p;
3498 if (path_can_be_null)
3499 return (RESET_FAIL_STACK (), 1);
3501 /* We have reached the (effective) end of pattern. */
3502 if (PATTERN_STACK_EMPTY ())
3503 return (RESET_FAIL_STACK (), 0);
3505 p = (unsigned char*) POP_PATTERN_OP ();
3506 path_can_be_null = true;
3510 /* We should never be about to go beyond the end of the pattern. */
3513 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
3520 /* If the first character has to match a backreference, that means
3521 that the group was empty (since it already matched). Since this
3522 is the only case that interests us here, we can assume that the
3523 backreference must match the empty string. */
3528 /* Following are the cases which match a character. These end
3534 int c = RE_STRING_CHAR (p + 1, pend - p);
3536 if (SINGLE_BYTE_CHAR_P (c))
3545 /* We could put all the chars except for \n (and maybe \0)
3546 but we don't bother since it is generally not worth it. */
3547 if (!fastmap) break;
3548 return (RESET_FAIL_STACK (), -1);
3552 /* Chars beyond end of bitmap are possible matches.
3553 All the single-byte codes can occur in multibyte buffers.
3554 So any that are not listed in the charset
3555 are possible matches, even in multibyte buffers. */
3556 if (!fastmap) break;
3557 for (j = CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH;
3558 j < (1 << BYTEWIDTH); j++)
3562 if (!fastmap) break;
3563 not = (re_opcode_t) *(p - 1) == charset_not;
3564 for (j = CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH - 1, p++;
3566 if (!!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))) ^ not)
3569 if ((not && multibyte)
3570 /* Any character set can possibly contain a character
3571 which doesn't match the specified set of characters. */
3572 || (CHARSET_RANGE_TABLE_EXISTS_P (&p[-2])
3573 && CHARSET_RANGE_TABLE_BITS (&p[-2]) != 0))
3574 /* If we can match a character class, we can match
3575 any character set. */
3577 set_fastmap_for_multibyte_characters:
3578 if (match_any_multibyte_characters == false)
3580 for (j = 0x80; j < 0xA0; j++) /* XXX */
3581 if (BASE_LEADING_CODE_P (j))
3583 match_any_multibyte_characters = true;
3587 else if (!not && CHARSET_RANGE_TABLE_EXISTS_P (&p[-2])
3588 && match_any_multibyte_characters == false)
3590 /* Set fastmap[I] 1 where I is a base leading code of each
3591 multibyte character in the range table. */
3594 /* Make P points the range table. `+ 2' is to skip flag
3595 bits for a character class. */
3596 p += CHARSET_BITMAP_SIZE (&p[-2]) + 2;
3598 /* Extract the number of ranges in range table into COUNT. */
3599 EXTRACT_NUMBER_AND_INCR (count, p);
3600 for (; count > 0; count--, p += 2 * 3) /* XXX */
3602 /* Extract the start of each range. */
3603 EXTRACT_CHARACTER (c, p);
3604 j = CHAR_CHARSET (c);
3605 fastmap[CHARSET_LEADING_CODE_BASE (j)] = 1;
3612 if (!fastmap) break;
3614 not = (re_opcode_t)p[-1] == notsyntaxspec;
3616 for (j = 0; j < (1 << BYTEWIDTH); j++)
3617 if ((SYNTAX (j) == (enum syntaxcode) k) ^ not)
3621 /* This match depends on text properties. These end with
3622 aborting optimizations. */
3623 return (RESET_FAIL_STACK (), -1);
3626 case notcategoryspec:
3627 if (!fastmap) break;
3628 not = (re_opcode_t)p[-1] == notcategoryspec;
3630 for (j = 0; j < (1 << BYTEWIDTH); j++)
3631 if ((CHAR_HAS_CATEGORY (j, k)) ^ not)
3635 /* Any character set can possibly contain a character
3636 whose category is K (or not). */
3637 goto set_fastmap_for_multibyte_characters;
3640 /* All cases after this match the empty string. These end with
3660 EXTRACT_NUMBER_AND_INCR (j, p);
3662 /* Backward jumps can only go back to code that we've already
3663 visited. `re_compile' should make sure this is true. */
3666 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p))
3668 case on_failure_jump:
3669 case on_failure_keep_string_jump:
3670 case on_failure_jump_loop:
3671 case on_failure_jump_nastyloop:
3672 case on_failure_jump_smart:
3678 /* Keep `p1' to allow the `on_failure_jump' we are jumping to
3679 to jump back to "just after here". */
3682 case on_failure_jump:
3683 case on_failure_keep_string_jump:
3684 case on_failure_jump_nastyloop:
3685 case on_failure_jump_loop:
3686 case on_failure_jump_smart:
3687 EXTRACT_NUMBER_AND_INCR (j, p);
3689 ; /* Backward jump to be ignored. */
3690 else if (!PUSH_PATTERN_OP (p + j, fail_stack))
3691 return (RESET_FAIL_STACK (), -2);
3696 /* This code simply does not properly handle forward jump_n. */
3697 DEBUG_STATEMENT (EXTRACT_NUMBER (j, p); assert (j < 0));
3699 /* jump_n can either jump or fall through. The (backward) jump
3700 case has already been handled, so we only need to look at the
3701 fallthrough case. */
3705 /* If N == 0, it should be an on_failure_jump_loop instead. */
3706 DEBUG_STATEMENT (EXTRACT_NUMBER (j, p + 2); assert (j > 0));
3708 /* We only care about one iteration of the loop, so we don't
3709 need to consider the case where this behaves like an
3726 abort (); /* We have listed all the cases. */
3729 /* Getting here means we have found the possible starting
3730 characters for one path of the pattern -- and that the empty
3731 string does not match. We need not follow this path further.
3732 Instead, look at the next alternative (remembered on the
3733 stack), or quit if no more. The test at the top of the loop
3734 does these things. */
3735 path_can_be_null = false;
3739 return (RESET_FAIL_STACK (), 0);
3740 } /* analyse_first */
3742 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
3743 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
3744 characters can start a string that matches the pattern. This fastmap
3745 is used by re_search to skip quickly over impossible starting points.
3747 Character codes above (1 << BYTEWIDTH) are not represented in the
3748 fastmap, but the leading codes are represented. Thus, the fastmap
3749 indicates which character sets could start a match.
3751 The caller must supply the address of a (1 << BYTEWIDTH)-byte data
3752 area as BUFP->fastmap.
3754 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
3757 Returns 0 if we succeed, -2 if an internal error. */
3760 re_compile_fastmap (bufp)
3761 struct re_pattern_buffer *bufp;
3763 char *fastmap = bufp->fastmap;
3766 assert (fastmap && bufp->buffer);
3768 bzero (fastmap, 1 << BYTEWIDTH); /* Assume nothing's valid. */
3769 bufp->fastmap_accurate = 1; /* It will be when we're done. */
3771 analysis = analyse_first (bufp->buffer, bufp->buffer + bufp->used,
3772 fastmap, RE_MULTIBYTE_P (bufp));
3773 bufp->can_be_null = (analysis != 0);
3777 } /* re_compile_fastmap */
3779 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
3780 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
3781 this memory for recording register information. STARTS and ENDS
3782 must be allocated using the malloc library routine, and must each
3783 be at least NUM_REGS * sizeof (regoff_t) bytes long.
3785 If NUM_REGS == 0, then subsequent matches should allocate their own
3788 Unless this function is called, the first search or match using
3789 PATTERN_BUFFER will allocate its own register data, without
3790 freeing the old data. */
3793 re_set_registers (bufp, regs, num_regs, starts, ends)
3794 struct re_pattern_buffer *bufp;
3795 struct re_registers *regs;
3797 regoff_t *starts, *ends;
3801 bufp->regs_allocated = REGS_REALLOCATE;
3802 regs->num_regs = num_regs;
3803 regs->start = starts;
3808 bufp->regs_allocated = REGS_UNALLOCATED;
3810 regs->start = regs->end = (regoff_t *) 0;
3813 WEAK_ALIAS (__re_set_registers, re_set_registers)
3815 /* Searching routines. */
3817 /* Like re_search_2, below, but only one string is specified, and
3818 doesn't let you say where to stop matching. */
3821 re_search (bufp, string, size, startpos, range, regs)
3822 struct re_pattern_buffer *bufp;
3824 int size, startpos, range;
3825 struct re_registers *regs;
3827 return re_search_2 (bufp, NULL, 0, string, size, startpos, range,
3830 WEAK_ALIAS (__re_search, re_search)
3832 /* End address of virtual concatenation of string. */
3833 #define STOP_ADDR_VSTRING(P) \
3834 (((P) >= size1 ? string2 + size2 : string1 + size1))
3836 /* Address of POS in the concatenation of virtual string. */
3837 #define POS_ADDR_VSTRING(POS) \
3838 (((POS) >= size1 ? string2 - size1 : string1) + (POS))
3840 /* Using the compiled pattern in BUFP->buffer, first tries to match the
3841 virtual concatenation of STRING1 and STRING2, starting first at index
3842 STARTPOS, then at STARTPOS + 1, and so on.
3844 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
3846 RANGE is how far to scan while trying to match. RANGE = 0 means try
3847 only at STARTPOS; in general, the last start tried is STARTPOS +
3850 In REGS, return the indices of the virtual concatenation of STRING1
3851 and STRING2 that matched the entire BUFP->buffer and its contained
3854 Do not consider matching one past the index STOP in the virtual
3855 concatenation of STRING1 and STRING2.
3857 We return either the position in the strings at which the match was
3858 found, -1 if no match, or -2 if error (such as failure
3862 re_search_2 (bufp, str1, size1, str2, size2, startpos, range, regs, stop)
3863 struct re_pattern_buffer *bufp;
3864 const char *str1, *str2;
3868 struct re_registers *regs;
3872 re_char *string1 = (re_char*) str1;
3873 re_char *string2 = (re_char*) str2;
3874 register char *fastmap = bufp->fastmap;
3875 register RE_TRANSLATE_TYPE translate = bufp->translate;
3876 int total_size = size1 + size2;
3877 int endpos = startpos + range;
3878 boolean anchored_start;
3880 /* Nonzero if we have to concern multibyte character. */
3881 const boolean multibyte = RE_MULTIBYTE_P (bufp);
3883 /* Check for out-of-range STARTPOS. */
3884 if (startpos < 0 || startpos > total_size)
3887 /* Fix up RANGE if it might eventually take us outside
3888 the virtual concatenation of STRING1 and STRING2.
3889 Make sure we won't move STARTPOS below 0 or above TOTAL_SIZE. */
3891 range = 0 - startpos;
3892 else if (endpos > total_size)
3893 range = total_size - startpos;
3895 /* If the search isn't to be a backwards one, don't waste time in a
3896 search for a pattern anchored at beginning of buffer. */
3897 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == begbuf && range > 0)
3906 /* In a forward search for something that starts with \=.
3907 don't keep searching past point. */
3908 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == at_dot && range > 0)
3910 range = PT_BYTE - BEGV_BYTE - startpos;
3916 /* Update the fastmap now if not correct already. */
3917 if (fastmap && !bufp->fastmap_accurate)
3918 if (re_compile_fastmap (bufp) == -2)
3921 /* See whether the pattern is anchored. */
3922 anchored_start = (bufp->buffer[0] == begline);
3925 gl_state.object = re_match_object;
3927 int charpos = SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (startpos));
3929 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object, charpos, 1);
3933 /* Loop through the string, looking for a place to start matching. */
3936 /* If the pattern is anchored,
3937 skip quickly past places we cannot match.
3938 We don't bother to treat startpos == 0 specially
3939 because that case doesn't repeat. */
3940 if (anchored_start && startpos > 0)
3942 if (! ((startpos <= size1 ? string1[startpos - 1]
3943 : string2[startpos - size1 - 1])
3948 /* If a fastmap is supplied, skip quickly over characters that
3949 cannot be the start of a match. If the pattern can match the
3950 null string, however, we don't need to skip characters; we want
3951 the first null string. */
3952 if (fastmap && startpos < total_size && !bufp->can_be_null)
3954 register re_char *d;
3955 register unsigned int buf_ch;
3957 d = POS_ADDR_VSTRING (startpos);
3959 if (range > 0) /* Searching forwards. */
3961 register int lim = 0;
3964 if (startpos < size1 && startpos + range >= size1)
3965 lim = range - (size1 - startpos);
3967 /* Written out as an if-else to avoid testing `translate'
3969 if (RE_TRANSLATE_P (translate))
3976 buf_ch = STRING_CHAR_AND_LENGTH (d, range - lim,
3979 buf_ch = RE_TRANSLATE (translate, buf_ch);
3984 range -= buf_charlen;
3989 && !fastmap[RE_TRANSLATE (translate, *d)])
3996 while (range > lim && !fastmap[*d])
4002 startpos += irange - range;
4004 else /* Searching backwards. */
4006 int room = (startpos >= size1
4007 ? size2 + size1 - startpos
4008 : size1 - startpos);
4009 buf_ch = RE_STRING_CHAR (d, room);
4010 buf_ch = TRANSLATE (buf_ch);
4012 if (! (buf_ch >= 0400
4013 || fastmap[buf_ch]))
4018 /* If can't match the null string, and that's all we have left, fail. */
4019 if (range >= 0 && startpos == total_size && fastmap
4020 && !bufp->can_be_null)
4023 val = re_match_2_internal (bufp, string1, size1, string2, size2,
4024 startpos, regs, stop);
4025 #ifndef REGEX_MALLOC
4042 /* Update STARTPOS to the next character boundary. */
4045 re_char *p = POS_ADDR_VSTRING (startpos);
4046 re_char *pend = STOP_ADDR_VSTRING (startpos);
4047 int len = MULTIBYTE_FORM_LENGTH (p, pend - p);
4065 /* Update STARTPOS to the previous character boundary. */
4068 re_char *p = POS_ADDR_VSTRING (startpos);
4071 /* Find the head of multibyte form. */
4072 while (!CHAR_HEAD_P (*p))
4077 if (MULTIBYTE_FORM_LENGTH (p, len + 1) != (len + 1))
4093 WEAK_ALIAS (__re_search_2, re_search_2)
4095 /* Declarations and macros for re_match_2. */
4097 static int bcmp_translate _RE_ARGS((re_char *s1, re_char *s2,
4099 RE_TRANSLATE_TYPE translate,
4100 const int multibyte));
4102 /* This converts PTR, a pointer into one of the search strings `string1'
4103 and `string2' into an offset from the beginning of that string. */
4104 #define POINTER_TO_OFFSET(ptr) \
4105 (FIRST_STRING_P (ptr) \
4106 ? ((regoff_t) ((ptr) - string1)) \
4107 : ((regoff_t) ((ptr) - string2 + size1)))
4109 /* Call before fetching a character with *d. This switches over to
4110 string2 if necessary.
4111 Check re_match_2_internal for a discussion of why end_match_2 might
4112 not be within string2 (but be equal to end_match_1 instead). */
4113 #define PREFETCH() \
4116 /* End of string2 => fail. */ \
4117 if (dend == end_match_2) \
4119 /* End of string1 => advance to string2. */ \
4121 dend = end_match_2; \
4124 /* Call before fetching a char with *d if you already checked other limits.
4125 This is meant for use in lookahead operations like wordend, etc..
4126 where we might need to look at parts of the string that might be
4127 outside of the LIMITs (i.e past `stop'). */
4128 #define PREFETCH_NOLIMIT() \
4132 dend = end_match_2; \
4135 /* Test if at very beginning or at very end of the virtual concatenation
4136 of `string1' and `string2'. If only one string, it's `string2'. */
4137 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
4138 #define AT_STRINGS_END(d) ((d) == end2)
4141 /* Test if D points to a character which is word-constituent. We have
4142 two special cases to check for: if past the end of string1, look at
4143 the first character in string2; and if before the beginning of
4144 string2, look at the last character in string1. */
4145 #define WORDCHAR_P(d) \
4146 (SYNTAX ((d) == end1 ? *string2 \
4147 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
4150 /* Disabled due to a compiler bug -- see comment at case wordbound */
4152 /* The comment at case wordbound is following one, but we don't use
4153 AT_WORD_BOUNDARY anymore to support multibyte form.
4155 The DEC Alpha C compiler 3.x generates incorrect code for the
4156 test WORDCHAR_P (d - 1) != WORDCHAR_P (d) in the expansion of
4157 AT_WORD_BOUNDARY, so this code is disabled. Expanding the
4158 macro and introducing temporary variables works around the bug. */
4161 /* Test if the character before D and the one at D differ with respect
4162 to being word-constituent. */
4163 #define AT_WORD_BOUNDARY(d) \
4164 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
4165 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
4168 /* Free everything we malloc. */
4169 #ifdef MATCH_MAY_ALLOCATE
4170 # define FREE_VAR(var) if (var) { REGEX_FREE (var); var = NULL; } else
4171 # define FREE_VARIABLES() \
4173 REGEX_FREE_STACK (fail_stack.stack); \
4174 FREE_VAR (regstart); \
4175 FREE_VAR (regend); \
4176 FREE_VAR (best_regstart); \
4177 FREE_VAR (best_regend); \
4180 # define FREE_VARIABLES() ((void)0) /* Do nothing! But inhibit gcc warning. */
4181 #endif /* not MATCH_MAY_ALLOCATE */
4184 /* Optimization routines. */
4186 /* If the operation is a match against one or more chars,
4187 return a pointer to the next operation, else return NULL. */
4188 static unsigned char *
4192 switch (SWITCH_ENUM_CAST (*p++))
4203 if (CHARSET_RANGE_TABLE_EXISTS_P (p - 1))
4206 p = CHARSET_RANGE_TABLE (p - 1);
4207 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4208 p = CHARSET_RANGE_TABLE_END (p, mcnt);
4211 p += 1 + CHARSET_BITMAP_SIZE (p - 1);
4218 case notcategoryspec:
4230 /* Jump over non-matching operations. */
4231 static unsigned char *
4232 skip_noops (p, pend)
4233 unsigned char *p, *pend;
4238 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p))
4247 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4258 /* Non-zero if "p1 matches something" implies "p2 fails". */
4260 mutually_exclusive_p (bufp, p1, p2)
4261 struct re_pattern_buffer *bufp;
4262 unsigned char *p1, *p2;
4265 const boolean multibyte = RE_MULTIBYTE_P (bufp);
4266 unsigned char *pend = bufp->buffer + bufp->used;
4268 assert (p1 >= bufp->buffer && p1 < pend
4269 && p2 >= bufp->buffer && p2 <= pend);
4271 /* Skip over open/close-group commands.
4272 If what follows this loop is a ...+ construct,
4273 look at what begins its body, since we will have to
4274 match at least one of that. */
4275 p2 = skip_noops (p2, pend);
4276 /* The same skip can be done for p1, except that this function
4277 is only used in the case where p1 is a simple match operator. */
4278 /* p1 = skip_noops (p1, pend); */
4280 assert (p1 >= bufp->buffer && p1 < pend
4281 && p2 >= bufp->buffer && p2 <= pend);
4283 op2 = p2 == pend ? succeed : *p2;
4285 switch (SWITCH_ENUM_CAST (op2))
4289 /* If we're at the end of the pattern, we can change. */
4290 if (skip_one_char (p1))
4292 DEBUG_PRINT1 (" End of pattern: fast loop.\n");
4300 register unsigned int c
4301 = (re_opcode_t) *p2 == endline ? '\n'
4302 : RE_STRING_CHAR(p2 + 2, pend - p2 - 2);
4304 if ((re_opcode_t) *p1 == exactn)
4306 if (c != RE_STRING_CHAR (p1 + 2, pend - p1 - 2))
4308 DEBUG_PRINT3 (" '%c' != '%c' => fast loop.\n", c, p1[2]);
4313 else if ((re_opcode_t) *p1 == charset
4314 || (re_opcode_t) *p1 == charset_not)
4316 int not = (re_opcode_t) *p1 == charset_not;
4318 /* Test if C is listed in charset (or charset_not)
4320 if (SINGLE_BYTE_CHAR_P (c))
4322 if (c < CHARSET_BITMAP_SIZE (p1) * BYTEWIDTH
4323 && p1[2 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
4326 else if (CHARSET_RANGE_TABLE_EXISTS_P (p1))
4327 CHARSET_LOOKUP_RANGE_TABLE (not, c, p1);
4329 /* `not' is equal to 1 if c would match, which means
4330 that we can't change to pop_failure_jump. */
4333 DEBUG_PRINT1 (" No match => fast loop.\n");
4337 else if ((re_opcode_t) *p1 == anychar
4340 DEBUG_PRINT1 (" . != \\n => fast loop.\n");
4349 if ((re_opcode_t) *p1 == exactn)
4350 /* Reuse the code above. */
4351 return mutually_exclusive_p (bufp, p2, p1);
4354 /* It is hard to list up all the character in charset
4355 P2 if it includes multibyte character. Give up in
4357 else if (!multibyte || !CHARSET_RANGE_TABLE_EXISTS_P (p2))
4359 /* Now, we are sure that P2 has no range table.
4360 So, for the size of bitmap in P2, `p2[1]' is
4361 enough. But P1 may have range table, so the
4362 size of bitmap table of P1 is extracted by
4363 using macro `CHARSET_BITMAP_SIZE'.
4365 Since we know that all the character listed in
4366 P2 is ASCII, it is enough to test only bitmap
4372 /* We win if the charset inside the loop
4373 has no overlap with the one after the loop. */
4376 && idx < CHARSET_BITMAP_SIZE (p1));
4378 if ((p2[2 + idx] & p1[2 + idx]) != 0)
4382 || idx == CHARSET_BITMAP_SIZE (p1))
4384 DEBUG_PRINT1 (" No match => fast loop.\n");
4388 else if ((re_opcode_t) *p1 == charset
4389 || (re_opcode_t) *p1 == charset_not)
4392 /* We win if the charset_not inside the loop lists
4393 every character listed in the charset after. */
4394 for (idx = 0; idx < (int) p2[1]; idx++)
4395 if (! (p2[2 + idx] == 0
4396 || (idx < CHARSET_BITMAP_SIZE (p1)
4397 && ((p2[2 + idx] & ~ p1[2 + idx]) == 0))))
4402 DEBUG_PRINT1 (" No match => fast loop.\n");
4411 return ((re_opcode_t) *p1 == syntaxspec
4412 && p1[1] == (op2 == wordend ? Sword : p2[1]));
4416 return ((re_opcode_t) *p1 == notsyntaxspec
4417 && p1[1] == (op2 == wordend ? Sword : p2[1]));
4420 return (((re_opcode_t) *p1 == notsyntaxspec
4421 || (re_opcode_t) *p1 == syntaxspec)
4426 return ((re_opcode_t) *p1 == notcategoryspec && p1[1] == p2[1]);
4427 case notcategoryspec:
4428 return ((re_opcode_t) *p1 == categoryspec && p1[1] == p2[1]);
4440 /* Matching routines. */
4442 #ifndef emacs /* Emacs never uses this. */
4443 /* re_match is like re_match_2 except it takes only a single string. */
4446 re_match (bufp, string, size, pos, regs)
4447 struct re_pattern_buffer *bufp;
4450 struct re_registers *regs;
4452 int result = re_match_2_internal (bufp, NULL, 0, (re_char*) string, size,
4454 # if defined C_ALLOCA && !defined REGEX_MALLOC
4459 WEAK_ALIAS (__re_match, re_match)
4460 #endif /* not emacs */
4463 /* In Emacs, this is the string or buffer in which we
4464 are matching. It is used for looking up syntax properties. */
4465 Lisp_Object re_match_object;
4468 /* re_match_2 matches the compiled pattern in BUFP against the
4469 the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
4470 and SIZE2, respectively). We start matching at POS, and stop
4473 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
4474 store offsets for the substring each group matched in REGS. See the
4475 documentation for exactly how many groups we fill.
4477 We return -1 if no match, -2 if an internal error (such as the
4478 failure stack overflowing). Otherwise, we return the length of the
4479 matched substring. */
4482 re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
4483 struct re_pattern_buffer *bufp;
4484 const char *string1, *string2;
4487 struct re_registers *regs;
4494 gl_state.object = re_match_object;
4495 charpos = SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (pos));
4496 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object, charpos, 1);
4499 result = re_match_2_internal (bufp, (re_char*) string1, size1,
4500 (re_char*) string2, size2,
4502 #if defined C_ALLOCA && !defined REGEX_MALLOC
4507 WEAK_ALIAS (__re_match_2, re_match_2)
4509 /* This is a separate function so that we can force an alloca cleanup
4512 re_match_2_internal (bufp, string1, size1, string2, size2, pos, regs, stop)
4513 struct re_pattern_buffer *bufp;
4514 re_char *string1, *string2;
4517 struct re_registers *regs;
4520 /* General temporaries. */
4525 /* Just past the end of the corresponding string. */
4526 re_char *end1, *end2;
4528 /* Pointers into string1 and string2, just past the last characters in
4529 each to consider matching. */
4530 re_char *end_match_1, *end_match_2;
4532 /* Where we are in the data, and the end of the current string. */
4535 /* Used sometimes to remember where we were before starting matching
4536 an operator so that we can go back in case of failure. This "atomic"
4537 behavior of matching opcodes is indispensable to the correctness
4538 of the on_failure_keep_string_jump optimization. */
4541 /* Where we are in the pattern, and the end of the pattern. */
4542 unsigned char *p = bufp->buffer;
4543 register unsigned char *pend = p + bufp->used;
4545 /* We use this to map every character in the string. */
4546 RE_TRANSLATE_TYPE translate = bufp->translate;
4548 /* Nonzero if we have to concern multibyte character. */
4549 const boolean multibyte = RE_MULTIBYTE_P (bufp);
4551 /* Failure point stack. Each place that can handle a failure further
4552 down the line pushes a failure point on this stack. It consists of
4553 regstart, and regend for all registers corresponding to
4554 the subexpressions we're currently inside, plus the number of such
4555 registers, and, finally, two char *'s. The first char * is where
4556 to resume scanning the pattern; the second one is where to resume
4557 scanning the strings. */
4558 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
4559 fail_stack_type fail_stack;
4562 unsigned nfailure_points_pushed = 0, nfailure_points_popped = 0;
4565 #if defined REL_ALLOC && defined REGEX_MALLOC
4566 /* This holds the pointer to the failure stack, when
4567 it is allocated relocatably. */
4568 fail_stack_elt_t *failure_stack_ptr;
4571 /* We fill all the registers internally, independent of what we
4572 return, for use in backreferences. The number here includes
4573 an element for register zero. */
4574 size_t num_regs = bufp->re_nsub + 1;
4576 /* Information on the contents of registers. These are pointers into
4577 the input strings; they record just what was matched (on this
4578 attempt) by a subexpression part of the pattern, that is, the
4579 regnum-th regstart pointer points to where in the pattern we began
4580 matching and the regnum-th regend points to right after where we
4581 stopped matching the regnum-th subexpression. (The zeroth register
4582 keeps track of what the whole pattern matches.) */
4583 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4584 re_char **regstart, **regend;
4587 /* The following record the register info as found in the above
4588 variables when we find a match better than any we've seen before.
4589 This happens as we backtrack through the failure points, which in
4590 turn happens only if we have not yet matched the entire string. */
4591 unsigned best_regs_set = false;
4592 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4593 re_char **best_regstart, **best_regend;
4596 /* Logically, this is `best_regend[0]'. But we don't want to have to
4597 allocate space for that if we're not allocating space for anything
4598 else (see below). Also, we never need info about register 0 for
4599 any of the other register vectors, and it seems rather a kludge to
4600 treat `best_regend' differently than the rest. So we keep track of
4601 the end of the best match so far in a separate variable. We
4602 initialize this to NULL so that when we backtrack the first time
4603 and need to test it, it's not garbage. */
4604 re_char *match_end = NULL;
4607 /* Counts the total number of registers pushed. */
4608 unsigned num_regs_pushed = 0;
4611 DEBUG_PRINT1 ("\n\nEntering re_match_2.\n");
4615 #ifdef MATCH_MAY_ALLOCATE
4616 /* Do not bother to initialize all the register variables if there are
4617 no groups in the pattern, as it takes a fair amount of time. If
4618 there are groups, we include space for register 0 (the whole
4619 pattern), even though we never use it, since it simplifies the
4620 array indexing. We should fix this. */
4623 regstart = REGEX_TALLOC (num_regs, re_char *);
4624 regend = REGEX_TALLOC (num_regs, re_char *);
4625 best_regstart = REGEX_TALLOC (num_regs, re_char *);
4626 best_regend = REGEX_TALLOC (num_regs, re_char *);
4628 if (!(regstart && regend && best_regstart && best_regend))
4636 /* We must initialize all our variables to NULL, so that
4637 `FREE_VARIABLES' doesn't try to free them. */
4638 regstart = regend = best_regstart = best_regend = NULL;
4640 #endif /* MATCH_MAY_ALLOCATE */
4642 /* The starting position is bogus. */
4643 if (pos < 0 || pos > size1 + size2)
4649 /* Initialize subexpression text positions to -1 to mark ones that no
4650 start_memory/stop_memory has been seen for. Also initialize the
4651 register information struct. */
4652 for (mcnt = 1; mcnt < num_regs; mcnt++)
4653 regstart[mcnt] = regend[mcnt] = NULL;
4655 /* We move `string1' into `string2' if the latter's empty -- but not if
4656 `string1' is null. */
4657 if (size2 == 0 && string1 != NULL)
4664 end1 = string1 + size1;
4665 end2 = string2 + size2;
4667 /* `p' scans through the pattern as `d' scans through the data.
4668 `dend' is the end of the input string that `d' points within. `d'
4669 is advanced into the following input string whenever necessary, but
4670 this happens before fetching; therefore, at the beginning of the
4671 loop, `d' can be pointing at the end of a string, but it cannot
4675 /* Only match within string2. */
4676 d = string2 + pos - size1;
4677 dend = end_match_2 = string2 + stop - size1;
4678 end_match_1 = end1; /* Just to give it a value. */
4684 /* Only match within string1. */
4685 end_match_1 = string1 + stop;
4687 When we reach end_match_1, PREFETCH normally switches to string2.
4688 But in the present case, this means that just doing a PREFETCH
4689 makes us jump from `stop' to `gap' within the string.
4690 What we really want here is for the search to stop as
4691 soon as we hit end_match_1. That's why we set end_match_2
4692 to end_match_1 (since PREFETCH fails as soon as we hit
4694 end_match_2 = end_match_1;
4697 { /* It's important to use this code when stop == size so that
4698 moving `d' from end1 to string2 will not prevent the d == dend
4699 check from catching the end of string. */
4701 end_match_2 = string2 + stop - size1;
4707 DEBUG_PRINT1 ("The compiled pattern is: ");
4708 DEBUG_PRINT_COMPILED_PATTERN (bufp, p, pend);
4709 DEBUG_PRINT1 ("The string to match is: `");
4710 DEBUG_PRINT_DOUBLE_STRING (d, string1, size1, string2, size2);
4711 DEBUG_PRINT1 ("'\n");
4713 /* This loops over pattern commands. It exits by returning from the
4714 function if the match is complete, or it drops through if the match
4715 fails at this starting point in the input data. */
4718 DEBUG_PRINT2 ("\n%p: ", p);
4721 { /* End of pattern means we might have succeeded. */
4722 DEBUG_PRINT1 ("end of pattern ... ");
4724 /* If we haven't matched the entire string, and we want the
4725 longest match, try backtracking. */
4726 if (d != end_match_2)
4728 /* 1 if this match ends in the same string (string1 or string2)
4729 as the best previous match. */
4730 boolean same_str_p = (FIRST_STRING_P (match_end)
4731 == FIRST_STRING_P (d));
4732 /* 1 if this match is the best seen so far. */
4733 boolean best_match_p;
4735 /* AIX compiler got confused when this was combined
4736 with the previous declaration. */
4738 best_match_p = d > match_end;
4740 best_match_p = !FIRST_STRING_P (d);
4742 DEBUG_PRINT1 ("backtracking.\n");
4744 if (!FAIL_STACK_EMPTY ())
4745 { /* More failure points to try. */
4747 /* If exceeds best match so far, save it. */
4748 if (!best_regs_set || best_match_p)
4750 best_regs_set = true;
4753 DEBUG_PRINT1 ("\nSAVING match as best so far.\n");
4755 for (mcnt = 1; mcnt < num_regs; mcnt++)
4757 best_regstart[mcnt] = regstart[mcnt];
4758 best_regend[mcnt] = regend[mcnt];
4764 /* If no failure points, don't restore garbage. And if
4765 last match is real best match, don't restore second
4767 else if (best_regs_set && !best_match_p)
4770 /* Restore best match. It may happen that `dend ==
4771 end_match_1' while the restored d is in string2.
4772 For example, the pattern `x.*y.*z' against the
4773 strings `x-' and `y-z-', if the two strings are
4774 not consecutive in memory. */
4775 DEBUG_PRINT1 ("Restoring best registers.\n");
4778 dend = ((d >= string1 && d <= end1)
4779 ? end_match_1 : end_match_2);
4781 for (mcnt = 1; mcnt < num_regs; mcnt++)
4783 regstart[mcnt] = best_regstart[mcnt];
4784 regend[mcnt] = best_regend[mcnt];
4787 } /* d != end_match_2 */
4790 DEBUG_PRINT1 ("Accepting match.\n");
4792 /* If caller wants register contents data back, do it. */
4793 if (regs && !bufp->no_sub)
4795 /* Have the register data arrays been allocated? */
4796 if (bufp->regs_allocated == REGS_UNALLOCATED)
4797 { /* No. So allocate them with malloc. We need one
4798 extra element beyond `num_regs' for the `-1' marker
4800 regs->num_regs = MAX (RE_NREGS, num_regs + 1);
4801 regs->start = TALLOC (regs->num_regs, regoff_t);
4802 regs->end = TALLOC (regs->num_regs, regoff_t);
4803 if (regs->start == NULL || regs->end == NULL)
4808 bufp->regs_allocated = REGS_REALLOCATE;
4810 else if (bufp->regs_allocated == REGS_REALLOCATE)
4811 { /* Yes. If we need more elements than were already
4812 allocated, reallocate them. If we need fewer, just
4814 if (regs->num_regs < num_regs + 1)
4816 regs->num_regs = num_regs + 1;
4817 RETALLOC (regs->start, regs->num_regs, regoff_t);
4818 RETALLOC (regs->end, regs->num_regs, regoff_t);
4819 if (regs->start == NULL || regs->end == NULL)
4828 /* These braces fend off a "empty body in an else-statement"
4829 warning under GCC when assert expands to nothing. */
4830 assert (bufp->regs_allocated == REGS_FIXED);
4833 /* Convert the pointer data in `regstart' and `regend' to
4834 indices. Register zero has to be set differently,
4835 since we haven't kept track of any info for it. */
4836 if (regs->num_regs > 0)
4838 regs->start[0] = pos;
4839 regs->end[0] = POINTER_TO_OFFSET (d);
4842 /* Go through the first `min (num_regs, regs->num_regs)'
4843 registers, since that is all we initialized. */
4844 for (mcnt = 1; mcnt < MIN (num_regs, regs->num_regs); mcnt++)
4846 if (REG_UNSET (regstart[mcnt]) || REG_UNSET (regend[mcnt]))
4847 regs->start[mcnt] = regs->end[mcnt] = -1;
4851 = (regoff_t) POINTER_TO_OFFSET (regstart[mcnt]);
4853 = (regoff_t) POINTER_TO_OFFSET (regend[mcnt]);
4857 /* If the regs structure we return has more elements than
4858 were in the pattern, set the extra elements to -1. If
4859 we (re)allocated the registers, this is the case,
4860 because we always allocate enough to have at least one
4862 for (mcnt = num_regs; mcnt < regs->num_regs; mcnt++)
4863 regs->start[mcnt] = regs->end[mcnt] = -1;
4864 } /* regs && !bufp->no_sub */
4866 DEBUG_PRINT4 ("%u failure points pushed, %u popped (%u remain).\n",
4867 nfailure_points_pushed, nfailure_points_popped,
4868 nfailure_points_pushed - nfailure_points_popped);
4869 DEBUG_PRINT2 ("%u registers pushed.\n", num_regs_pushed);
4871 mcnt = POINTER_TO_OFFSET (d) - pos;
4873 DEBUG_PRINT2 ("Returning %d from re_match_2.\n", mcnt);
4879 /* Otherwise match next pattern command. */
4880 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
4882 /* Ignore these. Used to ignore the n of succeed_n's which
4883 currently have n == 0. */
4885 DEBUG_PRINT1 ("EXECUTING no_op.\n");
4889 DEBUG_PRINT1 ("EXECUTING succeed.\n");
4892 /* Match the next n pattern characters exactly. The following
4893 byte in the pattern defines n, and the n bytes after that
4894 are the characters to match. */
4897 DEBUG_PRINT2 ("EXECUTING exactn %d.\n", mcnt);
4899 /* Remember the start point to rollback upon failure. */
4902 /* This is written out as an if-else so we don't waste time
4903 testing `translate' inside the loop. */
4904 if (RE_TRANSLATE_P (translate))
4909 int pat_charlen, buf_charlen;
4910 unsigned int pat_ch, buf_ch;
4913 pat_ch = STRING_CHAR_AND_LENGTH (p, pend - p, pat_charlen);
4914 buf_ch = STRING_CHAR_AND_LENGTH (d, dend - d, buf_charlen);
4916 if (RE_TRANSLATE (translate, buf_ch)
4925 mcnt -= pat_charlen;
4932 if (RE_TRANSLATE (translate, *d) != *p++)
4957 /* Match any character except possibly a newline or a null. */
4961 unsigned int buf_ch;
4963 DEBUG_PRINT1 ("EXECUTING anychar.\n");
4966 buf_ch = RE_STRING_CHAR_AND_LENGTH (d, dend - d, buf_charlen);
4967 buf_ch = TRANSLATE (buf_ch);
4969 if ((!(bufp->syntax & RE_DOT_NEWLINE)
4971 || ((bufp->syntax & RE_DOT_NOT_NULL)
4972 && buf_ch == '\000'))
4975 DEBUG_PRINT2 (" Matched `%d'.\n", *d);
4984 register unsigned int c;
4985 boolean not = (re_opcode_t) *(p - 1) == charset_not;
4988 /* Start of actual range_table, or end of bitmap if there is no
4990 unsigned char *range_table;
4992 /* Nonzero if there is a range table. */
4993 int range_table_exists;
4995 /* Number of ranges of range table. This is not included
4996 in the initial byte-length of the command. */
4999 DEBUG_PRINT2 ("EXECUTING charset%s.\n", not ? "_not" : "");
5001 range_table_exists = CHARSET_RANGE_TABLE_EXISTS_P (&p[-1]);
5003 if (range_table_exists)
5005 range_table = CHARSET_RANGE_TABLE (&p[-1]); /* Past the bitmap. */
5006 EXTRACT_NUMBER_AND_INCR (count, range_table);
5010 c = RE_STRING_CHAR_AND_LENGTH (d, dend - d, len);
5011 c = TRANSLATE (c); /* The character to match. */
5013 if (SINGLE_BYTE_CHAR_P (c))
5014 { /* Lookup bitmap. */
5015 /* Cast to `unsigned' instead of `unsigned char' in
5016 case the bit list is a full 32 bytes long. */
5017 if (c < (unsigned) (CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH)
5018 && p[1 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
5022 else if (range_table_exists)
5024 int class_bits = CHARSET_RANGE_TABLE_BITS (&p[-1]);
5026 if ( (class_bits & BIT_LOWER && ISLOWER (c))
5027 | (class_bits & BIT_MULTIBYTE)
5028 | (class_bits & BIT_PUNCT && ISPUNCT (c))
5029 | (class_bits & BIT_SPACE && ISSPACE (c))
5030 | (class_bits & BIT_UPPER && ISUPPER (c))
5031 | (class_bits & BIT_WORD && ISWORD (c)))
5034 CHARSET_LOOKUP_RANGE_TABLE_RAW (not, c, range_table, count);
5038 if (range_table_exists)
5039 p = CHARSET_RANGE_TABLE_END (range_table, count);
5041 p += CHARSET_BITMAP_SIZE (&p[-1]) + 1;
5043 if (!not) goto fail;
5050 /* The beginning of a group is represented by start_memory.
5051 The argument is the register number. The text
5052 matched within the group is recorded (in the internal
5053 registers data structure) under the register number. */
5055 DEBUG_PRINT2 ("EXECUTING start_memory %d:\n", *p);
5057 /* In case we need to undo this operation (via backtracking). */
5058 PUSH_FAILURE_REG ((unsigned int)*p);
5061 regend[*p] = NULL; /* probably unnecessary. -sm */
5062 DEBUG_PRINT2 (" regstart: %d\n", POINTER_TO_OFFSET (regstart[*p]));
5064 /* Move past the register number and inner group count. */
5069 /* The stop_memory opcode represents the end of a group. Its
5070 argument is the same as start_memory's: the register number. */
5072 DEBUG_PRINT2 ("EXECUTING stop_memory %d:\n", *p);
5074 assert (!REG_UNSET (regstart[*p]));
5075 /* Strictly speaking, there should be code such as:
5077 assert (REG_UNSET (regend[*p]));
5078 PUSH_FAILURE_REGSTOP ((unsigned int)*p);
5080 But the only info to be pushed is regend[*p] and it is known to
5081 be UNSET, so there really isn't anything to push.
5082 Not pushing anything, on the other hand deprives us from the
5083 guarantee that regend[*p] is UNSET since undoing this operation
5084 will not reset its value properly. This is not important since
5085 the value will only be read on the next start_memory or at
5086 the very end and both events can only happen if this stop_memory
5090 DEBUG_PRINT2 (" regend: %d\n", POINTER_TO_OFFSET (regend[*p]));
5092 /* Move past the register number and the inner group count. */
5097 /* \<digit> has been turned into a `duplicate' command which is
5098 followed by the numeric value of <digit> as the register number. */
5101 register re_char *d2, *dend2;
5102 int regno = *p++; /* Get which register to match against. */
5103 DEBUG_PRINT2 ("EXECUTING duplicate %d.\n", regno);
5105 /* Can't back reference a group which we've never matched. */
5106 if (REG_UNSET (regstart[regno]) || REG_UNSET (regend[regno]))
5109 /* Where in input to try to start matching. */
5110 d2 = regstart[regno];
5112 /* Remember the start point to rollback upon failure. */
5115 /* Where to stop matching; if both the place to start and
5116 the place to stop matching are in the same string, then
5117 set to the place to stop, otherwise, for now have to use
5118 the end of the first string. */
5120 dend2 = ((FIRST_STRING_P (regstart[regno])
5121 == FIRST_STRING_P (regend[regno]))
5122 ? regend[regno] : end_match_1);
5125 /* If necessary, advance to next segment in register
5129 if (dend2 == end_match_2) break;
5130 if (dend2 == regend[regno]) break;
5132 /* End of string1 => advance to string2. */
5134 dend2 = regend[regno];
5136 /* At end of register contents => success */
5137 if (d2 == dend2) break;
5139 /* If necessary, advance to next segment in data. */
5142 /* How many characters left in this segment to match. */
5145 /* Want how many consecutive characters we can match in
5146 one shot, so, if necessary, adjust the count. */
5147 if (mcnt > dend2 - d2)
5150 /* Compare that many; failure if mismatch, else move
5152 if (RE_TRANSLATE_P (translate)
5153 ? bcmp_translate (d, d2, mcnt, translate, multibyte)
5154 : memcmp (d, d2, mcnt))
5159 d += mcnt, d2 += mcnt;
5165 /* begline matches the empty string at the beginning of the string
5166 (unless `not_bol' is set in `bufp'), and after newlines. */
5168 DEBUG_PRINT1 ("EXECUTING begline.\n");
5170 if (AT_STRINGS_BEG (d))
5172 if (!bufp->not_bol) break;
5177 GET_CHAR_BEFORE_2 (c, d, string1, end1, string2, end2);
5181 /* In all other cases, we fail. */
5185 /* endline is the dual of begline. */
5187 DEBUG_PRINT1 ("EXECUTING endline.\n");
5189 if (AT_STRINGS_END (d))
5191 if (!bufp->not_eol) break;
5195 PREFETCH_NOLIMIT ();
5202 /* Match at the very beginning of the data. */
5204 DEBUG_PRINT1 ("EXECUTING begbuf.\n");
5205 if (AT_STRINGS_BEG (d))
5210 /* Match at the very end of the data. */
5212 DEBUG_PRINT1 ("EXECUTING endbuf.\n");
5213 if (AT_STRINGS_END (d))
5218 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
5219 pushes NULL as the value for the string on the stack. Then
5220 `POP_FAILURE_POINT' will keep the current value for the
5221 string, instead of restoring it. To see why, consider
5222 matching `foo\nbar' against `.*\n'. The .* matches the foo;
5223 then the . fails against the \n. But the next thing we want
5224 to do is match the \n against the \n; if we restored the
5225 string value, we would be back at the foo.
5227 Because this is used only in specific cases, we don't need to
5228 check all the things that `on_failure_jump' does, to make
5229 sure the right things get saved on the stack. Hence we don't
5230 share its code. The only reason to push anything on the
5231 stack at all is that otherwise we would have to change
5232 `anychar's code to do something besides goto fail in this
5233 case; that seems worse than this. */
5234 case on_failure_keep_string_jump:
5235 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5236 DEBUG_PRINT3 ("EXECUTING on_failure_keep_string_jump %d (to %p):\n",
5239 PUSH_FAILURE_POINT (p - 3, NULL);
5242 /* A nasty loop is introduced by the non-greedy *? and +?.
5243 With such loops, the stack only ever contains one failure point
5244 at a time, so that a plain on_failure_jump_loop kind of
5245 cycle detection cannot work. Worse yet, such a detection
5246 can not only fail to detect a cycle, but it can also wrongly
5247 detect a cycle (between different instantiations of the same
5249 So the method used for those nasty loops is a little different:
5250 We use a special cycle-detection-stack-frame which is pushed
5251 when the on_failure_jump_nastyloop failure-point is *popped*.
5252 This special frame thus marks the beginning of one iteration
5253 through the loop and we can hence easily check right here
5254 whether something matched between the beginning and the end of
5256 case on_failure_jump_nastyloop:
5257 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5258 DEBUG_PRINT3 ("EXECUTING on_failure_jump_nastyloop %d (to %p):\n",
5261 assert ((re_opcode_t)p[-4] == no_op);
5262 CHECK_INFINITE_LOOP (p - 4, d);
5263 PUSH_FAILURE_POINT (p - 3, d);
5267 /* Simple loop detecting on_failure_jump: just check on the
5268 failure stack if the same spot was already hit earlier. */
5269 case on_failure_jump_loop:
5271 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5272 DEBUG_PRINT3 ("EXECUTING on_failure_jump_loop %d (to %p):\n",
5275 CHECK_INFINITE_LOOP (p - 3, d);
5276 PUSH_FAILURE_POINT (p - 3, d);
5280 /* Uses of on_failure_jump:
5282 Each alternative starts with an on_failure_jump that points
5283 to the beginning of the next alternative. Each alternative
5284 except the last ends with a jump that in effect jumps past
5285 the rest of the alternatives. (They really jump to the
5286 ending jump of the following alternative, because tensioning
5287 these jumps is a hassle.)
5289 Repeats start with an on_failure_jump that points past both
5290 the repetition text and either the following jump or
5291 pop_failure_jump back to this on_failure_jump. */
5292 case on_failure_jump:
5294 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5295 DEBUG_PRINT3 ("EXECUTING on_failure_jump %d (to %p):\n",
5298 PUSH_FAILURE_POINT (p -3, d);
5301 /* This operation is used for greedy *.
5302 Compare the beginning of the repeat with what in the
5303 pattern follows its end. If we can establish that there
5304 is nothing that they would both match, i.e., that we
5305 would have to backtrack because of (as in, e.g., `a*a')
5306 then we can use a non-backtracking loop based on
5307 on_failure_keep_string_jump instead of on_failure_jump. */
5308 case on_failure_jump_smart:
5310 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5311 DEBUG_PRINT3 ("EXECUTING on_failure_jump_smart %d (to %p).\n",
5314 unsigned char *p1 = p; /* Next operation. */
5315 unsigned char *p2 = p + mcnt; /* Destination of the jump. */
5317 p -= 3; /* Reset so that we will re-execute the
5318 instruction once it's been changed. */
5320 EXTRACT_NUMBER (mcnt, p2 - 2);
5322 /* Ensure this is a indeed the trivial kind of loop
5323 we are expecting. */
5324 assert (skip_one_char (p1) == p2 - 3);
5325 assert ((re_opcode_t) p2[-3] == jump && p2 + mcnt == p);
5326 DEBUG_STATEMENT (debug += 2);
5327 if (mutually_exclusive_p (bufp, p1, p2))
5329 /* Use a fast `on_failure_keep_string_jump' loop. */
5330 DEBUG_PRINT1 (" smart exclusive => fast loop.\n");
5331 *p = (unsigned char) on_failure_keep_string_jump;
5332 STORE_NUMBER (p2 - 2, mcnt + 3);
5336 /* Default to a safe `on_failure_jump' loop. */
5337 DEBUG_PRINT1 (" smart default => slow loop.\n");
5338 *p = (unsigned char) on_failure_jump;
5340 DEBUG_STATEMENT (debug -= 2);
5344 /* Unconditionally jump (without popping any failure points). */
5348 EXTRACT_NUMBER_AND_INCR (mcnt, p); /* Get the amount to jump. */
5349 DEBUG_PRINT2 ("EXECUTING jump %d ", mcnt);
5350 p += mcnt; /* Do the jump. */
5351 DEBUG_PRINT2 ("(to %p).\n", p);
5355 /* Have to succeed matching what follows at least n times.
5356 After that, handle like `on_failure_jump'. */
5358 EXTRACT_NUMBER (mcnt, p + 2);
5359 DEBUG_PRINT2 ("EXECUTING succeed_n %d.\n", mcnt);
5361 /* Originally, mcnt is how many times we HAVE to succeed. */
5366 PUSH_FAILURE_COUNT (p);
5367 DEBUG_PRINT3 (" Setting %p to %d.\n", p, mcnt);
5368 STORE_NUMBER_AND_INCR (p, mcnt);
5371 /* The two bytes encoding mcnt == 0 are two no_op opcodes. */
5376 EXTRACT_NUMBER (mcnt, p + 2);
5377 DEBUG_PRINT2 ("EXECUTING jump_n %d.\n", mcnt);
5379 /* Originally, this is how many times we CAN jump. */
5383 PUSH_FAILURE_COUNT (p + 2);
5384 STORE_NUMBER (p + 2, mcnt);
5385 goto unconditional_jump;
5387 /* If don't have to jump any more, skip over the rest of command. */
5394 DEBUG_PRINT1 ("EXECUTING set_number_at.\n");
5396 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5398 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5399 DEBUG_PRINT3 (" Setting %p to %d.\n", p1, mcnt);
5400 PUSH_FAILURE_COUNT (p1);
5401 STORE_NUMBER (p1, mcnt);
5407 not = (re_opcode_t) *(p - 1) == notwordbound;
5408 DEBUG_PRINT2 ("EXECUTING %swordbound.\n", not?"not":"");
5410 /* We SUCCEED (or FAIL) in one of the following cases: */
5412 /* Case 1: D is at the beginning or the end of string. */
5413 if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
5417 /* C1 is the character before D, S1 is the syntax of C1, C2
5418 is the character at D, and S2 is the syntax of C2. */
5421 int offset = PTR_TO_OFFSET (d - 1);
5422 int charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
5423 UPDATE_SYNTAX_TABLE (charpos);
5425 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
5428 UPDATE_SYNTAX_TABLE_FORWARD (charpos + 1);
5430 PREFETCH_NOLIMIT ();
5431 c2 = RE_STRING_CHAR (d, dend - d);
5434 if (/* Case 2: Only one of S1 and S2 is Sword. */
5435 ((s1 == Sword) != (s2 == Sword))
5436 /* Case 3: Both of S1 and S2 are Sword, and macro
5437 WORD_BOUNDARY_P (C1, C2) returns nonzero. */
5438 || ((s1 == Sword) && WORD_BOUNDARY_P (c1, c2)))
5447 DEBUG_PRINT1 ("EXECUTING wordbeg.\n");
5449 /* We FAIL in one of the following cases: */
5451 /* Case 1: D is at the end of string. */
5452 if (AT_STRINGS_END (d))
5456 /* C1 is the character before D, S1 is the syntax of C1, C2
5457 is the character at D, and S2 is the syntax of C2. */
5460 int offset = PTR_TO_OFFSET (d);
5461 int charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
5462 UPDATE_SYNTAX_TABLE (charpos);
5465 c2 = RE_STRING_CHAR (d, dend - d);
5468 /* Case 2: S2 is not Sword. */
5472 /* Case 3: D is not at the beginning of string ... */
5473 if (!AT_STRINGS_BEG (d))
5475 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
5477 UPDATE_SYNTAX_TABLE_BACKWARD (charpos - 1);
5481 /* ... and S1 is Sword, and WORD_BOUNDARY_P (C1, C2)
5483 if ((s1 == Sword) && !WORD_BOUNDARY_P (c1, c2))
5490 DEBUG_PRINT1 ("EXECUTING wordend.\n");
5492 /* We FAIL in one of the following cases: */
5494 /* Case 1: D is at the beginning of string. */
5495 if (AT_STRINGS_BEG (d))
5499 /* C1 is the character before D, S1 is the syntax of C1, C2
5500 is the character at D, and S2 is the syntax of C2. */
5503 int offset = PTR_TO_OFFSET (d) - 1;
5504 int charpos = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
5505 UPDATE_SYNTAX_TABLE (charpos);
5507 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
5510 /* Case 2: S1 is not Sword. */
5514 /* Case 3: D is not at the end of string ... */
5515 if (!AT_STRINGS_END (d))
5517 PREFETCH_NOLIMIT ();
5518 c2 = RE_STRING_CHAR (d, dend - d);
5520 UPDATE_SYNTAX_TABLE_FORWARD (charpos);
5524 /* ... and S2 is Sword, and WORD_BOUNDARY_P (C1, C2)
5526 if ((s2 == Sword) && !WORD_BOUNDARY_P (c1, c2))
5534 not = (re_opcode_t) *(p - 1) == notsyntaxspec;
5536 DEBUG_PRINT3 ("EXECUTING %ssyntaxspec %d.\n", not?"not":"", mcnt);
5540 int offset = PTR_TO_OFFSET (d);
5541 int pos1 = SYNTAX_TABLE_BYTE_TO_CHAR (offset);
5542 UPDATE_SYNTAX_TABLE (pos1);
5548 c = RE_STRING_CHAR_AND_LENGTH (d, dend - d, len);
5550 if ((SYNTAX (c) != (enum syntaxcode) mcnt) ^ not)
5558 DEBUG_PRINT1 ("EXECUTING before_dot.\n");
5559 if (PTR_BYTE_POS (d) >= PT_BYTE)
5564 DEBUG_PRINT1 ("EXECUTING at_dot.\n");
5565 if (PTR_BYTE_POS (d) != PT_BYTE)
5570 DEBUG_PRINT1 ("EXECUTING after_dot.\n");
5571 if (PTR_BYTE_POS (d) <= PT_BYTE)
5576 case notcategoryspec:
5577 not = (re_opcode_t) *(p - 1) == notcategoryspec;
5579 DEBUG_PRINT3 ("EXECUTING %scategoryspec %d.\n", not?"not":"", mcnt);
5583 c = RE_STRING_CHAR_AND_LENGTH (d, dend - d, len);
5585 if ((!CHAR_HAS_CATEGORY (c, mcnt)) ^ not)
5596 continue; /* Successfully executed one pattern command; keep going. */
5599 /* We goto here if a matching operation fails. */
5602 if (!FAIL_STACK_EMPTY ())
5606 /* A restart point is known. Restore to that state. */
5607 DEBUG_PRINT1 ("\nFAIL:\n");
5608 POP_FAILURE_POINT (str, pat);
5609 switch (SWITCH_ENUM_CAST ((re_opcode_t) *pat++))
5611 case on_failure_keep_string_jump:
5612 assert (str == NULL);
5613 goto continue_failure_jump;
5615 case on_failure_jump_nastyloop:
5616 assert ((re_opcode_t)pat[-2] == no_op);
5617 PUSH_FAILURE_POINT (pat - 2, str);
5620 case on_failure_jump_loop:
5621 case on_failure_jump:
5624 continue_failure_jump:
5625 EXTRACT_NUMBER_AND_INCR (mcnt, pat);
5630 /* A special frame used for nastyloops. */
5637 assert (p >= bufp->buffer && p <= pend);
5639 if (d >= string1 && d <= end1)
5643 break; /* Matching at this starting point really fails. */
5647 goto restore_best_regs;
5651 return -1; /* Failure to match. */
5654 /* Subroutine definitions for re_match_2. */
5656 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
5657 bytes; nonzero otherwise. */
5660 bcmp_translate (s1, s2, len, translate, multibyte)
5663 RE_TRANSLATE_TYPE translate;
5664 const int multibyte;
5666 register re_char *p1 = s1, *p2 = s2;
5667 re_char *p1_end = s1 + len;
5668 re_char *p2_end = s2 + len;
5670 /* FIXME: Checking both p1 and p2 presumes that the two strings might have
5671 different lengths, but relying on a single `len' would break this. -sm */
5672 while (p1 < p1_end && p2 < p2_end)
5674 int p1_charlen, p2_charlen;
5677 p1_ch = RE_STRING_CHAR_AND_LENGTH (p1, p1_end - p1, p1_charlen);
5678 p2_ch = RE_STRING_CHAR_AND_LENGTH (p2, p2_end - p2, p2_charlen);
5680 if (RE_TRANSLATE (translate, p1_ch)
5681 != RE_TRANSLATE (translate, p2_ch))
5684 p1 += p1_charlen, p2 += p2_charlen;
5687 if (p1 != p1_end || p2 != p2_end)
5693 /* Entry points for GNU code. */
5695 /* re_compile_pattern is the GNU regular expression compiler: it
5696 compiles PATTERN (of length SIZE) and puts the result in BUFP.
5697 Returns 0 if the pattern was valid, otherwise an error string.
5699 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
5700 are set in BUFP on entry.
5702 We call regex_compile to do the actual compilation. */
5705 re_compile_pattern (pattern, length, bufp)
5706 const char *pattern;
5708 struct re_pattern_buffer *bufp;
5712 /* GNU code is written to assume at least RE_NREGS registers will be set
5713 (and at least one extra will be -1). */
5714 bufp->regs_allocated = REGS_UNALLOCATED;
5716 /* And GNU code determines whether or not to get register information
5717 by passing null for the REGS argument to re_match, etc., not by
5721 ret = regex_compile ((re_char*) pattern, length, re_syntax_options, bufp);
5725 return gettext (re_error_msgid[(int) ret]);
5727 WEAK_ALIAS (__re_compile_pattern, re_compile_pattern)
5729 /* Entry points compatible with 4.2 BSD regex library. We don't define
5730 them unless specifically requested. */
5732 #if defined _REGEX_RE_COMP || defined _LIBC
5734 /* BSD has one and only one pattern buffer. */
5735 static struct re_pattern_buffer re_comp_buf;
5739 /* Make these definitions weak in libc, so POSIX programs can redefine
5740 these names if they don't use our functions, and still use
5741 regcomp/regexec below without link errors. */
5751 if (!re_comp_buf.buffer)
5752 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
5753 return (char *) gettext ("No previous regular expression");
5757 if (!re_comp_buf.buffer)
5759 re_comp_buf.buffer = (unsigned char *) malloc (200);
5760 if (re_comp_buf.buffer == NULL)
5761 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
5762 return (char *) gettext (re_error_msgid[(int) REG_ESPACE]);
5763 re_comp_buf.allocated = 200;
5765 re_comp_buf.fastmap = (char *) malloc (1 << BYTEWIDTH);
5766 if (re_comp_buf.fastmap == NULL)
5767 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
5768 return (char *) gettext (re_error_msgid[(int) REG_ESPACE]);
5771 /* Since `re_exec' always passes NULL for the `regs' argument, we
5772 don't need to initialize the pattern buffer fields which affect it. */
5774 ret = regex_compile (s, strlen (s), re_syntax_options, &re_comp_buf);
5779 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
5780 return (char *) gettext (re_error_msgid[(int) ret]);
5791 const int len = strlen (s);
5793 0 <= re_search (&re_comp_buf, s, len, 0, len, (struct re_registers *) 0);
5795 #endif /* _REGEX_RE_COMP */
5797 /* POSIX.2 functions. Don't define these for Emacs. */
5801 /* regcomp takes a regular expression as a string and compiles it.
5803 PREG is a regex_t *. We do not expect any fields to be initialized,
5804 since POSIX says we shouldn't. Thus, we set
5806 `buffer' to the compiled pattern;
5807 `used' to the length of the compiled pattern;
5808 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
5809 REG_EXTENDED bit in CFLAGS is set; otherwise, to
5810 RE_SYNTAX_POSIX_BASIC;
5811 `fastmap' to an allocated space for the fastmap;
5812 `fastmap_accurate' to zero;
5813 `re_nsub' to the number of subexpressions in PATTERN.
5815 PATTERN is the address of the pattern string.
5817 CFLAGS is a series of bits which affect compilation.
5819 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
5820 use POSIX basic syntax.
5822 If REG_NEWLINE is set, then . and [^...] don't match newline.
5823 Also, regexec will try a match beginning after every newline.
5825 If REG_ICASE is set, then we considers upper- and lowercase
5826 versions of letters to be equivalent when matching.
5828 If REG_NOSUB is set, then when PREG is passed to regexec, that
5829 routine will report only success or failure, and nothing about the
5832 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
5833 the return codes and their meanings.) */
5836 regcomp (preg, pattern, cflags)
5838 const char *pattern;
5843 = (cflags & REG_EXTENDED) ?
5844 RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC;
5846 /* regex_compile will allocate the space for the compiled pattern. */
5848 preg->allocated = 0;
5851 /* Try to allocate space for the fastmap. */
5852 preg->fastmap = (char *) malloc (1 << BYTEWIDTH);
5854 if (cflags & REG_ICASE)
5859 = (RE_TRANSLATE_TYPE) malloc (CHAR_SET_SIZE
5860 * sizeof (*(RE_TRANSLATE_TYPE)0));
5861 if (preg->translate == NULL)
5862 return (int) REG_ESPACE;
5864 /* Map uppercase characters to corresponding lowercase ones. */
5865 for (i = 0; i < CHAR_SET_SIZE; i++)
5866 preg->translate[i] = ISUPPER (i) ? TOLOWER (i) : i;
5869 preg->translate = NULL;
5871 /* If REG_NEWLINE is set, newlines are treated differently. */
5872 if (cflags & REG_NEWLINE)
5873 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
5874 syntax &= ~RE_DOT_NEWLINE;
5875 syntax |= RE_HAT_LISTS_NOT_NEWLINE;
5878 syntax |= RE_NO_NEWLINE_ANCHOR;
5880 preg->no_sub = !!(cflags & REG_NOSUB);
5882 /* POSIX says a null character in the pattern terminates it, so we
5883 can use strlen here in compiling the pattern. */
5884 ret = regex_compile ((re_char*) pattern, strlen (pattern), syntax, preg);
5886 /* POSIX doesn't distinguish between an unmatched open-group and an
5887 unmatched close-group: both are REG_EPAREN. */
5888 if (ret == REG_ERPAREN)
5891 if (ret == REG_NOERROR && preg->fastmap)
5892 { /* Compute the fastmap now, since regexec cannot modify the pattern
5894 re_compile_fastmap (preg);
5895 if (preg->can_be_null)
5896 { /* The fastmap can't be used anyway. */
5897 free (preg->fastmap);
5898 preg->fastmap = NULL;
5903 WEAK_ALIAS (__regcomp, regcomp)
5906 /* regexec searches for a given pattern, specified by PREG, in the
5909 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
5910 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
5911 least NMATCH elements, and we set them to the offsets of the
5912 corresponding matched substrings.
5914 EFLAGS specifies `execution flags' which affect matching: if
5915 REG_NOTBOL is set, then ^ does not match at the beginning of the
5916 string; if REG_NOTEOL is set, then $ does not match at the end.
5918 We return 0 if we find a match and REG_NOMATCH if not. */
5921 regexec (preg, string, nmatch, pmatch, eflags)
5922 const regex_t *preg;
5925 regmatch_t pmatch[];
5929 struct re_registers regs;
5930 regex_t private_preg;
5931 int len = strlen (string);
5932 boolean want_reg_info = !preg->no_sub && nmatch > 0 && pmatch;
5934 private_preg = *preg;
5936 private_preg.not_bol = !!(eflags & REG_NOTBOL);
5937 private_preg.not_eol = !!(eflags & REG_NOTEOL);
5939 /* The user has told us exactly how many registers to return
5940 information about, via `nmatch'. We have to pass that on to the
5941 matching routines. */
5942 private_preg.regs_allocated = REGS_FIXED;
5946 regs.num_regs = nmatch;
5947 regs.start = TALLOC (nmatch * 2, regoff_t);
5948 if (regs.start == NULL)
5949 return (int) REG_NOMATCH;
5950 regs.end = regs.start + nmatch;
5953 /* Instead of using not_eol to implement REG_NOTEOL, we could simply
5954 pass (&private_preg, string, len + 1, 0, len, ...) pretending the string
5955 was a little bit longer but still only matching the real part.
5956 This works because the `endline' will check for a '\n' and will find a
5957 '\0', correctly deciding that this is not the end of a line.
5958 But it doesn't work out so nicely for REG_NOTBOL, since we don't have
5959 a convenient '\0' there. For all we know, the string could be preceded
5960 by '\n' which would throw things off. */
5962 /* Perform the searching operation. */
5963 ret = re_search (&private_preg, string, len,
5964 /* start: */ 0, /* range: */ len,
5965 want_reg_info ? ®s : (struct re_registers *) 0);
5967 /* Copy the register information to the POSIX structure. */
5974 for (r = 0; r < nmatch; r++)
5976 pmatch[r].rm_so = regs.start[r];
5977 pmatch[r].rm_eo = regs.end[r];
5981 /* If we needed the temporary register info, free the space now. */
5985 /* We want zero return to mean success, unlike `re_search'. */
5986 return ret >= 0 ? (int) REG_NOERROR : (int) REG_NOMATCH;
5988 WEAK_ALIAS (__regexec, regexec)
5991 /* Returns a message corresponding to an error code, ERRCODE, returned
5992 from either regcomp or regexec. We don't use PREG here. */
5995 regerror (errcode, preg, errbuf, errbuf_size)
5997 const regex_t *preg;
6005 || errcode >= (sizeof (re_error_msgid) / sizeof (re_error_msgid[0])))
6006 /* Only error codes returned by the rest of the code should be passed
6007 to this routine. If we are given anything else, or if other regex
6008 code generates an invalid error code, then the program has a bug.
6009 Dump core so we can fix it. */
6012 msg = gettext (re_error_msgid[errcode]);
6014 msg_size = strlen (msg) + 1; /* Includes the null. */
6016 if (errbuf_size != 0)
6018 if (msg_size > errbuf_size)
6020 strncpy (errbuf, msg, errbuf_size - 1);
6021 errbuf[errbuf_size - 1] = 0;
6024 strcpy (errbuf, msg);
6029 WEAK_ALIAS (__regerror, regerror)
6032 /* Free dynamically allocated space used by PREG. */
6038 if (preg->buffer != NULL)
6039 free (preg->buffer);
6040 preg->buffer = NULL;
6042 preg->allocated = 0;
6045 if (preg->fastmap != NULL)
6046 free (preg->fastmap);
6047 preg->fastmap = NULL;
6048 preg->fastmap_accurate = 0;
6050 if (preg->translate != NULL)
6051 free (preg->translate);
6052 preg->translate = NULL;
6054 WEAK_ALIAS (__regfree, regfree)
6056 #endif /* not emacs */