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. */
52 #define WIDE_CHAR_SUPPORT \
53 (defined _LIBC || HAVE_WCTYPE_H && HAVE_WCHAR_H && HAVE_BTOWC && !emacs)
55 /* For platform which support the ISO C amendement 1 functionality we
56 support user defined character classes. */
58 /* Solaris 2.5 has a bug: <wchar.h> must be included before <wctype.h>. */
64 /* We have to keep the namespace clean. */
65 # define regfree(preg) __regfree (preg)
66 # define regexec(pr, st, nm, pm, ef) __regexec (pr, st, nm, pm, ef)
67 # define regcomp(preg, pattern, cflags) __regcomp (preg, pattern, cflags)
68 # define regerror(errcode, preg, errbuf, errbuf_size) \
69 __regerror(errcode, preg, errbuf, errbuf_size)
70 # define re_set_registers(bu, re, nu, st, en) \
71 __re_set_registers (bu, re, nu, st, en)
72 # define re_match_2(bufp, string1, size1, string2, size2, pos, regs, stop) \
73 __re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
74 # define re_match(bufp, string, size, pos, regs) \
75 __re_match (bufp, string, size, pos, regs)
76 # define re_search(bufp, string, size, startpos, range, regs) \
77 __re_search (bufp, string, size, startpos, range, regs)
78 # define re_compile_pattern(pattern, length, bufp) \
79 __re_compile_pattern (pattern, length, bufp)
80 # define re_set_syntax(syntax) __re_set_syntax (syntax)
81 # define re_search_2(bufp, st1, s1, st2, s2, startpos, range, regs, stop) \
82 __re_search_2 (bufp, st1, s1, st2, s2, startpos, range, regs, stop)
83 # define re_compile_fastmap(bufp) __re_compile_fastmap (bufp)
85 /* Make sure we call libc's function even if the user overrides them. */
86 # define btowc __btowc
87 # define iswctype __iswctype
88 # define wctype __wctype
90 # define WEAK_ALIAS(a,b) weak_alias (a, b)
92 /* We are also using some library internals. */
93 # include <locale/localeinfo.h>
94 # include <locale/elem-hash.h>
95 # include <langinfo.h>
97 # define WEAK_ALIAS(a,b)
100 /* This is for other GNU distributions with internationalized messages. */
101 #if HAVE_LIBINTL_H || defined _LIBC
102 # include <libintl.h>
104 # define gettext(msgid) (msgid)
108 /* This define is so xgettext can find the internationalizable
110 # define gettext_noop(String) String
113 /* The `emacs' switch turns on certain matching commands
114 that make sense only in Emacs. */
120 /* Make syntax table lookup grant data in gl_state. */
121 # define SYNTAX_ENTRY_VIA_PROPERTY
124 # include "charset.h"
125 # include "category.h"
127 # define malloc xmalloc
128 # define realloc xrealloc
131 /* Converts the pointer to the char to BEG-based offset from the start. */
132 # define PTR_TO_OFFSET(d) POS_AS_IN_BUFFER (POINTER_TO_OFFSET (d))
133 # define POS_AS_IN_BUFFER(p) ((p) + (NILP (re_match_object) || BUFFERP (re_match_object)))
135 # define RE_MULTIBYTE_P(bufp) ((bufp)->multibyte)
136 # define RE_STRING_CHAR(p, s) \
137 (multibyte ? (STRING_CHAR (p, s)) : (*(p)))
138 # define RE_STRING_CHAR_AND_LENGTH(p, s, len) \
139 (multibyte ? (STRING_CHAR_AND_LENGTH (p, s, len)) : ((len) = 1, *(p)))
141 /* Set C a (possibly multibyte) character before P. P points into a
142 string which is the virtual concatenation of STR1 (which ends at
143 END1) or STR2 (which ends at END2). */
144 # define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
148 re_char *dtemp = (p) == (str2) ? (end1) : (p); \
149 re_char *dlimit = ((p) > (str2) && (p) <= (end2)) ? (str2) : (str1); \
150 while (dtemp-- > dlimit && !CHAR_HEAD_P (*dtemp)); \
151 c = STRING_CHAR (dtemp, (p) - dtemp); \
154 (c = ((p) == (str2) ? (end1) : (p))[-1]); \
158 #else /* not emacs */
160 /* If we are not linking with Emacs proper,
161 we can't use the relocating allocator
162 even if config.h says that we can. */
165 # if defined STDC_HEADERS || defined _LIBC
172 /* When used in Emacs's lib-src, we need to get bzero and bcopy somehow.
173 If nothing else has been done, use the method below. */
174 # ifdef INHIBIT_STRING_HEADER
175 # if !(defined HAVE_BZERO && defined HAVE_BCOPY)
176 # if !defined bzero && !defined bcopy
177 # undef INHIBIT_STRING_HEADER
182 /* This is the normal way of making sure we have memcpy, memcmp and bzero.
183 This is used in most programs--a few other programs avoid this
184 by defining INHIBIT_STRING_HEADER. */
185 # ifndef INHIBIT_STRING_HEADER
186 # if defined HAVE_STRING_H || defined STDC_HEADERS || defined _LIBC
190 # define bzero(s, n) (memset (s, '\0', n), (s))
192 # define bzero(s, n) __bzero (s, n)
196 # include <strings.h>
198 # define memcmp(s1, s2, n) bcmp (s1, s2, n)
201 # define memcpy(d, s, n) (bcopy (s, d, n), (d))
206 /* Define the syntax stuff for \<, \>, etc. */
208 /* Sword must be nonzero for the wordchar pattern commands in re_match_2. */
209 enum syntaxcode
{ Swhitespace
= 0, Sword
= 1 };
211 # ifdef SWITCH_ENUM_BUG
212 # define SWITCH_ENUM_CAST(x) ((int)(x))
214 # define SWITCH_ENUM_CAST(x) (x)
217 /* Dummy macros for non-Emacs environments. */
218 # define BASE_LEADING_CODE_P(c) (0)
219 # define CHAR_CHARSET(c) 0
220 # define CHARSET_LEADING_CODE_BASE(c) 0
221 # define MAX_MULTIBYTE_LENGTH 1
222 # define RE_MULTIBYTE_P(x) 0
223 # define WORD_BOUNDARY_P(c1, c2) (0)
224 # define CHAR_HEAD_P(p) (1)
225 # define SINGLE_BYTE_CHAR_P(c) (1)
226 # define SAME_CHARSET_P(c1, c2) (1)
227 # define MULTIBYTE_FORM_LENGTH(p, s) (1)
228 # define STRING_CHAR(p, s) (*(p))
229 # define RE_STRING_CHAR STRING_CHAR
230 # define CHAR_STRING(c, s) (*(s) = (c), 1)
231 # define STRING_CHAR_AND_LENGTH(p, s, actual_len) ((actual_len) = 1, *(p))
232 # define RE_STRING_CHAR_AND_LENGTH STRING_CHAR_AND_LENGTH
233 # define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
234 (c = ((p) == (str2) ? *((end1) - 1) : *((p) - 1)))
235 # define MAKE_CHAR(charset, c1, c2) (c1)
236 #endif /* not emacs */
239 # define RE_TRANSLATE(TBL, C) ((unsigned char)(TBL)[C])
240 # define RE_TRANSLATE_P(TBL) (TBL)
243 /* Get the interface, including the syntax bits. */
246 /* isalpha etc. are used for the character classes. */
251 /* 1 if C is an ASCII character. */
252 # define IS_REAL_ASCII(c) ((c) < 0200)
254 /* 1 if C is a unibyte character. */
255 # define ISUNIBYTE(c) (SINGLE_BYTE_CHAR_P ((c)))
257 /* The Emacs definitions should not be directly affected by locales. */
259 /* In Emacs, these are only used for single-byte characters. */
260 # define ISDIGIT(c) ((c) >= '0' && (c) <= '9')
261 # define ISCNTRL(c) ((c) < ' ')
262 # define ISXDIGIT(c) (((c) >= '0' && (c) <= '9') \
263 || ((c) >= 'a' && (c) <= 'f') \
264 || ((c) >= 'A' && (c) <= 'F'))
266 /* This is only used for single-byte characters. */
267 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
269 /* The rest must handle multibyte characters. */
271 # define ISGRAPH(c) (SINGLE_BYTE_CHAR_P (c) \
272 ? (c) > ' ' && !((c) >= 0177 && (c) <= 0237) \
275 # define ISPRINT(c) (SINGLE_BYTE_CHAR_P (c) \
276 ? (c) >= ' ' && !((c) >= 0177 && (c) <= 0237) \
279 # define ISALNUM(c) (IS_REAL_ASCII (c) \
280 ? (((c) >= 'a' && (c) <= 'z') \
281 || ((c) >= 'A' && (c) <= 'Z') \
282 || ((c) >= '0' && (c) <= '9')) \
283 : SYNTAX (c) == Sword)
285 # define ISALPHA(c) (IS_REAL_ASCII (c) \
286 ? (((c) >= 'a' && (c) <= 'z') \
287 || ((c) >= 'A' && (c) <= 'Z')) \
288 : SYNTAX (c) == Sword)
290 # define ISLOWER(c) (LOWERCASEP (c))
292 # define ISPUNCT(c) (IS_REAL_ASCII (c) \
293 ? ((c) > ' ' && (c) < 0177 \
294 && !(((c) >= 'a' && (c) <= 'z') \
295 || ((c) >= 'A' && (c) <= 'Z') \
296 || ((c) >= '0' && (c) <= '9'))) \
297 : SYNTAX (c) != Sword)
299 # define ISSPACE(c) (SYNTAX (c) == Swhitespace)
301 # define ISUPPER(c) (UPPERCASEP (c))
303 # define ISWORD(c) (SYNTAX (c) == Sword)
305 #else /* not emacs */
307 /* Jim Meyering writes:
309 "... Some ctype macros are valid only for character codes that
310 isascii says are ASCII (SGI's IRIX-4.0.5 is one such system --when
311 using /bin/cc or gcc but without giving an ansi option). So, all
312 ctype uses should be through macros like ISPRINT... If
313 STDC_HEADERS is defined, then autoconf has verified that the ctype
314 macros don't need to be guarded with references to isascii. ...
315 Defining isascii to 1 should let any compiler worth its salt
316 eliminate the && through constant folding."
317 Solaris defines some of these symbols so we must undefine them first. */
320 # if defined STDC_HEADERS || (!defined isascii && !defined HAVE_ISASCII)
321 # define ISASCII(c) 1
323 # define ISASCII(c) isascii(c)
326 /* 1 if C is an ASCII character. */
327 # define IS_REAL_ASCII(c) ((c) < 0200)
329 /* This distinction is not meaningful, except in Emacs. */
330 # define ISUNIBYTE(c) 1
333 # define ISBLANK(c) (ISASCII (c) && isblank (c))
335 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
338 # define ISGRAPH(c) (ISASCII (c) && isgraph (c))
340 # define ISGRAPH(c) (ISASCII (c) && isprint (c) && !isspace (c))
344 # define ISPRINT(c) (ISASCII (c) && isprint (c))
345 # define ISDIGIT(c) (ISASCII (c) && isdigit (c))
346 # define ISALNUM(c) (ISASCII (c) && isalnum (c))
347 # define ISALPHA(c) (ISASCII (c) && isalpha (c))
348 # define ISCNTRL(c) (ISASCII (c) && iscntrl (c))
349 # define ISLOWER(c) (ISASCII (c) && islower (c))
350 # define ISPUNCT(c) (ISASCII (c) && ispunct (c))
351 # define ISSPACE(c) (ISASCII (c) && isspace (c))
352 # define ISUPPER(c) (ISASCII (c) && isupper (c))
353 # define ISXDIGIT(c) (ISASCII (c) && isxdigit (c))
355 # define ISWORD(c) ISALPHA(c)
358 # define TOLOWER(c) _tolower(c)
360 # define TOLOWER(c) tolower(c)
363 /* How many characters in the character set. */
364 # define CHAR_SET_SIZE 256
368 extern char *re_syntax_table
;
370 # else /* not SYNTAX_TABLE */
372 static char re_syntax_table
[CHAR_SET_SIZE
];
383 bzero (re_syntax_table
, sizeof re_syntax_table
);
385 for (c
= 0; c
< CHAR_SET_SIZE
; ++c
)
387 re_syntax_table
[c
] = Sword
;
389 re_syntax_table
['_'] = Sword
;
394 # endif /* not SYNTAX_TABLE */
396 # define SYNTAX(c) re_syntax_table[(c)]
398 #endif /* not emacs */
401 # define NULL (void *)0
404 /* We remove any previous definition of `SIGN_EXTEND_CHAR',
405 since ours (we hope) works properly with all combinations of
406 machines, compilers, `char' and `unsigned char' argument types.
407 (Per Bothner suggested the basic approach.) */
408 #undef SIGN_EXTEND_CHAR
410 # define SIGN_EXTEND_CHAR(c) ((signed char) (c))
411 #else /* not __STDC__ */
412 /* As in Harbison and Steele. */
413 # define SIGN_EXTEND_CHAR(c) ((((unsigned char) (c)) ^ 128) - 128)
416 /* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we
417 use `alloca' instead of `malloc'. This is because using malloc in
418 re_search* or re_match* could cause memory leaks when C-g is used in
419 Emacs; also, malloc is slower and causes storage fragmentation. On
420 the other hand, malloc is more portable, and easier to debug.
422 Because we sometimes use alloca, some routines have to be macros,
423 not functions -- `alloca'-allocated space disappears at the end of the
424 function it is called in. */
428 # define REGEX_ALLOCATE malloc
429 # define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
430 # define REGEX_FREE free
432 #else /* not REGEX_MALLOC */
434 /* Emacs already defines alloca, sometimes. */
437 /* Make alloca work the best possible way. */
439 # define alloca __builtin_alloca
440 # else /* not __GNUC__ */
443 # endif /* HAVE_ALLOCA_H */
444 # endif /* not __GNUC__ */
446 # endif /* not alloca */
448 # define REGEX_ALLOCATE alloca
450 /* Assumes a `char *destination' variable. */
451 # define REGEX_REALLOCATE(source, osize, nsize) \
452 (destination = (char *) alloca (nsize), \
453 memcpy (destination, source, osize))
455 /* No need to do anything to free, after alloca. */
456 # define REGEX_FREE(arg) ((void)0) /* Do nothing! But inhibit gcc warning. */
458 #endif /* not REGEX_MALLOC */
460 /* Define how to allocate the failure stack. */
462 #if defined REL_ALLOC && defined REGEX_MALLOC
464 # define REGEX_ALLOCATE_STACK(size) \
465 r_alloc (&failure_stack_ptr, (size))
466 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
467 r_re_alloc (&failure_stack_ptr, (nsize))
468 # define REGEX_FREE_STACK(ptr) \
469 r_alloc_free (&failure_stack_ptr)
471 #else /* not using relocating allocator */
475 # define REGEX_ALLOCATE_STACK malloc
476 # define REGEX_REALLOCATE_STACK(source, osize, nsize) realloc (source, nsize)
477 # define REGEX_FREE_STACK free
479 # else /* not REGEX_MALLOC */
481 # define REGEX_ALLOCATE_STACK alloca
483 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
484 REGEX_REALLOCATE (source, osize, nsize)
485 /* No need to explicitly free anything. */
486 # define REGEX_FREE_STACK(arg) ((void)0)
488 # endif /* not REGEX_MALLOC */
489 #endif /* not using relocating allocator */
492 /* True if `size1' is non-NULL and PTR is pointing anywhere inside
493 `string1' or just past its end. This works if PTR is NULL, which is
495 #define FIRST_STRING_P(ptr) \
496 (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
498 /* (Re)Allocate N items of type T using malloc, or fail. */
499 #define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
500 #define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
501 #define RETALLOC_IF(addr, n, t) \
502 if (addr) RETALLOC((addr), (n), t); else (addr) = TALLOC ((n), t)
503 #define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
505 #define BYTEWIDTH 8 /* In bits. */
507 #define STREQ(s1, s2) ((strcmp (s1, s2) == 0))
511 #define MAX(a, b) ((a) > (b) ? (a) : (b))
512 #define MIN(a, b) ((a) < (b) ? (a) : (b))
514 /* Type of source-pattern and string chars. */
515 typedef const unsigned char re_char
;
517 typedef char boolean
;
521 static int re_match_2_internal
_RE_ARGS ((struct re_pattern_buffer
*bufp
,
522 re_char
*string1
, int size1
,
523 re_char
*string2
, int size2
,
525 struct re_registers
*regs
,
528 /* These are the command codes that appear in compiled regular
529 expressions. Some opcodes are followed by argument bytes. A
530 command code can specify any interpretation whatsoever for its
531 arguments. Zero bytes may appear in the compiled regular expression. */
537 /* Succeed right away--no more backtracking. */
540 /* Followed by one byte giving n, then by n literal bytes. */
543 /* Matches any (more or less) character. */
546 /* Matches any one char belonging to specified set. First
547 following byte is number of bitmap bytes. Then come bytes
548 for a bitmap saying which chars are in. Bits in each byte
549 are ordered low-bit-first. A character is in the set if its
550 bit is 1. A character too large to have a bit in the map is
551 automatically not in the set.
553 If the length byte has the 0x80 bit set, then that stuff
554 is followed by a range table:
555 2 bytes of flags for character sets (low 8 bits, high 8 bits)
556 See RANGE_TABLE_WORK_BITS below.
557 2 bytes, the number of pairs that follow (upto 32767)
558 pairs, each 2 multibyte characters,
559 each multibyte character represented as 3 bytes. */
562 /* Same parameters as charset, but match any character that is
563 not one of those specified. */
566 /* Start remembering the text that is matched, for storing in a
567 register. Followed by one byte with the register number, in
568 the range 0 to one less than the pattern buffer's re_nsub
572 /* Stop remembering the text that is matched and store it in a
573 memory register. Followed by one byte with the register
574 number, in the range 0 to one less than `re_nsub' in the
578 /* Match a duplicate of something remembered. Followed by one
579 byte containing the register number. */
582 /* Fail unless at beginning of line. */
585 /* Fail unless at end of line. */
588 /* Succeeds if at beginning of buffer (if emacs) or at beginning
589 of string to be matched (if not). */
592 /* Analogously, for end of buffer/string. */
595 /* Followed by two byte relative address to which to jump. */
598 /* Followed by two-byte relative address of place to resume at
599 in case of failure. */
602 /* Like on_failure_jump, but pushes a placeholder instead of the
603 current string position when executed. */
604 on_failure_keep_string_jump
,
606 /* Just like `on_failure_jump', except that it checks that we
607 don't get stuck in an infinite loop (matching an empty string
609 on_failure_jump_loop
,
611 /* Just like `on_failure_jump_loop', except that it checks for
612 a different kind of loop (the kind that shows up with non-greedy
613 operators). This operation has to be immediately preceded
615 on_failure_jump_nastyloop
,
617 /* A smart `on_failure_jump' used for greedy * and + operators.
618 It analyses the loop before which it is put and if the
619 loop does not require backtracking, it changes itself to
620 `on_failure_keep_string_jump' and short-circuits the loop,
621 else it just defaults to changing itself into `on_failure_jump'.
622 It assumes that it is pointing to just past a `jump'. */
623 on_failure_jump_smart
,
625 /* Followed by two-byte relative address and two-byte number n.
626 After matching N times, jump to the address upon failure.
627 Does not work if N starts at 0: use on_failure_jump_loop
631 /* Followed by two-byte relative address, and two-byte number n.
632 Jump to the address N times, then fail. */
635 /* Set the following two-byte relative address to the
636 subsequent two-byte number. The address *includes* the two
640 wordbeg
, /* Succeeds if at word beginning. */
641 wordend
, /* Succeeds if at word end. */
643 wordbound
, /* Succeeds if at a word boundary. */
644 notwordbound
, /* Succeeds if not at a word boundary. */
646 /* Matches any character whose syntax is specified. Followed by
647 a byte which contains a syntax code, e.g., Sword. */
650 /* Matches any character whose syntax is not that specified. */
654 ,before_dot
, /* Succeeds if before point. */
655 at_dot
, /* Succeeds if at point. */
656 after_dot
, /* Succeeds if after point. */
658 /* Matches any character whose category-set contains the specified
659 category. The operator is followed by a byte which contains a
660 category code (mnemonic ASCII character). */
663 /* Matches any character whose category-set does not contain the
664 specified category. The operator is followed by a byte which
665 contains the category code (mnemonic ASCII character). */
670 /* Common operations on the compiled pattern. */
672 /* Store NUMBER in two contiguous bytes starting at DESTINATION. */
674 #define STORE_NUMBER(destination, number) \
676 (destination)[0] = (number) & 0377; \
677 (destination)[1] = (number) >> 8; \
680 /* Same as STORE_NUMBER, except increment DESTINATION to
681 the byte after where the number is stored. Therefore, DESTINATION
682 must be an lvalue. */
684 #define STORE_NUMBER_AND_INCR(destination, number) \
686 STORE_NUMBER (destination, number); \
687 (destination) += 2; \
690 /* Put into DESTINATION a number stored in two contiguous bytes starting
693 #define EXTRACT_NUMBER(destination, source) \
695 (destination) = *(source) & 0377; \
696 (destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8; \
700 static void extract_number
_RE_ARGS ((int *dest
, re_char
*source
));
702 extract_number (dest
, source
)
706 int temp
= SIGN_EXTEND_CHAR (*(source
+ 1));
707 *dest
= *source
& 0377;
711 # ifndef EXTRACT_MACROS /* To debug the macros. */
712 # undef EXTRACT_NUMBER
713 # define EXTRACT_NUMBER(dest, src) extract_number (&dest, src)
714 # endif /* not EXTRACT_MACROS */
718 /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
719 SOURCE must be an lvalue. */
721 #define EXTRACT_NUMBER_AND_INCR(destination, source) \
723 EXTRACT_NUMBER (destination, source); \
728 static void extract_number_and_incr
_RE_ARGS ((int *destination
,
731 extract_number_and_incr (destination
, source
)
735 extract_number (destination
, *source
);
739 # ifndef EXTRACT_MACROS
740 # undef EXTRACT_NUMBER_AND_INCR
741 # define EXTRACT_NUMBER_AND_INCR(dest, src) \
742 extract_number_and_incr (&dest, &src)
743 # endif /* not EXTRACT_MACROS */
747 /* Store a multibyte character in three contiguous bytes starting
748 DESTINATION, and increment DESTINATION to the byte after where the
749 character is stored. Therefore, DESTINATION must be an lvalue. */
751 #define STORE_CHARACTER_AND_INCR(destination, character) \
753 (destination)[0] = (character) & 0377; \
754 (destination)[1] = ((character) >> 8) & 0377; \
755 (destination)[2] = (character) >> 16; \
756 (destination) += 3; \
759 /* Put into DESTINATION a character stored in three contiguous bytes
760 starting at SOURCE. */
762 #define EXTRACT_CHARACTER(destination, source) \
764 (destination) = ((source)[0] \
765 | ((source)[1] << 8) \
766 | ((source)[2] << 16)); \
770 /* Macros for charset. */
772 /* Size of bitmap of charset P in bytes. P is a start of charset,
773 i.e. *P is (re_opcode_t) charset or (re_opcode_t) charset_not. */
774 #define CHARSET_BITMAP_SIZE(p) ((p)[1] & 0x7F)
776 /* Nonzero if charset P has range table. */
777 #define CHARSET_RANGE_TABLE_EXISTS_P(p) ((p)[1] & 0x80)
779 /* Return the address of range table of charset P. But not the start
780 of table itself, but the before where the number of ranges is
781 stored. `2 +' means to skip re_opcode_t and size of bitmap,
782 and the 2 bytes of flags at the start of the range table. */
783 #define CHARSET_RANGE_TABLE(p) (&(p)[4 + CHARSET_BITMAP_SIZE (p)])
785 /* Extract the bit flags that start a range table. */
786 #define CHARSET_RANGE_TABLE_BITS(p) \
787 ((p)[2 + CHARSET_BITMAP_SIZE (p)] \
788 + (p)[3 + CHARSET_BITMAP_SIZE (p)] * 0x100)
790 /* Test if C is listed in the bitmap of charset P. */
791 #define CHARSET_LOOKUP_BITMAP(p, c) \
792 ((c) < CHARSET_BITMAP_SIZE (p) * BYTEWIDTH \
793 && (p)[2 + (c) / BYTEWIDTH] & (1 << ((c) % BYTEWIDTH)))
795 /* Return the address of end of RANGE_TABLE. COUNT is number of
796 ranges (which is a pair of (start, end)) in the RANGE_TABLE. `* 2'
797 is start of range and end of range. `* 3' is size of each start
799 #define CHARSET_RANGE_TABLE_END(range_table, count) \
800 ((range_table) + (count) * 2 * 3)
802 /* Test if C is in RANGE_TABLE. A flag NOT is negated if C is in.
803 COUNT is number of ranges in RANGE_TABLE. */
804 #define CHARSET_LOOKUP_RANGE_TABLE_RAW(not, c, range_table, count) \
807 re_wchar_t range_start, range_end; \
809 re_char *range_table_end \
810 = CHARSET_RANGE_TABLE_END ((range_table), (count)); \
812 for (p = (range_table); p < range_table_end; p += 2 * 3) \
814 EXTRACT_CHARACTER (range_start, p); \
815 EXTRACT_CHARACTER (range_end, p + 3); \
817 if (range_start <= (c) && (c) <= range_end) \
826 /* Test if C is in range table of CHARSET. The flag NOT is negated if
827 C is listed in it. */
828 #define CHARSET_LOOKUP_RANGE_TABLE(not, c, charset) \
831 /* Number of ranges in range table. */ \
833 re_char *range_table = CHARSET_RANGE_TABLE (charset); \
835 EXTRACT_NUMBER_AND_INCR (count, range_table); \
836 CHARSET_LOOKUP_RANGE_TABLE_RAW ((not), (c), range_table, count); \
840 /* If DEBUG is defined, Regex prints many voluminous messages about what
841 it is doing (if the variable `debug' is nonzero). If linked with the
842 main program in `iregex.c', you can enter patterns and strings
843 interactively. And if linked with the main program in `main.c' and
844 the other test files, you can run the already-written tests. */
848 /* We use standard I/O for debugging. */
851 /* It is useful to test things that ``must'' be true when debugging. */
854 static int debug
= -100000;
856 # define DEBUG_STATEMENT(e) e
857 # define DEBUG_PRINT1(x) if (debug > 0) printf (x)
858 # define DEBUG_PRINT2(x1, x2) if (debug > 0) printf (x1, x2)
859 # define DEBUG_PRINT3(x1, x2, x3) if (debug > 0) printf (x1, x2, x3)
860 # define DEBUG_PRINT4(x1, x2, x3, x4) if (debug > 0) printf (x1, x2, x3, x4)
861 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
862 if (debug > 0) print_partial_compiled_pattern (s, e)
863 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
864 if (debug > 0) print_double_string (w, s1, sz1, s2, sz2)
867 /* Print the fastmap in human-readable form. */
870 print_fastmap (fastmap
)
873 unsigned was_a_range
= 0;
876 while (i
< (1 << BYTEWIDTH
))
882 while (i
< (1 << BYTEWIDTH
) && fastmap
[i
])
898 /* Print a compiled pattern string in human-readable form, starting at
899 the START pointer into it and ending just before the pointer END. */
902 print_partial_compiled_pattern (start
, end
)
916 /* Loop over pattern commands. */
919 printf ("%d:\t", p
- start
);
921 switch ((re_opcode_t
) *p
++)
933 printf ("/exactn/%d", mcnt
);
943 printf ("/start_memory/%d", *p
++);
947 printf ("/stop_memory/%d", *p
++);
951 printf ("/duplicate/%d", *p
++);
961 register int c
, last
= -100;
962 register int in_range
= 0;
963 int length
= CHARSET_BITMAP_SIZE (p
- 1);
964 int has_range_table
= CHARSET_RANGE_TABLE_EXISTS_P (p
- 1);
966 printf ("/charset [%s",
967 (re_opcode_t
) *(p
- 1) == charset_not
? "^" : "");
969 assert (p
+ *p
< pend
);
971 for (c
= 0; c
< 256; c
++)
973 && (p
[1 + (c
/8)] & (1 << (c
% 8))))
975 /* Are we starting a range? */
976 if (last
+ 1 == c
&& ! in_range
)
981 /* Have we broken a range? */
982 else if (last
+ 1 != c
&& in_range
)
1001 if (has_range_table
)
1004 printf ("has-range-table");
1006 /* ??? Should print the range table; for now, just skip it. */
1007 p
+= 2; /* skip range table bits */
1008 EXTRACT_NUMBER_AND_INCR (count
, p
);
1009 p
= CHARSET_RANGE_TABLE_END (p
, count
);
1015 printf ("/begline");
1019 printf ("/endline");
1022 case on_failure_jump
:
1023 extract_number_and_incr (&mcnt
, &p
);
1024 printf ("/on_failure_jump to %d", p
+ mcnt
- start
);
1027 case on_failure_keep_string_jump
:
1028 extract_number_and_incr (&mcnt
, &p
);
1029 printf ("/on_failure_keep_string_jump to %d", p
+ mcnt
- start
);
1032 case on_failure_jump_nastyloop
:
1033 extract_number_and_incr (&mcnt
, &p
);
1034 printf ("/on_failure_jump_nastyloop to %d", p
+ mcnt
- start
);
1037 case on_failure_jump_loop
:
1038 extract_number_and_incr (&mcnt
, &p
);
1039 printf ("/on_failure_jump_loop to %d", p
+ mcnt
- start
);
1042 case on_failure_jump_smart
:
1043 extract_number_and_incr (&mcnt
, &p
);
1044 printf ("/on_failure_jump_smart to %d", p
+ mcnt
- start
);
1048 extract_number_and_incr (&mcnt
, &p
);
1049 printf ("/jump to %d", p
+ mcnt
- start
);
1053 extract_number_and_incr (&mcnt
, &p
);
1054 extract_number_and_incr (&mcnt2
, &p
);
1055 printf ("/succeed_n to %d, %d times", p
- 2 + mcnt
- start
, mcnt2
);
1059 extract_number_and_incr (&mcnt
, &p
);
1060 extract_number_and_incr (&mcnt2
, &p
);
1061 printf ("/jump_n to %d, %d times", p
- 2 + mcnt
- start
, mcnt2
);
1065 extract_number_and_incr (&mcnt
, &p
);
1066 extract_number_and_incr (&mcnt2
, &p
);
1067 printf ("/set_number_at location %d to %d", p
- 2 + mcnt
- start
, mcnt2
);
1071 printf ("/wordbound");
1075 printf ("/notwordbound");
1079 printf ("/wordbeg");
1083 printf ("/wordend");
1086 printf ("/syntaxspec");
1088 printf ("/%d", mcnt
);
1092 printf ("/notsyntaxspec");
1094 printf ("/%d", mcnt
);
1099 printf ("/before_dot");
1107 printf ("/after_dot");
1111 printf ("/categoryspec");
1113 printf ("/%d", mcnt
);
1116 case notcategoryspec
:
1117 printf ("/notcategoryspec");
1119 printf ("/%d", mcnt
);
1132 printf ("?%d", *(p
-1));
1138 printf ("%d:\tend of pattern.\n", p
- start
);
1143 print_compiled_pattern (bufp
)
1144 struct re_pattern_buffer
*bufp
;
1146 re_char
*buffer
= bufp
->buffer
;
1148 print_partial_compiled_pattern (buffer
, buffer
+ bufp
->used
);
1149 printf ("%ld bytes used/%ld bytes allocated.\n",
1150 bufp
->used
, bufp
->allocated
);
1152 if (bufp
->fastmap_accurate
&& bufp
->fastmap
)
1154 printf ("fastmap: ");
1155 print_fastmap (bufp
->fastmap
);
1158 printf ("re_nsub: %d\t", bufp
->re_nsub
);
1159 printf ("regs_alloc: %d\t", bufp
->regs_allocated
);
1160 printf ("can_be_null: %d\t", bufp
->can_be_null
);
1161 printf ("no_sub: %d\t", bufp
->no_sub
);
1162 printf ("not_bol: %d\t", bufp
->not_bol
);
1163 printf ("not_eol: %d\t", bufp
->not_eol
);
1164 printf ("syntax: %lx\n", bufp
->syntax
);
1166 /* Perhaps we should print the translate table? */
1171 print_double_string (where
, string1
, size1
, string2
, size2
)
1184 if (FIRST_STRING_P (where
))
1186 for (this_char
= where
- string1
; this_char
< size1
; this_char
++)
1187 putchar (string1
[this_char
]);
1192 for (this_char
= where
- string2
; this_char
< size2
; this_char
++)
1193 putchar (string2
[this_char
]);
1197 #else /* not DEBUG */
1202 # define DEBUG_STATEMENT(e)
1203 # define DEBUG_PRINT1(x)
1204 # define DEBUG_PRINT2(x1, x2)
1205 # define DEBUG_PRINT3(x1, x2, x3)
1206 # define DEBUG_PRINT4(x1, x2, x3, x4)
1207 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
1208 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
1210 #endif /* not DEBUG */
1212 /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
1213 also be assigned to arbitrarily: each pattern buffer stores its own
1214 syntax, so it can be changed between regex compilations. */
1215 /* This has no initializer because initialized variables in Emacs
1216 become read-only after dumping. */
1217 reg_syntax_t re_syntax_options
;
1220 /* Specify the precise syntax of regexps for compilation. This provides
1221 for compatibility for various utilities which historically have
1222 different, incompatible syntaxes.
1224 The argument SYNTAX is a bit mask comprised of the various bits
1225 defined in regex.h. We return the old syntax. */
1228 re_set_syntax (syntax
)
1229 reg_syntax_t syntax
;
1231 reg_syntax_t ret
= re_syntax_options
;
1233 re_syntax_options
= syntax
;
1236 WEAK_ALIAS (__re_set_syntax
, re_set_syntax
)
1238 /* This table gives an error message for each of the error codes listed
1239 in regex.h. Obviously the order here has to be same as there.
1240 POSIX doesn't require that we do anything for REG_NOERROR,
1241 but why not be nice? */
1243 static const char *re_error_msgid
[] =
1245 gettext_noop ("Success"), /* REG_NOERROR */
1246 gettext_noop ("No match"), /* REG_NOMATCH */
1247 gettext_noop ("Invalid regular expression"), /* REG_BADPAT */
1248 gettext_noop ("Invalid collation character"), /* REG_ECOLLATE */
1249 gettext_noop ("Invalid character class name"), /* REG_ECTYPE */
1250 gettext_noop ("Trailing backslash"), /* REG_EESCAPE */
1251 gettext_noop ("Invalid back reference"), /* REG_ESUBREG */
1252 gettext_noop ("Unmatched [ or [^"), /* REG_EBRACK */
1253 gettext_noop ("Unmatched ( or \\("), /* REG_EPAREN */
1254 gettext_noop ("Unmatched \\{"), /* REG_EBRACE */
1255 gettext_noop ("Invalid content of \\{\\}"), /* REG_BADBR */
1256 gettext_noop ("Invalid range end"), /* REG_ERANGE */
1257 gettext_noop ("Memory exhausted"), /* REG_ESPACE */
1258 gettext_noop ("Invalid preceding regular expression"), /* REG_BADRPT */
1259 gettext_noop ("Premature end of regular expression"), /* REG_EEND */
1260 gettext_noop ("Regular expression too big"), /* REG_ESIZE */
1261 gettext_noop ("Unmatched ) or \\)"), /* REG_ERPAREN */
1264 /* Avoiding alloca during matching, to placate r_alloc. */
1266 /* Define MATCH_MAY_ALLOCATE unless we need to make sure that the
1267 searching and matching functions should not call alloca. On some
1268 systems, alloca is implemented in terms of malloc, and if we're
1269 using the relocating allocator routines, then malloc could cause a
1270 relocation, which might (if the strings being searched are in the
1271 ralloc heap) shift the data out from underneath the regexp
1274 Here's another reason to avoid allocation: Emacs
1275 processes input from X in a signal handler; processing X input may
1276 call malloc; if input arrives while a matching routine is calling
1277 malloc, then we're scrod. But Emacs can't just block input while
1278 calling matching routines; then we don't notice interrupts when
1279 they come in. So, Emacs blocks input around all regexp calls
1280 except the matching calls, which it leaves unprotected, in the
1281 faith that they will not malloc. */
1283 /* Normally, this is fine. */
1284 #define MATCH_MAY_ALLOCATE
1286 /* When using GNU C, we are not REALLY using the C alloca, no matter
1287 what config.h may say. So don't take precautions for it. */
1292 /* The match routines may not allocate if (1) they would do it with malloc
1293 and (2) it's not safe for them to use malloc.
1294 Note that if REL_ALLOC is defined, matching would not use malloc for the
1295 failure stack, but we would still use it for the register vectors;
1296 so REL_ALLOC should not affect this. */
1297 #if (defined C_ALLOCA || defined REGEX_MALLOC) && defined emacs
1298 # undef MATCH_MAY_ALLOCATE
1302 /* Failure stack declarations and macros; both re_compile_fastmap and
1303 re_match_2 use a failure stack. These have to be macros because of
1304 REGEX_ALLOCATE_STACK. */
1307 /* Approximate number of failure points for which to initially allocate space
1308 when matching. If this number is exceeded, we allocate more
1309 space, so it is not a hard limit. */
1310 #ifndef INIT_FAILURE_ALLOC
1311 # define INIT_FAILURE_ALLOC 20
1314 /* Roughly the maximum number of failure points on the stack. Would be
1315 exactly that if always used TYPICAL_FAILURE_SIZE items each time we failed.
1316 This is a variable only so users of regex can assign to it; we never
1317 change it ourselves. */
1318 # if defined MATCH_MAY_ALLOCATE
1319 /* Note that 4400 was enough to cause a crash on Alpha OSF/1,
1320 whose default stack limit is 2mb. In order for a larger
1321 value to work reliably, you have to try to make it accord
1322 with the process stack limit. */
1323 size_t re_max_failures
= 40000;
1325 size_t re_max_failures
= 4000;
1328 union fail_stack_elt
1331 /* This should be the biggest `int' that's no bigger than a pointer. */
1335 typedef union fail_stack_elt fail_stack_elt_t
;
1339 fail_stack_elt_t
*stack
;
1341 size_t avail
; /* Offset of next open position. */
1342 size_t frame
; /* Offset of the cur constructed frame. */
1345 #define FAIL_STACK_EMPTY() (fail_stack.frame == 0)
1346 #define FAIL_STACK_FULL() (fail_stack.avail == fail_stack.size)
1349 /* Define macros to initialize and free the failure stack.
1350 Do `return -2' if the alloc fails. */
1352 #ifdef MATCH_MAY_ALLOCATE
1353 # define INIT_FAIL_STACK() \
1355 fail_stack.stack = (fail_stack_elt_t *) \
1356 REGEX_ALLOCATE_STACK (INIT_FAILURE_ALLOC * TYPICAL_FAILURE_SIZE \
1357 * sizeof (fail_stack_elt_t)); \
1359 if (fail_stack.stack == NULL) \
1362 fail_stack.size = INIT_FAILURE_ALLOC; \
1363 fail_stack.avail = 0; \
1364 fail_stack.frame = 0; \
1367 # define RESET_FAIL_STACK() REGEX_FREE_STACK (fail_stack.stack)
1369 # define INIT_FAIL_STACK() \
1371 fail_stack.avail = 0; \
1372 fail_stack.frame = 0; \
1375 # define RESET_FAIL_STACK() ((void)0)
1379 /* Double the size of FAIL_STACK, up to a limit
1380 which allows approximately `re_max_failures' items.
1382 Return 1 if succeeds, and 0 if either ran out of memory
1383 allocating space for it or it was already too large.
1385 REGEX_REALLOCATE_STACK requires `destination' be declared. */
1387 /* Factor to increase the failure stack size by
1388 when we increase it.
1389 This used to be 2, but 2 was too wasteful
1390 because the old discarded stacks added up to as much space
1391 were as ultimate, maximum-size stack. */
1392 #define FAIL_STACK_GROWTH_FACTOR 4
1394 #define GROW_FAIL_STACK(fail_stack) \
1395 (((fail_stack).size * sizeof (fail_stack_elt_t) \
1396 >= re_max_failures * TYPICAL_FAILURE_SIZE) \
1398 : ((fail_stack).stack \
1399 = (fail_stack_elt_t *) \
1400 REGEX_REALLOCATE_STACK ((fail_stack).stack, \
1401 (fail_stack).size * sizeof (fail_stack_elt_t), \
1402 MIN (re_max_failures * TYPICAL_FAILURE_SIZE, \
1403 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1404 * FAIL_STACK_GROWTH_FACTOR))), \
1406 (fail_stack).stack == NULL \
1408 : ((fail_stack).size \
1409 = (MIN (re_max_failures * TYPICAL_FAILURE_SIZE, \
1410 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1411 * FAIL_STACK_GROWTH_FACTOR)) \
1412 / sizeof (fail_stack_elt_t)), \
1416 /* Push a pointer value onto the failure stack.
1417 Assumes the variable `fail_stack'. Probably should only
1418 be called from within `PUSH_FAILURE_POINT'. */
1419 #define PUSH_FAILURE_POINTER(item) \
1420 fail_stack.stack[fail_stack.avail++].pointer = (item)
1422 /* This pushes an integer-valued item onto the failure stack.
1423 Assumes the variable `fail_stack'. Probably should only
1424 be called from within `PUSH_FAILURE_POINT'. */
1425 #define PUSH_FAILURE_INT(item) \
1426 fail_stack.stack[fail_stack.avail++].integer = (item)
1428 /* Push a fail_stack_elt_t value onto the failure stack.
1429 Assumes the variable `fail_stack'. Probably should only
1430 be called from within `PUSH_FAILURE_POINT'. */
1431 #define PUSH_FAILURE_ELT(item) \
1432 fail_stack.stack[fail_stack.avail++] = (item)
1434 /* These three POP... operations complement the three PUSH... operations.
1435 All assume that `fail_stack' is nonempty. */
1436 #define POP_FAILURE_POINTER() fail_stack.stack[--fail_stack.avail].pointer
1437 #define POP_FAILURE_INT() fail_stack.stack[--fail_stack.avail].integer
1438 #define POP_FAILURE_ELT() fail_stack.stack[--fail_stack.avail]
1440 /* Individual items aside from the registers. */
1441 #define NUM_NONREG_ITEMS 3
1443 /* Used to examine the stack (to detect infinite loops). */
1444 #define FAILURE_PAT(h) fail_stack.stack[(h) - 1].pointer
1445 #define FAILURE_STR(h) (fail_stack.stack[(h) - 2].pointer)
1446 #define NEXT_FAILURE_HANDLE(h) fail_stack.stack[(h) - 3].integer
1447 #define TOP_FAILURE_HANDLE() fail_stack.frame
1450 #define ENSURE_FAIL_STACK(space) \
1451 while (REMAINING_AVAIL_SLOTS <= space) { \
1452 if (!GROW_FAIL_STACK (fail_stack)) \
1454 DEBUG_PRINT2 ("\n Doubled stack; size now: %d\n", (fail_stack).size);\
1455 DEBUG_PRINT2 (" slots available: %d\n", REMAINING_AVAIL_SLOTS);\
1458 /* Push register NUM onto the stack. */
1459 #define PUSH_FAILURE_REG(num) \
1461 char *destination; \
1462 ENSURE_FAIL_STACK(3); \
1463 DEBUG_PRINT4 (" Push reg %d (spanning %p -> %p)\n", \
1464 num, regstart[num], regend[num]); \
1465 PUSH_FAILURE_POINTER (regstart[num]); \
1466 PUSH_FAILURE_POINTER (regend[num]); \
1467 PUSH_FAILURE_INT (num); \
1470 /* Change the counter's value to VAL, but make sure that it will
1471 be reset when backtracking. */
1472 #define PUSH_NUMBER(ptr,val) \
1474 char *destination; \
1476 ENSURE_FAIL_STACK(3); \
1477 EXTRACT_NUMBER (c, ptr); \
1478 DEBUG_PRINT4 (" Push number %p = %d -> %d\n", ptr, c, val); \
1479 PUSH_FAILURE_INT (c); \
1480 PUSH_FAILURE_POINTER (ptr); \
1481 PUSH_FAILURE_INT (-1); \
1482 STORE_NUMBER (ptr, val); \
1485 /* Pop a saved register off the stack. */
1486 #define POP_FAILURE_REG_OR_COUNT() \
1488 int reg = POP_FAILURE_INT (); \
1491 /* It's a counter. */ \
1492 /* Here, we discard `const', making re_match non-reentrant. */ \
1493 unsigned char *ptr = (unsigned char*) POP_FAILURE_POINTER (); \
1494 reg = POP_FAILURE_INT (); \
1495 STORE_NUMBER (ptr, reg); \
1496 DEBUG_PRINT3 (" Pop counter %p = %d\n", ptr, reg); \
1500 regend[reg] = POP_FAILURE_POINTER (); \
1501 regstart[reg] = POP_FAILURE_POINTER (); \
1502 DEBUG_PRINT4 (" Pop reg %d (spanning %p -> %p)\n", \
1503 reg, regstart[reg], regend[reg]); \
1507 /* Check that we are not stuck in an infinite loop. */
1508 #define CHECK_INFINITE_LOOP(pat_cur, string_place) \
1510 int failure = TOP_FAILURE_HANDLE(); \
1511 /* Check for infinite matching loops */ \
1512 while (failure > 0 && \
1513 (FAILURE_STR (failure) == string_place \
1514 || FAILURE_STR (failure) == NULL)) \
1516 assert (FAILURE_PAT (failure) >= bufp->buffer \
1517 && FAILURE_PAT (failure) <= bufp->buffer + bufp->used); \
1518 if (FAILURE_PAT (failure) == pat_cur) \
1520 DEBUG_PRINT2 (" Other pattern: %p\n", FAILURE_PAT (failure)); \
1521 failure = NEXT_FAILURE_HANDLE(failure); \
1523 DEBUG_PRINT2 (" Other string: %p\n", FAILURE_STR (failure)); \
1526 /* Push the information about the state we will need
1527 if we ever fail back to it.
1529 Requires variables fail_stack, regstart, regend and
1530 num_regs be declared. GROW_FAIL_STACK requires `destination' be
1533 Does `return FAILURE_CODE' if runs out of memory. */
1535 #define PUSH_FAILURE_POINT(pattern, string_place) \
1537 char *destination; \
1538 /* Must be int, so when we don't save any registers, the arithmetic \
1539 of 0 + -1 isn't done as unsigned. */ \
1541 DEBUG_STATEMENT (nfailure_points_pushed++); \
1542 DEBUG_PRINT1 ("\nPUSH_FAILURE_POINT:\n"); \
1543 DEBUG_PRINT2 (" Before push, next avail: %d\n", (fail_stack).avail); \
1544 DEBUG_PRINT2 (" size: %d\n", (fail_stack).size);\
1546 ENSURE_FAIL_STACK (NUM_NONREG_ITEMS); \
1548 DEBUG_PRINT1 ("\n"); \
1550 DEBUG_PRINT2 (" Push frame index: %d\n", fail_stack.frame); \
1551 PUSH_FAILURE_INT (fail_stack.frame); \
1553 DEBUG_PRINT2 (" Push string %p: `", string_place); \
1554 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, size2);\
1555 DEBUG_PRINT1 ("'\n"); \
1556 PUSH_FAILURE_POINTER (string_place); \
1558 DEBUG_PRINT2 (" Push pattern %p: ", pattern); \
1559 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern, pend); \
1560 PUSH_FAILURE_POINTER (pattern); \
1562 /* Close the frame by moving the frame pointer past it. */ \
1563 fail_stack.frame = fail_stack.avail; \
1566 /* Estimate the size of data pushed by a typical failure stack entry.
1567 An estimate is all we need, because all we use this for
1568 is to choose a limit for how big to make the failure stack. */
1570 #define TYPICAL_FAILURE_SIZE 20
1572 /* How many items can still be added to the stack without overflowing it. */
1573 #define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
1576 /* Pops what PUSH_FAIL_STACK pushes.
1578 We restore into the parameters, all of which should be lvalues:
1579 STR -- the saved data position.
1580 PAT -- the saved pattern position.
1581 REGSTART, REGEND -- arrays of string positions.
1583 Also assumes the variables `fail_stack' and (if debugging), `bufp',
1584 `pend', `string1', `size1', `string2', and `size2'. */
1586 #define POP_FAILURE_POINT(str, pat) \
1588 assert (!FAIL_STACK_EMPTY ()); \
1590 /* Remove failure points and point to how many regs pushed. */ \
1591 DEBUG_PRINT1 ("POP_FAILURE_POINT:\n"); \
1592 DEBUG_PRINT2 (" Before pop, next avail: %d\n", fail_stack.avail); \
1593 DEBUG_PRINT2 (" size: %d\n", fail_stack.size); \
1595 /* Pop the saved registers. */ \
1596 while (fail_stack.frame < fail_stack.avail) \
1597 POP_FAILURE_REG_OR_COUNT (); \
1599 pat = POP_FAILURE_POINTER (); \
1600 DEBUG_PRINT2 (" Popping pattern %p: ", pat); \
1601 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
1603 /* If the saved string location is NULL, it came from an \
1604 on_failure_keep_string_jump opcode, and we want to throw away the \
1605 saved NULL, thus retaining our current position in the string. */ \
1606 str = POP_FAILURE_POINTER (); \
1607 DEBUG_PRINT2 (" Popping string %p: `", str); \
1608 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
1609 DEBUG_PRINT1 ("'\n"); \
1611 fail_stack.frame = POP_FAILURE_INT (); \
1612 DEBUG_PRINT2 (" Popping frame index: %d\n", fail_stack.frame); \
1614 assert (fail_stack.avail >= 0); \
1615 assert (fail_stack.frame <= fail_stack.avail); \
1617 DEBUG_STATEMENT (nfailure_points_popped++); \
1618 } while (0) /* POP_FAILURE_POINT */
1622 /* Registers are set to a sentinel when they haven't yet matched. */
1623 #define REG_UNSET(e) ((e) == NULL)
1625 /* Subroutine declarations and macros for regex_compile. */
1627 static reg_errcode_t regex_compile
_RE_ARGS ((re_char
*pattern
, size_t size
,
1628 reg_syntax_t syntax
,
1629 struct re_pattern_buffer
*bufp
));
1630 static void store_op1
_RE_ARGS ((re_opcode_t op
, unsigned char *loc
, int arg
));
1631 static void store_op2
_RE_ARGS ((re_opcode_t op
, unsigned char *loc
,
1632 int arg1
, int arg2
));
1633 static void insert_op1
_RE_ARGS ((re_opcode_t op
, unsigned char *loc
,
1634 int arg
, unsigned char *end
));
1635 static void insert_op2
_RE_ARGS ((re_opcode_t op
, unsigned char *loc
,
1636 int arg1
, int arg2
, unsigned char *end
));
1637 static boolean at_begline_loc_p
_RE_ARGS ((re_char
*pattern
,
1639 reg_syntax_t syntax
));
1640 static boolean at_endline_loc_p
_RE_ARGS ((re_char
*p
,
1642 reg_syntax_t syntax
));
1643 static re_char
*skip_one_char
_RE_ARGS ((re_char
*p
));
1644 static int analyse_first
_RE_ARGS ((re_char
*p
, re_char
*pend
,
1645 char *fastmap
, const int multibyte
));
1647 /* Fetch the next character in the uncompiled pattern---translating it
1649 #define PATFETCH(c) \
1652 c = TRANSLATE (c); \
1655 /* Fetch the next character in the uncompiled pattern, with no
1657 #define PATFETCH_RAW(c) \
1660 if (p == pend) return REG_EEND; \
1661 c = RE_STRING_CHAR_AND_LENGTH (p, pend - p, len); \
1666 /* If `translate' is non-null, return translate[D], else just D. We
1667 cast the subscript to translate because some data is declared as
1668 `char *', to avoid warnings when a string constant is passed. But
1669 when we use a character as a subscript we must make it unsigned. */
1671 # define TRANSLATE(d) \
1672 (RE_TRANSLATE_P (translate) ? RE_TRANSLATE (translate, (d)) : (d))
1676 /* Macros for outputting the compiled pattern into `buffer'. */
1678 /* If the buffer isn't allocated when it comes in, use this. */
1679 #define INIT_BUF_SIZE 32
1681 /* Make sure we have at least N more bytes of space in buffer. */
1682 #define GET_BUFFER_SPACE(n) \
1683 while ((size_t) (b - bufp->buffer + (n)) > bufp->allocated) \
1686 /* Make sure we have one more byte of buffer space and then add C to it. */
1687 #define BUF_PUSH(c) \
1689 GET_BUFFER_SPACE (1); \
1690 *b++ = (unsigned char) (c); \
1694 /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
1695 #define BUF_PUSH_2(c1, c2) \
1697 GET_BUFFER_SPACE (2); \
1698 *b++ = (unsigned char) (c1); \
1699 *b++ = (unsigned char) (c2); \
1703 /* As with BUF_PUSH_2, except for three bytes. */
1704 #define BUF_PUSH_3(c1, c2, c3) \
1706 GET_BUFFER_SPACE (3); \
1707 *b++ = (unsigned char) (c1); \
1708 *b++ = (unsigned char) (c2); \
1709 *b++ = (unsigned char) (c3); \
1713 /* Store a jump with opcode OP at LOC to location TO. We store a
1714 relative address offset by the three bytes the jump itself occupies. */
1715 #define STORE_JUMP(op, loc, to) \
1716 store_op1 (op, loc, (to) - (loc) - 3)
1718 /* Likewise, for a two-argument jump. */
1719 #define STORE_JUMP2(op, loc, to, arg) \
1720 store_op2 (op, loc, (to) - (loc) - 3, arg)
1722 /* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
1723 #define INSERT_JUMP(op, loc, to) \
1724 insert_op1 (op, loc, (to) - (loc) - 3, b)
1726 /* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
1727 #define INSERT_JUMP2(op, loc, to, arg) \
1728 insert_op2 (op, loc, (to) - (loc) - 3, arg, b)
1731 /* This is not an arbitrary limit: the arguments which represent offsets
1732 into the pattern are two bytes long. So if 2^16 bytes turns out to
1733 be too small, many things would have to change. */
1734 /* Any other compiler which, like MSC, has allocation limit below 2^16
1735 bytes will have to use approach similar to what was done below for
1736 MSC and drop MAX_BUF_SIZE a bit. Otherwise you may end up
1737 reallocating to 0 bytes. Such thing is not going to work too well.
1738 You have been warned!! */
1739 #if defined _MSC_VER && !defined WIN32
1740 /* Microsoft C 16-bit versions limit malloc to approx 65512 bytes. */
1741 # define MAX_BUF_SIZE 65500L
1743 # define MAX_BUF_SIZE (1L << 16)
1746 /* Extend the buffer by twice its current size via realloc and
1747 reset the pointers that pointed into the old block to point to the
1748 correct places in the new one. If extending the buffer results in it
1749 being larger than MAX_BUF_SIZE, then flag memory exhausted. */
1750 #if __BOUNDED_POINTERS__
1751 # define SET_HIGH_BOUND(P) (__ptrhigh (P) = __ptrlow (P) + bufp->allocated)
1752 # define MOVE_BUFFER_POINTER(P) \
1753 (__ptrlow (P) += incr, SET_HIGH_BOUND (P), __ptrvalue (P) += incr)
1754 # define ELSE_EXTEND_BUFFER_HIGH_BOUND \
1757 SET_HIGH_BOUND (b); \
1758 SET_HIGH_BOUND (begalt); \
1759 if (fixup_alt_jump) \
1760 SET_HIGH_BOUND (fixup_alt_jump); \
1762 SET_HIGH_BOUND (laststart); \
1763 if (pending_exact) \
1764 SET_HIGH_BOUND (pending_exact); \
1767 # define MOVE_BUFFER_POINTER(P) (P) += incr
1768 # define ELSE_EXTEND_BUFFER_HIGH_BOUND
1770 #define EXTEND_BUFFER() \
1772 re_char *old_buffer = bufp->buffer; \
1773 if (bufp->allocated == MAX_BUF_SIZE) \
1775 bufp->allocated <<= 1; \
1776 if (bufp->allocated > MAX_BUF_SIZE) \
1777 bufp->allocated = MAX_BUF_SIZE; \
1778 RETALLOC (bufp->buffer, bufp->allocated, unsigned char); \
1779 if (bufp->buffer == NULL) \
1780 return REG_ESPACE; \
1781 /* If the buffer moved, move all the pointers into it. */ \
1782 if (old_buffer != bufp->buffer) \
1784 int incr = bufp->buffer - old_buffer; \
1785 MOVE_BUFFER_POINTER (b); \
1786 MOVE_BUFFER_POINTER (begalt); \
1787 if (fixup_alt_jump) \
1788 MOVE_BUFFER_POINTER (fixup_alt_jump); \
1790 MOVE_BUFFER_POINTER (laststart); \
1791 if (pending_exact) \
1792 MOVE_BUFFER_POINTER (pending_exact); \
1794 ELSE_EXTEND_BUFFER_HIGH_BOUND \
1798 /* Since we have one byte reserved for the register number argument to
1799 {start,stop}_memory, the maximum number of groups we can report
1800 things about is what fits in that byte. */
1801 #define MAX_REGNUM 255
1803 /* But patterns can have more than `MAX_REGNUM' registers. We just
1804 ignore the excess. */
1805 typedef unsigned regnum_t
;
1808 /* Macros for the compile stack. */
1810 /* Since offsets can go either forwards or backwards, this type needs to
1811 be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
1812 /* int may be not enough when sizeof(int) == 2. */
1813 typedef long pattern_offset_t
;
1817 pattern_offset_t begalt_offset
;
1818 pattern_offset_t fixup_alt_jump
;
1819 pattern_offset_t laststart_offset
;
1821 } compile_stack_elt_t
;
1826 compile_stack_elt_t
*stack
;
1828 unsigned avail
; /* Offset of next open position. */
1829 } compile_stack_type
;
1832 #define INIT_COMPILE_STACK_SIZE 32
1834 #define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
1835 #define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
1837 /* The next available element. */
1838 #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
1841 /* Structure to manage work area for range table. */
1842 struct range_table_work_area
1844 int *table
; /* actual work area. */
1845 int allocated
; /* allocated size for work area in bytes. */
1846 int used
; /* actually used size in words. */
1847 int bits
; /* flag to record character classes */
1850 /* Make sure that WORK_AREA can hold more N multibyte characters. */
1851 #define EXTEND_RANGE_TABLE_WORK_AREA(work_area, n) \
1853 if (((work_area).used + (n)) * sizeof (int) > (work_area).allocated) \
1855 (work_area).allocated += 16 * sizeof (int); \
1856 if ((work_area).table) \
1858 = (int *) realloc ((work_area).table, (work_area).allocated); \
1861 = (int *) malloc ((work_area).allocated); \
1862 if ((work_area).table == 0) \
1863 FREE_STACK_RETURN (REG_ESPACE); \
1867 #define SET_RANGE_TABLE_WORK_AREA_BIT(work_area, bit) \
1868 (work_area).bits |= (bit)
1870 /* Bits used to implement the multibyte-part of the various character classes
1871 such as [:alnum:] in a charset's range table. */
1872 #define BIT_WORD 0x1
1873 #define BIT_LOWER 0x2
1874 #define BIT_PUNCT 0x4
1875 #define BIT_SPACE 0x8
1876 #define BIT_UPPER 0x10
1877 #define BIT_MULTIBYTE 0x20
1879 /* Set a range (RANGE_START, RANGE_END) to WORK_AREA. */
1880 #define SET_RANGE_TABLE_WORK_AREA(work_area, range_start, range_end) \
1882 EXTEND_RANGE_TABLE_WORK_AREA ((work_area), 2); \
1883 (work_area).table[(work_area).used++] = (range_start); \
1884 (work_area).table[(work_area).used++] = (range_end); \
1887 /* Free allocated memory for WORK_AREA. */
1888 #define FREE_RANGE_TABLE_WORK_AREA(work_area) \
1890 if ((work_area).table) \
1891 free ((work_area).table); \
1894 #define CLEAR_RANGE_TABLE_WORK_USED(work_area) ((work_area).used = 0, (work_area).bits = 0)
1895 #define RANGE_TABLE_WORK_USED(work_area) ((work_area).used)
1896 #define RANGE_TABLE_WORK_BITS(work_area) ((work_area).bits)
1897 #define RANGE_TABLE_WORK_ELT(work_area, i) ((work_area).table[i])
1900 /* Set the bit for character C in a list. */
1901 #define SET_LIST_BIT(c) (b[((c)) / BYTEWIDTH] |= 1 << ((c) % BYTEWIDTH))
1904 /* Get the next unsigned number in the uncompiled pattern. */
1905 #define GET_UNSIGNED_NUMBER(num) \
1906 do { if (p != pend) \
1909 while ('0' <= c && c <= '9') \
1913 num = num * 10 + c - '0'; \
1921 #if WIDE_CHAR_SUPPORT
1922 /* The GNU C library provides support for user-defined character classes
1923 and the functions from ISO C amendement 1. */
1924 # ifdef CHARCLASS_NAME_MAX
1925 # define CHAR_CLASS_MAX_LENGTH CHARCLASS_NAME_MAX
1927 /* This shouldn't happen but some implementation might still have this
1928 problem. Use a reasonable default value. */
1929 # define CHAR_CLASS_MAX_LENGTH 256
1931 typedef wctype_t re_wctype_t
;
1932 typedef wchar_t re_wchar_t
;
1933 # define re_wctype wctype
1934 # define re_iswctype iswctype
1935 # define re_wctype_to_bit(cc) 0
1937 # define CHAR_CLASS_MAX_LENGTH 9 /* Namely, `multibyte'. */
1940 /* Character classes. */
1941 typedef enum { RECC_ERROR
= 0,
1942 RECC_ALNUM
, RECC_ALPHA
, RECC_WORD
,
1943 RECC_GRAPH
, RECC_PRINT
,
1944 RECC_LOWER
, RECC_UPPER
,
1945 RECC_PUNCT
, RECC_CNTRL
,
1946 RECC_DIGIT
, RECC_XDIGIT
,
1947 RECC_BLANK
, RECC_SPACE
,
1948 RECC_MULTIBYTE
, RECC_NONASCII
,
1949 RECC_ASCII
, RECC_UNIBYTE
1952 typedef int re_wchar_t
;
1954 /* Map a string to the char class it names (if any). */
1959 if (STREQ (string
, "alnum")) return RECC_ALNUM
;
1960 else if (STREQ (string
, "alpha")) return RECC_ALPHA
;
1961 else if (STREQ (string
, "word")) return RECC_WORD
;
1962 else if (STREQ (string
, "ascii")) return RECC_ASCII
;
1963 else if (STREQ (string
, "nonascii")) return RECC_NONASCII
;
1964 else if (STREQ (string
, "graph")) return RECC_GRAPH
;
1965 else if (STREQ (string
, "lower")) return RECC_LOWER
;
1966 else if (STREQ (string
, "print")) return RECC_PRINT
;
1967 else if (STREQ (string
, "punct")) return RECC_PUNCT
;
1968 else if (STREQ (string
, "space")) return RECC_SPACE
;
1969 else if (STREQ (string
, "upper")) return RECC_UPPER
;
1970 else if (STREQ (string
, "unibyte")) return RECC_UNIBYTE
;
1971 else if (STREQ (string
, "multibyte")) return RECC_MULTIBYTE
;
1972 else if (STREQ (string
, "digit")) return RECC_DIGIT
;
1973 else if (STREQ (string
, "xdigit")) return RECC_XDIGIT
;
1974 else if (STREQ (string
, "cntrl")) return RECC_CNTRL
;
1975 else if (STREQ (string
, "blank")) return RECC_BLANK
;
1979 /* True iff CH is in the char class CC. */
1981 re_iswctype (ch
, cc
)
1987 case RECC_ALNUM
: return ISALNUM (ch
);
1988 case RECC_ALPHA
: return ISALPHA (ch
);
1989 case RECC_BLANK
: return ISBLANK (ch
);
1990 case RECC_CNTRL
: return ISCNTRL (ch
);
1991 case RECC_DIGIT
: return ISDIGIT (ch
);
1992 case RECC_GRAPH
: return ISGRAPH (ch
);
1993 case RECC_LOWER
: return ISLOWER (ch
);
1994 case RECC_PRINT
: return ISPRINT (ch
);
1995 case RECC_PUNCT
: return ISPUNCT (ch
);
1996 case RECC_SPACE
: return ISSPACE (ch
);
1997 case RECC_UPPER
: return ISUPPER (ch
);
1998 case RECC_XDIGIT
: return ISXDIGIT (ch
);
1999 case RECC_ASCII
: return IS_REAL_ASCII (ch
);
2000 case RECC_NONASCII
: return !IS_REAL_ASCII (ch
);
2001 case RECC_UNIBYTE
: return ISUNIBYTE (ch
);
2002 case RECC_MULTIBYTE
: return !ISUNIBYTE (ch
);
2003 case RECC_WORD
: return ISWORD (ch
);
2004 case RECC_ERROR
: return false;
2010 /* Return a bit-pattern to use in the range-table bits to match multibyte
2011 chars of class CC. */
2013 re_wctype_to_bit (cc
)
2018 case RECC_NONASCII
: case RECC_PRINT
: case RECC_GRAPH
:
2019 case RECC_MULTIBYTE
: return BIT_MULTIBYTE
;
2020 case RECC_ALPHA
: case RECC_ALNUM
: case RECC_WORD
: return BIT_WORD
;
2021 case RECC_LOWER
: return BIT_LOWER
;
2022 case RECC_UPPER
: return BIT_UPPER
;
2023 case RECC_PUNCT
: return BIT_PUNCT
;
2024 case RECC_SPACE
: return BIT_SPACE
;
2025 case RECC_ASCII
: case RECC_DIGIT
: case RECC_XDIGIT
: case RECC_CNTRL
:
2026 case RECC_BLANK
: case RECC_UNIBYTE
: case RECC_ERROR
: return 0;
2033 /* Explicit quit checking is only used on NTemacs. */
2034 #if defined WINDOWSNT && defined emacs && defined QUIT
2035 extern int immediate_quit
;
2036 # define IMMEDIATE_QUIT_CHECK \
2038 if (immediate_quit) QUIT; \
2041 # define IMMEDIATE_QUIT_CHECK ((void)0)
2044 #ifndef MATCH_MAY_ALLOCATE
2046 /* If we cannot allocate large objects within re_match_2_internal,
2047 we make the fail stack and register vectors global.
2048 The fail stack, we grow to the maximum size when a regexp
2050 The register vectors, we adjust in size each time we
2051 compile a regexp, according to the number of registers it needs. */
2053 static fail_stack_type fail_stack
;
2055 /* Size with which the following vectors are currently allocated.
2056 That is so we can make them bigger as needed,
2057 but never make them smaller. */
2058 static int regs_allocated_size
;
2060 static re_char
** regstart
, ** regend
;
2061 static re_char
**best_regstart
, **best_regend
;
2063 /* Make the register vectors big enough for NUM_REGS registers,
2064 but don't make them smaller. */
2067 regex_grow_registers (num_regs
)
2070 if (num_regs
> regs_allocated_size
)
2072 RETALLOC_IF (regstart
, num_regs
, re_char
*);
2073 RETALLOC_IF (regend
, num_regs
, re_char
*);
2074 RETALLOC_IF (best_regstart
, num_regs
, re_char
*);
2075 RETALLOC_IF (best_regend
, num_regs
, re_char
*);
2077 regs_allocated_size
= num_regs
;
2081 #endif /* not MATCH_MAY_ALLOCATE */
2083 static boolean group_in_compile_stack
_RE_ARGS ((compile_stack_type
2087 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
2088 Returns one of error codes defined in `regex.h', or zero for success.
2090 Assumes the `allocated' (and perhaps `buffer') and `translate'
2091 fields are set in BUFP on entry.
2093 If it succeeds, results are put in BUFP (if it returns an error, the
2094 contents of BUFP are undefined):
2095 `buffer' is the compiled pattern;
2096 `syntax' is set to SYNTAX;
2097 `used' is set to the length of the compiled pattern;
2098 `fastmap_accurate' is zero;
2099 `re_nsub' is the number of subexpressions in PATTERN;
2100 `not_bol' and `not_eol' are zero;
2102 The `fastmap' field is neither examined nor set. */
2104 /* Insert the `jump' from the end of last alternative to "here".
2105 The space for the jump has already been allocated. */
2106 #define FIXUP_ALT_JUMP() \
2108 if (fixup_alt_jump) \
2109 STORE_JUMP (jump, fixup_alt_jump, b); \
2113 /* Return, freeing storage we allocated. */
2114 #define FREE_STACK_RETURN(value) \
2116 FREE_RANGE_TABLE_WORK_AREA (range_table_work); \
2117 free (compile_stack.stack); \
2121 static reg_errcode_t
2122 regex_compile (pattern
, size
, syntax
, bufp
)
2125 reg_syntax_t syntax
;
2126 struct re_pattern_buffer
*bufp
;
2128 /* We fetch characters from PATTERN here. */
2129 register re_wchar_t c
, c1
;
2131 /* A random temporary spot in PATTERN. */
2134 /* Points to the end of the buffer, where we should append. */
2135 register unsigned char *b
;
2137 /* Keeps track of unclosed groups. */
2138 compile_stack_type compile_stack
;
2140 /* Points to the current (ending) position in the pattern. */
2142 /* `const' makes AIX compiler fail. */
2143 unsigned char *p
= pattern
;
2145 re_char
*p
= pattern
;
2147 re_char
*pend
= pattern
+ size
;
2149 /* How to translate the characters in the pattern. */
2150 RE_TRANSLATE_TYPE translate
= bufp
->translate
;
2152 /* Address of the count-byte of the most recently inserted `exactn'
2153 command. This makes it possible to tell if a new exact-match
2154 character can be added to that command or if the character requires
2155 a new `exactn' command. */
2156 unsigned char *pending_exact
= 0;
2158 /* Address of start of the most recently finished expression.
2159 This tells, e.g., postfix * where to find the start of its
2160 operand. Reset at the beginning of groups and alternatives. */
2161 unsigned char *laststart
= 0;
2163 /* Address of beginning of regexp, or inside of last group. */
2164 unsigned char *begalt
;
2166 /* Place in the uncompiled pattern (i.e., the {) to
2167 which to go back if the interval is invalid. */
2168 re_char
*beg_interval
;
2170 /* Address of the place where a forward jump should go to the end of
2171 the containing expression. Each alternative of an `or' -- except the
2172 last -- ends with a forward jump of this sort. */
2173 unsigned char *fixup_alt_jump
= 0;
2175 /* Counts open-groups as they are encountered. Remembered for the
2176 matching close-group on the compile stack, so the same register
2177 number is put in the stop_memory as the start_memory. */
2178 regnum_t regnum
= 0;
2180 /* Work area for range table of charset. */
2181 struct range_table_work_area range_table_work
;
2183 /* If the object matched can contain multibyte characters. */
2184 const boolean multibyte
= RE_MULTIBYTE_P (bufp
);
2188 DEBUG_PRINT1 ("\nCompiling pattern: ");
2191 unsigned debug_count
;
2193 for (debug_count
= 0; debug_count
< size
; debug_count
++)
2194 putchar (pattern
[debug_count
]);
2199 /* Initialize the compile stack. */
2200 compile_stack
.stack
= TALLOC (INIT_COMPILE_STACK_SIZE
, compile_stack_elt_t
);
2201 if (compile_stack
.stack
== NULL
)
2204 compile_stack
.size
= INIT_COMPILE_STACK_SIZE
;
2205 compile_stack
.avail
= 0;
2207 range_table_work
.table
= 0;
2208 range_table_work
.allocated
= 0;
2210 /* Initialize the pattern buffer. */
2211 bufp
->syntax
= syntax
;
2212 bufp
->fastmap_accurate
= 0;
2213 bufp
->not_bol
= bufp
->not_eol
= 0;
2215 /* Set `used' to zero, so that if we return an error, the pattern
2216 printer (for debugging) will think there's no pattern. We reset it
2220 /* Always count groups, whether or not bufp->no_sub is set. */
2223 #if !defined emacs && !defined SYNTAX_TABLE
2224 /* Initialize the syntax table. */
2225 init_syntax_once ();
2228 if (bufp
->allocated
== 0)
2231 { /* If zero allocated, but buffer is non-null, try to realloc
2232 enough space. This loses if buffer's address is bogus, but
2233 that is the user's responsibility. */
2234 RETALLOC (bufp
->buffer
, INIT_BUF_SIZE
, unsigned char);
2237 { /* Caller did not allocate a buffer. Do it for them. */
2238 bufp
->buffer
= TALLOC (INIT_BUF_SIZE
, unsigned char);
2240 if (!bufp
->buffer
) FREE_STACK_RETURN (REG_ESPACE
);
2242 bufp
->allocated
= INIT_BUF_SIZE
;
2245 begalt
= b
= bufp
->buffer
;
2247 /* Loop through the uncompiled pattern until we're at the end. */
2256 if ( /* If at start of pattern, it's an operator. */
2258 /* If context independent, it's an operator. */
2259 || syntax
& RE_CONTEXT_INDEP_ANCHORS
2260 /* Otherwise, depends on what's come before. */
2261 || at_begline_loc_p (pattern
, p
, syntax
))
2262 BUF_PUSH ((syntax
& RE_NO_NEWLINE_ANCHOR
) ? begbuf
: begline
);
2271 if ( /* If at end of pattern, it's an operator. */
2273 /* If context independent, it's an operator. */
2274 || syntax
& RE_CONTEXT_INDEP_ANCHORS
2275 /* Otherwise, depends on what's next. */
2276 || at_endline_loc_p (p
, pend
, syntax
))
2277 BUF_PUSH ((syntax
& RE_NO_NEWLINE_ANCHOR
) ? endbuf
: endline
);
2286 if ((syntax
& RE_BK_PLUS_QM
)
2287 || (syntax
& RE_LIMITED_OPS
))
2291 /* If there is no previous pattern... */
2294 if (syntax
& RE_CONTEXT_INVALID_OPS
)
2295 FREE_STACK_RETURN (REG_BADRPT
);
2296 else if (!(syntax
& RE_CONTEXT_INDEP_OPS
))
2301 /* 1 means zero (many) matches is allowed. */
2302 boolean zero_times_ok
= 0, many_times_ok
= 0;
2305 /* If there is a sequence of repetition chars, collapse it
2306 down to just one (the right one). We can't combine
2307 interval operators with these because of, e.g., `a{2}*',
2308 which should only match an even number of `a's. */
2312 if ((syntax
& RE_FRUGAL
)
2313 && c
== '?' && (zero_times_ok
|| many_times_ok
))
2317 zero_times_ok
|= c
!= '+';
2318 many_times_ok
|= c
!= '?';
2324 || (!(syntax
& RE_BK_PLUS_QM
)
2325 && (*p
== '+' || *p
== '?')))
2327 else if (syntax
& RE_BK_PLUS_QM
&& *p
== '\\')
2330 FREE_STACK_RETURN (REG_EESCAPE
);
2331 if (p
[1] == '+' || p
[1] == '?')
2332 PATFETCH (c
); /* Gobble up the backslash. */
2338 /* If we get here, we found another repeat character. */
2342 /* Star, etc. applied to an empty pattern is equivalent
2343 to an empty pattern. */
2344 if (!laststart
|| laststart
== b
)
2347 /* Now we know whether or not zero matches is allowed
2348 and also whether or not two or more matches is allowed. */
2353 boolean simple
= skip_one_char (laststart
) == b
;
2354 unsigned int startoffset
= 0;
2356 /* Check if the loop can match the empty string. */
2357 (simple
|| !analyse_first (laststart
, b
, NULL
, 0)) ?
2358 on_failure_jump
: on_failure_jump_loop
;
2359 assert (skip_one_char (laststart
) <= b
);
2361 if (!zero_times_ok
&& simple
)
2362 { /* Since simple * loops can be made faster by using
2363 on_failure_keep_string_jump, we turn simple P+
2364 into PP* if P is simple. */
2365 unsigned char *p1
, *p2
;
2366 startoffset
= b
- laststart
;
2367 GET_BUFFER_SPACE (startoffset
);
2368 p1
= b
; p2
= laststart
;
2374 GET_BUFFER_SPACE (6);
2377 STORE_JUMP (ofj
, b
, b
+ 6);
2379 /* Simple * loops can use on_failure_keep_string_jump
2380 depending on what follows. But since we don't know
2381 that yet, we leave the decision up to
2382 on_failure_jump_smart. */
2383 INSERT_JUMP (simple
? on_failure_jump_smart
: ofj
,
2384 laststart
+ startoffset
, b
+ 6);
2386 STORE_JUMP (jump
, b
, laststart
+ startoffset
);
2391 /* A simple ? pattern. */
2392 assert (zero_times_ok
);
2393 GET_BUFFER_SPACE (3);
2394 INSERT_JUMP (on_failure_jump
, laststart
, b
+ 3);
2398 else /* not greedy */
2399 { /* I wish the greedy and non-greedy cases could be merged. */
2401 GET_BUFFER_SPACE (7); /* We might use less. */
2404 boolean emptyp
= analyse_first (laststart
, b
, NULL
, 0);
2406 /* The non-greedy multiple match looks like a repeat..until:
2407 we only need a conditional jump at the end of the loop */
2408 if (emptyp
) BUF_PUSH (no_op
);
2409 STORE_JUMP (emptyp
? on_failure_jump_nastyloop
2410 : on_failure_jump
, b
, laststart
);
2414 /* The repeat...until naturally matches one or more.
2415 To also match zero times, we need to first jump to
2416 the end of the loop (its conditional jump). */
2417 INSERT_JUMP (jump
, laststart
, b
);
2423 /* non-greedy a?? */
2424 INSERT_JUMP (jump
, laststart
, b
+ 3);
2426 INSERT_JUMP (on_failure_jump
, laststart
, laststart
+ 6);
2443 CLEAR_RANGE_TABLE_WORK_USED (range_table_work
);
2445 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2447 /* Ensure that we have enough space to push a charset: the
2448 opcode, the length count, and the bitset; 34 bytes in all. */
2449 GET_BUFFER_SPACE (34);
2453 /* We test `*p == '^' twice, instead of using an if
2454 statement, so we only need one BUF_PUSH. */
2455 BUF_PUSH (*p
== '^' ? charset_not
: charset
);
2459 /* Remember the first position in the bracket expression. */
2462 /* Push the number of bytes in the bitmap. */
2463 BUF_PUSH ((1 << BYTEWIDTH
) / BYTEWIDTH
);
2465 /* Clear the whole map. */
2466 bzero (b
, (1 << BYTEWIDTH
) / BYTEWIDTH
);
2468 /* charset_not matches newline according to a syntax bit. */
2469 if ((re_opcode_t
) b
[-2] == charset_not
2470 && (syntax
& RE_HAT_LISTS_NOT_NEWLINE
))
2471 SET_LIST_BIT ('\n');
2473 /* Read in characters and ranges, setting map bits. */
2476 boolean escaped_char
= false;
2477 const unsigned char *p2
= p
;
2479 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2483 /* \ might escape characters inside [...] and [^...]. */
2484 if ((syntax
& RE_BACKSLASH_ESCAPE_IN_LISTS
) && c
== '\\')
2486 if (p
== pend
) FREE_STACK_RETURN (REG_EESCAPE
);
2489 escaped_char
= true;
2493 /* Could be the end of the bracket expression. If it's
2494 not (i.e., when the bracket expression is `[]' so
2495 far), the ']' character bit gets set way below. */
2496 if (c
== ']' && p2
!= p1
)
2500 /* What should we do for the character which is
2501 greater than 0x7F, but not BASE_LEADING_CODE_P?
2504 /* See if we're at the beginning of a possible character
2507 if (!escaped_char
&&
2508 syntax
& RE_CHAR_CLASSES
&& c
== '[' && *p
== ':')
2510 /* Leave room for the null. */
2511 unsigned char str
[CHAR_CLASS_MAX_LENGTH
+ 1];
2512 const unsigned char *class_beg
;
2518 /* If pattern is `[[:'. */
2519 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2524 if ((c
== ':' && *p
== ']') || p
== pend
)
2526 if (c1
< CHAR_CLASS_MAX_LENGTH
)
2529 /* This is in any case an invalid class name. */
2534 /* If isn't a word bracketed by `[:' and `:]':
2535 undo the ending character, the letters, and
2536 leave the leading `:' and `[' (but set bits for
2538 if (c
== ':' && *p
== ']')
2543 cc
= re_wctype (str
);
2546 FREE_STACK_RETURN (REG_ECTYPE
);
2548 /* Throw away the ] at the end of the character
2552 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2554 /* Most character classes in a multibyte match
2555 just set a flag. Exceptions are is_blank,
2556 is_digit, is_cntrl, and is_xdigit, since
2557 they can only match ASCII characters. We
2558 don't need to handle them for multibyte.
2559 They are distinguished by a negative wctype. */
2562 SET_RANGE_TABLE_WORK_AREA_BIT (range_table_work
,
2563 re_wctype_to_bit (cc
));
2565 for (ch
= 0; ch
< 1 << BYTEWIDTH
; ++ch
)
2567 int translated
= TRANSLATE (ch
);
2568 if (re_iswctype (btowc (ch
), cc
))
2569 SET_LIST_BIT (translated
);
2572 /* Repeat the loop. */
2577 /* Go back to right after the "[:". */
2581 /* Because the `:' may starts the range, we
2582 can't simply set bit and repeat the loop.
2583 Instead, just set it to C and handle below. */
2588 if (p
< pend
&& p
[0] == '-' && p
[1] != ']')
2591 /* Discard the `-'. */
2594 /* Fetch the character which ends the range. */
2597 if (SINGLE_BYTE_CHAR_P (c
))
2599 if (! SINGLE_BYTE_CHAR_P (c1
))
2601 /* Handle a range starting with a
2602 character of less than 256, and ending
2603 with a character of not less than 256.
2604 Split that into two ranges, the low one
2605 ending at 0377, and the high one
2606 starting at the smallest character in
2607 the charset of C1 and ending at C1. */
2608 int charset
= CHAR_CHARSET (c1
);
2609 int c2
= MAKE_CHAR (charset
, 0, 0);
2611 SET_RANGE_TABLE_WORK_AREA (range_table_work
,
2616 else if (!SAME_CHARSET_P (c
, c1
))
2617 FREE_STACK_RETURN (REG_ERANGE
);
2620 /* Range from C to C. */
2623 /* Set the range ... */
2624 if (SINGLE_BYTE_CHAR_P (c
))
2625 /* ... into bitmap. */
2627 re_wchar_t this_char
;
2628 int range_start
= c
, range_end
= c1
;
2630 /* If the start is after the end, the range is empty. */
2631 if (range_start
> range_end
)
2633 if (syntax
& RE_NO_EMPTY_RANGES
)
2634 FREE_STACK_RETURN (REG_ERANGE
);
2635 /* Else, repeat the loop. */
2639 for (this_char
= range_start
; this_char
<= range_end
;
2641 SET_LIST_BIT (TRANSLATE (this_char
));
2645 /* ... into range table. */
2646 SET_RANGE_TABLE_WORK_AREA (range_table_work
, c
, c1
);
2649 /* Discard any (non)matching list bytes that are all 0 at the
2650 end of the map. Decrease the map-length byte too. */
2651 while ((int) b
[-1] > 0 && b
[b
[-1] - 1] == 0)
2655 /* Build real range table from work area. */
2656 if (RANGE_TABLE_WORK_USED (range_table_work
)
2657 || RANGE_TABLE_WORK_BITS (range_table_work
))
2660 int used
= RANGE_TABLE_WORK_USED (range_table_work
);
2662 /* Allocate space for COUNT + RANGE_TABLE. Needs two
2663 bytes for flags, two for COUNT, and three bytes for
2665 GET_BUFFER_SPACE (4 + used
* 3);
2667 /* Indicate the existence of range table. */
2668 laststart
[1] |= 0x80;
2670 /* Store the character class flag bits into the range table.
2671 If not in emacs, these flag bits are always 0. */
2672 *b
++ = RANGE_TABLE_WORK_BITS (range_table_work
) & 0xff;
2673 *b
++ = RANGE_TABLE_WORK_BITS (range_table_work
) >> 8;
2675 STORE_NUMBER_AND_INCR (b
, used
/ 2);
2676 for (i
= 0; i
< used
; i
++)
2677 STORE_CHARACTER_AND_INCR
2678 (b
, RANGE_TABLE_WORK_ELT (range_table_work
, i
));
2685 if (syntax
& RE_NO_BK_PARENS
)
2692 if (syntax
& RE_NO_BK_PARENS
)
2699 if (syntax
& RE_NEWLINE_ALT
)
2706 if (syntax
& RE_NO_BK_VBAR
)
2713 if (syntax
& RE_INTERVALS
&& syntax
& RE_NO_BK_BRACES
)
2714 goto handle_interval
;
2720 if (p
== pend
) FREE_STACK_RETURN (REG_EESCAPE
);
2722 /* Do not translate the character after the \, so that we can
2723 distinguish, e.g., \B from \b, even if we normally would
2724 translate, e.g., B to b. */
2730 if (syntax
& RE_NO_BK_PARENS
)
2731 goto normal_backslash
;
2738 /* Look for a special (?...) construct */
2739 if ((syntax
& RE_SHY_GROUPS
) && *p
== '?')
2741 PATFETCH (c
); /* Gobble up the '?'. */
2745 case ':': shy
= 1; break;
2747 /* Only (?:...) is supported right now. */
2748 FREE_STACK_RETURN (REG_BADPAT
);
2759 if (COMPILE_STACK_FULL
)
2761 RETALLOC (compile_stack
.stack
, compile_stack
.size
<< 1,
2762 compile_stack_elt_t
);
2763 if (compile_stack
.stack
== NULL
) return REG_ESPACE
;
2765 compile_stack
.size
<<= 1;
2768 /* These are the values to restore when we hit end of this
2769 group. They are all relative offsets, so that if the
2770 whole pattern moves because of realloc, they will still
2772 COMPILE_STACK_TOP
.begalt_offset
= begalt
- bufp
->buffer
;
2773 COMPILE_STACK_TOP
.fixup_alt_jump
2774 = fixup_alt_jump
? fixup_alt_jump
- bufp
->buffer
+ 1 : 0;
2775 COMPILE_STACK_TOP
.laststart_offset
= b
- bufp
->buffer
;
2776 COMPILE_STACK_TOP
.regnum
= shy
? -regnum
: regnum
;
2779 start_memory for groups beyond the last one we can
2780 represent in the compiled pattern. */
2781 if (regnum
<= MAX_REGNUM
&& !shy
)
2782 BUF_PUSH_2 (start_memory
, regnum
);
2784 compile_stack
.avail
++;
2789 /* If we've reached MAX_REGNUM groups, then this open
2790 won't actually generate any code, so we'll have to
2791 clear pending_exact explicitly. */
2797 if (syntax
& RE_NO_BK_PARENS
) goto normal_backslash
;
2799 if (COMPILE_STACK_EMPTY
)
2801 if (syntax
& RE_UNMATCHED_RIGHT_PAREN_ORD
)
2802 goto normal_backslash
;
2804 FREE_STACK_RETURN (REG_ERPAREN
);
2810 /* See similar code for backslashed left paren above. */
2811 if (COMPILE_STACK_EMPTY
)
2813 if (syntax
& RE_UNMATCHED_RIGHT_PAREN_ORD
)
2816 FREE_STACK_RETURN (REG_ERPAREN
);
2819 /* Since we just checked for an empty stack above, this
2820 ``can't happen''. */
2821 assert (compile_stack
.avail
!= 0);
2823 /* We don't just want to restore into `regnum', because
2824 later groups should continue to be numbered higher,
2825 as in `(ab)c(de)' -- the second group is #2. */
2826 regnum_t this_group_regnum
;
2828 compile_stack
.avail
--;
2829 begalt
= bufp
->buffer
+ COMPILE_STACK_TOP
.begalt_offset
;
2831 = COMPILE_STACK_TOP
.fixup_alt_jump
2832 ? bufp
->buffer
+ COMPILE_STACK_TOP
.fixup_alt_jump
- 1
2834 laststart
= bufp
->buffer
+ COMPILE_STACK_TOP
.laststart_offset
;
2835 this_group_regnum
= COMPILE_STACK_TOP
.regnum
;
2836 /* If we've reached MAX_REGNUM groups, then this open
2837 won't actually generate any code, so we'll have to
2838 clear pending_exact explicitly. */
2841 /* We're at the end of the group, so now we know how many
2842 groups were inside this one. */
2843 if (this_group_regnum
<= MAX_REGNUM
&& this_group_regnum
> 0)
2844 BUF_PUSH_2 (stop_memory
, this_group_regnum
);
2849 case '|': /* `\|'. */
2850 if (syntax
& RE_LIMITED_OPS
|| syntax
& RE_NO_BK_VBAR
)
2851 goto normal_backslash
;
2853 if (syntax
& RE_LIMITED_OPS
)
2856 /* Insert before the previous alternative a jump which
2857 jumps to this alternative if the former fails. */
2858 GET_BUFFER_SPACE (3);
2859 INSERT_JUMP (on_failure_jump
, begalt
, b
+ 6);
2863 /* The alternative before this one has a jump after it
2864 which gets executed if it gets matched. Adjust that
2865 jump so it will jump to this alternative's analogous
2866 jump (put in below, which in turn will jump to the next
2867 (if any) alternative's such jump, etc.). The last such
2868 jump jumps to the correct final destination. A picture:
2874 If we are at `b', then fixup_alt_jump right now points to a
2875 three-byte space after `a'. We'll put in the jump, set
2876 fixup_alt_jump to right after `b', and leave behind three
2877 bytes which we'll fill in when we get to after `c'. */
2881 /* Mark and leave space for a jump after this alternative,
2882 to be filled in later either by next alternative or
2883 when know we're at the end of a series of alternatives. */
2885 GET_BUFFER_SPACE (3);
2894 /* If \{ is a literal. */
2895 if (!(syntax
& RE_INTERVALS
)
2896 /* If we're at `\{' and it's not the open-interval
2898 || (syntax
& RE_NO_BK_BRACES
))
2899 goto normal_backslash
;
2903 /* If got here, then the syntax allows intervals. */
2905 /* At least (most) this many matches must be made. */
2906 int lower_bound
= 0, upper_bound
= -1;
2911 FREE_STACK_RETURN (REG_EBRACE
);
2913 GET_UNSIGNED_NUMBER (lower_bound
);
2916 GET_UNSIGNED_NUMBER (upper_bound
);
2918 /* Interval such as `{1}' => match exactly once. */
2919 upper_bound
= lower_bound
;
2921 if (lower_bound
< 0 || upper_bound
> RE_DUP_MAX
2922 || (upper_bound
>= 0 && lower_bound
> upper_bound
))
2923 FREE_STACK_RETURN (REG_BADBR
);
2925 if (!(syntax
& RE_NO_BK_BRACES
))
2928 FREE_STACK_RETURN (REG_BADBR
);
2934 FREE_STACK_RETURN (REG_BADBR
);
2936 /* We just parsed a valid interval. */
2938 /* If it's invalid to have no preceding re. */
2941 if (syntax
& RE_CONTEXT_INVALID_OPS
)
2942 FREE_STACK_RETURN (REG_BADRPT
);
2943 else if (syntax
& RE_CONTEXT_INDEP_OPS
)
2946 goto unfetch_interval
;
2949 if (upper_bound
== 0)
2950 /* If the upper bound is zero, just drop the sub pattern
2953 else if (lower_bound
== 1 && upper_bound
== 1)
2954 /* Just match it once: nothing to do here. */
2957 /* Otherwise, we have a nontrivial interval. When
2958 we're all done, the pattern will look like:
2959 set_number_at <jump count> <upper bound>
2960 set_number_at <succeed_n count> <lower bound>
2961 succeed_n <after jump addr> <succeed_n count>
2963 jump_n <succeed_n addr> <jump count>
2964 (The upper bound and `jump_n' are omitted if
2965 `upper_bound' is 1, though.) */
2967 { /* If the upper bound is > 1, we need to insert
2968 more at the end of the loop. */
2969 unsigned int nbytes
= (upper_bound
< 0 ? 3
2970 : upper_bound
> 1 ? 5 : 0);
2971 unsigned int startoffset
= 0;
2973 GET_BUFFER_SPACE (20); /* We might use less. */
2975 if (lower_bound
== 0)
2977 /* A succeed_n that starts with 0 is really a
2978 a simple on_failure_jump_loop. */
2979 INSERT_JUMP (on_failure_jump_loop
, laststart
,
2985 /* Initialize lower bound of the `succeed_n', even
2986 though it will be set during matching by its
2987 attendant `set_number_at' (inserted next),
2988 because `re_compile_fastmap' needs to know.
2989 Jump to the `jump_n' we might insert below. */
2990 INSERT_JUMP2 (succeed_n
, laststart
,
2995 /* Code to initialize the lower bound. Insert
2996 before the `succeed_n'. The `5' is the last two
2997 bytes of this `set_number_at', plus 3 bytes of
2998 the following `succeed_n'. */
2999 insert_op2 (set_number_at
, laststart
, 5, lower_bound
, b
);
3004 if (upper_bound
< 0)
3006 /* A negative upper bound stands for infinity,
3007 in which case it degenerates to a plain jump. */
3008 STORE_JUMP (jump
, b
, laststart
+ startoffset
);
3011 else if (upper_bound
> 1)
3012 { /* More than one repetition is allowed, so
3013 append a backward jump to the `succeed_n'
3014 that starts this interval.
3016 When we've reached this during matching,
3017 we'll have matched the interval once, so
3018 jump back only `upper_bound - 1' times. */
3019 STORE_JUMP2 (jump_n
, b
, laststart
+ startoffset
,
3023 /* The location we want to set is the second
3024 parameter of the `jump_n'; that is `b-2' as
3025 an absolute address. `laststart' will be
3026 the `set_number_at' we're about to insert;
3027 `laststart+3' the number to set, the source
3028 for the relative address. But we are
3029 inserting into the middle of the pattern --
3030 so everything is getting moved up by 5.
3031 Conclusion: (b - 2) - (laststart + 3) + 5,
3032 i.e., b - laststart.
3034 We insert this at the beginning of the loop
3035 so that if we fail during matching, we'll
3036 reinitialize the bounds. */
3037 insert_op2 (set_number_at
, laststart
, b
- laststart
,
3038 upper_bound
- 1, b
);
3043 beg_interval
= NULL
;
3048 /* If an invalid interval, match the characters as literals. */
3049 assert (beg_interval
);
3051 beg_interval
= NULL
;
3053 /* normal_char and normal_backslash need `c'. */
3056 if (!(syntax
& RE_NO_BK_BRACES
))
3058 assert (p
> pattern
&& p
[-1] == '\\');
3059 goto normal_backslash
;
3065 /* There is no way to specify the before_dot and after_dot
3066 operators. rms says this is ok. --karl */
3074 BUF_PUSH_2 (syntaxspec
, syntax_spec_code
[c
]);
3080 BUF_PUSH_2 (notsyntaxspec
, syntax_spec_code
[c
]);
3086 BUF_PUSH_2 (categoryspec
, c
);
3092 BUF_PUSH_2 (notcategoryspec
, c
);
3098 if (syntax
& RE_NO_GNU_OPS
)
3101 BUF_PUSH_2 (syntaxspec
, Sword
);
3106 if (syntax
& RE_NO_GNU_OPS
)
3109 BUF_PUSH_2 (notsyntaxspec
, Sword
);
3114 if (syntax
& RE_NO_GNU_OPS
)
3120 if (syntax
& RE_NO_GNU_OPS
)
3126 if (syntax
& RE_NO_GNU_OPS
)
3128 BUF_PUSH (wordbound
);
3132 if (syntax
& RE_NO_GNU_OPS
)
3134 BUF_PUSH (notwordbound
);
3138 if (syntax
& RE_NO_GNU_OPS
)
3144 if (syntax
& RE_NO_GNU_OPS
)
3149 case '1': case '2': case '3': case '4': case '5':
3150 case '6': case '7': case '8': case '9':
3154 if (syntax
& RE_NO_BK_REFS
)
3155 goto normal_backslash
;
3159 /* Can't back reference to a subexpression before its end. */
3160 if (reg
> regnum
|| group_in_compile_stack (compile_stack
, reg
))
3161 FREE_STACK_RETURN (REG_ESUBREG
);
3164 BUF_PUSH_2 (duplicate
, reg
);
3171 if (syntax
& RE_BK_PLUS_QM
)
3174 goto normal_backslash
;
3178 /* You might think it would be useful for \ to mean
3179 not to translate; but if we don't translate it
3180 it will never match anything. */
3188 /* Expects the character in `c'. */
3190 /* If no exactn currently being built. */
3193 /* If last exactn not at current position. */
3194 || pending_exact
+ *pending_exact
+ 1 != b
3196 /* We have only one byte following the exactn for the count. */
3197 || *pending_exact
>= (1 << BYTEWIDTH
) - MAX_MULTIBYTE_LENGTH
3199 /* If followed by a repetition operator. */
3200 || (p
!= pend
&& (*p
== '*' || *p
== '^'))
3201 || ((syntax
& RE_BK_PLUS_QM
)
3202 ? p
+ 1 < pend
&& *p
== '\\' && (p
[1] == '+' || p
[1] == '?')
3203 : p
!= pend
&& (*p
== '+' || *p
== '?'))
3204 || ((syntax
& RE_INTERVALS
)
3205 && ((syntax
& RE_NO_BK_BRACES
)
3206 ? p
!= pend
&& *p
== '{'
3207 : p
+ 1 < pend
&& p
[0] == '\\' && p
[1] == '{')))
3209 /* Start building a new exactn. */
3213 BUF_PUSH_2 (exactn
, 0);
3214 pending_exact
= b
- 1;
3217 GET_BUFFER_SPACE (MAX_MULTIBYTE_LENGTH
);
3222 len
= CHAR_STRING (c
, b
);
3226 (*pending_exact
) += len
;
3231 } /* while p != pend */
3234 /* Through the pattern now. */
3238 if (!COMPILE_STACK_EMPTY
)
3239 FREE_STACK_RETURN (REG_EPAREN
);
3241 /* If we don't want backtracking, force success
3242 the first time we reach the end of the compiled pattern. */
3243 if (syntax
& RE_NO_POSIX_BACKTRACKING
)
3246 free (compile_stack
.stack
);
3248 /* We have succeeded; set the length of the buffer. */
3249 bufp
->used
= b
- bufp
->buffer
;
3254 re_compile_fastmap (bufp
);
3255 DEBUG_PRINT1 ("\nCompiled pattern: \n");
3256 print_compiled_pattern (bufp
);
3261 #ifndef MATCH_MAY_ALLOCATE
3262 /* Initialize the failure stack to the largest possible stack. This
3263 isn't necessary unless we're trying to avoid calling alloca in
3264 the search and match routines. */
3266 int num_regs
= bufp
->re_nsub
+ 1;
3268 if (fail_stack
.size
< re_max_failures
* TYPICAL_FAILURE_SIZE
)
3270 fail_stack
.size
= re_max_failures
* TYPICAL_FAILURE_SIZE
;
3272 if (! fail_stack
.stack
)
3274 = (fail_stack_elt_t
*) malloc (fail_stack
.size
3275 * sizeof (fail_stack_elt_t
));
3278 = (fail_stack_elt_t
*) realloc (fail_stack
.stack
,
3280 * sizeof (fail_stack_elt_t
)));
3283 regex_grow_registers (num_regs
);
3285 #endif /* not MATCH_MAY_ALLOCATE */
3288 } /* regex_compile */
3290 /* Subroutines for `regex_compile'. */
3292 /* Store OP at LOC followed by two-byte integer parameter ARG. */
3295 store_op1 (op
, loc
, arg
)
3300 *loc
= (unsigned char) op
;
3301 STORE_NUMBER (loc
+ 1, arg
);
3305 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
3308 store_op2 (op
, loc
, arg1
, arg2
)
3313 *loc
= (unsigned char) op
;
3314 STORE_NUMBER (loc
+ 1, arg1
);
3315 STORE_NUMBER (loc
+ 3, arg2
);
3319 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
3320 for OP followed by two-byte integer parameter ARG. */
3323 insert_op1 (op
, loc
, arg
, end
)
3329 register unsigned char *pfrom
= end
;
3330 register unsigned char *pto
= end
+ 3;
3332 while (pfrom
!= loc
)
3335 store_op1 (op
, loc
, arg
);
3339 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
3342 insert_op2 (op
, loc
, arg1
, arg2
, end
)
3348 register unsigned char *pfrom
= end
;
3349 register unsigned char *pto
= end
+ 5;
3351 while (pfrom
!= loc
)
3354 store_op2 (op
, loc
, arg1
, arg2
);
3358 /* P points to just after a ^ in PATTERN. Return true if that ^ comes
3359 after an alternative or a begin-subexpression. We assume there is at
3360 least one character before the ^. */
3363 at_begline_loc_p (pattern
, p
, syntax
)
3364 re_char
*pattern
, *p
;
3365 reg_syntax_t syntax
;
3367 re_char
*prev
= p
- 2;
3368 boolean prev_prev_backslash
= prev
> pattern
&& prev
[-1] == '\\';
3371 /* After a subexpression? */
3372 (*prev
== '(' && (syntax
& RE_NO_BK_PARENS
|| prev_prev_backslash
))
3373 /* After an alternative? */
3374 || (*prev
== '|' && (syntax
& RE_NO_BK_VBAR
|| prev_prev_backslash
))
3375 /* After a shy subexpression? */
3376 || ((syntax
& RE_SHY_GROUPS
) && prev
- 2 >= pattern
3377 && prev
[-1] == '?' && prev
[-2] == '('
3378 && (syntax
& RE_NO_BK_PARENS
3379 || (prev
- 3 >= pattern
&& prev
[-3] == '\\')));
3383 /* The dual of at_begline_loc_p. This one is for $. We assume there is
3384 at least one character after the $, i.e., `P < PEND'. */
3387 at_endline_loc_p (p
, pend
, syntax
)
3389 reg_syntax_t syntax
;
3392 boolean next_backslash
= *next
== '\\';
3393 re_char
*next_next
= p
+ 1 < pend
? p
+ 1 : 0;
3396 /* Before a subexpression? */
3397 (syntax
& RE_NO_BK_PARENS
? *next
== ')'
3398 : next_backslash
&& next_next
&& *next_next
== ')')
3399 /* Before an alternative? */
3400 || (syntax
& RE_NO_BK_VBAR
? *next
== '|'
3401 : next_backslash
&& next_next
&& *next_next
== '|');
3405 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
3406 false if it's not. */
3409 group_in_compile_stack (compile_stack
, regnum
)
3410 compile_stack_type compile_stack
;
3415 for (this_element
= compile_stack
.avail
- 1;
3418 if (compile_stack
.stack
[this_element
].regnum
== regnum
)
3425 If fastmap is non-NULL, go through the pattern and fill fastmap
3426 with all the possible leading chars. If fastmap is NULL, don't
3427 bother filling it up (obviously) and only return whether the
3428 pattern could potentially match the empty string.
3430 Return 1 if p..pend might match the empty string.
3431 Return 0 if p..pend matches at least one char.
3432 Return -1 if fastmap was not updated accurately. */
3435 analyse_first (p
, pend
, fastmap
, multibyte
)
3438 const int multibyte
;
3443 /* If all elements for base leading-codes in fastmap is set, this
3444 flag is set true. */
3445 boolean match_any_multibyte_characters
= false;
3449 /* The loop below works as follows:
3450 - It has a working-list kept in the PATTERN_STACK and which basically
3451 starts by only containing a pointer to the first operation.
3452 - If the opcode we're looking at is a match against some set of
3453 chars, then we add those chars to the fastmap and go on to the
3454 next work element from the worklist (done via `break').
3455 - If the opcode is a control operator on the other hand, we either
3456 ignore it (if it's meaningless at this point, such as `start_memory')
3457 or execute it (if it's a jump). If the jump has several destinations
3458 (i.e. `on_failure_jump'), then we push the other destination onto the
3460 We guarantee termination by ignoring backward jumps (more or less),
3461 so that `p' is monotonically increasing. More to the point, we
3462 never set `p' (or push) anything `<= p1'. */
3466 /* `p1' is used as a marker of how far back a `on_failure_jump'
3467 can go without being ignored. It is normally equal to `p'
3468 (which prevents any backward `on_failure_jump') except right
3469 after a plain `jump', to allow patterns such as:
3472 10: on_failure_jump 3
3473 as used for the *? operator. */
3476 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *p
++))
3483 /* If the first character has to match a backreference, that means
3484 that the group was empty (since it already matched). Since this
3485 is the only case that interests us here, we can assume that the
3486 backreference must match the empty string. */
3491 /* Following are the cases which match a character. These end
3497 int c
= RE_STRING_CHAR (p
+ 1, pend
- p
);
3499 if (SINGLE_BYTE_CHAR_P (c
))
3508 /* We could put all the chars except for \n (and maybe \0)
3509 but we don't bother since it is generally not worth it. */
3510 if (!fastmap
) break;
3515 /* Chars beyond end of bitmap are possible matches.
3516 All the single-byte codes can occur in multibyte buffers.
3517 So any that are not listed in the charset
3518 are possible matches, even in multibyte buffers. */
3519 if (!fastmap
) break;
3520 for (j
= CHARSET_BITMAP_SIZE (&p
[-1]) * BYTEWIDTH
;
3521 j
< (1 << BYTEWIDTH
); j
++)
3525 if (!fastmap
) break;
3526 not = (re_opcode_t
) *(p
- 1) == charset_not
;
3527 for (j
= CHARSET_BITMAP_SIZE (&p
[-1]) * BYTEWIDTH
- 1, p
++;
3529 if (!!(p
[j
/ BYTEWIDTH
] & (1 << (j
% BYTEWIDTH
))) ^ not)
3532 if ((not && multibyte
)
3533 /* Any character set can possibly contain a character
3534 which doesn't match the specified set of characters. */
3535 || (CHARSET_RANGE_TABLE_EXISTS_P (&p
[-2])
3536 && CHARSET_RANGE_TABLE_BITS (&p
[-2]) != 0))
3537 /* If we can match a character class, we can match
3538 any character set. */
3540 set_fastmap_for_multibyte_characters
:
3541 if (match_any_multibyte_characters
== false)
3543 for (j
= 0x80; j
< 0xA0; j
++) /* XXX */
3544 if (BASE_LEADING_CODE_P (j
))
3546 match_any_multibyte_characters
= true;
3550 else if (!not && CHARSET_RANGE_TABLE_EXISTS_P (&p
[-2])
3551 && match_any_multibyte_characters
== false)
3553 /* Set fastmap[I] 1 where I is a base leading code of each
3554 multibyte character in the range table. */
3557 /* Make P points the range table. `+ 2' is to skip flag
3558 bits for a character class. */
3559 p
+= CHARSET_BITMAP_SIZE (&p
[-2]) + 2;
3561 /* Extract the number of ranges in range table into COUNT. */
3562 EXTRACT_NUMBER_AND_INCR (count
, p
);
3563 for (; count
> 0; count
--, p
+= 2 * 3) /* XXX */
3565 /* Extract the start of each range. */
3566 EXTRACT_CHARACTER (c
, p
);
3567 j
= CHAR_CHARSET (c
);
3568 fastmap
[CHARSET_LEADING_CODE_BASE (j
)] = 1;
3575 if (!fastmap
) break;
3577 not = (re_opcode_t
)p
[-1] == notsyntaxspec
;
3579 for (j
= 0; j
< (1 << BYTEWIDTH
); j
++)
3580 if ((SYNTAX (j
) == (enum syntaxcode
) k
) ^ not)
3584 /* This match depends on text properties. These end with
3585 aborting optimizations. */
3589 case notcategoryspec
:
3590 if (!fastmap
) break;
3591 not = (re_opcode_t
)p
[-1] == notcategoryspec
;
3593 for (j
= 0; j
< (1 << BYTEWIDTH
); j
++)
3594 if ((CHAR_HAS_CATEGORY (j
, k
)) ^ not)
3598 /* Any character set can possibly contain a character
3599 whose category is K (or not). */
3600 goto set_fastmap_for_multibyte_characters
;
3603 /* All cases after this match the empty string. These end with
3623 EXTRACT_NUMBER_AND_INCR (j
, p
);
3625 /* Backward jumps can only go back to code that we've already
3626 visited. `re_compile' should make sure this is true. */
3629 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *p
))
3631 case on_failure_jump
:
3632 case on_failure_keep_string_jump
:
3633 case on_failure_jump_loop
:
3634 case on_failure_jump_nastyloop
:
3635 case on_failure_jump_smart
:
3641 /* Keep `p1' to allow the `on_failure_jump' we are jumping to
3642 to jump back to "just after here". */
3645 case on_failure_jump
:
3646 case on_failure_keep_string_jump
:
3647 case on_failure_jump_nastyloop
:
3648 case on_failure_jump_loop
:
3649 case on_failure_jump_smart
:
3650 EXTRACT_NUMBER_AND_INCR (j
, p
);
3652 ; /* Backward jump to be ignored. */
3654 { /* We have to look down both arms.
3655 We first go down the "straight" path so as to minimize
3656 stack usage when going through alternatives. */
3657 int r
= analyse_first (p
, pend
, fastmap
, multibyte
);
3665 /* This code simply does not properly handle forward jump_n. */
3666 DEBUG_STATEMENT (EXTRACT_NUMBER (j
, p
); assert (j
< 0));
3668 /* jump_n can either jump or fall through. The (backward) jump
3669 case has already been handled, so we only need to look at the
3670 fallthrough case. */
3674 /* If N == 0, it should be an on_failure_jump_loop instead. */
3675 DEBUG_STATEMENT (EXTRACT_NUMBER (j
, p
+ 2); assert (j
> 0));
3677 /* We only care about one iteration of the loop, so we don't
3678 need to consider the case where this behaves like an
3695 abort (); /* We have listed all the cases. */
3698 /* Getting here means we have found the possible starting
3699 characters for one path of the pattern -- and that the empty
3700 string does not match. We need not follow this path further. */
3704 /* We reached the end without matching anything. */
3707 } /* analyse_first */
3709 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
3710 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
3711 characters can start a string that matches the pattern. This fastmap
3712 is used by re_search to skip quickly over impossible starting points.
3714 Character codes above (1 << BYTEWIDTH) are not represented in the
3715 fastmap, but the leading codes are represented. Thus, the fastmap
3716 indicates which character sets could start a match.
3718 The caller must supply the address of a (1 << BYTEWIDTH)-byte data
3719 area as BUFP->fastmap.
3721 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
3724 Returns 0 if we succeed, -2 if an internal error. */
3727 re_compile_fastmap (bufp
)
3728 struct re_pattern_buffer
*bufp
;
3730 char *fastmap
= bufp
->fastmap
;
3733 assert (fastmap
&& bufp
->buffer
);
3735 bzero (fastmap
, 1 << BYTEWIDTH
); /* Assume nothing's valid. */
3736 bufp
->fastmap_accurate
= 1; /* It will be when we're done. */
3738 analysis
= analyse_first (bufp
->buffer
, bufp
->buffer
+ bufp
->used
,
3739 fastmap
, RE_MULTIBYTE_P (bufp
));
3740 bufp
->can_be_null
= (analysis
!= 0);
3742 } /* re_compile_fastmap */
3744 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
3745 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
3746 this memory for recording register information. STARTS and ENDS
3747 must be allocated using the malloc library routine, and must each
3748 be at least NUM_REGS * sizeof (regoff_t) bytes long.
3750 If NUM_REGS == 0, then subsequent matches should allocate their own
3753 Unless this function is called, the first search or match using
3754 PATTERN_BUFFER will allocate its own register data, without
3755 freeing the old data. */
3758 re_set_registers (bufp
, regs
, num_regs
, starts
, ends
)
3759 struct re_pattern_buffer
*bufp
;
3760 struct re_registers
*regs
;
3762 regoff_t
*starts
, *ends
;
3766 bufp
->regs_allocated
= REGS_REALLOCATE
;
3767 regs
->num_regs
= num_regs
;
3768 regs
->start
= starts
;
3773 bufp
->regs_allocated
= REGS_UNALLOCATED
;
3775 regs
->start
= regs
->end
= (regoff_t
*) 0;
3778 WEAK_ALIAS (__re_set_registers
, re_set_registers
)
3780 /* Searching routines. */
3782 /* Like re_search_2, below, but only one string is specified, and
3783 doesn't let you say where to stop matching. */
3786 re_search (bufp
, string
, size
, startpos
, range
, regs
)
3787 struct re_pattern_buffer
*bufp
;
3789 int size
, startpos
, range
;
3790 struct re_registers
*regs
;
3792 return re_search_2 (bufp
, NULL
, 0, string
, size
, startpos
, range
,
3795 WEAK_ALIAS (__re_search
, re_search
)
3797 /* End address of virtual concatenation of string. */
3798 #define STOP_ADDR_VSTRING(P) \
3799 (((P) >= size1 ? string2 + size2 : string1 + size1))
3801 /* Address of POS in the concatenation of virtual string. */
3802 #define POS_ADDR_VSTRING(POS) \
3803 (((POS) >= size1 ? string2 - size1 : string1) + (POS))
3805 /* Using the compiled pattern in BUFP->buffer, first tries to match the
3806 virtual concatenation of STRING1 and STRING2, starting first at index
3807 STARTPOS, then at STARTPOS + 1, and so on.
3809 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
3811 RANGE is how far to scan while trying to match. RANGE = 0 means try
3812 only at STARTPOS; in general, the last start tried is STARTPOS +
3815 In REGS, return the indices of the virtual concatenation of STRING1
3816 and STRING2 that matched the entire BUFP->buffer and its contained
3819 Do not consider matching one past the index STOP in the virtual
3820 concatenation of STRING1 and STRING2.
3822 We return either the position in the strings at which the match was
3823 found, -1 if no match, or -2 if error (such as failure
3827 re_search_2 (bufp
, str1
, size1
, str2
, size2
, startpos
, range
, regs
, stop
)
3828 struct re_pattern_buffer
*bufp
;
3829 const char *str1
, *str2
;
3833 struct re_registers
*regs
;
3837 re_char
*string1
= (re_char
*) str1
;
3838 re_char
*string2
= (re_char
*) str2
;
3839 register char *fastmap
= bufp
->fastmap
;
3840 register RE_TRANSLATE_TYPE translate
= bufp
->translate
;
3841 int total_size
= size1
+ size2
;
3842 int endpos
= startpos
+ range
;
3843 boolean anchored_start
;
3845 /* Nonzero if we have to concern multibyte character. */
3846 const boolean multibyte
= RE_MULTIBYTE_P (bufp
);
3848 /* Check for out-of-range STARTPOS. */
3849 if (startpos
< 0 || startpos
> total_size
)
3852 /* Fix up RANGE if it might eventually take us outside
3853 the virtual concatenation of STRING1 and STRING2.
3854 Make sure we won't move STARTPOS below 0 or above TOTAL_SIZE. */
3856 range
= 0 - startpos
;
3857 else if (endpos
> total_size
)
3858 range
= total_size
- startpos
;
3860 /* If the search isn't to be a backwards one, don't waste time in a
3861 search for a pattern anchored at beginning of buffer. */
3862 if (bufp
->used
> 0 && (re_opcode_t
) bufp
->buffer
[0] == begbuf
&& range
> 0)
3871 /* In a forward search for something that starts with \=.
3872 don't keep searching past point. */
3873 if (bufp
->used
> 0 && (re_opcode_t
) bufp
->buffer
[0] == at_dot
&& range
> 0)
3875 range
= PT_BYTE
- BEGV_BYTE
- startpos
;
3881 /* Update the fastmap now if not correct already. */
3882 if (fastmap
&& !bufp
->fastmap_accurate
)
3883 re_compile_fastmap (bufp
);
3885 /* See whether the pattern is anchored. */
3886 anchored_start
= (bufp
->buffer
[0] == begline
);
3889 gl_state
.object
= re_match_object
;
3891 int charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (startpos
));
3893 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object
, charpos
, 1);
3897 /* Loop through the string, looking for a place to start matching. */
3900 /* If the pattern is anchored,
3901 skip quickly past places we cannot match.
3902 We don't bother to treat startpos == 0 specially
3903 because that case doesn't repeat. */
3904 if (anchored_start
&& startpos
> 0)
3906 if (! ((startpos
<= size1
? string1
[startpos
- 1]
3907 : string2
[startpos
- size1
- 1])
3912 /* If a fastmap is supplied, skip quickly over characters that
3913 cannot be the start of a match. If the pattern can match the
3914 null string, however, we don't need to skip characters; we want
3915 the first null string. */
3916 if (fastmap
&& startpos
< total_size
&& !bufp
->can_be_null
)
3918 register re_char
*d
;
3919 register re_wchar_t buf_ch
;
3921 d
= POS_ADDR_VSTRING (startpos
);
3923 if (range
> 0) /* Searching forwards. */
3925 register int lim
= 0;
3928 if (startpos
< size1
&& startpos
+ range
>= size1
)
3929 lim
= range
- (size1
- startpos
);
3931 /* Written out as an if-else to avoid testing `translate'
3933 if (RE_TRANSLATE_P (translate
))
3940 buf_ch
= STRING_CHAR_AND_LENGTH (d
, range
- lim
,
3943 buf_ch
= RE_TRANSLATE (translate
, buf_ch
);
3948 range
-= buf_charlen
;
3953 && !fastmap
[RE_TRANSLATE (translate
, *d
)])
3960 while (range
> lim
&& !fastmap
[*d
])
3966 startpos
+= irange
- range
;
3968 else /* Searching backwards. */
3970 int room
= (startpos
>= size1
3971 ? size2
+ size1
- startpos
3972 : size1
- startpos
);
3973 buf_ch
= RE_STRING_CHAR (d
, room
);
3974 buf_ch
= TRANSLATE (buf_ch
);
3976 if (! (buf_ch
>= 0400
3977 || fastmap
[buf_ch
]))
3982 /* If can't match the null string, and that's all we have left, fail. */
3983 if (range
>= 0 && startpos
== total_size
&& fastmap
3984 && !bufp
->can_be_null
)
3987 val
= re_match_2_internal (bufp
, string1
, size1
, string2
, size2
,
3988 startpos
, regs
, stop
);
3989 #ifndef REGEX_MALLOC
4006 /* Update STARTPOS to the next character boundary. */
4009 re_char
*p
= POS_ADDR_VSTRING (startpos
);
4010 re_char
*pend
= STOP_ADDR_VSTRING (startpos
);
4011 int len
= MULTIBYTE_FORM_LENGTH (p
, pend
- p
);
4029 /* Update STARTPOS to the previous character boundary. */
4032 re_char
*p
= POS_ADDR_VSTRING (startpos
);
4035 /* Find the head of multibyte form. */
4036 while (!CHAR_HEAD_P (*p
))
4041 if (MULTIBYTE_FORM_LENGTH (p
, len
+ 1) != (len
+ 1))
4057 WEAK_ALIAS (__re_search_2
, re_search_2
)
4059 /* Declarations and macros for re_match_2. */
4061 static int bcmp_translate
_RE_ARGS((re_char
*s1
, re_char
*s2
,
4063 RE_TRANSLATE_TYPE translate
,
4064 const int multibyte
));
4066 /* This converts PTR, a pointer into one of the search strings `string1'
4067 and `string2' into an offset from the beginning of that string. */
4068 #define POINTER_TO_OFFSET(ptr) \
4069 (FIRST_STRING_P (ptr) \
4070 ? ((regoff_t) ((ptr) - string1)) \
4071 : ((regoff_t) ((ptr) - string2 + size1)))
4073 /* Call before fetching a character with *d. This switches over to
4074 string2 if necessary.
4075 Check re_match_2_internal for a discussion of why end_match_2 might
4076 not be within string2 (but be equal to end_match_1 instead). */
4077 #define PREFETCH() \
4080 /* End of string2 => fail. */ \
4081 if (dend == end_match_2) \
4083 /* End of string1 => advance to string2. */ \
4085 dend = end_match_2; \
4088 /* Call before fetching a char with *d if you already checked other limits.
4089 This is meant for use in lookahead operations like wordend, etc..
4090 where we might need to look at parts of the string that might be
4091 outside of the LIMITs (i.e past `stop'). */
4092 #define PREFETCH_NOLIMIT() \
4096 dend = end_match_2; \
4099 /* Test if at very beginning or at very end of the virtual concatenation
4100 of `string1' and `string2'. If only one string, it's `string2'. */
4101 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
4102 #define AT_STRINGS_END(d) ((d) == end2)
4105 /* Test if D points to a character which is word-constituent. We have
4106 two special cases to check for: if past the end of string1, look at
4107 the first character in string2; and if before the beginning of
4108 string2, look at the last character in string1. */
4109 #define WORDCHAR_P(d) \
4110 (SYNTAX ((d) == end1 ? *string2 \
4111 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
4114 /* Disabled due to a compiler bug -- see comment at case wordbound */
4116 /* The comment at case wordbound is following one, but we don't use
4117 AT_WORD_BOUNDARY anymore to support multibyte form.
4119 The DEC Alpha C compiler 3.x generates incorrect code for the
4120 test WORDCHAR_P (d - 1) != WORDCHAR_P (d) in the expansion of
4121 AT_WORD_BOUNDARY, so this code is disabled. Expanding the
4122 macro and introducing temporary variables works around the bug. */
4125 /* Test if the character before D and the one at D differ with respect
4126 to being word-constituent. */
4127 #define AT_WORD_BOUNDARY(d) \
4128 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
4129 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
4132 /* Free everything we malloc. */
4133 #ifdef MATCH_MAY_ALLOCATE
4134 # define FREE_VAR(var) if (var) { REGEX_FREE (var); var = NULL; } else
4135 # define FREE_VARIABLES() \
4137 REGEX_FREE_STACK (fail_stack.stack); \
4138 FREE_VAR (regstart); \
4139 FREE_VAR (regend); \
4140 FREE_VAR (best_regstart); \
4141 FREE_VAR (best_regend); \
4144 # define FREE_VARIABLES() ((void)0) /* Do nothing! But inhibit gcc warning. */
4145 #endif /* not MATCH_MAY_ALLOCATE */
4148 /* Optimization routines. */
4150 /* If the operation is a match against one or more chars,
4151 return a pointer to the next operation, else return NULL. */
4156 switch (SWITCH_ENUM_CAST (*p
++))
4167 if (CHARSET_RANGE_TABLE_EXISTS_P (p
- 1))
4170 p
= CHARSET_RANGE_TABLE (p
- 1);
4171 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
4172 p
= CHARSET_RANGE_TABLE_END (p
, mcnt
);
4175 p
+= 1 + CHARSET_BITMAP_SIZE (p
- 1);
4182 case notcategoryspec
:
4194 /* Jump over non-matching operations. */
4195 static unsigned char *
4196 skip_noops (p
, pend
)
4197 unsigned char *p
, *pend
;
4202 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *p
))
4211 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
4222 /* Non-zero if "p1 matches something" implies "p2 fails". */
4224 mutually_exclusive_p (bufp
, p1
, p2
)
4225 struct re_pattern_buffer
*bufp
;
4226 unsigned char *p1
, *p2
;
4229 const boolean multibyte
= RE_MULTIBYTE_P (bufp
);
4230 unsigned char *pend
= bufp
->buffer
+ bufp
->used
;
4232 assert (p1
>= bufp
->buffer
&& p1
< pend
4233 && p2
>= bufp
->buffer
&& p2
<= pend
);
4235 /* Skip over open/close-group commands.
4236 If what follows this loop is a ...+ construct,
4237 look at what begins its body, since we will have to
4238 match at least one of that. */
4239 p2
= skip_noops (p2
, pend
);
4240 /* The same skip can be done for p1, except that this function
4241 is only used in the case where p1 is a simple match operator. */
4242 /* p1 = skip_noops (p1, pend); */
4244 assert (p1
>= bufp
->buffer
&& p1
< pend
4245 && p2
>= bufp
->buffer
&& p2
<= pend
);
4247 op2
= p2
== pend
? succeed
: *p2
;
4249 switch (SWITCH_ENUM_CAST (op2
))
4253 /* If we're at the end of the pattern, we can change. */
4254 if (skip_one_char (p1
))
4256 DEBUG_PRINT1 (" End of pattern: fast loop.\n");
4264 register re_wchar_t c
4265 = (re_opcode_t
) *p2
== endline
? '\n'
4266 : RE_STRING_CHAR (p2
+ 2, pend
- p2
- 2);
4268 if ((re_opcode_t
) *p1
== exactn
)
4270 if (c
!= RE_STRING_CHAR (p1
+ 2, pend
- p1
- 2))
4272 DEBUG_PRINT3 (" '%c' != '%c' => fast loop.\n", c
, p1
[2]);
4277 else if ((re_opcode_t
) *p1
== charset
4278 || (re_opcode_t
) *p1
== charset_not
)
4280 int not = (re_opcode_t
) *p1
== charset_not
;
4282 /* Test if C is listed in charset (or charset_not)
4284 if (SINGLE_BYTE_CHAR_P (c
))
4286 if (c
< CHARSET_BITMAP_SIZE (p1
) * BYTEWIDTH
4287 && p1
[2 + c
/ BYTEWIDTH
] & (1 << (c
% BYTEWIDTH
)))
4290 else if (CHARSET_RANGE_TABLE_EXISTS_P (p1
))
4291 CHARSET_LOOKUP_RANGE_TABLE (not, c
, p1
);
4293 /* `not' is equal to 1 if c would match, which means
4294 that we can't change to pop_failure_jump. */
4297 DEBUG_PRINT1 (" No match => fast loop.\n");
4301 else if ((re_opcode_t
) *p1
== anychar
4304 DEBUG_PRINT1 (" . != \\n => fast loop.\n");
4312 if ((re_opcode_t
) *p1
== exactn
)
4313 /* Reuse the code above. */
4314 return mutually_exclusive_p (bufp
, p2
, p1
);
4316 /* It is hard to list up all the character in charset
4317 P2 if it includes multibyte character. Give up in
4319 else if (!multibyte
|| !CHARSET_RANGE_TABLE_EXISTS_P (p2
))
4321 /* Now, we are sure that P2 has no range table.
4322 So, for the size of bitmap in P2, `p2[1]' is
4323 enough. But P1 may have range table, so the
4324 size of bitmap table of P1 is extracted by
4325 using macro `CHARSET_BITMAP_SIZE'.
4327 Since we know that all the character listed in
4328 P2 is ASCII, it is enough to test only bitmap
4331 if ((re_opcode_t
) *p1
== charset
)
4334 /* We win if the charset inside the loop
4335 has no overlap with the one after the loop. */
4338 && idx
< CHARSET_BITMAP_SIZE (p1
));
4340 if ((p2
[2 + idx
] & p1
[2 + idx
]) != 0)
4344 || idx
== CHARSET_BITMAP_SIZE (p1
))
4346 DEBUG_PRINT1 (" No match => fast loop.\n");
4350 else if ((re_opcode_t
) *p1
== charset_not
)
4353 /* We win if the charset_not inside the loop lists
4354 every character listed in the charset after. */
4355 for (idx
= 0; idx
< (int) p2
[1]; idx
++)
4356 if (! (p2
[2 + idx
] == 0
4357 || (idx
< CHARSET_BITMAP_SIZE (p1
)
4358 && ((p2
[2 + idx
] & ~ p1
[2 + idx
]) == 0))))
4363 DEBUG_PRINT1 (" No match => fast loop.\n");
4372 switch (SWITCH_ENUM_CAST (*p1
))
4376 /* Reuse the code above. */
4377 return mutually_exclusive_p (bufp
, p2
, p1
);
4379 /* When we have two charset_not, it's very unlikely that
4380 they don't overlap. The union of the two sets of excluded
4381 chars should cover all possible chars, which, as a matter of
4382 fact, is virtually impossible in multibyte buffers. */
4389 return ((re_opcode_t
) *p1
== syntaxspec
4390 && p1
[1] == (op2
== wordend
? Sword
: p2
[1]));
4394 return ((re_opcode_t
) *p1
== notsyntaxspec
4395 && p1
[1] == (op2
== wordend
? Sword
: p2
[1]));
4398 return (((re_opcode_t
) *p1
== notsyntaxspec
4399 || (re_opcode_t
) *p1
== syntaxspec
)
4404 return ((re_opcode_t
) *p1
== notcategoryspec
&& p1
[1] == p2
[1]);
4405 case notcategoryspec
:
4406 return ((re_opcode_t
) *p1
== categoryspec
&& p1
[1] == p2
[1]);
4418 /* Matching routines. */
4420 #ifndef emacs /* Emacs never uses this. */
4421 /* re_match is like re_match_2 except it takes only a single string. */
4424 re_match (bufp
, string
, size
, pos
, regs
)
4425 struct re_pattern_buffer
*bufp
;
4428 struct re_registers
*regs
;
4430 int result
= re_match_2_internal (bufp
, NULL
, 0, (re_char
*) string
, size
,
4432 # if defined C_ALLOCA && !defined REGEX_MALLOC
4437 WEAK_ALIAS (__re_match
, re_match
)
4438 #endif /* not emacs */
4441 /* In Emacs, this is the string or buffer in which we
4442 are matching. It is used for looking up syntax properties. */
4443 Lisp_Object re_match_object
;
4446 /* re_match_2 matches the compiled pattern in BUFP against the
4447 the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
4448 and SIZE2, respectively). We start matching at POS, and stop
4451 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
4452 store offsets for the substring each group matched in REGS. See the
4453 documentation for exactly how many groups we fill.
4455 We return -1 if no match, -2 if an internal error (such as the
4456 failure stack overflowing). Otherwise, we return the length of the
4457 matched substring. */
4460 re_match_2 (bufp
, string1
, size1
, string2
, size2
, pos
, regs
, stop
)
4461 struct re_pattern_buffer
*bufp
;
4462 const char *string1
, *string2
;
4465 struct re_registers
*regs
;
4472 gl_state
.object
= re_match_object
;
4473 charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (pos
));
4474 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object
, charpos
, 1);
4477 result
= re_match_2_internal (bufp
, (re_char
*) string1
, size1
,
4478 (re_char
*) string2
, size2
,
4480 #if defined C_ALLOCA && !defined REGEX_MALLOC
4485 WEAK_ALIAS (__re_match_2
, re_match_2
)
4487 /* This is a separate function so that we can force an alloca cleanup
4490 re_match_2_internal (bufp
, string1
, size1
, string2
, size2
, pos
, regs
, stop
)
4491 struct re_pattern_buffer
*bufp
;
4492 re_char
*string1
, *string2
;
4495 struct re_registers
*regs
;
4498 /* General temporaries. */
4503 /* Just past the end of the corresponding string. */
4504 re_char
*end1
, *end2
;
4506 /* Pointers into string1 and string2, just past the last characters in
4507 each to consider matching. */
4508 re_char
*end_match_1
, *end_match_2
;
4510 /* Where we are in the data, and the end of the current string. */
4513 /* Used sometimes to remember where we were before starting matching
4514 an operator so that we can go back in case of failure. This "atomic"
4515 behavior of matching opcodes is indispensable to the correctness
4516 of the on_failure_keep_string_jump optimization. */
4519 /* Where we are in the pattern, and the end of the pattern. */
4520 re_char
*p
= bufp
->buffer
;
4521 re_char
*pend
= p
+ bufp
->used
;
4523 /* We use this to map every character in the string. */
4524 RE_TRANSLATE_TYPE translate
= bufp
->translate
;
4526 /* Nonzero if we have to concern multibyte character. */
4527 const boolean multibyte
= RE_MULTIBYTE_P (bufp
);
4529 /* Failure point stack. Each place that can handle a failure further
4530 down the line pushes a failure point on this stack. It consists of
4531 regstart, and regend for all registers corresponding to
4532 the subexpressions we're currently inside, plus the number of such
4533 registers, and, finally, two char *'s. The first char * is where
4534 to resume scanning the pattern; the second one is where to resume
4535 scanning the strings. */
4536 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
4537 fail_stack_type fail_stack
;
4540 unsigned nfailure_points_pushed
= 0, nfailure_points_popped
= 0;
4543 #if defined REL_ALLOC && defined REGEX_MALLOC
4544 /* This holds the pointer to the failure stack, when
4545 it is allocated relocatably. */
4546 fail_stack_elt_t
*failure_stack_ptr
;
4549 /* We fill all the registers internally, independent of what we
4550 return, for use in backreferences. The number here includes
4551 an element for register zero. */
4552 size_t num_regs
= bufp
->re_nsub
+ 1;
4554 /* Information on the contents of registers. These are pointers into
4555 the input strings; they record just what was matched (on this
4556 attempt) by a subexpression part of the pattern, that is, the
4557 regnum-th regstart pointer points to where in the pattern we began
4558 matching and the regnum-th regend points to right after where we
4559 stopped matching the regnum-th subexpression. (The zeroth register
4560 keeps track of what the whole pattern matches.) */
4561 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4562 re_char
**regstart
, **regend
;
4565 /* The following record the register info as found in the above
4566 variables when we find a match better than any we've seen before.
4567 This happens as we backtrack through the failure points, which in
4568 turn happens only if we have not yet matched the entire string. */
4569 unsigned best_regs_set
= false;
4570 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4571 re_char
**best_regstart
, **best_regend
;
4574 /* Logically, this is `best_regend[0]'. But we don't want to have to
4575 allocate space for that if we're not allocating space for anything
4576 else (see below). Also, we never need info about register 0 for
4577 any of the other register vectors, and it seems rather a kludge to
4578 treat `best_regend' differently than the rest. So we keep track of
4579 the end of the best match so far in a separate variable. We
4580 initialize this to NULL so that when we backtrack the first time
4581 and need to test it, it's not garbage. */
4582 re_char
*match_end
= NULL
;
4585 /* Counts the total number of registers pushed. */
4586 unsigned num_regs_pushed
= 0;
4589 DEBUG_PRINT1 ("\n\nEntering re_match_2.\n");
4593 #ifdef MATCH_MAY_ALLOCATE
4594 /* Do not bother to initialize all the register variables if there are
4595 no groups in the pattern, as it takes a fair amount of time. If
4596 there are groups, we include space for register 0 (the whole
4597 pattern), even though we never use it, since it simplifies the
4598 array indexing. We should fix this. */
4601 regstart
= REGEX_TALLOC (num_regs
, re_char
*);
4602 regend
= REGEX_TALLOC (num_regs
, re_char
*);
4603 best_regstart
= REGEX_TALLOC (num_regs
, re_char
*);
4604 best_regend
= REGEX_TALLOC (num_regs
, re_char
*);
4606 if (!(regstart
&& regend
&& best_regstart
&& best_regend
))
4614 /* We must initialize all our variables to NULL, so that
4615 `FREE_VARIABLES' doesn't try to free them. */
4616 regstart
= regend
= best_regstart
= best_regend
= NULL
;
4618 #endif /* MATCH_MAY_ALLOCATE */
4620 /* The starting position is bogus. */
4621 if (pos
< 0 || pos
> size1
+ size2
)
4627 /* Initialize subexpression text positions to -1 to mark ones that no
4628 start_memory/stop_memory has been seen for. Also initialize the
4629 register information struct. */
4630 for (reg
= 1; reg
< num_regs
; reg
++)
4631 regstart
[reg
] = regend
[reg
] = NULL
;
4633 /* We move `string1' into `string2' if the latter's empty -- but not if
4634 `string1' is null. */
4635 if (size2
== 0 && string1
!= NULL
)
4642 end1
= string1
+ size1
;
4643 end2
= string2
+ size2
;
4645 /* `p' scans through the pattern as `d' scans through the data.
4646 `dend' is the end of the input string that `d' points within. `d'
4647 is advanced into the following input string whenever necessary, but
4648 this happens before fetching; therefore, at the beginning of the
4649 loop, `d' can be pointing at the end of a string, but it cannot
4653 /* Only match within string2. */
4654 d
= string2
+ pos
- size1
;
4655 dend
= end_match_2
= string2
+ stop
- size1
;
4656 end_match_1
= end1
; /* Just to give it a value. */
4662 /* Only match within string1. */
4663 end_match_1
= string1
+ stop
;
4665 When we reach end_match_1, PREFETCH normally switches to string2.
4666 But in the present case, this means that just doing a PREFETCH
4667 makes us jump from `stop' to `gap' within the string.
4668 What we really want here is for the search to stop as
4669 soon as we hit end_match_1. That's why we set end_match_2
4670 to end_match_1 (since PREFETCH fails as soon as we hit
4672 end_match_2
= end_match_1
;
4675 { /* It's important to use this code when stop == size so that
4676 moving `d' from end1 to string2 will not prevent the d == dend
4677 check from catching the end of string. */
4679 end_match_2
= string2
+ stop
- size1
;
4685 DEBUG_PRINT1 ("The compiled pattern is: ");
4686 DEBUG_PRINT_COMPILED_PATTERN (bufp
, p
, pend
);
4687 DEBUG_PRINT1 ("The string to match is: `");
4688 DEBUG_PRINT_DOUBLE_STRING (d
, string1
, size1
, string2
, size2
);
4689 DEBUG_PRINT1 ("'\n");
4691 /* This loops over pattern commands. It exits by returning from the
4692 function if the match is complete, or it drops through if the match
4693 fails at this starting point in the input data. */
4696 DEBUG_PRINT2 ("\n%p: ", p
);
4699 { /* End of pattern means we might have succeeded. */
4700 DEBUG_PRINT1 ("end of pattern ... ");
4702 /* If we haven't matched the entire string, and we want the
4703 longest match, try backtracking. */
4704 if (d
!= end_match_2
)
4706 /* 1 if this match ends in the same string (string1 or string2)
4707 as the best previous match. */
4708 boolean same_str_p
= (FIRST_STRING_P (match_end
)
4709 == FIRST_STRING_P (d
));
4710 /* 1 if this match is the best seen so far. */
4711 boolean best_match_p
;
4713 /* AIX compiler got confused when this was combined
4714 with the previous declaration. */
4716 best_match_p
= d
> match_end
;
4718 best_match_p
= !FIRST_STRING_P (d
);
4720 DEBUG_PRINT1 ("backtracking.\n");
4722 if (!FAIL_STACK_EMPTY ())
4723 { /* More failure points to try. */
4725 /* If exceeds best match so far, save it. */
4726 if (!best_regs_set
|| best_match_p
)
4728 best_regs_set
= true;
4731 DEBUG_PRINT1 ("\nSAVING match as best so far.\n");
4733 for (reg
= 1; reg
< num_regs
; reg
++)
4735 best_regstart
[reg
] = regstart
[reg
];
4736 best_regend
[reg
] = regend
[reg
];
4742 /* If no failure points, don't restore garbage. And if
4743 last match is real best match, don't restore second
4745 else if (best_regs_set
&& !best_match_p
)
4748 /* Restore best match. It may happen that `dend ==
4749 end_match_1' while the restored d is in string2.
4750 For example, the pattern `x.*y.*z' against the
4751 strings `x-' and `y-z-', if the two strings are
4752 not consecutive in memory. */
4753 DEBUG_PRINT1 ("Restoring best registers.\n");
4756 dend
= ((d
>= string1
&& d
<= end1
)
4757 ? end_match_1
: end_match_2
);
4759 for (reg
= 1; reg
< num_regs
; reg
++)
4761 regstart
[reg
] = best_regstart
[reg
];
4762 regend
[reg
] = best_regend
[reg
];
4765 } /* d != end_match_2 */
4768 DEBUG_PRINT1 ("Accepting match.\n");
4770 /* If caller wants register contents data back, do it. */
4771 if (regs
&& !bufp
->no_sub
)
4773 /* Have the register data arrays been allocated? */
4774 if (bufp
->regs_allocated
== REGS_UNALLOCATED
)
4775 { /* No. So allocate them with malloc. We need one
4776 extra element beyond `num_regs' for the `-1' marker
4778 regs
->num_regs
= MAX (RE_NREGS
, num_regs
+ 1);
4779 regs
->start
= TALLOC (regs
->num_regs
, regoff_t
);
4780 regs
->end
= TALLOC (regs
->num_regs
, regoff_t
);
4781 if (regs
->start
== NULL
|| regs
->end
== NULL
)
4786 bufp
->regs_allocated
= REGS_REALLOCATE
;
4788 else if (bufp
->regs_allocated
== REGS_REALLOCATE
)
4789 { /* Yes. If we need more elements than were already
4790 allocated, reallocate them. If we need fewer, just
4792 if (regs
->num_regs
< num_regs
+ 1)
4794 regs
->num_regs
= num_regs
+ 1;
4795 RETALLOC (regs
->start
, regs
->num_regs
, regoff_t
);
4796 RETALLOC (regs
->end
, regs
->num_regs
, regoff_t
);
4797 if (regs
->start
== NULL
|| regs
->end
== NULL
)
4806 /* These braces fend off a "empty body in an else-statement"
4807 warning under GCC when assert expands to nothing. */
4808 assert (bufp
->regs_allocated
== REGS_FIXED
);
4811 /* Convert the pointer data in `regstart' and `regend' to
4812 indices. Register zero has to be set differently,
4813 since we haven't kept track of any info for it. */
4814 if (regs
->num_regs
> 0)
4816 regs
->start
[0] = pos
;
4817 regs
->end
[0] = POINTER_TO_OFFSET (d
);
4820 /* Go through the first `min (num_regs, regs->num_regs)'
4821 registers, since that is all we initialized. */
4822 for (reg
= 1; reg
< MIN (num_regs
, regs
->num_regs
); reg
++)
4824 if (REG_UNSET (regstart
[reg
]) || REG_UNSET (regend
[reg
]))
4825 regs
->start
[reg
] = regs
->end
[reg
] = -1;
4829 = (regoff_t
) POINTER_TO_OFFSET (regstart
[reg
]);
4831 = (regoff_t
) POINTER_TO_OFFSET (regend
[reg
]);
4835 /* If the regs structure we return has more elements than
4836 were in the pattern, set the extra elements to -1. If
4837 we (re)allocated the registers, this is the case,
4838 because we always allocate enough to have at least one
4840 for (reg
= num_regs
; reg
< regs
->num_regs
; reg
++)
4841 regs
->start
[reg
] = regs
->end
[reg
] = -1;
4842 } /* regs && !bufp->no_sub */
4844 DEBUG_PRINT4 ("%u failure points pushed, %u popped (%u remain).\n",
4845 nfailure_points_pushed
, nfailure_points_popped
,
4846 nfailure_points_pushed
- nfailure_points_popped
);
4847 DEBUG_PRINT2 ("%u registers pushed.\n", num_regs_pushed
);
4849 mcnt
= POINTER_TO_OFFSET (d
) - pos
;
4851 DEBUG_PRINT2 ("Returning %d from re_match_2.\n", mcnt
);
4857 /* Otherwise match next pattern command. */
4858 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *p
++))
4860 /* Ignore these. Used to ignore the n of succeed_n's which
4861 currently have n == 0. */
4863 DEBUG_PRINT1 ("EXECUTING no_op.\n");
4867 DEBUG_PRINT1 ("EXECUTING succeed.\n");
4870 /* Match the next n pattern characters exactly. The following
4871 byte in the pattern defines n, and the n bytes after that
4872 are the characters to match. */
4875 DEBUG_PRINT2 ("EXECUTING exactn %d.\n", mcnt
);
4877 /* Remember the start point to rollback upon failure. */
4880 /* This is written out as an if-else so we don't waste time
4881 testing `translate' inside the loop. */
4882 if (RE_TRANSLATE_P (translate
))
4887 int pat_charlen
, buf_charlen
;
4888 unsigned int pat_ch
, buf_ch
;
4891 pat_ch
= STRING_CHAR_AND_LENGTH (p
, pend
- p
, pat_charlen
);
4892 buf_ch
= STRING_CHAR_AND_LENGTH (d
, dend
- d
, buf_charlen
);
4894 if (RE_TRANSLATE (translate
, buf_ch
)
4903 mcnt
-= pat_charlen
;
4910 if (RE_TRANSLATE (translate
, *d
) != *p
++)
4935 /* Match any character except possibly a newline or a null. */
4941 DEBUG_PRINT1 ("EXECUTING anychar.\n");
4944 buf_ch
= RE_STRING_CHAR_AND_LENGTH (d
, dend
- d
, buf_charlen
);
4945 buf_ch
= TRANSLATE (buf_ch
);
4947 if ((!(bufp
->syntax
& RE_DOT_NEWLINE
)
4949 || ((bufp
->syntax
& RE_DOT_NOT_NULL
)
4950 && buf_ch
== '\000'))
4953 DEBUG_PRINT2 (" Matched `%d'.\n", *d
);
4962 register unsigned int c
;
4963 boolean
not = (re_opcode_t
) *(p
- 1) == charset_not
;
4966 /* Start of actual range_table, or end of bitmap if there is no
4968 re_char
*range_table
;
4970 /* Nonzero if there is a range table. */
4971 int range_table_exists
;
4973 /* Number of ranges of range table. This is not included
4974 in the initial byte-length of the command. */
4977 DEBUG_PRINT2 ("EXECUTING charset%s.\n", not ? "_not" : "");
4979 range_table_exists
= CHARSET_RANGE_TABLE_EXISTS_P (&p
[-1]);
4981 if (range_table_exists
)
4983 range_table
= CHARSET_RANGE_TABLE (&p
[-1]); /* Past the bitmap. */
4984 EXTRACT_NUMBER_AND_INCR (count
, range_table
);
4988 c
= RE_STRING_CHAR_AND_LENGTH (d
, dend
- d
, len
);
4989 c
= TRANSLATE (c
); /* The character to match. */
4991 if (SINGLE_BYTE_CHAR_P (c
))
4992 { /* Lookup bitmap. */
4993 /* Cast to `unsigned' instead of `unsigned char' in
4994 case the bit list is a full 32 bytes long. */
4995 if (c
< (unsigned) (CHARSET_BITMAP_SIZE (&p
[-1]) * BYTEWIDTH
)
4996 && p
[1 + c
/ BYTEWIDTH
] & (1 << (c
% BYTEWIDTH
)))
5000 else if (range_table_exists
)
5002 int class_bits
= CHARSET_RANGE_TABLE_BITS (&p
[-1]);
5004 if ( (class_bits
& BIT_LOWER
&& ISLOWER (c
))
5005 | (class_bits
& BIT_MULTIBYTE
)
5006 | (class_bits
& BIT_PUNCT
&& ISPUNCT (c
))
5007 | (class_bits
& BIT_SPACE
&& ISSPACE (c
))
5008 | (class_bits
& BIT_UPPER
&& ISUPPER (c
))
5009 | (class_bits
& BIT_WORD
&& ISWORD (c
)))
5012 CHARSET_LOOKUP_RANGE_TABLE_RAW (not, c
, range_table
, count
);
5016 if (range_table_exists
)
5017 p
= CHARSET_RANGE_TABLE_END (range_table
, count
);
5019 p
+= CHARSET_BITMAP_SIZE (&p
[-1]) + 1;
5021 if (!not) goto fail
;
5028 /* The beginning of a group is represented by start_memory.
5029 The argument is the register number. The text
5030 matched within the group is recorded (in the internal
5031 registers data structure) under the register number. */
5033 DEBUG_PRINT2 ("EXECUTING start_memory %d:\n", *p
);
5035 /* In case we need to undo this operation (via backtracking). */
5036 PUSH_FAILURE_REG ((unsigned int)*p
);
5039 regend
[*p
] = NULL
; /* probably unnecessary. -sm */
5040 DEBUG_PRINT2 (" regstart: %d\n", POINTER_TO_OFFSET (regstart
[*p
]));
5042 /* Move past the register number and inner group count. */
5047 /* The stop_memory opcode represents the end of a group. Its
5048 argument is the same as start_memory's: the register number. */
5050 DEBUG_PRINT2 ("EXECUTING stop_memory %d:\n", *p
);
5052 assert (!REG_UNSET (regstart
[*p
]));
5053 /* Strictly speaking, there should be code such as:
5055 assert (REG_UNSET (regend[*p]));
5056 PUSH_FAILURE_REGSTOP ((unsigned int)*p);
5058 But the only info to be pushed is regend[*p] and it is known to
5059 be UNSET, so there really isn't anything to push.
5060 Not pushing anything, on the other hand deprives us from the
5061 guarantee that regend[*p] is UNSET since undoing this operation
5062 will not reset its value properly. This is not important since
5063 the value will only be read on the next start_memory or at
5064 the very end and both events can only happen if this stop_memory
5068 DEBUG_PRINT2 (" regend: %d\n", POINTER_TO_OFFSET (regend
[*p
]));
5070 /* Move past the register number and the inner group count. */
5075 /* \<digit> has been turned into a `duplicate' command which is
5076 followed by the numeric value of <digit> as the register number. */
5079 register re_char
*d2
, *dend2
;
5080 int regno
= *p
++; /* Get which register to match against. */
5081 DEBUG_PRINT2 ("EXECUTING duplicate %d.\n", regno
);
5083 /* Can't back reference a group which we've never matched. */
5084 if (REG_UNSET (regstart
[regno
]) || REG_UNSET (regend
[regno
]))
5087 /* Where in input to try to start matching. */
5088 d2
= regstart
[regno
];
5090 /* Remember the start point to rollback upon failure. */
5093 /* Where to stop matching; if both the place to start and
5094 the place to stop matching are in the same string, then
5095 set to the place to stop, otherwise, for now have to use
5096 the end of the first string. */
5098 dend2
= ((FIRST_STRING_P (regstart
[regno
])
5099 == FIRST_STRING_P (regend
[regno
]))
5100 ? regend
[regno
] : end_match_1
);
5103 /* If necessary, advance to next segment in register
5107 if (dend2
== end_match_2
) break;
5108 if (dend2
== regend
[regno
]) break;
5110 /* End of string1 => advance to string2. */
5112 dend2
= regend
[regno
];
5114 /* At end of register contents => success */
5115 if (d2
== dend2
) break;
5117 /* If necessary, advance to next segment in data. */
5120 /* How many characters left in this segment to match. */
5123 /* Want how many consecutive characters we can match in
5124 one shot, so, if necessary, adjust the count. */
5125 if (mcnt
> dend2
- d2
)
5128 /* Compare that many; failure if mismatch, else move
5130 if (RE_TRANSLATE_P (translate
)
5131 ? bcmp_translate (d
, d2
, mcnt
, translate
, multibyte
)
5132 : memcmp (d
, d2
, mcnt
))
5137 d
+= mcnt
, d2
+= mcnt
;
5143 /* begline matches the empty string at the beginning of the string
5144 (unless `not_bol' is set in `bufp'), and after newlines. */
5146 DEBUG_PRINT1 ("EXECUTING begline.\n");
5148 if (AT_STRINGS_BEG (d
))
5150 if (!bufp
->not_bol
) break;
5155 GET_CHAR_BEFORE_2 (c
, d
, string1
, end1
, string2
, end2
);
5159 /* In all other cases, we fail. */
5163 /* endline is the dual of begline. */
5165 DEBUG_PRINT1 ("EXECUTING endline.\n");
5167 if (AT_STRINGS_END (d
))
5169 if (!bufp
->not_eol
) break;
5173 PREFETCH_NOLIMIT ();
5180 /* Match at the very beginning of the data. */
5182 DEBUG_PRINT1 ("EXECUTING begbuf.\n");
5183 if (AT_STRINGS_BEG (d
))
5188 /* Match at the very end of the data. */
5190 DEBUG_PRINT1 ("EXECUTING endbuf.\n");
5191 if (AT_STRINGS_END (d
))
5196 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
5197 pushes NULL as the value for the string on the stack. Then
5198 `POP_FAILURE_POINT' will keep the current value for the
5199 string, instead of restoring it. To see why, consider
5200 matching `foo\nbar' against `.*\n'. The .* matches the foo;
5201 then the . fails against the \n. But the next thing we want
5202 to do is match the \n against the \n; if we restored the
5203 string value, we would be back at the foo.
5205 Because this is used only in specific cases, we don't need to
5206 check all the things that `on_failure_jump' does, to make
5207 sure the right things get saved on the stack. Hence we don't
5208 share its code. The only reason to push anything on the
5209 stack at all is that otherwise we would have to change
5210 `anychar's code to do something besides goto fail in this
5211 case; that seems worse than this. */
5212 case on_failure_keep_string_jump
:
5213 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5214 DEBUG_PRINT3 ("EXECUTING on_failure_keep_string_jump %d (to %p):\n",
5217 PUSH_FAILURE_POINT (p
- 3, NULL
);
5220 /* A nasty loop is introduced by the non-greedy *? and +?.
5221 With such loops, the stack only ever contains one failure point
5222 at a time, so that a plain on_failure_jump_loop kind of
5223 cycle detection cannot work. Worse yet, such a detection
5224 can not only fail to detect a cycle, but it can also wrongly
5225 detect a cycle (between different instantiations of the same
5227 So the method used for those nasty loops is a little different:
5228 We use a special cycle-detection-stack-frame which is pushed
5229 when the on_failure_jump_nastyloop failure-point is *popped*.
5230 This special frame thus marks the beginning of one iteration
5231 through the loop and we can hence easily check right here
5232 whether something matched between the beginning and the end of
5234 case on_failure_jump_nastyloop
:
5235 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5236 DEBUG_PRINT3 ("EXECUTING on_failure_jump_nastyloop %d (to %p):\n",
5239 assert ((re_opcode_t
)p
[-4] == no_op
);
5240 CHECK_INFINITE_LOOP (p
- 4, d
);
5241 PUSH_FAILURE_POINT (p
- 3, d
);
5245 /* Simple loop detecting on_failure_jump: just check on the
5246 failure stack if the same spot was already hit earlier. */
5247 case on_failure_jump_loop
:
5249 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5250 DEBUG_PRINT3 ("EXECUTING on_failure_jump_loop %d (to %p):\n",
5253 CHECK_INFINITE_LOOP (p
- 3, d
);
5254 PUSH_FAILURE_POINT (p
- 3, d
);
5258 /* Uses of on_failure_jump:
5260 Each alternative starts with an on_failure_jump that points
5261 to the beginning of the next alternative. Each alternative
5262 except the last ends with a jump that in effect jumps past
5263 the rest of the alternatives. (They really jump to the
5264 ending jump of the following alternative, because tensioning
5265 these jumps is a hassle.)
5267 Repeats start with an on_failure_jump that points past both
5268 the repetition text and either the following jump or
5269 pop_failure_jump back to this on_failure_jump. */
5270 case on_failure_jump
:
5271 IMMEDIATE_QUIT_CHECK
;
5272 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5273 DEBUG_PRINT3 ("EXECUTING on_failure_jump %d (to %p):\n",
5276 PUSH_FAILURE_POINT (p
-3, d
);
5279 /* This operation is used for greedy *.
5280 Compare the beginning of the repeat with what in the
5281 pattern follows its end. If we can establish that there
5282 is nothing that they would both match, i.e., that we
5283 would have to backtrack because of (as in, e.g., `a*a')
5284 then we can use a non-backtracking loop based on
5285 on_failure_keep_string_jump instead of on_failure_jump. */
5286 case on_failure_jump_smart
:
5287 IMMEDIATE_QUIT_CHECK
;
5288 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5289 DEBUG_PRINT3 ("EXECUTING on_failure_jump_smart %d (to %p).\n",
5292 re_char
*p1
= p
; /* Next operation. */
5293 /* Here, we discard `const', making re_match non-reentrant. */
5294 unsigned char *p2
= (unsigned char*) p
+ mcnt
; /* Jump dest. */
5295 unsigned char *p3
= (unsigned char*) p
- 3; /* opcode location. */
5297 p
-= 3; /* Reset so that we will re-execute the
5298 instruction once it's been changed. */
5300 EXTRACT_NUMBER (mcnt
, p2
- 2);
5302 /* Ensure this is a indeed the trivial kind of loop
5303 we are expecting. */
5304 assert (skip_one_char (p1
) == p2
- 3);
5305 assert ((re_opcode_t
) p2
[-3] == jump
&& p2
+ mcnt
== p
);
5306 DEBUG_STATEMENT (debug
+= 2);
5307 if (mutually_exclusive_p (bufp
, p1
, p2
))
5309 /* Use a fast `on_failure_keep_string_jump' loop. */
5310 DEBUG_PRINT1 (" smart exclusive => fast loop.\n");
5311 *p3
= (unsigned char) on_failure_keep_string_jump
;
5312 STORE_NUMBER (p2
- 2, mcnt
+ 3);
5316 /* Default to a safe `on_failure_jump' loop. */
5317 DEBUG_PRINT1 (" smart default => slow loop.\n");
5318 *p3
= (unsigned char) on_failure_jump
;
5320 DEBUG_STATEMENT (debug
-= 2);
5324 /* Unconditionally jump (without popping any failure points). */
5327 IMMEDIATE_QUIT_CHECK
;
5328 EXTRACT_NUMBER_AND_INCR (mcnt
, p
); /* Get the amount to jump. */
5329 DEBUG_PRINT2 ("EXECUTING jump %d ", mcnt
);
5330 p
+= mcnt
; /* Do the jump. */
5331 DEBUG_PRINT2 ("(to %p).\n", p
);
5335 /* Have to succeed matching what follows at least n times.
5336 After that, handle like `on_failure_jump'. */
5338 /* Signedness doesn't matter since we only compare MCNT to 0. */
5339 EXTRACT_NUMBER (mcnt
, p
+ 2);
5340 DEBUG_PRINT2 ("EXECUTING succeed_n %d.\n", mcnt
);
5342 /* Originally, mcnt is how many times we HAVE to succeed. */
5345 /* Here, we discard `const', making re_match non-reentrant. */
5346 unsigned char *p2
= (unsigned char*) p
+ 2; /* counter loc. */
5349 PUSH_NUMBER (p2
, mcnt
);
5352 /* The two bytes encoding mcnt == 0 are two no_op opcodes. */
5357 /* Signedness doesn't matter since we only compare MCNT to 0. */
5358 EXTRACT_NUMBER (mcnt
, p
+ 2);
5359 DEBUG_PRINT2 ("EXECUTING jump_n %d.\n", mcnt
);
5361 /* Originally, this is how many times we CAN jump. */
5364 /* Here, we discard `const', making re_match non-reentrant. */
5365 unsigned char *p2
= (unsigned char*) p
+ 2; /* counter loc. */
5367 PUSH_NUMBER (p2
, mcnt
);
5368 goto unconditional_jump
;
5370 /* If don't have to jump any more, skip over the rest of command. */
5377 unsigned char *p2
; /* Location of the counter. */
5378 DEBUG_PRINT1 ("EXECUTING set_number_at.\n");
5380 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5381 /* Here, we discard `const', making re_match non-reentrant. */
5382 p2
= (unsigned char*) p
+ mcnt
;
5383 /* Signedness doesn't matter since we only copy MCNT's bits . */
5384 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5385 DEBUG_PRINT3 (" Setting %p to %d.\n", p2
, mcnt
);
5386 PUSH_NUMBER (p2
, mcnt
);
5392 not = (re_opcode_t
) *(p
- 1) == notwordbound
;
5393 DEBUG_PRINT2 ("EXECUTING %swordbound.\n", not?"not":"");
5395 /* We SUCCEED (or FAIL) in one of the following cases: */
5397 /* Case 1: D is at the beginning or the end of string. */
5398 if (AT_STRINGS_BEG (d
) || AT_STRINGS_END (d
))
5402 /* C1 is the character before D, S1 is the syntax of C1, C2
5403 is the character at D, and S2 is the syntax of C2. */
5407 int offset
= PTR_TO_OFFSET (d
- 1);
5408 int charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
5409 UPDATE_SYNTAX_TABLE (charpos
);
5411 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
5414 UPDATE_SYNTAX_TABLE_FORWARD (charpos
+ 1);
5416 PREFETCH_NOLIMIT ();
5417 c2
= RE_STRING_CHAR (d
, dend
- d
);
5420 if (/* Case 2: Only one of S1 and S2 is Sword. */
5421 ((s1
== Sword
) != (s2
== Sword
))
5422 /* Case 3: Both of S1 and S2 are Sword, and macro
5423 WORD_BOUNDARY_P (C1, C2) returns nonzero. */
5424 || ((s1
== Sword
) && WORD_BOUNDARY_P (c1
, c2
)))
5433 DEBUG_PRINT1 ("EXECUTING wordbeg.\n");
5435 /* We FAIL in one of the following cases: */
5437 /* Case 1: D is at the end of string. */
5438 if (AT_STRINGS_END (d
))
5442 /* C1 is the character before D, S1 is the syntax of C1, C2
5443 is the character at D, and S2 is the syntax of C2. */
5447 int offset
= PTR_TO_OFFSET (d
);
5448 int charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
5449 UPDATE_SYNTAX_TABLE (charpos
);
5452 c2
= RE_STRING_CHAR (d
, dend
- d
);
5455 /* Case 2: S2 is not Sword. */
5459 /* Case 3: D is not at the beginning of string ... */
5460 if (!AT_STRINGS_BEG (d
))
5462 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
5464 UPDATE_SYNTAX_TABLE_BACKWARD (charpos
- 1);
5468 /* ... and S1 is Sword, and WORD_BOUNDARY_P (C1, C2)
5470 if ((s1
== Sword
) && !WORD_BOUNDARY_P (c1
, c2
))
5477 DEBUG_PRINT1 ("EXECUTING wordend.\n");
5479 /* We FAIL in one of the following cases: */
5481 /* Case 1: D is at the beginning of string. */
5482 if (AT_STRINGS_BEG (d
))
5486 /* C1 is the character before D, S1 is the syntax of C1, C2
5487 is the character at D, and S2 is the syntax of C2. */
5491 int offset
= PTR_TO_OFFSET (d
) - 1;
5492 int charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
5493 UPDATE_SYNTAX_TABLE (charpos
);
5495 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
5498 /* Case 2: S1 is not Sword. */
5502 /* Case 3: D is not at the end of string ... */
5503 if (!AT_STRINGS_END (d
))
5505 PREFETCH_NOLIMIT ();
5506 c2
= RE_STRING_CHAR (d
, dend
- d
);
5508 UPDATE_SYNTAX_TABLE_FORWARD (charpos
);
5512 /* ... and S2 is Sword, and WORD_BOUNDARY_P (C1, C2)
5514 if ((s2
== Sword
) && !WORD_BOUNDARY_P (c1
, c2
))
5522 not = (re_opcode_t
) *(p
- 1) == notsyntaxspec
;
5524 DEBUG_PRINT3 ("EXECUTING %ssyntaxspec %d.\n", not?"not":"", mcnt
);
5528 int offset
= PTR_TO_OFFSET (d
);
5529 int pos1
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
5530 UPDATE_SYNTAX_TABLE (pos1
);
5537 c
= RE_STRING_CHAR_AND_LENGTH (d
, dend
- d
, len
);
5539 if ((SYNTAX (c
) != (enum syntaxcode
) mcnt
) ^ not)
5547 DEBUG_PRINT1 ("EXECUTING before_dot.\n");
5548 if (PTR_BYTE_POS (d
) >= PT_BYTE
)
5553 DEBUG_PRINT1 ("EXECUTING at_dot.\n");
5554 if (PTR_BYTE_POS (d
) != PT_BYTE
)
5559 DEBUG_PRINT1 ("EXECUTING after_dot.\n");
5560 if (PTR_BYTE_POS (d
) <= PT_BYTE
)
5565 case notcategoryspec
:
5566 not = (re_opcode_t
) *(p
- 1) == notcategoryspec
;
5568 DEBUG_PRINT3 ("EXECUTING %scategoryspec %d.\n", not?"not":"", mcnt
);
5574 c
= RE_STRING_CHAR_AND_LENGTH (d
, dend
- d
, len
);
5576 if ((!CHAR_HAS_CATEGORY (c
, mcnt
)) ^ not)
5587 continue; /* Successfully executed one pattern command; keep going. */
5590 /* We goto here if a matching operation fails. */
5592 IMMEDIATE_QUIT_CHECK
;
5593 if (!FAIL_STACK_EMPTY ())
5596 /* A restart point is known. Restore to that state. */
5597 DEBUG_PRINT1 ("\nFAIL:\n");
5598 POP_FAILURE_POINT (str
, pat
);
5599 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *pat
++))
5601 case on_failure_keep_string_jump
:
5602 assert (str
== NULL
);
5603 goto continue_failure_jump
;
5605 case on_failure_jump_nastyloop
:
5606 assert ((re_opcode_t
)pat
[-2] == no_op
);
5607 PUSH_FAILURE_POINT (pat
- 2, str
);
5610 case on_failure_jump_loop
:
5611 case on_failure_jump
:
5614 continue_failure_jump
:
5615 EXTRACT_NUMBER_AND_INCR (mcnt
, pat
);
5620 /* A special frame used for nastyloops. */
5627 assert (p
>= bufp
->buffer
&& p
<= pend
);
5629 if (d
>= string1
&& d
<= end1
)
5633 break; /* Matching at this starting point really fails. */
5637 goto restore_best_regs
;
5641 return -1; /* Failure to match. */
5644 /* Subroutine definitions for re_match_2. */
5646 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
5647 bytes; nonzero otherwise. */
5650 bcmp_translate (s1
, s2
, len
, translate
, multibyte
)
5653 RE_TRANSLATE_TYPE translate
;
5654 const int multibyte
;
5656 register re_char
*p1
= s1
, *p2
= s2
;
5657 re_char
*p1_end
= s1
+ len
;
5658 re_char
*p2_end
= s2
+ len
;
5660 /* FIXME: Checking both p1 and p2 presumes that the two strings might have
5661 different lengths, but relying on a single `len' would break this. -sm */
5662 while (p1
< p1_end
&& p2
< p2_end
)
5664 int p1_charlen
, p2_charlen
;
5665 re_wchar_t p1_ch
, p2_ch
;
5667 p1_ch
= RE_STRING_CHAR_AND_LENGTH (p1
, p1_end
- p1
, p1_charlen
);
5668 p2_ch
= RE_STRING_CHAR_AND_LENGTH (p2
, p2_end
- p2
, p2_charlen
);
5670 if (RE_TRANSLATE (translate
, p1_ch
)
5671 != RE_TRANSLATE (translate
, p2_ch
))
5674 p1
+= p1_charlen
, p2
+= p2_charlen
;
5677 if (p1
!= p1_end
|| p2
!= p2_end
)
5683 /* Entry points for GNU code. */
5685 /* re_compile_pattern is the GNU regular expression compiler: it
5686 compiles PATTERN (of length SIZE) and puts the result in BUFP.
5687 Returns 0 if the pattern was valid, otherwise an error string.
5689 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
5690 are set in BUFP on entry.
5692 We call regex_compile to do the actual compilation. */
5695 re_compile_pattern (pattern
, length
, bufp
)
5696 const char *pattern
;
5698 struct re_pattern_buffer
*bufp
;
5702 /* GNU code is written to assume at least RE_NREGS registers will be set
5703 (and at least one extra will be -1). */
5704 bufp
->regs_allocated
= REGS_UNALLOCATED
;
5706 /* And GNU code determines whether or not to get register information
5707 by passing null for the REGS argument to re_match, etc., not by
5711 ret
= regex_compile ((re_char
*) pattern
, length
, re_syntax_options
, bufp
);
5715 return gettext (re_error_msgid
[(int) ret
]);
5717 WEAK_ALIAS (__re_compile_pattern
, re_compile_pattern
)
5719 /* Entry points compatible with 4.2 BSD regex library. We don't define
5720 them unless specifically requested. */
5722 #if defined _REGEX_RE_COMP || defined _LIBC
5724 /* BSD has one and only one pattern buffer. */
5725 static struct re_pattern_buffer re_comp_buf
;
5729 /* Make these definitions weak in libc, so POSIX programs can redefine
5730 these names if they don't use our functions, and still use
5731 regcomp/regexec below without link errors. */
5741 if (!re_comp_buf
.buffer
)
5742 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
5743 return (char *) gettext ("No previous regular expression");
5747 if (!re_comp_buf
.buffer
)
5749 re_comp_buf
.buffer
= (unsigned char *) malloc (200);
5750 if (re_comp_buf
.buffer
== NULL
)
5751 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
5752 return (char *) gettext (re_error_msgid
[(int) REG_ESPACE
]);
5753 re_comp_buf
.allocated
= 200;
5755 re_comp_buf
.fastmap
= (char *) malloc (1 << BYTEWIDTH
);
5756 if (re_comp_buf
.fastmap
== NULL
)
5757 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
5758 return (char *) gettext (re_error_msgid
[(int) REG_ESPACE
]);
5761 /* Since `re_exec' always passes NULL for the `regs' argument, we
5762 don't need to initialize the pattern buffer fields which affect it. */
5764 ret
= regex_compile (s
, strlen (s
), re_syntax_options
, &re_comp_buf
);
5769 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
5770 return (char *) gettext (re_error_msgid
[(int) ret
]);
5781 const int len
= strlen (s
);
5783 0 <= re_search (&re_comp_buf
, s
, len
, 0, len
, (struct re_registers
*) 0);
5785 #endif /* _REGEX_RE_COMP */
5787 /* POSIX.2 functions. Don't define these for Emacs. */
5791 /* regcomp takes a regular expression as a string and compiles it.
5793 PREG is a regex_t *. We do not expect any fields to be initialized,
5794 since POSIX says we shouldn't. Thus, we set
5796 `buffer' to the compiled pattern;
5797 `used' to the length of the compiled pattern;
5798 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
5799 REG_EXTENDED bit in CFLAGS is set; otherwise, to
5800 RE_SYNTAX_POSIX_BASIC;
5801 `fastmap' to an allocated space for the fastmap;
5802 `fastmap_accurate' to zero;
5803 `re_nsub' to the number of subexpressions in PATTERN.
5805 PATTERN is the address of the pattern string.
5807 CFLAGS is a series of bits which affect compilation.
5809 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
5810 use POSIX basic syntax.
5812 If REG_NEWLINE is set, then . and [^...] don't match newline.
5813 Also, regexec will try a match beginning after every newline.
5815 If REG_ICASE is set, then we considers upper- and lowercase
5816 versions of letters to be equivalent when matching.
5818 If REG_NOSUB is set, then when PREG is passed to regexec, that
5819 routine will report only success or failure, and nothing about the
5822 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
5823 the return codes and their meanings.) */
5826 regcomp (preg
, pattern
, cflags
)
5828 const char *pattern
;
5833 = (cflags
& REG_EXTENDED
) ?
5834 RE_SYNTAX_POSIX_EXTENDED
: RE_SYNTAX_POSIX_BASIC
;
5836 /* regex_compile will allocate the space for the compiled pattern. */
5838 preg
->allocated
= 0;
5841 /* Try to allocate space for the fastmap. */
5842 preg
->fastmap
= (char *) malloc (1 << BYTEWIDTH
);
5844 if (cflags
& REG_ICASE
)
5849 = (RE_TRANSLATE_TYPE
) malloc (CHAR_SET_SIZE
5850 * sizeof (*(RE_TRANSLATE_TYPE
)0));
5851 if (preg
->translate
== NULL
)
5852 return (int) REG_ESPACE
;
5854 /* Map uppercase characters to corresponding lowercase ones. */
5855 for (i
= 0; i
< CHAR_SET_SIZE
; i
++)
5856 preg
->translate
[i
] = ISUPPER (i
) ? TOLOWER (i
) : i
;
5859 preg
->translate
= NULL
;
5861 /* If REG_NEWLINE is set, newlines are treated differently. */
5862 if (cflags
& REG_NEWLINE
)
5863 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
5864 syntax
&= ~RE_DOT_NEWLINE
;
5865 syntax
|= RE_HAT_LISTS_NOT_NEWLINE
;
5868 syntax
|= RE_NO_NEWLINE_ANCHOR
;
5870 preg
->no_sub
= !!(cflags
& REG_NOSUB
);
5872 /* POSIX says a null character in the pattern terminates it, so we
5873 can use strlen here in compiling the pattern. */
5874 ret
= regex_compile ((re_char
*) pattern
, strlen (pattern
), syntax
, preg
);
5876 /* POSIX doesn't distinguish between an unmatched open-group and an
5877 unmatched close-group: both are REG_EPAREN. */
5878 if (ret
== REG_ERPAREN
)
5881 if (ret
== REG_NOERROR
&& preg
->fastmap
)
5882 { /* Compute the fastmap now, since regexec cannot modify the pattern
5884 re_compile_fastmap (preg
);
5885 if (preg
->can_be_null
)
5886 { /* The fastmap can't be used anyway. */
5887 free (preg
->fastmap
);
5888 preg
->fastmap
= NULL
;
5893 WEAK_ALIAS (__regcomp
, regcomp
)
5896 /* regexec searches for a given pattern, specified by PREG, in the
5899 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
5900 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
5901 least NMATCH elements, and we set them to the offsets of the
5902 corresponding matched substrings.
5904 EFLAGS specifies `execution flags' which affect matching: if
5905 REG_NOTBOL is set, then ^ does not match at the beginning of the
5906 string; if REG_NOTEOL is set, then $ does not match at the end.
5908 We return 0 if we find a match and REG_NOMATCH if not. */
5911 regexec (preg
, string
, nmatch
, pmatch
, eflags
)
5912 const regex_t
*preg
;
5915 regmatch_t pmatch
[];
5919 struct re_registers regs
;
5920 regex_t private_preg
;
5921 int len
= strlen (string
);
5922 boolean want_reg_info
= !preg
->no_sub
&& nmatch
> 0 && pmatch
;
5924 private_preg
= *preg
;
5926 private_preg
.not_bol
= !!(eflags
& REG_NOTBOL
);
5927 private_preg
.not_eol
= !!(eflags
& REG_NOTEOL
);
5929 /* The user has told us exactly how many registers to return
5930 information about, via `nmatch'. We have to pass that on to the
5931 matching routines. */
5932 private_preg
.regs_allocated
= REGS_FIXED
;
5936 regs
.num_regs
= nmatch
;
5937 regs
.start
= TALLOC (nmatch
* 2, regoff_t
);
5938 if (regs
.start
== NULL
)
5939 return (int) REG_NOMATCH
;
5940 regs
.end
= regs
.start
+ nmatch
;
5943 /* Instead of using not_eol to implement REG_NOTEOL, we could simply
5944 pass (&private_preg, string, len + 1, 0, len, ...) pretending the string
5945 was a little bit longer but still only matching the real part.
5946 This works because the `endline' will check for a '\n' and will find a
5947 '\0', correctly deciding that this is not the end of a line.
5948 But it doesn't work out so nicely for REG_NOTBOL, since we don't have
5949 a convenient '\0' there. For all we know, the string could be preceded
5950 by '\n' which would throw things off. */
5952 /* Perform the searching operation. */
5953 ret
= re_search (&private_preg
, string
, len
,
5954 /* start: */ 0, /* range: */ len
,
5955 want_reg_info
? ®s
: (struct re_registers
*) 0);
5957 /* Copy the register information to the POSIX structure. */
5964 for (r
= 0; r
< nmatch
; r
++)
5966 pmatch
[r
].rm_so
= regs
.start
[r
];
5967 pmatch
[r
].rm_eo
= regs
.end
[r
];
5971 /* If we needed the temporary register info, free the space now. */
5975 /* We want zero return to mean success, unlike `re_search'. */
5976 return ret
>= 0 ? (int) REG_NOERROR
: (int) REG_NOMATCH
;
5978 WEAK_ALIAS (__regexec
, regexec
)
5981 /* Returns a message corresponding to an error code, ERRCODE, returned
5982 from either regcomp or regexec. We don't use PREG here. */
5985 regerror (errcode
, preg
, errbuf
, errbuf_size
)
5987 const regex_t
*preg
;
5995 || errcode
>= (sizeof (re_error_msgid
) / sizeof (re_error_msgid
[0])))
5996 /* Only error codes returned by the rest of the code should be passed
5997 to this routine. If we are given anything else, or if other regex
5998 code generates an invalid error code, then the program has a bug.
5999 Dump core so we can fix it. */
6002 msg
= gettext (re_error_msgid
[errcode
]);
6004 msg_size
= strlen (msg
) + 1; /* Includes the null. */
6006 if (errbuf_size
!= 0)
6008 if (msg_size
> errbuf_size
)
6010 strncpy (errbuf
, msg
, errbuf_size
- 1);
6011 errbuf
[errbuf_size
- 1] = 0;
6014 strcpy (errbuf
, msg
);
6019 WEAK_ALIAS (__regerror
, regerror
)
6022 /* Free dynamically allocated space used by PREG. */
6028 if (preg
->buffer
!= NULL
)
6029 free (preg
->buffer
);
6030 preg
->buffer
= NULL
;
6032 preg
->allocated
= 0;
6035 if (preg
->fastmap
!= NULL
)
6036 free (preg
->fastmap
);
6037 preg
->fastmap
= NULL
;
6038 preg
->fastmap_accurate
= 0;
6040 if (preg
->translate
!= NULL
)
6041 free (preg
->translate
);
6042 preg
->translate
= NULL
;
6044 WEAK_ALIAS (__regfree
, regfree
)
6046 #endif /* not emacs */