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 + set_number_at) with something that doesn't
26 need to modify the compiled regexp so that re_match can be reentrant.
27 - get rid of on_failure_jump_smart by doing the optimization in re_comp
28 rather than at run-time, so that re_match can be reentrant.
31 /* AIX requires this to be the first thing in the file. */
32 #if defined _AIX && !defined REGEX_MALLOC
43 #if defined STDC_HEADERS && !defined emacs
46 /* We need this for `regex.h', and perhaps for the Emacs include files. */
47 # include <sys/types.h>
50 /* Whether to use ISO C Amendment 1 wide char functions.
51 Those should not be used for Emacs since it uses its own. */
53 #define WIDE_CHAR_SUPPORT 1
55 #define WIDE_CHAR_SUPPORT \
56 (HAVE_WCTYPE_H && HAVE_WCHAR_H && HAVE_BTOWC && !emacs)
59 /* For platform which support the ISO C amendement 1 functionality we
60 support user defined character classes. */
62 /* Solaris 2.5 has a bug: <wchar.h> must be included before <wctype.h>. */
68 /* We have to keep the namespace clean. */
69 # define regfree(preg) __regfree (preg)
70 # define regexec(pr, st, nm, pm, ef) __regexec (pr, st, nm, pm, ef)
71 # define regcomp(preg, pattern, cflags) __regcomp (preg, pattern, cflags)
72 # define regerror(errcode, preg, errbuf, errbuf_size) \
73 __regerror(errcode, preg, errbuf, errbuf_size)
74 # define re_set_registers(bu, re, nu, st, en) \
75 __re_set_registers (bu, re, nu, st, en)
76 # define re_match_2(bufp, string1, size1, string2, size2, pos, regs, stop) \
77 __re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
78 # define re_match(bufp, string, size, pos, regs) \
79 __re_match (bufp, string, size, pos, regs)
80 # define re_search(bufp, string, size, startpos, range, regs) \
81 __re_search (bufp, string, size, startpos, range, regs)
82 # define re_compile_pattern(pattern, length, bufp) \
83 __re_compile_pattern (pattern, length, bufp)
84 # define re_set_syntax(syntax) __re_set_syntax (syntax)
85 # define re_search_2(bufp, st1, s1, st2, s2, startpos, range, regs, stop) \
86 __re_search_2 (bufp, st1, s1, st2, s2, startpos, range, regs, stop)
87 # define re_compile_fastmap(bufp) __re_compile_fastmap (bufp)
89 /* Make sure we call libc's function even if the user overrides them. */
90 # define btowc __btowc
91 # define iswctype __iswctype
92 # define wctype __wctype
94 # define WEAK_ALIAS(a,b) weak_alias (a, b)
96 /* We are also using some library internals. */
97 # include <locale/localeinfo.h>
98 # include <locale/elem-hash.h>
99 # include <langinfo.h>
101 # define WEAK_ALIAS(a,b)
104 /* This is for other GNU distributions with internationalized messages. */
105 #if HAVE_LIBINTL_H || defined _LIBC
106 # include <libintl.h>
108 # define gettext(msgid) (msgid)
112 /* This define is so xgettext can find the internationalizable
114 # define gettext_noop(String) String
117 /* The `emacs' switch turns on certain matching commands
118 that make sense only in Emacs. */
124 /* Make syntax table lookup grant data in gl_state. */
125 # define SYNTAX_ENTRY_VIA_PROPERTY
128 # include "character.h"
129 # include "category.h"
134 # define malloc xmalloc
138 # define realloc xrealloc
144 /* Converts the pointer to the char to BEG-based offset from the start. */
145 # define PTR_TO_OFFSET(d) POS_AS_IN_BUFFER (POINTER_TO_OFFSET (d))
146 # define POS_AS_IN_BUFFER(p) ((p) + (NILP (re_match_object) || BUFFERP (re_match_object)))
148 # define RE_MULTIBYTE_P(bufp) ((bufp)->multibyte)
149 # define RE_STRING_CHAR(p, s) \
150 (multibyte ? (STRING_CHAR (p, s)) : (*(p)))
151 # define RE_STRING_CHAR_AND_LENGTH(p, s, len) \
152 (multibyte ? (STRING_CHAR_AND_LENGTH (p, s, len)) : ((len) = 1, *(p)))
154 /* Set C a (possibly multibyte) character before P. P points into a
155 string which is the virtual concatenation of STR1 (which ends at
156 END1) or STR2 (which ends at END2). */
157 # define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
161 re_char *dtemp = (p) == (str2) ? (end1) : (p); \
162 re_char *dlimit = ((p) > (str2) && (p) <= (end2)) ? (str2) : (str1); \
163 while (dtemp-- > dlimit && !CHAR_HEAD_P (*dtemp)); \
164 c = STRING_CHAR (dtemp, (p) - dtemp); \
167 (c = ((p) == (str2) ? (end1) : (p))[-1]); \
171 #else /* not emacs */
173 /* If we are not linking with Emacs proper,
174 we can't use the relocating allocator
175 even if config.h says that we can. */
178 # if defined STDC_HEADERS || defined _LIBC
185 /* When used in Emacs's lib-src, we need to get bzero and bcopy somehow.
186 If nothing else has been done, use the method below. */
187 # ifdef INHIBIT_STRING_HEADER
188 # if !(defined HAVE_BZERO && defined HAVE_BCOPY)
189 # if !defined bzero && !defined bcopy
190 # undef INHIBIT_STRING_HEADER
195 /* This is the normal way of making sure we have memcpy, memcmp and bzero.
196 This is used in most programs--a few other programs avoid this
197 by defining INHIBIT_STRING_HEADER. */
198 # ifndef INHIBIT_STRING_HEADER
199 # if defined HAVE_STRING_H || defined STDC_HEADERS || defined _LIBC
203 # define bzero(s, n) (memset (s, '\0', n), (s))
205 # define bzero(s, n) __bzero (s, n)
209 # include <strings.h>
211 # define memcmp(s1, s2, n) bcmp (s1, s2, n)
214 # define memcpy(d, s, n) (bcopy (s, d, n), (d))
219 /* Define the syntax stuff for \<, \>, etc. */
221 /* Sword must be nonzero for the wordchar pattern commands in re_match_2. */
222 enum syntaxcode
{ Swhitespace
= 0, Sword
= 1 };
224 # ifdef SWITCH_ENUM_BUG
225 # define SWITCH_ENUM_CAST(x) ((int)(x))
227 # define SWITCH_ENUM_CAST(x) (x)
230 /* Dummy macros for non-Emacs environments. */
231 # define BASE_LEADING_CODE_P(c) (0)
232 # define CHAR_CHARSET(c) 0
233 # define CHARSET_LEADING_CODE_BASE(c) 0
234 # define MAX_MULTIBYTE_LENGTH 1
235 # define RE_MULTIBYTE_P(x) 0
236 # define WORD_BOUNDARY_P(c1, c2) (0)
237 # define CHAR_HEAD_P(p) (1)
238 # define SINGLE_BYTE_CHAR_P(c) (1)
239 # define SAME_CHARSET_P(c1, c2) (1)
240 # define MULTIBYTE_FORM_LENGTH(p, s) (1)
241 # define STRING_CHAR(p, s) (*(p))
242 # define RE_STRING_CHAR STRING_CHAR
243 # define CHAR_STRING(c, s) (*(s) = (c), 1)
244 # define STRING_CHAR_AND_LENGTH(p, s, actual_len) ((actual_len) = 1, *(p))
245 # define RE_STRING_CHAR_AND_LENGTH STRING_CHAR_AND_LENGTH
246 # define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
247 (c = ((p) == (str2) ? *((end1) - 1) : *((p) - 1)))
248 # define MAKE_CHAR(charset, c1, c2) (c1)
249 # define BYTE8_TO_CHAR(c) (c)
250 # define CHAR_BYTE8_P(c) (0)
251 #endif /* not emacs */
254 # define RE_TRANSLATE(TBL, C) ((unsigned char)(TBL)[C])
255 # define RE_TRANSLATE_P(TBL) (TBL)
258 /* Get the interface, including the syntax bits. */
261 /* isalpha etc. are used for the character classes. */
266 /* 1 if C is an ASCII character. */
267 # define IS_REAL_ASCII(c) ((c) < 0200)
269 /* 1 if C is a unibyte character. */
270 # define ISUNIBYTE(c) (SINGLE_BYTE_CHAR_P ((c)))
272 /* The Emacs definitions should not be directly affected by locales. */
274 /* In Emacs, these are only used for single-byte characters. */
275 # define ISDIGIT(c) ((c) >= '0' && (c) <= '9')
276 # define ISCNTRL(c) ((c) < ' ')
277 # define ISXDIGIT(c) (((c) >= '0' && (c) <= '9') \
278 || ((c) >= 'a' && (c) <= 'f') \
279 || ((c) >= 'A' && (c) <= 'F'))
281 /* This is only used for single-byte characters. */
282 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
284 /* The rest must handle multibyte characters. */
286 # define ISGRAPH(c) (SINGLE_BYTE_CHAR_P (c) \
287 ? (c) > ' ' && !((c) >= 0177 && (c) <= 0237) \
290 # define ISPRINT(c) (SINGLE_BYTE_CHAR_P (c) \
291 ? (c) >= ' ' && !((c) >= 0177 && (c) <= 0237) \
294 # define ISALNUM(c) (IS_REAL_ASCII (c) \
295 ? (((c) >= 'a' && (c) <= 'z') \
296 || ((c) >= 'A' && (c) <= 'Z') \
297 || ((c) >= '0' && (c) <= '9')) \
298 : SYNTAX (c) == Sword)
300 # define ISALPHA(c) (IS_REAL_ASCII (c) \
301 ? (((c) >= 'a' && (c) <= 'z') \
302 || ((c) >= 'A' && (c) <= 'Z')) \
303 : SYNTAX (c) == Sword)
305 # define ISLOWER(c) (LOWERCASEP (c))
307 # define ISPUNCT(c) (IS_REAL_ASCII (c) \
308 ? ((c) > ' ' && (c) < 0177 \
309 && !(((c) >= 'a' && (c) <= 'z') \
310 || ((c) >= 'A' && (c) <= 'Z') \
311 || ((c) >= '0' && (c) <= '9'))) \
312 : SYNTAX (c) != Sword)
314 # define ISSPACE(c) (SYNTAX (c) == Swhitespace)
316 # define ISUPPER(c) (UPPERCASEP (c))
318 # define ISWORD(c) (SYNTAX (c) == Sword)
320 #else /* not emacs */
322 /* Jim Meyering writes:
324 "... Some ctype macros are valid only for character codes that
325 isascii says are ASCII (SGI's IRIX-4.0.5 is one such system --when
326 using /bin/cc or gcc but without giving an ansi option). So, all
327 ctype uses should be through macros like ISPRINT... If
328 STDC_HEADERS is defined, then autoconf has verified that the ctype
329 macros don't need to be guarded with references to isascii. ...
330 Defining isascii to 1 should let any compiler worth its salt
331 eliminate the && through constant folding."
332 Solaris defines some of these symbols so we must undefine them first. */
335 # if defined STDC_HEADERS || (!defined isascii && !defined HAVE_ISASCII)
336 # define ISASCII(c) 1
338 # define ISASCII(c) isascii(c)
341 /* 1 if C is an ASCII character. */
342 # define IS_REAL_ASCII(c) ((c) < 0200)
344 /* This distinction is not meaningful, except in Emacs. */
345 # define ISUNIBYTE(c) 1
348 # define ISBLANK(c) (ISASCII (c) && isblank (c))
350 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
353 # define ISGRAPH(c) (ISASCII (c) && isgraph (c))
355 # define ISGRAPH(c) (ISASCII (c) && isprint (c) && !isspace (c))
359 # define ISPRINT(c) (ISASCII (c) && isprint (c))
360 # define ISDIGIT(c) (ISASCII (c) && isdigit (c))
361 # define ISALNUM(c) (ISASCII (c) && isalnum (c))
362 # define ISALPHA(c) (ISASCII (c) && isalpha (c))
363 # define ISCNTRL(c) (ISASCII (c) && iscntrl (c))
364 # define ISLOWER(c) (ISASCII (c) && islower (c))
365 # define ISPUNCT(c) (ISASCII (c) && ispunct (c))
366 # define ISSPACE(c) (ISASCII (c) && isspace (c))
367 # define ISUPPER(c) (ISASCII (c) && isupper (c))
368 # define ISXDIGIT(c) (ISASCII (c) && isxdigit (c))
370 # define ISWORD(c) ISALPHA(c)
373 # define TOLOWER(c) _tolower(c)
375 # define TOLOWER(c) tolower(c)
378 /* How many characters in the character set. */
379 # define CHAR_SET_SIZE 256
383 extern char *re_syntax_table
;
385 # else /* not SYNTAX_TABLE */
387 static char re_syntax_table
[CHAR_SET_SIZE
];
398 bzero (re_syntax_table
, sizeof re_syntax_table
);
400 for (c
= 0; c
< CHAR_SET_SIZE
; ++c
)
402 re_syntax_table
[c
] = Sword
;
404 re_syntax_table
['_'] = Sword
;
409 # endif /* not SYNTAX_TABLE */
411 # define SYNTAX(c) re_syntax_table[(c)]
413 #endif /* not emacs */
416 # define NULL (void *)0
419 /* We remove any previous definition of `SIGN_EXTEND_CHAR',
420 since ours (we hope) works properly with all combinations of
421 machines, compilers, `char' and `unsigned char' argument types.
422 (Per Bothner suggested the basic approach.) */
423 #undef SIGN_EXTEND_CHAR
425 # define SIGN_EXTEND_CHAR(c) ((signed char) (c))
426 #else /* not __STDC__ */
427 /* As in Harbison and Steele. */
428 # define SIGN_EXTEND_CHAR(c) ((((unsigned char) (c)) ^ 128) - 128)
431 /* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we
432 use `alloca' instead of `malloc'. This is because using malloc in
433 re_search* or re_match* could cause memory leaks when C-g is used in
434 Emacs; also, malloc is slower and causes storage fragmentation. On
435 the other hand, malloc is more portable, and easier to debug.
437 Because we sometimes use alloca, some routines have to be macros,
438 not functions -- `alloca'-allocated space disappears at the end of the
439 function it is called in. */
443 # define REGEX_ALLOCATE malloc
444 # define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
445 # define REGEX_FREE free
447 #else /* not REGEX_MALLOC */
449 /* Emacs already defines alloca, sometimes. */
452 /* Make alloca work the best possible way. */
454 # define alloca __builtin_alloca
455 # else /* not __GNUC__ */
458 # endif /* HAVE_ALLOCA_H */
459 # endif /* not __GNUC__ */
461 # endif /* not alloca */
463 # define REGEX_ALLOCATE alloca
465 /* Assumes a `char *destination' variable. */
466 # define REGEX_REALLOCATE(source, osize, nsize) \
467 (destination = (char *) alloca (nsize), \
468 memcpy (destination, source, osize))
470 /* No need to do anything to free, after alloca. */
471 # define REGEX_FREE(arg) ((void)0) /* Do nothing! But inhibit gcc warning. */
473 #endif /* not REGEX_MALLOC */
475 /* Define how to allocate the failure stack. */
477 #if defined REL_ALLOC && defined REGEX_MALLOC
479 # define REGEX_ALLOCATE_STACK(size) \
480 r_alloc (&failure_stack_ptr, (size))
481 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
482 r_re_alloc (&failure_stack_ptr, (nsize))
483 # define REGEX_FREE_STACK(ptr) \
484 r_alloc_free (&failure_stack_ptr)
486 #else /* not using relocating allocator */
490 # define REGEX_ALLOCATE_STACK malloc
491 # define REGEX_REALLOCATE_STACK(source, osize, nsize) realloc (source, nsize)
492 # define REGEX_FREE_STACK free
494 # else /* not REGEX_MALLOC */
496 # define REGEX_ALLOCATE_STACK alloca
498 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
499 REGEX_REALLOCATE (source, osize, nsize)
500 /* No need to explicitly free anything. */
501 # define REGEX_FREE_STACK(arg) ((void)0)
503 # endif /* not REGEX_MALLOC */
504 #endif /* not using relocating allocator */
507 /* True if `size1' is non-NULL and PTR is pointing anywhere inside
508 `string1' or just past its end. This works if PTR is NULL, which is
510 #define FIRST_STRING_P(ptr) \
511 (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
513 /* (Re)Allocate N items of type T using malloc, or fail. */
514 #define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
515 #define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
516 #define RETALLOC_IF(addr, n, t) \
517 if (addr) RETALLOC((addr), (n), t); else (addr) = TALLOC ((n), t)
518 #define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
520 #define BYTEWIDTH 8 /* In bits. */
522 #define STREQ(s1, s2) ((strcmp (s1, s2) == 0))
526 #define MAX(a, b) ((a) > (b) ? (a) : (b))
527 #define MIN(a, b) ((a) < (b) ? (a) : (b))
529 /* Type of source-pattern and string chars. */
530 typedef const unsigned char re_char
;
532 typedef char boolean
;
536 static int re_match_2_internal
_RE_ARGS ((struct re_pattern_buffer
*bufp
,
537 re_char
*string1
, int size1
,
538 re_char
*string2
, int size2
,
540 struct re_registers
*regs
,
543 /* These are the command codes that appear in compiled regular
544 expressions. Some opcodes are followed by argument bytes. A
545 command code can specify any interpretation whatsoever for its
546 arguments. Zero bytes may appear in the compiled regular expression. */
552 /* Succeed right away--no more backtracking. */
555 /* Followed by one byte giving n, then by n literal bytes. */
558 /* Matches any (more or less) character. */
561 /* Matches any one char belonging to specified set. First
562 following byte is number of bitmap bytes. Then come bytes
563 for a bitmap saying which chars are in. Bits in each byte
564 are ordered low-bit-first. A character is in the set if its
565 bit is 1. A character too large to have a bit in the map is
566 automatically not in the set.
568 If the length byte has the 0x80 bit set, then that stuff
569 is followed by a range table:
570 2 bytes of flags for character sets (low 8 bits, high 8 bits)
571 See RANGE_TABLE_WORK_BITS below.
572 2 bytes, the number of pairs that follow (upto 32767)
573 pairs, each 2 multibyte characters,
574 each multibyte character represented as 3 bytes. */
577 /* Same parameters as charset, but match any character that is
578 not one of those specified. */
581 /* Start remembering the text that is matched, for storing in a
582 register. Followed by one byte with the register number, in
583 the range 0 to one less than the pattern buffer's re_nsub
587 /* Stop remembering the text that is matched and store it in a
588 memory register. Followed by one byte with the register
589 number, in the range 0 to one less than `re_nsub' in the
593 /* Match a duplicate of something remembered. Followed by one
594 byte containing the register number. */
597 /* Fail unless at beginning of line. */
600 /* Fail unless at end of line. */
603 /* Succeeds if at beginning of buffer (if emacs) or at beginning
604 of string to be matched (if not). */
607 /* Analogously, for end of buffer/string. */
610 /* Followed by two byte relative address to which to jump. */
613 /* Followed by two-byte relative address of place to resume at
614 in case of failure. */
617 /* Like on_failure_jump, but pushes a placeholder instead of the
618 current string position when executed. */
619 on_failure_keep_string_jump
,
621 /* Just like `on_failure_jump', except that it checks that we
622 don't get stuck in an infinite loop (matching an empty string
624 on_failure_jump_loop
,
626 /* Just like `on_failure_jump_loop', except that it checks for
627 a different kind of loop (the kind that shows up with non-greedy
628 operators). This operation has to be immediately preceded
630 on_failure_jump_nastyloop
,
632 /* A smart `on_failure_jump' used for greedy * and + operators.
633 It analyses the loop before which it is put and if the
634 loop does not require backtracking, it changes itself to
635 `on_failure_keep_string_jump' and short-circuits the loop,
636 else it just defaults to changing itself into `on_failure_jump'.
637 It assumes that it is pointing to just past a `jump'. */
638 on_failure_jump_smart
,
640 /* Followed by two-byte relative address and two-byte number n.
641 After matching N times, jump to the address upon failure.
642 Does not work if N starts at 0: use on_failure_jump_loop
646 /* Followed by two-byte relative address, and two-byte number n.
647 Jump to the address N times, then fail. */
650 /* Set the following two-byte relative address to the
651 subsequent two-byte number. The address *includes* the two
655 wordbeg
, /* Succeeds if at word beginning. */
656 wordend
, /* Succeeds if at word end. */
658 wordbound
, /* Succeeds if at a word boundary. */
659 notwordbound
, /* Succeeds if not at a word boundary. */
661 /* Matches any character whose syntax is specified. Followed by
662 a byte which contains a syntax code, e.g., Sword. */
665 /* Matches any character whose syntax is not that specified. */
669 ,before_dot
, /* Succeeds if before point. */
670 at_dot
, /* Succeeds if at point. */
671 after_dot
, /* Succeeds if after point. */
673 /* Matches any character whose category-set contains the specified
674 category. The operator is followed by a byte which contains a
675 category code (mnemonic ASCII character). */
678 /* Matches any character whose category-set does not contain the
679 specified category. The operator is followed by a byte which
680 contains the category code (mnemonic ASCII character). */
685 /* Common operations on the compiled pattern. */
687 /* Store NUMBER in two contiguous bytes starting at DESTINATION. */
689 #define STORE_NUMBER(destination, number) \
691 (destination)[0] = (number) & 0377; \
692 (destination)[1] = (number) >> 8; \
695 /* Same as STORE_NUMBER, except increment DESTINATION to
696 the byte after where the number is stored. Therefore, DESTINATION
697 must be an lvalue. */
699 #define STORE_NUMBER_AND_INCR(destination, number) \
701 STORE_NUMBER (destination, number); \
702 (destination) += 2; \
705 /* Put into DESTINATION a number stored in two contiguous bytes starting
708 #define EXTRACT_NUMBER(destination, source) \
710 (destination) = *(source) & 0377; \
711 (destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8; \
715 static void extract_number
_RE_ARGS ((int *dest
, re_char
*source
));
717 extract_number (dest
, source
)
721 int temp
= SIGN_EXTEND_CHAR (*(source
+ 1));
722 *dest
= *source
& 0377;
726 # ifndef EXTRACT_MACROS /* To debug the macros. */
727 # undef EXTRACT_NUMBER
728 # define EXTRACT_NUMBER(dest, src) extract_number (&dest, src)
729 # endif /* not EXTRACT_MACROS */
733 /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
734 SOURCE must be an lvalue. */
736 #define EXTRACT_NUMBER_AND_INCR(destination, source) \
738 EXTRACT_NUMBER (destination, source); \
743 static void extract_number_and_incr
_RE_ARGS ((int *destination
,
746 extract_number_and_incr (destination
, source
)
750 extract_number (destination
, *source
);
754 # ifndef EXTRACT_MACROS
755 # undef EXTRACT_NUMBER_AND_INCR
756 # define EXTRACT_NUMBER_AND_INCR(dest, src) \
757 extract_number_and_incr (&dest, &src)
758 # endif /* not EXTRACT_MACROS */
762 /* Store a multibyte character in three contiguous bytes starting
763 DESTINATION, and increment DESTINATION to the byte after where the
764 character is stored. Therefore, DESTINATION must be an lvalue. */
766 #define STORE_CHARACTER_AND_INCR(destination, character) \
768 (destination)[0] = (character) & 0377; \
769 (destination)[1] = ((character) >> 8) & 0377; \
770 (destination)[2] = (character) >> 16; \
771 (destination) += 3; \
774 /* Put into DESTINATION a character stored in three contiguous bytes
775 starting at SOURCE. */
777 #define EXTRACT_CHARACTER(destination, source) \
779 (destination) = ((source)[0] \
780 | ((source)[1] << 8) \
781 | ((source)[2] << 16)); \
785 /* Macros for charset. */
787 /* Size of bitmap of charset P in bytes. P is a start of charset,
788 i.e. *P is (re_opcode_t) charset or (re_opcode_t) charset_not. */
789 #define CHARSET_BITMAP_SIZE(p) ((p)[1] & 0x7F)
791 /* Nonzero if charset P has range table. */
792 #define CHARSET_RANGE_TABLE_EXISTS_P(p) ((p)[1] & 0x80)
794 /* Return the address of range table of charset P. But not the start
795 of table itself, but the before where the number of ranges is
796 stored. `2 +' means to skip re_opcode_t and size of bitmap,
797 and the 2 bytes of flags at the start of the range table. */
798 #define CHARSET_RANGE_TABLE(p) (&(p)[4 + CHARSET_BITMAP_SIZE (p)])
800 /* Extract the bit flags that start a range table. */
801 #define CHARSET_RANGE_TABLE_BITS(p) \
802 ((p)[2 + CHARSET_BITMAP_SIZE (p)] \
803 + (p)[3 + CHARSET_BITMAP_SIZE (p)] * 0x100)
805 /* Test if C is listed in the bitmap of charset P. */
806 #define CHARSET_LOOKUP_BITMAP(p, c) \
807 ((c) < CHARSET_BITMAP_SIZE (p) * BYTEWIDTH \
808 && (p)[2 + (c) / BYTEWIDTH] & (1 << ((c) % BYTEWIDTH)))
810 /* Return the address of end of RANGE_TABLE. COUNT is number of
811 ranges (which is a pair of (start, end)) in the RANGE_TABLE. `* 2'
812 is start of range and end of range. `* 3' is size of each start
814 #define CHARSET_RANGE_TABLE_END(range_table, count) \
815 ((range_table) + (count) * 2 * 3)
817 /* Test if C is in RANGE_TABLE. A flag NOT is negated if C is in.
818 COUNT is number of ranges in RANGE_TABLE. */
819 #define CHARSET_LOOKUP_RANGE_TABLE_RAW(not, c, range_table, count) \
822 re_wchar_t range_start, range_end; \
824 re_char *range_table_end \
825 = CHARSET_RANGE_TABLE_END ((range_table), (count)); \
827 for (p = (range_table); p < range_table_end; p += 2 * 3) \
829 EXTRACT_CHARACTER (range_start, p); \
830 EXTRACT_CHARACTER (range_end, p + 3); \
832 if (range_start <= (c) && (c) <= range_end) \
841 /* Test if C is in range table of CHARSET. The flag NOT is negated if
842 C is listed in it. */
843 #define CHARSET_LOOKUP_RANGE_TABLE(not, c, charset) \
846 /* Number of ranges in range table. */ \
848 re_char *range_table = CHARSET_RANGE_TABLE (charset); \
850 EXTRACT_NUMBER_AND_INCR (count, range_table); \
851 CHARSET_LOOKUP_RANGE_TABLE_RAW ((not), (c), range_table, count); \
855 /* If DEBUG is defined, Regex prints many voluminous messages about what
856 it is doing (if the variable `debug' is nonzero). If linked with the
857 main program in `iregex.c', you can enter patterns and strings
858 interactively. And if linked with the main program in `main.c' and
859 the other test files, you can run the already-written tests. */
863 /* We use standard I/O for debugging. */
866 /* It is useful to test things that ``must'' be true when debugging. */
869 static int debug
= -100000;
871 # define DEBUG_STATEMENT(e) e
872 # define DEBUG_PRINT1(x) if (debug > 0) printf (x)
873 # define DEBUG_PRINT2(x1, x2) if (debug > 0) printf (x1, x2)
874 # define DEBUG_PRINT3(x1, x2, x3) if (debug > 0) printf (x1, x2, x3)
875 # define DEBUG_PRINT4(x1, x2, x3, x4) if (debug > 0) printf (x1, x2, x3, x4)
876 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
877 if (debug > 0) print_partial_compiled_pattern (s, e)
878 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
879 if (debug > 0) print_double_string (w, s1, sz1, s2, sz2)
882 /* Print the fastmap in human-readable form. */
885 print_fastmap (fastmap
)
888 unsigned was_a_range
= 0;
891 while (i
< (1 << BYTEWIDTH
))
897 while (i
< (1 << BYTEWIDTH
) && fastmap
[i
])
913 /* Print a compiled pattern string in human-readable form, starting at
914 the START pointer into it and ending just before the pointer END. */
917 print_partial_compiled_pattern (start
, end
)
931 /* Loop over pattern commands. */
934 printf ("%d:\t", p
- start
);
936 switch ((re_opcode_t
) *p
++)
948 printf ("/exactn/%d", mcnt
);
958 printf ("/start_memory/%d", *p
++);
962 printf ("/stop_memory/%d", *p
++);
966 printf ("/duplicate/%d", *p
++);
976 register int c
, last
= -100;
977 register int in_range
= 0;
978 int length
= CHARSET_BITMAP_SIZE (p
- 1);
979 int has_range_table
= CHARSET_RANGE_TABLE_EXISTS_P (p
- 1);
981 printf ("/charset [%s",
982 (re_opcode_t
) *(p
- 1) == charset_not
? "^" : "");
984 assert (p
+ *p
< pend
);
986 for (c
= 0; c
< 256; c
++)
988 && (p
[1 + (c
/8)] & (1 << (c
% 8))))
990 /* Are we starting a range? */
991 if (last
+ 1 == c
&& ! in_range
)
996 /* Have we broken a range? */
997 else if (last
+ 1 != c
&& in_range
)
1016 if (has_range_table
)
1019 printf ("has-range-table");
1021 /* ??? Should print the range table; for now, just skip it. */
1022 p
+= 2; /* skip range table bits */
1023 EXTRACT_NUMBER_AND_INCR (count
, p
);
1024 p
= CHARSET_RANGE_TABLE_END (p
, count
);
1030 printf ("/begline");
1034 printf ("/endline");
1037 case on_failure_jump
:
1038 extract_number_and_incr (&mcnt
, &p
);
1039 printf ("/on_failure_jump to %d", p
+ mcnt
- start
);
1042 case on_failure_keep_string_jump
:
1043 extract_number_and_incr (&mcnt
, &p
);
1044 printf ("/on_failure_keep_string_jump to %d", p
+ mcnt
- start
);
1047 case on_failure_jump_nastyloop
:
1048 extract_number_and_incr (&mcnt
, &p
);
1049 printf ("/on_failure_jump_nastyloop to %d", p
+ mcnt
- start
);
1052 case on_failure_jump_loop
:
1053 extract_number_and_incr (&mcnt
, &p
);
1054 printf ("/on_failure_jump_loop to %d", p
+ mcnt
- start
);
1057 case on_failure_jump_smart
:
1058 extract_number_and_incr (&mcnt
, &p
);
1059 printf ("/on_failure_jump_smart to %d", p
+ mcnt
- start
);
1063 extract_number_and_incr (&mcnt
, &p
);
1064 printf ("/jump to %d", p
+ mcnt
- start
);
1068 extract_number_and_incr (&mcnt
, &p
);
1069 extract_number_and_incr (&mcnt2
, &p
);
1070 printf ("/succeed_n to %d, %d times", p
- 2 + mcnt
- start
, mcnt2
);
1074 extract_number_and_incr (&mcnt
, &p
);
1075 extract_number_and_incr (&mcnt2
, &p
);
1076 printf ("/jump_n to %d, %d times", p
- 2 + mcnt
- start
, mcnt2
);
1080 extract_number_and_incr (&mcnt
, &p
);
1081 extract_number_and_incr (&mcnt2
, &p
);
1082 printf ("/set_number_at location %d to %d", p
- 2 + mcnt
- start
, mcnt2
);
1086 printf ("/wordbound");
1090 printf ("/notwordbound");
1094 printf ("/wordbeg");
1098 printf ("/wordend");
1101 printf ("/syntaxspec");
1103 printf ("/%d", mcnt
);
1107 printf ("/notsyntaxspec");
1109 printf ("/%d", mcnt
);
1114 printf ("/before_dot");
1122 printf ("/after_dot");
1126 printf ("/categoryspec");
1128 printf ("/%d", mcnt
);
1131 case notcategoryspec
:
1132 printf ("/notcategoryspec");
1134 printf ("/%d", mcnt
);
1147 printf ("?%d", *(p
-1));
1153 printf ("%d:\tend of pattern.\n", p
- start
);
1158 print_compiled_pattern (bufp
)
1159 struct re_pattern_buffer
*bufp
;
1161 re_char
*buffer
= bufp
->buffer
;
1163 print_partial_compiled_pattern (buffer
, buffer
+ bufp
->used
);
1164 printf ("%ld bytes used/%ld bytes allocated.\n",
1165 bufp
->used
, bufp
->allocated
);
1167 if (bufp
->fastmap_accurate
&& bufp
->fastmap
)
1169 printf ("fastmap: ");
1170 print_fastmap (bufp
->fastmap
);
1173 printf ("re_nsub: %d\t", bufp
->re_nsub
);
1174 printf ("regs_alloc: %d\t", bufp
->regs_allocated
);
1175 printf ("can_be_null: %d\t", bufp
->can_be_null
);
1176 printf ("no_sub: %d\t", bufp
->no_sub
);
1177 printf ("not_bol: %d\t", bufp
->not_bol
);
1178 printf ("not_eol: %d\t", bufp
->not_eol
);
1179 printf ("syntax: %lx\n", bufp
->syntax
);
1181 /* Perhaps we should print the translate table? */
1186 print_double_string (where
, string1
, size1
, string2
, size2
)
1199 if (FIRST_STRING_P (where
))
1201 for (this_char
= where
- string1
; this_char
< size1
; this_char
++)
1202 putchar (string1
[this_char
]);
1207 for (this_char
= where
- string2
; this_char
< size2
; this_char
++)
1208 putchar (string2
[this_char
]);
1212 #else /* not DEBUG */
1217 # define DEBUG_STATEMENT(e)
1218 # define DEBUG_PRINT1(x)
1219 # define DEBUG_PRINT2(x1, x2)
1220 # define DEBUG_PRINT3(x1, x2, x3)
1221 # define DEBUG_PRINT4(x1, x2, x3, x4)
1222 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
1223 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
1225 #endif /* not DEBUG */
1227 /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
1228 also be assigned to arbitrarily: each pattern buffer stores its own
1229 syntax, so it can be changed between regex compilations. */
1230 /* This has no initializer because initialized variables in Emacs
1231 become read-only after dumping. */
1232 reg_syntax_t re_syntax_options
;
1235 /* Specify the precise syntax of regexps for compilation. This provides
1236 for compatibility for various utilities which historically have
1237 different, incompatible syntaxes.
1239 The argument SYNTAX is a bit mask comprised of the various bits
1240 defined in regex.h. We return the old syntax. */
1243 re_set_syntax (syntax
)
1244 reg_syntax_t syntax
;
1246 reg_syntax_t ret
= re_syntax_options
;
1248 re_syntax_options
= syntax
;
1251 WEAK_ALIAS (__re_set_syntax
, re_set_syntax
)
1253 /* This table gives an error message for each of the error codes listed
1254 in regex.h. Obviously the order here has to be same as there.
1255 POSIX doesn't require that we do anything for REG_NOERROR,
1256 but why not be nice? */
1258 static const char *re_error_msgid
[] =
1260 gettext_noop ("Success"), /* REG_NOERROR */
1261 gettext_noop ("No match"), /* REG_NOMATCH */
1262 gettext_noop ("Invalid regular expression"), /* REG_BADPAT */
1263 gettext_noop ("Invalid collation character"), /* REG_ECOLLATE */
1264 gettext_noop ("Invalid character class name"), /* REG_ECTYPE */
1265 gettext_noop ("Trailing backslash"), /* REG_EESCAPE */
1266 gettext_noop ("Invalid back reference"), /* REG_ESUBREG */
1267 gettext_noop ("Unmatched [ or [^"), /* REG_EBRACK */
1268 gettext_noop ("Unmatched ( or \\("), /* REG_EPAREN */
1269 gettext_noop ("Unmatched \\{"), /* REG_EBRACE */
1270 gettext_noop ("Invalid content of \\{\\}"), /* REG_BADBR */
1271 gettext_noop ("Invalid range end"), /* REG_ERANGE */
1272 gettext_noop ("Memory exhausted"), /* REG_ESPACE */
1273 gettext_noop ("Invalid preceding regular expression"), /* REG_BADRPT */
1274 gettext_noop ("Premature end of regular expression"), /* REG_EEND */
1275 gettext_noop ("Regular expression too big"), /* REG_ESIZE */
1276 gettext_noop ("Unmatched ) or \\)"), /* REG_ERPAREN */
1279 /* Avoiding alloca during matching, to placate r_alloc. */
1281 /* Define MATCH_MAY_ALLOCATE unless we need to make sure that the
1282 searching and matching functions should not call alloca. On some
1283 systems, alloca is implemented in terms of malloc, and if we're
1284 using the relocating allocator routines, then malloc could cause a
1285 relocation, which might (if the strings being searched are in the
1286 ralloc heap) shift the data out from underneath the regexp
1289 Here's another reason to avoid allocation: Emacs
1290 processes input from X in a signal handler; processing X input may
1291 call malloc; if input arrives while a matching routine is calling
1292 malloc, then we're scrod. But Emacs can't just block input while
1293 calling matching routines; then we don't notice interrupts when
1294 they come in. So, Emacs blocks input around all regexp calls
1295 except the matching calls, which it leaves unprotected, in the
1296 faith that they will not malloc. */
1298 /* Normally, this is fine. */
1299 #define MATCH_MAY_ALLOCATE
1301 /* When using GNU C, we are not REALLY using the C alloca, no matter
1302 what config.h may say. So don't take precautions for it. */
1307 /* The match routines may not allocate if (1) they would do it with malloc
1308 and (2) it's not safe for them to use malloc.
1309 Note that if REL_ALLOC is defined, matching would not use malloc for the
1310 failure stack, but we would still use it for the register vectors;
1311 so REL_ALLOC should not affect this. */
1312 #if (defined C_ALLOCA || defined REGEX_MALLOC) && defined emacs
1313 # undef MATCH_MAY_ALLOCATE
1317 /* Failure stack declarations and macros; both re_compile_fastmap and
1318 re_match_2 use a failure stack. These have to be macros because of
1319 REGEX_ALLOCATE_STACK. */
1322 /* Approximate number of failure points for which to initially allocate space
1323 when matching. If this number is exceeded, we allocate more
1324 space, so it is not a hard limit. */
1325 #ifndef INIT_FAILURE_ALLOC
1326 # define INIT_FAILURE_ALLOC 20
1329 /* Roughly the maximum number of failure points on the stack. Would be
1330 exactly that if always used TYPICAL_FAILURE_SIZE items each time we failed.
1331 This is a variable only so users of regex can assign to it; we never
1332 change it ourselves. We always multiply it by TYPICAL_FAILURE_SIZE
1333 before using it, so it should probably be a byte-count instead. */
1334 # if defined MATCH_MAY_ALLOCATE
1335 /* Note that 4400 was enough to cause a crash on Alpha OSF/1,
1336 whose default stack limit is 2mb. In order for a larger
1337 value to work reliably, you have to try to make it accord
1338 with the process stack limit. */
1339 size_t re_max_failures
= 40000;
1341 size_t re_max_failures
= 4000;
1344 union fail_stack_elt
1347 /* This should be the biggest `int' that's no bigger than a pointer. */
1351 typedef union fail_stack_elt fail_stack_elt_t
;
1355 fail_stack_elt_t
*stack
;
1357 size_t avail
; /* Offset of next open position. */
1358 size_t frame
; /* Offset of the cur constructed frame. */
1361 #define FAIL_STACK_EMPTY() (fail_stack.frame == 0)
1362 #define FAIL_STACK_FULL() (fail_stack.avail == fail_stack.size)
1365 /* Define macros to initialize and free the failure stack.
1366 Do `return -2' if the alloc fails. */
1368 #ifdef MATCH_MAY_ALLOCATE
1369 # define INIT_FAIL_STACK() \
1371 fail_stack.stack = (fail_stack_elt_t *) \
1372 REGEX_ALLOCATE_STACK (INIT_FAILURE_ALLOC * TYPICAL_FAILURE_SIZE \
1373 * sizeof (fail_stack_elt_t)); \
1375 if (fail_stack.stack == NULL) \
1378 fail_stack.size = INIT_FAILURE_ALLOC; \
1379 fail_stack.avail = 0; \
1380 fail_stack.frame = 0; \
1383 # define RESET_FAIL_STACK() REGEX_FREE_STACK (fail_stack.stack)
1385 # define INIT_FAIL_STACK() \
1387 fail_stack.avail = 0; \
1388 fail_stack.frame = 0; \
1391 # define RESET_FAIL_STACK() ((void)0)
1395 /* Double the size of FAIL_STACK, up to a limit
1396 which allows approximately `re_max_failures' items.
1398 Return 1 if succeeds, and 0 if either ran out of memory
1399 allocating space for it or it was already too large.
1401 REGEX_REALLOCATE_STACK requires `destination' be declared. */
1403 /* Factor to increase the failure stack size by
1404 when we increase it.
1405 This used to be 2, but 2 was too wasteful
1406 because the old discarded stacks added up to as much space
1407 were as ultimate, maximum-size stack. */
1408 #define FAIL_STACK_GROWTH_FACTOR 4
1410 #define GROW_FAIL_STACK(fail_stack) \
1411 (((fail_stack).size * sizeof (fail_stack_elt_t) \
1412 >= re_max_failures * TYPICAL_FAILURE_SIZE) \
1414 : ((fail_stack).stack \
1415 = (fail_stack_elt_t *) \
1416 REGEX_REALLOCATE_STACK ((fail_stack).stack, \
1417 (fail_stack).size * sizeof (fail_stack_elt_t), \
1418 MIN (re_max_failures * TYPICAL_FAILURE_SIZE, \
1419 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1420 * FAIL_STACK_GROWTH_FACTOR))), \
1422 (fail_stack).stack == NULL \
1424 : ((fail_stack).size \
1425 = (MIN (re_max_failures * TYPICAL_FAILURE_SIZE, \
1426 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1427 * FAIL_STACK_GROWTH_FACTOR)) \
1428 / sizeof (fail_stack_elt_t)), \
1432 /* Push a pointer value onto the failure stack.
1433 Assumes the variable `fail_stack'. Probably should only
1434 be called from within `PUSH_FAILURE_POINT'. */
1435 #define PUSH_FAILURE_POINTER(item) \
1436 fail_stack.stack[fail_stack.avail++].pointer = (item)
1438 /* This pushes an integer-valued item onto the failure stack.
1439 Assumes the variable `fail_stack'. Probably should only
1440 be called from within `PUSH_FAILURE_POINT'. */
1441 #define PUSH_FAILURE_INT(item) \
1442 fail_stack.stack[fail_stack.avail++].integer = (item)
1444 /* Push a fail_stack_elt_t value onto the failure stack.
1445 Assumes the variable `fail_stack'. Probably should only
1446 be called from within `PUSH_FAILURE_POINT'. */
1447 #define PUSH_FAILURE_ELT(item) \
1448 fail_stack.stack[fail_stack.avail++] = (item)
1450 /* These three POP... operations complement the three PUSH... operations.
1451 All assume that `fail_stack' is nonempty. */
1452 #define POP_FAILURE_POINTER() fail_stack.stack[--fail_stack.avail].pointer
1453 #define POP_FAILURE_INT() fail_stack.stack[--fail_stack.avail].integer
1454 #define POP_FAILURE_ELT() fail_stack.stack[--fail_stack.avail]
1456 /* Individual items aside from the registers. */
1457 #define NUM_NONREG_ITEMS 3
1459 /* Used to examine the stack (to detect infinite loops). */
1460 #define FAILURE_PAT(h) fail_stack.stack[(h) - 1].pointer
1461 #define FAILURE_STR(h) (fail_stack.stack[(h) - 2].pointer)
1462 #define NEXT_FAILURE_HANDLE(h) fail_stack.stack[(h) - 3].integer
1463 #define TOP_FAILURE_HANDLE() fail_stack.frame
1466 #define ENSURE_FAIL_STACK(space) \
1467 while (REMAINING_AVAIL_SLOTS <= space) { \
1468 if (!GROW_FAIL_STACK (fail_stack)) \
1470 DEBUG_PRINT2 ("\n Doubled stack; size now: %d\n", (fail_stack).size);\
1471 DEBUG_PRINT2 (" slots available: %d\n", REMAINING_AVAIL_SLOTS);\
1474 /* Push register NUM onto the stack. */
1475 #define PUSH_FAILURE_REG(num) \
1477 char *destination; \
1478 ENSURE_FAIL_STACK(3); \
1479 DEBUG_PRINT4 (" Push reg %d (spanning %p -> %p)\n", \
1480 num, regstart[num], regend[num]); \
1481 PUSH_FAILURE_POINTER (regstart[num]); \
1482 PUSH_FAILURE_POINTER (regend[num]); \
1483 PUSH_FAILURE_INT (num); \
1486 /* Change the counter's value to VAL, but make sure that it will
1487 be reset when backtracking. */
1488 #define PUSH_NUMBER(ptr,val) \
1490 char *destination; \
1492 ENSURE_FAIL_STACK(3); \
1493 EXTRACT_NUMBER (c, ptr); \
1494 DEBUG_PRINT4 (" Push number %p = %d -> %d\n", ptr, c, val); \
1495 PUSH_FAILURE_INT (c); \
1496 PUSH_FAILURE_POINTER (ptr); \
1497 PUSH_FAILURE_INT (-1); \
1498 STORE_NUMBER (ptr, val); \
1501 /* Pop a saved register off the stack. */
1502 #define POP_FAILURE_REG_OR_COUNT() \
1504 int reg = POP_FAILURE_INT (); \
1507 /* It's a counter. */ \
1508 /* Here, we discard `const', making re_match non-reentrant. */ \
1509 unsigned char *ptr = (unsigned char*) POP_FAILURE_POINTER (); \
1510 reg = POP_FAILURE_INT (); \
1511 STORE_NUMBER (ptr, reg); \
1512 DEBUG_PRINT3 (" Pop counter %p = %d\n", ptr, reg); \
1516 regend[reg] = POP_FAILURE_POINTER (); \
1517 regstart[reg] = POP_FAILURE_POINTER (); \
1518 DEBUG_PRINT4 (" Pop reg %d (spanning %p -> %p)\n", \
1519 reg, regstart[reg], regend[reg]); \
1523 /* Check that we are not stuck in an infinite loop. */
1524 #define CHECK_INFINITE_LOOP(pat_cur, string_place) \
1526 int failure = TOP_FAILURE_HANDLE(); \
1527 /* Check for infinite matching loops */ \
1528 while (failure > 0 && \
1529 (FAILURE_STR (failure) == string_place \
1530 || FAILURE_STR (failure) == NULL)) \
1532 assert (FAILURE_PAT (failure) >= bufp->buffer \
1533 && FAILURE_PAT (failure) <= bufp->buffer + bufp->used); \
1534 if (FAILURE_PAT (failure) == pat_cur) \
1536 DEBUG_PRINT2 (" Other pattern: %p\n", FAILURE_PAT (failure)); \
1537 failure = NEXT_FAILURE_HANDLE(failure); \
1539 DEBUG_PRINT2 (" Other string: %p\n", FAILURE_STR (failure)); \
1542 /* Push the information about the state we will need
1543 if we ever fail back to it.
1545 Requires variables fail_stack, regstart, regend and
1546 num_regs be declared. GROW_FAIL_STACK requires `destination' be
1549 Does `return FAILURE_CODE' if runs out of memory. */
1551 #define PUSH_FAILURE_POINT(pattern, string_place) \
1553 char *destination; \
1554 /* Must be int, so when we don't save any registers, the arithmetic \
1555 of 0 + -1 isn't done as unsigned. */ \
1557 DEBUG_STATEMENT (nfailure_points_pushed++); \
1558 DEBUG_PRINT1 ("\nPUSH_FAILURE_POINT:\n"); \
1559 DEBUG_PRINT2 (" Before push, next avail: %d\n", (fail_stack).avail); \
1560 DEBUG_PRINT2 (" size: %d\n", (fail_stack).size);\
1562 ENSURE_FAIL_STACK (NUM_NONREG_ITEMS); \
1564 DEBUG_PRINT1 ("\n"); \
1566 DEBUG_PRINT2 (" Push frame index: %d\n", fail_stack.frame); \
1567 PUSH_FAILURE_INT (fail_stack.frame); \
1569 DEBUG_PRINT2 (" Push string %p: `", string_place); \
1570 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, size2);\
1571 DEBUG_PRINT1 ("'\n"); \
1572 PUSH_FAILURE_POINTER (string_place); \
1574 DEBUG_PRINT2 (" Push pattern %p: ", pattern); \
1575 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern, pend); \
1576 PUSH_FAILURE_POINTER (pattern); \
1578 /* Close the frame by moving the frame pointer past it. */ \
1579 fail_stack.frame = fail_stack.avail; \
1582 /* Estimate the size of data pushed by a typical failure stack entry.
1583 An estimate is all we need, because all we use this for
1584 is to choose a limit for how big to make the failure stack. */
1585 /* BEWARE, the value `20' is hard-coded in emacs.c:main(). */
1586 #define TYPICAL_FAILURE_SIZE 20
1588 /* How many items can still be added to the stack without overflowing it. */
1589 #define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
1592 /* Pops what PUSH_FAIL_STACK pushes.
1594 We restore into the parameters, all of which should be lvalues:
1595 STR -- the saved data position.
1596 PAT -- the saved pattern position.
1597 REGSTART, REGEND -- arrays of string positions.
1599 Also assumes the variables `fail_stack' and (if debugging), `bufp',
1600 `pend', `string1', `size1', `string2', and `size2'. */
1602 #define POP_FAILURE_POINT(str, pat) \
1604 assert (!FAIL_STACK_EMPTY ()); \
1606 /* Remove failure points and point to how many regs pushed. */ \
1607 DEBUG_PRINT1 ("POP_FAILURE_POINT:\n"); \
1608 DEBUG_PRINT2 (" Before pop, next avail: %d\n", fail_stack.avail); \
1609 DEBUG_PRINT2 (" size: %d\n", fail_stack.size); \
1611 /* Pop the saved registers. */ \
1612 while (fail_stack.frame < fail_stack.avail) \
1613 POP_FAILURE_REG_OR_COUNT (); \
1615 pat = POP_FAILURE_POINTER (); \
1616 DEBUG_PRINT2 (" Popping pattern %p: ", pat); \
1617 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
1619 /* If the saved string location is NULL, it came from an \
1620 on_failure_keep_string_jump opcode, and we want to throw away the \
1621 saved NULL, thus retaining our current position in the string. */ \
1622 str = POP_FAILURE_POINTER (); \
1623 DEBUG_PRINT2 (" Popping string %p: `", str); \
1624 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
1625 DEBUG_PRINT1 ("'\n"); \
1627 fail_stack.frame = POP_FAILURE_INT (); \
1628 DEBUG_PRINT2 (" Popping frame index: %d\n", fail_stack.frame); \
1630 assert (fail_stack.avail >= 0); \
1631 assert (fail_stack.frame <= fail_stack.avail); \
1633 DEBUG_STATEMENT (nfailure_points_popped++); \
1634 } while (0) /* POP_FAILURE_POINT */
1638 /* Registers are set to a sentinel when they haven't yet matched. */
1639 #define REG_UNSET(e) ((e) == NULL)
1641 /* Subroutine declarations and macros for regex_compile. */
1643 static reg_errcode_t regex_compile
_RE_ARGS ((re_char
*pattern
, size_t size
,
1644 reg_syntax_t syntax
,
1645 struct re_pattern_buffer
*bufp
));
1646 static void store_op1
_RE_ARGS ((re_opcode_t op
, unsigned char *loc
, int arg
));
1647 static void store_op2
_RE_ARGS ((re_opcode_t op
, unsigned char *loc
,
1648 int arg1
, int arg2
));
1649 static void insert_op1
_RE_ARGS ((re_opcode_t op
, unsigned char *loc
,
1650 int arg
, unsigned char *end
));
1651 static void insert_op2
_RE_ARGS ((re_opcode_t op
, unsigned char *loc
,
1652 int arg1
, int arg2
, unsigned char *end
));
1653 static boolean at_begline_loc_p
_RE_ARGS ((re_char
*pattern
,
1655 reg_syntax_t syntax
));
1656 static boolean at_endline_loc_p
_RE_ARGS ((re_char
*p
,
1658 reg_syntax_t syntax
));
1659 static re_char
*skip_one_char
_RE_ARGS ((re_char
*p
));
1660 static int analyse_first
_RE_ARGS ((re_char
*p
, re_char
*pend
,
1661 char *fastmap
, const int multibyte
));
1663 /* Fetch the next character in the uncompiled pattern---translating it
1665 #define PATFETCH(c) \
1668 c = TRANSLATE (c); \
1671 /* Fetch the next character in the uncompiled pattern, with no
1673 #define PATFETCH_RAW(c) \
1676 if (p == pend) return REG_EEND; \
1677 c = RE_STRING_CHAR_AND_LENGTH (p, pend - p, len); \
1682 /* If `translate' is non-null, return translate[D], else just D. We
1683 cast the subscript to translate because some data is declared as
1684 `char *', to avoid warnings when a string constant is passed. But
1685 when we use a character as a subscript we must make it unsigned. */
1687 # define TRANSLATE(d) \
1688 (RE_TRANSLATE_P (translate) ? RE_TRANSLATE (translate, (d)) : (d))
1692 /* Macros for outputting the compiled pattern into `buffer'. */
1694 /* If the buffer isn't allocated when it comes in, use this. */
1695 #define INIT_BUF_SIZE 32
1697 /* Make sure we have at least N more bytes of space in buffer. */
1698 #define GET_BUFFER_SPACE(n) \
1699 while ((size_t) (b - bufp->buffer + (n)) > bufp->allocated) \
1702 /* Make sure we have one more byte of buffer space and then add C to it. */
1703 #define BUF_PUSH(c) \
1705 GET_BUFFER_SPACE (1); \
1706 *b++ = (unsigned char) (c); \
1710 /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
1711 #define BUF_PUSH_2(c1, c2) \
1713 GET_BUFFER_SPACE (2); \
1714 *b++ = (unsigned char) (c1); \
1715 *b++ = (unsigned char) (c2); \
1719 /* As with BUF_PUSH_2, except for three bytes. */
1720 #define BUF_PUSH_3(c1, c2, c3) \
1722 GET_BUFFER_SPACE (3); \
1723 *b++ = (unsigned char) (c1); \
1724 *b++ = (unsigned char) (c2); \
1725 *b++ = (unsigned char) (c3); \
1729 /* Store a jump with opcode OP at LOC to location TO. We store a
1730 relative address offset by the three bytes the jump itself occupies. */
1731 #define STORE_JUMP(op, loc, to) \
1732 store_op1 (op, loc, (to) - (loc) - 3)
1734 /* Likewise, for a two-argument jump. */
1735 #define STORE_JUMP2(op, loc, to, arg) \
1736 store_op2 (op, loc, (to) - (loc) - 3, arg)
1738 /* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
1739 #define INSERT_JUMP(op, loc, to) \
1740 insert_op1 (op, loc, (to) - (loc) - 3, b)
1742 /* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
1743 #define INSERT_JUMP2(op, loc, to, arg) \
1744 insert_op2 (op, loc, (to) - (loc) - 3, arg, b)
1747 /* This is not an arbitrary limit: the arguments which represent offsets
1748 into the pattern are two bytes long. So if 2^16 bytes turns out to
1749 be too small, many things would have to change. */
1750 /* Any other compiler which, like MSC, has allocation limit below 2^16
1751 bytes will have to use approach similar to what was done below for
1752 MSC and drop MAX_BUF_SIZE a bit. Otherwise you may end up
1753 reallocating to 0 bytes. Such thing is not going to work too well.
1754 You have been warned!! */
1755 #if defined _MSC_VER && !defined WIN32
1756 /* Microsoft C 16-bit versions limit malloc to approx 65512 bytes. */
1757 # define MAX_BUF_SIZE 65500L
1759 # define MAX_BUF_SIZE (1L << 16)
1762 /* Extend the buffer by twice its current size via realloc and
1763 reset the pointers that pointed into the old block to point to the
1764 correct places in the new one. If extending the buffer results in it
1765 being larger than MAX_BUF_SIZE, then flag memory exhausted. */
1766 #if __BOUNDED_POINTERS__
1767 # define SET_HIGH_BOUND(P) (__ptrhigh (P) = __ptrlow (P) + bufp->allocated)
1768 # define MOVE_BUFFER_POINTER(P) \
1769 (__ptrlow (P) += incr, SET_HIGH_BOUND (P), __ptrvalue (P) += incr)
1770 # define ELSE_EXTEND_BUFFER_HIGH_BOUND \
1773 SET_HIGH_BOUND (b); \
1774 SET_HIGH_BOUND (begalt); \
1775 if (fixup_alt_jump) \
1776 SET_HIGH_BOUND (fixup_alt_jump); \
1778 SET_HIGH_BOUND (laststart); \
1779 if (pending_exact) \
1780 SET_HIGH_BOUND (pending_exact); \
1783 # define MOVE_BUFFER_POINTER(P) (P) += incr
1784 # define ELSE_EXTEND_BUFFER_HIGH_BOUND
1786 #define EXTEND_BUFFER() \
1788 re_char *old_buffer = bufp->buffer; \
1789 if (bufp->allocated == MAX_BUF_SIZE) \
1791 bufp->allocated <<= 1; \
1792 if (bufp->allocated > MAX_BUF_SIZE) \
1793 bufp->allocated = MAX_BUF_SIZE; \
1794 RETALLOC (bufp->buffer, bufp->allocated, unsigned char); \
1795 if (bufp->buffer == NULL) \
1796 return REG_ESPACE; \
1797 /* If the buffer moved, move all the pointers into it. */ \
1798 if (old_buffer != bufp->buffer) \
1800 int incr = bufp->buffer - old_buffer; \
1801 MOVE_BUFFER_POINTER (b); \
1802 MOVE_BUFFER_POINTER (begalt); \
1803 if (fixup_alt_jump) \
1804 MOVE_BUFFER_POINTER (fixup_alt_jump); \
1806 MOVE_BUFFER_POINTER (laststart); \
1807 if (pending_exact) \
1808 MOVE_BUFFER_POINTER (pending_exact); \
1810 ELSE_EXTEND_BUFFER_HIGH_BOUND \
1814 /* Since we have one byte reserved for the register number argument to
1815 {start,stop}_memory, the maximum number of groups we can report
1816 things about is what fits in that byte. */
1817 #define MAX_REGNUM 255
1819 /* But patterns can have more than `MAX_REGNUM' registers. We just
1820 ignore the excess. */
1821 typedef unsigned regnum_t
;
1824 /* Macros for the compile stack. */
1826 /* Since offsets can go either forwards or backwards, this type needs to
1827 be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
1828 /* int may be not enough when sizeof(int) == 2. */
1829 typedef long pattern_offset_t
;
1833 pattern_offset_t begalt_offset
;
1834 pattern_offset_t fixup_alt_jump
;
1835 pattern_offset_t laststart_offset
;
1837 } compile_stack_elt_t
;
1842 compile_stack_elt_t
*stack
;
1844 unsigned avail
; /* Offset of next open position. */
1845 } compile_stack_type
;
1848 #define INIT_COMPILE_STACK_SIZE 32
1850 #define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
1851 #define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
1853 /* The next available element. */
1854 #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
1857 /* Structure to manage work area for range table. */
1858 struct range_table_work_area
1860 int *table
; /* actual work area. */
1861 int allocated
; /* allocated size for work area in bytes. */
1862 int used
; /* actually used size in words. */
1863 int bits
; /* flag to record character classes */
1866 /* Make sure that WORK_AREA can hold more N multibyte characters. */
1867 #define EXTEND_RANGE_TABLE_WORK_AREA(work_area, n) \
1869 if (((work_area).used + (n)) * sizeof (int) > (work_area).allocated) \
1871 (work_area).allocated += 16 * sizeof (int); \
1872 if ((work_area).table) \
1874 = (int *) realloc ((work_area).table, (work_area).allocated); \
1877 = (int *) malloc ((work_area).allocated); \
1878 if ((work_area).table == 0) \
1879 FREE_STACK_RETURN (REG_ESPACE); \
1883 #define SET_RANGE_TABLE_WORK_AREA_BIT(work_area, bit) \
1884 (work_area).bits |= (bit)
1886 /* Bits used to implement the multibyte-part of the various character classes
1887 such as [:alnum:] in a charset's range table. */
1888 #define BIT_WORD 0x1
1889 #define BIT_LOWER 0x2
1890 #define BIT_PUNCT 0x4
1891 #define BIT_SPACE 0x8
1892 #define BIT_UPPER 0x10
1893 #define BIT_MULTIBYTE 0x20
1895 /* Set a range (RANGE_START, RANGE_END) to WORK_AREA. */
1896 #define SET_RANGE_TABLE_WORK_AREA(work_area, range_start, range_end) \
1898 EXTEND_RANGE_TABLE_WORK_AREA ((work_area), 2); \
1899 (work_area).table[(work_area).used++] = (range_start); \
1900 (work_area).table[(work_area).used++] = (range_end); \
1903 /* Free allocated memory for WORK_AREA. */
1904 #define FREE_RANGE_TABLE_WORK_AREA(work_area) \
1906 if ((work_area).table) \
1907 free ((work_area).table); \
1910 #define CLEAR_RANGE_TABLE_WORK_USED(work_area) ((work_area).used = 0, (work_area).bits = 0)
1911 #define RANGE_TABLE_WORK_USED(work_area) ((work_area).used)
1912 #define RANGE_TABLE_WORK_BITS(work_area) ((work_area).bits)
1913 #define RANGE_TABLE_WORK_ELT(work_area, i) ((work_area).table[i])
1916 /* Set the bit for character C in a list. */
1917 #define SET_LIST_BIT(c) (b[((c)) / BYTEWIDTH] |= 1 << ((c) % BYTEWIDTH))
1920 /* Get the next unsigned number in the uncompiled pattern. */
1921 #define GET_UNSIGNED_NUMBER(num) \
1922 do { if (p != pend) \
1925 while ('0' <= c && c <= '9') \
1929 num = num * 10 + c - '0'; \
1937 #if WIDE_CHAR_SUPPORT
1938 /* The GNU C library provides support for user-defined character classes
1939 and the functions from ISO C amendement 1. */
1940 # ifdef CHARCLASS_NAME_MAX
1941 # define CHAR_CLASS_MAX_LENGTH CHARCLASS_NAME_MAX
1943 /* This shouldn't happen but some implementation might still have this
1944 problem. Use a reasonable default value. */
1945 # define CHAR_CLASS_MAX_LENGTH 256
1947 typedef wctype_t re_wctype_t
;
1948 typedef wchar_t re_wchar_t
;
1949 # define re_wctype wctype
1950 # define re_iswctype iswctype
1951 # define re_wctype_to_bit(cc) 0
1953 # define CHAR_CLASS_MAX_LENGTH 9 /* Namely, `multibyte'. */
1956 /* Character classes. */
1957 typedef enum { RECC_ERROR
= 0,
1958 RECC_ALNUM
, RECC_ALPHA
, RECC_WORD
,
1959 RECC_GRAPH
, RECC_PRINT
,
1960 RECC_LOWER
, RECC_UPPER
,
1961 RECC_PUNCT
, RECC_CNTRL
,
1962 RECC_DIGIT
, RECC_XDIGIT
,
1963 RECC_BLANK
, RECC_SPACE
,
1964 RECC_MULTIBYTE
, RECC_NONASCII
,
1965 RECC_ASCII
, RECC_UNIBYTE
1968 typedef int re_wchar_t
;
1970 /* Map a string to the char class it names (if any). */
1975 const char *string
= str
;
1976 if (STREQ (string
, "alnum")) return RECC_ALNUM
;
1977 else if (STREQ (string
, "alpha")) return RECC_ALPHA
;
1978 else if (STREQ (string
, "word")) return RECC_WORD
;
1979 else if (STREQ (string
, "ascii")) return RECC_ASCII
;
1980 else if (STREQ (string
, "nonascii")) return RECC_NONASCII
;
1981 else if (STREQ (string
, "graph")) return RECC_GRAPH
;
1982 else if (STREQ (string
, "lower")) return RECC_LOWER
;
1983 else if (STREQ (string
, "print")) return RECC_PRINT
;
1984 else if (STREQ (string
, "punct")) return RECC_PUNCT
;
1985 else if (STREQ (string
, "space")) return RECC_SPACE
;
1986 else if (STREQ (string
, "upper")) return RECC_UPPER
;
1987 else if (STREQ (string
, "unibyte")) return RECC_UNIBYTE
;
1988 else if (STREQ (string
, "multibyte")) return RECC_MULTIBYTE
;
1989 else if (STREQ (string
, "digit")) return RECC_DIGIT
;
1990 else if (STREQ (string
, "xdigit")) return RECC_XDIGIT
;
1991 else if (STREQ (string
, "cntrl")) return RECC_CNTRL
;
1992 else if (STREQ (string
, "blank")) return RECC_BLANK
;
1996 /* True iff CH is in the char class CC. */
1998 re_iswctype (ch
, cc
)
2004 case RECC_ALNUM
: return ISALNUM (ch
);
2005 case RECC_ALPHA
: return ISALPHA (ch
);
2006 case RECC_BLANK
: return ISBLANK (ch
);
2007 case RECC_CNTRL
: return ISCNTRL (ch
);
2008 case RECC_DIGIT
: return ISDIGIT (ch
);
2009 case RECC_GRAPH
: return ISGRAPH (ch
);
2010 case RECC_LOWER
: return ISLOWER (ch
);
2011 case RECC_PRINT
: return ISPRINT (ch
);
2012 case RECC_PUNCT
: return ISPUNCT (ch
);
2013 case RECC_SPACE
: return ISSPACE (ch
);
2014 case RECC_UPPER
: return ISUPPER (ch
);
2015 case RECC_XDIGIT
: return ISXDIGIT (ch
);
2016 case RECC_ASCII
: return IS_REAL_ASCII (ch
);
2017 case RECC_NONASCII
: return !IS_REAL_ASCII (ch
);
2018 case RECC_UNIBYTE
: return ISUNIBYTE (ch
);
2019 case RECC_MULTIBYTE
: return !ISUNIBYTE (ch
);
2020 case RECC_WORD
: return ISWORD (ch
);
2021 case RECC_ERROR
: return false;
2027 /* Return a bit-pattern to use in the range-table bits to match multibyte
2028 chars of class CC. */
2030 re_wctype_to_bit (cc
)
2035 case RECC_NONASCII
: case RECC_PRINT
: case RECC_GRAPH
:
2036 case RECC_MULTIBYTE
: return BIT_MULTIBYTE
;
2037 case RECC_ALPHA
: case RECC_ALNUM
: case RECC_WORD
: return BIT_WORD
;
2038 case RECC_LOWER
: return BIT_LOWER
;
2039 case RECC_UPPER
: return BIT_UPPER
;
2040 case RECC_PUNCT
: return BIT_PUNCT
;
2041 case RECC_SPACE
: return BIT_SPACE
;
2042 case RECC_ASCII
: case RECC_DIGIT
: case RECC_XDIGIT
: case RECC_CNTRL
:
2043 case RECC_BLANK
: case RECC_UNIBYTE
: case RECC_ERROR
: return 0;
2050 /* Explicit quit checking is only used on NTemacs. */
2051 #if defined WINDOWSNT && defined emacs && defined QUIT
2052 extern int immediate_quit
;
2053 # define IMMEDIATE_QUIT_CHECK \
2055 if (immediate_quit) QUIT; \
2058 # define IMMEDIATE_QUIT_CHECK ((void)0)
2061 #ifndef MATCH_MAY_ALLOCATE
2063 /* If we cannot allocate large objects within re_match_2_internal,
2064 we make the fail stack and register vectors global.
2065 The fail stack, we grow to the maximum size when a regexp
2067 The register vectors, we adjust in size each time we
2068 compile a regexp, according to the number of registers it needs. */
2070 static fail_stack_type fail_stack
;
2072 /* Size with which the following vectors are currently allocated.
2073 That is so we can make them bigger as needed,
2074 but never make them smaller. */
2075 static int regs_allocated_size
;
2077 static re_char
** regstart
, ** regend
;
2078 static re_char
**best_regstart
, **best_regend
;
2080 /* Make the register vectors big enough for NUM_REGS registers,
2081 but don't make them smaller. */
2084 regex_grow_registers (num_regs
)
2087 if (num_regs
> regs_allocated_size
)
2089 RETALLOC_IF (regstart
, num_regs
, re_char
*);
2090 RETALLOC_IF (regend
, num_regs
, re_char
*);
2091 RETALLOC_IF (best_regstart
, num_regs
, re_char
*);
2092 RETALLOC_IF (best_regend
, num_regs
, re_char
*);
2094 regs_allocated_size
= num_regs
;
2098 #endif /* not MATCH_MAY_ALLOCATE */
2100 static boolean group_in_compile_stack
_RE_ARGS ((compile_stack_type
2104 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
2105 Returns one of error codes defined in `regex.h', or zero for success.
2107 Assumes the `allocated' (and perhaps `buffer') and `translate'
2108 fields are set in BUFP on entry.
2110 If it succeeds, results are put in BUFP (if it returns an error, the
2111 contents of BUFP are undefined):
2112 `buffer' is the compiled pattern;
2113 `syntax' is set to SYNTAX;
2114 `used' is set to the length of the compiled pattern;
2115 `fastmap_accurate' is zero;
2116 `re_nsub' is the number of subexpressions in PATTERN;
2117 `not_bol' and `not_eol' are zero;
2119 The `fastmap' field is neither examined nor set. */
2121 /* Insert the `jump' from the end of last alternative to "here".
2122 The space for the jump has already been allocated. */
2123 #define FIXUP_ALT_JUMP() \
2125 if (fixup_alt_jump) \
2126 STORE_JUMP (jump, fixup_alt_jump, b); \
2130 /* Return, freeing storage we allocated. */
2131 #define FREE_STACK_RETURN(value) \
2133 FREE_RANGE_TABLE_WORK_AREA (range_table_work); \
2134 free (compile_stack.stack); \
2138 static reg_errcode_t
2139 regex_compile (pattern
, size
, syntax
, bufp
)
2142 reg_syntax_t syntax
;
2143 struct re_pattern_buffer
*bufp
;
2145 /* We fetch characters from PATTERN here. */
2146 register re_wchar_t c
, c1
;
2148 /* A random temporary spot in PATTERN. */
2151 /* Points to the end of the buffer, where we should append. */
2152 register unsigned char *b
;
2154 /* Keeps track of unclosed groups. */
2155 compile_stack_type compile_stack
;
2157 /* Points to the current (ending) position in the pattern. */
2159 /* `const' makes AIX compiler fail. */
2160 unsigned char *p
= pattern
;
2162 re_char
*p
= pattern
;
2164 re_char
*pend
= pattern
+ size
;
2166 /* How to translate the characters in the pattern. */
2167 RE_TRANSLATE_TYPE translate
= bufp
->translate
;
2169 /* Address of the count-byte of the most recently inserted `exactn'
2170 command. This makes it possible to tell if a new exact-match
2171 character can be added to that command or if the character requires
2172 a new `exactn' command. */
2173 unsigned char *pending_exact
= 0;
2175 /* Address of start of the most recently finished expression.
2176 This tells, e.g., postfix * where to find the start of its
2177 operand. Reset at the beginning of groups and alternatives. */
2178 unsigned char *laststart
= 0;
2180 /* Address of beginning of regexp, or inside of last group. */
2181 unsigned char *begalt
;
2183 /* Place in the uncompiled pattern (i.e., the {) to
2184 which to go back if the interval is invalid. */
2185 re_char
*beg_interval
;
2187 /* Address of the place where a forward jump should go to the end of
2188 the containing expression. Each alternative of an `or' -- except the
2189 last -- ends with a forward jump of this sort. */
2190 unsigned char *fixup_alt_jump
= 0;
2192 /* Counts open-groups as they are encountered. Remembered for the
2193 matching close-group on the compile stack, so the same register
2194 number is put in the stop_memory as the start_memory. */
2195 regnum_t regnum
= 0;
2197 /* Work area for range table of charset. */
2198 struct range_table_work_area range_table_work
;
2200 /* If the object matched can contain multibyte characters. */
2201 const boolean multibyte
= RE_MULTIBYTE_P (bufp
);
2205 DEBUG_PRINT1 ("\nCompiling pattern: ");
2208 unsigned debug_count
;
2210 for (debug_count
= 0; debug_count
< size
; debug_count
++)
2211 putchar (pattern
[debug_count
]);
2216 /* Initialize the compile stack. */
2217 compile_stack
.stack
= TALLOC (INIT_COMPILE_STACK_SIZE
, compile_stack_elt_t
);
2218 if (compile_stack
.stack
== NULL
)
2221 compile_stack
.size
= INIT_COMPILE_STACK_SIZE
;
2222 compile_stack
.avail
= 0;
2224 range_table_work
.table
= 0;
2225 range_table_work
.allocated
= 0;
2227 /* Initialize the pattern buffer. */
2228 bufp
->syntax
= syntax
;
2229 bufp
->fastmap_accurate
= 0;
2230 bufp
->not_bol
= bufp
->not_eol
= 0;
2232 /* Set `used' to zero, so that if we return an error, the pattern
2233 printer (for debugging) will think there's no pattern. We reset it
2237 /* Always count groups, whether or not bufp->no_sub is set. */
2240 #if !defined emacs && !defined SYNTAX_TABLE
2241 /* Initialize the syntax table. */
2242 init_syntax_once ();
2245 if (bufp
->allocated
== 0)
2248 { /* If zero allocated, but buffer is non-null, try to realloc
2249 enough space. This loses if buffer's address is bogus, but
2250 that is the user's responsibility. */
2251 RETALLOC (bufp
->buffer
, INIT_BUF_SIZE
, unsigned char);
2254 { /* Caller did not allocate a buffer. Do it for them. */
2255 bufp
->buffer
= TALLOC (INIT_BUF_SIZE
, unsigned char);
2257 if (!bufp
->buffer
) FREE_STACK_RETURN (REG_ESPACE
);
2259 bufp
->allocated
= INIT_BUF_SIZE
;
2262 begalt
= b
= bufp
->buffer
;
2264 /* Loop through the uncompiled pattern until we're at the end. */
2273 if ( /* If at start of pattern, it's an operator. */
2275 /* If context independent, it's an operator. */
2276 || syntax
& RE_CONTEXT_INDEP_ANCHORS
2277 /* Otherwise, depends on what's come before. */
2278 || at_begline_loc_p (pattern
, p
, syntax
))
2279 BUF_PUSH ((syntax
& RE_NO_NEWLINE_ANCHOR
) ? begbuf
: begline
);
2288 if ( /* If at end of pattern, it's an operator. */
2290 /* If context independent, it's an operator. */
2291 || syntax
& RE_CONTEXT_INDEP_ANCHORS
2292 /* Otherwise, depends on what's next. */
2293 || at_endline_loc_p (p
, pend
, syntax
))
2294 BUF_PUSH ((syntax
& RE_NO_NEWLINE_ANCHOR
) ? endbuf
: endline
);
2303 if ((syntax
& RE_BK_PLUS_QM
)
2304 || (syntax
& RE_LIMITED_OPS
))
2308 /* If there is no previous pattern... */
2311 if (syntax
& RE_CONTEXT_INVALID_OPS
)
2312 FREE_STACK_RETURN (REG_BADRPT
);
2313 else if (!(syntax
& RE_CONTEXT_INDEP_OPS
))
2318 /* 1 means zero (many) matches is allowed. */
2319 boolean zero_times_ok
= 0, many_times_ok
= 0;
2322 /* If there is a sequence of repetition chars, collapse it
2323 down to just one (the right one). We can't combine
2324 interval operators with these because of, e.g., `a{2}*',
2325 which should only match an even number of `a's. */
2329 if ((syntax
& RE_FRUGAL
)
2330 && c
== '?' && (zero_times_ok
|| many_times_ok
))
2334 zero_times_ok
|= c
!= '+';
2335 many_times_ok
|= c
!= '?';
2341 || (!(syntax
& RE_BK_PLUS_QM
)
2342 && (*p
== '+' || *p
== '?')))
2344 else if (syntax
& RE_BK_PLUS_QM
&& *p
== '\\')
2347 FREE_STACK_RETURN (REG_EESCAPE
);
2348 if (p
[1] == '+' || p
[1] == '?')
2349 PATFETCH (c
); /* Gobble up the backslash. */
2355 /* If we get here, we found another repeat character. */
2359 /* Star, etc. applied to an empty pattern is equivalent
2360 to an empty pattern. */
2361 if (!laststart
|| laststart
== b
)
2364 /* Now we know whether or not zero matches is allowed
2365 and also whether or not two or more matches is allowed. */
2370 boolean simple
= skip_one_char (laststart
) == b
;
2371 unsigned int startoffset
= 0;
2373 /* Check if the loop can match the empty string. */
2374 (simple
|| !analyse_first (laststart
, b
, NULL
, 0)) ?
2375 on_failure_jump
: on_failure_jump_loop
;
2376 assert (skip_one_char (laststart
) <= b
);
2378 if (!zero_times_ok
&& simple
)
2379 { /* Since simple * loops can be made faster by using
2380 on_failure_keep_string_jump, we turn simple P+
2381 into PP* if P is simple. */
2382 unsigned char *p1
, *p2
;
2383 startoffset
= b
- laststart
;
2384 GET_BUFFER_SPACE (startoffset
);
2385 p1
= b
; p2
= laststart
;
2391 GET_BUFFER_SPACE (6);
2394 STORE_JUMP (ofj
, b
, b
+ 6);
2396 /* Simple * loops can use on_failure_keep_string_jump
2397 depending on what follows. But since we don't know
2398 that yet, we leave the decision up to
2399 on_failure_jump_smart. */
2400 INSERT_JUMP (simple
? on_failure_jump_smart
: ofj
,
2401 laststart
+ startoffset
, b
+ 6);
2403 STORE_JUMP (jump
, b
, laststart
+ startoffset
);
2408 /* A simple ? pattern. */
2409 assert (zero_times_ok
);
2410 GET_BUFFER_SPACE (3);
2411 INSERT_JUMP (on_failure_jump
, laststart
, b
+ 3);
2415 else /* not greedy */
2416 { /* I wish the greedy and non-greedy cases could be merged. */
2418 GET_BUFFER_SPACE (7); /* We might use less. */
2421 boolean emptyp
= analyse_first (laststart
, b
, NULL
, 0);
2423 /* The non-greedy multiple match looks like a repeat..until:
2424 we only need a conditional jump at the end of the loop */
2425 if (emptyp
) BUF_PUSH (no_op
);
2426 STORE_JUMP (emptyp
? on_failure_jump_nastyloop
2427 : on_failure_jump
, b
, laststart
);
2431 /* The repeat...until naturally matches one or more.
2432 To also match zero times, we need to first jump to
2433 the end of the loop (its conditional jump). */
2434 INSERT_JUMP (jump
, laststart
, b
);
2440 /* non-greedy a?? */
2441 INSERT_JUMP (jump
, laststart
, b
+ 3);
2443 INSERT_JUMP (on_failure_jump
, laststart
, laststart
+ 6);
2460 CLEAR_RANGE_TABLE_WORK_USED (range_table_work
);
2462 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2464 /* Ensure that we have enough space to push a charset: the
2465 opcode, the length count, and the bitset; 34 bytes in all. */
2466 GET_BUFFER_SPACE (34);
2470 /* We test `*p == '^' twice, instead of using an if
2471 statement, so we only need one BUF_PUSH. */
2472 BUF_PUSH (*p
== '^' ? charset_not
: charset
);
2476 /* Remember the first position in the bracket expression. */
2479 /* Push the number of bytes in the bitmap. */
2480 BUF_PUSH ((1 << BYTEWIDTH
) / BYTEWIDTH
);
2482 /* Clear the whole map. */
2483 bzero (b
, (1 << BYTEWIDTH
) / BYTEWIDTH
);
2485 /* charset_not matches newline according to a syntax bit. */
2486 if ((re_opcode_t
) b
[-2] == charset_not
2487 && (syntax
& RE_HAT_LISTS_NOT_NEWLINE
))
2488 SET_LIST_BIT ('\n');
2490 /* Read in characters and ranges, setting map bits. */
2493 boolean escaped_char
= false;
2494 const unsigned char *p2
= p
;
2496 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2500 /* \ might escape characters inside [...] and [^...]. */
2501 if ((syntax
& RE_BACKSLASH_ESCAPE_IN_LISTS
) && c
== '\\')
2503 if (p
== pend
) FREE_STACK_RETURN (REG_EESCAPE
);
2506 escaped_char
= true;
2510 /* Could be the end of the bracket expression. If it's
2511 not (i.e., when the bracket expression is `[]' so
2512 far), the ']' character bit gets set way below. */
2513 if (c
== ']' && p2
!= p1
)
2517 /* What should we do for the character which is
2518 greater than 0x7F, but not BASE_LEADING_CODE_P?
2521 /* See if we're at the beginning of a possible character
2524 if (!escaped_char
&&
2525 syntax
& RE_CHAR_CLASSES
&& c
== '[' && *p
== ':')
2527 /* Leave room for the null. */
2528 unsigned char str
[CHAR_CLASS_MAX_LENGTH
+ 1];
2529 const unsigned char *class_beg
;
2535 /* If pattern is `[[:'. */
2536 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2541 if ((c
== ':' && *p
== ']') || p
== pend
)
2543 if (c1
< CHAR_CLASS_MAX_LENGTH
)
2546 /* This is in any case an invalid class name. */
2551 /* If isn't a word bracketed by `[:' and `:]':
2552 undo the ending character, the letters, and
2553 leave the leading `:' and `[' (but set bits for
2555 if (c
== ':' && *p
== ']')
2560 cc
= re_wctype (str
);
2563 FREE_STACK_RETURN (REG_ECTYPE
);
2565 /* Throw away the ] at the end of the character
2569 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2571 /* Most character classes in a multibyte match
2572 just set a flag. Exceptions are is_blank,
2573 is_digit, is_cntrl, and is_xdigit, since
2574 they can only match ASCII characters. We
2575 don't need to handle them for multibyte.
2576 They are distinguished by a negative wctype. */
2579 SET_RANGE_TABLE_WORK_AREA_BIT (range_table_work
,
2580 re_wctype_to_bit (cc
));
2582 for (ch
= 0; ch
< 1 << BYTEWIDTH
; ++ch
)
2584 int translated
= TRANSLATE (ch
);
2585 if (re_iswctype (btowc (ch
), cc
))
2586 SET_LIST_BIT (translated
);
2589 /* Repeat the loop. */
2594 /* Go back to right after the "[:". */
2598 /* Because the `:' may starts the range, we
2599 can't simply set bit and repeat the loop.
2600 Instead, just set it to C and handle below. */
2605 if (p
< pend
&& p
[0] == '-' && p
[1] != ']')
2608 /* Discard the `-'. */
2611 /* Fetch the character which ends the range. */
2614 if (SINGLE_BYTE_CHAR_P (c
)
2615 && ! SINGLE_BYTE_CHAR_P (c1
))
2617 /* Handle a range starting with a character
2618 fitting in a bitmap to a character not
2619 fitting in a bitmap (thus require range
2620 table). We use both a bitmap (for the
2621 range from C to 255) and a range table (for
2622 the remaining range). Here, we setup only
2623 a range table. A bitmap is setup later. */
2625 = CHAR_BYTE8_P (c1
) ? BYTE8_TO_CHAR (0x80) : 256;
2627 SET_RANGE_TABLE_WORK_AREA (range_table_work
, c2
, c1
);
2632 /* Range from C to C. */
2635 /* Set the range ... */
2636 if (SINGLE_BYTE_CHAR_P (c
))
2637 /* ... into bitmap. */
2639 re_wchar_t this_char
;
2640 int range_start
= c
, range_end
= c1
;
2642 /* If the start is after the end, the range is empty. */
2643 if (range_start
> range_end
)
2645 if (syntax
& RE_NO_EMPTY_RANGES
)
2646 FREE_STACK_RETURN (REG_ERANGE
);
2647 /* Else, repeat the loop. */
2651 for (this_char
= range_start
; this_char
<= range_end
;
2653 SET_LIST_BIT (TRANSLATE (this_char
));
2657 /* ... into range table. */
2658 SET_RANGE_TABLE_WORK_AREA (range_table_work
, c
, c1
);
2661 /* Discard any (non)matching list bytes that are all 0 at the
2662 end of the map. Decrease the map-length byte too. */
2663 while ((int) b
[-1] > 0 && b
[b
[-1] - 1] == 0)
2667 /* Build real range table from work area. */
2668 if (RANGE_TABLE_WORK_USED (range_table_work
)
2669 || RANGE_TABLE_WORK_BITS (range_table_work
))
2672 int used
= RANGE_TABLE_WORK_USED (range_table_work
);
2674 /* Allocate space for COUNT + RANGE_TABLE. Needs two
2675 bytes for flags, two for COUNT, and three bytes for
2677 GET_BUFFER_SPACE (4 + used
* 3);
2679 /* Indicate the existence of range table. */
2680 laststart
[1] |= 0x80;
2682 /* Store the character class flag bits into the range table.
2683 If not in emacs, these flag bits are always 0. */
2684 *b
++ = RANGE_TABLE_WORK_BITS (range_table_work
) & 0xff;
2685 *b
++ = RANGE_TABLE_WORK_BITS (range_table_work
) >> 8;
2687 STORE_NUMBER_AND_INCR (b
, used
/ 2);
2688 for (i
= 0; i
< used
; i
++)
2689 STORE_CHARACTER_AND_INCR
2690 (b
, RANGE_TABLE_WORK_ELT (range_table_work
, i
));
2697 if (syntax
& RE_NO_BK_PARENS
)
2704 if (syntax
& RE_NO_BK_PARENS
)
2711 if (syntax
& RE_NEWLINE_ALT
)
2718 if (syntax
& RE_NO_BK_VBAR
)
2725 if (syntax
& RE_INTERVALS
&& syntax
& RE_NO_BK_BRACES
)
2726 goto handle_interval
;
2732 if (p
== pend
) FREE_STACK_RETURN (REG_EESCAPE
);
2734 /* Do not translate the character after the \, so that we can
2735 distinguish, e.g., \B from \b, even if we normally would
2736 translate, e.g., B to b. */
2742 if (syntax
& RE_NO_BK_PARENS
)
2743 goto normal_backslash
;
2750 /* Look for a special (?...) construct */
2751 if ((syntax
& RE_SHY_GROUPS
) && *p
== '?')
2753 PATFETCH (c
); /* Gobble up the '?'. */
2757 case ':': shy
= 1; break;
2759 /* Only (?:...) is supported right now. */
2760 FREE_STACK_RETURN (REG_BADPAT
);
2771 if (COMPILE_STACK_FULL
)
2773 RETALLOC (compile_stack
.stack
, compile_stack
.size
<< 1,
2774 compile_stack_elt_t
);
2775 if (compile_stack
.stack
== NULL
) return REG_ESPACE
;
2777 compile_stack
.size
<<= 1;
2780 /* These are the values to restore when we hit end of this
2781 group. They are all relative offsets, so that if the
2782 whole pattern moves because of realloc, they will still
2784 COMPILE_STACK_TOP
.begalt_offset
= begalt
- bufp
->buffer
;
2785 COMPILE_STACK_TOP
.fixup_alt_jump
2786 = fixup_alt_jump
? fixup_alt_jump
- bufp
->buffer
+ 1 : 0;
2787 COMPILE_STACK_TOP
.laststart_offset
= b
- bufp
->buffer
;
2788 COMPILE_STACK_TOP
.regnum
= shy
? -regnum
: regnum
;
2791 start_memory for groups beyond the last one we can
2792 represent in the compiled pattern. */
2793 if (regnum
<= MAX_REGNUM
&& !shy
)
2794 BUF_PUSH_2 (start_memory
, regnum
);
2796 compile_stack
.avail
++;
2801 /* If we've reached MAX_REGNUM groups, then this open
2802 won't actually generate any code, so we'll have to
2803 clear pending_exact explicitly. */
2809 if (syntax
& RE_NO_BK_PARENS
) goto normal_backslash
;
2811 if (COMPILE_STACK_EMPTY
)
2813 if (syntax
& RE_UNMATCHED_RIGHT_PAREN_ORD
)
2814 goto normal_backslash
;
2816 FREE_STACK_RETURN (REG_ERPAREN
);
2822 /* See similar code for backslashed left paren above. */
2823 if (COMPILE_STACK_EMPTY
)
2825 if (syntax
& RE_UNMATCHED_RIGHT_PAREN_ORD
)
2828 FREE_STACK_RETURN (REG_ERPAREN
);
2831 /* Since we just checked for an empty stack above, this
2832 ``can't happen''. */
2833 assert (compile_stack
.avail
!= 0);
2835 /* We don't just want to restore into `regnum', because
2836 later groups should continue to be numbered higher,
2837 as in `(ab)c(de)' -- the second group is #2. */
2838 regnum_t this_group_regnum
;
2840 compile_stack
.avail
--;
2841 begalt
= bufp
->buffer
+ COMPILE_STACK_TOP
.begalt_offset
;
2843 = COMPILE_STACK_TOP
.fixup_alt_jump
2844 ? bufp
->buffer
+ COMPILE_STACK_TOP
.fixup_alt_jump
- 1
2846 laststart
= bufp
->buffer
+ COMPILE_STACK_TOP
.laststart_offset
;
2847 this_group_regnum
= COMPILE_STACK_TOP
.regnum
;
2848 /* If we've reached MAX_REGNUM groups, then this open
2849 won't actually generate any code, so we'll have to
2850 clear pending_exact explicitly. */
2853 /* We're at the end of the group, so now we know how many
2854 groups were inside this one. */
2855 if (this_group_regnum
<= MAX_REGNUM
&& this_group_regnum
> 0)
2856 BUF_PUSH_2 (stop_memory
, this_group_regnum
);
2861 case '|': /* `\|'. */
2862 if (syntax
& RE_LIMITED_OPS
|| syntax
& RE_NO_BK_VBAR
)
2863 goto normal_backslash
;
2865 if (syntax
& RE_LIMITED_OPS
)
2868 /* Insert before the previous alternative a jump which
2869 jumps to this alternative if the former fails. */
2870 GET_BUFFER_SPACE (3);
2871 INSERT_JUMP (on_failure_jump
, begalt
, b
+ 6);
2875 /* The alternative before this one has a jump after it
2876 which gets executed if it gets matched. Adjust that
2877 jump so it will jump to this alternative's analogous
2878 jump (put in below, which in turn will jump to the next
2879 (if any) alternative's such jump, etc.). The last such
2880 jump jumps to the correct final destination. A picture:
2886 If we are at `b', then fixup_alt_jump right now points to a
2887 three-byte space after `a'. We'll put in the jump, set
2888 fixup_alt_jump to right after `b', and leave behind three
2889 bytes which we'll fill in when we get to after `c'. */
2893 /* Mark and leave space for a jump after this alternative,
2894 to be filled in later either by next alternative or
2895 when know we're at the end of a series of alternatives. */
2897 GET_BUFFER_SPACE (3);
2906 /* If \{ is a literal. */
2907 if (!(syntax
& RE_INTERVALS
)
2908 /* If we're at `\{' and it's not the open-interval
2910 || (syntax
& RE_NO_BK_BRACES
))
2911 goto normal_backslash
;
2915 /* If got here, then the syntax allows intervals. */
2917 /* At least (most) this many matches must be made. */
2918 int lower_bound
= 0, upper_bound
= -1;
2923 FREE_STACK_RETURN (REG_EBRACE
);
2925 GET_UNSIGNED_NUMBER (lower_bound
);
2928 GET_UNSIGNED_NUMBER (upper_bound
);
2930 /* Interval such as `{1}' => match exactly once. */
2931 upper_bound
= lower_bound
;
2933 if (lower_bound
< 0 || upper_bound
> RE_DUP_MAX
2934 || (upper_bound
>= 0 && lower_bound
> upper_bound
))
2935 FREE_STACK_RETURN (REG_BADBR
);
2937 if (!(syntax
& RE_NO_BK_BRACES
))
2940 FREE_STACK_RETURN (REG_BADBR
);
2946 FREE_STACK_RETURN (REG_BADBR
);
2948 /* We just parsed a valid interval. */
2950 /* If it's invalid to have no preceding re. */
2953 if (syntax
& RE_CONTEXT_INVALID_OPS
)
2954 FREE_STACK_RETURN (REG_BADRPT
);
2955 else if (syntax
& RE_CONTEXT_INDEP_OPS
)
2958 goto unfetch_interval
;
2961 if (upper_bound
== 0)
2962 /* If the upper bound is zero, just drop the sub pattern
2965 else if (lower_bound
== 1 && upper_bound
== 1)
2966 /* Just match it once: nothing to do here. */
2969 /* Otherwise, we have a nontrivial interval. When
2970 we're all done, the pattern will look like:
2971 set_number_at <jump count> <upper bound>
2972 set_number_at <succeed_n count> <lower bound>
2973 succeed_n <after jump addr> <succeed_n count>
2975 jump_n <succeed_n addr> <jump count>
2976 (The upper bound and `jump_n' are omitted if
2977 `upper_bound' is 1, though.) */
2979 { /* If the upper bound is > 1, we need to insert
2980 more at the end of the loop. */
2981 unsigned int nbytes
= (upper_bound
< 0 ? 3
2982 : upper_bound
> 1 ? 5 : 0);
2983 unsigned int startoffset
= 0;
2985 GET_BUFFER_SPACE (20); /* We might use less. */
2987 if (lower_bound
== 0)
2989 /* A succeed_n that starts with 0 is really a
2990 a simple on_failure_jump_loop. */
2991 INSERT_JUMP (on_failure_jump_loop
, laststart
,
2997 /* Initialize lower bound of the `succeed_n', even
2998 though it will be set during matching by its
2999 attendant `set_number_at' (inserted next),
3000 because `re_compile_fastmap' needs to know.
3001 Jump to the `jump_n' we might insert below. */
3002 INSERT_JUMP2 (succeed_n
, laststart
,
3007 /* Code to initialize the lower bound. Insert
3008 before the `succeed_n'. The `5' is the last two
3009 bytes of this `set_number_at', plus 3 bytes of
3010 the following `succeed_n'. */
3011 insert_op2 (set_number_at
, laststart
, 5, lower_bound
, b
);
3016 if (upper_bound
< 0)
3018 /* A negative upper bound stands for infinity,
3019 in which case it degenerates to a plain jump. */
3020 STORE_JUMP (jump
, b
, laststart
+ startoffset
);
3023 else if (upper_bound
> 1)
3024 { /* More than one repetition is allowed, so
3025 append a backward jump to the `succeed_n'
3026 that starts this interval.
3028 When we've reached this during matching,
3029 we'll have matched the interval once, so
3030 jump back only `upper_bound - 1' times. */
3031 STORE_JUMP2 (jump_n
, b
, laststart
+ startoffset
,
3035 /* The location we want to set is the second
3036 parameter of the `jump_n'; that is `b-2' as
3037 an absolute address. `laststart' will be
3038 the `set_number_at' we're about to insert;
3039 `laststart+3' the number to set, the source
3040 for the relative address. But we are
3041 inserting into the middle of the pattern --
3042 so everything is getting moved up by 5.
3043 Conclusion: (b - 2) - (laststart + 3) + 5,
3044 i.e., b - laststart.
3046 We insert this at the beginning of the loop
3047 so that if we fail during matching, we'll
3048 reinitialize the bounds. */
3049 insert_op2 (set_number_at
, laststart
, b
- laststart
,
3050 upper_bound
- 1, b
);
3055 beg_interval
= NULL
;
3060 /* If an invalid interval, match the characters as literals. */
3061 assert (beg_interval
);
3063 beg_interval
= NULL
;
3065 /* normal_char and normal_backslash need `c'. */
3068 if (!(syntax
& RE_NO_BK_BRACES
))
3070 assert (p
> pattern
&& p
[-1] == '\\');
3071 goto normal_backslash
;
3077 /* There is no way to specify the before_dot and after_dot
3078 operators. rms says this is ok. --karl */
3086 BUF_PUSH_2 (syntaxspec
, syntax_spec_code
[c
]);
3092 BUF_PUSH_2 (notsyntaxspec
, syntax_spec_code
[c
]);
3098 BUF_PUSH_2 (categoryspec
, c
);
3104 BUF_PUSH_2 (notcategoryspec
, c
);
3110 if (syntax
& RE_NO_GNU_OPS
)
3113 BUF_PUSH_2 (syntaxspec
, Sword
);
3118 if (syntax
& RE_NO_GNU_OPS
)
3121 BUF_PUSH_2 (notsyntaxspec
, Sword
);
3126 if (syntax
& RE_NO_GNU_OPS
)
3132 if (syntax
& RE_NO_GNU_OPS
)
3138 if (syntax
& RE_NO_GNU_OPS
)
3140 BUF_PUSH (wordbound
);
3144 if (syntax
& RE_NO_GNU_OPS
)
3146 BUF_PUSH (notwordbound
);
3150 if (syntax
& RE_NO_GNU_OPS
)
3156 if (syntax
& RE_NO_GNU_OPS
)
3161 case '1': case '2': case '3': case '4': case '5':
3162 case '6': case '7': case '8': case '9':
3166 if (syntax
& RE_NO_BK_REFS
)
3167 goto normal_backslash
;
3171 /* Can't back reference to a subexpression before its end. */
3172 if (reg
> regnum
|| group_in_compile_stack (compile_stack
, reg
))
3173 FREE_STACK_RETURN (REG_ESUBREG
);
3176 BUF_PUSH_2 (duplicate
, reg
);
3183 if (syntax
& RE_BK_PLUS_QM
)
3186 goto normal_backslash
;
3190 /* You might think it would be useful for \ to mean
3191 not to translate; but if we don't translate it
3192 it will never match anything. */
3200 /* Expects the character in `c'. */
3202 /* If no exactn currently being built. */
3205 /* If last exactn not at current position. */
3206 || pending_exact
+ *pending_exact
+ 1 != b
3208 /* We have only one byte following the exactn for the count. */
3209 || *pending_exact
>= (1 << BYTEWIDTH
) - MAX_MULTIBYTE_LENGTH
3211 /* If followed by a repetition operator. */
3212 || (p
!= pend
&& (*p
== '*' || *p
== '^'))
3213 || ((syntax
& RE_BK_PLUS_QM
)
3214 ? p
+ 1 < pend
&& *p
== '\\' && (p
[1] == '+' || p
[1] == '?')
3215 : p
!= pend
&& (*p
== '+' || *p
== '?'))
3216 || ((syntax
& RE_INTERVALS
)
3217 && ((syntax
& RE_NO_BK_BRACES
)
3218 ? p
!= pend
&& *p
== '{'
3219 : p
+ 1 < pend
&& p
[0] == '\\' && p
[1] == '{')))
3221 /* Start building a new exactn. */
3225 BUF_PUSH_2 (exactn
, 0);
3226 pending_exact
= b
- 1;
3229 GET_BUFFER_SPACE (MAX_MULTIBYTE_LENGTH
);
3234 len
= CHAR_STRING (c
, b
);
3238 (*pending_exact
) += len
;
3243 } /* while p != pend */
3246 /* Through the pattern now. */
3250 if (!COMPILE_STACK_EMPTY
)
3251 FREE_STACK_RETURN (REG_EPAREN
);
3253 /* If we don't want backtracking, force success
3254 the first time we reach the end of the compiled pattern. */
3255 if (syntax
& RE_NO_POSIX_BACKTRACKING
)
3258 free (compile_stack
.stack
);
3260 /* We have succeeded; set the length of the buffer. */
3261 bufp
->used
= b
- bufp
->buffer
;
3266 re_compile_fastmap (bufp
);
3267 DEBUG_PRINT1 ("\nCompiled pattern: \n");
3268 print_compiled_pattern (bufp
);
3273 #ifndef MATCH_MAY_ALLOCATE
3274 /* Initialize the failure stack to the largest possible stack. This
3275 isn't necessary unless we're trying to avoid calling alloca in
3276 the search and match routines. */
3278 int num_regs
= bufp
->re_nsub
+ 1;
3280 if (fail_stack
.size
< re_max_failures
* TYPICAL_FAILURE_SIZE
)
3282 fail_stack
.size
= re_max_failures
* TYPICAL_FAILURE_SIZE
;
3284 if (! fail_stack
.stack
)
3286 = (fail_stack_elt_t
*) malloc (fail_stack
.size
3287 * sizeof (fail_stack_elt_t
));
3290 = (fail_stack_elt_t
*) realloc (fail_stack
.stack
,
3292 * sizeof (fail_stack_elt_t
)));
3295 regex_grow_registers (num_regs
);
3297 #endif /* not MATCH_MAY_ALLOCATE */
3300 } /* regex_compile */
3302 /* Subroutines for `regex_compile'. */
3304 /* Store OP at LOC followed by two-byte integer parameter ARG. */
3307 store_op1 (op
, loc
, arg
)
3312 *loc
= (unsigned char) op
;
3313 STORE_NUMBER (loc
+ 1, arg
);
3317 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
3320 store_op2 (op
, loc
, arg1
, arg2
)
3325 *loc
= (unsigned char) op
;
3326 STORE_NUMBER (loc
+ 1, arg1
);
3327 STORE_NUMBER (loc
+ 3, arg2
);
3331 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
3332 for OP followed by two-byte integer parameter ARG. */
3335 insert_op1 (op
, loc
, arg
, end
)
3341 register unsigned char *pfrom
= end
;
3342 register unsigned char *pto
= end
+ 3;
3344 while (pfrom
!= loc
)
3347 store_op1 (op
, loc
, arg
);
3351 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
3354 insert_op2 (op
, loc
, arg1
, arg2
, end
)
3360 register unsigned char *pfrom
= end
;
3361 register unsigned char *pto
= end
+ 5;
3363 while (pfrom
!= loc
)
3366 store_op2 (op
, loc
, arg1
, arg2
);
3370 /* P points to just after a ^ in PATTERN. Return true if that ^ comes
3371 after an alternative or a begin-subexpression. We assume there is at
3372 least one character before the ^. */
3375 at_begline_loc_p (pattern
, p
, syntax
)
3376 re_char
*pattern
, *p
;
3377 reg_syntax_t syntax
;
3379 re_char
*prev
= p
- 2;
3380 boolean prev_prev_backslash
= prev
> pattern
&& prev
[-1] == '\\';
3383 /* After a subexpression? */
3384 (*prev
== '(' && (syntax
& RE_NO_BK_PARENS
|| prev_prev_backslash
))
3385 /* After an alternative? */
3386 || (*prev
== '|' && (syntax
& RE_NO_BK_VBAR
|| prev_prev_backslash
))
3387 /* After a shy subexpression? */
3388 || ((syntax
& RE_SHY_GROUPS
) && prev
- 2 >= pattern
3389 && prev
[-1] == '?' && prev
[-2] == '('
3390 && (syntax
& RE_NO_BK_PARENS
3391 || (prev
- 3 >= pattern
&& prev
[-3] == '\\')));
3395 /* The dual of at_begline_loc_p. This one is for $. We assume there is
3396 at least one character after the $, i.e., `P < PEND'. */
3399 at_endline_loc_p (p
, pend
, syntax
)
3401 reg_syntax_t syntax
;
3404 boolean next_backslash
= *next
== '\\';
3405 re_char
*next_next
= p
+ 1 < pend
? p
+ 1 : 0;
3408 /* Before a subexpression? */
3409 (syntax
& RE_NO_BK_PARENS
? *next
== ')'
3410 : next_backslash
&& next_next
&& *next_next
== ')')
3411 /* Before an alternative? */
3412 || (syntax
& RE_NO_BK_VBAR
? *next
== '|'
3413 : next_backslash
&& next_next
&& *next_next
== '|');
3417 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
3418 false if it's not. */
3421 group_in_compile_stack (compile_stack
, regnum
)
3422 compile_stack_type compile_stack
;
3427 for (this_element
= compile_stack
.avail
- 1;
3430 if (compile_stack
.stack
[this_element
].regnum
== regnum
)
3437 If fastmap is non-NULL, go through the pattern and fill fastmap
3438 with all the possible leading chars. If fastmap is NULL, don't
3439 bother filling it up (obviously) and only return whether the
3440 pattern could potentially match the empty string.
3442 Return 1 if p..pend might match the empty string.
3443 Return 0 if p..pend matches at least one char.
3444 Return -1 if fastmap was not updated accurately. */
3447 analyse_first (p
, pend
, fastmap
, multibyte
)
3450 const int multibyte
;
3455 /* If all elements for base leading-codes in fastmap is set, this
3456 flag is set true. */
3457 boolean match_any_multibyte_characters
= false;
3461 /* The loop below works as follows:
3462 - It has a working-list kept in the PATTERN_STACK and which basically
3463 starts by only containing a pointer to the first operation.
3464 - If the opcode we're looking at is a match against some set of
3465 chars, then we add those chars to the fastmap and go on to the
3466 next work element from the worklist (done via `break').
3467 - If the opcode is a control operator on the other hand, we either
3468 ignore it (if it's meaningless at this point, such as `start_memory')
3469 or execute it (if it's a jump). If the jump has several destinations
3470 (i.e. `on_failure_jump'), then we push the other destination onto the
3472 We guarantee termination by ignoring backward jumps (more or less),
3473 so that `p' is monotonically increasing. More to the point, we
3474 never set `p' (or push) anything `<= p1'. */
3478 /* `p1' is used as a marker of how far back a `on_failure_jump'
3479 can go without being ignored. It is normally equal to `p'
3480 (which prevents any backward `on_failure_jump') except right
3481 after a plain `jump', to allow patterns such as:
3484 10: on_failure_jump 3
3485 as used for the *? operator. */
3488 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *p
++))
3495 /* If the first character has to match a backreference, that means
3496 that the group was empty (since it already matched). Since this
3497 is the only case that interests us here, we can assume that the
3498 backreference must match the empty string. */
3503 /* Following are the cases which match a character. These end
3509 int c
= RE_STRING_CHAR (p
+ 1, pend
- p
);
3511 if (SINGLE_BYTE_CHAR_P (c
))
3520 /* We could put all the chars except for \n (and maybe \0)
3521 but we don't bother since it is generally not worth it. */
3522 if (!fastmap
) break;
3527 /* Chars beyond end of bitmap are possible matches.
3528 All the single-byte codes can occur in multibyte buffers.
3529 So any that are not listed in the charset
3530 are possible matches, even in multibyte buffers. */
3531 if (!fastmap
) break;
3532 for (j
= CHARSET_BITMAP_SIZE (&p
[-1]) * BYTEWIDTH
;
3533 j
< (1 << BYTEWIDTH
); j
++)
3537 if (!fastmap
) break;
3538 not = (re_opcode_t
) *(p
- 1) == charset_not
;
3539 for (j
= CHARSET_BITMAP_SIZE (&p
[-1]) * BYTEWIDTH
- 1, p
++;
3541 if (!!(p
[j
/ BYTEWIDTH
] & (1 << (j
% BYTEWIDTH
))) ^ not)
3544 if ((not && multibyte
)
3545 /* Any character set can possibly contain a character
3546 which doesn't match the specified set of characters. */
3547 || (CHARSET_RANGE_TABLE_EXISTS_P (&p
[-2])
3548 && CHARSET_RANGE_TABLE_BITS (&p
[-2]) != 0))
3549 /* If we can match a character class, we can match
3550 any character set. */
3552 set_fastmap_for_multibyte_characters
:
3553 if (match_any_multibyte_characters
== false)
3555 for (j
= 0x80; j
< 0x100; j
++) /* XXX */
3556 if (BASE_LEADING_CODE_P (j
))
3558 match_any_multibyte_characters
= true;
3562 else if (!not && CHARSET_RANGE_TABLE_EXISTS_P (&p
[-2])
3563 && match_any_multibyte_characters
== false)
3565 /* Set fastmap[I] to 1 where I is a base leading code of each
3566 multibyte characer in the range table. */
3568 unsigned char buf1
[MAX_MULTIBYTE_LENGTH
];
3569 unsigned char buf2
[MAX_MULTIBYTE_LENGTH
];
3571 /* Make P points the range table. `+ 2' is to skip flag
3572 bits for a character class. */
3573 p
+= CHARSET_BITMAP_SIZE (&p
[-2]) + 2;
3575 /* Extract the number of ranges in range table into COUNT. */
3576 EXTRACT_NUMBER_AND_INCR (count
, p
);
3577 for (; count
> 0; count
--, p
+= 2 * 3) /* XXX */
3579 /* Extract the start and end of each range. */
3580 EXTRACT_CHARACTER (c
, p
);
3581 CHAR_STRING (c
, buf1
);
3583 EXTRACT_CHARACTER (c
, p
);
3584 CHAR_STRING (c
, buf2
);
3585 for (j
= buf1
[0]; j
<= buf2
[0]; j
++)
3593 if (!fastmap
) break;
3595 not = (re_opcode_t
)p
[-1] == notsyntaxspec
;
3597 for (j
= 0; j
< (1 << BYTEWIDTH
); j
++)
3598 if ((SYNTAX (j
) == (enum syntaxcode
) k
) ^ not)
3602 /* This match depends on text properties. These end with
3603 aborting optimizations. */
3607 case notcategoryspec
:
3608 if (!fastmap
) break;
3609 not = (re_opcode_t
)p
[-1] == notcategoryspec
;
3611 for (j
= 0; j
< (1 << BYTEWIDTH
); j
++)
3612 if ((CHAR_HAS_CATEGORY (j
, k
)) ^ not)
3616 /* Any character set can possibly contain a character
3617 whose category is K (or not). */
3618 goto set_fastmap_for_multibyte_characters
;
3621 /* All cases after this match the empty string. These end with
3641 EXTRACT_NUMBER_AND_INCR (j
, p
);
3643 /* Backward jumps can only go back to code that we've already
3644 visited. `re_compile' should make sure this is true. */
3647 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *p
))
3649 case on_failure_jump
:
3650 case on_failure_keep_string_jump
:
3651 case on_failure_jump_loop
:
3652 case on_failure_jump_nastyloop
:
3653 case on_failure_jump_smart
:
3659 /* Keep `p1' to allow the `on_failure_jump' we are jumping to
3660 to jump back to "just after here". */
3663 case on_failure_jump
:
3664 case on_failure_keep_string_jump
:
3665 case on_failure_jump_nastyloop
:
3666 case on_failure_jump_loop
:
3667 case on_failure_jump_smart
:
3668 EXTRACT_NUMBER_AND_INCR (j
, p
);
3670 ; /* Backward jump to be ignored. */
3672 { /* We have to look down both arms.
3673 We first go down the "straight" path so as to minimize
3674 stack usage when going through alternatives. */
3675 int r
= analyse_first (p
, pend
, fastmap
, multibyte
);
3683 /* This code simply does not properly handle forward jump_n. */
3684 DEBUG_STATEMENT (EXTRACT_NUMBER (j
, p
); assert (j
< 0));
3686 /* jump_n can either jump or fall through. The (backward) jump
3687 case has already been handled, so we only need to look at the
3688 fallthrough case. */
3692 /* If N == 0, it should be an on_failure_jump_loop instead. */
3693 DEBUG_STATEMENT (EXTRACT_NUMBER (j
, p
+ 2); assert (j
> 0));
3695 /* We only care about one iteration of the loop, so we don't
3696 need to consider the case where this behaves like an
3713 abort (); /* We have listed all the cases. */
3716 /* Getting here means we have found the possible starting
3717 characters for one path of the pattern -- and that the empty
3718 string does not match. We need not follow this path further. */
3722 /* We reached the end without matching anything. */
3725 } /* analyse_first */
3727 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
3728 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
3729 characters can start a string that matches the pattern. This fastmap
3730 is used by re_search to skip quickly over impossible starting points.
3732 Character codes above (1 << BYTEWIDTH) are not represented in the
3733 fastmap, but the leading codes are represented. Thus, the fastmap
3734 indicates which character sets could start a match.
3736 The caller must supply the address of a (1 << BYTEWIDTH)-byte data
3737 area as BUFP->fastmap.
3739 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
3742 Returns 0 if we succeed, -2 if an internal error. */
3745 re_compile_fastmap (bufp
)
3746 struct re_pattern_buffer
*bufp
;
3748 char *fastmap
= bufp
->fastmap
;
3751 assert (fastmap
&& bufp
->buffer
);
3753 bzero (fastmap
, 1 << BYTEWIDTH
); /* Assume nothing's valid. */
3754 bufp
->fastmap_accurate
= 1; /* It will be when we're done. */
3756 analysis
= analyse_first (bufp
->buffer
, bufp
->buffer
+ bufp
->used
,
3757 fastmap
, RE_MULTIBYTE_P (bufp
));
3758 bufp
->can_be_null
= (analysis
!= 0);
3760 } /* re_compile_fastmap */
3762 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
3763 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
3764 this memory for recording register information. STARTS and ENDS
3765 must be allocated using the malloc library routine, and must each
3766 be at least NUM_REGS * sizeof (regoff_t) bytes long.
3768 If NUM_REGS == 0, then subsequent matches should allocate their own
3771 Unless this function is called, the first search or match using
3772 PATTERN_BUFFER will allocate its own register data, without
3773 freeing the old data. */
3776 re_set_registers (bufp
, regs
, num_regs
, starts
, ends
)
3777 struct re_pattern_buffer
*bufp
;
3778 struct re_registers
*regs
;
3780 regoff_t
*starts
, *ends
;
3784 bufp
->regs_allocated
= REGS_REALLOCATE
;
3785 regs
->num_regs
= num_regs
;
3786 regs
->start
= starts
;
3791 bufp
->regs_allocated
= REGS_UNALLOCATED
;
3793 regs
->start
= regs
->end
= (regoff_t
*) 0;
3796 WEAK_ALIAS (__re_set_registers
, re_set_registers
)
3798 /* Searching routines. */
3800 /* Like re_search_2, below, but only one string is specified, and
3801 doesn't let you say where to stop matching. */
3804 re_search (bufp
, string
, size
, startpos
, range
, regs
)
3805 struct re_pattern_buffer
*bufp
;
3807 int size
, startpos
, range
;
3808 struct re_registers
*regs
;
3810 return re_search_2 (bufp
, NULL
, 0, string
, size
, startpos
, range
,
3813 WEAK_ALIAS (__re_search
, re_search
)
3815 /* End address of virtual concatenation of string. */
3816 #define STOP_ADDR_VSTRING(P) \
3817 (((P) >= size1 ? string2 + size2 : string1 + size1))
3819 /* Address of POS in the concatenation of virtual string. */
3820 #define POS_ADDR_VSTRING(POS) \
3821 (((POS) >= size1 ? string2 - size1 : string1) + (POS))
3823 /* Using the compiled pattern in BUFP->buffer, first tries to match the
3824 virtual concatenation of STRING1 and STRING2, starting first at index
3825 STARTPOS, then at STARTPOS + 1, and so on.
3827 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
3829 RANGE is how far to scan while trying to match. RANGE = 0 means try
3830 only at STARTPOS; in general, the last start tried is STARTPOS +
3833 In REGS, return the indices of the virtual concatenation of STRING1
3834 and STRING2 that matched the entire BUFP->buffer and its contained
3837 Do not consider matching one past the index STOP in the virtual
3838 concatenation of STRING1 and STRING2.
3840 We return either the position in the strings at which the match was
3841 found, -1 if no match, or -2 if error (such as failure
3845 re_search_2 (bufp
, str1
, size1
, str2
, size2
, startpos
, range
, regs
, stop
)
3846 struct re_pattern_buffer
*bufp
;
3847 const char *str1
, *str2
;
3851 struct re_registers
*regs
;
3855 re_char
*string1
= (re_char
*) str1
;
3856 re_char
*string2
= (re_char
*) str2
;
3857 register char *fastmap
= bufp
->fastmap
;
3858 register RE_TRANSLATE_TYPE translate
= bufp
->translate
;
3859 int total_size
= size1
+ size2
;
3860 int endpos
= startpos
+ range
;
3861 boolean anchored_start
;
3863 /* Nonzero if we have to concern multibyte character. */
3864 const boolean multibyte
= RE_MULTIBYTE_P (bufp
);
3866 /* Check for out-of-range STARTPOS. */
3867 if (startpos
< 0 || startpos
> total_size
)
3870 /* Fix up RANGE if it might eventually take us outside
3871 the virtual concatenation of STRING1 and STRING2.
3872 Make sure we won't move STARTPOS below 0 or above TOTAL_SIZE. */
3874 range
= 0 - startpos
;
3875 else if (endpos
> total_size
)
3876 range
= total_size
- startpos
;
3878 /* If the search isn't to be a backwards one, don't waste time in a
3879 search for a pattern anchored at beginning of buffer. */
3880 if (bufp
->used
> 0 && (re_opcode_t
) bufp
->buffer
[0] == begbuf
&& range
> 0)
3889 /* In a forward search for something that starts with \=.
3890 don't keep searching past point. */
3891 if (bufp
->used
> 0 && (re_opcode_t
) bufp
->buffer
[0] == at_dot
&& range
> 0)
3893 range
= PT_BYTE
- BEGV_BYTE
- startpos
;
3899 /* Update the fastmap now if not correct already. */
3900 if (fastmap
&& !bufp
->fastmap_accurate
)
3901 re_compile_fastmap (bufp
);
3903 /* See whether the pattern is anchored. */
3904 anchored_start
= (bufp
->buffer
[0] == begline
);
3907 gl_state
.object
= re_match_object
;
3909 int charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (startpos
));
3911 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object
, charpos
, 1);
3915 /* Loop through the string, looking for a place to start matching. */
3918 /* If the pattern is anchored,
3919 skip quickly past places we cannot match.
3920 We don't bother to treat startpos == 0 specially
3921 because that case doesn't repeat. */
3922 if (anchored_start
&& startpos
> 0)
3924 if (! ((startpos
<= size1
? string1
[startpos
- 1]
3925 : string2
[startpos
- size1
- 1])
3930 /* If a fastmap is supplied, skip quickly over characters that
3931 cannot be the start of a match. If the pattern can match the
3932 null string, however, we don't need to skip characters; we want
3933 the first null string. */
3934 if (fastmap
&& startpos
< total_size
&& !bufp
->can_be_null
)
3936 register re_char
*d
;
3937 register re_wchar_t buf_ch
;
3939 d
= POS_ADDR_VSTRING (startpos
);
3941 if (range
> 0) /* Searching forwards. */
3943 register int lim
= 0;
3946 if (startpos
< size1
&& startpos
+ range
>= size1
)
3947 lim
= range
- (size1
- startpos
);
3949 /* Written out as an if-else to avoid testing `translate'
3951 if (RE_TRANSLATE_P (translate
))
3958 buf_ch
= STRING_CHAR_AND_LENGTH (d
, range
- lim
,
3961 buf_ch
= RE_TRANSLATE (translate
, buf_ch
);
3966 range
-= buf_charlen
;
3971 && !fastmap
[RE_TRANSLATE (translate
, *d
)])
3978 while (range
> lim
&& !fastmap
[*d
])
3984 startpos
+= irange
- range
;
3986 else /* Searching backwards. */
3988 int room
= (startpos
>= size1
3989 ? size2
+ size1
- startpos
3990 : size1
- startpos
);
3991 buf_ch
= RE_STRING_CHAR (d
, room
);
3992 buf_ch
= TRANSLATE (buf_ch
);
3994 if (! (buf_ch
>= 0400
3995 || fastmap
[buf_ch
]))
4000 /* If can't match the null string, and that's all we have left, fail. */
4001 if (range
>= 0 && startpos
== total_size
&& fastmap
4002 && !bufp
->can_be_null
)
4005 val
= re_match_2_internal (bufp
, string1
, size1
, string2
, size2
,
4006 startpos
, regs
, stop
);
4007 #ifndef REGEX_MALLOC
4024 /* Update STARTPOS to the next character boundary. */
4027 re_char
*p
= POS_ADDR_VSTRING (startpos
);
4028 re_char
*pend
= STOP_ADDR_VSTRING (startpos
);
4029 int len
= MULTIBYTE_FORM_LENGTH (p
, pend
- p
);
4047 /* Update STARTPOS to the previous character boundary. */
4050 re_char
*p
= POS_ADDR_VSTRING (startpos
);
4053 /* Find the head of multibyte form. */
4054 while (!CHAR_HEAD_P (*p
))
4059 if (MULTIBYTE_FORM_LENGTH (p
, len
+ 1) != (len
+ 1))
4075 WEAK_ALIAS (__re_search_2
, re_search_2
)
4077 /* Declarations and macros for re_match_2. */
4079 static int bcmp_translate
_RE_ARGS((re_char
*s1
, re_char
*s2
,
4081 RE_TRANSLATE_TYPE translate
,
4082 const int multibyte
));
4084 /* This converts PTR, a pointer into one of the search strings `string1'
4085 and `string2' into an offset from the beginning of that string. */
4086 #define POINTER_TO_OFFSET(ptr) \
4087 (FIRST_STRING_P (ptr) \
4088 ? ((regoff_t) ((ptr) - string1)) \
4089 : ((regoff_t) ((ptr) - string2 + size1)))
4091 /* Call before fetching a character with *d. This switches over to
4092 string2 if necessary.
4093 Check re_match_2_internal for a discussion of why end_match_2 might
4094 not be within string2 (but be equal to end_match_1 instead). */
4095 #define PREFETCH() \
4098 /* End of string2 => fail. */ \
4099 if (dend == end_match_2) \
4101 /* End of string1 => advance to string2. */ \
4103 dend = end_match_2; \
4106 /* Call before fetching a char with *d if you already checked other limits.
4107 This is meant for use in lookahead operations like wordend, etc..
4108 where we might need to look at parts of the string that might be
4109 outside of the LIMITs (i.e past `stop'). */
4110 #define PREFETCH_NOLIMIT() \
4114 dend = end_match_2; \
4117 /* Test if at very beginning or at very end of the virtual concatenation
4118 of `string1' and `string2'. If only one string, it's `string2'. */
4119 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
4120 #define AT_STRINGS_END(d) ((d) == end2)
4123 /* Test if D points to a character which is word-constituent. We have
4124 two special cases to check for: if past the end of string1, look at
4125 the first character in string2; and if before the beginning of
4126 string2, look at the last character in string1. */
4127 #define WORDCHAR_P(d) \
4128 (SYNTAX ((d) == end1 ? *string2 \
4129 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
4132 /* Disabled due to a compiler bug -- see comment at case wordbound */
4134 /* The comment at case wordbound is following one, but we don't use
4135 AT_WORD_BOUNDARY anymore to support multibyte form.
4137 The DEC Alpha C compiler 3.x generates incorrect code for the
4138 test WORDCHAR_P (d - 1) != WORDCHAR_P (d) in the expansion of
4139 AT_WORD_BOUNDARY, so this code is disabled. Expanding the
4140 macro and introducing temporary variables works around the bug. */
4143 /* Test if the character before D and the one at D differ with respect
4144 to being word-constituent. */
4145 #define AT_WORD_BOUNDARY(d) \
4146 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
4147 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
4150 /* Free everything we malloc. */
4151 #ifdef MATCH_MAY_ALLOCATE
4152 # define FREE_VAR(var) if (var) { REGEX_FREE (var); var = NULL; } else
4153 # define FREE_VARIABLES() \
4155 REGEX_FREE_STACK (fail_stack.stack); \
4156 FREE_VAR (regstart); \
4157 FREE_VAR (regend); \
4158 FREE_VAR (best_regstart); \
4159 FREE_VAR (best_regend); \
4162 # define FREE_VARIABLES() ((void)0) /* Do nothing! But inhibit gcc warning. */
4163 #endif /* not MATCH_MAY_ALLOCATE */
4166 /* Optimization routines. */
4168 /* If the operation is a match against one or more chars,
4169 return a pointer to the next operation, else return NULL. */
4174 switch (SWITCH_ENUM_CAST (*p
++))
4185 if (CHARSET_RANGE_TABLE_EXISTS_P (p
- 1))
4188 p
= CHARSET_RANGE_TABLE (p
- 1);
4189 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
4190 p
= CHARSET_RANGE_TABLE_END (p
, mcnt
);
4193 p
+= 1 + CHARSET_BITMAP_SIZE (p
- 1);
4200 case notcategoryspec
:
4212 /* Jump over non-matching operations. */
4213 static unsigned char *
4214 skip_noops (p
, pend
)
4215 unsigned char *p
, *pend
;
4220 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *p
))
4229 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
4240 /* Non-zero if "p1 matches something" implies "p2 fails". */
4242 mutually_exclusive_p (bufp
, p1
, p2
)
4243 struct re_pattern_buffer
*bufp
;
4244 unsigned char *p1
, *p2
;
4247 const boolean multibyte
= RE_MULTIBYTE_P (bufp
);
4248 unsigned char *pend
= bufp
->buffer
+ bufp
->used
;
4250 assert (p1
>= bufp
->buffer
&& p1
< pend
4251 && p2
>= bufp
->buffer
&& p2
<= pend
);
4253 /* Skip over open/close-group commands.
4254 If what follows this loop is a ...+ construct,
4255 look at what begins its body, since we will have to
4256 match at least one of that. */
4257 p2
= skip_noops (p2
, pend
);
4258 /* The same skip can be done for p1, except that this function
4259 is only used in the case where p1 is a simple match operator. */
4260 /* p1 = skip_noops (p1, pend); */
4262 assert (p1
>= bufp
->buffer
&& p1
< pend
4263 && p2
>= bufp
->buffer
&& p2
<= pend
);
4265 op2
= p2
== pend
? succeed
: *p2
;
4267 switch (SWITCH_ENUM_CAST (op2
))
4271 /* If we're at the end of the pattern, we can change. */
4272 if (skip_one_char (p1
))
4274 DEBUG_PRINT1 (" End of pattern: fast loop.\n");
4282 register re_wchar_t c
4283 = (re_opcode_t
) *p2
== endline
? '\n'
4284 : RE_STRING_CHAR (p2
+ 2, pend
- p2
- 2);
4286 if ((re_opcode_t
) *p1
== exactn
)
4288 if (c
!= RE_STRING_CHAR (p1
+ 2, pend
- p1
- 2))
4290 DEBUG_PRINT3 (" '%c' != '%c' => fast loop.\n", c
, p1
[2]);
4295 else if ((re_opcode_t
) *p1
== charset
4296 || (re_opcode_t
) *p1
== charset_not
)
4298 int not = (re_opcode_t
) *p1
== charset_not
;
4300 /* Test if C is listed in charset (or charset_not)
4302 if (SINGLE_BYTE_CHAR_P (c
))
4304 if (c
< CHARSET_BITMAP_SIZE (p1
) * BYTEWIDTH
4305 && p1
[2 + c
/ BYTEWIDTH
] & (1 << (c
% BYTEWIDTH
)))
4308 else if (CHARSET_RANGE_TABLE_EXISTS_P (p1
))
4309 CHARSET_LOOKUP_RANGE_TABLE (not, c
, p1
);
4311 /* `not' is equal to 1 if c would match, which means
4312 that we can't change to pop_failure_jump. */
4315 DEBUG_PRINT1 (" No match => fast loop.\n");
4319 else if ((re_opcode_t
) *p1
== anychar
4322 DEBUG_PRINT1 (" . != \\n => fast loop.\n");
4330 if ((re_opcode_t
) *p1
== exactn
)
4331 /* Reuse the code above. */
4332 return mutually_exclusive_p (bufp
, p2
, p1
);
4334 /* It is hard to list up all the character in charset
4335 P2 if it includes multibyte character. Give up in
4337 else if (!multibyte
|| !CHARSET_RANGE_TABLE_EXISTS_P (p2
))
4339 /* Now, we are sure that P2 has no range table.
4340 So, for the size of bitmap in P2, `p2[1]' is
4341 enough. But P1 may have range table, so the
4342 size of bitmap table of P1 is extracted by
4343 using macro `CHARSET_BITMAP_SIZE'.
4345 Since we know that all the character listed in
4346 P2 is ASCII, it is enough to test only bitmap
4349 if ((re_opcode_t
) *p1
== charset
)
4352 /* We win if the charset inside the loop
4353 has no overlap with the one after the loop. */
4356 && idx
< CHARSET_BITMAP_SIZE (p1
));
4358 if ((p2
[2 + idx
] & p1
[2 + idx
]) != 0)
4362 || idx
== CHARSET_BITMAP_SIZE (p1
))
4364 DEBUG_PRINT1 (" No match => fast loop.\n");
4368 else if ((re_opcode_t
) *p1
== charset_not
)
4371 /* We win if the charset_not inside the loop lists
4372 every character listed in the charset after. */
4373 for (idx
= 0; idx
< (int) p2
[1]; idx
++)
4374 if (! (p2
[2 + idx
] == 0
4375 || (idx
< CHARSET_BITMAP_SIZE (p1
)
4376 && ((p2
[2 + idx
] & ~ p1
[2 + idx
]) == 0))))
4381 DEBUG_PRINT1 (" No match => fast loop.\n");
4390 switch (SWITCH_ENUM_CAST (*p1
))
4394 /* Reuse the code above. */
4395 return mutually_exclusive_p (bufp
, p2
, p1
);
4397 /* When we have two charset_not, it's very unlikely that
4398 they don't overlap. The union of the two sets of excluded
4399 chars should cover all possible chars, which, as a matter of
4400 fact, is virtually impossible in multibyte buffers. */
4407 return ((re_opcode_t
) *p1
== syntaxspec
4408 && p1
[1] == (op2
== wordend
? Sword
: p2
[1]));
4412 return ((re_opcode_t
) *p1
== notsyntaxspec
4413 && p1
[1] == (op2
== wordend
? Sword
: p2
[1]));
4416 return (((re_opcode_t
) *p1
== notsyntaxspec
4417 || (re_opcode_t
) *p1
== syntaxspec
)
4422 return ((re_opcode_t
) *p1
== notcategoryspec
&& p1
[1] == p2
[1]);
4423 case notcategoryspec
:
4424 return ((re_opcode_t
) *p1
== categoryspec
&& p1
[1] == p2
[1]);
4436 /* Matching routines. */
4438 #ifndef emacs /* Emacs never uses this. */
4439 /* re_match is like re_match_2 except it takes only a single string. */
4442 re_match (bufp
, string
, size
, pos
, regs
)
4443 struct re_pattern_buffer
*bufp
;
4446 struct re_registers
*regs
;
4448 int result
= re_match_2_internal (bufp
, NULL
, 0, (re_char
*) string
, size
,
4450 # if defined C_ALLOCA && !defined REGEX_MALLOC
4455 WEAK_ALIAS (__re_match
, re_match
)
4456 #endif /* not emacs */
4459 /* In Emacs, this is the string or buffer in which we
4460 are matching. It is used for looking up syntax properties. */
4461 Lisp_Object re_match_object
;
4464 /* re_match_2 matches the compiled pattern in BUFP against the
4465 the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
4466 and SIZE2, respectively). We start matching at POS, and stop
4469 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
4470 store offsets for the substring each group matched in REGS. See the
4471 documentation for exactly how many groups we fill.
4473 We return -1 if no match, -2 if an internal error (such as the
4474 failure stack overflowing). Otherwise, we return the length of the
4475 matched substring. */
4478 re_match_2 (bufp
, string1
, size1
, string2
, size2
, pos
, regs
, stop
)
4479 struct re_pattern_buffer
*bufp
;
4480 const char *string1
, *string2
;
4483 struct re_registers
*regs
;
4490 gl_state
.object
= re_match_object
;
4491 charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (pos
));
4492 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object
, charpos
, 1);
4495 result
= re_match_2_internal (bufp
, (re_char
*) string1
, size1
,
4496 (re_char
*) string2
, size2
,
4498 #if defined C_ALLOCA && !defined REGEX_MALLOC
4503 WEAK_ALIAS (__re_match_2
, re_match_2
)
4505 /* This is a separate function so that we can force an alloca cleanup
4508 re_match_2_internal (bufp
, string1
, size1
, string2
, size2
, pos
, regs
, stop
)
4509 struct re_pattern_buffer
*bufp
;
4510 re_char
*string1
, *string2
;
4513 struct re_registers
*regs
;
4516 /* General temporaries. */
4521 /* Just past the end of the corresponding string. */
4522 re_char
*end1
, *end2
;
4524 /* Pointers into string1 and string2, just past the last characters in
4525 each to consider matching. */
4526 re_char
*end_match_1
, *end_match_2
;
4528 /* Where we are in the data, and the end of the current string. */
4531 /* Used sometimes to remember where we were before starting matching
4532 an operator so that we can go back in case of failure. This "atomic"
4533 behavior of matching opcodes is indispensable to the correctness
4534 of the on_failure_keep_string_jump optimization. */
4537 /* Where we are in the pattern, and the end of the pattern. */
4538 re_char
*p
= bufp
->buffer
;
4539 re_char
*pend
= p
+ bufp
->used
;
4541 /* We use this to map every character in the string. */
4542 RE_TRANSLATE_TYPE translate
= bufp
->translate
;
4544 /* Nonzero if we have to concern multibyte character. */
4545 const boolean multibyte
= RE_MULTIBYTE_P (bufp
);
4547 /* Failure point stack. Each place that can handle a failure further
4548 down the line pushes a failure point on this stack. It consists of
4549 regstart, and regend for all registers corresponding to
4550 the subexpressions we're currently inside, plus the number of such
4551 registers, and, finally, two char *'s. The first char * is where
4552 to resume scanning the pattern; the second one is where to resume
4553 scanning the strings. */
4554 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
4555 fail_stack_type fail_stack
;
4558 unsigned nfailure_points_pushed
= 0, nfailure_points_popped
= 0;
4561 #if defined REL_ALLOC && defined REGEX_MALLOC
4562 /* This holds the pointer to the failure stack, when
4563 it is allocated relocatably. */
4564 fail_stack_elt_t
*failure_stack_ptr
;
4567 /* We fill all the registers internally, independent of what we
4568 return, for use in backreferences. The number here includes
4569 an element for register zero. */
4570 size_t num_regs
= bufp
->re_nsub
+ 1;
4572 /* Information on the contents of registers. These are pointers into
4573 the input strings; they record just what was matched (on this
4574 attempt) by a subexpression part of the pattern, that is, the
4575 regnum-th regstart pointer points to where in the pattern we began
4576 matching and the regnum-th regend points to right after where we
4577 stopped matching the regnum-th subexpression. (The zeroth register
4578 keeps track of what the whole pattern matches.) */
4579 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4580 re_char
**regstart
, **regend
;
4583 /* The following record the register info as found in the above
4584 variables when we find a match better than any we've seen before.
4585 This happens as we backtrack through the failure points, which in
4586 turn happens only if we have not yet matched the entire string. */
4587 unsigned best_regs_set
= false;
4588 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4589 re_char
**best_regstart
, **best_regend
;
4592 /* Logically, this is `best_regend[0]'. But we don't want to have to
4593 allocate space for that if we're not allocating space for anything
4594 else (see below). Also, we never need info about register 0 for
4595 any of the other register vectors, and it seems rather a kludge to
4596 treat `best_regend' differently than the rest. So we keep track of
4597 the end of the best match so far in a separate variable. We
4598 initialize this to NULL so that when we backtrack the first time
4599 and need to test it, it's not garbage. */
4600 re_char
*match_end
= NULL
;
4603 /* Counts the total number of registers pushed. */
4604 unsigned num_regs_pushed
= 0;
4607 DEBUG_PRINT1 ("\n\nEntering re_match_2.\n");
4611 #ifdef MATCH_MAY_ALLOCATE
4612 /* Do not bother to initialize all the register variables if there are
4613 no groups in the pattern, as it takes a fair amount of time. If
4614 there are groups, we include space for register 0 (the whole
4615 pattern), even though we never use it, since it simplifies the
4616 array indexing. We should fix this. */
4619 regstart
= REGEX_TALLOC (num_regs
, re_char
*);
4620 regend
= REGEX_TALLOC (num_regs
, re_char
*);
4621 best_regstart
= REGEX_TALLOC (num_regs
, re_char
*);
4622 best_regend
= REGEX_TALLOC (num_regs
, re_char
*);
4624 if (!(regstart
&& regend
&& best_regstart
&& best_regend
))
4632 /* We must initialize all our variables to NULL, so that
4633 `FREE_VARIABLES' doesn't try to free them. */
4634 regstart
= regend
= best_regstart
= best_regend
= NULL
;
4636 #endif /* MATCH_MAY_ALLOCATE */
4638 /* The starting position is bogus. */
4639 if (pos
< 0 || pos
> size1
+ size2
)
4645 /* Initialize subexpression text positions to -1 to mark ones that no
4646 start_memory/stop_memory has been seen for. Also initialize the
4647 register information struct. */
4648 for (reg
= 1; reg
< num_regs
; reg
++)
4649 regstart
[reg
] = regend
[reg
] = NULL
;
4651 /* We move `string1' into `string2' if the latter's empty -- but not if
4652 `string1' is null. */
4653 if (size2
== 0 && string1
!= NULL
)
4660 end1
= string1
+ size1
;
4661 end2
= string2
+ size2
;
4663 /* `p' scans through the pattern as `d' scans through the data.
4664 `dend' is the end of the input string that `d' points within. `d'
4665 is advanced into the following input string whenever necessary, but
4666 this happens before fetching; therefore, at the beginning of the
4667 loop, `d' can be pointing at the end of a string, but it cannot
4671 /* Only match within string2. */
4672 d
= string2
+ pos
- size1
;
4673 dend
= end_match_2
= string2
+ stop
- size1
;
4674 end_match_1
= end1
; /* Just to give it a value. */
4680 /* Only match within string1. */
4681 end_match_1
= string1
+ stop
;
4683 When we reach end_match_1, PREFETCH normally switches to string2.
4684 But in the present case, this means that just doing a PREFETCH
4685 makes us jump from `stop' to `gap' within the string.
4686 What we really want here is for the search to stop as
4687 soon as we hit end_match_1. That's why we set end_match_2
4688 to end_match_1 (since PREFETCH fails as soon as we hit
4690 end_match_2
= end_match_1
;
4693 { /* It's important to use this code when stop == size so that
4694 moving `d' from end1 to string2 will not prevent the d == dend
4695 check from catching the end of string. */
4697 end_match_2
= string2
+ stop
- size1
;
4703 DEBUG_PRINT1 ("The compiled pattern is: ");
4704 DEBUG_PRINT_COMPILED_PATTERN (bufp
, p
, pend
);
4705 DEBUG_PRINT1 ("The string to match is: `");
4706 DEBUG_PRINT_DOUBLE_STRING (d
, string1
, size1
, string2
, size2
);
4707 DEBUG_PRINT1 ("'\n");
4709 /* This loops over pattern commands. It exits by returning from the
4710 function if the match is complete, or it drops through if the match
4711 fails at this starting point in the input data. */
4714 DEBUG_PRINT2 ("\n%p: ", p
);
4717 { /* End of pattern means we might have succeeded. */
4718 DEBUG_PRINT1 ("end of pattern ... ");
4720 /* If we haven't matched the entire string, and we want the
4721 longest match, try backtracking. */
4722 if (d
!= end_match_2
)
4724 /* 1 if this match ends in the same string (string1 or string2)
4725 as the best previous match. */
4726 boolean same_str_p
= (FIRST_STRING_P (match_end
)
4727 == FIRST_STRING_P (d
));
4728 /* 1 if this match is the best seen so far. */
4729 boolean best_match_p
;
4731 /* AIX compiler got confused when this was combined
4732 with the previous declaration. */
4734 best_match_p
= d
> match_end
;
4736 best_match_p
= !FIRST_STRING_P (d
);
4738 DEBUG_PRINT1 ("backtracking.\n");
4740 if (!FAIL_STACK_EMPTY ())
4741 { /* More failure points to try. */
4743 /* If exceeds best match so far, save it. */
4744 if (!best_regs_set
|| best_match_p
)
4746 best_regs_set
= true;
4749 DEBUG_PRINT1 ("\nSAVING match as best so far.\n");
4751 for (reg
= 1; reg
< num_regs
; reg
++)
4753 best_regstart
[reg
] = regstart
[reg
];
4754 best_regend
[reg
] = regend
[reg
];
4760 /* If no failure points, don't restore garbage. And if
4761 last match is real best match, don't restore second
4763 else if (best_regs_set
&& !best_match_p
)
4766 /* Restore best match. It may happen that `dend ==
4767 end_match_1' while the restored d is in string2.
4768 For example, the pattern `x.*y.*z' against the
4769 strings `x-' and `y-z-', if the two strings are
4770 not consecutive in memory. */
4771 DEBUG_PRINT1 ("Restoring best registers.\n");
4774 dend
= ((d
>= string1
&& d
<= end1
)
4775 ? end_match_1
: end_match_2
);
4777 for (reg
= 1; reg
< num_regs
; reg
++)
4779 regstart
[reg
] = best_regstart
[reg
];
4780 regend
[reg
] = best_regend
[reg
];
4783 } /* d != end_match_2 */
4786 DEBUG_PRINT1 ("Accepting match.\n");
4788 /* If caller wants register contents data back, do it. */
4789 if (regs
&& !bufp
->no_sub
)
4791 /* Have the register data arrays been allocated? */
4792 if (bufp
->regs_allocated
== REGS_UNALLOCATED
)
4793 { /* No. So allocate them with malloc. We need one
4794 extra element beyond `num_regs' for the `-1' marker
4796 regs
->num_regs
= MAX (RE_NREGS
, num_regs
+ 1);
4797 regs
->start
= TALLOC (regs
->num_regs
, regoff_t
);
4798 regs
->end
= TALLOC (regs
->num_regs
, regoff_t
);
4799 if (regs
->start
== NULL
|| regs
->end
== NULL
)
4804 bufp
->regs_allocated
= REGS_REALLOCATE
;
4806 else if (bufp
->regs_allocated
== REGS_REALLOCATE
)
4807 { /* Yes. If we need more elements than were already
4808 allocated, reallocate them. If we need fewer, just
4810 if (regs
->num_regs
< num_regs
+ 1)
4812 regs
->num_regs
= num_regs
+ 1;
4813 RETALLOC (regs
->start
, regs
->num_regs
, regoff_t
);
4814 RETALLOC (regs
->end
, regs
->num_regs
, regoff_t
);
4815 if (regs
->start
== NULL
|| regs
->end
== NULL
)
4824 /* These braces fend off a "empty body in an else-statement"
4825 warning under GCC when assert expands to nothing. */
4826 assert (bufp
->regs_allocated
== REGS_FIXED
);
4829 /* Convert the pointer data in `regstart' and `regend' to
4830 indices. Register zero has to be set differently,
4831 since we haven't kept track of any info for it. */
4832 if (regs
->num_regs
> 0)
4834 regs
->start
[0] = pos
;
4835 regs
->end
[0] = POINTER_TO_OFFSET (d
);
4838 /* Go through the first `min (num_regs, regs->num_regs)'
4839 registers, since that is all we initialized. */
4840 for (reg
= 1; reg
< MIN (num_regs
, regs
->num_regs
); reg
++)
4842 if (REG_UNSET (regstart
[reg
]) || REG_UNSET (regend
[reg
]))
4843 regs
->start
[reg
] = regs
->end
[reg
] = -1;
4847 = (regoff_t
) POINTER_TO_OFFSET (regstart
[reg
]);
4849 = (regoff_t
) POINTER_TO_OFFSET (regend
[reg
]);
4853 /* If the regs structure we return has more elements than
4854 were in the pattern, set the extra elements to -1. If
4855 we (re)allocated the registers, this is the case,
4856 because we always allocate enough to have at least one
4858 for (reg
= num_regs
; reg
< regs
->num_regs
; reg
++)
4859 regs
->start
[reg
] = regs
->end
[reg
] = -1;
4860 } /* regs && !bufp->no_sub */
4862 DEBUG_PRINT4 ("%u failure points pushed, %u popped (%u remain).\n",
4863 nfailure_points_pushed
, nfailure_points_popped
,
4864 nfailure_points_pushed
- nfailure_points_popped
);
4865 DEBUG_PRINT2 ("%u registers pushed.\n", num_regs_pushed
);
4867 mcnt
= POINTER_TO_OFFSET (d
) - pos
;
4869 DEBUG_PRINT2 ("Returning %d from re_match_2.\n", mcnt
);
4875 /* Otherwise match next pattern command. */
4876 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *p
++))
4878 /* Ignore these. Used to ignore the n of succeed_n's which
4879 currently have n == 0. */
4881 DEBUG_PRINT1 ("EXECUTING no_op.\n");
4885 DEBUG_PRINT1 ("EXECUTING succeed.\n");
4888 /* Match the next n pattern characters exactly. The following
4889 byte in the pattern defines n, and the n bytes after that
4890 are the characters to match. */
4893 DEBUG_PRINT2 ("EXECUTING exactn %d.\n", mcnt
);
4895 /* Remember the start point to rollback upon failure. */
4898 /* This is written out as an if-else so we don't waste time
4899 testing `translate' inside the loop. */
4900 if (RE_TRANSLATE_P (translate
))
4905 int pat_charlen
, buf_charlen
;
4906 unsigned int pat_ch
, buf_ch
;
4909 pat_ch
= STRING_CHAR_AND_LENGTH (p
, pend
- p
, pat_charlen
);
4910 buf_ch
= STRING_CHAR_AND_LENGTH (d
, dend
- d
, buf_charlen
);
4912 if (RE_TRANSLATE (translate
, buf_ch
)
4921 mcnt
-= pat_charlen
;
4928 if (RE_TRANSLATE (translate
, *d
) != *p
++)
4953 /* Match any character except possibly a newline or a null. */
4959 DEBUG_PRINT1 ("EXECUTING anychar.\n");
4962 buf_ch
= RE_STRING_CHAR_AND_LENGTH (d
, dend
- d
, buf_charlen
);
4963 buf_ch
= TRANSLATE (buf_ch
);
4965 if ((!(bufp
->syntax
& RE_DOT_NEWLINE
)
4967 || ((bufp
->syntax
& RE_DOT_NOT_NULL
)
4968 && buf_ch
== '\000'))
4971 DEBUG_PRINT2 (" Matched `%d'.\n", *d
);
4980 register unsigned int c
;
4981 boolean
not = (re_opcode_t
) *(p
- 1) == charset_not
;
4984 /* Start of actual range_table, or end of bitmap if there is no
4986 re_char
*range_table
;
4988 /* Nonzero if there is a range table. */
4989 int range_table_exists
;
4991 /* Number of ranges of range table. This is not included
4992 in the initial byte-length of the command. */
4995 DEBUG_PRINT2 ("EXECUTING charset%s.\n", not ? "_not" : "");
4997 range_table_exists
= CHARSET_RANGE_TABLE_EXISTS_P (&p
[-1]);
4999 if (range_table_exists
)
5001 range_table
= CHARSET_RANGE_TABLE (&p
[-1]); /* Past the bitmap. */
5002 EXTRACT_NUMBER_AND_INCR (count
, range_table
);
5006 c
= RE_STRING_CHAR_AND_LENGTH (d
, dend
- d
, len
);
5007 c
= TRANSLATE (c
); /* The character to match. */
5009 if (SINGLE_BYTE_CHAR_P (c
))
5010 { /* Lookup bitmap. */
5011 /* Cast to `unsigned' instead of `unsigned char' in
5012 case the bit list is a full 32 bytes long. */
5013 if (c
< (unsigned) (CHARSET_BITMAP_SIZE (&p
[-1]) * BYTEWIDTH
)
5014 && p
[1 + c
/ BYTEWIDTH
] & (1 << (c
% BYTEWIDTH
)))
5018 else if (range_table_exists
)
5020 int class_bits
= CHARSET_RANGE_TABLE_BITS (&p
[-1]);
5022 if ( (class_bits
& BIT_LOWER
&& ISLOWER (c
))
5023 | (class_bits
& BIT_MULTIBYTE
)
5024 | (class_bits
& BIT_PUNCT
&& ISPUNCT (c
))
5025 | (class_bits
& BIT_SPACE
&& ISSPACE (c
))
5026 | (class_bits
& BIT_UPPER
&& ISUPPER (c
))
5027 | (class_bits
& BIT_WORD
&& ISWORD (c
)))
5030 CHARSET_LOOKUP_RANGE_TABLE_RAW (not, c
, range_table
, count
);
5034 if (range_table_exists
)
5035 p
= CHARSET_RANGE_TABLE_END (range_table
, count
);
5037 p
+= CHARSET_BITMAP_SIZE (&p
[-1]) + 1;
5039 if (!not) goto fail
;
5046 /* The beginning of a group is represented by start_memory.
5047 The argument is the register number. The text
5048 matched within the group is recorded (in the internal
5049 registers data structure) under the register number. */
5051 DEBUG_PRINT2 ("EXECUTING start_memory %d:\n", *p
);
5053 /* In case we need to undo this operation (via backtracking). */
5054 PUSH_FAILURE_REG ((unsigned int)*p
);
5057 regend
[*p
] = NULL
; /* probably unnecessary. -sm */
5058 DEBUG_PRINT2 (" regstart: %d\n", POINTER_TO_OFFSET (regstart
[*p
]));
5060 /* Move past the register number and inner group count. */
5065 /* The stop_memory opcode represents the end of a group. Its
5066 argument is the same as start_memory's: the register number. */
5068 DEBUG_PRINT2 ("EXECUTING stop_memory %d:\n", *p
);
5070 assert (!REG_UNSET (regstart
[*p
]));
5071 /* Strictly speaking, there should be code such as:
5073 assert (REG_UNSET (regend[*p]));
5074 PUSH_FAILURE_REGSTOP ((unsigned int)*p);
5076 But the only info to be pushed is regend[*p] and it is known to
5077 be UNSET, so there really isn't anything to push.
5078 Not pushing anything, on the other hand deprives us from the
5079 guarantee that regend[*p] is UNSET since undoing this operation
5080 will not reset its value properly. This is not important since
5081 the value will only be read on the next start_memory or at
5082 the very end and both events can only happen if this stop_memory
5086 DEBUG_PRINT2 (" regend: %d\n", POINTER_TO_OFFSET (regend
[*p
]));
5088 /* Move past the register number and the inner group count. */
5093 /* \<digit> has been turned into a `duplicate' command which is
5094 followed by the numeric value of <digit> as the register number. */
5097 register re_char
*d2
, *dend2
;
5098 int regno
= *p
++; /* Get which register to match against. */
5099 DEBUG_PRINT2 ("EXECUTING duplicate %d.\n", regno
);
5101 /* Can't back reference a group which we've never matched. */
5102 if (REG_UNSET (regstart
[regno
]) || REG_UNSET (regend
[regno
]))
5105 /* Where in input to try to start matching. */
5106 d2
= regstart
[regno
];
5108 /* Remember the start point to rollback upon failure. */
5111 /* Where to stop matching; if both the place to start and
5112 the place to stop matching are in the same string, then
5113 set to the place to stop, otherwise, for now have to use
5114 the end of the first string. */
5116 dend2
= ((FIRST_STRING_P (regstart
[regno
])
5117 == FIRST_STRING_P (regend
[regno
]))
5118 ? regend
[regno
] : end_match_1
);
5121 /* If necessary, advance to next segment in register
5125 if (dend2
== end_match_2
) break;
5126 if (dend2
== regend
[regno
]) break;
5128 /* End of string1 => advance to string2. */
5130 dend2
= regend
[regno
];
5132 /* At end of register contents => success */
5133 if (d2
== dend2
) break;
5135 /* If necessary, advance to next segment in data. */
5138 /* How many characters left in this segment to match. */
5141 /* Want how many consecutive characters we can match in
5142 one shot, so, if necessary, adjust the count. */
5143 if (mcnt
> dend2
- d2
)
5146 /* Compare that many; failure if mismatch, else move
5148 if (RE_TRANSLATE_P (translate
)
5149 ? bcmp_translate (d
, d2
, mcnt
, translate
, multibyte
)
5150 : memcmp (d
, d2
, mcnt
))
5155 d
+= mcnt
, d2
+= mcnt
;
5161 /* begline matches the empty string at the beginning of the string
5162 (unless `not_bol' is set in `bufp'), and after newlines. */
5164 DEBUG_PRINT1 ("EXECUTING begline.\n");
5166 if (AT_STRINGS_BEG (d
))
5168 if (!bufp
->not_bol
) break;
5173 GET_CHAR_BEFORE_2 (c
, d
, string1
, end1
, string2
, end2
);
5177 /* In all other cases, we fail. */
5181 /* endline is the dual of begline. */
5183 DEBUG_PRINT1 ("EXECUTING endline.\n");
5185 if (AT_STRINGS_END (d
))
5187 if (!bufp
->not_eol
) break;
5191 PREFETCH_NOLIMIT ();
5198 /* Match at the very beginning of the data. */
5200 DEBUG_PRINT1 ("EXECUTING begbuf.\n");
5201 if (AT_STRINGS_BEG (d
))
5206 /* Match at the very end of the data. */
5208 DEBUG_PRINT1 ("EXECUTING endbuf.\n");
5209 if (AT_STRINGS_END (d
))
5214 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
5215 pushes NULL as the value for the string on the stack. Then
5216 `POP_FAILURE_POINT' will keep the current value for the
5217 string, instead of restoring it. To see why, consider
5218 matching `foo\nbar' against `.*\n'. The .* matches the foo;
5219 then the . fails against the \n. But the next thing we want
5220 to do is match the \n against the \n; if we restored the
5221 string value, we would be back at the foo.
5223 Because this is used only in specific cases, we don't need to
5224 check all the things that `on_failure_jump' does, to make
5225 sure the right things get saved on the stack. Hence we don't
5226 share its code. The only reason to push anything on the
5227 stack at all is that otherwise we would have to change
5228 `anychar's code to do something besides goto fail in this
5229 case; that seems worse than this. */
5230 case on_failure_keep_string_jump
:
5231 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5232 DEBUG_PRINT3 ("EXECUTING on_failure_keep_string_jump %d (to %p):\n",
5235 PUSH_FAILURE_POINT (p
- 3, NULL
);
5238 /* A nasty loop is introduced by the non-greedy *? and +?.
5239 With such loops, the stack only ever contains one failure point
5240 at a time, so that a plain on_failure_jump_loop kind of
5241 cycle detection cannot work. Worse yet, such a detection
5242 can not only fail to detect a cycle, but it can also wrongly
5243 detect a cycle (between different instantiations of the same
5245 So the method used for those nasty loops is a little different:
5246 We use a special cycle-detection-stack-frame which is pushed
5247 when the on_failure_jump_nastyloop failure-point is *popped*.
5248 This special frame thus marks the beginning of one iteration
5249 through the loop and we can hence easily check right here
5250 whether something matched between the beginning and the end of
5252 case on_failure_jump_nastyloop
:
5253 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5254 DEBUG_PRINT3 ("EXECUTING on_failure_jump_nastyloop %d (to %p):\n",
5257 assert ((re_opcode_t
)p
[-4] == no_op
);
5258 CHECK_INFINITE_LOOP (p
- 4, d
);
5259 PUSH_FAILURE_POINT (p
- 3, d
);
5263 /* Simple loop detecting on_failure_jump: just check on the
5264 failure stack if the same spot was already hit earlier. */
5265 case on_failure_jump_loop
:
5267 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5268 DEBUG_PRINT3 ("EXECUTING on_failure_jump_loop %d (to %p):\n",
5271 CHECK_INFINITE_LOOP (p
- 3, d
);
5272 PUSH_FAILURE_POINT (p
- 3, d
);
5276 /* Uses of on_failure_jump:
5278 Each alternative starts with an on_failure_jump that points
5279 to the beginning of the next alternative. Each alternative
5280 except the last ends with a jump that in effect jumps past
5281 the rest of the alternatives. (They really jump to the
5282 ending jump of the following alternative, because tensioning
5283 these jumps is a hassle.)
5285 Repeats start with an on_failure_jump that points past both
5286 the repetition text and either the following jump or
5287 pop_failure_jump back to this on_failure_jump. */
5288 case on_failure_jump
:
5289 IMMEDIATE_QUIT_CHECK
;
5290 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5291 DEBUG_PRINT3 ("EXECUTING on_failure_jump %d (to %p):\n",
5294 PUSH_FAILURE_POINT (p
-3, d
);
5297 /* This operation is used for greedy *.
5298 Compare the beginning of the repeat with what in the
5299 pattern follows its end. If we can establish that there
5300 is nothing that they would both match, i.e., that we
5301 would have to backtrack because of (as in, e.g., `a*a')
5302 then we can use a non-backtracking loop based on
5303 on_failure_keep_string_jump instead of on_failure_jump. */
5304 case on_failure_jump_smart
:
5305 IMMEDIATE_QUIT_CHECK
;
5306 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5307 DEBUG_PRINT3 ("EXECUTING on_failure_jump_smart %d (to %p).\n",
5310 re_char
*p1
= p
; /* Next operation. */
5311 /* Here, we discard `const', making re_match non-reentrant. */
5312 unsigned char *p2
= (unsigned char*) p
+ mcnt
; /* Jump dest. */
5313 unsigned char *p3
= (unsigned char*) p
- 3; /* opcode location. */
5315 p
-= 3; /* Reset so that we will re-execute the
5316 instruction once it's been changed. */
5318 EXTRACT_NUMBER (mcnt
, p2
- 2);
5320 /* Ensure this is a indeed the trivial kind of loop
5321 we are expecting. */
5322 assert (skip_one_char (p1
) == p2
- 3);
5323 assert ((re_opcode_t
) p2
[-3] == jump
&& p2
+ mcnt
== p
);
5324 DEBUG_STATEMENT (debug
+= 2);
5325 if (mutually_exclusive_p (bufp
, p1
, p2
))
5327 /* Use a fast `on_failure_keep_string_jump' loop. */
5328 DEBUG_PRINT1 (" smart exclusive => fast loop.\n");
5329 *p3
= (unsigned char) on_failure_keep_string_jump
;
5330 STORE_NUMBER (p2
- 2, mcnt
+ 3);
5334 /* Default to a safe `on_failure_jump' loop. */
5335 DEBUG_PRINT1 (" smart default => slow loop.\n");
5336 *p3
= (unsigned char) on_failure_jump
;
5338 DEBUG_STATEMENT (debug
-= 2);
5342 /* Unconditionally jump (without popping any failure points). */
5345 IMMEDIATE_QUIT_CHECK
;
5346 EXTRACT_NUMBER_AND_INCR (mcnt
, p
); /* Get the amount to jump. */
5347 DEBUG_PRINT2 ("EXECUTING jump %d ", mcnt
);
5348 p
+= mcnt
; /* Do the jump. */
5349 DEBUG_PRINT2 ("(to %p).\n", p
);
5353 /* Have to succeed matching what follows at least n times.
5354 After that, handle like `on_failure_jump'. */
5356 /* Signedness doesn't matter since we only compare MCNT to 0. */
5357 EXTRACT_NUMBER (mcnt
, p
+ 2);
5358 DEBUG_PRINT2 ("EXECUTING succeed_n %d.\n", mcnt
);
5360 /* Originally, mcnt is how many times we HAVE to succeed. */
5363 /* Here, we discard `const', making re_match non-reentrant. */
5364 unsigned char *p2
= (unsigned char*) p
+ 2; /* counter loc. */
5367 PUSH_NUMBER (p2
, mcnt
);
5370 /* The two bytes encoding mcnt == 0 are two no_op opcodes. */
5375 /* Signedness doesn't matter since we only compare MCNT to 0. */
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. */
5382 /* Here, we discard `const', making re_match non-reentrant. */
5383 unsigned char *p2
= (unsigned char*) p
+ 2; /* counter loc. */
5385 PUSH_NUMBER (p2
, mcnt
);
5386 goto unconditional_jump
;
5388 /* If don't have to jump any more, skip over the rest of command. */
5395 unsigned char *p2
; /* Location of the counter. */
5396 DEBUG_PRINT1 ("EXECUTING set_number_at.\n");
5398 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5399 /* Here, we discard `const', making re_match non-reentrant. */
5400 p2
= (unsigned char*) p
+ mcnt
;
5401 /* Signedness doesn't matter since we only copy MCNT's bits . */
5402 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5403 DEBUG_PRINT3 (" Setting %p to %d.\n", p2
, mcnt
);
5404 PUSH_NUMBER (p2
, mcnt
);
5410 not = (re_opcode_t
) *(p
- 1) == notwordbound
;
5411 DEBUG_PRINT2 ("EXECUTING %swordbound.\n", not?"not":"");
5413 /* We SUCCEED (or FAIL) in one of the following cases: */
5415 /* Case 1: D is at the beginning or the end of string. */
5416 if (AT_STRINGS_BEG (d
) || AT_STRINGS_END (d
))
5420 /* C1 is the character before D, S1 is the syntax of C1, C2
5421 is the character at D, and S2 is the syntax of C2. */
5425 int offset
= PTR_TO_OFFSET (d
- 1);
5426 int charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
5427 UPDATE_SYNTAX_TABLE (charpos
);
5429 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
5432 UPDATE_SYNTAX_TABLE_FORWARD (charpos
+ 1);
5434 PREFETCH_NOLIMIT ();
5435 c2
= RE_STRING_CHAR (d
, dend
- d
);
5438 if (/* Case 2: Only one of S1 and S2 is Sword. */
5439 ((s1
== Sword
) != (s2
== Sword
))
5440 /* Case 3: Both of S1 and S2 are Sword, and macro
5441 WORD_BOUNDARY_P (C1, C2) returns nonzero. */
5442 || ((s1
== Sword
) && WORD_BOUNDARY_P (c1
, c2
)))
5451 DEBUG_PRINT1 ("EXECUTING wordbeg.\n");
5453 /* We FAIL in one of the following cases: */
5455 /* Case 1: D is at the end of string. */
5456 if (AT_STRINGS_END (d
))
5460 /* C1 is the character before D, S1 is the syntax of C1, C2
5461 is the character at D, and S2 is the syntax of C2. */
5465 int offset
= PTR_TO_OFFSET (d
);
5466 int charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
5467 UPDATE_SYNTAX_TABLE (charpos
);
5470 c2
= RE_STRING_CHAR (d
, dend
- d
);
5473 /* Case 2: S2 is not Sword. */
5477 /* Case 3: D is not at the beginning of string ... */
5478 if (!AT_STRINGS_BEG (d
))
5480 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
5482 UPDATE_SYNTAX_TABLE_BACKWARD (charpos
- 1);
5486 /* ... and S1 is Sword, and WORD_BOUNDARY_P (C1, C2)
5488 if ((s1
== Sword
) && !WORD_BOUNDARY_P (c1
, c2
))
5495 DEBUG_PRINT1 ("EXECUTING wordend.\n");
5497 /* We FAIL in one of the following cases: */
5499 /* Case 1: D is at the beginning of string. */
5500 if (AT_STRINGS_BEG (d
))
5504 /* C1 is the character before D, S1 is the syntax of C1, C2
5505 is the character at D, and S2 is the syntax of C2. */
5509 int offset
= PTR_TO_OFFSET (d
) - 1;
5510 int charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
5511 UPDATE_SYNTAX_TABLE (charpos
);
5513 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
5516 /* Case 2: S1 is not Sword. */
5520 /* Case 3: D is not at the end of string ... */
5521 if (!AT_STRINGS_END (d
))
5523 PREFETCH_NOLIMIT ();
5524 c2
= RE_STRING_CHAR (d
, dend
- d
);
5526 UPDATE_SYNTAX_TABLE_FORWARD (charpos
);
5530 /* ... and S2 is Sword, and WORD_BOUNDARY_P (C1, C2)
5532 if ((s2
== Sword
) && !WORD_BOUNDARY_P (c1
, c2
))
5540 not = (re_opcode_t
) *(p
- 1) == notsyntaxspec
;
5542 DEBUG_PRINT3 ("EXECUTING %ssyntaxspec %d.\n", not?"not":"", mcnt
);
5546 int offset
= PTR_TO_OFFSET (d
);
5547 int pos1
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
5548 UPDATE_SYNTAX_TABLE (pos1
);
5555 c
= RE_STRING_CHAR_AND_LENGTH (d
, dend
- d
, len
);
5557 if ((SYNTAX (c
) != (enum syntaxcode
) mcnt
) ^ not)
5565 DEBUG_PRINT1 ("EXECUTING before_dot.\n");
5566 if (PTR_BYTE_POS (d
) >= PT_BYTE
)
5571 DEBUG_PRINT1 ("EXECUTING at_dot.\n");
5572 if (PTR_BYTE_POS (d
) != PT_BYTE
)
5577 DEBUG_PRINT1 ("EXECUTING after_dot.\n");
5578 if (PTR_BYTE_POS (d
) <= PT_BYTE
)
5583 case notcategoryspec
:
5584 not = (re_opcode_t
) *(p
- 1) == notcategoryspec
;
5586 DEBUG_PRINT3 ("EXECUTING %scategoryspec %d.\n", not?"not":"", mcnt
);
5592 c
= RE_STRING_CHAR_AND_LENGTH (d
, dend
- d
, len
);
5594 if ((!CHAR_HAS_CATEGORY (c
, mcnt
)) ^ not)
5605 continue; /* Successfully executed one pattern command; keep going. */
5608 /* We goto here if a matching operation fails. */
5610 IMMEDIATE_QUIT_CHECK
;
5611 if (!FAIL_STACK_EMPTY ())
5614 /* A restart point is known. Restore to that state. */
5615 DEBUG_PRINT1 ("\nFAIL:\n");
5616 POP_FAILURE_POINT (str
, pat
);
5617 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *pat
++))
5619 case on_failure_keep_string_jump
:
5620 assert (str
== NULL
);
5621 goto continue_failure_jump
;
5623 case on_failure_jump_nastyloop
:
5624 assert ((re_opcode_t
)pat
[-2] == no_op
);
5625 PUSH_FAILURE_POINT (pat
- 2, str
);
5628 case on_failure_jump_loop
:
5629 case on_failure_jump
:
5632 continue_failure_jump
:
5633 EXTRACT_NUMBER_AND_INCR (mcnt
, pat
);
5638 /* A special frame used for nastyloops. */
5645 assert (p
>= bufp
->buffer
&& p
<= pend
);
5647 if (d
>= string1
&& d
<= end1
)
5651 break; /* Matching at this starting point really fails. */
5655 goto restore_best_regs
;
5659 return -1; /* Failure to match. */
5662 /* Subroutine definitions for re_match_2. */
5664 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
5665 bytes; nonzero otherwise. */
5668 bcmp_translate (s1
, s2
, len
, translate
, multibyte
)
5671 RE_TRANSLATE_TYPE translate
;
5672 const int multibyte
;
5674 register re_char
*p1
= s1
, *p2
= s2
;
5675 re_char
*p1_end
= s1
+ len
;
5676 re_char
*p2_end
= s2
+ len
;
5678 /* FIXME: Checking both p1 and p2 presumes that the two strings might have
5679 different lengths, but relying on a single `len' would break this. -sm */
5680 while (p1
< p1_end
&& p2
< p2_end
)
5682 int p1_charlen
, p2_charlen
;
5683 re_wchar_t p1_ch
, p2_ch
;
5685 p1_ch
= RE_STRING_CHAR_AND_LENGTH (p1
, p1_end
- p1
, p1_charlen
);
5686 p2_ch
= RE_STRING_CHAR_AND_LENGTH (p2
, p2_end
- p2
, p2_charlen
);
5688 if (RE_TRANSLATE (translate
, p1_ch
)
5689 != RE_TRANSLATE (translate
, p2_ch
))
5692 p1
+= p1_charlen
, p2
+= p2_charlen
;
5695 if (p1
!= p1_end
|| p2
!= p2_end
)
5701 /* Entry points for GNU code. */
5703 /* re_compile_pattern is the GNU regular expression compiler: it
5704 compiles PATTERN (of length SIZE) and puts the result in BUFP.
5705 Returns 0 if the pattern was valid, otherwise an error string.
5707 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
5708 are set in BUFP on entry.
5710 We call regex_compile to do the actual compilation. */
5713 re_compile_pattern (pattern
, length
, bufp
)
5714 const char *pattern
;
5716 struct re_pattern_buffer
*bufp
;
5720 /* GNU code is written to assume at least RE_NREGS registers will be set
5721 (and at least one extra will be -1). */
5722 bufp
->regs_allocated
= REGS_UNALLOCATED
;
5724 /* And GNU code determines whether or not to get register information
5725 by passing null for the REGS argument to re_match, etc., not by
5729 ret
= regex_compile ((re_char
*) pattern
, length
, re_syntax_options
, bufp
);
5733 return gettext (re_error_msgid
[(int) ret
]);
5735 WEAK_ALIAS (__re_compile_pattern
, re_compile_pattern
)
5737 /* Entry points compatible with 4.2 BSD regex library. We don't define
5738 them unless specifically requested. */
5740 #if defined _REGEX_RE_COMP || defined _LIBC
5742 /* BSD has one and only one pattern buffer. */
5743 static struct re_pattern_buffer re_comp_buf
;
5747 /* Make these definitions weak in libc, so POSIX programs can redefine
5748 these names if they don't use our functions, and still use
5749 regcomp/regexec below without link errors. */
5759 if (!re_comp_buf
.buffer
)
5760 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
5761 return (char *) gettext ("No previous regular expression");
5765 if (!re_comp_buf
.buffer
)
5767 re_comp_buf
.buffer
= (unsigned char *) malloc (200);
5768 if (re_comp_buf
.buffer
== NULL
)
5769 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
5770 return (char *) gettext (re_error_msgid
[(int) REG_ESPACE
]);
5771 re_comp_buf
.allocated
= 200;
5773 re_comp_buf
.fastmap
= (char *) malloc (1 << BYTEWIDTH
);
5774 if (re_comp_buf
.fastmap
== NULL
)
5775 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
5776 return (char *) gettext (re_error_msgid
[(int) REG_ESPACE
]);
5779 /* Since `re_exec' always passes NULL for the `regs' argument, we
5780 don't need to initialize the pattern buffer fields which affect it. */
5782 ret
= regex_compile (s
, strlen (s
), re_syntax_options
, &re_comp_buf
);
5787 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
5788 return (char *) gettext (re_error_msgid
[(int) ret
]);
5799 const int len
= strlen (s
);
5801 0 <= re_search (&re_comp_buf
, s
, len
, 0, len
, (struct re_registers
*) 0);
5803 #endif /* _REGEX_RE_COMP */
5805 /* POSIX.2 functions. Don't define these for Emacs. */
5809 /* regcomp takes a regular expression as a string and compiles it.
5811 PREG is a regex_t *. We do not expect any fields to be initialized,
5812 since POSIX says we shouldn't. Thus, we set
5814 `buffer' to the compiled pattern;
5815 `used' to the length of the compiled pattern;
5816 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
5817 REG_EXTENDED bit in CFLAGS is set; otherwise, to
5818 RE_SYNTAX_POSIX_BASIC;
5819 `fastmap' to an allocated space for the fastmap;
5820 `fastmap_accurate' to zero;
5821 `re_nsub' to the number of subexpressions in PATTERN.
5823 PATTERN is the address of the pattern string.
5825 CFLAGS is a series of bits which affect compilation.
5827 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
5828 use POSIX basic syntax.
5830 If REG_NEWLINE is set, then . and [^...] don't match newline.
5831 Also, regexec will try a match beginning after every newline.
5833 If REG_ICASE is set, then we considers upper- and lowercase
5834 versions of letters to be equivalent when matching.
5836 If REG_NOSUB is set, then when PREG is passed to regexec, that
5837 routine will report only success or failure, and nothing about the
5840 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
5841 the return codes and their meanings.) */
5844 regcomp (preg
, pattern
, cflags
)
5845 regex_t
*__restrict preg
;
5846 const char *__restrict pattern
;
5851 = (cflags
& REG_EXTENDED
) ?
5852 RE_SYNTAX_POSIX_EXTENDED
: RE_SYNTAX_POSIX_BASIC
;
5854 /* regex_compile will allocate the space for the compiled pattern. */
5856 preg
->allocated
= 0;
5859 /* Try to allocate space for the fastmap. */
5860 preg
->fastmap
= (char *) malloc (1 << BYTEWIDTH
);
5862 if (cflags
& REG_ICASE
)
5867 = (RE_TRANSLATE_TYPE
) malloc (CHAR_SET_SIZE
5868 * sizeof (*(RE_TRANSLATE_TYPE
)0));
5869 if (preg
->translate
== NULL
)
5870 return (int) REG_ESPACE
;
5872 /* Map uppercase characters to corresponding lowercase ones. */
5873 for (i
= 0; i
< CHAR_SET_SIZE
; i
++)
5874 preg
->translate
[i
] = ISUPPER (i
) ? TOLOWER (i
) : i
;
5877 preg
->translate
= NULL
;
5879 /* If REG_NEWLINE is set, newlines are treated differently. */
5880 if (cflags
& REG_NEWLINE
)
5881 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
5882 syntax
&= ~RE_DOT_NEWLINE
;
5883 syntax
|= RE_HAT_LISTS_NOT_NEWLINE
;
5886 syntax
|= RE_NO_NEWLINE_ANCHOR
;
5888 preg
->no_sub
= !!(cflags
& REG_NOSUB
);
5890 /* POSIX says a null character in the pattern terminates it, so we
5891 can use strlen here in compiling the pattern. */
5892 ret
= regex_compile ((re_char
*) pattern
, strlen (pattern
), syntax
, preg
);
5894 /* POSIX doesn't distinguish between an unmatched open-group and an
5895 unmatched close-group: both are REG_EPAREN. */
5896 if (ret
== REG_ERPAREN
)
5899 if (ret
== REG_NOERROR
&& preg
->fastmap
)
5900 { /* Compute the fastmap now, since regexec cannot modify the pattern
5902 re_compile_fastmap (preg
);
5903 if (preg
->can_be_null
)
5904 { /* The fastmap can't be used anyway. */
5905 free (preg
->fastmap
);
5906 preg
->fastmap
= NULL
;
5911 WEAK_ALIAS (__regcomp
, regcomp
)
5914 /* regexec searches for a given pattern, specified by PREG, in the
5917 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
5918 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
5919 least NMATCH elements, and we set them to the offsets of the
5920 corresponding matched substrings.
5922 EFLAGS specifies `execution flags' which affect matching: if
5923 REG_NOTBOL is set, then ^ does not match at the beginning of the
5924 string; if REG_NOTEOL is set, then $ does not match at the end.
5926 We return 0 if we find a match and REG_NOMATCH if not. */
5929 regexec (preg
, string
, nmatch
, pmatch
, eflags
)
5930 const regex_t
*__restrict preg
;
5931 const char *__restrict string
;
5933 regmatch_t pmatch
[];
5937 struct re_registers regs
;
5938 regex_t private_preg
;
5939 int len
= strlen (string
);
5940 boolean want_reg_info
= !preg
->no_sub
&& nmatch
> 0 && pmatch
;
5942 private_preg
= *preg
;
5944 private_preg
.not_bol
= !!(eflags
& REG_NOTBOL
);
5945 private_preg
.not_eol
= !!(eflags
& REG_NOTEOL
);
5947 /* The user has told us exactly how many registers to return
5948 information about, via `nmatch'. We have to pass that on to the
5949 matching routines. */
5950 private_preg
.regs_allocated
= REGS_FIXED
;
5954 regs
.num_regs
= nmatch
;
5955 regs
.start
= TALLOC (nmatch
* 2, regoff_t
);
5956 if (regs
.start
== NULL
)
5957 return (int) REG_NOMATCH
;
5958 regs
.end
= regs
.start
+ nmatch
;
5961 /* Instead of using not_eol to implement REG_NOTEOL, we could simply
5962 pass (&private_preg, string, len + 1, 0, len, ...) pretending the string
5963 was a little bit longer but still only matching the real part.
5964 This works because the `endline' will check for a '\n' and will find a
5965 '\0', correctly deciding that this is not the end of a line.
5966 But it doesn't work out so nicely for REG_NOTBOL, since we don't have
5967 a convenient '\0' there. For all we know, the string could be preceded
5968 by '\n' which would throw things off. */
5970 /* Perform the searching operation. */
5971 ret
= re_search (&private_preg
, string
, len
,
5972 /* start: */ 0, /* range: */ len
,
5973 want_reg_info
? ®s
: (struct re_registers
*) 0);
5975 /* Copy the register information to the POSIX structure. */
5982 for (r
= 0; r
< nmatch
; r
++)
5984 pmatch
[r
].rm_so
= regs
.start
[r
];
5985 pmatch
[r
].rm_eo
= regs
.end
[r
];
5989 /* If we needed the temporary register info, free the space now. */
5993 /* We want zero return to mean success, unlike `re_search'. */
5994 return ret
>= 0 ? (int) REG_NOERROR
: (int) REG_NOMATCH
;
5996 WEAK_ALIAS (__regexec
, regexec
)
5999 /* Returns a message corresponding to an error code, ERRCODE, returned
6000 from either regcomp or regexec. We don't use PREG here. */
6003 regerror (errcode
, preg
, errbuf
, errbuf_size
)
6005 const regex_t
*preg
;
6013 || errcode
>= (sizeof (re_error_msgid
) / sizeof (re_error_msgid
[0])))
6014 /* Only error codes returned by the rest of the code should be passed
6015 to this routine. If we are given anything else, or if other regex
6016 code generates an invalid error code, then the program has a bug.
6017 Dump core so we can fix it. */
6020 msg
= gettext (re_error_msgid
[errcode
]);
6022 msg_size
= strlen (msg
) + 1; /* Includes the null. */
6024 if (errbuf_size
!= 0)
6026 if (msg_size
> errbuf_size
)
6028 strncpy (errbuf
, msg
, errbuf_size
- 1);
6029 errbuf
[errbuf_size
- 1] = 0;
6032 strcpy (errbuf
, msg
);
6037 WEAK_ALIAS (__regerror
, regerror
)
6040 /* Free dynamically allocated space used by PREG. */
6046 if (preg
->buffer
!= NULL
)
6047 free (preg
->buffer
);
6048 preg
->buffer
= NULL
;
6050 preg
->allocated
= 0;
6053 if (preg
->fastmap
!= NULL
)
6054 free (preg
->fastmap
);
6055 preg
->fastmap
= NULL
;
6056 preg
->fastmap_accurate
= 0;
6058 if (preg
->translate
!= NULL
)
6059 free (preg
->translate
);
6060 preg
->translate
= NULL
;
6062 WEAK_ALIAS (__regfree
, regfree
)
6064 #endif /* not emacs */