1 /* Extended regular expression matching and search library, version
2 0.12. (Implements POSIX draft P1003.2/D11.2, except for some of the
3 internationalization features.)
5 Copyright (C) 1993,94,95,96,97,98,99,2000 Free Software Foundation, Inc.
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
23 - structure the opcode space into opcode+flag.
24 - merge with glibc's regex.[ch].
25 - replace succeed_n + jump_n with a combined operation so that the counter
26 can simply be decremented when popping the failure_point without having
27 to stack up failure_count entries.
28 - get rid of `newline_anchor'.
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 /* This is for other GNU distributions with internationalized messages. */
51 #if HAVE_LIBINTL_H || defined _LIBC
54 # define gettext(msgid) (msgid)
58 /* This define is so xgettext can find the internationalizable
60 # define gettext_noop(String) String
63 /* The `emacs' switch turns on certain matching commands
64 that make sense only in Emacs. */
70 /* Make syntax table lookup grant data in gl_state. */
71 # define SYNTAX_ENTRY_VIA_PROPERTY
75 # include "category.h"
77 # define malloc xmalloc
78 # define realloc xrealloc
81 /* Converts the pointer to the char to BEG-based offset from the start. */
82 # define PTR_TO_OFFSET(d) POS_AS_IN_BUFFER (POINTER_TO_OFFSET (d))
83 # define POS_AS_IN_BUFFER(p) ((p) + (NILP (re_match_object) || BUFFERP (re_match_object)))
85 # define RE_MULTIBYTE_P(bufp) ((bufp)->multibyte)
86 # define RE_STRING_CHAR(p, s) \
87 (multibyte ? (STRING_CHAR (p, s)) : (*(p)))
88 # define RE_STRING_CHAR_AND_LENGTH(p, s, len) \
89 (multibyte ? (STRING_CHAR_AND_LENGTH (p, s, len)) : ((len) = 1, *(p)))
91 /* Set C a (possibly multibyte) character before P. P points into a
92 string which is the virtual concatenation of STR1 (which ends at
93 END1) or STR2 (which ends at END2). */
94 # define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
98 re_char *dtemp = (p) == (str2) ? (end1) : (p); \
99 re_char *dlimit = ((p) > (str2) && (p) <= (end2)) ? (str2) : (str1); \
100 while (dtemp-- > dlimit && !CHAR_HEAD_P (*dtemp)); \
101 c = STRING_CHAR (dtemp, (p) - dtemp); \
104 (c = ((p) == (str2) ? (end1) : (p))[-1]); \
108 #else /* not emacs */
110 /* If we are not linking with Emacs proper,
111 we can't use the relocating allocator
112 even if config.h says that we can. */
115 # if defined STDC_HEADERS || defined _LIBC
122 /* When used in Emacs's lib-src, we need to get bzero and bcopy somehow.
123 If nothing else has been done, use the method below. */
124 # ifdef INHIBIT_STRING_HEADER
125 # if !(defined HAVE_BZERO && defined HAVE_BCOPY)
126 # if !defined bzero && !defined bcopy
127 # undef INHIBIT_STRING_HEADER
132 /* This is the normal way of making sure we have memcpy, memcmp and bzero.
133 This is used in most programs--a few other programs avoid this
134 by defining INHIBIT_STRING_HEADER. */
135 # ifndef INHIBIT_STRING_HEADER
136 # if defined HAVE_STRING_H || defined STDC_HEADERS || defined _LIBC
140 # define bzero(s, n) (memset (s, '\0', n), (s))
142 # define bzero(s, n) __bzero (s, n)
146 # include <strings.h>
148 # define memcmp(s1, s2, n) bcmp (s1, s2, n)
151 # define memcpy(d, s, n) (bcopy (s, d, n), (d))
156 /* Define the syntax stuff for \<, \>, etc. */
158 /* Sword must be nonzero for the wordchar pattern commands in re_match_2. */
159 enum syntaxcode
{ Swhitespace
= 0, Sword
= 1 };
161 # ifdef SWITCH_ENUM_BUG
162 # define SWITCH_ENUM_CAST(x) ((int)(x))
164 # define SWITCH_ENUM_CAST(x) (x)
167 /* Dummy macros for non-Emacs environments. */
168 # define BASE_LEADING_CODE_P(c) (0)
169 # define CHAR_CHARSET(c) 0
170 # define CHARSET_LEADING_CODE_BASE(c) 0
171 # define MAX_MULTIBYTE_LENGTH 1
172 # define RE_MULTIBYTE_P(x) 0
173 # define WORD_BOUNDARY_P(c1, c2) (0)
174 # define CHAR_HEAD_P(p) (1)
175 # define SINGLE_BYTE_CHAR_P(c) (1)
176 # define SAME_CHARSET_P(c1, c2) (1)
177 # define MULTIBYTE_FORM_LENGTH(p, s) (1)
178 # define STRING_CHAR(p, s) (*(p))
179 # define RE_STRING_CHAR STRING_CHAR
180 # define CHAR_STRING(c, s) (*(s) = (c), 1)
181 # define STRING_CHAR_AND_LENGTH(p, s, actual_len) ((actual_len) = 1, *(p))
182 # define RE_STRING_CHAR_AND_LENGTH STRING_CHAR_AND_LENGTH
183 # define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
184 (c = ((p) == (str2) ? *((end1) - 1) : *((p) - 1)))
185 # define MAKE_CHAR(charset, c1, c2) (c1)
186 #endif /* not emacs */
189 # define RE_TRANSLATE(TBL, C) ((unsigned char)(TBL)[C])
190 # define RE_TRANSLATE_P(TBL) (TBL)
193 /* Get the interface, including the syntax bits. */
196 /* isalpha etc. are used for the character classes. */
201 /* 1 if C is an ASCII character. */
202 # define IS_REAL_ASCII(c) ((c) < 0200)
204 /* 1 if C is a unibyte character. */
205 # define ISUNIBYTE(c) (SINGLE_BYTE_CHAR_P ((c)))
207 /* The Emacs definitions should not be directly affected by locales. */
209 /* In Emacs, these are only used for single-byte characters. */
210 # define ISDIGIT(c) ((c) >= '0' && (c) <= '9')
211 # define ISCNTRL(c) ((c) < ' ')
212 # define ISXDIGIT(c) (((c) >= '0' && (c) <= '9') \
213 || ((c) >= 'a' && (c) <= 'f') \
214 || ((c) >= 'A' && (c) <= 'F'))
216 /* This is only used for single-byte characters. */
217 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
219 /* The rest must handle multibyte characters. */
221 # define ISGRAPH(c) (SINGLE_BYTE_CHAR_P (c) \
222 ? (c) > ' ' && !((c) >= 0177 && (c) <= 0237) \
225 # define ISPRINT(c) (SINGLE_BYTE_CHAR_P (c) \
226 ? (c) >= ' ' && !((c) >= 0177 && (c) <= 0237) \
229 # define ISALNUM(c) (IS_REAL_ASCII (c) \
230 ? (((c) >= 'a' && (c) <= 'z') \
231 || ((c) >= 'A' && (c) <= 'Z') \
232 || ((c) >= '0' && (c) <= '9')) \
233 : SYNTAX (c) == Sword)
235 # define ISALPHA(c) (IS_REAL_ASCII (c) \
236 ? (((c) >= 'a' && (c) <= 'z') \
237 || ((c) >= 'A' && (c) <= 'Z')) \
238 : SYNTAX (c) == Sword)
240 # define ISLOWER(c) (LOWERCASEP (c))
242 # define ISPUNCT(c) (IS_REAL_ASCII (c) \
243 ? ((c) > ' ' && (c) < 0177 \
244 && !(((c) >= 'a' && (c) <= 'z') \
245 || ((c) >= 'A' && (c) <= 'Z') \
246 || ((c) >= '0' && (c) <= '9'))) \
247 : SYNTAX (c) != Sword)
249 # define ISSPACE(c) (SYNTAX (c) == Swhitespace)
251 # define ISUPPER(c) (UPPERCASEP (c))
253 # define ISWORD(c) (SYNTAX (c) == Sword)
255 #else /* not emacs */
257 /* Jim Meyering writes:
259 "... Some ctype macros are valid only for character codes that
260 isascii says are ASCII (SGI's IRIX-4.0.5 is one such system --when
261 using /bin/cc or gcc but without giving an ansi option). So, all
262 ctype uses should be through macros like ISPRINT... If
263 STDC_HEADERS is defined, then autoconf has verified that the ctype
264 macros don't need to be guarded with references to isascii. ...
265 Defining isascii to 1 should let any compiler worth its salt
266 eliminate the && through constant folding."
267 Solaris defines some of these symbols so we must undefine them first. */
270 # if defined STDC_HEADERS || (!defined isascii && !defined HAVE_ISASCII)
271 # define ISASCII(c) 1
273 # define ISASCII(c) isascii(c)
276 /* 1 if C is an ASCII character. */
277 # define IS_REAL_ASCII(c) ((c) < 0200)
279 /* This distinction is not meaningful, except in Emacs. */
280 # define ISUNIBYTE(c) 1
283 # define ISBLANK(c) (ISASCII (c) && isblank (c))
285 # define ISBLANK(c) ((c) == ' ' || (c) == '\t')
288 # define ISGRAPH(c) (ISASCII (c) && isgraph (c))
290 # define ISGRAPH(c) (ISASCII (c) && isprint (c) && !isspace (c))
294 # define ISPRINT(c) (ISASCII (c) && isprint (c))
295 # define ISDIGIT(c) (ISASCII (c) && isdigit (c))
296 # define ISALNUM(c) (ISASCII (c) && isalnum (c))
297 # define ISALPHA(c) (ISASCII (c) && isalpha (c))
298 # define ISCNTRL(c) (ISASCII (c) && iscntrl (c))
299 # define ISLOWER(c) (ISASCII (c) && islower (c))
300 # define ISPUNCT(c) (ISASCII (c) && ispunct (c))
301 # define ISSPACE(c) (ISASCII (c) && isspace (c))
302 # define ISUPPER(c) (ISASCII (c) && isupper (c))
303 # define ISXDIGIT(c) (ISASCII (c) && isxdigit (c))
305 # define ISWORD(c) ISALPHA(c)
308 # define TOLOWER(c) _tolower(c)
310 # define TOLOWER(c) tolower(c)
313 /* How many characters in the character set. */
314 # define CHAR_SET_SIZE 256
318 extern char *re_syntax_table
;
320 # else /* not SYNTAX_TABLE */
322 static char re_syntax_table
[CHAR_SET_SIZE
];
333 bzero (re_syntax_table
, sizeof re_syntax_table
);
335 for (c
= 0; c
< CHAR_SET_SIZE
; ++c
)
337 re_syntax_table
[c
] = Sword
;
339 re_syntax_table
['_'] = Sword
;
344 # endif /* not SYNTAX_TABLE */
346 # define SYNTAX(c) re_syntax_table[(c)]
348 #endif /* not emacs */
351 # define NULL (void *)0
354 /* We remove any previous definition of `SIGN_EXTEND_CHAR',
355 since ours (we hope) works properly with all combinations of
356 machines, compilers, `char' and `unsigned char' argument types.
357 (Per Bothner suggested the basic approach.) */
358 #undef SIGN_EXTEND_CHAR
360 # define SIGN_EXTEND_CHAR(c) ((signed char) (c))
361 #else /* not __STDC__ */
362 /* As in Harbison and Steele. */
363 # define SIGN_EXTEND_CHAR(c) ((((unsigned char) (c)) ^ 128) - 128)
366 /* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we
367 use `alloca' instead of `malloc'. This is because using malloc in
368 re_search* or re_match* could cause memory leaks when C-g is used in
369 Emacs; also, malloc is slower and causes storage fragmentation. On
370 the other hand, malloc is more portable, and easier to debug.
372 Because we sometimes use alloca, some routines have to be macros,
373 not functions -- `alloca'-allocated space disappears at the end of the
374 function it is called in. */
378 # define REGEX_ALLOCATE malloc
379 # define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
380 # define REGEX_FREE free
382 #else /* not REGEX_MALLOC */
384 /* Emacs already defines alloca, sometimes. */
387 /* Make alloca work the best possible way. */
389 # define alloca __builtin_alloca
390 # else /* not __GNUC__ */
393 # endif /* HAVE_ALLOCA_H */
394 # endif /* not __GNUC__ */
396 # endif /* not alloca */
398 # define REGEX_ALLOCATE alloca
400 /* Assumes a `char *destination' variable. */
401 # define REGEX_REALLOCATE(source, osize, nsize) \
402 (destination = (char *) alloca (nsize), \
403 memcpy (destination, source, osize))
405 /* No need to do anything to free, after alloca. */
406 # define REGEX_FREE(arg) ((void)0) /* Do nothing! But inhibit gcc warning. */
408 #endif /* not REGEX_MALLOC */
410 /* Define how to allocate the failure stack. */
412 #if defined REL_ALLOC && defined REGEX_MALLOC
414 # define REGEX_ALLOCATE_STACK(size) \
415 r_alloc (&failure_stack_ptr, (size))
416 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
417 r_re_alloc (&failure_stack_ptr, (nsize))
418 # define REGEX_FREE_STACK(ptr) \
419 r_alloc_free (&failure_stack_ptr)
421 #else /* not using relocating allocator */
425 # define REGEX_ALLOCATE_STACK malloc
426 # define REGEX_REALLOCATE_STACK(source, osize, nsize) realloc (source, nsize)
427 # define REGEX_FREE_STACK free
429 # else /* not REGEX_MALLOC */
431 # define REGEX_ALLOCATE_STACK alloca
433 # define REGEX_REALLOCATE_STACK(source, osize, nsize) \
434 REGEX_REALLOCATE (source, osize, nsize)
435 /* No need to explicitly free anything. */
436 # define REGEX_FREE_STACK(arg) ((void)0)
438 # endif /* not REGEX_MALLOC */
439 #endif /* not using relocating allocator */
442 /* True if `size1' is non-NULL and PTR is pointing anywhere inside
443 `string1' or just past its end. This works if PTR is NULL, which is
445 #define FIRST_STRING_P(ptr) \
446 (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
448 /* (Re)Allocate N items of type T using malloc, or fail. */
449 #define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
450 #define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
451 #define RETALLOC_IF(addr, n, t) \
452 if (addr) RETALLOC((addr), (n), t); else (addr) = TALLOC ((n), t)
453 #define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
455 #define BYTEWIDTH 8 /* In bits. */
457 #define STREQ(s1, s2) ((strcmp (s1, s2) == 0))
461 #define MAX(a, b) ((a) > (b) ? (a) : (b))
462 #define MIN(a, b) ((a) < (b) ? (a) : (b))
464 /* Type of source-pattern and string chars. */
465 typedef const unsigned char re_char
;
467 typedef char boolean
;
471 static int re_match_2_internal
_RE_ARGS ((struct re_pattern_buffer
*bufp
,
472 re_char
*string1
, int size1
,
473 re_char
*string2
, int size2
,
475 struct re_registers
*regs
,
478 /* These are the command codes that appear in compiled regular
479 expressions. Some opcodes are followed by argument bytes. A
480 command code can specify any interpretation whatsoever for its
481 arguments. Zero bytes may appear in the compiled regular expression. */
487 /* Succeed right away--no more backtracking. */
490 /* Followed by one byte giving n, then by n literal bytes. */
493 /* Matches any (more or less) character. */
496 /* Matches any one char belonging to specified set. First
497 following byte is number of bitmap bytes. Then come bytes
498 for a bitmap saying which chars are in. Bits in each byte
499 are ordered low-bit-first. A character is in the set if its
500 bit is 1. A character too large to have a bit in the map is
501 automatically not in the set.
503 If the length byte has the 0x80 bit set, then that stuff
504 is followed by a range table:
505 2 bytes of flags for character sets (low 8 bits, high 8 bits)
506 See RANGE_TABLE_WORK_BITS below.
507 2 bytes, the number of pairs that follow
508 pairs, each 2 multibyte characters,
509 each multibyte character represented as 3 bytes. */
512 /* Same parameters as charset, but match any character that is
513 not one of those specified. */
516 /* Start remembering the text that is matched, for storing in a
517 register. Followed by one byte with the register number, in
518 the range 0 to one less than the pattern buffer's re_nsub
522 /* Stop remembering the text that is matched and store it in a
523 memory register. Followed by one byte with the register
524 number, in the range 0 to one less than `re_nsub' in the
528 /* Match a duplicate of something remembered. Followed by one
529 byte containing the register number. */
532 /* Fail unless at beginning of line. */
535 /* Fail unless at end of line. */
538 /* Succeeds if at beginning of buffer (if emacs) or at beginning
539 of string to be matched (if not). */
542 /* Analogously, for end of buffer/string. */
545 /* Followed by two byte relative address to which to jump. */
548 /* Followed by two-byte relative address of place to resume at
549 in case of failure. */
552 /* Like on_failure_jump, but pushes a placeholder instead of the
553 current string position when executed. */
554 on_failure_keep_string_jump
,
556 /* Just like `on_failure_jump', except that it checks that we
557 don't get stuck in an infinite loop (matching an empty string
559 on_failure_jump_loop
,
561 /* Just like `on_failure_jump_loop', except that it checks for
562 a different kind of loop (the kind that shows up with non-greedy
563 operators). This operation has to be immediately preceded
565 on_failure_jump_nastyloop
,
567 /* A smart `on_failure_jump' used for greedy * and + operators.
568 It analyses the loop before which it is put and if the
569 loop does not require backtracking, it changes itself to
570 `on_failure_keep_string_jump' and short-circuits the loop,
571 else it just defaults to changing itself into `on_failure_jump'.
572 It assumes that it is pointing to just past a `jump'. */
573 on_failure_jump_smart
,
575 /* Followed by two-byte relative address and two-byte number n.
576 After matching N times, jump to the address upon failure.
577 Does not work if N starts at 0: use on_failure_jump_loop
581 /* Followed by two-byte relative address, and two-byte number n.
582 Jump to the address N times, then fail. */
585 /* Set the following two-byte relative address to the
586 subsequent two-byte number. The address *includes* the two
590 wordbeg
, /* Succeeds if at word beginning. */
591 wordend
, /* Succeeds if at word end. */
593 wordbound
, /* Succeeds if at a word boundary. */
594 notwordbound
, /* Succeeds if not at a word boundary. */
596 /* Matches any character whose syntax is specified. Followed by
597 a byte which contains a syntax code, e.g., Sword. */
600 /* Matches any character whose syntax is not that specified. */
604 ,before_dot
, /* Succeeds if before point. */
605 at_dot
, /* Succeeds if at point. */
606 after_dot
, /* Succeeds if after point. */
608 /* Matches any character whose category-set contains the specified
609 category. The operator is followed by a byte which contains a
610 category code (mnemonic ASCII character). */
613 /* Matches any character whose category-set does not contain the
614 specified category. The operator is followed by a byte which
615 contains the category code (mnemonic ASCII character). */
620 /* Common operations on the compiled pattern. */
622 /* Store NUMBER in two contiguous bytes starting at DESTINATION. */
624 #define STORE_NUMBER(destination, number) \
626 (destination)[0] = (number) & 0377; \
627 (destination)[1] = (number) >> 8; \
630 /* Same as STORE_NUMBER, except increment DESTINATION to
631 the byte after where the number is stored. Therefore, DESTINATION
632 must be an lvalue. */
634 #define STORE_NUMBER_AND_INCR(destination, number) \
636 STORE_NUMBER (destination, number); \
637 (destination) += 2; \
640 /* Put into DESTINATION a number stored in two contiguous bytes starting
643 #define EXTRACT_NUMBER(destination, source) \
645 (destination) = *(source) & 0377; \
646 (destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8; \
650 static void extract_number
_RE_ARGS ((int *dest
, re_char
*source
));
652 extract_number (dest
, source
)
654 unsigned char *source
;
656 int temp
= SIGN_EXTEND_CHAR (*(source
+ 1));
657 *dest
= *source
& 0377;
661 # ifndef EXTRACT_MACROS /* To debug the macros. */
662 # undef EXTRACT_NUMBER
663 # define EXTRACT_NUMBER(dest, src) extract_number (&dest, src)
664 # endif /* not EXTRACT_MACROS */
668 /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
669 SOURCE must be an lvalue. */
671 #define EXTRACT_NUMBER_AND_INCR(destination, source) \
673 EXTRACT_NUMBER (destination, source); \
678 static void extract_number_and_incr
_RE_ARGS ((int *destination
,
681 extract_number_and_incr (destination
, source
)
683 unsigned char **source
;
685 extract_number (destination
, *source
);
689 # ifndef EXTRACT_MACROS
690 # undef EXTRACT_NUMBER_AND_INCR
691 # define EXTRACT_NUMBER_AND_INCR(dest, src) \
692 extract_number_and_incr (&dest, &src)
693 # endif /* not EXTRACT_MACROS */
697 /* Store a multibyte character in three contiguous bytes starting
698 DESTINATION, and increment DESTINATION to the byte after where the
699 character is stored. Therefore, DESTINATION must be an lvalue. */
701 #define STORE_CHARACTER_AND_INCR(destination, character) \
703 (destination)[0] = (character) & 0377; \
704 (destination)[1] = ((character) >> 8) & 0377; \
705 (destination)[2] = (character) >> 16; \
706 (destination) += 3; \
709 /* Put into DESTINATION a character stored in three contiguous bytes
710 starting at SOURCE. */
712 #define EXTRACT_CHARACTER(destination, source) \
714 (destination) = ((source)[0] \
715 | ((source)[1] << 8) \
716 | ((source)[2] << 16)); \
720 /* Macros for charset. */
722 /* Size of bitmap of charset P in bytes. P is a start of charset,
723 i.e. *P is (re_opcode_t) charset or (re_opcode_t) charset_not. */
724 #define CHARSET_BITMAP_SIZE(p) ((p)[1] & 0x7F)
726 /* Nonzero if charset P has range table. */
727 #define CHARSET_RANGE_TABLE_EXISTS_P(p) ((p)[1] & 0x80)
729 /* Return the address of range table of charset P. But not the start
730 of table itself, but the before where the number of ranges is
731 stored. `2 +' means to skip re_opcode_t and size of bitmap,
732 and the 2 bytes of flags at the start of the range table. */
733 #define CHARSET_RANGE_TABLE(p) (&(p)[4 + CHARSET_BITMAP_SIZE (p)])
735 /* Extract the bit flags that start a range table. */
736 #define CHARSET_RANGE_TABLE_BITS(p) \
737 ((p)[2 + CHARSET_BITMAP_SIZE (p)] \
738 + (p)[3 + CHARSET_BITMAP_SIZE (p)] * 0x100)
740 /* Test if C is listed in the bitmap of charset P. */
741 #define CHARSET_LOOKUP_BITMAP(p, c) \
742 ((c) < CHARSET_BITMAP_SIZE (p) * BYTEWIDTH \
743 && (p)[2 + (c) / BYTEWIDTH] & (1 << ((c) % BYTEWIDTH)))
745 /* Return the address of end of RANGE_TABLE. COUNT is number of
746 ranges (which is a pair of (start, end)) in the RANGE_TABLE. `* 2'
747 is start of range and end of range. `* 3' is size of each start
749 #define CHARSET_RANGE_TABLE_END(range_table, count) \
750 ((range_table) + (count) * 2 * 3)
752 /* Test if C is in RANGE_TABLE. A flag NOT is negated if C is in.
753 COUNT is number of ranges in RANGE_TABLE. */
754 #define CHARSET_LOOKUP_RANGE_TABLE_RAW(not, c, range_table, count) \
757 int range_start, range_end; \
759 unsigned char *range_table_end \
760 = CHARSET_RANGE_TABLE_END ((range_table), (count)); \
762 for (p = (range_table); p < range_table_end; p += 2 * 3) \
764 EXTRACT_CHARACTER (range_start, p); \
765 EXTRACT_CHARACTER (range_end, p + 3); \
767 if (range_start <= (c) && (c) <= range_end) \
776 /* Test if C is in range table of CHARSET. The flag NOT is negated if
777 C is listed in it. */
778 #define CHARSET_LOOKUP_RANGE_TABLE(not, c, charset) \
781 /* Number of ranges in range table. */ \
783 unsigned char *range_table = CHARSET_RANGE_TABLE (charset); \
785 EXTRACT_NUMBER_AND_INCR (count, range_table); \
786 CHARSET_LOOKUP_RANGE_TABLE_RAW ((not), (c), range_table, count); \
790 /* If DEBUG is defined, Regex prints many voluminous messages about what
791 it is doing (if the variable `debug' is nonzero). If linked with the
792 main program in `iregex.c', you can enter patterns and strings
793 interactively. And if linked with the main program in `main.c' and
794 the other test files, you can run the already-written tests. */
798 /* We use standard I/O for debugging. */
801 /* It is useful to test things that ``must'' be true when debugging. */
804 static int debug
= -100000;
806 # define DEBUG_STATEMENT(e) e
807 # define DEBUG_PRINT1(x) if (debug > 0) printf (x)
808 # define DEBUG_PRINT2(x1, x2) if (debug > 0) printf (x1, x2)
809 # define DEBUG_PRINT3(x1, x2, x3) if (debug > 0) printf (x1, x2, x3)
810 # define DEBUG_PRINT4(x1, x2, x3, x4) if (debug > 0) printf (x1, x2, x3, x4)
811 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
812 if (debug > 0) print_partial_compiled_pattern (s, e)
813 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
814 if (debug > 0) print_double_string (w, s1, sz1, s2, sz2)
817 /* Print the fastmap in human-readable form. */
820 print_fastmap (fastmap
)
823 unsigned was_a_range
= 0;
826 while (i
< (1 << BYTEWIDTH
))
832 while (i
< (1 << BYTEWIDTH
) && fastmap
[i
])
848 /* Print a compiled pattern string in human-readable form, starting at
849 the START pointer into it and ending just before the pointer END. */
852 print_partial_compiled_pattern (start
, end
)
853 unsigned char *start
;
857 unsigned char *p
= start
;
858 unsigned char *pend
= end
;
866 /* Loop over pattern commands. */
869 printf ("%d:\t", p
- start
);
871 switch ((re_opcode_t
) *p
++)
883 printf ("/exactn/%d", mcnt
);
893 printf ("/start_memory/%d", *p
++);
897 printf ("/stop_memory/%d", *p
++);
901 printf ("/duplicate/%d", *p
++);
911 register int c
, last
= -100;
912 register int in_range
= 0;
913 int length
= CHARSET_BITMAP_SIZE (p
- 1);
914 int has_range_table
= CHARSET_RANGE_TABLE_EXISTS_P (p
- 1);
916 printf ("/charset [%s",
917 (re_opcode_t
) *(p
- 1) == charset_not
? "^" : "");
919 assert (p
+ *p
< pend
);
921 for (c
= 0; c
< 256; c
++)
923 && (p
[1 + (c
/8)] & (1 << (c
% 8))))
925 /* Are we starting a range? */
926 if (last
+ 1 == c
&& ! in_range
)
931 /* Have we broken a range? */
932 else if (last
+ 1 != c
&& in_range
)
954 printf ("has-range-table");
956 /* ??? Should print the range table; for now, just skip it. */
957 p
+= 2; /* skip range table bits */
958 EXTRACT_NUMBER_AND_INCR (count
, p
);
959 p
= CHARSET_RANGE_TABLE_END (p
, count
);
972 case on_failure_jump
:
973 extract_number_and_incr (&mcnt
, &p
);
974 printf ("/on_failure_jump to %d", p
+ mcnt
- start
);
977 case on_failure_keep_string_jump
:
978 extract_number_and_incr (&mcnt
, &p
);
979 printf ("/on_failure_keep_string_jump to %d", p
+ mcnt
- start
);
982 case on_failure_jump_nastyloop
:
983 extract_number_and_incr (&mcnt
, &p
);
984 printf ("/on_failure_jump_nastyloop to %d", p
+ mcnt
- start
);
987 case on_failure_jump_loop
:
988 extract_number_and_incr (&mcnt
, &p
);
989 printf ("/on_failure_jump_loop to %d", p
+ mcnt
- start
);
992 case on_failure_jump_smart
:
993 extract_number_and_incr (&mcnt
, &p
);
994 printf ("/on_failure_jump_smart to %d", p
+ mcnt
- start
);
998 extract_number_and_incr (&mcnt
, &p
);
999 printf ("/jump to %d", p
+ mcnt
- start
);
1003 extract_number_and_incr (&mcnt
, &p
);
1004 extract_number_and_incr (&mcnt2
, &p
);
1005 printf ("/succeed_n to %d, %d times", p
- 2 + mcnt
- start
, mcnt2
);
1009 extract_number_and_incr (&mcnt
, &p
);
1010 extract_number_and_incr (&mcnt2
, &p
);
1011 printf ("/jump_n to %d, %d times", p
- 2 + mcnt
- start
, mcnt2
);
1015 extract_number_and_incr (&mcnt
, &p
);
1016 extract_number_and_incr (&mcnt2
, &p
);
1017 printf ("/set_number_at location %d to %d", p
- 2 + mcnt
- start
, mcnt2
);
1021 printf ("/wordbound");
1025 printf ("/notwordbound");
1029 printf ("/wordbeg");
1033 printf ("/wordend");
1036 printf ("/syntaxspec");
1038 printf ("/%d", mcnt
);
1042 printf ("/notsyntaxspec");
1044 printf ("/%d", mcnt
);
1049 printf ("/before_dot");
1057 printf ("/after_dot");
1061 printf ("/categoryspec");
1063 printf ("/%d", mcnt
);
1066 case notcategoryspec
:
1067 printf ("/notcategoryspec");
1069 printf ("/%d", mcnt
);
1082 printf ("?%d", *(p
-1));
1088 printf ("%d:\tend of pattern.\n", p
- start
);
1093 print_compiled_pattern (bufp
)
1094 struct re_pattern_buffer
*bufp
;
1096 unsigned char *buffer
= bufp
->buffer
;
1098 print_partial_compiled_pattern (buffer
, buffer
+ bufp
->used
);
1099 printf ("%ld bytes used/%ld bytes allocated.\n",
1100 bufp
->used
, bufp
->allocated
);
1102 if (bufp
->fastmap_accurate
&& bufp
->fastmap
)
1104 printf ("fastmap: ");
1105 print_fastmap (bufp
->fastmap
);
1108 printf ("re_nsub: %d\t", bufp
->re_nsub
);
1109 printf ("regs_alloc: %d\t", bufp
->regs_allocated
);
1110 printf ("can_be_null: %d\t", bufp
->can_be_null
);
1111 printf ("newline_anchor: %d\n", bufp
->newline_anchor
);
1112 printf ("no_sub: %d\t", bufp
->no_sub
);
1113 printf ("not_bol: %d\t", bufp
->not_bol
);
1114 printf ("not_eol: %d\t", bufp
->not_eol
);
1115 printf ("syntax: %lx\n", bufp
->syntax
);
1117 /* Perhaps we should print the translate table? */
1122 print_double_string (where
, string1
, size1
, string2
, size2
)
1135 if (FIRST_STRING_P (where
))
1137 for (this_char
= where
- string1
; this_char
< size1
; this_char
++)
1138 putchar (string1
[this_char
]);
1143 for (this_char
= where
- string2
; this_char
< size2
; this_char
++)
1144 putchar (string2
[this_char
]);
1148 #else /* not DEBUG */
1153 # define DEBUG_STATEMENT(e)
1154 # define DEBUG_PRINT1(x)
1155 # define DEBUG_PRINT2(x1, x2)
1156 # define DEBUG_PRINT3(x1, x2, x3)
1157 # define DEBUG_PRINT4(x1, x2, x3, x4)
1158 # define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
1159 # define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
1161 #endif /* not DEBUG */
1163 /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
1164 also be assigned to arbitrarily: each pattern buffer stores its own
1165 syntax, so it can be changed between regex compilations. */
1166 /* This has no initializer because initialized variables in Emacs
1167 become read-only after dumping. */
1168 reg_syntax_t re_syntax_options
;
1171 /* Specify the precise syntax of regexps for compilation. This provides
1172 for compatibility for various utilities which historically have
1173 different, incompatible syntaxes.
1175 The argument SYNTAX is a bit mask comprised of the various bits
1176 defined in regex.h. We return the old syntax. */
1179 re_set_syntax (syntax
)
1180 reg_syntax_t syntax
;
1182 reg_syntax_t ret
= re_syntax_options
;
1184 re_syntax_options
= syntax
;
1188 /* This table gives an error message for each of the error codes listed
1189 in regex.h. Obviously the order here has to be same as there.
1190 POSIX doesn't require that we do anything for REG_NOERROR,
1191 but why not be nice? */
1193 static const char *re_error_msgid
[] =
1195 gettext_noop ("Success"), /* REG_NOERROR */
1196 gettext_noop ("No match"), /* REG_NOMATCH */
1197 gettext_noop ("Invalid regular expression"), /* REG_BADPAT */
1198 gettext_noop ("Invalid collation character"), /* REG_ECOLLATE */
1199 gettext_noop ("Invalid character class name"), /* REG_ECTYPE */
1200 gettext_noop ("Trailing backslash"), /* REG_EESCAPE */
1201 gettext_noop ("Invalid back reference"), /* REG_ESUBREG */
1202 gettext_noop ("Unmatched [ or [^"), /* REG_EBRACK */
1203 gettext_noop ("Unmatched ( or \\("), /* REG_EPAREN */
1204 gettext_noop ("Unmatched \\{"), /* REG_EBRACE */
1205 gettext_noop ("Invalid content of \\{\\}"), /* REG_BADBR */
1206 gettext_noop ("Invalid range end"), /* REG_ERANGE */
1207 gettext_noop ("Memory exhausted"), /* REG_ESPACE */
1208 gettext_noop ("Invalid preceding regular expression"), /* REG_BADRPT */
1209 gettext_noop ("Premature end of regular expression"), /* REG_EEND */
1210 gettext_noop ("Regular expression too big"), /* REG_ESIZE */
1211 gettext_noop ("Unmatched ) or \\)"), /* REG_ERPAREN */
1214 /* Avoiding alloca during matching, to placate r_alloc. */
1216 /* Define MATCH_MAY_ALLOCATE unless we need to make sure that the
1217 searching and matching functions should not call alloca. On some
1218 systems, alloca is implemented in terms of malloc, and if we're
1219 using the relocating allocator routines, then malloc could cause a
1220 relocation, which might (if the strings being searched are in the
1221 ralloc heap) shift the data out from underneath the regexp
1224 Here's another reason to avoid allocation: Emacs
1225 processes input from X in a signal handler; processing X input may
1226 call malloc; if input arrives while a matching routine is calling
1227 malloc, then we're scrod. But Emacs can't just block input while
1228 calling matching routines; then we don't notice interrupts when
1229 they come in. So, Emacs blocks input around all regexp calls
1230 except the matching calls, which it leaves unprotected, in the
1231 faith that they will not malloc. */
1233 /* Normally, this is fine. */
1234 #define MATCH_MAY_ALLOCATE
1236 /* When using GNU C, we are not REALLY using the C alloca, no matter
1237 what config.h may say. So don't take precautions for it. */
1242 /* The match routines may not allocate if (1) they would do it with malloc
1243 and (2) it's not safe for them to use malloc.
1244 Note that if REL_ALLOC is defined, matching would not use malloc for the
1245 failure stack, but we would still use it for the register vectors;
1246 so REL_ALLOC should not affect this. */
1247 #if (defined C_ALLOCA || defined REGEX_MALLOC) && defined emacs
1248 # undef MATCH_MAY_ALLOCATE
1252 /* Failure stack declarations and macros; both re_compile_fastmap and
1253 re_match_2 use a failure stack. These have to be macros because of
1254 REGEX_ALLOCATE_STACK. */
1257 /* Approximate number of failure points for which to initially allocate space
1258 when matching. If this number is exceeded, we allocate more
1259 space, so it is not a hard limit. */
1260 #ifndef INIT_FAILURE_ALLOC
1261 # define INIT_FAILURE_ALLOC 20
1264 /* Roughly the maximum number of failure points on the stack. Would be
1265 exactly that if always used TYPICAL_FAILURE_SIZE items each time we failed.
1266 This is a variable only so users of regex can assign to it; we never
1267 change it ourselves. */
1268 #if defined MATCH_MAY_ALLOCATE
1269 /* Note that 4400 is enough to cause a crash on Alpha OSF/1,
1270 whose default stack limit is 2mb. In order for a larger
1271 value to work reliably, you have to try to make it accord
1272 with the process stack limit. */
1273 int re_max_failures
= 40000;
1275 int re_max_failures
= 4000;
1278 union fail_stack_elt
1280 const unsigned char *pointer
;
1281 unsigned int integer
;
1284 typedef union fail_stack_elt fail_stack_elt_t
;
1288 fail_stack_elt_t
*stack
;
1290 unsigned avail
; /* Offset of next open position. */
1291 unsigned frame
; /* Offset of the cur constructed frame. */
1294 #define PATTERN_STACK_EMPTY() (fail_stack.avail == 0)
1295 #define FAIL_STACK_EMPTY() (fail_stack.frame == 0)
1296 #define FAIL_STACK_FULL() (fail_stack.avail == fail_stack.size)
1299 /* Define macros to initialize and free the failure stack.
1300 Do `return -2' if the alloc fails. */
1302 #ifdef MATCH_MAY_ALLOCATE
1303 # define INIT_FAIL_STACK() \
1305 fail_stack.stack = (fail_stack_elt_t *) \
1306 REGEX_ALLOCATE_STACK (INIT_FAILURE_ALLOC * TYPICAL_FAILURE_SIZE \
1307 * sizeof (fail_stack_elt_t)); \
1309 if (fail_stack.stack == NULL) \
1312 fail_stack.size = INIT_FAILURE_ALLOC; \
1313 fail_stack.avail = 0; \
1314 fail_stack.frame = 0; \
1317 # define RESET_FAIL_STACK() REGEX_FREE_STACK (fail_stack.stack)
1319 # define INIT_FAIL_STACK() \
1321 fail_stack.avail = 0; \
1322 fail_stack.frame = 0; \
1325 # define RESET_FAIL_STACK() ((void)0)
1329 /* Double the size of FAIL_STACK, up to a limit
1330 which allows approximately `re_max_failures' items.
1332 Return 1 if succeeds, and 0 if either ran out of memory
1333 allocating space for it or it was already too large.
1335 REGEX_REALLOCATE_STACK requires `destination' be declared. */
1337 /* Factor to increase the failure stack size by
1338 when we increase it.
1339 This used to be 2, but 2 was too wasteful
1340 because the old discarded stacks added up to as much space
1341 were as ultimate, maximum-size stack. */
1342 #define FAIL_STACK_GROWTH_FACTOR 4
1344 #define GROW_FAIL_STACK(fail_stack) \
1345 (((fail_stack).size * sizeof (fail_stack_elt_t) \
1346 >= re_max_failures * TYPICAL_FAILURE_SIZE) \
1348 : ((fail_stack).stack \
1349 = (fail_stack_elt_t *) \
1350 REGEX_REALLOCATE_STACK ((fail_stack).stack, \
1351 (fail_stack).size * sizeof (fail_stack_elt_t), \
1352 MIN (re_max_failures * TYPICAL_FAILURE_SIZE, \
1353 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1354 * FAIL_STACK_GROWTH_FACTOR))), \
1356 (fail_stack).stack == NULL \
1358 : ((fail_stack).size \
1359 = (MIN (re_max_failures * TYPICAL_FAILURE_SIZE, \
1360 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1361 * FAIL_STACK_GROWTH_FACTOR)) \
1362 / sizeof (fail_stack_elt_t)), \
1366 /* Push pointer POINTER on FAIL_STACK.
1367 Return 1 if was able to do so and 0 if ran out of memory allocating
1369 #define PUSH_PATTERN_OP(POINTER, FAIL_STACK) \
1370 ((FAIL_STACK_FULL () \
1371 && !GROW_FAIL_STACK (FAIL_STACK)) \
1373 : ((FAIL_STACK).stack[(FAIL_STACK).avail++].pointer = POINTER, \
1375 #define POP_PATTERN_OP() POP_FAILURE_POINTER ()
1377 /* Push a pointer value onto the failure stack.
1378 Assumes the variable `fail_stack'. Probably should only
1379 be called from within `PUSH_FAILURE_POINT'. */
1380 #define PUSH_FAILURE_POINTER(item) \
1381 fail_stack.stack[fail_stack.avail++].pointer = (unsigned char *) (item)
1383 /* This pushes an integer-valued item onto the failure stack.
1384 Assumes the variable `fail_stack'. Probably should only
1385 be called from within `PUSH_FAILURE_POINT'. */
1386 #define PUSH_FAILURE_INT(item) \
1387 fail_stack.stack[fail_stack.avail++].integer = (item)
1389 /* Push a fail_stack_elt_t value onto the failure stack.
1390 Assumes the variable `fail_stack'. Probably should only
1391 be called from within `PUSH_FAILURE_POINT'. */
1392 #define PUSH_FAILURE_ELT(item) \
1393 fail_stack.stack[fail_stack.avail++] = (item)
1395 /* These three POP... operations complement the three PUSH... operations.
1396 All assume that `fail_stack' is nonempty. */
1397 #define POP_FAILURE_POINTER() fail_stack.stack[--fail_stack.avail].pointer
1398 #define POP_FAILURE_INT() fail_stack.stack[--fail_stack.avail].integer
1399 #define POP_FAILURE_ELT() fail_stack.stack[--fail_stack.avail]
1401 /* Individual items aside from the registers. */
1402 #define NUM_NONREG_ITEMS 3
1404 /* Used to examine the stack (to detect infinite loops). */
1405 #define FAILURE_PAT(h) fail_stack.stack[(h) - 1].pointer
1406 #define FAILURE_STR(h) (fail_stack.stack[(h) - 2].pointer)
1407 #define NEXT_FAILURE_HANDLE(h) fail_stack.stack[(h) - 3].integer
1408 #define TOP_FAILURE_HANDLE() fail_stack.frame
1411 #define ENSURE_FAIL_STACK(space) \
1412 while (REMAINING_AVAIL_SLOTS <= space) { \
1413 if (!GROW_FAIL_STACK (fail_stack)) \
1415 DEBUG_PRINT2 ("\n Doubled stack; size now: %d\n", (fail_stack).size);\
1416 DEBUG_PRINT2 (" slots available: %d\n", REMAINING_AVAIL_SLOTS);\
1419 /* Push register NUM onto the stack. */
1420 #define PUSH_FAILURE_REG(num) \
1422 char *destination; \
1423 ENSURE_FAIL_STACK(3); \
1424 DEBUG_PRINT4 (" Push reg %d (spanning %p -> %p)\n", \
1425 num, regstart[num], regend[num]); \
1426 PUSH_FAILURE_POINTER (regstart[num]); \
1427 PUSH_FAILURE_POINTER (regend[num]); \
1428 PUSH_FAILURE_INT (num); \
1431 #define PUSH_FAILURE_COUNT(ptr) \
1433 char *destination; \
1435 ENSURE_FAIL_STACK(3); \
1436 EXTRACT_NUMBER (c, ptr); \
1437 DEBUG_PRINT3 (" Push counter %p = %d\n", ptr, c); \
1438 PUSH_FAILURE_INT (c); \
1439 PUSH_FAILURE_POINTER (ptr); \
1440 PUSH_FAILURE_INT (-1); \
1443 /* Pop a saved register off the stack. */
1444 #define POP_FAILURE_REG_OR_COUNT() \
1446 int reg = POP_FAILURE_INT (); \
1449 /* It's a counter. */ \
1450 unsigned char *ptr = (unsigned char*) POP_FAILURE_POINTER (); \
1451 reg = POP_FAILURE_INT (); \
1452 STORE_NUMBER (ptr, reg); \
1453 DEBUG_PRINT3 (" Pop counter %p = %d\n", ptr, reg); \
1457 regend[reg] = POP_FAILURE_POINTER (); \
1458 regstart[reg] = POP_FAILURE_POINTER (); \
1459 DEBUG_PRINT4 (" Pop reg %d (spanning %p -> %p)\n", \
1460 reg, regstart[reg], regend[reg]); \
1464 /* Check that we are not stuck in an infinite loop. */
1465 #define CHECK_INFINITE_LOOP(pat_cur, string_place) \
1467 int failure = TOP_FAILURE_HANDLE(); \
1468 /* Check for infinite matching loops */ \
1469 while (failure > 0 && \
1470 (FAILURE_STR (failure) == string_place \
1471 || FAILURE_STR (failure) == NULL)) \
1473 assert (FAILURE_PAT (failure) >= bufp->buffer \
1474 && FAILURE_PAT (failure) <= bufp->buffer + bufp->used); \
1475 if (FAILURE_PAT (failure) == pat_cur) \
1477 DEBUG_PRINT2 (" Other pattern: %p\n", FAILURE_PAT (failure)); \
1478 failure = NEXT_FAILURE_HANDLE(failure); \
1480 DEBUG_PRINT2 (" Other string: %p\n", FAILURE_STR (failure)); \
1483 /* Push the information about the state we will need
1484 if we ever fail back to it.
1486 Requires variables fail_stack, regstart, regend and
1487 num_regs be declared. GROW_FAIL_STACK requires `destination' be
1490 Does `return FAILURE_CODE' if runs out of memory. */
1492 #define PUSH_FAILURE_POINT(pattern, string_place) \
1494 char *destination; \
1495 /* Must be int, so when we don't save any registers, the arithmetic \
1496 of 0 + -1 isn't done as unsigned. */ \
1498 DEBUG_STATEMENT (nfailure_points_pushed++); \
1499 DEBUG_PRINT1 ("\nPUSH_FAILURE_POINT:\n"); \
1500 DEBUG_PRINT2 (" Before push, next avail: %d\n", (fail_stack).avail); \
1501 DEBUG_PRINT2 (" size: %d\n", (fail_stack).size);\
1503 ENSURE_FAIL_STACK (NUM_NONREG_ITEMS); \
1505 DEBUG_PRINT1 ("\n"); \
1507 DEBUG_PRINT2 (" Push frame index: %d\n", fail_stack.frame); \
1508 PUSH_FAILURE_INT (fail_stack.frame); \
1510 DEBUG_PRINT2 (" Push string %p: `", string_place); \
1511 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, size2);\
1512 DEBUG_PRINT1 ("'\n"); \
1513 PUSH_FAILURE_POINTER (string_place); \
1515 DEBUG_PRINT2 (" Push pattern %p: ", pattern); \
1516 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern, pend); \
1517 PUSH_FAILURE_POINTER (pattern); \
1519 /* Close the frame by moving the frame pointer past it. */ \
1520 fail_stack.frame = fail_stack.avail; \
1523 /* Estimate the size of data pushed by a typical failure stack entry.
1524 An estimate is all we need, because all we use this for
1525 is to choose a limit for how big to make the failure stack. */
1527 #define TYPICAL_FAILURE_SIZE 20
1529 /* How many items can still be added to the stack without overflowing it. */
1530 #define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
1533 /* Pops what PUSH_FAIL_STACK pushes.
1535 We restore into the parameters, all of which should be lvalues:
1536 STR -- the saved data position.
1537 PAT -- the saved pattern position.
1538 REGSTART, REGEND -- arrays of string positions.
1540 Also assumes the variables `fail_stack' and (if debugging), `bufp',
1541 `pend', `string1', `size1', `string2', and `size2'. */
1543 #define POP_FAILURE_POINT(str, pat) \
1545 assert (!FAIL_STACK_EMPTY ()); \
1547 /* Remove failure points and point to how many regs pushed. */ \
1548 DEBUG_PRINT1 ("POP_FAILURE_POINT:\n"); \
1549 DEBUG_PRINT2 (" Before pop, next avail: %d\n", fail_stack.avail); \
1550 DEBUG_PRINT2 (" size: %d\n", fail_stack.size); \
1552 /* Pop the saved registers. */ \
1553 while (fail_stack.frame < fail_stack.avail) \
1554 POP_FAILURE_REG_OR_COUNT (); \
1556 pat = (unsigned char *) POP_FAILURE_POINTER (); \
1557 DEBUG_PRINT2 (" Popping pattern %p: ", pat); \
1558 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
1560 /* If the saved string location is NULL, it came from an \
1561 on_failure_keep_string_jump opcode, and we want to throw away the \
1562 saved NULL, thus retaining our current position in the string. */ \
1563 str = (re_char *) POP_FAILURE_POINTER (); \
1564 DEBUG_PRINT2 (" Popping string %p: `", str); \
1565 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
1566 DEBUG_PRINT1 ("'\n"); \
1568 fail_stack.frame = POP_FAILURE_INT (); \
1569 DEBUG_PRINT2 (" Popping frame index: %d\n", fail_stack.frame); \
1571 assert (fail_stack.avail >= 0); \
1572 assert (fail_stack.frame <= fail_stack.avail); \
1574 DEBUG_STATEMENT (nfailure_points_popped++); \
1575 } while (0) /* POP_FAILURE_POINT */
1579 /* Registers are set to a sentinel when they haven't yet matched. */
1580 #define REG_UNSET(e) ((e) == NULL)
1582 /* Subroutine declarations and macros for regex_compile. */
1584 static reg_errcode_t regex_compile
_RE_ARGS ((re_char
*pattern
, size_t size
,
1585 reg_syntax_t syntax
,
1586 struct re_pattern_buffer
*bufp
));
1587 static void store_op1
_RE_ARGS ((re_opcode_t op
, unsigned char *loc
, int arg
));
1588 static void store_op2
_RE_ARGS ((re_opcode_t op
, unsigned char *loc
,
1589 int arg1
, int arg2
));
1590 static void insert_op1
_RE_ARGS ((re_opcode_t op
, unsigned char *loc
,
1591 int arg
, unsigned char *end
));
1592 static void insert_op2
_RE_ARGS ((re_opcode_t op
, unsigned char *loc
,
1593 int arg1
, int arg2
, unsigned char *end
));
1594 static boolean at_begline_loc_p
_RE_ARGS ((const unsigned char *pattern
,
1595 const unsigned char *p
,
1596 reg_syntax_t syntax
));
1597 static boolean at_endline_loc_p
_RE_ARGS ((const unsigned char *p
,
1598 const unsigned char *pend
,
1599 reg_syntax_t syntax
));
1600 static unsigned char *skip_one_char
_RE_ARGS ((unsigned char *p
));
1601 static int analyse_first
_RE_ARGS ((unsigned char *p
, unsigned char *pend
,
1602 char *fastmap
, const int multibyte
));
1604 /* Fetch the next character in the uncompiled pattern---translating it
1605 if necessary. Also cast from a signed character in the constant
1606 string passed to us by the user to an unsigned char that we can use
1607 as an array index (in, e.g., `translate'). */
1608 #define PATFETCH(c) \
1611 c = TRANSLATE (c); \
1614 /* Fetch the next character in the uncompiled pattern, with no
1616 #define PATFETCH_RAW(c) \
1619 if (p == pend) return REG_EEND; \
1620 c = RE_STRING_CHAR_AND_LENGTH (p, pend - p, len); \
1625 /* If `translate' is non-null, return translate[D], else just D. We
1626 cast the subscript to translate because some data is declared as
1627 `char *', to avoid warnings when a string constant is passed. But
1628 when we use a character as a subscript we must make it unsigned. */
1630 # define TRANSLATE(d) \
1631 (RE_TRANSLATE_P (translate) ? RE_TRANSLATE (translate, (d)) : (d))
1635 /* Macros for outputting the compiled pattern into `buffer'. */
1637 /* If the buffer isn't allocated when it comes in, use this. */
1638 #define INIT_BUF_SIZE 32
1640 /* Make sure we have at least N more bytes of space in buffer. */
1641 #define GET_BUFFER_SPACE(n) \
1642 while ((unsigned long) (b - bufp->buffer + (n)) > bufp->allocated) \
1645 /* Make sure we have one more byte of buffer space and then add C to it. */
1646 #define BUF_PUSH(c) \
1648 GET_BUFFER_SPACE (1); \
1649 *b++ = (unsigned char) (c); \
1653 /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
1654 #define BUF_PUSH_2(c1, c2) \
1656 GET_BUFFER_SPACE (2); \
1657 *b++ = (unsigned char) (c1); \
1658 *b++ = (unsigned char) (c2); \
1662 /* As with BUF_PUSH_2, except for three bytes. */
1663 #define BUF_PUSH_3(c1, c2, c3) \
1665 GET_BUFFER_SPACE (3); \
1666 *b++ = (unsigned char) (c1); \
1667 *b++ = (unsigned char) (c2); \
1668 *b++ = (unsigned char) (c3); \
1672 /* Store a jump with opcode OP at LOC to location TO. We store a
1673 relative address offset by the three bytes the jump itself occupies. */
1674 #define STORE_JUMP(op, loc, to) \
1675 store_op1 (op, loc, (to) - (loc) - 3)
1677 /* Likewise, for a two-argument jump. */
1678 #define STORE_JUMP2(op, loc, to, arg) \
1679 store_op2 (op, loc, (to) - (loc) - 3, arg)
1681 /* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
1682 #define INSERT_JUMP(op, loc, to) \
1683 insert_op1 (op, loc, (to) - (loc) - 3, b)
1685 /* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
1686 #define INSERT_JUMP2(op, loc, to, arg) \
1687 insert_op2 (op, loc, (to) - (loc) - 3, arg, b)
1690 /* This is not an arbitrary limit: the arguments which represent offsets
1691 into the pattern are two bytes long. So if 2^16 bytes turns out to
1692 be too small, many things would have to change. */
1693 /* Any other compiler which, like MSC, has allocation limit below 2^16
1694 bytes will have to use approach similar to what was done below for
1695 MSC and drop MAX_BUF_SIZE a bit. Otherwise you may end up
1696 reallocating to 0 bytes. Such thing is not going to work too well.
1697 You have been warned!! */
1698 #if defined _MSC_VER && !defined WIN32
1699 /* Microsoft C 16-bit versions limit malloc to approx 65512 bytes. */
1700 # define MAX_BUF_SIZE 65500L
1702 # define MAX_BUF_SIZE (1L << 16)
1705 /* Extend the buffer by twice its current size via realloc and
1706 reset the pointers that pointed into the old block to point to the
1707 correct places in the new one. If extending the buffer results in it
1708 being larger than MAX_BUF_SIZE, then flag memory exhausted. */
1709 #if __BOUNDED_POINTERS__
1710 # define SET_HIGH_BOUND(P) (__ptrhigh (P) = __ptrlow (P) + bufp->allocated)
1711 # define MOVE_BUFFER_POINTER(P) \
1712 (__ptrlow (P) += incr, SET_HIGH_BOUND (P), __ptrvalue (P) += incr)
1713 # define ELSE_EXTEND_BUFFER_HIGH_BOUND \
1716 SET_HIGH_BOUND (b); \
1717 SET_HIGH_BOUND (begalt); \
1718 if (fixup_alt_jump) \
1719 SET_HIGH_BOUND (fixup_alt_jump); \
1721 SET_HIGH_BOUND (laststart); \
1722 if (pending_exact) \
1723 SET_HIGH_BOUND (pending_exact); \
1726 # define MOVE_BUFFER_POINTER(P) (P) += incr
1727 # define ELSE_EXTEND_BUFFER_HIGH_BOUND
1729 #define EXTEND_BUFFER() \
1731 unsigned char *old_buffer = bufp->buffer; \
1732 if (bufp->allocated == MAX_BUF_SIZE) \
1734 bufp->allocated <<= 1; \
1735 if (bufp->allocated > MAX_BUF_SIZE) \
1736 bufp->allocated = MAX_BUF_SIZE; \
1737 bufp->buffer = (unsigned char *) realloc (bufp->buffer, bufp->allocated);\
1738 if (bufp->buffer == NULL) \
1739 return REG_ESPACE; \
1740 /* If the buffer moved, move all the pointers into it. */ \
1741 if (old_buffer != bufp->buffer) \
1743 int incr = bufp->buffer - old_buffer; \
1744 MOVE_BUFFER_POINTER (b); \
1745 MOVE_BUFFER_POINTER (begalt); \
1746 if (fixup_alt_jump) \
1747 MOVE_BUFFER_POINTER (fixup_alt_jump); \
1749 MOVE_BUFFER_POINTER (laststart); \
1750 if (pending_exact) \
1751 MOVE_BUFFER_POINTER (pending_exact); \
1753 ELSE_EXTEND_BUFFER_HIGH_BOUND \
1757 /* Since we have one byte reserved for the register number argument to
1758 {start,stop}_memory, the maximum number of groups we can report
1759 things about is what fits in that byte. */
1760 #define MAX_REGNUM 255
1762 /* But patterns can have more than `MAX_REGNUM' registers. We just
1763 ignore the excess. */
1764 typedef unsigned regnum_t
;
1767 /* Macros for the compile stack. */
1769 /* Since offsets can go either forwards or backwards, this type needs to
1770 be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
1771 /* int may be not enough when sizeof(int) == 2. */
1772 typedef long pattern_offset_t
;
1776 pattern_offset_t begalt_offset
;
1777 pattern_offset_t fixup_alt_jump
;
1778 pattern_offset_t laststart_offset
;
1780 } compile_stack_elt_t
;
1785 compile_stack_elt_t
*stack
;
1787 unsigned avail
; /* Offset of next open position. */
1788 } compile_stack_type
;
1791 #define INIT_COMPILE_STACK_SIZE 32
1793 #define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
1794 #define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
1796 /* The next available element. */
1797 #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
1800 /* Structure to manage work area for range table. */
1801 struct range_table_work_area
1803 int *table
; /* actual work area. */
1804 int allocated
; /* allocated size for work area in bytes. */
1805 int used
; /* actually used size in words. */
1806 int bits
; /* flag to record character classes */
1809 /* Make sure that WORK_AREA can hold more N multibyte characters. */
1810 #define EXTEND_RANGE_TABLE_WORK_AREA(work_area, n) \
1812 if (((work_area).used + (n)) * sizeof (int) > (work_area).allocated) \
1814 (work_area).allocated += 16 * sizeof (int); \
1815 if ((work_area).table) \
1817 = (int *) realloc ((work_area).table, (work_area).allocated); \
1820 = (int *) malloc ((work_area).allocated); \
1821 if ((work_area).table == 0) \
1822 FREE_STACK_RETURN (REG_ESPACE); \
1826 #define SET_RANGE_TABLE_WORK_AREA_BIT(work_area, bit) \
1827 (work_area).bits |= (bit)
1829 /* These bits represent the various character classes such as [:alnum:]
1830 in a charset's range table. */
1831 #define BIT_ALNUM 0x1
1832 #define BIT_ALPHA 0x2
1833 #define BIT_WORD 0x4
1834 #define BIT_ASCII 0x8
1835 #define BIT_NONASCII 0x10
1836 #define BIT_GRAPH 0x20
1837 #define BIT_LOWER 0x40
1838 #define BIT_PRINT 0x80
1839 #define BIT_PUNCT 0x100
1840 #define BIT_SPACE 0x200
1841 #define BIT_UPPER 0x400
1842 #define BIT_UNIBYTE 0x800
1843 #define BIT_MULTIBYTE 0x1000
1845 /* Set a range (RANGE_START, RANGE_END) to WORK_AREA. */
1846 #define SET_RANGE_TABLE_WORK_AREA(work_area, range_start, range_end) \
1848 EXTEND_RANGE_TABLE_WORK_AREA ((work_area), 2); \
1849 (work_area).table[(work_area).used++] = (range_start); \
1850 (work_area).table[(work_area).used++] = (range_end); \
1853 /* Free allocated memory for WORK_AREA. */
1854 #define FREE_RANGE_TABLE_WORK_AREA(work_area) \
1856 if ((work_area).table) \
1857 free ((work_area).table); \
1860 #define CLEAR_RANGE_TABLE_WORK_USED(work_area) ((work_area).used = 0, (work_area).bits = 0)
1861 #define RANGE_TABLE_WORK_USED(work_area) ((work_area).used)
1862 #define RANGE_TABLE_WORK_BITS(work_area) ((work_area).bits)
1863 #define RANGE_TABLE_WORK_ELT(work_area, i) ((work_area).table[i])
1866 /* Set the bit for character C in a list. */
1867 #define SET_LIST_BIT(c) \
1868 (b[((unsigned char) (c)) / BYTEWIDTH] \
1869 |= 1 << (((unsigned char) c) % BYTEWIDTH))
1872 /* Get the next unsigned number in the uncompiled pattern. */
1873 #define GET_UNSIGNED_NUMBER(num) \
1874 do { if (p != pend) \
1877 while ('0' <= c && c <= '9') \
1881 num = num * 10 + c - '0'; \
1889 #define CHAR_CLASS_MAX_LENGTH 6 /* Namely, `xdigit'. */
1891 #define IS_CHAR_CLASS(string) \
1892 (STREQ (string, "alpha") || STREQ (string, "upper") \
1893 || STREQ (string, "lower") || STREQ (string, "digit") \
1894 || STREQ (string, "alnum") || STREQ (string, "xdigit") \
1895 || STREQ (string, "space") || STREQ (string, "print") \
1896 || STREQ (string, "punct") || STREQ (string, "graph") \
1897 || STREQ (string, "cntrl") || STREQ (string, "blank") \
1898 || STREQ (string, "word") \
1899 || STREQ (string, "ascii") || STREQ (string, "nonascii") \
1900 || STREQ (string, "unibyte") || STREQ (string, "multibyte"))
1902 /* QUIT is only used on NTemacs. */
1903 #if !defined WINDOWSNT || !defined emacs || !defined QUIT
1908 #ifndef MATCH_MAY_ALLOCATE
1910 /* If we cannot allocate large objects within re_match_2_internal,
1911 we make the fail stack and register vectors global.
1912 The fail stack, we grow to the maximum size when a regexp
1914 The register vectors, we adjust in size each time we
1915 compile a regexp, according to the number of registers it needs. */
1917 static fail_stack_type fail_stack
;
1919 /* Size with which the following vectors are currently allocated.
1920 That is so we can make them bigger as needed,
1921 but never make them smaller. */
1922 static int regs_allocated_size
;
1924 static re_char
** regstart
, ** regend
;
1925 static re_char
**best_regstart
, **best_regend
;
1927 /* Make the register vectors big enough for NUM_REGS registers,
1928 but don't make them smaller. */
1931 regex_grow_registers (num_regs
)
1934 if (num_regs
> regs_allocated_size
)
1936 RETALLOC_IF (regstart
, num_regs
, re_char
*);
1937 RETALLOC_IF (regend
, num_regs
, re_char
*);
1938 RETALLOC_IF (best_regstart
, num_regs
, re_char
*);
1939 RETALLOC_IF (best_regend
, num_regs
, re_char
*);
1941 regs_allocated_size
= num_regs
;
1945 #endif /* not MATCH_MAY_ALLOCATE */
1947 static boolean group_in_compile_stack
_RE_ARGS ((compile_stack_type
1951 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
1952 Returns one of error codes defined in `regex.h', or zero for success.
1954 Assumes the `allocated' (and perhaps `buffer') and `translate'
1955 fields are set in BUFP on entry.
1957 If it succeeds, results are put in BUFP (if it returns an error, the
1958 contents of BUFP are undefined):
1959 `buffer' is the compiled pattern;
1960 `syntax' is set to SYNTAX;
1961 `used' is set to the length of the compiled pattern;
1962 `fastmap_accurate' is zero;
1963 `re_nsub' is the number of subexpressions in PATTERN;
1964 `not_bol' and `not_eol' are zero;
1966 The `fastmap' and `newline_anchor' fields are neither
1967 examined nor set. */
1969 /* Insert the `jump' from the end of last alternative to "here".
1970 The space for the jump has already been allocated. */
1971 #define FIXUP_ALT_JUMP() \
1973 if (fixup_alt_jump) \
1974 STORE_JUMP (jump, fixup_alt_jump, b); \
1978 /* Return, freeing storage we allocated. */
1979 #define FREE_STACK_RETURN(value) \
1981 FREE_RANGE_TABLE_WORK_AREA (range_table_work); \
1982 free (compile_stack.stack); \
1986 static reg_errcode_t
1987 regex_compile (pattern
, size
, syntax
, bufp
)
1990 reg_syntax_t syntax
;
1991 struct re_pattern_buffer
*bufp
;
1993 /* We fetch characters from PATTERN here. Even though PATTERN is
1994 `char *' (i.e., signed), we declare these variables as unsigned, so
1995 they can be reliably used as array indices. */
1996 register unsigned int c
, c1
;
1998 /* A random temporary spot in PATTERN. */
2001 /* Points to the end of the buffer, where we should append. */
2002 register unsigned char *b
;
2004 /* Keeps track of unclosed groups. */
2005 compile_stack_type compile_stack
;
2007 /* Points to the current (ending) position in the pattern. */
2009 /* `const' makes AIX compiler fail. */
2010 unsigned char *p
= pattern
;
2012 re_char
*p
= pattern
;
2014 re_char
*pend
= pattern
+ size
;
2016 /* How to translate the characters in the pattern. */
2017 RE_TRANSLATE_TYPE translate
= bufp
->translate
;
2019 /* Address of the count-byte of the most recently inserted `exactn'
2020 command. This makes it possible to tell if a new exact-match
2021 character can be added to that command or if the character requires
2022 a new `exactn' command. */
2023 unsigned char *pending_exact
= 0;
2025 /* Address of start of the most recently finished expression.
2026 This tells, e.g., postfix * where to find the start of its
2027 operand. Reset at the beginning of groups and alternatives. */
2028 unsigned char *laststart
= 0;
2030 /* Address of beginning of regexp, or inside of last group. */
2031 unsigned char *begalt
;
2033 /* Place in the uncompiled pattern (i.e., the {) to
2034 which to go back if the interval is invalid. */
2035 re_char
*beg_interval
;
2037 /* Address of the place where a forward jump should go to the end of
2038 the containing expression. Each alternative of an `or' -- except the
2039 last -- ends with a forward jump of this sort. */
2040 unsigned char *fixup_alt_jump
= 0;
2042 /* Counts open-groups as they are encountered. Remembered for the
2043 matching close-group on the compile stack, so the same register
2044 number is put in the stop_memory as the start_memory. */
2045 regnum_t regnum
= 0;
2047 /* Work area for range table of charset. */
2048 struct range_table_work_area range_table_work
;
2050 /* If the object matched can contain multibyte characters. */
2051 const boolean multibyte
= RE_MULTIBYTE_P (bufp
);
2055 DEBUG_PRINT1 ("\nCompiling pattern: ");
2058 unsigned debug_count
;
2060 for (debug_count
= 0; debug_count
< size
; debug_count
++)
2061 putchar (pattern
[debug_count
]);
2066 /* Initialize the compile stack. */
2067 compile_stack
.stack
= TALLOC (INIT_COMPILE_STACK_SIZE
, compile_stack_elt_t
);
2068 if (compile_stack
.stack
== NULL
)
2071 compile_stack
.size
= INIT_COMPILE_STACK_SIZE
;
2072 compile_stack
.avail
= 0;
2074 range_table_work
.table
= 0;
2075 range_table_work
.allocated
= 0;
2077 /* Initialize the pattern buffer. */
2078 bufp
->syntax
= syntax
;
2079 bufp
->fastmap_accurate
= 0;
2080 bufp
->not_bol
= bufp
->not_eol
= 0;
2082 /* Set `used' to zero, so that if we return an error, the pattern
2083 printer (for debugging) will think there's no pattern. We reset it
2087 /* Always count groups, whether or not bufp->no_sub is set. */
2090 #if !defined emacs && !defined SYNTAX_TABLE
2091 /* Initialize the syntax table. */
2092 init_syntax_once ();
2095 if (bufp
->allocated
== 0)
2098 { /* If zero allocated, but buffer is non-null, try to realloc
2099 enough space. This loses if buffer's address is bogus, but
2100 that is the user's responsibility. */
2101 RETALLOC (bufp
->buffer
, INIT_BUF_SIZE
, unsigned char);
2104 { /* Caller did not allocate a buffer. Do it for them. */
2105 bufp
->buffer
= TALLOC (INIT_BUF_SIZE
, unsigned char);
2107 if (!bufp
->buffer
) FREE_STACK_RETURN (REG_ESPACE
);
2109 bufp
->allocated
= INIT_BUF_SIZE
;
2112 begalt
= b
= bufp
->buffer
;
2114 /* Loop through the uncompiled pattern until we're at the end. */
2123 if ( /* If at start of pattern, it's an operator. */
2125 /* If context independent, it's an operator. */
2126 || syntax
& RE_CONTEXT_INDEP_ANCHORS
2127 /* Otherwise, depends on what's come before. */
2128 || at_begline_loc_p (pattern
, p
, syntax
))
2138 if ( /* If at end of pattern, it's an operator. */
2140 /* If context independent, it's an operator. */
2141 || syntax
& RE_CONTEXT_INDEP_ANCHORS
2142 /* Otherwise, depends on what's next. */
2143 || at_endline_loc_p (p
, pend
, syntax
))
2153 if ((syntax
& RE_BK_PLUS_QM
)
2154 || (syntax
& RE_LIMITED_OPS
))
2158 /* If there is no previous pattern... */
2161 if (syntax
& RE_CONTEXT_INVALID_OPS
)
2162 FREE_STACK_RETURN (REG_BADRPT
);
2163 else if (!(syntax
& RE_CONTEXT_INDEP_OPS
))
2168 /* 1 means zero (many) matches is allowed. */
2169 boolean zero_times_ok
= 0, many_times_ok
= 0;
2172 /* If there is a sequence of repetition chars, collapse it
2173 down to just one (the right one). We can't combine
2174 interval operators with these because of, e.g., `a{2}*',
2175 which should only match an even number of `a's. */
2179 if ((syntax
& RE_FRUGAL
)
2180 && c
== '?' && (zero_times_ok
|| many_times_ok
))
2184 zero_times_ok
|= c
!= '+';
2185 many_times_ok
|= c
!= '?';
2191 || (!(syntax
& RE_BK_PLUS_QM
)
2192 && (*p
== '+' || *p
== '?')))
2194 else if (syntax
& RE_BK_PLUS_QM
&& *p
== '\\')
2197 FREE_STACK_RETURN (REG_EESCAPE
);
2198 if (p
[1] == '+' || p
[1] == '?')
2199 PATFETCH (c
); /* Gobble up the backslash. */
2205 /* If we get here, we found another repeat character. */
2209 /* Star, etc. applied to an empty pattern is equivalent
2210 to an empty pattern. */
2211 if (!laststart
|| laststart
== b
)
2214 /* Now we know whether or not zero matches is allowed
2215 and also whether or not two or more matches is allowed. */
2220 boolean simple
= skip_one_char (laststart
) == b
;
2221 unsigned int startoffset
= 0;
2223 (simple
|| !analyse_first (laststart
, b
, NULL
, 0)) ?
2224 on_failure_jump
: on_failure_jump_loop
;
2225 assert (skip_one_char (laststart
) <= b
);
2227 if (!zero_times_ok
&& simple
)
2228 { /* Since simple * loops can be made faster by using
2229 on_failure_keep_string_jump, we turn simple P+
2230 into PP* if P is simple. */
2231 unsigned char *p1
, *p2
;
2232 startoffset
= b
- laststart
;
2233 GET_BUFFER_SPACE (startoffset
);
2234 p1
= b
; p2
= laststart
;
2240 GET_BUFFER_SPACE (6);
2243 STORE_JUMP (ofj
, b
, b
+ 6);
2245 /* Simple * loops can use on_failure_keep_string_jump
2246 depending on what follows. But since we don't know
2247 that yet, we leave the decision up to
2248 on_failure_jump_smart. */
2249 INSERT_JUMP (simple
? on_failure_jump_smart
: ofj
,
2250 laststart
+ startoffset
, b
+ 6);
2252 STORE_JUMP (jump
, b
, laststart
+ startoffset
);
2257 /* A simple ? pattern. */
2258 assert (zero_times_ok
);
2259 GET_BUFFER_SPACE (3);
2260 INSERT_JUMP (on_failure_jump
, laststart
, b
+ 3);
2264 else /* not greedy */
2265 { /* I wish the greedy and non-greedy cases could be merged. */
2267 GET_BUFFER_SPACE (7); /* We might use less. */
2270 boolean emptyp
= analyse_first (laststart
, b
, NULL
, 0);
2272 /* The non-greedy multiple match looks like a repeat..until:
2273 we only need a conditional jump at the end of the loop */
2274 if (emptyp
) BUF_PUSH (no_op
);
2275 STORE_JUMP (emptyp
? on_failure_jump_nastyloop
2276 : on_failure_jump
, b
, laststart
);
2280 /* The repeat...until naturally matches one or more.
2281 To also match zero times, we need to first jump to
2282 the end of the loop (its conditional jump). */
2283 INSERT_JUMP (jump
, laststart
, b
);
2289 /* non-greedy a?? */
2290 INSERT_JUMP (jump
, laststart
, b
+ 3);
2292 INSERT_JUMP (on_failure_jump
, laststart
, laststart
+ 6);
2309 CLEAR_RANGE_TABLE_WORK_USED (range_table_work
);
2311 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2313 /* Ensure that we have enough space to push a charset: the
2314 opcode, the length count, and the bitset; 34 bytes in all. */
2315 GET_BUFFER_SPACE (34);
2319 /* We test `*p == '^' twice, instead of using an if
2320 statement, so we only need one BUF_PUSH. */
2321 BUF_PUSH (*p
== '^' ? charset_not
: charset
);
2325 /* Remember the first position in the bracket expression. */
2328 /* Push the number of bytes in the bitmap. */
2329 BUF_PUSH ((1 << BYTEWIDTH
) / BYTEWIDTH
);
2331 /* Clear the whole map. */
2332 bzero (b
, (1 << BYTEWIDTH
) / BYTEWIDTH
);
2334 /* charset_not matches newline according to a syntax bit. */
2335 if ((re_opcode_t
) b
[-2] == charset_not
2336 && (syntax
& RE_HAT_LISTS_NOT_NEWLINE
))
2337 SET_LIST_BIT ('\n');
2339 /* Read in characters and ranges, setting map bits. */
2342 boolean escaped_char
= false;
2343 const unsigned char *p2
= p
;
2345 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2349 /* \ might escape characters inside [...] and [^...]. */
2350 if ((syntax
& RE_BACKSLASH_ESCAPE_IN_LISTS
) && c
== '\\')
2352 if (p
== pend
) FREE_STACK_RETURN (REG_EESCAPE
);
2355 escaped_char
= true;
2359 /* Could be the end of the bracket expression. If it's
2360 not (i.e., when the bracket expression is `[]' so
2361 far), the ']' character bit gets set way below. */
2362 if (c
== ']' && p2
!= p1
)
2366 /* What should we do for the character which is
2367 greater than 0x7F, but not BASE_LEADING_CODE_P?
2370 /* See if we're at the beginning of a possible character
2373 if (!escaped_char
&&
2374 syntax
& RE_CHAR_CLASSES
&& c
== '[' && *p
== ':')
2376 /* Leave room for the null. */
2377 char str
[CHAR_CLASS_MAX_LENGTH
+ 1];
2378 const unsigned char *class_beg
;
2384 /* If pattern is `[[:'. */
2385 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2390 if (c
== ':' || c
== ']' || p
== pend
2391 || c1
== CHAR_CLASS_MAX_LENGTH
)
2397 /* If isn't a word bracketed by `[:' and `:]':
2398 undo the ending character, the letters, and
2399 leave the leading `:' and `[' (but set bits for
2401 if (c
== ':' && *p
== ']')
2404 boolean is_alnum
= STREQ (str
, "alnum");
2405 boolean is_alpha
= STREQ (str
, "alpha");
2406 boolean is_ascii
= STREQ (str
, "ascii");
2407 boolean is_blank
= STREQ (str
, "blank");
2408 boolean is_cntrl
= STREQ (str
, "cntrl");
2409 boolean is_digit
= STREQ (str
, "digit");
2410 boolean is_graph
= STREQ (str
, "graph");
2411 boolean is_lower
= STREQ (str
, "lower");
2412 boolean is_multibyte
= STREQ (str
, "multibyte");
2413 boolean is_nonascii
= STREQ (str
, "nonascii");
2414 boolean is_print
= STREQ (str
, "print");
2415 boolean is_punct
= STREQ (str
, "punct");
2416 boolean is_space
= STREQ (str
, "space");
2417 boolean is_unibyte
= STREQ (str
, "unibyte");
2418 boolean is_upper
= STREQ (str
, "upper");
2419 boolean is_word
= STREQ (str
, "word");
2420 boolean is_xdigit
= STREQ (str
, "xdigit");
2422 if (!IS_CHAR_CLASS (str
))
2423 FREE_STACK_RETURN (REG_ECTYPE
);
2425 /* Throw away the ] at the end of the character
2429 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2431 /* Most character classes in a multibyte match
2432 just set a flag. Exceptions are is_blank,
2433 is_digit, is_cntrl, and is_xdigit, since
2434 they can only match ASCII characters. We
2435 don't need to handle them for multibyte. */
2441 if (is_alnum
) bit
= BIT_ALNUM
;
2442 if (is_alpha
) bit
= BIT_ALPHA
;
2443 if (is_ascii
) bit
= BIT_ASCII
;
2444 if (is_graph
) bit
= BIT_GRAPH
;
2445 if (is_lower
) bit
= BIT_LOWER
;
2446 if (is_multibyte
) bit
= BIT_MULTIBYTE
;
2447 if (is_nonascii
) bit
= BIT_NONASCII
;
2448 if (is_print
) bit
= BIT_PRINT
;
2449 if (is_punct
) bit
= BIT_PUNCT
;
2450 if (is_space
) bit
= BIT_SPACE
;
2451 if (is_unibyte
) bit
= BIT_UNIBYTE
;
2452 if (is_upper
) bit
= BIT_UPPER
;
2453 if (is_word
) bit
= BIT_WORD
;
2455 SET_RANGE_TABLE_WORK_AREA_BIT (range_table_work
,
2459 /* Handle character classes for ASCII characters. */
2460 for (ch
= 0; ch
< 1 << BYTEWIDTH
; ch
++)
2462 int translated
= TRANSLATE (ch
);
2463 /* This was split into 3 if's to
2464 avoid an arbitrary limit in some compiler. */
2465 if ( (is_alnum
&& ISALNUM (ch
))
2466 || (is_alpha
&& ISALPHA (ch
))
2467 || (is_blank
&& ISBLANK (ch
))
2468 || (is_cntrl
&& ISCNTRL (ch
)))
2469 SET_LIST_BIT (translated
);
2470 if ( (is_digit
&& ISDIGIT (ch
))
2471 || (is_graph
&& ISGRAPH (ch
))
2472 || (is_lower
&& ISLOWER (ch
))
2473 || (is_print
&& ISPRINT (ch
)))
2474 SET_LIST_BIT (translated
);
2475 if ( (is_punct
&& ISPUNCT (ch
))
2476 || (is_space
&& ISSPACE (ch
))
2477 || (is_upper
&& ISUPPER (ch
))
2478 || (is_xdigit
&& ISXDIGIT (ch
)))
2479 SET_LIST_BIT (translated
);
2480 if ( (is_ascii
&& IS_REAL_ASCII (ch
))
2481 || (is_nonascii
&& !IS_REAL_ASCII (ch
))
2482 || (is_unibyte
&& ISUNIBYTE (ch
))
2483 || (is_multibyte
&& !ISUNIBYTE (ch
)))
2484 SET_LIST_BIT (translated
);
2486 if ( (is_word
&& ISWORD (ch
)))
2487 SET_LIST_BIT (translated
);
2490 /* Repeat the loop. */
2495 /* Go back to right after the "[:". */
2499 /* Because the `:' may starts the range, we
2500 can't simply set bit and repeat the loop.
2501 Instead, just set it to C and handle below. */
2506 if (p
< pend
&& p
[0] == '-' && p
[1] != ']')
2509 /* Discard the `-'. */
2512 /* Fetch the character which ends the range. */
2515 if (SINGLE_BYTE_CHAR_P (c
))
2517 if (! SINGLE_BYTE_CHAR_P (c1
))
2519 /* Handle a range such as \177-\377 in
2520 multibyte mode. Split that into two
2521 ranges, the low one ending at 0237, and
2522 the high one starting at the smallest
2523 character in the charset of C1 and
2525 int charset
= CHAR_CHARSET (c1
);
2526 int c2
= MAKE_CHAR (charset
, 0, 0);
2528 SET_RANGE_TABLE_WORK_AREA (range_table_work
,
2533 else if (!SAME_CHARSET_P (c
, c1
))
2534 FREE_STACK_RETURN (REG_ERANGE
);
2537 /* Range from C to C. */
2540 /* Set the range ... */
2541 if (SINGLE_BYTE_CHAR_P (c
))
2542 /* ... into bitmap. */
2545 int range_start
= c
, range_end
= c1
;
2547 /* If the start is after the end, the range is empty. */
2548 if (range_start
> range_end
)
2550 if (syntax
& RE_NO_EMPTY_RANGES
)
2551 FREE_STACK_RETURN (REG_ERANGE
);
2552 /* Else, repeat the loop. */
2556 for (this_char
= range_start
; this_char
<= range_end
;
2558 SET_LIST_BIT (TRANSLATE (this_char
));
2562 /* ... into range table. */
2563 SET_RANGE_TABLE_WORK_AREA (range_table_work
, c
, c1
);
2566 /* Discard any (non)matching list bytes that are all 0 at the
2567 end of the map. Decrease the map-length byte too. */
2568 while ((int) b
[-1] > 0 && b
[b
[-1] - 1] == 0)
2572 /* Build real range table from work area. */
2573 if (RANGE_TABLE_WORK_USED (range_table_work
)
2574 || RANGE_TABLE_WORK_BITS (range_table_work
))
2577 int used
= RANGE_TABLE_WORK_USED (range_table_work
);
2579 /* Allocate space for COUNT + RANGE_TABLE. Needs two
2580 bytes for flags, two for COUNT, and three bytes for
2582 GET_BUFFER_SPACE (4 + used
* 3);
2584 /* Indicate the existence of range table. */
2585 laststart
[1] |= 0x80;
2587 /* Store the character class flag bits into the range table.
2588 If not in emacs, these flag bits are always 0. */
2589 *b
++ = RANGE_TABLE_WORK_BITS (range_table_work
) & 0xff;
2590 *b
++ = RANGE_TABLE_WORK_BITS (range_table_work
) >> 8;
2592 STORE_NUMBER_AND_INCR (b
, used
/ 2);
2593 for (i
= 0; i
< used
; i
++)
2594 STORE_CHARACTER_AND_INCR
2595 (b
, RANGE_TABLE_WORK_ELT (range_table_work
, i
));
2602 if (syntax
& RE_NO_BK_PARENS
)
2609 if (syntax
& RE_NO_BK_PARENS
)
2616 if (syntax
& RE_NEWLINE_ALT
)
2623 if (syntax
& RE_NO_BK_VBAR
)
2630 if (syntax
& RE_INTERVALS
&& syntax
& RE_NO_BK_BRACES
)
2631 goto handle_interval
;
2637 if (p
== pend
) FREE_STACK_RETURN (REG_EESCAPE
);
2639 /* Do not translate the character after the \, so that we can
2640 distinguish, e.g., \B from \b, even if we normally would
2641 translate, e.g., B to b. */
2647 if (syntax
& RE_NO_BK_PARENS
)
2648 goto normal_backslash
;
2655 /* Look for a special (?...) construct */
2656 if ((syntax
& RE_SHY_GROUPS
) && *p
== '?')
2658 PATFETCH (c
); /* Gobble up the '?'. */
2662 case ':': shy
= 1; break;
2664 /* Only (?:...) is supported right now. */
2665 FREE_STACK_RETURN (REG_BADPAT
);
2676 if (COMPILE_STACK_FULL
)
2678 RETALLOC (compile_stack
.stack
, compile_stack
.size
<< 1,
2679 compile_stack_elt_t
);
2680 if (compile_stack
.stack
== NULL
) return REG_ESPACE
;
2682 compile_stack
.size
<<= 1;
2685 /* These are the values to restore when we hit end of this
2686 group. They are all relative offsets, so that if the
2687 whole pattern moves because of realloc, they will still
2689 COMPILE_STACK_TOP
.begalt_offset
= begalt
- bufp
->buffer
;
2690 COMPILE_STACK_TOP
.fixup_alt_jump
2691 = fixup_alt_jump
? fixup_alt_jump
- bufp
->buffer
+ 1 : 0;
2692 COMPILE_STACK_TOP
.laststart_offset
= b
- bufp
->buffer
;
2693 COMPILE_STACK_TOP
.regnum
= shy
? -regnum
: regnum
;
2696 start_memory for groups beyond the last one we can
2697 represent in the compiled pattern. */
2698 if (regnum
<= MAX_REGNUM
&& !shy
)
2699 BUF_PUSH_2 (start_memory
, regnum
);
2701 compile_stack
.avail
++;
2706 /* If we've reached MAX_REGNUM groups, then this open
2707 won't actually generate any code, so we'll have to
2708 clear pending_exact explicitly. */
2714 if (syntax
& RE_NO_BK_PARENS
) goto normal_backslash
;
2716 if (COMPILE_STACK_EMPTY
)
2718 if (syntax
& RE_UNMATCHED_RIGHT_PAREN_ORD
)
2719 goto normal_backslash
;
2721 FREE_STACK_RETURN (REG_ERPAREN
);
2727 /* See similar code for backslashed left paren above. */
2728 if (COMPILE_STACK_EMPTY
)
2730 if (syntax
& RE_UNMATCHED_RIGHT_PAREN_ORD
)
2733 FREE_STACK_RETURN (REG_ERPAREN
);
2736 /* Since we just checked for an empty stack above, this
2737 ``can't happen''. */
2738 assert (compile_stack
.avail
!= 0);
2740 /* We don't just want to restore into `regnum', because
2741 later groups should continue to be numbered higher,
2742 as in `(ab)c(de)' -- the second group is #2. */
2743 regnum_t this_group_regnum
;
2745 compile_stack
.avail
--;
2746 begalt
= bufp
->buffer
+ COMPILE_STACK_TOP
.begalt_offset
;
2748 = COMPILE_STACK_TOP
.fixup_alt_jump
2749 ? bufp
->buffer
+ COMPILE_STACK_TOP
.fixup_alt_jump
- 1
2751 laststart
= bufp
->buffer
+ COMPILE_STACK_TOP
.laststart_offset
;
2752 this_group_regnum
= COMPILE_STACK_TOP
.regnum
;
2753 /* If we've reached MAX_REGNUM groups, then this open
2754 won't actually generate any code, so we'll have to
2755 clear pending_exact explicitly. */
2758 /* We're at the end of the group, so now we know how many
2759 groups were inside this one. */
2760 if (this_group_regnum
<= MAX_REGNUM
&& this_group_regnum
> 0)
2761 BUF_PUSH_2 (stop_memory
, this_group_regnum
);
2766 case '|': /* `\|'. */
2767 if (syntax
& RE_LIMITED_OPS
|| syntax
& RE_NO_BK_VBAR
)
2768 goto normal_backslash
;
2770 if (syntax
& RE_LIMITED_OPS
)
2773 /* Insert before the previous alternative a jump which
2774 jumps to this alternative if the former fails. */
2775 GET_BUFFER_SPACE (3);
2776 INSERT_JUMP (on_failure_jump
, begalt
, b
+ 6);
2780 /* The alternative before this one has a jump after it
2781 which gets executed if it gets matched. Adjust that
2782 jump so it will jump to this alternative's analogous
2783 jump (put in below, which in turn will jump to the next
2784 (if any) alternative's such jump, etc.). The last such
2785 jump jumps to the correct final destination. A picture:
2791 If we are at `b', then fixup_alt_jump right now points to a
2792 three-byte space after `a'. We'll put in the jump, set
2793 fixup_alt_jump to right after `b', and leave behind three
2794 bytes which we'll fill in when we get to after `c'. */
2798 /* Mark and leave space for a jump after this alternative,
2799 to be filled in later either by next alternative or
2800 when know we're at the end of a series of alternatives. */
2802 GET_BUFFER_SPACE (3);
2811 /* If \{ is a literal. */
2812 if (!(syntax
& RE_INTERVALS
)
2813 /* If we're at `\{' and it's not the open-interval
2815 || (syntax
& RE_NO_BK_BRACES
))
2816 goto normal_backslash
;
2820 /* If got here, then the syntax allows intervals. */
2822 /* At least (most) this many matches must be made. */
2823 int lower_bound
= 0, upper_bound
= -1;
2828 FREE_STACK_RETURN (REG_EBRACE
);
2830 GET_UNSIGNED_NUMBER (lower_bound
);
2833 GET_UNSIGNED_NUMBER (upper_bound
);
2835 /* Interval such as `{1}' => match exactly once. */
2836 upper_bound
= lower_bound
;
2838 if (lower_bound
< 0 || upper_bound
> RE_DUP_MAX
2839 || (upper_bound
>= 0 && lower_bound
> upper_bound
))
2840 FREE_STACK_RETURN (REG_BADBR
);
2842 if (!(syntax
& RE_NO_BK_BRACES
))
2845 FREE_STACK_RETURN (REG_BADBR
);
2851 FREE_STACK_RETURN (REG_BADBR
);
2853 /* We just parsed a valid interval. */
2855 /* If it's invalid to have no preceding re. */
2858 if (syntax
& RE_CONTEXT_INVALID_OPS
)
2859 FREE_STACK_RETURN (REG_BADRPT
);
2860 else if (syntax
& RE_CONTEXT_INDEP_OPS
)
2863 goto unfetch_interval
;
2866 if (upper_bound
== 0)
2867 /* If the upper bound is zero, just drop the sub pattern
2870 else if (lower_bound
== 1 && upper_bound
== 1)
2871 /* Just match it once: nothing to do here. */
2874 /* Otherwise, we have a nontrivial interval. When
2875 we're all done, the pattern will look like:
2876 set_number_at <jump count> <upper bound>
2877 set_number_at <succeed_n count> <lower bound>
2878 succeed_n <after jump addr> <succeed_n count>
2880 jump_n <succeed_n addr> <jump count>
2881 (The upper bound and `jump_n' are omitted if
2882 `upper_bound' is 1, though.) */
2884 { /* If the upper bound is > 1, we need to insert
2885 more at the end of the loop. */
2886 unsigned int nbytes
= (upper_bound
< 0 ? 3
2887 : upper_bound
> 1 ? 5 : 0);
2888 unsigned int startoffset
= 0;
2890 GET_BUFFER_SPACE (20); /* We might use less. */
2892 if (lower_bound
== 0)
2894 /* A succeed_n that starts with 0 is really a
2895 a simple on_failure_jump_loop. */
2896 INSERT_JUMP (on_failure_jump_loop
, laststart
,
2902 /* Initialize lower bound of the `succeed_n', even
2903 though it will be set during matching by its
2904 attendant `set_number_at' (inserted next),
2905 because `re_compile_fastmap' needs to know.
2906 Jump to the `jump_n' we might insert below. */
2907 INSERT_JUMP2 (succeed_n
, laststart
,
2912 /* Code to initialize the lower bound. Insert
2913 before the `succeed_n'. The `5' is the last two
2914 bytes of this `set_number_at', plus 3 bytes of
2915 the following `succeed_n'. */
2916 insert_op2 (set_number_at
, laststart
, 5, lower_bound
, b
);
2921 if (upper_bound
< 0)
2923 /* A negative upper bound stands for infinity,
2924 in which case it degenerates to a plain jump. */
2925 STORE_JUMP (jump
, b
, laststart
+ startoffset
);
2928 else if (upper_bound
> 1)
2929 { /* More than one repetition is allowed, so
2930 append a backward jump to the `succeed_n'
2931 that starts this interval.
2933 When we've reached this during matching,
2934 we'll have matched the interval once, so
2935 jump back only `upper_bound - 1' times. */
2936 STORE_JUMP2 (jump_n
, b
, laststart
+ startoffset
,
2940 /* The location we want to set is the second
2941 parameter of the `jump_n'; that is `b-2' as
2942 an absolute address. `laststart' will be
2943 the `set_number_at' we're about to insert;
2944 `laststart+3' the number to set, the source
2945 for the relative address. But we are
2946 inserting into the middle of the pattern --
2947 so everything is getting moved up by 5.
2948 Conclusion: (b - 2) - (laststart + 3) + 5,
2949 i.e., b - laststart.
2951 We insert this at the beginning of the loop
2952 so that if we fail during matching, we'll
2953 reinitialize the bounds. */
2954 insert_op2 (set_number_at
, laststart
, b
- laststart
,
2955 upper_bound
- 1, b
);
2960 beg_interval
= NULL
;
2965 /* If an invalid interval, match the characters as literals. */
2966 assert (beg_interval
);
2968 beg_interval
= NULL
;
2970 /* normal_char and normal_backslash need `c'. */
2973 if (!(syntax
& RE_NO_BK_BRACES
))
2975 assert (p
> pattern
&& p
[-1] == '\\');
2976 goto normal_backslash
;
2982 /* There is no way to specify the before_dot and after_dot
2983 operators. rms says this is ok. --karl */
2991 BUF_PUSH_2 (syntaxspec
, syntax_spec_code
[c
]);
2997 BUF_PUSH_2 (notsyntaxspec
, syntax_spec_code
[c
]);
3003 BUF_PUSH_2 (categoryspec
, c
);
3009 BUF_PUSH_2 (notcategoryspec
, c
);
3015 if (syntax
& RE_NO_GNU_OPS
)
3018 BUF_PUSH_2 (syntaxspec
, Sword
);
3023 if (syntax
& RE_NO_GNU_OPS
)
3026 BUF_PUSH_2 (notsyntaxspec
, Sword
);
3031 if (syntax
& RE_NO_GNU_OPS
)
3037 if (syntax
& RE_NO_GNU_OPS
)
3043 if (syntax
& RE_NO_GNU_OPS
)
3045 BUF_PUSH (wordbound
);
3049 if (syntax
& RE_NO_GNU_OPS
)
3051 BUF_PUSH (notwordbound
);
3055 if (syntax
& RE_NO_GNU_OPS
)
3061 if (syntax
& RE_NO_GNU_OPS
)
3066 case '1': case '2': case '3': case '4': case '5':
3067 case '6': case '7': case '8': case '9':
3068 if (syntax
& RE_NO_BK_REFS
)
3074 FREE_STACK_RETURN (REG_ESUBREG
);
3076 /* Can't back reference to a subexpression if inside of it. */
3077 if (group_in_compile_stack (compile_stack
, (regnum_t
) c1
))
3081 BUF_PUSH_2 (duplicate
, c1
);
3087 if (syntax
& RE_BK_PLUS_QM
)
3090 goto normal_backslash
;
3094 /* You might think it would be useful for \ to mean
3095 not to translate; but if we don't translate it
3096 it will never match anything. */
3104 /* Expects the character in `c'. */
3106 /* If no exactn currently being built. */
3109 /* If last exactn not at current position. */
3110 || pending_exact
+ *pending_exact
+ 1 != b
3112 /* We have only one byte following the exactn for the count. */
3113 || *pending_exact
>= (1 << BYTEWIDTH
) - MAX_MULTIBYTE_LENGTH
3115 /* If followed by a repetition operator. */
3116 || (p
!= pend
&& (*p
== '*' || *p
== '^'))
3117 || ((syntax
& RE_BK_PLUS_QM
)
3118 ? p
+ 1 < pend
&& *p
== '\\' && (p
[1] == '+' || p
[1] == '?')
3119 : p
!= pend
&& (*p
== '+' || *p
== '?'))
3120 || ((syntax
& RE_INTERVALS
)
3121 && ((syntax
& RE_NO_BK_BRACES
)
3122 ? p
!= pend
&& *p
== '{'
3123 : p
+ 1 < pend
&& p
[0] == '\\' && p
[1] == '{')))
3125 /* Start building a new exactn. */
3129 BUF_PUSH_2 (exactn
, 0);
3130 pending_exact
= b
- 1;
3133 GET_BUFFER_SPACE (MAX_MULTIBYTE_LENGTH
);
3138 len
= CHAR_STRING (c
, b
);
3142 (*pending_exact
) += len
;
3147 } /* while p != pend */
3150 /* Through the pattern now. */
3154 if (!COMPILE_STACK_EMPTY
)
3155 FREE_STACK_RETURN (REG_EPAREN
);
3157 /* If we don't want backtracking, force success
3158 the first time we reach the end of the compiled pattern. */
3159 if (syntax
& RE_NO_POSIX_BACKTRACKING
)
3162 free (compile_stack
.stack
);
3164 /* We have succeeded; set the length of the buffer. */
3165 bufp
->used
= b
- bufp
->buffer
;
3170 re_compile_fastmap (bufp
);
3171 DEBUG_PRINT1 ("\nCompiled pattern: \n");
3172 print_compiled_pattern (bufp
);
3177 #ifndef MATCH_MAY_ALLOCATE
3178 /* Initialize the failure stack to the largest possible stack. This
3179 isn't necessary unless we're trying to avoid calling alloca in
3180 the search and match routines. */
3182 int num_regs
= bufp
->re_nsub
+ 1;
3184 if (fail_stack
.size
< re_max_failures
* TYPICAL_FAILURE_SIZE
)
3186 fail_stack
.size
= re_max_failures
* TYPICAL_FAILURE_SIZE
;
3188 if (! fail_stack
.stack
)
3190 = (fail_stack_elt_t
*) malloc (fail_stack
.size
3191 * sizeof (fail_stack_elt_t
));
3194 = (fail_stack_elt_t
*) realloc (fail_stack
.stack
,
3196 * sizeof (fail_stack_elt_t
)));
3199 regex_grow_registers (num_regs
);
3201 #endif /* not MATCH_MAY_ALLOCATE */
3204 } /* regex_compile */
3206 /* Subroutines for `regex_compile'. */
3208 /* Store OP at LOC followed by two-byte integer parameter ARG. */
3211 store_op1 (op
, loc
, arg
)
3216 *loc
= (unsigned char) op
;
3217 STORE_NUMBER (loc
+ 1, arg
);
3221 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
3224 store_op2 (op
, loc
, arg1
, arg2
)
3229 *loc
= (unsigned char) op
;
3230 STORE_NUMBER (loc
+ 1, arg1
);
3231 STORE_NUMBER (loc
+ 3, arg2
);
3235 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
3236 for OP followed by two-byte integer parameter ARG. */
3239 insert_op1 (op
, loc
, arg
, end
)
3245 register unsigned char *pfrom
= end
;
3246 register unsigned char *pto
= end
+ 3;
3248 while (pfrom
!= loc
)
3251 store_op1 (op
, loc
, arg
);
3255 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
3258 insert_op2 (op
, loc
, arg1
, arg2
, end
)
3264 register unsigned char *pfrom
= end
;
3265 register unsigned char *pto
= end
+ 5;
3267 while (pfrom
!= loc
)
3270 store_op2 (op
, loc
, arg1
, arg2
);
3274 /* P points to just after a ^ in PATTERN. Return true if that ^ comes
3275 after an alternative or a begin-subexpression. We assume there is at
3276 least one character before the ^. */
3279 at_begline_loc_p (pattern
, p
, syntax
)
3280 const unsigned char *pattern
, *p
;
3281 reg_syntax_t syntax
;
3283 const unsigned char *prev
= p
- 2;
3284 boolean prev_prev_backslash
= prev
> pattern
&& prev
[-1] == '\\';
3287 /* After a subexpression? */
3288 (*prev
== '(' && (syntax
& RE_NO_BK_PARENS
|| prev_prev_backslash
))
3289 /* After an alternative? */
3290 || (*prev
== '|' && (syntax
& RE_NO_BK_VBAR
|| prev_prev_backslash
))
3291 /* After a shy subexpression? */
3292 || ((syntax
& RE_SHY_GROUPS
) && prev
- 2 >= pattern
3293 && prev
[-1] == '?' && prev
[-2] == '('
3294 && (syntax
& RE_NO_BK_PARENS
3295 || (prev
- 3 >= pattern
&& prev
[-3] == '\\')));
3299 /* The dual of at_begline_loc_p. This one is for $. We assume there is
3300 at least one character after the $, i.e., `P < PEND'. */
3303 at_endline_loc_p (p
, pend
, syntax
)
3304 const unsigned char *p
, *pend
;
3305 reg_syntax_t syntax
;
3307 const unsigned char *next
= p
;
3308 boolean next_backslash
= *next
== '\\';
3309 const unsigned char *next_next
= p
+ 1 < pend
? p
+ 1 : 0;
3312 /* Before a subexpression? */
3313 (syntax
& RE_NO_BK_PARENS
? *next
== ')'
3314 : next_backslash
&& next_next
&& *next_next
== ')')
3315 /* Before an alternative? */
3316 || (syntax
& RE_NO_BK_VBAR
? *next
== '|'
3317 : next_backslash
&& next_next
&& *next_next
== '|');
3321 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
3322 false if it's not. */
3325 group_in_compile_stack (compile_stack
, regnum
)
3326 compile_stack_type compile_stack
;
3331 for (this_element
= compile_stack
.avail
- 1;
3334 if (compile_stack
.stack
[this_element
].regnum
== regnum
)
3341 If fastmap is non-NULL, go through the pattern and fill fastmap
3342 with all the possible leading chars. If fastmap is NULL, don't
3343 bother filling it up (obviously) and only return whether the
3344 pattern could potentially match the empty string.
3346 Return 1 if p..pend might match the empty string.
3347 Return 0 if p..pend matches at least one char.
3348 Return -1 if p..pend matches at least one char, but fastmap was not
3350 Return -2 if an error occurred. */
3353 analyse_first (p
, pend
, fastmap
, multibyte
)
3354 unsigned char *p
, *pend
;
3356 const int multibyte
;
3360 #ifdef MATCH_MAY_ALLOCATE
3361 fail_stack_type fail_stack
;
3363 #ifndef REGEX_MALLOC
3367 #if defined REL_ALLOC && defined REGEX_MALLOC
3368 /* This holds the pointer to the failure stack, when
3369 it is allocated relocatably. */
3370 fail_stack_elt_t
*failure_stack_ptr
;
3373 /* Assume that each path through the pattern can be null until
3374 proven otherwise. We set this false at the bottom of switch
3375 statement, to which we get only if a particular path doesn't
3376 match the empty string. */
3377 boolean path_can_be_null
= true;
3379 /* If all elements for base leading-codes in fastmap is set, this
3380 flag is set true. */
3381 boolean match_any_multibyte_characters
= false;
3387 /* The loop below works as follows:
3388 - It has a working-list kept in the PATTERN_STACK and which basically
3389 starts by only containing a pointer to the first operation.
3390 - If the opcode we're looking at is a match against some set of
3391 chars, then we add those chars to the fastmap and go on to the
3392 next work element from the worklist (done via `break').
3393 - If the opcode is a control operator on the other hand, we either
3394 ignore it (if it's meaningless at this point, such as `start_memory')
3395 or execute it (if it's a jump). If the jump has several destinations
3396 (i.e. `on_failure_jump'), then we push the other destination onto the
3398 We guarantee termination by ignoring backward jumps (more or less),
3399 so that `p' is monotonically increasing. More to the point, we
3400 never set `p' (or push) anything `<= p1'. */
3402 /* If can_be_null is set, then the fastmap will not be used anyway. */
3405 /* `p1' is used as a marker of how far back a `on_failure_jump'
3406 can go without being ignored. It is normally equal to `p'
3407 (which prevents any backward `on_failure_jump') except right
3408 after a plain `jump', to allow patterns such as:
3411 10: on_failure_jump 3
3412 as used for the *? operator. */
3413 unsigned char *p1
= p
;
3417 if (path_can_be_null
)
3418 return (RESET_FAIL_STACK (), 1);
3420 /* We have reached the (effective) end of pattern. */
3421 if (PATTERN_STACK_EMPTY ())
3422 return (RESET_FAIL_STACK (), 0);
3424 p
= (unsigned char*) POP_PATTERN_OP ();
3425 path_can_be_null
= true;
3429 /* We should never be about to go beyond the end of the pattern. */
3432 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *p
++))
3439 /* If the first character has to match a backreference, that means
3440 that the group was empty (since it already matched). Since this
3441 is the only case that interests us here, we can assume that the
3442 backreference must match the empty string. */
3447 /* Following are the cases which match a character. These end
3453 int c
= RE_STRING_CHAR (p
+ 1, pend
- p
);
3455 if (SINGLE_BYTE_CHAR_P (c
))
3464 /* We could put all the chars except for \n (and maybe \0)
3465 but we don't bother since it is generally not worth it. */
3466 if (!fastmap
) break;
3467 return (RESET_FAIL_STACK (), -1);
3471 /* Chars beyond end of bitmap are possible matches.
3472 All the single-byte codes can occur in multibyte buffers.
3473 So any that are not listed in the charset
3474 are possible matches, even in multibyte buffers. */
3475 if (!fastmap
) break;
3476 for (j
= CHARSET_BITMAP_SIZE (&p
[-1]) * BYTEWIDTH
;
3477 j
< (1 << BYTEWIDTH
); j
++)
3481 if (!fastmap
) break;
3482 not = (re_opcode_t
) *(p
- 1) == charset_not
;
3483 for (j
= CHARSET_BITMAP_SIZE (&p
[-1]) * BYTEWIDTH
- 1, p
++;
3485 if (!!(p
[j
/ BYTEWIDTH
] & (1 << (j
% BYTEWIDTH
))) ^ not)
3488 if ((not && multibyte
)
3489 /* Any character set can possibly contain a character
3490 which doesn't match the specified set of characters. */
3491 || (CHARSET_RANGE_TABLE_EXISTS_P (&p
[-2])
3492 && CHARSET_RANGE_TABLE_BITS (&p
[-2]) != 0))
3493 /* If we can match a character class, we can match
3494 any character set. */
3496 set_fastmap_for_multibyte_characters
:
3497 if (match_any_multibyte_characters
== false)
3499 for (j
= 0x80; j
< 0xA0; j
++) /* XXX */
3500 if (BASE_LEADING_CODE_P (j
))
3502 match_any_multibyte_characters
= true;
3506 else if (!not && CHARSET_RANGE_TABLE_EXISTS_P (&p
[-2])
3507 && match_any_multibyte_characters
== false)
3509 /* Set fastmap[I] 1 where I is a base leading code of each
3510 multibyte character in the range table. */
3513 /* Make P points the range table. `+ 2' is to skip flag
3514 bits for a character class. */
3515 p
+= CHARSET_BITMAP_SIZE (&p
[-2]) + 2;
3517 /* Extract the number of ranges in range table into COUNT. */
3518 EXTRACT_NUMBER_AND_INCR (count
, p
);
3519 for (; count
> 0; count
--, p
+= 2 * 3) /* XXX */
3521 /* Extract the start of each range. */
3522 EXTRACT_CHARACTER (c
, p
);
3523 j
= CHAR_CHARSET (c
);
3524 fastmap
[CHARSET_LEADING_CODE_BASE (j
)] = 1;
3531 if (!fastmap
) break;
3533 not = (re_opcode_t
)p
[-1] == notsyntaxspec
;
3535 for (j
= 0; j
< (1 << BYTEWIDTH
); j
++)
3536 if ((SYNTAX (j
) == (enum syntaxcode
) k
) ^ not)
3540 /* This match depends on text properties. These end with
3541 aborting optimizations. */
3542 return (RESET_FAIL_STACK (), -1);
3545 case notcategoryspec
:
3546 if (!fastmap
) break;
3547 not = (re_opcode_t
)p
[-1] == notcategoryspec
;
3549 for (j
= 0; j
< (1 << BYTEWIDTH
); j
++)
3550 if ((CHAR_HAS_CATEGORY (j
, k
)) ^ not)
3554 /* Any character set can possibly contain a character
3555 whose category is K (or not). */
3556 goto set_fastmap_for_multibyte_characters
;
3559 /* All cases after this match the empty string. These end with
3579 EXTRACT_NUMBER_AND_INCR (j
, p
);
3581 /* Backward jumps can only go back to code that we've already
3582 visited. `re_compile' should make sure this is true. */
3585 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *p
))
3587 case on_failure_jump
:
3588 case on_failure_keep_string_jump
:
3589 case on_failure_jump_loop
:
3590 case on_failure_jump_nastyloop
:
3591 case on_failure_jump_smart
:
3597 /* Keep `p1' to allow the `on_failure_jump' we are jumping to
3598 to jump back to "just after here". */
3601 case on_failure_jump
:
3602 case on_failure_keep_string_jump
:
3603 case on_failure_jump_nastyloop
:
3604 case on_failure_jump_loop
:
3605 case on_failure_jump_smart
:
3606 EXTRACT_NUMBER_AND_INCR (j
, p
);
3608 ; /* Backward jump to be ignored. */
3609 else if (!PUSH_PATTERN_OP (p
+ j
, fail_stack
))
3610 return (RESET_FAIL_STACK (), -2);
3615 /* This code simply does not properly handle forward jump_n. */
3616 DEBUG_STATEMENT (EXTRACT_NUMBER (j
, p
); assert (j
< 0));
3618 /* jump_n can either jump or fall through. The (backward) jump
3619 case has already been handled, so we only need to look at the
3620 fallthrough case. */
3624 /* If N == 0, it should be an on_failure_jump_loop instead. */
3625 DEBUG_STATEMENT (EXTRACT_NUMBER (j
, p
+ 2); assert (j
> 0));
3627 /* We only care about one iteration of the loop, so we don't
3628 need to consider the case where this behaves like an
3645 abort (); /* We have listed all the cases. */
3648 /* Getting here means we have found the possible starting
3649 characters for one path of the pattern -- and that the empty
3650 string does not match. We need not follow this path further.
3651 Instead, look at the next alternative (remembered on the
3652 stack), or quit if no more. The test at the top of the loop
3653 does these things. */
3654 path_can_be_null
= false;
3658 return (RESET_FAIL_STACK (), 0);
3659 } /* analyse_first */
3661 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
3662 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
3663 characters can start a string that matches the pattern. This fastmap
3664 is used by re_search to skip quickly over impossible starting points.
3666 Character codes above (1 << BYTEWIDTH) are not represented in the
3667 fastmap, but the leading codes are represented. Thus, the fastmap
3668 indicates which character sets could start a match.
3670 The caller must supply the address of a (1 << BYTEWIDTH)-byte data
3671 area as BUFP->fastmap.
3673 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
3676 Returns 0 if we succeed, -2 if an internal error. */
3679 re_compile_fastmap (bufp
)
3680 struct re_pattern_buffer
*bufp
;
3682 char *fastmap
= bufp
->fastmap
;
3685 assert (fastmap
&& bufp
->buffer
);
3687 bzero (fastmap
, 1 << BYTEWIDTH
); /* Assume nothing's valid. */
3688 bufp
->fastmap_accurate
= 1; /* It will be when we're done. */
3690 analysis
= analyse_first (bufp
->buffer
, bufp
->buffer
+ bufp
->used
,
3691 fastmap
, RE_MULTIBYTE_P (bufp
));
3694 bufp
->can_be_null
= (analysis
!= 0);
3696 } /* re_compile_fastmap */
3698 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
3699 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
3700 this memory for recording register information. STARTS and ENDS
3701 must be allocated using the malloc library routine, and must each
3702 be at least NUM_REGS * sizeof (regoff_t) bytes long.
3704 If NUM_REGS == 0, then subsequent matches should allocate their own
3707 Unless this function is called, the first search or match using
3708 PATTERN_BUFFER will allocate its own register data, without
3709 freeing the old data. */
3712 re_set_registers (bufp
, regs
, num_regs
, starts
, ends
)
3713 struct re_pattern_buffer
*bufp
;
3714 struct re_registers
*regs
;
3716 regoff_t
*starts
, *ends
;
3720 bufp
->regs_allocated
= REGS_REALLOCATE
;
3721 regs
->num_regs
= num_regs
;
3722 regs
->start
= starts
;
3727 bufp
->regs_allocated
= REGS_UNALLOCATED
;
3729 regs
->start
= regs
->end
= (regoff_t
*) 0;
3733 /* Searching routines. */
3735 /* Like re_search_2, below, but only one string is specified, and
3736 doesn't let you say where to stop matching. */
3739 re_search (bufp
, string
, size
, startpos
, range
, regs
)
3740 struct re_pattern_buffer
*bufp
;
3742 int size
, startpos
, range
;
3743 struct re_registers
*regs
;
3745 return re_search_2 (bufp
, NULL
, 0, string
, size
, startpos
, range
,
3749 /* End address of virtual concatenation of string. */
3750 #define STOP_ADDR_VSTRING(P) \
3751 (((P) >= size1 ? string2 + size2 : string1 + size1))
3753 /* Address of POS in the concatenation of virtual string. */
3754 #define POS_ADDR_VSTRING(POS) \
3755 (((POS) >= size1 ? string2 - size1 : string1) + (POS))
3757 /* Using the compiled pattern in BUFP->buffer, first tries to match the
3758 virtual concatenation of STRING1 and STRING2, starting first at index
3759 STARTPOS, then at STARTPOS + 1, and so on.
3761 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
3763 RANGE is how far to scan while trying to match. RANGE = 0 means try
3764 only at STARTPOS; in general, the last start tried is STARTPOS +
3767 In REGS, return the indices of the virtual concatenation of STRING1
3768 and STRING2 that matched the entire BUFP->buffer and its contained
3771 Do not consider matching one past the index STOP in the virtual
3772 concatenation of STRING1 and STRING2.
3774 We return either the position in the strings at which the match was
3775 found, -1 if no match, or -2 if error (such as failure
3779 re_search_2 (bufp
, str1
, size1
, str2
, size2
, startpos
, range
, regs
, stop
)
3780 struct re_pattern_buffer
*bufp
;
3781 const char *str1
, *str2
;
3785 struct re_registers
*regs
;
3789 re_char
*string1
= (re_char
*) str1
;
3790 re_char
*string2
= (re_char
*) str2
;
3791 register char *fastmap
= bufp
->fastmap
;
3792 register RE_TRANSLATE_TYPE translate
= bufp
->translate
;
3793 int total_size
= size1
+ size2
;
3794 int endpos
= startpos
+ range
;
3795 int anchored_start
= 0;
3797 /* Nonzero if we have to concern multibyte character. */
3798 const boolean multibyte
= RE_MULTIBYTE_P (bufp
);
3800 /* Check for out-of-range STARTPOS. */
3801 if (startpos
< 0 || startpos
> total_size
)
3804 /* Fix up RANGE if it might eventually take us outside
3805 the virtual concatenation of STRING1 and STRING2.
3806 Make sure we won't move STARTPOS below 0 or above TOTAL_SIZE. */
3808 range
= 0 - startpos
;
3809 else if (endpos
> total_size
)
3810 range
= total_size
- startpos
;
3812 /* If the search isn't to be a backwards one, don't waste time in a
3813 search for a pattern anchored at beginning of buffer. */
3814 if (bufp
->used
> 0 && (re_opcode_t
) bufp
->buffer
[0] == begbuf
&& range
> 0)
3823 /* In a forward search for something that starts with \=.
3824 don't keep searching past point. */
3825 if (bufp
->used
> 0 && (re_opcode_t
) bufp
->buffer
[0] == at_dot
&& range
> 0)
3827 range
= PT_BYTE
- BEGV_BYTE
- startpos
;
3833 /* Update the fastmap now if not correct already. */
3834 if (fastmap
&& !bufp
->fastmap_accurate
)
3835 if (re_compile_fastmap (bufp
) == -2)
3838 /* See whether the pattern is anchored. */
3839 if (bufp
->buffer
[0] == begline
)
3843 gl_state
.object
= re_match_object
;
3845 int charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (startpos
));
3847 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object
, charpos
, 1);
3851 /* Loop through the string, looking for a place to start matching. */
3854 /* If the pattern is anchored,
3855 skip quickly past places we cannot match.
3856 We don't bother to treat startpos == 0 specially
3857 because that case doesn't repeat. */
3858 if (anchored_start
&& startpos
> 0)
3860 if (! (bufp
->newline_anchor
3861 && ((startpos
<= size1
? string1
[startpos
- 1]
3862 : string2
[startpos
- size1
- 1])
3867 /* If a fastmap is supplied, skip quickly over characters that
3868 cannot be the start of a match. If the pattern can match the
3869 null string, however, we don't need to skip characters; we want
3870 the first null string. */
3871 if (fastmap
&& startpos
< total_size
&& !bufp
->can_be_null
)
3873 register re_char
*d
;
3874 register unsigned int buf_ch
;
3876 d
= POS_ADDR_VSTRING (startpos
);
3878 if (range
> 0) /* Searching forwards. */
3880 register int lim
= 0;
3883 if (startpos
< size1
&& startpos
+ range
>= size1
)
3884 lim
= range
- (size1
- startpos
);
3886 /* Written out as an if-else to avoid testing `translate'
3888 if (RE_TRANSLATE_P (translate
))
3895 buf_ch
= STRING_CHAR_AND_LENGTH (d
, range
- lim
,
3898 buf_ch
= RE_TRANSLATE (translate
, buf_ch
);
3903 range
-= buf_charlen
;
3908 && !fastmap
[RE_TRANSLATE (translate
, *d
)])
3915 while (range
> lim
&& !fastmap
[*d
])
3921 startpos
+= irange
- range
;
3923 else /* Searching backwards. */
3925 int room
= (startpos
>= size1
3926 ? size2
+ size1
- startpos
3927 : size1
- startpos
);
3928 buf_ch
= RE_STRING_CHAR (d
, room
);
3929 buf_ch
= TRANSLATE (buf_ch
);
3931 if (! (buf_ch
>= 0400
3932 || fastmap
[buf_ch
]))
3937 /* If can't match the null string, and that's all we have left, fail. */
3938 if (range
>= 0 && startpos
== total_size
&& fastmap
3939 && !bufp
->can_be_null
)
3942 val
= re_match_2_internal (bufp
, string1
, size1
, string2
, size2
,
3943 startpos
, regs
, stop
);
3944 #ifndef REGEX_MALLOC
3961 /* Update STARTPOS to the next character boundary. */
3964 re_char
*p
= POS_ADDR_VSTRING (startpos
);
3965 re_char
*pend
= STOP_ADDR_VSTRING (startpos
);
3966 int len
= MULTIBYTE_FORM_LENGTH (p
, pend
- p
);
3984 /* Update STARTPOS to the previous character boundary. */
3987 re_char
*p
= POS_ADDR_VSTRING (startpos
);
3990 /* Find the head of multibyte form. */
3991 while (!CHAR_HEAD_P (*p
))
3996 if (MULTIBYTE_FORM_LENGTH (p
, len
+ 1) != (len
+ 1))
4013 /* Declarations and macros for re_match_2. */
4015 static int bcmp_translate
_RE_ARGS((re_char
*s1
, re_char
*s2
,
4017 RE_TRANSLATE_TYPE translate
,
4018 const int multibyte
));
4020 /* This converts PTR, a pointer into one of the search strings `string1'
4021 and `string2' into an offset from the beginning of that string. */
4022 #define POINTER_TO_OFFSET(ptr) \
4023 (FIRST_STRING_P (ptr) \
4024 ? ((regoff_t) ((ptr) - string1)) \
4025 : ((regoff_t) ((ptr) - string2 + size1)))
4027 /* Call before fetching a character with *d. This switches over to
4028 string2 if necessary.
4029 Check re_match_2_internal for a discussion of why end_match_2 might
4030 not be within string2 (but be equal to end_match_1 instead). */
4031 #define PREFETCH() \
4034 /* End of string2 => fail. */ \
4035 if (dend == end_match_2) \
4037 /* End of string1 => advance to string2. */ \
4039 dend = end_match_2; \
4042 /* Call before fetching a char with *d if you already checked other limits.
4043 This is meant for use in lookahead operations like wordend, etc..
4044 where we might need to look at parts of the string that might be
4045 outside of the LIMITs (i.e past `stop'). */
4046 #define PREFETCH_NOLIMIT() \
4050 dend = end_match_2; \
4053 /* Test if at very beginning or at very end of the virtual concatenation
4054 of `string1' and `string2'. If only one string, it's `string2'. */
4055 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
4056 #define AT_STRINGS_END(d) ((d) == end2)
4059 /* Test if D points to a character which is word-constituent. We have
4060 two special cases to check for: if past the end of string1, look at
4061 the first character in string2; and if before the beginning of
4062 string2, look at the last character in string1. */
4063 #define WORDCHAR_P(d) \
4064 (SYNTAX ((d) == end1 ? *string2 \
4065 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
4068 /* Disabled due to a compiler bug -- see comment at case wordbound */
4070 /* The comment at case wordbound is following one, but we don't use
4071 AT_WORD_BOUNDARY anymore to support multibyte form.
4073 The DEC Alpha C compiler 3.x generates incorrect code for the
4074 test WORDCHAR_P (d - 1) != WORDCHAR_P (d) in the expansion of
4075 AT_WORD_BOUNDARY, so this code is disabled. Expanding the
4076 macro and introducing temporary variables works around the bug. */
4079 /* Test if the character before D and the one at D differ with respect
4080 to being word-constituent. */
4081 #define AT_WORD_BOUNDARY(d) \
4082 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
4083 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
4086 /* Free everything we malloc. */
4087 #ifdef MATCH_MAY_ALLOCATE
4088 # define FREE_VAR(var) if (var) { REGEX_FREE (var); var = NULL; } else
4089 # define FREE_VARIABLES() \
4091 REGEX_FREE_STACK (fail_stack.stack); \
4092 FREE_VAR (regstart); \
4093 FREE_VAR (regend); \
4094 FREE_VAR (best_regstart); \
4095 FREE_VAR (best_regend); \
4098 # define FREE_VARIABLES() ((void)0) /* Do nothing! But inhibit gcc warning. */
4099 #endif /* not MATCH_MAY_ALLOCATE */
4102 /* Optimization routines. */
4104 /* If the operation is a match against one or more chars,
4105 return a pointer to the next operation, else return NULL. */
4106 static unsigned char *
4110 switch (SWITCH_ENUM_CAST (*p
++))
4121 if (CHARSET_RANGE_TABLE_EXISTS_P (p
- 1))
4124 p
= CHARSET_RANGE_TABLE (p
- 1);
4125 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
4126 p
= CHARSET_RANGE_TABLE_END (p
, mcnt
);
4129 p
+= 1 + CHARSET_BITMAP_SIZE (p
- 1);
4136 case notcategoryspec
:
4148 /* Jump over non-matching operations. */
4149 static unsigned char *
4150 skip_noops (p
, pend
)
4151 unsigned char *p
, *pend
;
4156 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *p
))
4165 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
4176 /* Non-zero if "p1 matches something" implies "p2 fails". */
4178 mutually_exclusive_p (bufp
, p1
, p2
)
4179 struct re_pattern_buffer
*bufp
;
4180 unsigned char *p1
, *p2
;
4183 const boolean multibyte
= RE_MULTIBYTE_P (bufp
);
4184 unsigned char *pend
= bufp
->buffer
+ bufp
->used
;
4186 assert (p1
>= bufp
->buffer
&& p1
< pend
4187 && p2
>= bufp
->buffer
&& p2
<= pend
);
4189 /* Skip over open/close-group commands.
4190 If what follows this loop is a ...+ construct,
4191 look at what begins its body, since we will have to
4192 match at least one of that. */
4193 p2
= skip_noops (p2
, pend
);
4194 /* The same skip can be done for p1, except that this function
4195 is only used in the case where p1 is a simple match operator. */
4196 /* p1 = skip_noops (p1, pend); */
4198 assert (p1
>= bufp
->buffer
&& p1
< pend
4199 && p2
>= bufp
->buffer
&& p2
<= pend
);
4201 op2
= p2
== pend
? succeed
: *p2
;
4203 switch (SWITCH_ENUM_CAST (op2
))
4207 /* If we're at the end of the pattern, we can change. */
4208 if (skip_one_char (p1
))
4210 DEBUG_PRINT1 (" End of pattern: fast loop.\n");
4216 if (!bufp
->newline_anchor
)
4221 register unsigned int c
4222 = (re_opcode_t
) *p2
== endline
? '\n'
4223 : RE_STRING_CHAR(p2
+ 2, pend
- p2
- 2);
4225 if ((re_opcode_t
) *p1
== exactn
)
4227 if (c
!= RE_STRING_CHAR (p1
+ 2, pend
- p1
- 2))
4229 DEBUG_PRINT3 (" '%c' != '%c' => fast loop.\n", c
, p1
[2]);
4234 else if ((re_opcode_t
) *p1
== charset
4235 || (re_opcode_t
) *p1
== charset_not
)
4237 int not = (re_opcode_t
) *p1
== charset_not
;
4239 /* Test if C is listed in charset (or charset_not)
4241 if (SINGLE_BYTE_CHAR_P (c
))
4243 if (c
< CHARSET_BITMAP_SIZE (p1
) * BYTEWIDTH
4244 && p1
[2 + c
/ BYTEWIDTH
] & (1 << (c
% BYTEWIDTH
)))
4247 else if (CHARSET_RANGE_TABLE_EXISTS_P (p1
))
4248 CHARSET_LOOKUP_RANGE_TABLE (not, c
, p1
);
4250 /* `not' is equal to 1 if c would match, which means
4251 that we can't change to pop_failure_jump. */
4254 DEBUG_PRINT1 (" No match => fast loop.\n");
4258 else if ((re_opcode_t
) *p1
== anychar
4261 DEBUG_PRINT1 (" . != \\n => fast loop.\n");
4270 if ((re_opcode_t
) *p1
== exactn
)
4271 /* Reuse the code above. */
4272 return mutually_exclusive_p (bufp
, p2
, p1
);
4275 /* It is hard to list up all the character in charset
4276 P2 if it includes multibyte character. Give up in
4278 else if (!multibyte
|| !CHARSET_RANGE_TABLE_EXISTS_P (p2
))
4280 /* Now, we are sure that P2 has no range table.
4281 So, for the size of bitmap in P2, `p2[1]' is
4282 enough. But P1 may have range table, so the
4283 size of bitmap table of P1 is extracted by
4284 using macro `CHARSET_BITMAP_SIZE'.
4286 Since we know that all the character listed in
4287 P2 is ASCII, it is enough to test only bitmap
4293 /* We win if the charset inside the loop
4294 has no overlap with the one after the loop. */
4297 && idx
< CHARSET_BITMAP_SIZE (p1
));
4299 if ((p2
[2 + idx
] & p1
[2 + idx
]) != 0)
4303 || idx
== CHARSET_BITMAP_SIZE (p1
))
4305 DEBUG_PRINT1 (" No match => fast loop.\n");
4309 else if ((re_opcode_t
) *p1
== charset
4310 || (re_opcode_t
) *p1
== charset_not
)
4313 /* We win if the charset_not inside the loop lists
4314 every character listed in the charset after. */
4315 for (idx
= 0; idx
< (int) p2
[1]; idx
++)
4316 if (! (p2
[2 + idx
] == 0
4317 || (idx
< CHARSET_BITMAP_SIZE (p1
)
4318 && ((p2
[2 + idx
] & ~ p1
[2 + idx
]) == 0))))
4323 DEBUG_PRINT1 (" No match => fast loop.\n");
4332 return ((re_opcode_t
) *p1
== syntaxspec
4333 && p1
[1] == (op2
== wordend
? Sword
: p2
[1]));
4337 return ((re_opcode_t
) *p1
== notsyntaxspec
4338 && p1
[1] == (op2
== wordend
? Sword
: p2
[1]));
4341 return (((re_opcode_t
) *p1
== notsyntaxspec
4342 || (re_opcode_t
) *p1
== syntaxspec
)
4347 return ((re_opcode_t
) *p1
== notcategoryspec
&& p1
[1] == p2
[1]);
4348 case notcategoryspec
:
4349 return ((re_opcode_t
) *p1
== categoryspec
&& p1
[1] == p2
[1]);
4361 /* Matching routines. */
4363 #ifndef emacs /* Emacs never uses this. */
4364 /* re_match is like re_match_2 except it takes only a single string. */
4367 re_match (bufp
, string
, size
, pos
, regs
)
4368 struct re_pattern_buffer
*bufp
;
4371 struct re_registers
*regs
;
4373 int result
= re_match_2_internal (bufp
, NULL
, 0, (re_char
*) string
, size
,
4375 # if defined C_ALLOCA && !defined REGEX_MALLOC
4380 #endif /* not emacs */
4383 /* In Emacs, this is the string or buffer in which we
4384 are matching. It is used for looking up syntax properties. */
4385 Lisp_Object re_match_object
;
4388 /* re_match_2 matches the compiled pattern in BUFP against the
4389 the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
4390 and SIZE2, respectively). We start matching at POS, and stop
4393 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
4394 store offsets for the substring each group matched in REGS. See the
4395 documentation for exactly how many groups we fill.
4397 We return -1 if no match, -2 if an internal error (such as the
4398 failure stack overflowing). Otherwise, we return the length of the
4399 matched substring. */
4402 re_match_2 (bufp
, string1
, size1
, string2
, size2
, pos
, regs
, stop
)
4403 struct re_pattern_buffer
*bufp
;
4404 const char *string1
, *string2
;
4407 struct re_registers
*regs
;
4414 gl_state
.object
= re_match_object
;
4415 charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (pos
));
4416 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object
, charpos
, 1);
4419 result
= re_match_2_internal (bufp
, (re_char
*) string1
, size1
,
4420 (re_char
*) string2
, size2
,
4422 #if defined C_ALLOCA && !defined REGEX_MALLOC
4428 /* This is a separate function so that we can force an alloca cleanup
4431 re_match_2_internal (bufp
, string1
, size1
, string2
, size2
, pos
, regs
, stop
)
4432 struct re_pattern_buffer
*bufp
;
4433 re_char
*string1
, *string2
;
4436 struct re_registers
*regs
;
4439 /* General temporaries. */
4444 /* Just past the end of the corresponding string. */
4445 re_char
*end1
, *end2
;
4447 /* Pointers into string1 and string2, just past the last characters in
4448 each to consider matching. */
4449 re_char
*end_match_1
, *end_match_2
;
4451 /* Where we are in the data, and the end of the current string. */
4454 /* Used sometimes to remember where we were before starting matching
4455 an operator so that we can go back in case of failure. This "atomic"
4456 behavior of matching opcodes is indispensable to the correctness
4457 of the on_failure_keep_string_jump optimization. */
4460 /* Where we are in the pattern, and the end of the pattern. */
4461 unsigned char *p
= bufp
->buffer
;
4462 register unsigned char *pend
= p
+ bufp
->used
;
4464 /* We use this to map every character in the string. */
4465 RE_TRANSLATE_TYPE translate
= bufp
->translate
;
4467 /* Nonzero if we have to concern multibyte character. */
4468 const boolean multibyte
= RE_MULTIBYTE_P (bufp
);
4470 /* Failure point stack. Each place that can handle a failure further
4471 down the line pushes a failure point on this stack. It consists of
4472 regstart, and regend for all registers corresponding to
4473 the subexpressions we're currently inside, plus the number of such
4474 registers, and, finally, two char *'s. The first char * is where
4475 to resume scanning the pattern; the second one is where to resume
4476 scanning the strings. */
4477 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
4478 fail_stack_type fail_stack
;
4481 unsigned nfailure_points_pushed
= 0, nfailure_points_popped
= 0;
4484 #if defined REL_ALLOC && defined REGEX_MALLOC
4485 /* This holds the pointer to the failure stack, when
4486 it is allocated relocatably. */
4487 fail_stack_elt_t
*failure_stack_ptr
;
4490 /* We fill all the registers internally, independent of what we
4491 return, for use in backreferences. The number here includes
4492 an element for register zero. */
4493 size_t num_regs
= bufp
->re_nsub
+ 1;
4495 /* Information on the contents of registers. These are pointers into
4496 the input strings; they record just what was matched (on this
4497 attempt) by a subexpression part of the pattern, that is, the
4498 regnum-th regstart pointer points to where in the pattern we began
4499 matching and the regnum-th regend points to right after where we
4500 stopped matching the regnum-th subexpression. (The zeroth register
4501 keeps track of what the whole pattern matches.) */
4502 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4503 re_char
**regstart
, **regend
;
4506 /* The following record the register info as found in the above
4507 variables when we find a match better than any we've seen before.
4508 This happens as we backtrack through the failure points, which in
4509 turn happens only if we have not yet matched the entire string. */
4510 unsigned best_regs_set
= false;
4511 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4512 re_char
**best_regstart
, **best_regend
;
4515 /* Logically, this is `best_regend[0]'. But we don't want to have to
4516 allocate space for that if we're not allocating space for anything
4517 else (see below). Also, we never need info about register 0 for
4518 any of the other register vectors, and it seems rather a kludge to
4519 treat `best_regend' differently than the rest. So we keep track of
4520 the end of the best match so far in a separate variable. We
4521 initialize this to NULL so that when we backtrack the first time
4522 and need to test it, it's not garbage. */
4523 re_char
*match_end
= NULL
;
4526 /* Counts the total number of registers pushed. */
4527 unsigned num_regs_pushed
= 0;
4530 DEBUG_PRINT1 ("\n\nEntering re_match_2.\n");
4534 #ifdef MATCH_MAY_ALLOCATE
4535 /* Do not bother to initialize all the register variables if there are
4536 no groups in the pattern, as it takes a fair amount of time. If
4537 there are groups, we include space for register 0 (the whole
4538 pattern), even though we never use it, since it simplifies the
4539 array indexing. We should fix this. */
4542 regstart
= REGEX_TALLOC (num_regs
, re_char
*);
4543 regend
= REGEX_TALLOC (num_regs
, re_char
*);
4544 best_regstart
= REGEX_TALLOC (num_regs
, re_char
*);
4545 best_regend
= REGEX_TALLOC (num_regs
, re_char
*);
4547 if (!(regstart
&& regend
&& best_regstart
&& best_regend
))
4555 /* We must initialize all our variables to NULL, so that
4556 `FREE_VARIABLES' doesn't try to free them. */
4557 regstart
= regend
= best_regstart
= best_regend
= NULL
;
4559 #endif /* MATCH_MAY_ALLOCATE */
4561 /* The starting position is bogus. */
4562 if (pos
< 0 || pos
> size1
+ size2
)
4568 /* Initialize subexpression text positions to -1 to mark ones that no
4569 start_memory/stop_memory has been seen for. Also initialize the
4570 register information struct. */
4571 for (mcnt
= 1; mcnt
< num_regs
; mcnt
++)
4572 regstart
[mcnt
] = regend
[mcnt
] = NULL
;
4574 /* We move `string1' into `string2' if the latter's empty -- but not if
4575 `string1' is null. */
4576 if (size2
== 0 && string1
!= NULL
)
4583 end1
= string1
+ size1
;
4584 end2
= string2
+ size2
;
4586 /* `p' scans through the pattern as `d' scans through the data.
4587 `dend' is the end of the input string that `d' points within. `d'
4588 is advanced into the following input string whenever necessary, but
4589 this happens before fetching; therefore, at the beginning of the
4590 loop, `d' can be pointing at the end of a string, but it cannot
4594 /* Only match within string2. */
4595 d
= string2
+ pos
- size1
;
4596 dend
= end_match_2
= string2
+ stop
- size1
;
4597 end_match_1
= end1
; /* Just to give it a value. */
4603 /* Only match within string1. */
4604 end_match_1
= string1
+ stop
;
4606 When we reach end_match_1, PREFETCH normally switches to string2.
4607 But in the present case, this means that just doing a PREFETCH
4608 makes us jump from `stop' to `gap' within the string.
4609 What we really want here is for the search to stop as
4610 soon as we hit end_match_1. That's why we set end_match_2
4611 to end_match_1 (since PREFETCH fails as soon as we hit
4613 end_match_2
= end_match_1
;
4616 { /* It's important to use this code when stop == size so that
4617 moving `d' from end1 to string2 will not prevent the d == dend
4618 check from catching the end of string. */
4620 end_match_2
= string2
+ stop
- size1
;
4626 DEBUG_PRINT1 ("The compiled pattern is: ");
4627 DEBUG_PRINT_COMPILED_PATTERN (bufp
, p
, pend
);
4628 DEBUG_PRINT1 ("The string to match is: `");
4629 DEBUG_PRINT_DOUBLE_STRING (d
, string1
, size1
, string2
, size2
);
4630 DEBUG_PRINT1 ("'\n");
4632 /* This loops over pattern commands. It exits by returning from the
4633 function if the match is complete, or it drops through if the match
4634 fails at this starting point in the input data. */
4637 DEBUG_PRINT2 ("\n%p: ", p
);
4640 { /* End of pattern means we might have succeeded. */
4641 DEBUG_PRINT1 ("end of pattern ... ");
4643 /* If we haven't matched the entire string, and we want the
4644 longest match, try backtracking. */
4645 if (d
!= end_match_2
)
4647 /* 1 if this match ends in the same string (string1 or string2)
4648 as the best previous match. */
4649 boolean same_str_p
= (FIRST_STRING_P (match_end
)
4650 == FIRST_STRING_P (d
));
4651 /* 1 if this match is the best seen so far. */
4652 boolean best_match_p
;
4654 /* AIX compiler got confused when this was combined
4655 with the previous declaration. */
4657 best_match_p
= d
> match_end
;
4659 best_match_p
= !FIRST_STRING_P (d
);
4661 DEBUG_PRINT1 ("backtracking.\n");
4663 if (!FAIL_STACK_EMPTY ())
4664 { /* More failure points to try. */
4666 /* If exceeds best match so far, save it. */
4667 if (!best_regs_set
|| best_match_p
)
4669 best_regs_set
= true;
4672 DEBUG_PRINT1 ("\nSAVING match as best so far.\n");
4674 for (mcnt
= 1; mcnt
< num_regs
; mcnt
++)
4676 best_regstart
[mcnt
] = regstart
[mcnt
];
4677 best_regend
[mcnt
] = regend
[mcnt
];
4683 /* If no failure points, don't restore garbage. And if
4684 last match is real best match, don't restore second
4686 else if (best_regs_set
&& !best_match_p
)
4689 /* Restore best match. It may happen that `dend ==
4690 end_match_1' while the restored d is in string2.
4691 For example, the pattern `x.*y.*z' against the
4692 strings `x-' and `y-z-', if the two strings are
4693 not consecutive in memory. */
4694 DEBUG_PRINT1 ("Restoring best registers.\n");
4697 dend
= ((d
>= string1
&& d
<= end1
)
4698 ? end_match_1
: end_match_2
);
4700 for (mcnt
= 1; mcnt
< num_regs
; mcnt
++)
4702 regstart
[mcnt
] = best_regstart
[mcnt
];
4703 regend
[mcnt
] = best_regend
[mcnt
];
4706 } /* d != end_match_2 */
4709 DEBUG_PRINT1 ("Accepting match.\n");
4711 /* If caller wants register contents data back, do it. */
4712 if (regs
&& !bufp
->no_sub
)
4714 /* Have the register data arrays been allocated? */
4715 if (bufp
->regs_allocated
== REGS_UNALLOCATED
)
4716 { /* No. So allocate them with malloc. We need one
4717 extra element beyond `num_regs' for the `-1' marker
4719 regs
->num_regs
= MAX (RE_NREGS
, num_regs
+ 1);
4720 regs
->start
= TALLOC (regs
->num_regs
, regoff_t
);
4721 regs
->end
= TALLOC (regs
->num_regs
, regoff_t
);
4722 if (regs
->start
== NULL
|| regs
->end
== NULL
)
4727 bufp
->regs_allocated
= REGS_REALLOCATE
;
4729 else if (bufp
->regs_allocated
== REGS_REALLOCATE
)
4730 { /* Yes. If we need more elements than were already
4731 allocated, reallocate them. If we need fewer, just
4733 if (regs
->num_regs
< num_regs
+ 1)
4735 regs
->num_regs
= num_regs
+ 1;
4736 RETALLOC (regs
->start
, regs
->num_regs
, regoff_t
);
4737 RETALLOC (regs
->end
, regs
->num_regs
, regoff_t
);
4738 if (regs
->start
== NULL
|| regs
->end
== NULL
)
4747 /* These braces fend off a "empty body in an else-statement"
4748 warning under GCC when assert expands to nothing. */
4749 assert (bufp
->regs_allocated
== REGS_FIXED
);
4752 /* Convert the pointer data in `regstart' and `regend' to
4753 indices. Register zero has to be set differently,
4754 since we haven't kept track of any info for it. */
4755 if (regs
->num_regs
> 0)
4757 regs
->start
[0] = pos
;
4758 regs
->end
[0] = POINTER_TO_OFFSET (d
);
4761 /* Go through the first `min (num_regs, regs->num_regs)'
4762 registers, since that is all we initialized. */
4763 for (mcnt
= 1; mcnt
< MIN (num_regs
, regs
->num_regs
); mcnt
++)
4765 if (REG_UNSET (regstart
[mcnt
]) || REG_UNSET (regend
[mcnt
]))
4766 regs
->start
[mcnt
] = regs
->end
[mcnt
] = -1;
4770 = (regoff_t
) POINTER_TO_OFFSET (regstart
[mcnt
]);
4772 = (regoff_t
) POINTER_TO_OFFSET (regend
[mcnt
]);
4776 /* If the regs structure we return has more elements than
4777 were in the pattern, set the extra elements to -1. If
4778 we (re)allocated the registers, this is the case,
4779 because we always allocate enough to have at least one
4781 for (mcnt
= num_regs
; mcnt
< regs
->num_regs
; mcnt
++)
4782 regs
->start
[mcnt
] = regs
->end
[mcnt
] = -1;
4783 } /* regs && !bufp->no_sub */
4785 DEBUG_PRINT4 ("%u failure points pushed, %u popped (%u remain).\n",
4786 nfailure_points_pushed
, nfailure_points_popped
,
4787 nfailure_points_pushed
- nfailure_points_popped
);
4788 DEBUG_PRINT2 ("%u registers pushed.\n", num_regs_pushed
);
4790 mcnt
= POINTER_TO_OFFSET (d
) - pos
;
4792 DEBUG_PRINT2 ("Returning %d from re_match_2.\n", mcnt
);
4798 /* Otherwise match next pattern command. */
4799 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *p
++))
4801 /* Ignore these. Used to ignore the n of succeed_n's which
4802 currently have n == 0. */
4804 DEBUG_PRINT1 ("EXECUTING no_op.\n");
4808 DEBUG_PRINT1 ("EXECUTING succeed.\n");
4811 /* Match the next n pattern characters exactly. The following
4812 byte in the pattern defines n, and the n bytes after that
4813 are the characters to match. */
4816 DEBUG_PRINT2 ("EXECUTING exactn %d.\n", mcnt
);
4818 /* Remember the start point to rollback upon failure. */
4821 /* This is written out as an if-else so we don't waste time
4822 testing `translate' inside the loop. */
4823 if (RE_TRANSLATE_P (translate
))
4828 int pat_charlen
, buf_charlen
;
4829 unsigned int pat_ch
, buf_ch
;
4832 pat_ch
= STRING_CHAR_AND_LENGTH (p
, pend
- p
, pat_charlen
);
4833 buf_ch
= STRING_CHAR_AND_LENGTH (d
, dend
- d
, buf_charlen
);
4835 if (RE_TRANSLATE (translate
, buf_ch
)
4844 mcnt
-= pat_charlen
;
4851 if (RE_TRANSLATE (translate
, *d
) != *p
++)
4876 /* Match any character except possibly a newline or a null. */
4880 unsigned int buf_ch
;
4882 DEBUG_PRINT1 ("EXECUTING anychar.\n");
4885 buf_ch
= RE_STRING_CHAR_AND_LENGTH (d
, dend
- d
, buf_charlen
);
4886 buf_ch
= TRANSLATE (buf_ch
);
4888 if ((!(bufp
->syntax
& RE_DOT_NEWLINE
)
4890 || ((bufp
->syntax
& RE_DOT_NOT_NULL
)
4891 && buf_ch
== '\000'))
4894 DEBUG_PRINT2 (" Matched `%d'.\n", *d
);
4903 register unsigned int c
;
4904 boolean
not = (re_opcode_t
) *(p
- 1) == charset_not
;
4907 /* Start of actual range_table, or end of bitmap if there is no
4909 unsigned char *range_table
;
4911 /* Nonzero if there is a range table. */
4912 int range_table_exists
;
4914 /* Number of ranges of range table. This is not included
4915 in the initial byte-length of the command. */
4918 DEBUG_PRINT2 ("EXECUTING charset%s.\n", not ? "_not" : "");
4920 range_table_exists
= CHARSET_RANGE_TABLE_EXISTS_P (&p
[-1]);
4922 if (range_table_exists
)
4924 range_table
= CHARSET_RANGE_TABLE (&p
[-1]); /* Past the bitmap. */
4925 EXTRACT_NUMBER_AND_INCR (count
, range_table
);
4929 c
= RE_STRING_CHAR_AND_LENGTH (d
, dend
- d
, len
);
4930 c
= TRANSLATE (c
); /* The character to match. */
4932 if (SINGLE_BYTE_CHAR_P (c
))
4933 { /* Lookup bitmap. */
4934 /* Cast to `unsigned' instead of `unsigned char' in
4935 case the bit list is a full 32 bytes long. */
4936 if (c
< (unsigned) (CHARSET_BITMAP_SIZE (&p
[-1]) * BYTEWIDTH
)
4937 && p
[1 + c
/ BYTEWIDTH
] & (1 << (c
% BYTEWIDTH
)))
4941 else if (range_table_exists
)
4943 int class_bits
= CHARSET_RANGE_TABLE_BITS (&p
[-1]);
4945 if ( (class_bits
& BIT_ALNUM
&& ISALNUM (c
))
4946 | (class_bits
& BIT_ALPHA
&& ISALPHA (c
))
4947 | (class_bits
& BIT_ASCII
&& IS_REAL_ASCII (c
))
4948 | (class_bits
& BIT_GRAPH
&& ISGRAPH (c
))
4949 | (class_bits
& BIT_LOWER
&& ISLOWER (c
))
4950 | (class_bits
& BIT_MULTIBYTE
&& !ISUNIBYTE (c
))
4951 | (class_bits
& BIT_NONASCII
&& !IS_REAL_ASCII (c
))
4952 | (class_bits
& BIT_PRINT
&& ISPRINT (c
))
4953 | (class_bits
& BIT_PUNCT
&& ISPUNCT (c
))
4954 | (class_bits
& BIT_SPACE
&& ISSPACE (c
))
4955 | (class_bits
& BIT_UNIBYTE
&& ISUNIBYTE (c
))
4956 | (class_bits
& BIT_UPPER
&& ISUPPER (c
))
4957 | (class_bits
& BIT_WORD
&& ISWORD (c
)))
4960 CHARSET_LOOKUP_RANGE_TABLE_RAW (not, c
, range_table
, count
);
4964 if (range_table_exists
)
4965 p
= CHARSET_RANGE_TABLE_END (range_table
, count
);
4967 p
+= CHARSET_BITMAP_SIZE (&p
[-1]) + 1;
4969 if (!not) goto fail
;
4976 /* The beginning of a group is represented by start_memory.
4977 The argument is the register number. The text
4978 matched within the group is recorded (in the internal
4979 registers data structure) under the register number. */
4981 DEBUG_PRINT2 ("EXECUTING start_memory %d:\n", *p
);
4983 /* In case we need to undo this operation (via backtracking). */
4984 PUSH_FAILURE_REG ((unsigned int)*p
);
4987 regend
[*p
] = NULL
; /* probably unnecessary. -sm */
4988 DEBUG_PRINT2 (" regstart: %d\n", POINTER_TO_OFFSET (regstart
[*p
]));
4990 /* Move past the register number and inner group count. */
4995 /* The stop_memory opcode represents the end of a group. Its
4996 argument is the same as start_memory's: the register number. */
4998 DEBUG_PRINT2 ("EXECUTING stop_memory %d:\n", *p
);
5000 assert (!REG_UNSET (regstart
[*p
]));
5001 /* Strictly speaking, there should be code such as:
5003 assert (REG_UNSET (regend[*p]));
5004 PUSH_FAILURE_REGSTOP ((unsigned int)*p);
5006 But the only info to be pushed is regend[*p] and it is known to
5007 be UNSET, so there really isn't anything to push.
5008 Not pushing anything, on the other hand deprives us from the
5009 guarantee that regend[*p] is UNSET since undoing this operation
5010 will not reset its value properly. This is not important since
5011 the value will only be read on the next start_memory or at
5012 the very end and both events can only happen if this stop_memory
5016 DEBUG_PRINT2 (" regend: %d\n", POINTER_TO_OFFSET (regend
[*p
]));
5018 /* Move past the register number and the inner group count. */
5023 /* \<digit> has been turned into a `duplicate' command which is
5024 followed by the numeric value of <digit> as the register number. */
5027 register re_char
*d2
, *dend2
;
5028 int regno
= *p
++; /* Get which register to match against. */
5029 DEBUG_PRINT2 ("EXECUTING duplicate %d.\n", regno
);
5031 /* Can't back reference a group which we've never matched. */
5032 if (REG_UNSET (regstart
[regno
]) || REG_UNSET (regend
[regno
]))
5035 /* Where in input to try to start matching. */
5036 d2
= regstart
[regno
];
5038 /* Remember the start point to rollback upon failure. */
5041 /* Where to stop matching; if both the place to start and
5042 the place to stop matching are in the same string, then
5043 set to the place to stop, otherwise, for now have to use
5044 the end of the first string. */
5046 dend2
= ((FIRST_STRING_P (regstart
[regno
])
5047 == FIRST_STRING_P (regend
[regno
]))
5048 ? regend
[regno
] : end_match_1
);
5051 /* If necessary, advance to next segment in register
5055 if (dend2
== end_match_2
) break;
5056 if (dend2
== regend
[regno
]) break;
5058 /* End of string1 => advance to string2. */
5060 dend2
= regend
[regno
];
5062 /* At end of register contents => success */
5063 if (d2
== dend2
) break;
5065 /* If necessary, advance to next segment in data. */
5068 /* How many characters left in this segment to match. */
5071 /* Want how many consecutive characters we can match in
5072 one shot, so, if necessary, adjust the count. */
5073 if (mcnt
> dend2
- d2
)
5076 /* Compare that many; failure if mismatch, else move
5078 if (RE_TRANSLATE_P (translate
)
5079 ? bcmp_translate (d
, d2
, mcnt
, translate
, multibyte
)
5080 : memcmp (d
, d2
, mcnt
))
5085 d
+= mcnt
, d2
+= mcnt
;
5091 /* begline matches the empty string at the beginning of the string
5092 (unless `not_bol' is set in `bufp'), and, if
5093 `newline_anchor' is set, after newlines. */
5095 DEBUG_PRINT1 ("EXECUTING begline.\n");
5097 if (AT_STRINGS_BEG (d
))
5099 if (!bufp
->not_bol
) break;
5104 GET_CHAR_BEFORE_2 (c
, d
, string1
, end1
, string2
, end2
);
5105 if (c
== '\n' && bufp
->newline_anchor
)
5108 /* In all other cases, we fail. */
5112 /* endline is the dual of begline. */
5114 DEBUG_PRINT1 ("EXECUTING endline.\n");
5116 if (AT_STRINGS_END (d
))
5118 if (!bufp
->not_eol
) break;
5122 PREFETCH_NOLIMIT ();
5123 if (*d
== '\n' && bufp
->newline_anchor
)
5129 /* Match at the very beginning of the data. */
5131 DEBUG_PRINT1 ("EXECUTING begbuf.\n");
5132 if (AT_STRINGS_BEG (d
))
5137 /* Match at the very end of the data. */
5139 DEBUG_PRINT1 ("EXECUTING endbuf.\n");
5140 if (AT_STRINGS_END (d
))
5145 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
5146 pushes NULL as the value for the string on the stack. Then
5147 `POP_FAILURE_POINT' will keep the current value for the
5148 string, instead of restoring it. To see why, consider
5149 matching `foo\nbar' against `.*\n'. The .* matches the foo;
5150 then the . fails against the \n. But the next thing we want
5151 to do is match the \n against the \n; if we restored the
5152 string value, we would be back at the foo.
5154 Because this is used only in specific cases, we don't need to
5155 check all the things that `on_failure_jump' does, to make
5156 sure the right things get saved on the stack. Hence we don't
5157 share its code. The only reason to push anything on the
5158 stack at all is that otherwise we would have to change
5159 `anychar's code to do something besides goto fail in this
5160 case; that seems worse than this. */
5161 case on_failure_keep_string_jump
:
5162 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5163 DEBUG_PRINT3 ("EXECUTING on_failure_keep_string_jump %d (to %p):\n",
5166 PUSH_FAILURE_POINT (p
- 3, NULL
);
5169 /* A nasty loop is introduced by the non-greedy *? and +?.
5170 With such loops, the stack only ever contains one failure point
5171 at a time, so that a plain on_failure_jump_loop kind of
5172 cycle detection cannot work. Worse yet, such a detection
5173 can not only fail to detect a cycle, but it can also wrongly
5174 detect a cycle (between different instantiations of the same
5176 So the method used for those nasty loops is a little different:
5177 We use a special cycle-detection-stack-frame which is pushed
5178 when the on_failure_jump_nastyloop failure-point is *popped*.
5179 This special frame thus marks the beginning of one iteration
5180 through the loop and we can hence easily check right here
5181 whether something matched between the beginning and the end of
5183 case on_failure_jump_nastyloop
:
5184 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5185 DEBUG_PRINT3 ("EXECUTING on_failure_jump_nastyloop %d (to %p):\n",
5188 assert ((re_opcode_t
)p
[-4] == no_op
);
5189 CHECK_INFINITE_LOOP (p
- 4, d
);
5190 PUSH_FAILURE_POINT (p
- 3, d
);
5194 /* Simple loop detecting on_failure_jump: just check on the
5195 failure stack if the same spot was already hit earlier. */
5196 case on_failure_jump_loop
:
5198 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5199 DEBUG_PRINT3 ("EXECUTING on_failure_jump_loop %d (to %p):\n",
5202 CHECK_INFINITE_LOOP (p
- 3, d
);
5203 PUSH_FAILURE_POINT (p
- 3, d
);
5207 /* Uses of on_failure_jump:
5209 Each alternative starts with an on_failure_jump that points
5210 to the beginning of the next alternative. Each alternative
5211 except the last ends with a jump that in effect jumps past
5212 the rest of the alternatives. (They really jump to the
5213 ending jump of the following alternative, because tensioning
5214 these jumps is a hassle.)
5216 Repeats start with an on_failure_jump that points past both
5217 the repetition text and either the following jump or
5218 pop_failure_jump back to this on_failure_jump. */
5219 case on_failure_jump
:
5221 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5222 DEBUG_PRINT3 ("EXECUTING on_failure_jump %d (to %p):\n",
5225 PUSH_FAILURE_POINT (p
-3, d
);
5228 /* This operation is used for greedy *.
5229 Compare the beginning of the repeat with what in the
5230 pattern follows its end. If we can establish that there
5231 is nothing that they would both match, i.e., that we
5232 would have to backtrack because of (as in, e.g., `a*a')
5233 then we can use a non-backtracking loop based on
5234 on_failure_keep_string_jump instead of on_failure_jump. */
5235 case on_failure_jump_smart
:
5237 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5238 DEBUG_PRINT3 ("EXECUTING on_failure_jump_smart %d (to %p).\n",
5241 unsigned char *p1
= p
; /* Next operation. */
5242 unsigned char *p2
= p
+ mcnt
; /* Destination of the jump. */
5244 p
-= 3; /* Reset so that we will re-execute the
5245 instruction once it's been changed. */
5247 EXTRACT_NUMBER (mcnt
, p2
- 2);
5249 /* Ensure this is a indeed the trivial kind of loop
5250 we are expecting. */
5251 assert (skip_one_char (p1
) == p2
- 3);
5252 assert ((re_opcode_t
) p2
[-3] == jump
&& p2
+ mcnt
== p
);
5253 DEBUG_STATEMENT (debug
+= 2);
5254 if (mutually_exclusive_p (bufp
, p1
, p2
))
5256 /* Use a fast `on_failure_keep_string_jump' loop. */
5257 DEBUG_PRINT1 (" smart exclusive => fast loop.\n");
5258 *p
= (unsigned char) on_failure_keep_string_jump
;
5259 STORE_NUMBER (p2
- 2, mcnt
+ 3);
5263 /* Default to a safe `on_failure_jump' loop. */
5264 DEBUG_PRINT1 (" smart default => slow loop.\n");
5265 *p
= (unsigned char) on_failure_jump
;
5267 DEBUG_STATEMENT (debug
-= 2);
5271 /* Unconditionally jump (without popping any failure points). */
5275 EXTRACT_NUMBER_AND_INCR (mcnt
, p
); /* Get the amount to jump. */
5276 DEBUG_PRINT2 ("EXECUTING jump %d ", mcnt
);
5277 p
+= mcnt
; /* Do the jump. */
5278 DEBUG_PRINT2 ("(to %p).\n", p
);
5282 /* Have to succeed matching what follows at least n times.
5283 After that, handle like `on_failure_jump'. */
5285 EXTRACT_NUMBER (mcnt
, p
+ 2);
5286 DEBUG_PRINT2 ("EXECUTING succeed_n %d.\n", mcnt
);
5288 /* Originally, mcnt is how many times we HAVE to succeed. */
5293 PUSH_FAILURE_COUNT (p
);
5294 DEBUG_PRINT3 (" Setting %p to %d.\n", p
, mcnt
);
5295 STORE_NUMBER_AND_INCR (p
, mcnt
);
5298 /* The two bytes encoding mcnt == 0 are two no_op opcodes. */
5303 EXTRACT_NUMBER (mcnt
, p
+ 2);
5304 DEBUG_PRINT2 ("EXECUTING jump_n %d.\n", mcnt
);
5306 /* Originally, this is how many times we CAN jump. */
5310 PUSH_FAILURE_COUNT (p
+ 2);
5311 STORE_NUMBER (p
+ 2, mcnt
);
5312 goto unconditional_jump
;
5314 /* If don't have to jump any more, skip over the rest of command. */
5321 DEBUG_PRINT1 ("EXECUTING set_number_at.\n");
5323 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5325 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5326 DEBUG_PRINT3 (" Setting %p to %d.\n", p1
, mcnt
);
5327 PUSH_FAILURE_COUNT (p1
);
5328 STORE_NUMBER (p1
, mcnt
);
5334 not = (re_opcode_t
) *(p
- 1) == notwordbound
;
5335 DEBUG_PRINT2 ("EXECUTING %swordbound.\n", not?"not":"");
5337 /* We SUCCEED (or FAIL) in one of the following cases: */
5339 /* Case 1: D is at the beginning or the end of string. */
5340 if (AT_STRINGS_BEG (d
) || AT_STRINGS_END (d
))
5344 /* C1 is the character before D, S1 is the syntax of C1, C2
5345 is the character at D, and S2 is the syntax of C2. */
5348 int offset
= PTR_TO_OFFSET (d
- 1);
5349 int charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
5350 UPDATE_SYNTAX_TABLE (charpos
);
5352 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
5355 UPDATE_SYNTAX_TABLE_FORWARD (charpos
+ 1);
5357 PREFETCH_NOLIMIT ();
5358 c2
= RE_STRING_CHAR (d
, dend
- d
);
5361 if (/* Case 2: Only one of S1 and S2 is Sword. */
5362 ((s1
== Sword
) != (s2
== Sword
))
5363 /* Case 3: Both of S1 and S2 are Sword, and macro
5364 WORD_BOUNDARY_P (C1, C2) returns nonzero. */
5365 || ((s1
== Sword
) && WORD_BOUNDARY_P (c1
, c2
)))
5374 DEBUG_PRINT1 ("EXECUTING wordbeg.\n");
5376 /* We FAIL in one of the following cases: */
5378 /* Case 1: D is at the end of string. */
5379 if (AT_STRINGS_END (d
))
5383 /* C1 is the character before D, S1 is the syntax of C1, C2
5384 is the character at D, and S2 is the syntax of C2. */
5387 int offset
= PTR_TO_OFFSET (d
);
5388 int charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
5389 UPDATE_SYNTAX_TABLE (charpos
);
5392 c2
= RE_STRING_CHAR (d
, dend
- d
);
5395 /* Case 2: S2 is not Sword. */
5399 /* Case 3: D is not at the beginning of string ... */
5400 if (!AT_STRINGS_BEG (d
))
5402 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
5404 UPDATE_SYNTAX_TABLE_BACKWARD (charpos
- 1);
5408 /* ... and S1 is Sword, and WORD_BOUNDARY_P (C1, C2)
5410 if ((s1
== Sword
) && !WORD_BOUNDARY_P (c1
, c2
))
5417 DEBUG_PRINT1 ("EXECUTING wordend.\n");
5419 /* We FAIL in one of the following cases: */
5421 /* Case 1: D is at the beginning of string. */
5422 if (AT_STRINGS_BEG (d
))
5426 /* C1 is the character before D, S1 is the syntax of C1, C2
5427 is the character at D, and S2 is the syntax of C2. */
5430 int offset
= PTR_TO_OFFSET (d
) - 1;
5431 int charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
5432 UPDATE_SYNTAX_TABLE (charpos
);
5434 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
5437 /* Case 2: S1 is not Sword. */
5441 /* Case 3: D is not at the end of string ... */
5442 if (!AT_STRINGS_END (d
))
5444 PREFETCH_NOLIMIT ();
5445 c2
= RE_STRING_CHAR (d
, dend
- d
);
5447 UPDATE_SYNTAX_TABLE_FORWARD (charpos
);
5451 /* ... and S2 is Sword, and WORD_BOUNDARY_P (C1, C2)
5453 if ((s2
== Sword
) && !WORD_BOUNDARY_P (c1
, c2
))
5461 not = (re_opcode_t
) *(p
- 1) == notsyntaxspec
;
5463 DEBUG_PRINT3 ("EXECUTING %ssyntaxspec %d.\n", not?"not":"", mcnt
);
5467 int offset
= PTR_TO_OFFSET (d
);
5468 int pos1
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
5469 UPDATE_SYNTAX_TABLE (pos1
);
5475 c
= RE_STRING_CHAR_AND_LENGTH (d
, dend
- d
, len
);
5477 if ((SYNTAX (c
) != (enum syntaxcode
) mcnt
) ^ not)
5485 DEBUG_PRINT1 ("EXECUTING before_dot.\n");
5486 if (PTR_BYTE_POS (d
) >= PT_BYTE
)
5491 DEBUG_PRINT1 ("EXECUTING at_dot.\n");
5492 if (PTR_BYTE_POS (d
) != PT_BYTE
)
5497 DEBUG_PRINT1 ("EXECUTING after_dot.\n");
5498 if (PTR_BYTE_POS (d
) <= PT_BYTE
)
5503 case notcategoryspec
:
5504 not = (re_opcode_t
) *(p
- 1) == notcategoryspec
;
5506 DEBUG_PRINT3 ("EXECUTING %scategoryspec %d.\n", not?"not":"", mcnt
);
5510 c
= RE_STRING_CHAR_AND_LENGTH (d
, dend
- d
, len
);
5512 if ((!CHAR_HAS_CATEGORY (c
, mcnt
)) ^ not)
5523 continue; /* Successfully executed one pattern command; keep going. */
5526 /* We goto here if a matching operation fails. */
5529 if (!FAIL_STACK_EMPTY ())
5533 /* A restart point is known. Restore to that state. */
5534 DEBUG_PRINT1 ("\nFAIL:\n");
5535 POP_FAILURE_POINT (str
, pat
);
5536 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *pat
++))
5538 case on_failure_keep_string_jump
:
5539 assert (str
== NULL
);
5540 goto continue_failure_jump
;
5542 case on_failure_jump_nastyloop
:
5543 assert ((re_opcode_t
)pat
[-2] == no_op
);
5544 PUSH_FAILURE_POINT (pat
- 2, str
);
5547 case on_failure_jump_loop
:
5548 case on_failure_jump
:
5551 continue_failure_jump
:
5552 EXTRACT_NUMBER_AND_INCR (mcnt
, pat
);
5557 /* A special frame used for nastyloops. */
5564 assert (p
>= bufp
->buffer
&& p
<= pend
);
5566 if (d
>= string1
&& d
<= end1
)
5570 break; /* Matching at this starting point really fails. */
5574 goto restore_best_regs
;
5578 return -1; /* Failure to match. */
5581 /* Subroutine definitions for re_match_2. */
5583 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
5584 bytes; nonzero otherwise. */
5587 bcmp_translate (s1
, s2
, len
, translate
, multibyte
)
5590 RE_TRANSLATE_TYPE translate
;
5591 const int multibyte
;
5593 register re_char
*p1
= s1
, *p2
= s2
;
5594 re_char
*p1_end
= s1
+ len
;
5595 re_char
*p2_end
= s2
+ len
;
5597 /* FIXME: Checking both p1 and p2 presumes that the two strings might have
5598 different lengths, but relying on a single `len' would break this. -sm */
5599 while (p1
< p1_end
&& p2
< p2_end
)
5601 int p1_charlen
, p2_charlen
;
5604 p1_ch
= RE_STRING_CHAR_AND_LENGTH (p1
, p1_end
- p1
, p1_charlen
);
5605 p2_ch
= RE_STRING_CHAR_AND_LENGTH (p2
, p2_end
- p2
, p2_charlen
);
5607 if (RE_TRANSLATE (translate
, p1_ch
)
5608 != RE_TRANSLATE (translate
, p2_ch
))
5611 p1
+= p1_charlen
, p2
+= p2_charlen
;
5614 if (p1
!= p1_end
|| p2
!= p2_end
)
5620 /* Entry points for GNU code. */
5622 /* re_compile_pattern is the GNU regular expression compiler: it
5623 compiles PATTERN (of length SIZE) and puts the result in BUFP.
5624 Returns 0 if the pattern was valid, otherwise an error string.
5626 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
5627 are set in BUFP on entry.
5629 We call regex_compile to do the actual compilation. */
5632 re_compile_pattern (pattern
, length
, bufp
)
5633 const char *pattern
;
5635 struct re_pattern_buffer
*bufp
;
5639 /* GNU code is written to assume at least RE_NREGS registers will be set
5640 (and at least one extra will be -1). */
5641 bufp
->regs_allocated
= REGS_UNALLOCATED
;
5643 /* And GNU code determines whether or not to get register information
5644 by passing null for the REGS argument to re_match, etc., not by
5648 /* Match anchors at newline. */
5649 bufp
->newline_anchor
= 1;
5651 ret
= regex_compile ((re_char
*) pattern
, length
, re_syntax_options
, bufp
);
5655 return gettext (re_error_msgid
[(int) ret
]);
5658 /* Entry points compatible with 4.2 BSD regex library. We don't define
5659 them unless specifically requested. */
5661 #if defined _REGEX_RE_COMP || defined _LIBC
5663 /* BSD has one and only one pattern buffer. */
5664 static struct re_pattern_buffer re_comp_buf
;
5668 /* Make these definitions weak in libc, so POSIX programs can redefine
5669 these names if they don't use our functions, and still use
5670 regcomp/regexec below without link errors. */
5680 if (!re_comp_buf
.buffer
)
5681 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
5682 return (char *) gettext ("No previous regular expression");
5686 if (!re_comp_buf
.buffer
)
5688 re_comp_buf
.buffer
= (unsigned char *) malloc (200);
5689 if (re_comp_buf
.buffer
== NULL
)
5690 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
5691 return (char *) gettext (re_error_msgid
[(int) REG_ESPACE
]);
5692 re_comp_buf
.allocated
= 200;
5694 re_comp_buf
.fastmap
= (char *) malloc (1 << BYTEWIDTH
);
5695 if (re_comp_buf
.fastmap
== NULL
)
5696 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
5697 return (char *) gettext (re_error_msgid
[(int) REG_ESPACE
]);
5700 /* Since `re_exec' always passes NULL for the `regs' argument, we
5701 don't need to initialize the pattern buffer fields which affect it. */
5703 /* Match anchors at newlines. */
5704 re_comp_buf
.newline_anchor
= 1;
5706 ret
= regex_compile (s
, strlen (s
), re_syntax_options
, &re_comp_buf
);
5711 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
5712 return (char *) gettext (re_error_msgid
[(int) ret
]);
5723 const int len
= strlen (s
);
5725 0 <= re_search (&re_comp_buf
, s
, len
, 0, len
, (struct re_registers
*) 0);
5727 #endif /* _REGEX_RE_COMP */
5729 /* POSIX.2 functions. Don't define these for Emacs. */
5733 /* regcomp takes a regular expression as a string and compiles it.
5735 PREG is a regex_t *. We do not expect any fields to be initialized,
5736 since POSIX says we shouldn't. Thus, we set
5738 `buffer' to the compiled pattern;
5739 `used' to the length of the compiled pattern;
5740 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
5741 REG_EXTENDED bit in CFLAGS is set; otherwise, to
5742 RE_SYNTAX_POSIX_BASIC;
5743 `newline_anchor' to REG_NEWLINE being set in CFLAGS;
5744 `fastmap' and `fastmap_accurate' to zero;
5745 `re_nsub' to the number of subexpressions in PATTERN.
5747 PATTERN is the address of the pattern string.
5749 CFLAGS is a series of bits which affect compilation.
5751 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
5752 use POSIX basic syntax.
5754 If REG_NEWLINE is set, then . and [^...] don't match newline.
5755 Also, regexec will try a match beginning after every newline.
5757 If REG_ICASE is set, then we considers upper- and lowercase
5758 versions of letters to be equivalent when matching.
5760 If REG_NOSUB is set, then when PREG is passed to regexec, that
5761 routine will report only success or failure, and nothing about the
5764 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
5765 the return codes and their meanings.) */
5768 regcomp (preg
, pattern
, cflags
)
5770 const char *pattern
;
5775 = (cflags
& REG_EXTENDED
) ?
5776 RE_SYNTAX_POSIX_EXTENDED
: RE_SYNTAX_POSIX_BASIC
;
5778 /* regex_compile will allocate the space for the compiled pattern. */
5780 preg
->allocated
= 0;
5783 /* Don't bother to use a fastmap when searching. This simplifies the
5784 REG_NEWLINE case: if we used a fastmap, we'd have to put all the
5785 characters after newlines into the fastmap. This way, we just try
5789 if (cflags
& REG_ICASE
)
5794 = (RE_TRANSLATE_TYPE
) malloc (CHAR_SET_SIZE
5795 * sizeof (*(RE_TRANSLATE_TYPE
)0));
5796 if (preg
->translate
== NULL
)
5797 return (int) REG_ESPACE
;
5799 /* Map uppercase characters to corresponding lowercase ones. */
5800 for (i
= 0; i
< CHAR_SET_SIZE
; i
++)
5801 preg
->translate
[i
] = ISUPPER (i
) ? TOLOWER (i
) : i
;
5804 preg
->translate
= NULL
;
5806 /* If REG_NEWLINE is set, newlines are treated differently. */
5807 if (cflags
& REG_NEWLINE
)
5808 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
5809 syntax
&= ~RE_DOT_NEWLINE
;
5810 syntax
|= RE_HAT_LISTS_NOT_NEWLINE
;
5811 /* It also changes the matching behavior. */
5812 preg
->newline_anchor
= 1;
5815 preg
->newline_anchor
= 0;
5817 preg
->no_sub
= !!(cflags
& REG_NOSUB
);
5819 /* POSIX says a null character in the pattern terminates it, so we
5820 can use strlen here in compiling the pattern. */
5821 ret
= regex_compile ((re_char
*) pattern
, strlen (pattern
), syntax
, preg
);
5823 /* POSIX doesn't distinguish between an unmatched open-group and an
5824 unmatched close-group: both are REG_EPAREN. */
5825 if (ret
== REG_ERPAREN
) ret
= REG_EPAREN
;
5831 /* regexec searches for a given pattern, specified by PREG, in the
5834 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
5835 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
5836 least NMATCH elements, and we set them to the offsets of the
5837 corresponding matched substrings.
5839 EFLAGS specifies `execution flags' which affect matching: if
5840 REG_NOTBOL is set, then ^ does not match at the beginning of the
5841 string; if REG_NOTEOL is set, then $ does not match at the end.
5843 We return 0 if we find a match and REG_NOMATCH if not. */
5846 regexec (preg
, string
, nmatch
, pmatch
, eflags
)
5847 const regex_t
*preg
;
5850 regmatch_t pmatch
[];
5854 struct re_registers regs
;
5855 regex_t private_preg
;
5856 int len
= strlen (string
);
5857 boolean want_reg_info
= !preg
->no_sub
&& nmatch
> 0;
5859 private_preg
= *preg
;
5861 private_preg
.not_bol
= !!(eflags
& REG_NOTBOL
);
5862 private_preg
.not_eol
= !!(eflags
& REG_NOTEOL
);
5864 /* The user has told us exactly how many registers to return
5865 information about, via `nmatch'. We have to pass that on to the
5866 matching routines. */
5867 private_preg
.regs_allocated
= REGS_FIXED
;
5871 regs
.num_regs
= nmatch
;
5872 regs
.start
= TALLOC (nmatch
* 2, regoff_t
);
5873 if (regs
.start
== NULL
)
5874 return (int) REG_NOMATCH
;
5875 regs
.end
= regs
.start
+ nmatch
;
5878 /* Perform the searching operation. */
5879 ret
= re_search (&private_preg
, string
, len
,
5880 /* start: */ 0, /* range: */ len
,
5881 want_reg_info
? ®s
: (struct re_registers
*) 0);
5883 /* Copy the register information to the POSIX structure. */
5890 for (r
= 0; r
< nmatch
; r
++)
5892 pmatch
[r
].rm_so
= regs
.start
[r
];
5893 pmatch
[r
].rm_eo
= regs
.end
[r
];
5897 /* If we needed the temporary register info, free the space now. */
5901 /* We want zero return to mean success, unlike `re_search'. */
5902 return ret
>= 0 ? (int) REG_NOERROR
: (int) REG_NOMATCH
;
5906 /* Returns a message corresponding to an error code, ERRCODE, returned
5907 from either regcomp or regexec. We don't use PREG here. */
5910 regerror (errcode
, preg
, errbuf
, errbuf_size
)
5912 const regex_t
*preg
;
5920 || errcode
>= (sizeof (re_error_msgid
) / sizeof (re_error_msgid
[0])))
5921 /* Only error codes returned by the rest of the code should be passed
5922 to this routine. If we are given anything else, or if other regex
5923 code generates an invalid error code, then the program has a bug.
5924 Dump core so we can fix it. */
5927 msg
= gettext (re_error_msgid
[errcode
]);
5929 msg_size
= strlen (msg
) + 1; /* Includes the null. */
5931 if (errbuf_size
!= 0)
5933 if (msg_size
> errbuf_size
)
5935 strncpy (errbuf
, msg
, errbuf_size
- 1);
5936 errbuf
[errbuf_size
- 1] = 0;
5939 strcpy (errbuf
, msg
);
5946 /* Free dynamically allocated space used by PREG. */
5952 if (preg
->buffer
!= NULL
)
5953 free (preg
->buffer
);
5954 preg
->buffer
= NULL
;
5956 preg
->allocated
= 0;
5959 if (preg
->fastmap
!= NULL
)
5960 free (preg
->fastmap
);
5961 preg
->fastmap
= NULL
;
5962 preg
->fastmap_accurate
= 0;
5964 if (preg
->translate
!= NULL
)
5965 free (preg
->translate
);
5966 preg
->translate
= NULL
;
5969 #endif /* not emacs */