1 /* Extended regular expression matching and search library, version
2 0.12. (Implements POSIX draft P10003.2/D11.2, except for
3 internationalization features.)
5 Copyright (C) 1993,94,95,96,97,98,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]
27 /* AIX requires this to be the first thing in the file. */
28 #if defined (_AIX) && !defined (REGEX_MALLOC)
36 /* Converts the pointer to the char to BEG-based offset from the start. */
37 #define PTR_TO_OFFSET(d) POS_AS_IN_BUFFER (POINTER_TO_OFFSET (d))
38 #define POS_AS_IN_BUFFER(p) ((p) + (NILP (re_match_object) || BUFFERP (re_match_object)))
45 /* We need this for `regex.h', and perhaps for the Emacs include files. */
46 #include <sys/types.h>
48 /* This is for other GNU distributions with internationalized messages. */
49 #if HAVE_LIBINTL_H || defined (_LIBC)
52 # define gettext(msgid) (msgid)
56 /* This define is so xgettext can find the internationalizable
58 #define gettext_noop(String) String
61 /* The `emacs' switch turns on certain matching commands
62 that make sense only in Emacs. */
68 /* Make syntax table lookup grant data in gl_state. */
69 #define SYNTAX_ENTRY_VIA_PROPERTY
75 #define malloc xmalloc
76 #define realloc xrealloc
79 #define RE_MULTIBYTE_P(bufp) ((bufp)->multibyte)
80 #define RE_STRING_CHAR(p, s) \
81 (multibyte ? (STRING_CHAR (p, s)) : (*(p)))
82 #define RE_STRING_CHAR_AND_LENGTH(p, s, len) \
83 (multibyte ? (STRING_CHAR_AND_LENGTH (p, s, len)) : ((len) = 1, *(p)))
85 /* Set C a (possibly multibyte) character before P. P points into a
86 string which is the virtual concatenation of STR1 (which ends at
87 END1) or STR2 (which ends at END2). */
88 #define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
92 re_char *dtemp = (p) == (str2) ? (end1) : (p); \
93 re_char *dlimit = ((p) > (str2) && (p) <= (end2)) ? (str2) : (str1); \
94 while (dtemp-- > dlimit && !CHAR_HEAD_P (*dtemp)); \
95 c = STRING_CHAR (dtemp, (p) - dtemp); \
98 (c = ((p) == (str2) ? (end1) : (p))[-1]); \
102 #else /* not emacs */
104 /* If we are not linking with Emacs proper,
105 we can't use the relocating allocator
106 even if config.h says that we can. */
109 #if defined (STDC_HEADERS) || defined (_LIBC)
116 /* When used in Emacs's lib-src, we need to get bzero and bcopy somehow.
117 If nothing else has been done, use the method below. */
118 #ifdef INHIBIT_STRING_HEADER
119 #if !(defined (HAVE_BZERO) && defined (HAVE_BCOPY))
120 #if !defined (bzero) && !defined (bcopy)
121 #undef INHIBIT_STRING_HEADER
126 /* This is the normal way of making sure we have a bcopy and a bzero.
127 This is used in most programs--a few other programs avoid this
128 by defining INHIBIT_STRING_HEADER. */
129 #ifndef INHIBIT_STRING_HEADER
130 #if defined (HAVE_STRING_H) || defined (STDC_HEADERS) || defined (_LIBC)
133 #define bcmp(s1, s2, n) memcmp ((s1), (s2), (n))
136 #define bcopy(s, d, n) memcpy ((d), (s), (n))
139 #define bzero(s, n) memset ((s), 0, (n))
146 /* Define the syntax stuff for \<, \>, etc. */
148 /* Sword must be nonzero for the wordchar pattern commands in re_match_2. */
149 enum syntaxcode
{ Swhitespace
= 0, Sword
= 1 };
151 #ifdef SWITCH_ENUM_BUG
152 #define SWITCH_ENUM_CAST(x) ((int)(x))
154 #define SWITCH_ENUM_CAST(x) (x)
159 extern char *re_syntax_table
;
161 #else /* not SYNTAX_TABLE */
163 /* How many characters in the character set. */
164 #define CHAR_SET_SIZE 256
166 static char re_syntax_table
[CHAR_SET_SIZE
];
177 bzero (re_syntax_table
, sizeof re_syntax_table
);
179 for (c
= 'a'; c
<= 'z'; c
++)
180 re_syntax_table
[c
] = Sword
;
182 for (c
= 'A'; c
<= 'Z'; c
++)
183 re_syntax_table
[c
] = Sword
;
185 for (c
= '0'; c
<= '9'; c
++)
186 re_syntax_table
[c
] = Sword
;
188 re_syntax_table
['_'] = Sword
;
193 #endif /* not SYNTAX_TABLE */
195 #define SYNTAX(c) re_syntax_table[c]
197 /* Dummy macros for non-Emacs environments. */
198 #define BASE_LEADING_CODE_P(c) (0)
199 #define CHAR_CHARSET(c) 0
200 #define CHARSET_LEADING_CODE_BASE(c) 0
201 #define MAX_MULTIBYTE_LENGTH 1
202 #define RE_MULTIBYTE_P(x) 0
203 #define WORD_BOUNDARY_P(c1, c2) (0)
204 #define CHAR_HEAD_P(p) (1)
205 #define SINGLE_BYTE_CHAR_P(c) (1)
206 #define SAME_CHARSET_P(c1, c2) (1)
207 #define MULTIBYTE_FORM_LENGTH(p, s) (1)
208 #define STRING_CHAR(p, s) (*(p))
209 #define RE_STRING_CHAR STRING_CHAR
210 #define CHAR_STRING(c, s) (*(s) = (c), 1)
211 #define STRING_CHAR_AND_LENGTH(p, s, actual_len) ((actual_len) = 1, *(p))
212 #define RE_STRING_CHAR_AND_LENGTH STRING_CHAR_AND_LENGTH
213 #define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
214 (c = ((p) == (str2) ? *((end1) - 1) : *((p) - 1)))
215 #endif /* not emacs */
218 #define RE_TRANSLATE(TBL, C) ((unsigned char)(TBL)[C])
219 #define RE_TRANSLATE_P(TBL) (TBL)
222 /* Get the interface, including the syntax bits. */
225 /* isalpha etc. are used for the character classes. */
230 /* 1 if C is an ASCII character. */
231 #define IS_REAL_ASCII(c) ((c) < 0200)
233 /* 1 if C is a unibyte character. */
234 #define ISUNIBYTE(c) (SINGLE_BYTE_CHAR_P ((c)))
236 /* The Emacs definitions should not be directly affected by locales. */
238 /* In Emacs, these are only used for single-byte characters. */
239 #define ISDIGIT(c) ((c) >= '0' && (c) <= '9')
240 #define ISCNTRL(c) ((c) < ' ')
241 #define ISXDIGIT(c) (((c) >= '0' && (c) <= '9') \
242 || ((c) >= 'a' && (c) <= 'f') \
243 || ((c) >= 'A' && (c) <= 'F'))
245 /* This is only used for single-byte characters. */
246 #define ISBLANK(c) ((c) == ' ' || (c) == '\t')
248 /* The rest must handle multibyte characters. */
250 #define ISGRAPH(c) (SINGLE_BYTE_CHAR_P (c) \
251 ? (c) > ' ' && !((c) >= 0177 && (c) <= 0237) \
254 #define ISPRINT(c) (SINGLE_BYTE_CHAR_P (c) \
255 ? (c) >= ' ' && !((c) >= 0177 && (c) <= 0237) \
258 #define ISALNUM(c) (IS_REAL_ASCII (c) \
259 ? (((c) >= 'a' && (c) <= 'z') \
260 || ((c) >= 'A' && (c) <= 'Z') \
261 || ((c) >= '0' && (c) <= '9')) \
262 : SYNTAX (c) == Sword)
264 #define ISALPHA(c) (IS_REAL_ASCII (c) \
265 ? (((c) >= 'a' && (c) <= 'z') \
266 || ((c) >= 'A' && (c) <= 'Z')) \
267 : SYNTAX (c) == Sword)
269 #define ISLOWER(c) (LOWERCASEP (c))
271 #define ISPUNCT(c) (IS_REAL_ASCII (c) \
272 ? ((c) > ' ' && (c) < 0177 \
273 && !(((c) >= 'a' && (c) <= 'z') \
274 || ((c) >= 'A' && (c) <= 'Z') \
275 || ((c) >= '0' && (c) <= '9'))) \
276 : SYNTAX (c) != Sword)
278 #define ISSPACE(c) (SYNTAX (c) == Swhitespace)
280 #define ISUPPER(c) (UPPERCASEP (c))
282 #define ISWORD(c) (SYNTAX (c) == Sword)
284 #else /* not emacs */
286 /* Jim Meyering writes:
288 "... Some ctype macros are valid only for character codes that
289 isascii says are ASCII (SGI's IRIX-4.0.5 is one such system --when
290 using /bin/cc or gcc but without giving an ansi option). So, all
291 ctype uses should be through macros like ISPRINT... If
292 STDC_HEADERS is defined, then autoconf has verified that the ctype
293 macros don't need to be guarded with references to isascii. ...
294 Defining isascii to 1 should let any compiler worth its salt
295 eliminate the && through constant folding." */
297 #if defined (STDC_HEADERS) || (!defined (isascii) && !defined (HAVE_ISASCII))
300 #define ISASCII(c) isascii(c)
303 /* 1 if C is an ASCII character. */
304 #define IS_REAL_ASCII(c) ((c) < 0200)
306 /* This distinction is not meaningful, except in Emacs. */
307 #define ISUNIBYTE(c) 1
309 #define ISDIGIT(c) (ISASCII (c) && isdigit (c))
310 #define ISCNTRL(c) (ISASCII (c) && iscntrl (c))
311 #define ISXDIGIT(c) (ISASCII (c) && isxdigit (c))
314 #define ISBLANK(c) (ISASCII (c) && isblank (c))
316 #define ISBLANK(c) ((c) == ' ' || (c) == '\t')
319 #define ISGRAPH(c) (ISASCII (c) && isgraph (c))
321 #define ISGRAPH(c) (ISASCII (c) && isprint (c) && !isspace (c))
324 #define ISPRINT(c) (ISASCII (c) && isprint (c))
325 #define ISDIGIT(c) (ISASCII (c) && isdigit (c))
326 #define ISALNUM(c) (ISASCII (c) && isalnum (c))
327 #define ISALPHA(c) (ISASCII (c) && isalpha (c))
328 #define ISCNTRL(c) (ISASCII (c) && iscntrl (c))
329 #define ISLOWER(c) (ISASCII (c) && islower (c))
330 #define ISPUNCT(c) (ISASCII (c) && ispunct (c))
331 #define ISSPACE(c) (ISASCII (c) && isspace (c))
332 #define ISUPPER(c) (ISASCII (c) && isupper (c))
333 #define ISXDIGIT(c) (ISASCII (c) && isxdigit (c))
335 #define ISWORD(c) ISALPHA(c)
337 #endif /* not emacs */
340 #define NULL (void *)0
343 /* We remove any previous definition of `SIGN_EXTEND_CHAR',
344 since ours (we hope) works properly with all combinations of
345 machines, compilers, `char' and `unsigned char' argument types.
346 (Per Bothner suggested the basic approach.) */
347 #undef SIGN_EXTEND_CHAR
349 #define SIGN_EXTEND_CHAR(c) ((signed char) (c))
350 #else /* not __STDC__ */
351 /* As in Harbison and Steele. */
352 #define SIGN_EXTEND_CHAR(c) ((((unsigned char) (c)) ^ 128) - 128)
355 /* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we
356 use `alloca' instead of `malloc'. This is because using malloc in
357 re_search* or re_match* could cause memory leaks when C-g is used in
358 Emacs; also, malloc is slower and causes storage fragmentation. On
359 the other hand, malloc is more portable, and easier to debug.
361 Because we sometimes use alloca, some routines have to be macros,
362 not functions -- `alloca'-allocated space disappears at the end of the
363 function it is called in. */
367 #define REGEX_ALLOCATE malloc
368 #define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
369 #define REGEX_FREE free
371 #else /* not REGEX_MALLOC */
373 /* Emacs already defines alloca, sometimes. */
376 /* Make alloca work the best possible way. */
378 #define alloca __builtin_alloca
379 #else /* not __GNUC__ */
382 #else /* not __GNUC__ or HAVE_ALLOCA_H */
383 #if 0 /* It is a bad idea to declare alloca. We always cast the result. */
384 #ifndef _AIX /* Already did AIX, up at the top. */
386 #endif /* not _AIX */
388 #endif /* not HAVE_ALLOCA_H */
389 #endif /* not __GNUC__ */
391 #endif /* not alloca */
393 #define REGEX_ALLOCATE alloca
395 /* Assumes a `char *destination' variable. */
396 #define REGEX_REALLOCATE(source, osize, nsize) \
397 (destination = (char *) alloca (nsize), \
398 bcopy (source, destination, osize), \
401 /* No need to do anything to free, after alloca. */
402 #define REGEX_FREE(arg) ((void)0) /* Do nothing! But inhibit gcc warning. */
404 #endif /* not REGEX_MALLOC */
406 /* Define how to allocate the failure stack. */
408 #if defined (REL_ALLOC) && defined (REGEX_MALLOC)
410 #define REGEX_ALLOCATE_STACK(size) \
411 r_alloc (&failure_stack_ptr, (size))
412 #define REGEX_REALLOCATE_STACK(source, osize, nsize) \
413 r_re_alloc (&failure_stack_ptr, (nsize))
414 #define REGEX_FREE_STACK(ptr) \
415 r_alloc_free (&failure_stack_ptr)
417 #else /* not using relocating allocator */
421 #define REGEX_ALLOCATE_STACK malloc
422 #define REGEX_REALLOCATE_STACK(source, osize, nsize) realloc (source, nsize)
423 #define REGEX_FREE_STACK free
425 #else /* not REGEX_MALLOC */
427 #define REGEX_ALLOCATE_STACK alloca
429 #define REGEX_REALLOCATE_STACK(source, osize, nsize) \
430 REGEX_REALLOCATE (source, osize, nsize)
431 /* No need to explicitly free anything. */
432 #define REGEX_FREE_STACK(arg) ((void)0)
434 #endif /* not REGEX_MALLOC */
435 #endif /* not using relocating allocator */
438 /* True if `size1' is non-NULL and PTR is pointing anywhere inside
439 `string1' or just past its end. This works if PTR is NULL, which is
441 #define FIRST_STRING_P(ptr) \
442 (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
444 /* (Re)Allocate N items of type T using malloc, or fail. */
445 #define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
446 #define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
447 #define RETALLOC_IF(addr, n, t) \
448 if (addr) RETALLOC((addr), (n), t); else (addr) = TALLOC ((n), t)
449 #define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
451 #define BYTEWIDTH 8 /* In bits. */
453 #define STREQ(s1, s2) ((strcmp (s1, s2) == 0))
457 #define MAX(a, b) ((a) > (b) ? (a) : (b))
458 #define MIN(a, b) ((a) < (b) ? (a) : (b))
460 /* Type of source-pattern and string chars. */
461 typedef const unsigned char re_char
;
463 typedef char boolean
;
467 static int re_match_2_internal ();
469 /* These are the command codes that appear in compiled regular
470 expressions. Some opcodes are followed by argument bytes. A
471 command code can specify any interpretation whatsoever for its
472 arguments. Zero bytes may appear in the compiled regular expression. */
478 /* Succeed right away--no more backtracking. */
481 /* Followed by one byte giving n, then by n literal bytes. */
484 /* Matches any (more or less) character. */
487 /* Matches any one char belonging to specified set. First
488 following byte is number of bitmap bytes. Then come bytes
489 for a bitmap saying which chars are in. Bits in each byte
490 are ordered low-bit-first. A character is in the set if its
491 bit is 1. A character too large to have a bit in the map is
492 automatically not in the set.
494 If the length byte has the 0x80 bit set, then that stuff
495 is followed by a range table:
496 2 bytes of flags for character sets (low 8 bits, high 8 bits)
497 See RANGE_TABLE_WORK_BITS below.
498 2 bytes, the number of pairs that follow
499 pairs, each 2 multibyte characters,
500 each multibyte character represented as 3 bytes. */
503 /* Same parameters as charset, but match any character that is
504 not one of those specified. */
507 /* Start remembering the text that is matched, for storing in a
508 register. Followed by one byte with the register number, in
509 the range 0 to one less than the pattern buffer's re_nsub
513 /* Stop remembering the text that is matched and store it in a
514 memory register. Followed by one byte with the register
515 number, in the range 0 to one less than `re_nsub' in the
519 /* Match a duplicate of something remembered. Followed by one
520 byte containing the register number. */
523 /* Fail unless at beginning of line. */
526 /* Fail unless at end of line. */
529 /* Succeeds if at beginning of buffer (if emacs) or at beginning
530 of string to be matched (if not). */
533 /* Analogously, for end of buffer/string. */
536 /* Followed by two byte relative address to which to jump. */
539 /* Followed by two-byte relative address of place to resume at
540 in case of failure. */
543 /* Like on_failure_jump, but pushes a placeholder instead of the
544 current string position when executed. */
545 on_failure_keep_string_jump
,
547 /* Just like `on_failure_jump', except that it checks that we
548 don't get stuck in an infinite loop (matching an empty string
550 on_failure_jump_loop
,
552 /* Just like `on_failure_jump_loop', except that it checks for
553 a different kind of loop (the kind that shows up with non-greedy
554 operators). This operation has to be immediately preceded
556 on_failure_jump_nastyloop
,
558 /* A smart `on_failure_jump' used for greedy * and + operators.
559 It analyses the loop before which it is put and if the
560 loop does not require backtracking, it changes itself to
561 `on_failure_keep_string_jump' and short-circuits the loop,
562 else it just defaults to changing itself into `on_failure_jump'.
563 It assumes that it is pointing to just past a `jump'. */
564 on_failure_jump_smart
,
566 /* Followed by two-byte relative address and two-byte number n.
567 After matching N times, jump to the address upon failure.
568 Does not work if N starts at 0: use on_failure_jump_loop
572 /* Followed by two-byte relative address, and two-byte number n.
573 Jump to the address N times, then fail. */
576 /* Set the following two-byte relative address to the
577 subsequent two-byte number. The address *includes* the two
581 wordbeg
, /* Succeeds if at word beginning. */
582 wordend
, /* Succeeds if at word end. */
584 wordbound
, /* Succeeds if at a word boundary. */
585 notwordbound
, /* Succeeds if not at a word boundary. */
587 /* Matches any character whose syntax is specified. Followed by
588 a byte which contains a syntax code, e.g., Sword. */
591 /* Matches any character whose syntax is not that specified. */
595 ,before_dot
, /* Succeeds if before point. */
596 at_dot
, /* Succeeds if at point. */
597 after_dot
, /* Succeeds if after point. */
599 /* Matches any character whose category-set contains the specified
600 category. The operator is followed by a byte which contains a
601 category code (mnemonic ASCII character). */
604 /* Matches any character whose category-set does not contain the
605 specified category. The operator is followed by a byte which
606 contains the category code (mnemonic ASCII character). */
611 /* Common operations on the compiled pattern. */
613 /* Store NUMBER in two contiguous bytes starting at DESTINATION. */
615 #define STORE_NUMBER(destination, number) \
617 (destination)[0] = (number) & 0377; \
618 (destination)[1] = (number) >> 8; \
621 /* Same as STORE_NUMBER, except increment DESTINATION to
622 the byte after where the number is stored. Therefore, DESTINATION
623 must be an lvalue. */
625 #define STORE_NUMBER_AND_INCR(destination, number) \
627 STORE_NUMBER (destination, number); \
628 (destination) += 2; \
631 /* Put into DESTINATION a number stored in two contiguous bytes starting
634 #define EXTRACT_NUMBER(destination, source) \
636 (destination) = *(source) & 0377; \
637 (destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8; \
642 extract_number (dest
, source
)
644 unsigned char *source
;
646 int temp
= SIGN_EXTEND_CHAR (*(source
+ 1));
647 *dest
= *source
& 0377;
651 #ifndef EXTRACT_MACROS /* To debug the macros. */
652 #undef EXTRACT_NUMBER
653 #define EXTRACT_NUMBER(dest, src) extract_number (&dest, src)
654 #endif /* not EXTRACT_MACROS */
658 /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
659 SOURCE must be an lvalue. */
661 #define EXTRACT_NUMBER_AND_INCR(destination, source) \
663 EXTRACT_NUMBER (destination, source); \
669 extract_number_and_incr (destination
, source
)
671 unsigned char **source
;
673 extract_number (destination
, *source
);
677 #ifndef EXTRACT_MACROS
678 #undef EXTRACT_NUMBER_AND_INCR
679 #define EXTRACT_NUMBER_AND_INCR(dest, src) \
680 extract_number_and_incr (&dest, &src)
681 #endif /* not EXTRACT_MACROS */
685 /* Store a multibyte character in three contiguous bytes starting
686 DESTINATION, and increment DESTINATION to the byte after where the
687 character is stored. Therefore, DESTINATION must be an lvalue. */
689 #define STORE_CHARACTER_AND_INCR(destination, character) \
691 (destination)[0] = (character) & 0377; \
692 (destination)[1] = ((character) >> 8) & 0377; \
693 (destination)[2] = (character) >> 16; \
694 (destination) += 3; \
697 /* Put into DESTINATION a character stored in three contiguous bytes
698 starting at SOURCE. */
700 #define EXTRACT_CHARACTER(destination, source) \
702 (destination) = ((source)[0] \
703 | ((source)[1] << 8) \
704 | ((source)[2] << 16)); \
708 /* Macros for charset. */
710 /* Size of bitmap of charset P in bytes. P is a start of charset,
711 i.e. *P is (re_opcode_t) charset or (re_opcode_t) charset_not. */
712 #define CHARSET_BITMAP_SIZE(p) ((p)[1] & 0x7F)
714 /* Nonzero if charset P has range table. */
715 #define CHARSET_RANGE_TABLE_EXISTS_P(p) ((p)[1] & 0x80)
717 /* Return the address of range table of charset P. But not the start
718 of table itself, but the before where the number of ranges is
719 stored. `2 +' means to skip re_opcode_t and size of bitmap,
720 and the 2 bytes of flags at the start of the range table. */
721 #define CHARSET_RANGE_TABLE(p) (&(p)[4 + CHARSET_BITMAP_SIZE (p)])
723 /* Extract the bit flags that start a range table. */
724 #define CHARSET_RANGE_TABLE_BITS(p) \
725 ((p)[2 + CHARSET_BITMAP_SIZE (p)] \
726 + (p)[3 + CHARSET_BITMAP_SIZE (p)] * 0x100)
728 /* Test if C is listed in the bitmap of charset P. */
729 #define CHARSET_LOOKUP_BITMAP(p, c) \
730 ((c) < CHARSET_BITMAP_SIZE (p) * BYTEWIDTH \
731 && (p)[2 + (c) / BYTEWIDTH] & (1 << ((c) % BYTEWIDTH)))
733 /* Return the address of end of RANGE_TABLE. COUNT is number of
734 ranges (which is a pair of (start, end)) in the RANGE_TABLE. `* 2'
735 is start of range and end of range. `* 3' is size of each start
737 #define CHARSET_RANGE_TABLE_END(range_table, count) \
738 ((range_table) + (count) * 2 * 3)
740 /* Test if C is in RANGE_TABLE. A flag NOT is negated if C is in.
741 COUNT is number of ranges in RANGE_TABLE. */
742 #define CHARSET_LOOKUP_RANGE_TABLE_RAW(not, c, range_table, count) \
745 int range_start, range_end; \
747 unsigned char *range_table_end \
748 = CHARSET_RANGE_TABLE_END ((range_table), (count)); \
750 for (p = (range_table); p < range_table_end; p += 2 * 3) \
752 EXTRACT_CHARACTER (range_start, p); \
753 EXTRACT_CHARACTER (range_end, p + 3); \
755 if (range_start <= (c) && (c) <= range_end) \
764 /* Test if C is in range table of CHARSET. The flag NOT is negated if
765 C is listed in it. */
766 #define CHARSET_LOOKUP_RANGE_TABLE(not, c, charset) \
769 /* Number of ranges in range table. */ \
771 unsigned char *range_table = CHARSET_RANGE_TABLE (charset); \
773 EXTRACT_NUMBER_AND_INCR (count, range_table); \
774 CHARSET_LOOKUP_RANGE_TABLE_RAW ((not), (c), range_table, count); \
778 /* If DEBUG is defined, Regex prints many voluminous messages about what
779 it is doing (if the variable `debug' is nonzero). If linked with the
780 main program in `iregex.c', you can enter patterns and strings
781 interactively. And if linked with the main program in `main.c' and
782 the other test files, you can run the already-written tests. */
786 /* We use standard I/O for debugging. */
789 /* It is useful to test things that ``must'' be true when debugging. */
792 static int debug
= -100000;
794 #define DEBUG_STATEMENT(e) e
795 #define DEBUG_PRINT1(x) if (debug > 0) printf (x)
796 #define DEBUG_PRINT2(x1, x2) if (debug > 0) printf (x1, x2)
797 #define DEBUG_PRINT3(x1, x2, x3) if (debug > 0) printf (x1, x2, x3)
798 #define DEBUG_PRINT4(x1, x2, x3, x4) if (debug > 0) printf (x1, x2, x3, x4)
799 #define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
800 if (debug > 0) print_partial_compiled_pattern (s, e)
801 #define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
802 if (debug > 0) print_double_string (w, s1, sz1, s2, sz2)
805 /* Print the fastmap in human-readable form. */
808 print_fastmap (fastmap
)
811 unsigned was_a_range
= 0;
814 while (i
< (1 << BYTEWIDTH
))
820 while (i
< (1 << BYTEWIDTH
) && fastmap
[i
])
836 /* Print a compiled pattern string in human-readable form, starting at
837 the START pointer into it and ending just before the pointer END. */
840 print_partial_compiled_pattern (start
, end
)
841 unsigned char *start
;
845 unsigned char *p
= start
;
846 unsigned char *pend
= end
;
854 /* Loop over pattern commands. */
857 printf ("%d:\t", p
- start
);
859 switch ((re_opcode_t
) *p
++)
871 printf ("/exactn/%d", mcnt
);
881 printf ("/start_memory/%d", *p
++);
885 printf ("/stop_memory/%d", *p
++);
889 printf ("/duplicate/%d", *p
++);
899 register int c
, last
= -100;
900 register int in_range
= 0;
901 int length
= CHARSET_BITMAP_SIZE (p
- 1);
902 int has_range_table
= CHARSET_RANGE_TABLE_EXISTS_P (p
- 1);
904 printf ("/charset [%s",
905 (re_opcode_t
) *(p
- 1) == charset_not
? "^" : "");
907 assert (p
+ *p
< pend
);
909 for (c
= 0; c
< 256; c
++)
911 && (p
[1 + (c
/8)] & (1 << (c
% 8))))
913 /* Are we starting a range? */
914 if (last
+ 1 == c
&& ! in_range
)
919 /* Have we broken a range? */
920 else if (last
+ 1 != c
&& in_range
)
942 printf ("has-range-table");
944 /* ??? Should print the range table; for now, just skip it. */
945 p
+= 2; /* skip range table bits */
946 EXTRACT_NUMBER_AND_INCR (count
, p
);
947 p
= CHARSET_RANGE_TABLE_END (p
, count
);
960 case on_failure_jump
:
961 extract_number_and_incr (&mcnt
, &p
);
962 printf ("/on_failure_jump to %d", p
+ mcnt
- start
);
965 case on_failure_keep_string_jump
:
966 extract_number_and_incr (&mcnt
, &p
);
967 printf ("/on_failure_keep_string_jump to %d", p
+ mcnt
- start
);
970 case on_failure_jump_nastyloop
:
971 extract_number_and_incr (&mcnt
, &p
);
972 printf ("/on_failure_jump_nastyloop to %d", p
+ mcnt
- start
);
975 case on_failure_jump_loop
:
976 extract_number_and_incr (&mcnt
, &p
);
977 printf ("/on_failure_jump_loop to %d", p
+ mcnt
- start
);
980 case on_failure_jump_smart
:
981 extract_number_and_incr (&mcnt
, &p
);
982 printf ("/on_failure_jump_smart to %d", p
+ mcnt
- start
);
986 extract_number_and_incr (&mcnt
, &p
);
987 printf ("/jump to %d", p
+ mcnt
- start
);
991 extract_number_and_incr (&mcnt
, &p
);
992 extract_number_and_incr (&mcnt2
, &p
);
993 printf ("/succeed_n to %d, %d times", p
- 2 + mcnt
- start
, mcnt2
);
997 extract_number_and_incr (&mcnt
, &p
);
998 extract_number_and_incr (&mcnt2
, &p
);
999 printf ("/jump_n to %d, %d times", p
- 2 + mcnt
- start
, mcnt2
);
1003 extract_number_and_incr (&mcnt
, &p
);
1004 extract_number_and_incr (&mcnt2
, &p
);
1005 printf ("/set_number_at location %d to %d", p
- 2 + mcnt
- start
, mcnt2
);
1009 printf ("/wordbound");
1013 printf ("/notwordbound");
1017 printf ("/wordbeg");
1021 printf ("/wordend");
1024 printf ("/syntaxspec");
1026 printf ("/%d", mcnt
);
1030 printf ("/notsyntaxspec");
1032 printf ("/%d", mcnt
);
1037 printf ("/before_dot");
1045 printf ("/after_dot");
1049 printf ("/categoryspec");
1051 printf ("/%d", mcnt
);
1054 case notcategoryspec
:
1055 printf ("/notcategoryspec");
1057 printf ("/%d", mcnt
);
1070 printf ("?%d", *(p
-1));
1076 printf ("%d:\tend of pattern.\n", p
- start
);
1081 print_compiled_pattern (bufp
)
1082 struct re_pattern_buffer
*bufp
;
1084 unsigned char *buffer
= bufp
->buffer
;
1086 print_partial_compiled_pattern (buffer
, buffer
+ bufp
->used
);
1087 printf ("%ld bytes used/%ld bytes allocated.\n", bufp
->used
, bufp
->allocated
);
1089 if (bufp
->fastmap_accurate
&& bufp
->fastmap
)
1091 printf ("fastmap: ");
1092 print_fastmap (bufp
->fastmap
);
1095 printf ("re_nsub: %d\t", bufp
->re_nsub
);
1096 printf ("regs_alloc: %d\t", bufp
->regs_allocated
);
1097 printf ("can_be_null: %d\t", bufp
->can_be_null
);
1098 printf ("newline_anchor: %d\n", bufp
->newline_anchor
);
1099 printf ("no_sub: %d\t", bufp
->no_sub
);
1100 printf ("not_bol: %d\t", bufp
->not_bol
);
1101 printf ("not_eol: %d\t", bufp
->not_eol
);
1102 printf ("syntax: %d\n", bufp
->syntax
);
1104 /* Perhaps we should print the translate table? */
1109 print_double_string (where
, string1
, size1
, string2
, size2
)
1122 if (FIRST_STRING_P (where
))
1124 for (this_char
= where
- string1
; this_char
< size1
; this_char
++)
1125 putchar (string1
[this_char
]);
1130 for (this_char
= where
- string2
; this_char
< size2
; this_char
++)
1131 putchar (string2
[this_char
]);
1135 #else /* not DEBUG */
1140 #define DEBUG_STATEMENT(e)
1141 #define DEBUG_PRINT1(x)
1142 #define DEBUG_PRINT2(x1, x2)
1143 #define DEBUG_PRINT3(x1, x2, x3)
1144 #define DEBUG_PRINT4(x1, x2, x3, x4)
1145 #define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
1146 #define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
1148 #endif /* not DEBUG */
1150 /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
1151 also be assigned to arbitrarily: each pattern buffer stores its own
1152 syntax, so it can be changed between regex compilations. */
1153 /* This has no initializer because initialized variables in Emacs
1154 become read-only after dumping. */
1155 reg_syntax_t re_syntax_options
;
1158 /* Specify the precise syntax of regexps for compilation. This provides
1159 for compatibility for various utilities which historically have
1160 different, incompatible syntaxes.
1162 The argument SYNTAX is a bit mask comprised of the various bits
1163 defined in regex.h. We return the old syntax. */
1166 re_set_syntax (syntax
)
1167 reg_syntax_t syntax
;
1169 reg_syntax_t ret
= re_syntax_options
;
1171 re_syntax_options
= syntax
;
1175 /* This table gives an error message for each of the error codes listed
1176 in regex.h. Obviously the order here has to be same as there.
1177 POSIX doesn't require that we do anything for REG_NOERROR,
1178 but why not be nice? */
1180 static const char *re_error_msgid
[] =
1182 gettext_noop ("Success"), /* REG_NOERROR */
1183 gettext_noop ("No match"), /* REG_NOMATCH */
1184 gettext_noop ("Invalid regular expression"), /* REG_BADPAT */
1185 gettext_noop ("Invalid collation character"), /* REG_ECOLLATE */
1186 gettext_noop ("Invalid character class name"), /* REG_ECTYPE */
1187 gettext_noop ("Trailing backslash"), /* REG_EESCAPE */
1188 gettext_noop ("Invalid back reference"), /* REG_ESUBREG */
1189 gettext_noop ("Unmatched [ or [^"), /* REG_EBRACK */
1190 gettext_noop ("Unmatched ( or \\("), /* REG_EPAREN */
1191 gettext_noop ("Unmatched \\{"), /* REG_EBRACE */
1192 gettext_noop ("Invalid content of \\{\\}"), /* REG_BADBR */
1193 gettext_noop ("Invalid range end"), /* REG_ERANGE */
1194 gettext_noop ("Memory exhausted"), /* REG_ESPACE */
1195 gettext_noop ("Invalid preceding regular expression"), /* REG_BADRPT */
1196 gettext_noop ("Premature end of regular expression"), /* REG_EEND */
1197 gettext_noop ("Regular expression too big"), /* REG_ESIZE */
1198 gettext_noop ("Unmatched ) or \\)"), /* REG_ERPAREN */
1201 /* Avoiding alloca during matching, to placate r_alloc. */
1203 /* Define MATCH_MAY_ALLOCATE unless we need to make sure that the
1204 searching and matching functions should not call alloca. On some
1205 systems, alloca is implemented in terms of malloc, and if we're
1206 using the relocating allocator routines, then malloc could cause a
1207 relocation, which might (if the strings being searched are in the
1208 ralloc heap) shift the data out from underneath the regexp
1211 Here's another reason to avoid allocation: Emacs
1212 processes input from X in a signal handler; processing X input may
1213 call malloc; if input arrives while a matching routine is calling
1214 malloc, then we're scrod. But Emacs can't just block input while
1215 calling matching routines; then we don't notice interrupts when
1216 they come in. So, Emacs blocks input around all regexp calls
1217 except the matching calls, which it leaves unprotected, in the
1218 faith that they will not malloc. */
1220 /* Normally, this is fine. */
1221 #define MATCH_MAY_ALLOCATE
1223 /* When using GNU C, we are not REALLY using the C alloca, no matter
1224 what config.h may say. So don't take precautions for it. */
1229 /* The match routines may not allocate if (1) they would do it with malloc
1230 and (2) it's not safe for them to use malloc.
1231 Note that if REL_ALLOC is defined, matching would not use malloc for the
1232 failure stack, but we would still use it for the register vectors;
1233 so REL_ALLOC should not affect this. */
1234 #if (defined (C_ALLOCA) || defined (REGEX_MALLOC)) && defined (emacs)
1235 #undef MATCH_MAY_ALLOCATE
1239 /* Failure stack declarations and macros; both re_compile_fastmap and
1240 re_match_2 use a failure stack. These have to be macros because of
1241 REGEX_ALLOCATE_STACK. */
1244 /* Approximate number of failure points for which to initially allocate space
1245 when matching. If this number is exceeded, we allocate more
1246 space, so it is not a hard limit. */
1247 #ifndef INIT_FAILURE_ALLOC
1248 #define INIT_FAILURE_ALLOC 20
1251 /* Roughly the maximum number of failure points on the stack. Would be
1252 exactly that if always used TYPICAL_FAILURE_SIZE items each time we failed.
1253 This is a variable only so users of regex can assign to it; we never
1254 change it ourselves. */
1255 #if defined (MATCH_MAY_ALLOCATE)
1256 /* Note that 4400 is enough to cause a crash on Alpha OSF/1,
1257 whose default stack limit is 2mb. In order for a larger
1258 value to work reliably, you have to try to make it accord
1259 with the process stack limit. */
1260 int re_max_failures
= 40000;
1262 int re_max_failures
= 4000;
1265 union fail_stack_elt
1267 const unsigned char *pointer
;
1268 unsigned int integer
;
1271 typedef union fail_stack_elt fail_stack_elt_t
;
1275 fail_stack_elt_t
*stack
;
1277 unsigned avail
; /* Offset of next open position. */
1278 unsigned frame
; /* Offset of the cur constructed frame. */
1281 #define PATTERN_STACK_EMPTY() (fail_stack.avail == 0)
1282 #define FAIL_STACK_EMPTY() (fail_stack.frame == 0)
1283 #define FAIL_STACK_FULL() (fail_stack.avail == fail_stack.size)
1286 /* Define macros to initialize and free the failure stack.
1287 Do `return -2' if the alloc fails. */
1289 #ifdef MATCH_MAY_ALLOCATE
1290 #define INIT_FAIL_STACK() \
1292 fail_stack.stack = (fail_stack_elt_t *) \
1293 REGEX_ALLOCATE_STACK (INIT_FAILURE_ALLOC * TYPICAL_FAILURE_SIZE \
1294 * sizeof (fail_stack_elt_t)); \
1296 if (fail_stack.stack == NULL) \
1299 fail_stack.size = INIT_FAILURE_ALLOC; \
1300 fail_stack.avail = 0; \
1301 fail_stack.frame = 0; \
1304 #define RESET_FAIL_STACK() REGEX_FREE_STACK (fail_stack.stack)
1306 #define INIT_FAIL_STACK() \
1308 fail_stack.avail = 0; \
1309 fail_stack.frame = 0; \
1312 #define RESET_FAIL_STACK() ((void)0)
1316 /* Double the size of FAIL_STACK, up to a limit
1317 which allows approximately `re_max_failures' items.
1319 Return 1 if succeeds, and 0 if either ran out of memory
1320 allocating space for it or it was already too large.
1322 REGEX_REALLOCATE_STACK requires `destination' be declared. */
1324 /* Factor to increase the failure stack size by
1325 when we increase it.
1326 This used to be 2, but 2 was too wasteful
1327 because the old discarded stacks added up to as much space
1328 were as ultimate, maximum-size stack. */
1329 #define FAIL_STACK_GROWTH_FACTOR 4
1331 #define GROW_FAIL_STACK(fail_stack) \
1332 (((fail_stack).size * sizeof (fail_stack_elt_t) \
1333 >= re_max_failures * TYPICAL_FAILURE_SIZE) \
1335 : ((fail_stack).stack \
1336 = (fail_stack_elt_t *) \
1337 REGEX_REALLOCATE_STACK ((fail_stack).stack, \
1338 (fail_stack).size * sizeof (fail_stack_elt_t), \
1339 MIN (re_max_failures * TYPICAL_FAILURE_SIZE, \
1340 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1341 * FAIL_STACK_GROWTH_FACTOR))), \
1343 (fail_stack).stack == NULL \
1345 : ((fail_stack).size \
1346 = (MIN (re_max_failures * TYPICAL_FAILURE_SIZE, \
1347 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1348 * FAIL_STACK_GROWTH_FACTOR)) \
1349 / sizeof (fail_stack_elt_t)), \
1353 /* Push pointer POINTER on FAIL_STACK.
1354 Return 1 if was able to do so and 0 if ran out of memory allocating
1356 #define PUSH_PATTERN_OP(POINTER, FAIL_STACK) \
1357 ((FAIL_STACK_FULL () \
1358 && !GROW_FAIL_STACK (FAIL_STACK)) \
1360 : ((FAIL_STACK).stack[(FAIL_STACK).avail++].pointer = POINTER, \
1362 #define POP_PATTERN_OP() POP_FAILURE_POINTER ()
1364 /* Push a pointer value onto the failure stack.
1365 Assumes the variable `fail_stack'. Probably should only
1366 be called from within `PUSH_FAILURE_POINT'. */
1367 #define PUSH_FAILURE_POINTER(item) \
1368 fail_stack.stack[fail_stack.avail++].pointer = (unsigned char *) (item)
1370 /* This pushes an integer-valued item onto the failure stack.
1371 Assumes the variable `fail_stack'. Probably should only
1372 be called from within `PUSH_FAILURE_POINT'. */
1373 #define PUSH_FAILURE_INT(item) \
1374 fail_stack.stack[fail_stack.avail++].integer = (item)
1376 /* Push a fail_stack_elt_t value onto the failure stack.
1377 Assumes the variable `fail_stack'. Probably should only
1378 be called from within `PUSH_FAILURE_POINT'. */
1379 #define PUSH_FAILURE_ELT(item) \
1380 fail_stack.stack[fail_stack.avail++] = (item)
1382 /* These three POP... operations complement the three PUSH... operations.
1383 All assume that `fail_stack' is nonempty. */
1384 #define POP_FAILURE_POINTER() fail_stack.stack[--fail_stack.avail].pointer
1385 #define POP_FAILURE_INT() fail_stack.stack[--fail_stack.avail].integer
1386 #define POP_FAILURE_ELT() fail_stack.stack[--fail_stack.avail]
1388 /* Individual items aside from the registers. */
1389 #define NUM_NONREG_ITEMS 3
1391 /* Used to examine the stack (to detect infinite loops). */
1392 #define FAILURE_PAT(h) fail_stack.stack[(h) - 1].pointer
1393 #define FAILURE_STR(h) (fail_stack.stack[(h) - 2].pointer)
1394 #define NEXT_FAILURE_HANDLE(h) fail_stack.stack[(h) - 3].integer
1395 #define TOP_FAILURE_HANDLE() fail_stack.frame
1398 #define ENSURE_FAIL_STACK(space) \
1399 while (REMAINING_AVAIL_SLOTS <= space) { \
1400 if (!GROW_FAIL_STACK (fail_stack)) \
1402 DEBUG_PRINT2 ("\n Doubled stack; size now: %d\n", (fail_stack).size);\
1403 DEBUG_PRINT2 (" slots available: %d\n", REMAINING_AVAIL_SLOTS);\
1406 /* Push register NUM onto the stack. */
1407 #define PUSH_FAILURE_REG(num) \
1409 char *destination; \
1410 ENSURE_FAIL_STACK(3); \
1411 DEBUG_PRINT4 (" Push reg %d (spanning %p -> %p)\n", \
1412 num, regstart[num], regend[num]); \
1413 PUSH_FAILURE_POINTER (regstart[num]); \
1414 PUSH_FAILURE_POINTER (regend[num]); \
1415 PUSH_FAILURE_INT (num); \
1418 /* Pop a saved register off the stack. */
1419 #define POP_FAILURE_REG() \
1421 int reg = POP_FAILURE_INT (); \
1422 regend[reg] = POP_FAILURE_POINTER (); \
1423 regstart[reg] = POP_FAILURE_POINTER (); \
1424 DEBUG_PRINT4 (" Pop reg %d (spanning %p -> %p)\n", \
1425 reg, regstart[reg], regend[reg]); \
1428 /* Check that we are not stuck in an infinite loop. */
1429 #define CHECK_INFINITE_LOOP(pat_cur, string_place) \
1431 int failure = TOP_FAILURE_HANDLE(); \
1432 /* Check for infinite matching loops */ \
1433 while (failure > 0 && \
1434 (FAILURE_STR (failure) == string_place \
1435 || FAILURE_STR (failure) == NULL)) \
1437 assert (FAILURE_PAT (failure) >= bufp->buffer \
1438 && FAILURE_PAT (failure) <= bufp->buffer + bufp->used); \
1439 if (FAILURE_PAT (failure) == pat_cur) \
1441 DEBUG_PRINT2 (" Other pattern: %p\n", FAILURE_PAT (failure)); \
1442 failure = NEXT_FAILURE_HANDLE(failure); \
1444 DEBUG_PRINT2 (" Other string: %p\n", FAILURE_STR (failure)); \
1447 /* Push the information about the state we will need
1448 if we ever fail back to it.
1450 Requires variables fail_stack, regstart, regend and
1451 num_regs be declared. GROW_FAIL_STACK requires `destination' be
1454 Does `return FAILURE_CODE' if runs out of memory. */
1456 #define PUSH_FAILURE_POINT(pattern, string_place) \
1458 char *destination; \
1459 /* Must be int, so when we don't save any registers, the arithmetic \
1460 of 0 + -1 isn't done as unsigned. */ \
1462 DEBUG_STATEMENT (failure_id++); \
1463 DEBUG_STATEMENT (nfailure_points_pushed++); \
1464 DEBUG_PRINT2 ("\nPUSH_FAILURE_POINT #%u:\n", failure_id); \
1465 DEBUG_PRINT2 (" Before push, next avail: %d\n", (fail_stack).avail); \
1466 DEBUG_PRINT2 (" size: %d\n", (fail_stack).size);\
1468 ENSURE_FAIL_STACK (NUM_NONREG_ITEMS); \
1470 DEBUG_PRINT1 ("\n"); \
1472 DEBUG_PRINT2 (" Push frame index: %d\n", fail_stack.frame); \
1473 PUSH_FAILURE_INT (fail_stack.frame); \
1475 DEBUG_PRINT2 (" Push string %p: `", string_place); \
1476 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, size2);\
1477 DEBUG_PRINT1 ("'\n"); \
1478 PUSH_FAILURE_POINTER (string_place); \
1480 DEBUG_PRINT2 (" Push pattern %p: ", pattern); \
1481 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern, pend); \
1482 PUSH_FAILURE_POINTER (pattern); \
1484 /* Close the frame by moving the frame pointer past it. */ \
1485 fail_stack.frame = fail_stack.avail; \
1488 /* Estimate the size of data pushed by a typical failure stack entry.
1489 An estimate is all we need, because all we use this for
1490 is to choose a limit for how big to make the failure stack. */
1492 #define TYPICAL_FAILURE_SIZE 20
1494 /* How many items can still be added to the stack without overflowing it. */
1495 #define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
1498 /* Pops what PUSH_FAIL_STACK pushes.
1500 We restore into the parameters, all of which should be lvalues:
1501 STR -- the saved data position.
1502 PAT -- the saved pattern position.
1503 REGSTART, REGEND -- arrays of string positions.
1505 Also assumes the variables `fail_stack' and (if debugging), `bufp',
1506 `pend', `string1', `size1', `string2', and `size2'. */
1508 #define POP_FAILURE_POINT(str, pat) \
1510 assert (!FAIL_STACK_EMPTY ()); \
1512 /* Remove failure points and point to how many regs pushed. */ \
1513 DEBUG_PRINT1 ("POP_FAILURE_POINT:\n"); \
1514 DEBUG_PRINT2 (" Before pop, next avail: %d\n", fail_stack.avail); \
1515 DEBUG_PRINT2 (" size: %d\n", fail_stack.size); \
1517 /* Pop the saved registers. */ \
1518 while (fail_stack.frame < fail_stack.avail) \
1519 POP_FAILURE_REG (); \
1521 pat = (unsigned char *) POP_FAILURE_POINTER (); \
1522 DEBUG_PRINT2 (" Popping pattern %p: ", pat); \
1523 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
1525 /* If the saved string location is NULL, it came from an \
1526 on_failure_keep_string_jump opcode, and we want to throw away the \
1527 saved NULL, thus retaining our current position in the string. */ \
1528 str = (re_char *) POP_FAILURE_POINTER (); \
1529 DEBUG_PRINT2 (" Popping string %p: `", str); \
1530 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
1531 DEBUG_PRINT1 ("'\n"); \
1533 fail_stack.frame = POP_FAILURE_INT (); \
1534 DEBUG_PRINT2 (" Popping frame index: %d\n", fail_stack.frame); \
1536 assert (fail_stack.avail >= 0); \
1537 assert (fail_stack.frame <= fail_stack.avail); \
1539 DEBUG_STATEMENT (nfailure_points_popped++); \
1540 } while (0) /* POP_FAILURE_POINT */
1544 /* Registers are set to a sentinel when they haven't yet matched. */
1545 #define REG_UNSET_VALUE NULL
1546 #define REG_UNSET(e) ((e) == REG_UNSET_VALUE)
1548 /* Subroutine declarations and macros for regex_compile. */
1550 static void store_op1
_RE_ARGS((re_opcode_t op
, unsigned char *loc
, int arg
));
1551 static void store_op2
_RE_ARGS((re_opcode_t op
, unsigned char *loc
,
1552 int arg1
, int arg2
));
1553 static void insert_op1
_RE_ARGS((re_opcode_t op
, unsigned char *loc
,
1554 int arg
, unsigned char *end
));
1555 static void insert_op2
_RE_ARGS((re_opcode_t op
, unsigned char *loc
,
1556 int arg1
, int arg2
, unsigned char *end
));
1557 static boolean at_begline_loc_p
_RE_ARGS((const unsigned char *pattern
,
1558 const unsigned char *p
,
1559 reg_syntax_t syntax
));
1560 static boolean at_endline_loc_p
_RE_ARGS((const unsigned char *p
,
1561 const unsigned char *pend
,
1562 reg_syntax_t syntax
));
1563 static unsigned char *skip_one_char
_RE_ARGS((unsigned char *p
));
1564 static int analyse_first
_RE_ARGS((unsigned char *p
, unsigned char *pend
,
1565 char *fastmap
, const int multibyte
));
1567 /* Fetch the next character in the uncompiled pattern---translating it
1568 if necessary. Also cast from a signed character in the constant
1569 string passed to us by the user to an unsigned char that we can use
1570 as an array index (in, e.g., `translate'). */
1571 #define PATFETCH(c) \
1574 c = TRANSLATE (c); \
1577 /* Fetch the next character in the uncompiled pattern, with no
1579 #define PATFETCH_RAW(c) \
1582 if (p == pend) return REG_EEND; \
1583 c = RE_STRING_CHAR_AND_LENGTH (p, pend - p, len); \
1588 /* If `translate' is non-null, return translate[D], else just D. We
1589 cast the subscript to translate because some data is declared as
1590 `char *', to avoid warnings when a string constant is passed. But
1591 when we use a character as a subscript we must make it unsigned. */
1593 #define TRANSLATE(d) \
1594 (RE_TRANSLATE_P (translate) ? RE_TRANSLATE (translate, (d)) : (d))
1598 /* Macros for outputting the compiled pattern into `buffer'. */
1600 /* If the buffer isn't allocated when it comes in, use this. */
1601 #define INIT_BUF_SIZE 32
1603 /* Make sure we have at least N more bytes of space in buffer. */
1604 #define GET_BUFFER_SPACE(n) \
1605 while (b - bufp->buffer + (n) > bufp->allocated) \
1608 /* Make sure we have one more byte of buffer space and then add C to it. */
1609 #define BUF_PUSH(c) \
1611 GET_BUFFER_SPACE (1); \
1612 *b++ = (unsigned char) (c); \
1616 /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
1617 #define BUF_PUSH_2(c1, c2) \
1619 GET_BUFFER_SPACE (2); \
1620 *b++ = (unsigned char) (c1); \
1621 *b++ = (unsigned char) (c2); \
1625 /* As with BUF_PUSH_2, except for three bytes. */
1626 #define BUF_PUSH_3(c1, c2, c3) \
1628 GET_BUFFER_SPACE (3); \
1629 *b++ = (unsigned char) (c1); \
1630 *b++ = (unsigned char) (c2); \
1631 *b++ = (unsigned char) (c3); \
1635 /* Store a jump with opcode OP at LOC to location TO. We store a
1636 relative address offset by the three bytes the jump itself occupies. */
1637 #define STORE_JUMP(op, loc, to) \
1638 store_op1 (op, loc, (to) - (loc) - 3)
1640 /* Likewise, for a two-argument jump. */
1641 #define STORE_JUMP2(op, loc, to, arg) \
1642 store_op2 (op, loc, (to) - (loc) - 3, arg)
1644 /* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
1645 #define INSERT_JUMP(op, loc, to) \
1646 insert_op1 (op, loc, (to) - (loc) - 3, b)
1648 /* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
1649 #define INSERT_JUMP2(op, loc, to, arg) \
1650 insert_op2 (op, loc, (to) - (loc) - 3, arg, b)
1653 /* This is not an arbitrary limit: the arguments which represent offsets
1654 into the pattern are two bytes long. So if 2^16 bytes turns out to
1655 be too small, many things would have to change. */
1656 #define MAX_BUF_SIZE (1L << 16)
1659 /* Extend the buffer by twice its current size via realloc and
1660 reset the pointers that pointed into the old block to point to the
1661 correct places in the new one. If extending the buffer results in it
1662 being larger than MAX_BUF_SIZE, then flag memory exhausted. */
1663 #define EXTEND_BUFFER() \
1665 unsigned char *old_buffer = bufp->buffer; \
1666 if (bufp->allocated == MAX_BUF_SIZE) \
1668 bufp->allocated <<= 1; \
1669 if (bufp->allocated > MAX_BUF_SIZE) \
1670 bufp->allocated = MAX_BUF_SIZE; \
1671 bufp->buffer = (unsigned char *) realloc (bufp->buffer, bufp->allocated);\
1672 if (bufp->buffer == NULL) \
1673 return REG_ESPACE; \
1674 /* If the buffer moved, move all the pointers into it. */ \
1675 if (old_buffer != bufp->buffer) \
1677 b = (b - old_buffer) + bufp->buffer; \
1678 begalt = (begalt - old_buffer) + bufp->buffer; \
1679 if (fixup_alt_jump) \
1680 fixup_alt_jump = (fixup_alt_jump - old_buffer) + bufp->buffer;\
1682 laststart = (laststart - old_buffer) + bufp->buffer; \
1683 if (pending_exact) \
1684 pending_exact = (pending_exact - old_buffer) + bufp->buffer; \
1689 /* Since we have one byte reserved for the register number argument to
1690 {start,stop}_memory, the maximum number of groups we can report
1691 things about is what fits in that byte. */
1692 #define MAX_REGNUM 255
1694 /* But patterns can have more than `MAX_REGNUM' registers. We just
1695 ignore the excess. */
1696 typedef unsigned regnum_t
;
1699 /* Macros for the compile stack. */
1701 /* Since offsets can go either forwards or backwards, this type needs to
1702 be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
1703 typedef int pattern_offset_t
;
1707 pattern_offset_t begalt_offset
;
1708 pattern_offset_t fixup_alt_jump
;
1709 pattern_offset_t laststart_offset
;
1711 } compile_stack_elt_t
;
1716 compile_stack_elt_t
*stack
;
1718 unsigned avail
; /* Offset of next open position. */
1719 } compile_stack_type
;
1722 #define INIT_COMPILE_STACK_SIZE 32
1724 #define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
1725 #define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
1727 /* The next available element. */
1728 #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
1731 /* Structure to manage work area for range table. */
1732 struct range_table_work_area
1734 int *table
; /* actual work area. */
1735 int allocated
; /* allocated size for work area in bytes. */
1736 int used
; /* actually used size in words. */
1737 int bits
; /* flag to record character classes */
1740 /* Make sure that WORK_AREA can hold more N multibyte characters. */
1741 #define EXTEND_RANGE_TABLE_WORK_AREA(work_area, n) \
1743 if (((work_area).used + (n)) * sizeof (int) > (work_area).allocated) \
1745 (work_area).allocated += 16 * sizeof (int); \
1746 if ((work_area).table) \
1748 = (int *) realloc ((work_area).table, (work_area).allocated); \
1751 = (int *) malloc ((work_area).allocated); \
1752 if ((work_area).table == 0) \
1753 FREE_STACK_RETURN (REG_ESPACE); \
1757 #define SET_RANGE_TABLE_WORK_AREA_BIT(work_area, bit) \
1758 (work_area).bits |= (bit)
1760 /* These bits represent the various character classes such as [:alnum:]
1761 in a charset's range table. */
1762 #define BIT_ALNUM 0x1
1763 #define BIT_ALPHA 0x2
1764 #define BIT_WORD 0x4
1765 #define BIT_ASCII 0x8
1766 #define BIT_NONASCII 0x10
1767 #define BIT_GRAPH 0x20
1768 #define BIT_LOWER 0x40
1769 #define BIT_PRINT 0x80
1770 #define BIT_PUNCT 0x100
1771 #define BIT_SPACE 0x200
1772 #define BIT_UPPER 0x400
1773 #define BIT_UNIBYTE 0x800
1774 #define BIT_MULTIBYTE 0x1000
1776 /* Set a range (RANGE_START, RANGE_END) to WORK_AREA. */
1777 #define SET_RANGE_TABLE_WORK_AREA(work_area, range_start, range_end) \
1779 EXTEND_RANGE_TABLE_WORK_AREA ((work_area), 2); \
1780 (work_area).table[(work_area).used++] = (range_start); \
1781 (work_area).table[(work_area).used++] = (range_end); \
1784 /* Free allocated memory for WORK_AREA. */
1785 #define FREE_RANGE_TABLE_WORK_AREA(work_area) \
1787 if ((work_area).table) \
1788 free ((work_area).table); \
1791 #define CLEAR_RANGE_TABLE_WORK_USED(work_area) ((work_area).used = 0, (work_area).bits = 0)
1792 #define RANGE_TABLE_WORK_USED(work_area) ((work_area).used)
1793 #define RANGE_TABLE_WORK_BITS(work_area) ((work_area).bits)
1794 #define RANGE_TABLE_WORK_ELT(work_area, i) ((work_area).table[i])
1797 /* Set the bit for character C in a list. */
1798 #define SET_LIST_BIT(c) \
1799 (b[((unsigned char) (c)) / BYTEWIDTH] \
1800 |= 1 << (((unsigned char) c) % BYTEWIDTH))
1803 /* Get the next unsigned number in the uncompiled pattern. */
1804 #define GET_UNSIGNED_NUMBER(num) \
1805 do { if (p != pend) \
1808 while (ISDIGIT (c)) \
1812 num = num * 10 + c - '0'; \
1820 #define CHAR_CLASS_MAX_LENGTH 6 /* Namely, `xdigit'. */
1822 #define IS_CHAR_CLASS(string) \
1823 (STREQ (string, "alpha") || STREQ (string, "upper") \
1824 || STREQ (string, "lower") || STREQ (string, "digit") \
1825 || STREQ (string, "alnum") || STREQ (string, "xdigit") \
1826 || STREQ (string, "space") || STREQ (string, "print") \
1827 || STREQ (string, "punct") || STREQ (string, "graph") \
1828 || STREQ (string, "cntrl") || STREQ (string, "blank") \
1829 || STREQ (string, "word") \
1830 || STREQ (string, "ascii") || STREQ (string, "nonascii") \
1831 || STREQ (string, "unibyte") || STREQ (string, "multibyte"))
1833 /* QUIT is only used on NTemacs. */
1834 #if !defined (WINDOWSNT) || !defined (emacs)
1839 #ifndef MATCH_MAY_ALLOCATE
1841 /* If we cannot allocate large objects within re_match_2_internal,
1842 we make the fail stack and register vectors global.
1843 The fail stack, we grow to the maximum size when a regexp
1845 The register vectors, we adjust in size each time we
1846 compile a regexp, according to the number of registers it needs. */
1848 static fail_stack_type fail_stack
;
1850 /* Size with which the following vectors are currently allocated.
1851 That is so we can make them bigger as needed,
1852 but never make them smaller. */
1853 static int regs_allocated_size
;
1855 static re_char
** regstart
, ** regend
;
1856 static re_char
**best_regstart
, **best_regend
;
1858 /* Make the register vectors big enough for NUM_REGS registers,
1859 but don't make them smaller. */
1862 regex_grow_registers (num_regs
)
1865 if (num_regs
> regs_allocated_size
)
1867 RETALLOC_IF (regstart
, num_regs
, re_char
*);
1868 RETALLOC_IF (regend
, num_regs
, re_char
*);
1869 RETALLOC_IF (best_regstart
, num_regs
, re_char
*);
1870 RETALLOC_IF (best_regend
, num_regs
, re_char
*);
1872 regs_allocated_size
= num_regs
;
1876 #endif /* not MATCH_MAY_ALLOCATE */
1878 static boolean group_in_compile_stack
_RE_ARGS ((compile_stack_type
1882 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
1883 Returns one of error codes defined in `regex.h', or zero for success.
1885 Assumes the `allocated' (and perhaps `buffer') and `translate'
1886 fields are set in BUFP on entry.
1888 If it succeeds, results are put in BUFP (if it returns an error, the
1889 contents of BUFP are undefined):
1890 `buffer' is the compiled pattern;
1891 `syntax' is set to SYNTAX;
1892 `used' is set to the length of the compiled pattern;
1893 `fastmap_accurate' is zero;
1894 `re_nsub' is the number of subexpressions in PATTERN;
1895 `not_bol' and `not_eol' are zero;
1897 The `fastmap' and `newline_anchor' fields are neither
1898 examined nor set. */
1900 /* Insert the `jump' from the end of last alternative to "here".
1901 The space for the jump has already been allocated. */
1902 #define FIXUP_ALT_JUMP() \
1904 if (fixup_alt_jump) \
1905 STORE_JUMP (jump, fixup_alt_jump, b); \
1909 /* Return, freeing storage we allocated. */
1910 #define FREE_STACK_RETURN(value) \
1912 FREE_RANGE_TABLE_WORK_AREA (range_table_work); \
1913 free (compile_stack.stack); \
1917 static reg_errcode_t
1918 regex_compile (pattern
, size
, syntax
, bufp
)
1921 reg_syntax_t syntax
;
1922 struct re_pattern_buffer
*bufp
;
1924 /* We fetch characters from PATTERN here. Even though PATTERN is
1925 `char *' (i.e., signed), we declare these variables as unsigned, so
1926 they can be reliably used as array indices. */
1927 register unsigned int c
, c1
;
1929 /* A random temporary spot in PATTERN. */
1932 /* Points to the end of the buffer, where we should append. */
1933 register unsigned char *b
;
1935 /* Keeps track of unclosed groups. */
1936 compile_stack_type compile_stack
;
1938 /* Points to the current (ending) position in the pattern. */
1940 /* `const' makes AIX compiler fail. */
1941 unsigned char *p
= pattern
;
1943 re_char
*p
= pattern
;
1945 re_char
*pend
= pattern
+ size
;
1947 /* How to translate the characters in the pattern. */
1948 RE_TRANSLATE_TYPE translate
= bufp
->translate
;
1950 /* Address of the count-byte of the most recently inserted `exactn'
1951 command. This makes it possible to tell if a new exact-match
1952 character can be added to that command or if the character requires
1953 a new `exactn' command. */
1954 unsigned char *pending_exact
= 0;
1956 /* Address of start of the most recently finished expression.
1957 This tells, e.g., postfix * where to find the start of its
1958 operand. Reset at the beginning of groups and alternatives. */
1959 unsigned char *laststart
= 0;
1961 /* Address of beginning of regexp, or inside of last group. */
1962 unsigned char *begalt
;
1964 /* Place in the uncompiled pattern (i.e., the {) to
1965 which to go back if the interval is invalid. */
1966 re_char
*beg_interval
;
1968 /* Address of the place where a forward jump should go to the end of
1969 the containing expression. Each alternative of an `or' -- except the
1970 last -- ends with a forward jump of this sort. */
1971 unsigned char *fixup_alt_jump
= 0;
1973 /* Counts open-groups as they are encountered. Remembered for the
1974 matching close-group on the compile stack, so the same register
1975 number is put in the stop_memory as the start_memory. */
1976 regnum_t regnum
= 0;
1978 /* Work area for range table of charset. */
1979 struct range_table_work_area range_table_work
;
1981 /* If the object matched can contain multibyte characters. */
1982 const boolean multibyte
= RE_MULTIBYTE_P (bufp
);
1986 DEBUG_PRINT1 ("\nCompiling pattern: ");
1989 unsigned debug_count
;
1991 for (debug_count
= 0; debug_count
< size
; debug_count
++)
1992 putchar (pattern
[debug_count
]);
1997 /* Initialize the compile stack. */
1998 compile_stack
.stack
= TALLOC (INIT_COMPILE_STACK_SIZE
, compile_stack_elt_t
);
1999 if (compile_stack
.stack
== NULL
)
2002 compile_stack
.size
= INIT_COMPILE_STACK_SIZE
;
2003 compile_stack
.avail
= 0;
2005 range_table_work
.table
= 0;
2006 range_table_work
.allocated
= 0;
2008 /* Initialize the pattern buffer. */
2009 bufp
->syntax
= syntax
;
2010 bufp
->fastmap_accurate
= 0;
2011 bufp
->not_bol
= bufp
->not_eol
= 0;
2013 /* Set `used' to zero, so that if we return an error, the pattern
2014 printer (for debugging) will think there's no pattern. We reset it
2018 /* Always count groups, whether or not bufp->no_sub is set. */
2021 #if !defined (emacs) && !defined (SYNTAX_TABLE)
2022 /* Initialize the syntax table. */
2023 init_syntax_once ();
2026 if (bufp
->allocated
== 0)
2029 { /* If zero allocated, but buffer is non-null, try to realloc
2030 enough space. This loses if buffer's address is bogus, but
2031 that is the user's responsibility. */
2032 RETALLOC (bufp
->buffer
, INIT_BUF_SIZE
, unsigned char);
2035 { /* Caller did not allocate a buffer. Do it for them. */
2036 bufp
->buffer
= TALLOC (INIT_BUF_SIZE
, unsigned char);
2038 if (!bufp
->buffer
) FREE_STACK_RETURN (REG_ESPACE
);
2040 bufp
->allocated
= INIT_BUF_SIZE
;
2043 begalt
= b
= bufp
->buffer
;
2045 /* Loop through the uncompiled pattern until we're at the end. */
2054 if ( /* If at start of pattern, it's an operator. */
2056 /* If context independent, it's an operator. */
2057 || syntax
& RE_CONTEXT_INDEP_ANCHORS
2058 /* Otherwise, depends on what's come before. */
2059 || at_begline_loc_p (pattern
, p
, syntax
))
2069 if ( /* If at end of pattern, it's an operator. */
2071 /* If context independent, it's an operator. */
2072 || syntax
& RE_CONTEXT_INDEP_ANCHORS
2073 /* Otherwise, depends on what's next. */
2074 || at_endline_loc_p (p
, pend
, syntax
))
2084 if ((syntax
& RE_BK_PLUS_QM
)
2085 || (syntax
& RE_LIMITED_OPS
))
2089 /* If there is no previous pattern... */
2092 if (syntax
& RE_CONTEXT_INVALID_OPS
)
2093 FREE_STACK_RETURN (REG_BADRPT
);
2094 else if (!(syntax
& RE_CONTEXT_INDEP_OPS
))
2099 /* 1 means zero (many) matches is allowed. */
2100 boolean zero_times_ok
= 0, many_times_ok
= 0;
2103 /* If there is a sequence of repetition chars, collapse it
2104 down to just one (the right one). We can't combine
2105 interval operators with these because of, e.g., `a{2}*',
2106 which should only match an even number of `a's. */
2110 if (!(syntax
& RE_ALL_GREEDY
)
2111 && c
== '?' && (zero_times_ok
|| many_times_ok
))
2115 zero_times_ok
|= c
!= '+';
2116 many_times_ok
|= c
!= '?';
2122 || (!(syntax
& RE_BK_PLUS_QM
)
2123 && (*p
== '+' || *p
== '?')))
2125 else if (syntax
& RE_BK_PLUS_QM
&& *p
== '\\')
2128 FREE_STACK_RETURN (REG_EESCAPE
);
2129 if (p
[1] == '+' || p
[1] == '?')
2130 PATFETCH (c
); /* Gobble up the backslash. */
2136 /* If we get here, we found another repeat character. */
2140 /* Star, etc. applied to an empty pattern is equivalent
2141 to an empty pattern. */
2142 if (!laststart
|| laststart
== b
)
2145 /* Now we know whether or not zero matches is allowed
2146 and also whether or not two or more matches is allowed. */
2151 boolean simple
= skip_one_char (laststart
) == b
;
2152 unsigned int startoffset
= 0;
2154 (simple
|| !analyse_first (laststart
, b
, NULL
, 0)) ?
2155 on_failure_jump
: on_failure_jump_loop
;
2156 assert (skip_one_char (laststart
) <= b
);
2158 if (!zero_times_ok
&& simple
)
2159 { /* Since simple * loops can be made faster by using
2160 on_failure_keep_string_jump, we turn simple P+
2161 into PP* if P is simple. */
2162 unsigned char *p1
, *p2
;
2163 startoffset
= b
- laststart
;
2164 GET_BUFFER_SPACE (startoffset
);
2165 p1
= b
; p2
= laststart
;
2171 GET_BUFFER_SPACE (6);
2174 STORE_JUMP (ofj
, b
, b
+ 6);
2176 /* Simple * loops can use on_failure_keep_string_jump
2177 depending on what follows. But since we don't know
2178 that yet, we leave the decision up to
2179 on_failure_jump_smart. */
2180 INSERT_JUMP (simple
? on_failure_jump_smart
: ofj
,
2181 laststart
+ startoffset
, b
+ 6);
2183 STORE_JUMP (jump
, b
, laststart
+ startoffset
);
2188 /* A simple ? pattern. */
2189 assert (zero_times_ok
);
2190 GET_BUFFER_SPACE (3);
2191 INSERT_JUMP (on_failure_jump
, laststart
, b
+ 3);
2195 else /* not greedy */
2196 { /* I wish the greedy and non-greedy cases could be merged. */
2198 GET_BUFFER_SPACE (7); /* We might use less. */
2201 boolean emptyp
= analyse_first (laststart
, b
, NULL
, 0);
2203 /* The non-greedy multiple match looks like a repeat..until:
2204 we only need a conditional jump at the end of the loop */
2205 if (emptyp
) BUF_PUSH (no_op
);
2206 STORE_JUMP (emptyp
? on_failure_jump_nastyloop
2207 : on_failure_jump
, b
, laststart
);
2211 /* The repeat...until naturally matches one or more.
2212 To also match zero times, we need to first jump to
2213 the end of the loop (its conditional jump). */
2214 INSERT_JUMP (jump
, laststart
, b
);
2220 /* non-greedy a?? */
2221 INSERT_JUMP (jump
, laststart
, b
+ 3);
2223 INSERT_JUMP (on_failure_jump
, laststart
, laststart
+ 6);
2240 CLEAR_RANGE_TABLE_WORK_USED (range_table_work
);
2242 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2244 /* Ensure that we have enough space to push a charset: the
2245 opcode, the length count, and the bitset; 34 bytes in all. */
2246 GET_BUFFER_SPACE (34);
2250 /* We test `*p == '^' twice, instead of using an if
2251 statement, so we only need one BUF_PUSH. */
2252 BUF_PUSH (*p
== '^' ? charset_not
: charset
);
2256 /* Remember the first position in the bracket expression. */
2259 /* Push the number of bytes in the bitmap. */
2260 BUF_PUSH ((1 << BYTEWIDTH
) / BYTEWIDTH
);
2262 /* Clear the whole map. */
2263 bzero (b
, (1 << BYTEWIDTH
) / BYTEWIDTH
);
2265 /* charset_not matches newline according to a syntax bit. */
2266 if ((re_opcode_t
) b
[-2] == charset_not
2267 && (syntax
& RE_HAT_LISTS_NOT_NEWLINE
))
2268 SET_LIST_BIT ('\n');
2270 /* Read in characters and ranges, setting map bits. */
2273 boolean escaped_char
= false;
2274 const unsigned char *p2
= p
;
2276 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2280 /* \ might escape characters inside [...] and [^...]. */
2281 if ((syntax
& RE_BACKSLASH_ESCAPE_IN_LISTS
) && c
== '\\')
2283 if (p
== pend
) FREE_STACK_RETURN (REG_EESCAPE
);
2286 escaped_char
= true;
2290 /* Could be the end of the bracket expression. If it's
2291 not (i.e., when the bracket expression is `[]' so
2292 far), the ']' character bit gets set way below. */
2293 if (c
== ']' && p2
!= p1
)
2297 /* What should we do for the character which is
2298 greater than 0x7F, but not BASE_LEADING_CODE_P?
2301 /* See if we're at the beginning of a possible character
2304 if (!escaped_char
&&
2305 syntax
& RE_CHAR_CLASSES
&& c
== '[' && *p
== ':')
2307 /* Leave room for the null. */
2308 char str
[CHAR_CLASS_MAX_LENGTH
+ 1];
2309 const unsigned char *class_beg
;
2315 /* If pattern is `[[:'. */
2316 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2321 if (c
== ':' || c
== ']' || p
== pend
2322 || c1
== CHAR_CLASS_MAX_LENGTH
)
2328 /* If isn't a word bracketed by `[:' and `:]':
2329 undo the ending character, the letters, and
2330 leave the leading `:' and `[' (but set bits for
2332 if (c
== ':' && *p
== ']')
2335 boolean is_alnum
= STREQ (str
, "alnum");
2336 boolean is_alpha
= STREQ (str
, "alpha");
2337 boolean is_ascii
= STREQ (str
, "ascii");
2338 boolean is_blank
= STREQ (str
, "blank");
2339 boolean is_cntrl
= STREQ (str
, "cntrl");
2340 boolean is_digit
= STREQ (str
, "digit");
2341 boolean is_graph
= STREQ (str
, "graph");
2342 boolean is_lower
= STREQ (str
, "lower");
2343 boolean is_multibyte
= STREQ (str
, "multibyte");
2344 boolean is_nonascii
= STREQ (str
, "nonascii");
2345 boolean is_print
= STREQ (str
, "print");
2346 boolean is_punct
= STREQ (str
, "punct");
2347 boolean is_space
= STREQ (str
, "space");
2348 boolean is_unibyte
= STREQ (str
, "unibyte");
2349 boolean is_upper
= STREQ (str
, "upper");
2350 boolean is_word
= STREQ (str
, "word");
2351 boolean is_xdigit
= STREQ (str
, "xdigit");
2353 if (!IS_CHAR_CLASS (str
))
2354 FREE_STACK_RETURN (REG_ECTYPE
);
2356 /* Throw away the ] at the end of the character
2360 if (p
== pend
) FREE_STACK_RETURN (REG_EBRACK
);
2362 /* Most character classes in a multibyte match
2363 just set a flag. Exceptions are is_blank,
2364 is_digit, is_cntrl, and is_xdigit, since
2365 they can only match ASCII characters. We
2366 don't need to handle them for multibyte. */
2372 if (is_alnum
) bit
= BIT_ALNUM
;
2373 if (is_alpha
) bit
= BIT_ALPHA
;
2374 if (is_ascii
) bit
= BIT_ASCII
;
2375 if (is_graph
) bit
= BIT_GRAPH
;
2376 if (is_lower
) bit
= BIT_LOWER
;
2377 if (is_multibyte
) bit
= BIT_MULTIBYTE
;
2378 if (is_nonascii
) bit
= BIT_NONASCII
;
2379 if (is_print
) bit
= BIT_PRINT
;
2380 if (is_punct
) bit
= BIT_PUNCT
;
2381 if (is_space
) bit
= BIT_SPACE
;
2382 if (is_unibyte
) bit
= BIT_UNIBYTE
;
2383 if (is_upper
) bit
= BIT_UPPER
;
2384 if (is_word
) bit
= BIT_WORD
;
2386 SET_RANGE_TABLE_WORK_AREA_BIT (range_table_work
,
2390 /* Handle character classes for ASCII characters. */
2391 for (ch
= 0; ch
< 1 << BYTEWIDTH
; ch
++)
2393 int translated
= TRANSLATE (ch
);
2394 /* This was split into 3 if's to
2395 avoid an arbitrary limit in some compiler. */
2396 if ( (is_alnum
&& ISALNUM (ch
))
2397 || (is_alpha
&& ISALPHA (ch
))
2398 || (is_blank
&& ISBLANK (ch
))
2399 || (is_cntrl
&& ISCNTRL (ch
)))
2400 SET_LIST_BIT (translated
);
2401 if ( (is_digit
&& ISDIGIT (ch
))
2402 || (is_graph
&& ISGRAPH (ch
))
2403 || (is_lower
&& ISLOWER (ch
))
2404 || (is_print
&& ISPRINT (ch
)))
2405 SET_LIST_BIT (translated
);
2406 if ( (is_punct
&& ISPUNCT (ch
))
2407 || (is_space
&& ISSPACE (ch
))
2408 || (is_upper
&& ISUPPER (ch
))
2409 || (is_xdigit
&& ISXDIGIT (ch
)))
2410 SET_LIST_BIT (translated
);
2411 if ( (is_ascii
&& IS_REAL_ASCII (ch
))
2412 || (is_nonascii
&& !IS_REAL_ASCII (ch
))
2413 || (is_unibyte
&& ISUNIBYTE (ch
))
2414 || (is_multibyte
&& !ISUNIBYTE (ch
)))
2415 SET_LIST_BIT (translated
);
2417 if ( (is_word
&& ISWORD (ch
)))
2418 SET_LIST_BIT (translated
);
2421 /* Repeat the loop. */
2426 /* Go back to right after the "[:". */
2430 /* Because the `:' may starts the range, we
2431 can't simply set bit and repeat the loop.
2432 Instead, just set it to C and handle below. */
2437 if (p
< pend
&& p
[0] == '-' && p
[1] != ']')
2440 /* Discard the `-'. */
2443 /* Fetch the character which ends the range. */
2446 if (SINGLE_BYTE_CHAR_P (c
)
2447 && ! SINGLE_BYTE_CHAR_P (c1
))
2449 /* Handle a range such as \177-\377 in multibyte mode.
2450 Split that into two ranges,,
2451 the low one ending at 0237, and the high one
2452 starting at ...040. */
2453 /* Unless I'm missing something,
2454 this line is useless. -sm
2455 int c1_base = (c1 & ~0177) | 040; */
2456 SET_RANGE_TABLE_WORK_AREA (range_table_work
, c
, c1
);
2459 else if (!SAME_CHARSET_P (c
, c1
))
2460 FREE_STACK_RETURN (REG_ERANGE
);
2463 /* Range from C to C. */
2466 /* Set the range ... */
2467 if (SINGLE_BYTE_CHAR_P (c
))
2468 /* ... into bitmap. */
2471 int range_start
= c
, range_end
= c1
;
2473 /* If the start is after the end, the range is empty. */
2474 if (range_start
> range_end
)
2476 if (syntax
& RE_NO_EMPTY_RANGES
)
2477 FREE_STACK_RETURN (REG_ERANGE
);
2478 /* Else, repeat the loop. */
2482 for (this_char
= range_start
; this_char
<= range_end
;
2484 SET_LIST_BIT (TRANSLATE (this_char
));
2488 /* ... into range table. */
2489 SET_RANGE_TABLE_WORK_AREA (range_table_work
, c
, c1
);
2492 /* Discard any (non)matching list bytes that are all 0 at the
2493 end of the map. Decrease the map-length byte too. */
2494 while ((int) b
[-1] > 0 && b
[b
[-1] - 1] == 0)
2498 /* Build real range table from work area. */
2499 if (RANGE_TABLE_WORK_USED (range_table_work
)
2500 || RANGE_TABLE_WORK_BITS (range_table_work
))
2503 int used
= RANGE_TABLE_WORK_USED (range_table_work
);
2505 /* Allocate space for COUNT + RANGE_TABLE. Needs two
2506 bytes for flags, two for COUNT, and three bytes for
2508 GET_BUFFER_SPACE (4 + used
* 3);
2510 /* Indicate the existence of range table. */
2511 laststart
[1] |= 0x80;
2513 /* Store the character class flag bits into the range table.
2514 If not in emacs, these flag bits are always 0. */
2515 *b
++ = RANGE_TABLE_WORK_BITS (range_table_work
) & 0xff;
2516 *b
++ = RANGE_TABLE_WORK_BITS (range_table_work
) >> 8;
2518 STORE_NUMBER_AND_INCR (b
, used
/ 2);
2519 for (i
= 0; i
< used
; i
++)
2520 STORE_CHARACTER_AND_INCR
2521 (b
, RANGE_TABLE_WORK_ELT (range_table_work
, i
));
2528 if (syntax
& RE_NO_BK_PARENS
)
2535 if (syntax
& RE_NO_BK_PARENS
)
2542 if (syntax
& RE_NEWLINE_ALT
)
2549 if (syntax
& RE_NO_BK_VBAR
)
2556 if (syntax
& RE_INTERVALS
&& syntax
& RE_NO_BK_BRACES
)
2557 goto handle_interval
;
2563 if (p
== pend
) FREE_STACK_RETURN (REG_EESCAPE
);
2565 /* Do not translate the character after the \, so that we can
2566 distinguish, e.g., \B from \b, even if we normally would
2567 translate, e.g., B to b. */
2573 if (syntax
& RE_NO_BK_PARENS
)
2574 goto normal_backslash
;
2581 /* Look for a special (?...) construct */
2582 if ((syntax
& RE_SHY_GROUPS
) && *p
== '?')
2584 PATFETCH (c
); /* Gobble up the '?'. */
2588 case ':': shy
= 1; break;
2590 /* Only (?:...) is supported right now. */
2591 FREE_STACK_RETURN (REG_BADPAT
);
2602 if (COMPILE_STACK_FULL
)
2604 RETALLOC (compile_stack
.stack
, compile_stack
.size
<< 1,
2605 compile_stack_elt_t
);
2606 if (compile_stack
.stack
== NULL
) return REG_ESPACE
;
2608 compile_stack
.size
<<= 1;
2611 /* These are the values to restore when we hit end of this
2612 group. They are all relative offsets, so that if the
2613 whole pattern moves because of realloc, they will still
2615 COMPILE_STACK_TOP
.begalt_offset
= begalt
- bufp
->buffer
;
2616 COMPILE_STACK_TOP
.fixup_alt_jump
2617 = fixup_alt_jump
? fixup_alt_jump
- bufp
->buffer
+ 1 : 0;
2618 COMPILE_STACK_TOP
.laststart_offset
= b
- bufp
->buffer
;
2619 COMPILE_STACK_TOP
.regnum
= shy
? -regnum
: regnum
;
2622 start_memory for groups beyond the last one we can
2623 represent in the compiled pattern. */
2624 if (regnum
<= MAX_REGNUM
&& !shy
)
2625 BUF_PUSH_2 (start_memory
, regnum
);
2627 compile_stack
.avail
++;
2632 /* If we've reached MAX_REGNUM groups, then this open
2633 won't actually generate any code, so we'll have to
2634 clear pending_exact explicitly. */
2640 if (syntax
& RE_NO_BK_PARENS
) goto normal_backslash
;
2642 if (COMPILE_STACK_EMPTY
)
2644 if (syntax
& RE_UNMATCHED_RIGHT_PAREN_ORD
)
2645 goto normal_backslash
;
2647 FREE_STACK_RETURN (REG_ERPAREN
);
2653 /* See similar code for backslashed left paren above. */
2654 if (COMPILE_STACK_EMPTY
)
2656 if (syntax
& RE_UNMATCHED_RIGHT_PAREN_ORD
)
2659 FREE_STACK_RETURN (REG_ERPAREN
);
2662 /* Since we just checked for an empty stack above, this
2663 ``can't happen''. */
2664 assert (compile_stack
.avail
!= 0);
2666 /* We don't just want to restore into `regnum', because
2667 later groups should continue to be numbered higher,
2668 as in `(ab)c(de)' -- the second group is #2. */
2669 regnum_t this_group_regnum
;
2671 compile_stack
.avail
--;
2672 begalt
= bufp
->buffer
+ COMPILE_STACK_TOP
.begalt_offset
;
2674 = COMPILE_STACK_TOP
.fixup_alt_jump
2675 ? bufp
->buffer
+ COMPILE_STACK_TOP
.fixup_alt_jump
- 1
2677 laststart
= bufp
->buffer
+ COMPILE_STACK_TOP
.laststart_offset
;
2678 this_group_regnum
= COMPILE_STACK_TOP
.regnum
;
2679 /* If we've reached MAX_REGNUM groups, then this open
2680 won't actually generate any code, so we'll have to
2681 clear pending_exact explicitly. */
2684 /* We're at the end of the group, so now we know how many
2685 groups were inside this one. */
2686 if (this_group_regnum
<= MAX_REGNUM
&& this_group_regnum
> 0)
2687 BUF_PUSH_2 (stop_memory
, this_group_regnum
);
2692 case '|': /* `\|'. */
2693 if (syntax
& RE_LIMITED_OPS
|| syntax
& RE_NO_BK_VBAR
)
2694 goto normal_backslash
;
2696 if (syntax
& RE_LIMITED_OPS
)
2699 /* Insert before the previous alternative a jump which
2700 jumps to this alternative if the former fails. */
2701 GET_BUFFER_SPACE (3);
2702 INSERT_JUMP (on_failure_jump
, begalt
, b
+ 6);
2706 /* The alternative before this one has a jump after it
2707 which gets executed if it gets matched. Adjust that
2708 jump so it will jump to this alternative's analogous
2709 jump (put in below, which in turn will jump to the next
2710 (if any) alternative's such jump, etc.). The last such
2711 jump jumps to the correct final destination. A picture:
2717 If we are at `b', then fixup_alt_jump right now points to a
2718 three-byte space after `a'. We'll put in the jump, set
2719 fixup_alt_jump to right after `b', and leave behind three
2720 bytes which we'll fill in when we get to after `c'. */
2724 /* Mark and leave space for a jump after this alternative,
2725 to be filled in later either by next alternative or
2726 when know we're at the end of a series of alternatives. */
2728 GET_BUFFER_SPACE (3);
2737 /* If \{ is a literal. */
2738 if (!(syntax
& RE_INTERVALS
)
2739 /* If we're at `\{' and it's not the open-interval
2741 || (syntax
& RE_NO_BK_BRACES
)
2742 /* What is that? -sm */
2743 /* || (p - 2 == pattern && p == pend) */)
2744 goto normal_backslash
;
2748 /* If got here, then the syntax allows intervals. */
2750 /* At least (most) this many matches must be made. */
2751 int lower_bound
= 0, upper_bound
= -1;
2757 if (syntax
& RE_NO_BK_BRACES
)
2758 goto unfetch_interval
;
2760 FREE_STACK_RETURN (REG_EBRACE
);
2763 GET_UNSIGNED_NUMBER (lower_bound
);
2766 GET_UNSIGNED_NUMBER (upper_bound
);
2768 /* Interval such as `{1}' => match exactly once. */
2769 upper_bound
= lower_bound
;
2771 if (lower_bound
< 0 || upper_bound
> RE_DUP_MAX
2772 || (upper_bound
>= 0 && lower_bound
> upper_bound
))
2774 if (syntax
& RE_NO_BK_BRACES
)
2775 goto unfetch_interval
;
2777 FREE_STACK_RETURN (REG_BADBR
);
2780 if (!(syntax
& RE_NO_BK_BRACES
))
2782 if (c
!= '\\') FREE_STACK_RETURN (REG_EBRACE
);
2789 if (syntax
& RE_NO_BK_BRACES
)
2790 goto unfetch_interval
;
2792 FREE_STACK_RETURN (REG_BADBR
);
2795 /* We just parsed a valid interval. */
2797 /* If it's invalid to have no preceding re. */
2800 if (syntax
& RE_CONTEXT_INVALID_OPS
)
2801 FREE_STACK_RETURN (REG_BADRPT
);
2802 else if (syntax
& RE_CONTEXT_INDEP_OPS
)
2805 goto unfetch_interval
;
2808 if (upper_bound
== 0)
2809 /* If the upper bound is zero, just drop the sub pattern
2812 else if (lower_bound
== 1 && upper_bound
== 1)
2813 /* Just match it once: nothing to do here. */
2816 /* Otherwise, we have a nontrivial interval. When
2817 we're all done, the pattern will look like:
2818 set_number_at <jump count> <upper bound>
2819 set_number_at <succeed_n count> <lower bound>
2820 succeed_n <after jump addr> <succeed_n count>
2822 jump_n <succeed_n addr> <jump count>
2823 (The upper bound and `jump_n' are omitted if
2824 `upper_bound' is 1, though.) */
2826 { /* If the upper bound is > 1, we need to insert
2827 more at the end of the loop. */
2828 unsigned int nbytes
= (upper_bound
< 0 ? 3
2829 : upper_bound
> 1 ? 5 : 0);
2830 unsigned int startoffset
= 0;
2832 GET_BUFFER_SPACE (20); /* We might use less. */
2834 if (lower_bound
== 0)
2836 /* A succeed_n that starts with 0 is really a
2837 a simple on_failure_jump_loop. */
2838 INSERT_JUMP (on_failure_jump_loop
, laststart
,
2844 /* Initialize lower bound of the `succeed_n', even
2845 though it will be set during matching by its
2846 attendant `set_number_at' (inserted next),
2847 because `re_compile_fastmap' needs to know.
2848 Jump to the `jump_n' we might insert below. */
2849 INSERT_JUMP2 (succeed_n
, laststart
,
2854 /* Code to initialize the lower bound. Insert
2855 before the `succeed_n'. The `5' is the last two
2856 bytes of this `set_number_at', plus 3 bytes of
2857 the following `succeed_n'. */
2858 insert_op2 (set_number_at
, laststart
, 5, lower_bound
, b
);
2863 if (upper_bound
< 0)
2865 /* A negative upper bound stands for infinity,
2866 in which case it degenerates to a plain jump. */
2867 STORE_JUMP (jump
, b
, laststart
+ startoffset
);
2870 else if (upper_bound
> 1)
2871 { /* More than one repetition is allowed, so
2872 append a backward jump to the `succeed_n'
2873 that starts this interval.
2875 When we've reached this during matching,
2876 we'll have matched the interval once, so
2877 jump back only `upper_bound - 1' times. */
2878 STORE_JUMP2 (jump_n
, b
, laststart
+ startoffset
,
2882 /* The location we want to set is the second
2883 parameter of the `jump_n'; that is `b-2' as
2884 an absolute address. `laststart' will be
2885 the `set_number_at' we're about to insert;
2886 `laststart+3' the number to set, the source
2887 for the relative address. But we are
2888 inserting into the middle of the pattern --
2889 so everything is getting moved up by 5.
2890 Conclusion: (b - 2) - (laststart + 3) + 5,
2891 i.e., b - laststart.
2893 We insert this at the beginning of the loop
2894 so that if we fail during matching, we'll
2895 reinitialize the bounds. */
2896 insert_op2 (set_number_at
, laststart
, b
- laststart
,
2897 upper_bound
- 1, b
);
2902 beg_interval
= NULL
;
2907 /* If an invalid interval, match the characters as literals. */
2908 assert (beg_interval
);
2910 beg_interval
= NULL
;
2912 /* normal_char and normal_backslash need `c'. */
2915 if (!(syntax
& RE_NO_BK_BRACES
))
2917 assert (p
> pattern
&& p
[-1] == '\\');
2918 goto normal_backslash
;
2924 /* There is no way to specify the before_dot and after_dot
2925 operators. rms says this is ok. --karl */
2933 BUF_PUSH_2 (syntaxspec
, syntax_spec_code
[c
]);
2939 BUF_PUSH_2 (notsyntaxspec
, syntax_spec_code
[c
]);
2945 BUF_PUSH_2 (categoryspec
, c
);
2951 BUF_PUSH_2 (notcategoryspec
, c
);
2958 BUF_PUSH_2 (syntaxspec
, Sword
);
2964 BUF_PUSH_2 (notsyntaxspec
, Sword
);
2977 BUF_PUSH (wordbound
);
2981 BUF_PUSH (notwordbound
);
2992 case '1': case '2': case '3': case '4': case '5':
2993 case '6': case '7': case '8': case '9':
2994 if (syntax
& RE_NO_BK_REFS
)
3000 FREE_STACK_RETURN (REG_ESUBREG
);
3002 /* Can't back reference to a subexpression if inside of it. */
3003 if (group_in_compile_stack (compile_stack
, c1
))
3007 BUF_PUSH_2 (duplicate
, c1
);
3013 if (syntax
& RE_BK_PLUS_QM
)
3016 goto normal_backslash
;
3020 /* You might think it would be useful for \ to mean
3021 not to translate; but if we don't translate it
3022 it will never match anything. */
3030 /* Expects the character in `c'. */
3032 /* If no exactn currently being built. */
3035 /* If last exactn not at current position. */
3036 || pending_exact
+ *pending_exact
+ 1 != b
3038 /* We have only one byte following the exactn for the count. */
3039 || *pending_exact
>= (1 << BYTEWIDTH
) - MAX_MULTIBYTE_LENGTH
3041 /* If followed by a repetition operator. */
3042 || (p
!= pend
&& (*p
== '*' || *p
== '^'))
3043 || ((syntax
& RE_BK_PLUS_QM
)
3044 ? p
+ 1 < pend
&& *p
== '\\' && (p
[1] == '+' || p
[1] == '?')
3045 : p
!= pend
&& (*p
== '+' || *p
== '?'))
3046 || ((syntax
& RE_INTERVALS
)
3047 && ((syntax
& RE_NO_BK_BRACES
)
3048 ? p
!= pend
&& *p
== '{'
3049 : p
+ 1 < pend
&& p
[0] == '\\' && p
[1] == '{')))
3051 /* Start building a new exactn. */
3055 BUF_PUSH_2 (exactn
, 0);
3056 pending_exact
= b
- 1;
3059 GET_BUFFER_SPACE (MAX_MULTIBYTE_LENGTH
);
3061 int len
= CHAR_STRING (c
, b
);
3063 (*pending_exact
) += len
;
3068 } /* while p != pend */
3071 /* Through the pattern now. */
3075 if (!COMPILE_STACK_EMPTY
)
3076 FREE_STACK_RETURN (REG_EPAREN
);
3078 /* If we don't want backtracking, force success
3079 the first time we reach the end of the compiled pattern. */
3080 if (syntax
& RE_NO_POSIX_BACKTRACKING
)
3083 free (compile_stack
.stack
);
3085 /* We have succeeded; set the length of the buffer. */
3086 bufp
->used
= b
- bufp
->buffer
;
3091 re_compile_fastmap (bufp
);
3092 DEBUG_PRINT1 ("\nCompiled pattern: \n");
3093 print_compiled_pattern (bufp
);
3098 #ifndef MATCH_MAY_ALLOCATE
3099 /* Initialize the failure stack to the largest possible stack. This
3100 isn't necessary unless we're trying to avoid calling alloca in
3101 the search and match routines. */
3103 int num_regs
= bufp
->re_nsub
+ 1;
3105 if (fail_stack
.size
< re_max_failures
* TYPICAL_FAILURE_SIZE
)
3107 fail_stack
.size
= re_max_failures
* TYPICAL_FAILURE_SIZE
;
3109 if (! fail_stack
.stack
)
3111 = (fail_stack_elt_t
*) malloc (fail_stack
.size
3112 * sizeof (fail_stack_elt_t
));
3115 = (fail_stack_elt_t
*) realloc (fail_stack
.stack
,
3117 * sizeof (fail_stack_elt_t
)));
3120 regex_grow_registers (num_regs
);
3122 #endif /* not MATCH_MAY_ALLOCATE */
3125 } /* regex_compile */
3127 /* Subroutines for `regex_compile'. */
3129 /* Store OP at LOC followed by two-byte integer parameter ARG. */
3132 store_op1 (op
, loc
, arg
)
3137 *loc
= (unsigned char) op
;
3138 STORE_NUMBER (loc
+ 1, arg
);
3142 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
3145 store_op2 (op
, loc
, arg1
, arg2
)
3150 *loc
= (unsigned char) op
;
3151 STORE_NUMBER (loc
+ 1, arg1
);
3152 STORE_NUMBER (loc
+ 3, arg2
);
3156 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
3157 for OP followed by two-byte integer parameter ARG. */
3160 insert_op1 (op
, loc
, arg
, end
)
3166 register unsigned char *pfrom
= end
;
3167 register unsigned char *pto
= end
+ 3;
3169 while (pfrom
!= loc
)
3172 store_op1 (op
, loc
, arg
);
3176 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
3179 insert_op2 (op
, loc
, arg1
, arg2
, end
)
3185 register unsigned char *pfrom
= end
;
3186 register unsigned char *pto
= end
+ 5;
3188 while (pfrom
!= loc
)
3191 store_op2 (op
, loc
, arg1
, arg2
);
3195 /* P points to just after a ^ in PATTERN. Return true if that ^ comes
3196 after an alternative or a begin-subexpression. We assume there is at
3197 least one character before the ^. */
3200 at_begline_loc_p (pattern
, p
, syntax
)
3201 const unsigned char *pattern
, *p
;
3202 reg_syntax_t syntax
;
3204 const unsigned char *prev
= p
- 2;
3205 boolean prev_prev_backslash
= prev
> pattern
&& prev
[-1] == '\\';
3208 /* After a subexpression? */
3209 (*prev
== '(' && (syntax
& RE_NO_BK_PARENS
|| prev_prev_backslash
))
3210 /* After an alternative? */
3211 || (*prev
== '|' && (syntax
& RE_NO_BK_VBAR
|| prev_prev_backslash
))
3212 /* After a shy subexpression? */
3213 || ((syntax
& RE_SHY_GROUPS
) && prev
- 2 >= pattern
3214 && prev
[-1] == '?' && prev
[-2] == '('
3215 && (syntax
& RE_NO_BK_PARENS
3216 || (prev
- 3 >= pattern
&& prev
[-3] == '\\')));
3220 /* The dual of at_begline_loc_p. This one is for $. We assume there is
3221 at least one character after the $, i.e., `P < PEND'. */
3224 at_endline_loc_p (p
, pend
, syntax
)
3225 const unsigned char *p
, *pend
;
3226 reg_syntax_t syntax
;
3228 const unsigned char *next
= p
;
3229 boolean next_backslash
= *next
== '\\';
3230 const unsigned char *next_next
= p
+ 1 < pend
? p
+ 1 : 0;
3233 /* Before a subexpression? */
3234 (syntax
& RE_NO_BK_PARENS
? *next
== ')'
3235 : next_backslash
&& next_next
&& *next_next
== ')')
3236 /* Before an alternative? */
3237 || (syntax
& RE_NO_BK_VBAR
? *next
== '|'
3238 : next_backslash
&& next_next
&& *next_next
== '|');
3242 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
3243 false if it's not. */
3246 group_in_compile_stack (compile_stack
, regnum
)
3247 compile_stack_type compile_stack
;
3252 for (this_element
= compile_stack
.avail
- 1;
3255 if (compile_stack
.stack
[this_element
].regnum
== regnum
)
3262 If fastmap is non-NULL, go through the pattern and fill fastmap
3263 with all the possible leading chars. If fastmap is NULL, don't
3264 bother filling it up (obviously) and only return whether the
3265 pattern could potentially match the empty string.
3267 Return 1 if p..pend might match the empty string.
3268 Return 0 if p..pend matches at least one char.
3269 Return -1 if p..pend matches at least one char, but fastmap was not
3271 Return -2 if an error occurred. */
3274 analyse_first (p
, pend
, fastmap
, multibyte
)
3275 unsigned char *p
, *pend
;
3277 const int multibyte
;
3281 #ifdef MATCH_MAY_ALLOCATE
3282 fail_stack_type fail_stack
;
3284 #ifndef REGEX_MALLOC
3288 #if defined (REL_ALLOC) && defined (REGEX_MALLOC)
3289 /* This holds the pointer to the failure stack, when
3290 it is allocated relocatably. */
3291 fail_stack_elt_t
*failure_stack_ptr
;
3294 /* Assume that each path through the pattern can be null until
3295 proven otherwise. We set this false at the bottom of switch
3296 statement, to which we get only if a particular path doesn't
3297 match the empty string. */
3298 boolean path_can_be_null
= true;
3300 /* If all elements for base leading-codes in fastmap is set, this
3301 flag is set true. */
3302 boolean match_any_multibyte_characters
= false;
3308 /* The loop below works as follows:
3309 - It has a working-list kept in the PATTERN_STACK and which basically
3310 starts by only containing a pointer to the first operation.
3311 - If the opcode we're looking at is a match against some set of
3312 chars, then we add those chars to the fastmap and go on to the
3313 next work element from the worklist (done via `break').
3314 - If the opcode is a control operator on the other hand, we either
3315 ignore it (if it's meaningless at this point, such as `start_memory')
3316 or execute it (if it's a jump). If the jump has several destinations
3317 (i.e. `on_failure_jump'), then we push the other destination onto the
3319 We guarantee termination by ignoring backward jumps (more or less),
3320 so that `p' is monotonically increasing. More to the point, we
3321 never set `p' (or push) anything `<= p1'. */
3323 /* If can_be_null is set, then the fastmap will not be used anyway. */
3326 /* `p1' is used as a marker of how far back a `on_failure_jump'
3327 can go without being ignored. It is normally equal to `p'
3328 (which prevents any backward `on_failure_jump') except right
3329 after a plain `jump', to allow patterns such as:
3332 10: on_failure_jump 3
3333 as used for the *? operator. */
3334 unsigned char *p1
= p
;
3338 if (path_can_be_null
)
3339 return (RESET_FAIL_STACK (), 1);
3341 /* We have reached the (effective) end of pattern. */
3342 if (PATTERN_STACK_EMPTY ())
3343 return (RESET_FAIL_STACK (), 0);
3345 p
= (unsigned char*) POP_PATTERN_OP ();
3346 path_can_be_null
= true;
3350 /* We should never be about to go beyond the end of the pattern. */
3353 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *p
++))
3360 /* If the first character has to match a backreference, that means
3361 that the group was empty (since it already matched). Since this
3362 is the only case that interests us here, we can assume that the
3363 backreference must match the empty string. */
3368 /* Following are the cases which match a character. These end
3372 if (fastmap
) fastmap
[p
[1]] = 1;
3377 /* We could put all the chars except for \n (and maybe \0)
3378 but we don't bother since it is generally not worth it. */
3379 if (!fastmap
) break;
3380 return (RESET_FAIL_STACK (), -1);
3384 /* Chars beyond end of bitmap are possible matches.
3385 All the single-byte codes can occur in multibyte buffers.
3386 So any that are not listed in the charset
3387 are possible matches, even in multibyte buffers. */
3388 if (!fastmap
) break;
3389 for (j
= CHARSET_BITMAP_SIZE (&p
[-1]) * BYTEWIDTH
;
3390 j
< (1 << BYTEWIDTH
); j
++)
3394 if (!fastmap
) break;
3395 not = (re_opcode_t
) *(p
- 1) == charset_not
;
3396 for (j
= CHARSET_BITMAP_SIZE (&p
[-1]) * BYTEWIDTH
- 1, p
++;
3398 if (!!(p
[j
/ BYTEWIDTH
] & (1 << (j
% BYTEWIDTH
))) ^ not)
3401 if ((not && multibyte
)
3402 /* Any character set can possibly contain a character
3403 which doesn't match the specified set of characters. */
3404 || (CHARSET_RANGE_TABLE_EXISTS_P (&p
[-2])
3405 && CHARSET_RANGE_TABLE_BITS (&p
[-2]) != 0))
3406 /* If we can match a character class, we can match
3407 any character set. */
3409 set_fastmap_for_multibyte_characters
:
3410 if (match_any_multibyte_characters
== false)
3412 for (j
= 0x80; j
< 0xA0; j
++) /* XXX */
3413 if (BASE_LEADING_CODE_P (j
))
3415 match_any_multibyte_characters
= true;
3419 else if (!not && CHARSET_RANGE_TABLE_EXISTS_P (&p
[-2])
3420 && match_any_multibyte_characters
== false)
3422 /* Set fastmap[I] 1 where I is a base leading code of each
3423 multibyte character in the range table. */
3426 /* Make P points the range table. `+ 2' is to skip flag
3427 bits for a character class. */
3428 p
+= CHARSET_BITMAP_SIZE (&p
[-2]) + 2;
3430 /* Extract the number of ranges in range table into COUNT. */
3431 EXTRACT_NUMBER_AND_INCR (count
, p
);
3432 for (; count
> 0; count
--, p
+= 2 * 3) /* XXX */
3434 /* Extract the start of each range. */
3435 EXTRACT_CHARACTER (c
, p
);
3436 j
= CHAR_CHARSET (c
);
3437 fastmap
[CHARSET_LEADING_CODE_BASE (j
)] = 1;
3444 if (!fastmap
) break;
3446 not = (re_opcode_t
)p
[-1] == notsyntaxspec
;
3448 for (j
= 0; j
< (1 << BYTEWIDTH
); j
++)
3449 if ((SYNTAX (j
) == (enum syntaxcode
) k
) ^ not)
3453 /* This match depends on text properties. These end with
3454 aborting optimizations. */
3455 return (RESET_FAIL_STACK (), -1);
3458 case notcategoryspec
:
3459 if (!fastmap
) break;
3460 not = (re_opcode_t
)p
[-1] == notcategoryspec
;
3462 for (j
= 0; j
< (1 << BYTEWIDTH
); j
++)
3463 if ((CHAR_HAS_CATEGORY (j
, k
)) ^ not)
3467 /* Any character set can possibly contain a character
3468 whose category is K (or not). */
3469 goto set_fastmap_for_multibyte_characters
;
3472 /* All cases after this match the empty string. These end with
3492 EXTRACT_NUMBER_AND_INCR (j
, p
);
3494 /* Backward jumps can only go back to code that we've already
3495 visited. `re_compile' should make sure this is true. */
3498 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *p
))
3500 case on_failure_jump
:
3501 case on_failure_keep_string_jump
:
3502 case on_failure_jump_loop
:
3503 case on_failure_jump_nastyloop
:
3504 case on_failure_jump_smart
:
3510 /* Keep `p1' to allow the `on_failure_jump' we are jumping to
3511 to jump back to "just after here". */
3514 case on_failure_jump
:
3515 case on_failure_keep_string_jump
:
3516 case on_failure_jump_nastyloop
:
3517 case on_failure_jump_loop
:
3518 case on_failure_jump_smart
:
3519 EXTRACT_NUMBER_AND_INCR (j
, p
);
3521 ; /* Backward jump to be ignored. */
3522 else if (!PUSH_PATTERN_OP (p
+ j
, fail_stack
))
3523 return (RESET_FAIL_STACK (), -2);
3528 /* This code simply does not properly handle forward jump_n. */
3529 DEBUG_STATEMENT (EXTRACT_NUMBER (j
, p
); assert (j
< 0));
3531 /* jump_n can either jump or fall through. The (backward) jump
3532 case has already been handled, so we only need to look at the
3533 fallthrough case. */
3537 /* If N == 0, it should be an on_failure_jump_loop instead. */
3538 DEBUG_STATEMENT (EXTRACT_NUMBER (j
, p
+ 2); assert (j
> 0));
3540 /* We only care about one iteration of the loop, so we don't
3541 need to consider the case where this behaves like an
3558 abort (); /* We have listed all the cases. */
3561 /* Getting here means we have found the possible starting
3562 characters for one path of the pattern -- and that the empty
3563 string does not match. We need not follow this path further.
3564 Instead, look at the next alternative (remembered on the
3565 stack), or quit if no more. The test at the top of the loop
3566 does these things. */
3567 path_can_be_null
= false;
3571 return (RESET_FAIL_STACK (), 0);
3572 } /* analyse_first */
3574 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
3575 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
3576 characters can start a string that matches the pattern. This fastmap
3577 is used by re_search to skip quickly over impossible starting points.
3579 Character codes above (1 << BYTEWIDTH) are not represented in the
3580 fastmap, but the leading codes are represented. Thus, the fastmap
3581 indicates which character sets could start a match.
3583 The caller must supply the address of a (1 << BYTEWIDTH)-byte data
3584 area as BUFP->fastmap.
3586 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
3589 Returns 0 if we succeed, -2 if an internal error. */
3592 re_compile_fastmap (bufp
)
3593 struct re_pattern_buffer
*bufp
;
3595 char *fastmap
= bufp
->fastmap
;
3598 assert (fastmap
&& bufp
->buffer
);
3600 bzero (fastmap
, 1 << BYTEWIDTH
); /* Assume nothing's valid. */
3601 bufp
->fastmap_accurate
= 1; /* It will be when we're done. */
3603 analysis
= analyse_first (bufp
->buffer
, bufp
->buffer
+ bufp
->used
,
3604 fastmap
, RE_MULTIBYTE_P (bufp
));
3607 bufp
->can_be_null
= (analysis
!= 0);
3609 } /* re_compile_fastmap */
3611 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
3612 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
3613 this memory for recording register information. STARTS and ENDS
3614 must be allocated using the malloc library routine, and must each
3615 be at least NUM_REGS * sizeof (regoff_t) bytes long.
3617 If NUM_REGS == 0, then subsequent matches should allocate their own
3620 Unless this function is called, the first search or match using
3621 PATTERN_BUFFER will allocate its own register data, without
3622 freeing the old data. */
3625 re_set_registers (bufp
, regs
, num_regs
, starts
, ends
)
3626 struct re_pattern_buffer
*bufp
;
3627 struct re_registers
*regs
;
3629 regoff_t
*starts
, *ends
;
3633 bufp
->regs_allocated
= REGS_REALLOCATE
;
3634 regs
->num_regs
= num_regs
;
3635 regs
->start
= starts
;
3640 bufp
->regs_allocated
= REGS_UNALLOCATED
;
3642 regs
->start
= regs
->end
= (regoff_t
*) 0;
3646 /* Searching routines. */
3648 /* Like re_search_2, below, but only one string is specified, and
3649 doesn't let you say where to stop matching. */
3652 re_search (bufp
, string
, size
, startpos
, range
, regs
)
3653 struct re_pattern_buffer
*bufp
;
3655 int size
, startpos
, range
;
3656 struct re_registers
*regs
;
3658 return re_search_2 (bufp
, NULL
, 0, string
, size
, startpos
, range
,
3662 /* End address of virtual concatenation of string. */
3663 #define STOP_ADDR_VSTRING(P) \
3664 (((P) >= size1 ? string2 + size2 : string1 + size1))
3666 /* Address of POS in the concatenation of virtual string. */
3667 #define POS_ADDR_VSTRING(POS) \
3668 (((POS) >= size1 ? string2 - size1 : string1) + (POS))
3670 /* Using the compiled pattern in BUFP->buffer, first tries to match the
3671 virtual concatenation of STRING1 and STRING2, starting first at index
3672 STARTPOS, then at STARTPOS + 1, and so on.
3674 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
3676 RANGE is how far to scan while trying to match. RANGE = 0 means try
3677 only at STARTPOS; in general, the last start tried is STARTPOS +
3680 In REGS, return the indices of the virtual concatenation of STRING1
3681 and STRING2 that matched the entire BUFP->buffer and its contained
3684 Do not consider matching one past the index STOP in the virtual
3685 concatenation of STRING1 and STRING2.
3687 We return either the position in the strings at which the match was
3688 found, -1 if no match, or -2 if error (such as failure
3692 re_search_2 (bufp
, str1
, size1
, str2
, size2
, startpos
, range
, regs
, stop
)
3693 struct re_pattern_buffer
*bufp
;
3694 const char *str1
, *str2
;
3698 struct re_registers
*regs
;
3702 re_char
*string1
= (re_char
*) str1
;
3703 re_char
*string2
= (re_char
*) str2
;
3704 register char *fastmap
= bufp
->fastmap
;
3705 register RE_TRANSLATE_TYPE translate
= bufp
->translate
;
3706 int total_size
= size1
+ size2
;
3707 int endpos
= startpos
+ range
;
3708 int anchored_start
= 0;
3710 /* Nonzero if we have to concern multibyte character. */
3711 const boolean multibyte
= RE_MULTIBYTE_P (bufp
);
3713 /* Check for out-of-range STARTPOS. */
3714 if (startpos
< 0 || startpos
> total_size
)
3717 /* Fix up RANGE if it might eventually take us outside
3718 the virtual concatenation of STRING1 and STRING2.
3719 Make sure we won't move STARTPOS below 0 or above TOTAL_SIZE. */
3721 range
= 0 - startpos
;
3722 else if (endpos
> total_size
)
3723 range
= total_size
- startpos
;
3725 /* If the search isn't to be a backwards one, don't waste time in a
3726 search for a pattern anchored at beginning of buffer. */
3727 if (bufp
->used
> 0 && (re_opcode_t
) bufp
->buffer
[0] == begbuf
&& range
> 0)
3736 /* In a forward search for something that starts with \=.
3737 don't keep searching past point. */
3738 if (bufp
->used
> 0 && (re_opcode_t
) bufp
->buffer
[0] == at_dot
&& range
> 0)
3740 range
= PT_BYTE
- BEGV_BYTE
- startpos
;
3746 /* Update the fastmap now if not correct already. */
3747 if (fastmap
&& !bufp
->fastmap_accurate
)
3748 if (re_compile_fastmap (bufp
) == -2)
3751 /* See whether the pattern is anchored. */
3752 if (bufp
->buffer
[0] == begline
)
3756 gl_state
.object
= re_match_object
;
3758 int charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (startpos
));
3760 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object
, charpos
, 1);
3764 /* Loop through the string, looking for a place to start matching. */
3767 /* If the pattern is anchored,
3768 skip quickly past places we cannot match.
3769 We don't bother to treat startpos == 0 specially
3770 because that case doesn't repeat. */
3771 if (anchored_start
&& startpos
> 0)
3773 if (! (bufp
->newline_anchor
3774 && ((startpos
<= size1
? string1
[startpos
- 1]
3775 : string2
[startpos
- size1
- 1])
3780 /* If a fastmap is supplied, skip quickly over characters that
3781 cannot be the start of a match. If the pattern can match the
3782 null string, however, we don't need to skip characters; we want
3783 the first null string. */
3784 if (fastmap
&& startpos
< total_size
&& !bufp
->can_be_null
)
3786 register re_char
*d
;
3787 register unsigned int buf_ch
;
3789 d
= POS_ADDR_VSTRING (startpos
);
3791 if (range
> 0) /* Searching forwards. */
3793 register int lim
= 0;
3796 if (startpos
< size1
&& startpos
+ range
>= size1
)
3797 lim
= range
- (size1
- startpos
);
3799 /* Written out as an if-else to avoid testing `translate'
3801 if (RE_TRANSLATE_P (translate
))
3808 buf_ch
= STRING_CHAR_AND_LENGTH (d
, range
- lim
,
3811 buf_ch
= RE_TRANSLATE (translate
, buf_ch
);
3816 range
-= buf_charlen
;
3821 && !fastmap
[RE_TRANSLATE (translate
, *d
)])
3828 while (range
> lim
&& !fastmap
[*d
])
3834 startpos
+= irange
- range
;
3836 else /* Searching backwards. */
3838 int room
= (startpos
>= size1
3839 ? size2
+ size1
- startpos
3840 : size1
- startpos
);
3841 buf_ch
= RE_STRING_CHAR (d
, room
);
3842 buf_ch
= TRANSLATE (buf_ch
);
3844 if (! (buf_ch
>= 0400
3845 || fastmap
[buf_ch
]))
3850 /* If can't match the null string, and that's all we have left, fail. */
3851 if (range
>= 0 && startpos
== total_size
&& fastmap
3852 && !bufp
->can_be_null
)
3855 val
= re_match_2_internal (bufp
, string1
, size1
, string2
, size2
,
3856 startpos
, regs
, stop
);
3857 #ifndef REGEX_MALLOC
3874 /* Update STARTPOS to the next character boundary. */
3877 re_char
*p
= POS_ADDR_VSTRING (startpos
);
3878 re_char
*pend
= STOP_ADDR_VSTRING (startpos
);
3879 int len
= MULTIBYTE_FORM_LENGTH (p
, pend
- p
);
3897 /* Update STARTPOS to the previous character boundary. */
3900 re_char
*p
= POS_ADDR_VSTRING (startpos
);
3903 /* Find the head of multibyte form. */
3904 while (!CHAR_HEAD_P (*p
))
3909 if (MULTIBYTE_FORM_LENGTH (p
, len
+ 1) != (len
+ 1))
3926 /* Declarations and macros for re_match_2. */
3928 static int bcmp_translate
_RE_ARGS((re_char
*s1
, re_char
*s2
,
3930 RE_TRANSLATE_TYPE translate
,
3931 const int multibyte
));
3933 /* This converts PTR, a pointer into one of the search strings `string1'
3934 and `string2' into an offset from the beginning of that string. */
3935 #define POINTER_TO_OFFSET(ptr) \
3936 (FIRST_STRING_P (ptr) \
3937 ? ((regoff_t) ((ptr) - string1)) \
3938 : ((regoff_t) ((ptr) - string2 + size1)))
3940 /* Call before fetching a character with *d. This switches over to
3941 string2 if necessary.
3942 Check re_match_2_internal for a discussion of why end_match_2 might
3943 not be within string2 (but be equal to end_match_1 instead). */
3944 #define PREFETCH() \
3947 /* End of string2 => fail. */ \
3948 if (dend == end_match_2) \
3950 /* End of string1 => advance to string2. */ \
3952 dend = end_match_2; \
3956 /* Test if at very beginning or at very end of the virtual concatenation
3957 of `string1' and `string2'. If only one string, it's `string2'. */
3958 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
3959 #define AT_STRINGS_END(d) ((d) == end2)
3962 /* Test if D points to a character which is word-constituent. We have
3963 two special cases to check for: if past the end of string1, look at
3964 the first character in string2; and if before the beginning of
3965 string2, look at the last character in string1. */
3966 #define WORDCHAR_P(d) \
3967 (SYNTAX ((d) == end1 ? *string2 \
3968 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
3971 /* Disabled due to a compiler bug -- see comment at case wordbound */
3973 /* The comment at case wordbound is following one, but we don't use
3974 AT_WORD_BOUNDARY anymore to support multibyte form.
3976 The DEC Alpha C compiler 3.x generates incorrect code for the
3977 test WORDCHAR_P (d - 1) != WORDCHAR_P (d) in the expansion of
3978 AT_WORD_BOUNDARY, so this code is disabled. Expanding the
3979 macro and introducing temporary variables works around the bug. */
3982 /* Test if the character before D and the one at D differ with respect
3983 to being word-constituent. */
3984 #define AT_WORD_BOUNDARY(d) \
3985 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
3986 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
3989 /* Free everything we malloc. */
3990 #ifdef MATCH_MAY_ALLOCATE
3991 #define FREE_VAR(var) if (var) { REGEX_FREE (var); var = NULL; } else
3992 #define FREE_VARIABLES() \
3994 REGEX_FREE_STACK (fail_stack.stack); \
3995 FREE_VAR (regstart); \
3996 FREE_VAR (regend); \
3997 FREE_VAR (best_regstart); \
3998 FREE_VAR (best_regend); \
4001 #define FREE_VARIABLES() ((void)0) /* Do nothing! But inhibit gcc warning. */
4002 #endif /* not MATCH_MAY_ALLOCATE */
4005 /* Optimization routines. */
4007 /* If the operation is a match against one or more chars,
4008 return a pointer to the next operation, else return NULL. */
4009 static unsigned char *
4013 switch (SWITCH_ENUM_CAST (*p
++))
4024 if (CHARSET_RANGE_TABLE_EXISTS_P (p
- 1))
4027 p
= CHARSET_RANGE_TABLE (p
- 1);
4028 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
4029 p
= CHARSET_RANGE_TABLE_END (p
, mcnt
);
4032 p
+= 1 + CHARSET_BITMAP_SIZE (p
- 1);
4039 case notcategoryspec
:
4051 /* Jump over non-matching operations. */
4052 static unsigned char *
4053 skip_noops (p
, pend
)
4054 unsigned char *p
, *pend
;
4059 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *p
))
4068 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
4079 /* Non-zero if "p1 matches something" implies "p2 fails". */
4081 mutually_exclusive_p (bufp
, p1
, p2
)
4082 struct re_pattern_buffer
*bufp
;
4083 unsigned char *p1
, *p2
;
4086 const boolean multibyte
= RE_MULTIBYTE_P (bufp
);
4087 unsigned char *pend
= bufp
->buffer
+ bufp
->used
;
4089 assert (p1
>= bufp
->buffer
&& p1
< pend
4090 && p2
>= bufp
->buffer
&& p2
<= pend
);
4092 /* Skip over open/close-group commands.
4093 If what follows this loop is a ...+ construct,
4094 look at what begins its body, since we will have to
4095 match at least one of that. */
4096 p2
= skip_noops (p2
, pend
);
4097 /* The same skip can be done for p1, except that this function
4098 is only used in the case where p1 is a simple match operator. */
4099 /* p1 = skip_noops (p1, pend); */
4101 assert (p1
>= bufp
->buffer
&& p1
< pend
4102 && p2
>= bufp
->buffer
&& p2
<= pend
);
4104 op2
= p2
== pend
? succeed
: *p2
;
4106 switch (SWITCH_ENUM_CAST (op2
))
4110 /* If we're at the end of the pattern, we can change. */
4111 if (skip_one_char (p1
))
4113 DEBUG_PRINT1 (" End of pattern: fast loop.\n");
4119 if (!bufp
->newline_anchor
)
4124 register unsigned int c
4125 = (re_opcode_t
) *p2
== endline
? '\n'
4126 : RE_STRING_CHAR(p2
+ 2, pend
- p2
- 2);
4128 if ((re_opcode_t
) *p1
== exactn
)
4130 if (c
!= RE_STRING_CHAR (p1
+ 2, pend
- p1
- 2))
4132 DEBUG_PRINT3 (" '%c' != '%c' => fast loop.\n", c
, p1
[2]);
4137 else if ((re_opcode_t
) *p1
== charset
4138 || (re_opcode_t
) *p1
== charset_not
)
4140 int not = (re_opcode_t
) *p1
== charset_not
;
4142 /* Test if C is listed in charset (or charset_not)
4144 if (SINGLE_BYTE_CHAR_P (c
))
4146 if (c
< CHARSET_BITMAP_SIZE (p1
) * BYTEWIDTH
4147 && p1
[2 + c
/ BYTEWIDTH
] & (1 << (c
% BYTEWIDTH
)))
4150 else if (CHARSET_RANGE_TABLE_EXISTS_P (p1
))
4151 CHARSET_LOOKUP_RANGE_TABLE (not, c
, p1
);
4153 /* `not' is equal to 1 if c would match, which means
4154 that we can't change to pop_failure_jump. */
4157 DEBUG_PRINT1 (" No match => fast loop.\n");
4161 else if ((re_opcode_t
) *p1
== anychar
4164 DEBUG_PRINT1 (" . != \\n => fast loop.\n");
4173 if ((re_opcode_t
) *p1
== exactn
)
4174 /* Reuse the code above. */
4175 return mutually_exclusive_p (bufp
, p2
, p1
);
4178 /* It is hard to list up all the character in charset
4179 P2 if it includes multibyte character. Give up in
4181 else if (!multibyte
|| !CHARSET_RANGE_TABLE_EXISTS_P (p2
))
4183 /* Now, we are sure that P2 has no range table.
4184 So, for the size of bitmap in P2, `p2[1]' is
4185 enough. But P1 may have range table, so the
4186 size of bitmap table of P1 is extracted by
4187 using macro `CHARSET_BITMAP_SIZE'.
4189 Since we know that all the character listed in
4190 P2 is ASCII, it is enough to test only bitmap
4196 /* We win if the charset inside the loop
4197 has no overlap with the one after the loop. */
4200 && idx
< CHARSET_BITMAP_SIZE (p1
));
4202 if ((p2
[2 + idx
] & p1
[2 + idx
]) != 0)
4206 || idx
== CHARSET_BITMAP_SIZE (p1
))
4208 DEBUG_PRINT1 (" No match => fast loop.\n");
4212 else if ((re_opcode_t
) *p1
== charset
4213 || (re_opcode_t
) *p1
== charset_not
)
4216 /* We win if the charset_not inside the loop lists
4217 every character listed in the charset after. */
4218 for (idx
= 0; idx
< (int) p2
[1]; idx
++)
4219 if (! (p2
[2 + idx
] == 0
4220 || (idx
< CHARSET_BITMAP_SIZE (p1
)
4221 && ((p2
[2 + idx
] & ~ p1
[2 + idx
]) == 0))))
4226 DEBUG_PRINT1 (" No match => fast loop.\n");
4235 return ((re_opcode_t
) *p1
== syntaxspec
4236 && p1
[1] == (op2
== wordend
? Sword
: p2
[1]));
4240 return ((re_opcode_t
) *p1
== notsyntaxspec
4241 && p1
[1] == (op2
== wordend
? Sword
: p2
[1]));
4244 return (((re_opcode_t
) *p1
== notsyntaxspec
4245 || (re_opcode_t
) *p1
== syntaxspec
)
4250 return ((re_opcode_t
) *p1
== notcategoryspec
&& p1
[1] == p2
[1]);
4251 case notcategoryspec
:
4252 return ((re_opcode_t
) *p1
== categoryspec
&& p1
[1] == p2
[1]);
4264 /* Matching routines. */
4266 #ifndef emacs /* Emacs never uses this. */
4267 /* re_match is like re_match_2 except it takes only a single string. */
4270 re_match (bufp
, string
, size
, pos
, regs
)
4271 struct re_pattern_buffer
*bufp
;
4274 struct re_registers
*regs
;
4276 int result
= re_match_2_internal (bufp
, NULL
, 0, string
, size
,
4281 #endif /* not emacs */
4284 /* In Emacs, this is the string or buffer in which we
4285 are matching. It is used for looking up syntax properties. */
4286 Lisp_Object re_match_object
;
4289 /* re_match_2 matches the compiled pattern in BUFP against the
4290 the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
4291 and SIZE2, respectively). We start matching at POS, and stop
4294 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
4295 store offsets for the substring each group matched in REGS. See the
4296 documentation for exactly how many groups we fill.
4298 We return -1 if no match, -2 if an internal error (such as the
4299 failure stack overflowing). Otherwise, we return the length of the
4300 matched substring. */
4303 re_match_2 (bufp
, string1
, size1
, string2
, size2
, pos
, regs
, stop
)
4304 struct re_pattern_buffer
*bufp
;
4305 const char *string1
, *string2
;
4308 struct re_registers
*regs
;
4315 gl_state
.object
= re_match_object
;
4316 charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (pos
));
4317 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object
, charpos
, 1);
4320 result
= re_match_2_internal (bufp
, string1
, size1
, string2
, size2
,
4326 /* This is a separate function so that we can force an alloca cleanup
4329 re_match_2_internal (bufp
, string1
, size1
, string2
, size2
, pos
, regs
, stop
)
4330 struct re_pattern_buffer
*bufp
;
4331 re_char
*string1
, *string2
;
4334 struct re_registers
*regs
;
4337 /* General temporaries. */
4342 /* Just past the end of the corresponding string. */
4343 re_char
*end1
, *end2
;
4345 /* Pointers into string1 and string2, just past the last characters in
4346 each to consider matching. */
4347 re_char
*end_match_1
, *end_match_2
;
4349 /* Where we are in the data, and the end of the current string. */
4352 /* Used sometimes to remember where we were before starting matching
4353 an operator so that we can go back in case of failure. This "atomic"
4354 behavior of matching opcodes is indispensable to the correctness
4355 of the on_failure_keep_string_jump optimization. */
4358 /* Where we are in the pattern, and the end of the pattern. */
4359 unsigned char *p
= bufp
->buffer
;
4360 register unsigned char *pend
= p
+ bufp
->used
;
4362 /* We use this to map every character in the string. */
4363 RE_TRANSLATE_TYPE translate
= bufp
->translate
;
4365 /* Nonzero if we have to concern multibyte character. */
4366 const boolean multibyte
= RE_MULTIBYTE_P (bufp
);
4368 /* Failure point stack. Each place that can handle a failure further
4369 down the line pushes a failure point on this stack. It consists of
4370 regstart, and regend for all registers corresponding to
4371 the subexpressions we're currently inside, plus the number of such
4372 registers, and, finally, two char *'s. The first char * is where
4373 to resume scanning the pattern; the second one is where to resume
4374 scanning the strings. */
4375 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
4376 fail_stack_type fail_stack
;
4379 static unsigned failure_id
= 0;
4380 unsigned nfailure_points_pushed
= 0, nfailure_points_popped
= 0;
4383 #if defined (REL_ALLOC) && defined (REGEX_MALLOC)
4384 /* This holds the pointer to the failure stack, when
4385 it is allocated relocatably. */
4386 fail_stack_elt_t
*failure_stack_ptr
;
4389 /* We fill all the registers internally, independent of what we
4390 return, for use in backreferences. The number here includes
4391 an element for register zero. */
4392 unsigned num_regs
= bufp
->re_nsub
+ 1;
4394 /* Information on the contents of registers. These are pointers into
4395 the input strings; they record just what was matched (on this
4396 attempt) by a subexpression part of the pattern, that is, the
4397 regnum-th regstart pointer points to where in the pattern we began
4398 matching and the regnum-th regend points to right after where we
4399 stopped matching the regnum-th subexpression. (The zeroth register
4400 keeps track of what the whole pattern matches.) */
4401 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4402 re_char
**regstart
, **regend
;
4405 /* The following record the register info as found in the above
4406 variables when we find a match better than any we've seen before.
4407 This happens as we backtrack through the failure points, which in
4408 turn happens only if we have not yet matched the entire string. */
4409 unsigned best_regs_set
= false;
4410 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4411 re_char
**best_regstart
, **best_regend
;
4414 /* Logically, this is `best_regend[0]'. But we don't want to have to
4415 allocate space for that if we're not allocating space for anything
4416 else (see below). Also, we never need info about register 0 for
4417 any of the other register vectors, and it seems rather a kludge to
4418 treat `best_regend' differently than the rest. So we keep track of
4419 the end of the best match so far in a separate variable. We
4420 initialize this to NULL so that when we backtrack the first time
4421 and need to test it, it's not garbage. */
4422 re_char
*match_end
= NULL
;
4425 /* Counts the total number of registers pushed. */
4426 unsigned num_regs_pushed
= 0;
4429 DEBUG_PRINT1 ("\n\nEntering re_match_2.\n");
4433 #ifdef MATCH_MAY_ALLOCATE
4434 /* Do not bother to initialize all the register variables if there are
4435 no groups in the pattern, as it takes a fair amount of time. If
4436 there are groups, we include space for register 0 (the whole
4437 pattern), even though we never use it, since it simplifies the
4438 array indexing. We should fix this. */
4441 regstart
= REGEX_TALLOC (num_regs
, re_char
*);
4442 regend
= REGEX_TALLOC (num_regs
, re_char
*);
4443 best_regstart
= REGEX_TALLOC (num_regs
, re_char
*);
4444 best_regend
= REGEX_TALLOC (num_regs
, re_char
*);
4446 if (!(regstart
&& regend
&& best_regstart
&& best_regend
))
4454 /* We must initialize all our variables to NULL, so that
4455 `FREE_VARIABLES' doesn't try to free them. */
4456 regstart
= regend
= best_regstart
= best_regend
= NULL
;
4458 #endif /* MATCH_MAY_ALLOCATE */
4460 /* The starting position is bogus. */
4461 if (pos
< 0 || pos
> size1
+ size2
)
4467 /* Initialize subexpression text positions to -1 to mark ones that no
4468 start_memory/stop_memory has been seen for. Also initialize the
4469 register information struct. */
4470 for (mcnt
= 1; mcnt
< num_regs
; mcnt
++)
4471 regstart
[mcnt
] = regend
[mcnt
] = REG_UNSET_VALUE
;
4473 /* We move `string1' into `string2' if the latter's empty -- but not if
4474 `string1' is null. */
4475 if (size2
== 0 && string1
!= NULL
)
4482 end1
= string1
+ size1
;
4483 end2
= string2
+ size2
;
4485 /* `p' scans through the pattern as `d' scans through the data.
4486 `dend' is the end of the input string that `d' points within. `d'
4487 is advanced into the following input string whenever necessary, but
4488 this happens before fetching; therefore, at the beginning of the
4489 loop, `d' can be pointing at the end of a string, but it cannot
4493 /* Only match within string2. */
4494 d
= string2
+ pos
- size1
;
4495 dend
= end_match_2
= string2
+ stop
- size1
;
4496 end_match_1
= end1
; /* Just to give it a value. */
4502 /* Only match within string1. */
4503 end_match_1
= string1
+ stop
;
4505 When we reach end_match_1, PREFETCH normally switches to string2.
4506 But in the present case, this means that just doing a PREFETCH
4507 makes us jump from `stop' to `gap' within the string.
4508 What we really want here is for the search to stop as
4509 soon as we hit end_match_1. That's why we set end_match_2
4510 to end_match_1 (since PREFETCH fails as soon as we hit
4512 end_match_2
= end_match_1
;
4517 end_match_2
= string2
+ stop
- size1
;
4523 DEBUG_PRINT1 ("The compiled pattern is: ");
4524 DEBUG_PRINT_COMPILED_PATTERN (bufp
, p
, pend
);
4525 DEBUG_PRINT1 ("The string to match is: `");
4526 DEBUG_PRINT_DOUBLE_STRING (d
, string1
, size1
, string2
, size2
);
4527 DEBUG_PRINT1 ("'\n");
4529 /* This loops over pattern commands. It exits by returning from the
4530 function if the match is complete, or it drops through if the match
4531 fails at this starting point in the input data. */
4534 DEBUG_PRINT2 ("\n%p: ", p
);
4537 { /* End of pattern means we might have succeeded. */
4538 DEBUG_PRINT1 ("end of pattern ... ");
4540 /* If we haven't matched the entire string, and we want the
4541 longest match, try backtracking. */
4542 if (d
!= end_match_2
)
4544 /* 1 if this match ends in the same string (string1 or string2)
4545 as the best previous match. */
4546 boolean same_str_p
= (FIRST_STRING_P (match_end
)
4547 == FIRST_STRING_P (d
));
4548 /* 1 if this match is the best seen so far. */
4549 boolean best_match_p
;
4551 /* AIX compiler got confused when this was combined
4552 with the previous declaration. */
4554 best_match_p
= d
> match_end
;
4556 best_match_p
= !FIRST_STRING_P (d
);
4558 DEBUG_PRINT1 ("backtracking.\n");
4560 if (!FAIL_STACK_EMPTY ())
4561 { /* More failure points to try. */
4563 /* If exceeds best match so far, save it. */
4564 if (!best_regs_set
|| best_match_p
)
4566 best_regs_set
= true;
4569 DEBUG_PRINT1 ("\nSAVING match as best so far.\n");
4571 for (mcnt
= 1; mcnt
< num_regs
; mcnt
++)
4573 best_regstart
[mcnt
] = regstart
[mcnt
];
4574 best_regend
[mcnt
] = regend
[mcnt
];
4580 /* If no failure points, don't restore garbage. And if
4581 last match is real best match, don't restore second
4583 else if (best_regs_set
&& !best_match_p
)
4586 /* Restore best match. It may happen that `dend ==
4587 end_match_1' while the restored d is in string2.
4588 For example, the pattern `x.*y.*z' against the
4589 strings `x-' and `y-z-', if the two strings are
4590 not consecutive in memory. */
4591 DEBUG_PRINT1 ("Restoring best registers.\n");
4594 dend
= ((d
>= string1
&& d
<= end1
)
4595 ? end_match_1
: end_match_2
);
4597 for (mcnt
= 1; mcnt
< num_regs
; mcnt
++)
4599 regstart
[mcnt
] = best_regstart
[mcnt
];
4600 regend
[mcnt
] = best_regend
[mcnt
];
4603 } /* d != end_match_2 */
4606 DEBUG_PRINT1 ("Accepting match.\n");
4608 /* If caller wants register contents data back, do it. */
4609 if (regs
&& !bufp
->no_sub
)
4611 /* Have the register data arrays been allocated? */
4612 if (bufp
->regs_allocated
== REGS_UNALLOCATED
)
4613 { /* No. So allocate them with malloc. We need one
4614 extra element beyond `num_regs' for the `-1' marker
4616 regs
->num_regs
= MAX (RE_NREGS
, num_regs
+ 1);
4617 regs
->start
= TALLOC (regs
->num_regs
, regoff_t
);
4618 regs
->end
= TALLOC (regs
->num_regs
, regoff_t
);
4619 if (regs
->start
== NULL
|| regs
->end
== NULL
)
4624 bufp
->regs_allocated
= REGS_REALLOCATE
;
4626 else if (bufp
->regs_allocated
== REGS_REALLOCATE
)
4627 { /* Yes. If we need more elements than were already
4628 allocated, reallocate them. If we need fewer, just
4630 if (regs
->num_regs
< num_regs
+ 1)
4632 regs
->num_regs
= num_regs
+ 1;
4633 RETALLOC (regs
->start
, regs
->num_regs
, regoff_t
);
4634 RETALLOC (regs
->end
, regs
->num_regs
, regoff_t
);
4635 if (regs
->start
== NULL
|| regs
->end
== NULL
)
4644 /* These braces fend off a "empty body in an else-statement"
4645 warning under GCC when assert expands to nothing. */
4646 assert (bufp
->regs_allocated
== REGS_FIXED
);
4649 /* Convert the pointer data in `regstart' and `regend' to
4650 indices. Register zero has to be set differently,
4651 since we haven't kept track of any info for it. */
4652 if (regs
->num_regs
> 0)
4654 regs
->start
[0] = pos
;
4655 regs
->end
[0] = POINTER_TO_OFFSET (d
);
4658 /* Go through the first `min (num_regs, regs->num_regs)'
4659 registers, since that is all we initialized. */
4660 for (mcnt
= 1; mcnt
< MIN (num_regs
, regs
->num_regs
); mcnt
++)
4662 if (REG_UNSET (regstart
[mcnt
]) || REG_UNSET (regend
[mcnt
]))
4663 regs
->start
[mcnt
] = regs
->end
[mcnt
] = -1;
4667 = (regoff_t
) POINTER_TO_OFFSET (regstart
[mcnt
]);
4669 = (regoff_t
) POINTER_TO_OFFSET (regend
[mcnt
]);
4673 /* If the regs structure we return has more elements than
4674 were in the pattern, set the extra elements to -1. If
4675 we (re)allocated the registers, this is the case,
4676 because we always allocate enough to have at least one
4678 for (mcnt
= num_regs
; mcnt
< regs
->num_regs
; mcnt
++)
4679 regs
->start
[mcnt
] = regs
->end
[mcnt
] = -1;
4680 } /* regs && !bufp->no_sub */
4682 DEBUG_PRINT4 ("%u failure points pushed, %u popped (%u remain).\n",
4683 nfailure_points_pushed
, nfailure_points_popped
,
4684 nfailure_points_pushed
- nfailure_points_popped
);
4685 DEBUG_PRINT2 ("%u registers pushed.\n", num_regs_pushed
);
4687 mcnt
= POINTER_TO_OFFSET (d
) - pos
;
4689 DEBUG_PRINT2 ("Returning %d from re_match_2.\n", mcnt
);
4695 /* Otherwise match next pattern command. */
4696 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *p
++))
4698 /* Ignore these. Used to ignore the n of succeed_n's which
4699 currently have n == 0. */
4701 DEBUG_PRINT1 ("EXECUTING no_op.\n");
4705 DEBUG_PRINT1 ("EXECUTING succeed.\n");
4708 /* Match the next n pattern characters exactly. The following
4709 byte in the pattern defines n, and the n bytes after that
4710 are the characters to match. */
4713 DEBUG_PRINT2 ("EXECUTING exactn %d.\n", mcnt
);
4715 /* Remember the start point to rollback upon failure. */
4718 /* This is written out as an if-else so we don't waste time
4719 testing `translate' inside the loop. */
4720 if (RE_TRANSLATE_P (translate
))
4725 int pat_charlen
, buf_charlen
;
4726 unsigned int pat_ch
, buf_ch
;
4729 pat_ch
= STRING_CHAR_AND_LENGTH (p
, pend
- p
, pat_charlen
);
4730 buf_ch
= STRING_CHAR_AND_LENGTH (d
, dend
- d
, buf_charlen
);
4732 if (RE_TRANSLATE (translate
, buf_ch
)
4741 mcnt
-= pat_charlen
;
4748 if (RE_TRANSLATE (translate
, *d
) != *p
++)
4773 /* Match any character except possibly a newline or a null. */
4777 unsigned int buf_ch
;
4779 DEBUG_PRINT1 ("EXECUTING anychar.\n");
4782 buf_ch
= RE_STRING_CHAR_AND_LENGTH (d
, dend
- d
, buf_charlen
);
4783 buf_ch
= TRANSLATE (buf_ch
);
4785 if ((!(bufp
->syntax
& RE_DOT_NEWLINE
)
4787 || ((bufp
->syntax
& RE_DOT_NOT_NULL
)
4788 && buf_ch
== '\000'))
4791 DEBUG_PRINT2 (" Matched `%d'.\n", *d
);
4800 register unsigned int c
;
4801 boolean
not = (re_opcode_t
) *(p
- 1) == charset_not
;
4804 /* Start of actual range_table, or end of bitmap if there is no
4806 unsigned char *range_table
;
4808 /* Nonzero if there is a range table. */
4809 int range_table_exists
;
4811 /* Number of ranges of range table. This is not included
4812 in the initial byte-length of the command. */
4815 DEBUG_PRINT2 ("EXECUTING charset%s.\n", not ? "_not" : "");
4817 range_table_exists
= CHARSET_RANGE_TABLE_EXISTS_P (&p
[-1]);
4819 if (range_table_exists
)
4821 range_table
= CHARSET_RANGE_TABLE (&p
[-1]); /* Past the bitmap. */
4822 EXTRACT_NUMBER_AND_INCR (count
, range_table
);
4826 c
= RE_STRING_CHAR_AND_LENGTH (d
, dend
- d
, len
);
4827 c
= TRANSLATE (c
); /* The character to match. */
4829 if (SINGLE_BYTE_CHAR_P (c
))
4830 { /* Lookup bitmap. */
4831 /* Cast to `unsigned' instead of `unsigned char' in
4832 case the bit list is a full 32 bytes long. */
4833 if (c
< (unsigned) (CHARSET_BITMAP_SIZE (&p
[-1]) * BYTEWIDTH
)
4834 && p
[1 + c
/ BYTEWIDTH
] & (1 << (c
% BYTEWIDTH
)))
4838 else if (range_table_exists
)
4840 int class_bits
= CHARSET_RANGE_TABLE_BITS (&p
[-1]);
4842 if ( (class_bits
& BIT_ALNUM
&& ISALNUM (c
))
4843 | (class_bits
& BIT_ALPHA
&& ISALPHA (c
))
4844 | (class_bits
& BIT_ASCII
&& IS_REAL_ASCII (c
))
4845 | (class_bits
& BIT_GRAPH
&& ISGRAPH (c
))
4846 | (class_bits
& BIT_LOWER
&& ISLOWER (c
))
4847 | (class_bits
& BIT_MULTIBYTE
&& !ISUNIBYTE (c
))
4848 | (class_bits
& BIT_NONASCII
&& !IS_REAL_ASCII (c
))
4849 | (class_bits
& BIT_PRINT
&& ISPRINT (c
))
4850 | (class_bits
& BIT_PUNCT
&& ISPUNCT (c
))
4851 | (class_bits
& BIT_SPACE
&& ISSPACE (c
))
4852 | (class_bits
& BIT_UNIBYTE
&& ISUNIBYTE (c
))
4853 | (class_bits
& BIT_UPPER
&& ISUPPER (c
))
4854 | (class_bits
& BIT_WORD
&& ISWORD (c
)))
4857 CHARSET_LOOKUP_RANGE_TABLE_RAW (not, c
, range_table
, count
);
4861 if (range_table_exists
)
4862 p
= CHARSET_RANGE_TABLE_END (range_table
, count
);
4864 p
+= CHARSET_BITMAP_SIZE (&p
[-1]) + 1;
4866 if (!not) goto fail
;
4873 /* The beginning of a group is represented by start_memory.
4874 The argument is the register number. The text
4875 matched within the group is recorded (in the internal
4876 registers data structure) under the register number. */
4878 DEBUG_PRINT2 ("EXECUTING start_memory %d:\n", *p
);
4880 /* In case we need to undo this operation (via backtracking). */
4881 PUSH_FAILURE_REG ((unsigned int)*p
);
4884 regend
[*p
] = REG_UNSET_VALUE
; /* probably unnecessary. -sm */
4885 DEBUG_PRINT2 (" regstart: %d\n", POINTER_TO_OFFSET (regstart
[*p
]));
4887 /* Move past the register number and inner group count. */
4892 /* The stop_memory opcode represents the end of a group. Its
4893 argument is the same as start_memory's: the register number. */
4895 DEBUG_PRINT2 ("EXECUTING stop_memory %d:\n", *p
);
4897 assert (!REG_UNSET (regstart
[*p
]));
4898 /* Strictly speaking, there should be code such as:
4900 assert (REG_UNSET (regend[*p]));
4901 PUSH_FAILURE_REGSTOP ((unsigned int)*p);
4903 But the only info to be pushed is regend[*p] and it is known to
4904 be UNSET, so there really isn't anything to push.
4905 Not pushing anything, on the other hand deprives us from the
4906 guarantee that regend[*p] is UNSET since undoing this operation
4907 will not reset its value properly. This is not important since
4908 the value will only be read on the next start_memory or at
4909 the very end and both events can only happen if this stop_memory
4913 DEBUG_PRINT2 (" regend: %d\n", POINTER_TO_OFFSET (regend
[*p
]));
4915 /* Move past the register number and the inner group count. */
4920 /* \<digit> has been turned into a `duplicate' command which is
4921 followed by the numeric value of <digit> as the register number. */
4924 register re_char
*d2
, *dend2
;
4925 int regno
= *p
++; /* Get which register to match against. */
4926 DEBUG_PRINT2 ("EXECUTING duplicate %d.\n", regno
);
4928 /* Can't back reference a group which we've never matched. */
4929 if (REG_UNSET (regstart
[regno
]) || REG_UNSET (regend
[regno
]))
4932 /* Where in input to try to start matching. */
4933 d2
= regstart
[regno
];
4935 /* Remember the start point to rollback upon failure. */
4938 /* Where to stop matching; if both the place to start and
4939 the place to stop matching are in the same string, then
4940 set to the place to stop, otherwise, for now have to use
4941 the end of the first string. */
4943 dend2
= ((FIRST_STRING_P (regstart
[regno
])
4944 == FIRST_STRING_P (regend
[regno
]))
4945 ? regend
[regno
] : end_match_1
);
4948 /* If necessary, advance to next segment in register
4952 if (dend2
== end_match_2
) break;
4953 if (dend2
== regend
[regno
]) break;
4955 /* End of string1 => advance to string2. */
4957 dend2
= regend
[regno
];
4959 /* At end of register contents => success */
4960 if (d2
== dend2
) break;
4962 /* If necessary, advance to next segment in data. */
4965 /* How many characters left in this segment to match. */
4968 /* Want how many consecutive characters we can match in
4969 one shot, so, if necessary, adjust the count. */
4970 if (mcnt
> dend2
- d2
)
4973 /* Compare that many; failure if mismatch, else move
4975 if (RE_TRANSLATE_P (translate
)
4976 ? bcmp_translate (d
, d2
, mcnt
, translate
, multibyte
)
4977 : bcmp (d
, d2
, mcnt
))
4982 d
+= mcnt
, d2
+= mcnt
;
4988 /* begline matches the empty string at the beginning of the string
4989 (unless `not_bol' is set in `bufp'), and, if
4990 `newline_anchor' is set, after newlines. */
4992 DEBUG_PRINT1 ("EXECUTING begline.\n");
4994 if (AT_STRINGS_BEG (d
))
4996 if (!bufp
->not_bol
) break;
5001 GET_CHAR_BEFORE_2 (c
, d
, string1
, end1
, string2
, end2
);
5002 if (c
== '\n' && bufp
->newline_anchor
)
5005 /* In all other cases, we fail. */
5009 /* endline is the dual of begline. */
5011 DEBUG_PRINT1 ("EXECUTING endline.\n");
5013 if (AT_STRINGS_END (d
))
5015 if (!bufp
->not_eol
) break;
5018 /* We have to ``prefetch'' the next character. */
5019 else if ((d
== end1
? *string2
: *d
) == '\n'
5020 && bufp
->newline_anchor
)
5027 /* Match at the very beginning of the data. */
5029 DEBUG_PRINT1 ("EXECUTING begbuf.\n");
5030 if (AT_STRINGS_BEG (d
))
5035 /* Match at the very end of the data. */
5037 DEBUG_PRINT1 ("EXECUTING endbuf.\n");
5038 if (AT_STRINGS_END (d
))
5043 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
5044 pushes NULL as the value for the string on the stack. Then
5045 `POP_FAILURE_POINT' will keep the current value for the
5046 string, instead of restoring it. To see why, consider
5047 matching `foo\nbar' against `.*\n'. The .* matches the foo;
5048 then the . fails against the \n. But the next thing we want
5049 to do is match the \n against the \n; if we restored the
5050 string value, we would be back at the foo.
5052 Because this is used only in specific cases, we don't need to
5053 check all the things that `on_failure_jump' does, to make
5054 sure the right things get saved on the stack. Hence we don't
5055 share its code. The only reason to push anything on the
5056 stack at all is that otherwise we would have to change
5057 `anychar's code to do something besides goto fail in this
5058 case; that seems worse than this. */
5059 case on_failure_keep_string_jump
:
5060 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5061 DEBUG_PRINT3 ("EXECUTING on_failure_keep_string_jump %d (to %p):\n",
5064 PUSH_FAILURE_POINT (p
- 3, NULL
);
5067 /* A nasty loop is introduced by the non-greedy *? and +?.
5068 With such loops, the stack only ever contains one failure point
5069 at a time, so that a plain on_failure_jump_loop kind of
5070 cycle detection cannot work. Worse yet, such a detection
5071 can not only fail to detect a cycle, but it can also wrongly
5072 detect a cycle (between different instantiations of the same
5074 So the method used for those nasty loops is a little different:
5075 We use a special cycle-detection-stack-frame which is pushed
5076 when the on_failure_jump_nastyloop failure-point is *popped*.
5077 This special frame thus marks the beginning of one iteration
5078 through the loop and we can hence easily check right here
5079 whether something matched between the beginning and the end of
5081 case on_failure_jump_nastyloop
:
5082 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5083 DEBUG_PRINT3 ("EXECUTING on_failure_jump_nastyloop %d (to %p):\n",
5086 assert ((re_opcode_t
)p
[-4] == no_op
);
5087 CHECK_INFINITE_LOOP (p
- 4, d
);
5088 PUSH_FAILURE_POINT (p
- 3, d
);
5092 /* Simple loop detecting on_failure_jump: just check on the
5093 failure stack if the same spot was already hit earlier. */
5094 case on_failure_jump_loop
:
5096 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5097 DEBUG_PRINT3 ("EXECUTING on_failure_jump_loop %d (to %p):\n",
5100 CHECK_INFINITE_LOOP (p
- 3, d
);
5101 PUSH_FAILURE_POINT (p
- 3, d
);
5105 /* Uses of on_failure_jump:
5107 Each alternative starts with an on_failure_jump that points
5108 to the beginning of the next alternative. Each alternative
5109 except the last ends with a jump that in effect jumps past
5110 the rest of the alternatives. (They really jump to the
5111 ending jump of the following alternative, because tensioning
5112 these jumps is a hassle.)
5114 Repeats start with an on_failure_jump that points past both
5115 the repetition text and either the following jump or
5116 pop_failure_jump back to this on_failure_jump. */
5117 case on_failure_jump
:
5119 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5120 DEBUG_PRINT3 ("EXECUTING on_failure_jump %d (to %p):\n",
5123 PUSH_FAILURE_POINT (p
-3, d
);
5126 /* This operation is used for greedy *.
5127 Compare the beginning of the repeat with what in the
5128 pattern follows its end. If we can establish that there
5129 is nothing that they would both match, i.e., that we
5130 would have to backtrack because of (as in, e.g., `a*a')
5131 then we can use a non-backtracking loop based on
5132 on_failure_keep_string_jump instead of on_failure_jump. */
5133 case on_failure_jump_smart
:
5135 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5136 DEBUG_PRINT3 ("EXECUTING on_failure_jump_smart %d (to %p).\n",
5139 unsigned char *p1
= p
; /* Next operation. */
5140 unsigned char *p2
= p
+ mcnt
; /* Destination of the jump. */
5142 p
-= 3; /* Reset so that we will re-execute the
5143 instruction once it's been changed. */
5145 EXTRACT_NUMBER (mcnt
, p2
- 2);
5147 /* Ensure this is a indeed the trivial kind of loop
5148 we are expecting. */
5149 assert (skip_one_char (p1
) == p2
- 3);
5150 assert ((re_opcode_t
) p2
[-3] == jump
&& p2
+ mcnt
== p
);
5151 DEBUG_STATEMENT (debug
+= 2);
5152 if (mutually_exclusive_p (bufp
, p1
, p2
))
5154 /* Use a fast `on_failure_keep_string_jump' loop. */
5155 DEBUG_PRINT1 (" smart exclusive => fast loop.\n");
5156 *p
= (unsigned char) on_failure_keep_string_jump
;
5157 STORE_NUMBER (p2
- 2, mcnt
+ 3);
5161 /* Default to a safe `on_failure_jump' loop. */
5162 DEBUG_PRINT1 (" smart default => slow loop.\n");
5163 *p
= (unsigned char) on_failure_jump
;
5165 DEBUG_STATEMENT (debug
-= 2);
5169 /* Unconditionally jump (without popping any failure points). */
5173 EXTRACT_NUMBER_AND_INCR (mcnt
, p
); /* Get the amount to jump. */
5174 DEBUG_PRINT2 ("EXECUTING jump %d ", mcnt
);
5175 p
+= mcnt
; /* Do the jump. */
5176 DEBUG_PRINT2 ("(to %p).\n", p
);
5180 /* Have to succeed matching what follows at least n times.
5181 After that, handle like `on_failure_jump'. */
5183 EXTRACT_NUMBER (mcnt
, p
+ 2);
5184 DEBUG_PRINT2 ("EXECUTING succeed_n %d.\n", mcnt
);
5187 /* Originally, this is how many times we HAVE to succeed. */
5192 STORE_NUMBER_AND_INCR (p
, mcnt
);
5193 DEBUG_PRINT3 (" Setting %p to %d.\n", p
, mcnt
);
5197 DEBUG_PRINT2 (" Setting two bytes from %p to no_op.\n", p
+2);
5198 p
[2] = (unsigned char) no_op
;
5199 p
[3] = (unsigned char) no_op
;
5205 EXTRACT_NUMBER (mcnt
, p
+ 2);
5206 DEBUG_PRINT2 ("EXECUTING jump_n %d.\n", mcnt
);
5208 /* Originally, this is how many times we CAN jump. */
5212 STORE_NUMBER (p
+ 2, mcnt
);
5213 goto unconditional_jump
;
5215 /* If don't have to jump any more, skip over the rest of command. */
5222 DEBUG_PRINT1 ("EXECUTING set_number_at.\n");
5224 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5226 EXTRACT_NUMBER_AND_INCR (mcnt
, p
);
5227 DEBUG_PRINT3 (" Setting %p to %d.\n", p1
, mcnt
);
5228 STORE_NUMBER (p1
, mcnt
);
5234 not = (re_opcode_t
) *(p
- 1) == notwordbound
;
5235 DEBUG_PRINT2 ("EXECUTING %swordbound.\n", not?"not":"");
5237 /* We SUCCEED (or FAIL) in one of the following cases: */
5239 /* Case 1: D is at the beginning or the end of string. */
5240 if (AT_STRINGS_BEG (d
) || AT_STRINGS_END (d
))
5244 /* C1 is the character before D, S1 is the syntax of C1, C2
5245 is the character at D, and S2 is the syntax of C2. */
5248 int offset
= PTR_TO_OFFSET (d
- 1);
5249 int charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
5250 UPDATE_SYNTAX_TABLE (charpos
);
5252 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
5255 UPDATE_SYNTAX_TABLE_FORWARD (charpos
+ 1);
5258 c2
= RE_STRING_CHAR (d
, dend
- d
);
5261 if (/* Case 2: Only one of S1 and S2 is Sword. */
5262 ((s1
== Sword
) != (s2
== Sword
))
5263 /* Case 3: Both of S1 and S2 are Sword, and macro
5264 WORD_BOUNDARY_P (C1, C2) returns nonzero. */
5265 || ((s1
== Sword
) && WORD_BOUNDARY_P (c1
, c2
)))
5274 DEBUG_PRINT1 ("EXECUTING wordbeg.\n");
5276 /* We FAIL in one of the following cases: */
5278 /* Case 1: D is at the end of string. */
5279 if (AT_STRINGS_END (d
))
5283 /* C1 is the character before D, S1 is the syntax of C1, C2
5284 is the character at D, and S2 is the syntax of C2. */
5287 int offset
= PTR_TO_OFFSET (d
);
5288 int charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
5289 UPDATE_SYNTAX_TABLE (charpos
);
5292 c2
= RE_STRING_CHAR (d
, dend
- d
);
5295 /* Case 2: S2 is not Sword. */
5299 /* Case 3: D is not at the beginning of string ... */
5300 if (!AT_STRINGS_BEG (d
))
5302 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
5304 UPDATE_SYNTAX_TABLE_BACKWARD (charpos
- 1);
5308 /* ... and S1 is Sword, and WORD_BOUNDARY_P (C1, C2)
5310 if ((s1
== Sword
) && !WORD_BOUNDARY_P (c1
, c2
))
5317 DEBUG_PRINT1 ("EXECUTING wordend.\n");
5319 /* We FAIL in one of the following cases: */
5321 /* Case 1: D is at the beginning of string. */
5322 if (AT_STRINGS_BEG (d
))
5326 /* C1 is the character before D, S1 is the syntax of C1, C2
5327 is the character at D, and S2 is the syntax of C2. */
5330 int offset
= PTR_TO_OFFSET (d
) - 1;
5331 int charpos
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
5332 UPDATE_SYNTAX_TABLE (charpos
);
5334 GET_CHAR_BEFORE_2 (c1
, d
, string1
, end1
, string2
, end2
);
5337 /* Case 2: S1 is not Sword. */
5341 /* Case 3: D is not at the end of string ... */
5342 if (!AT_STRINGS_END (d
))
5345 c2
= RE_STRING_CHAR (d
, dend
- d
);
5347 UPDATE_SYNTAX_TABLE_FORWARD (charpos
);
5351 /* ... and S2 is Sword, and WORD_BOUNDARY_P (C1, C2)
5353 if ((s2
== Sword
) && !WORD_BOUNDARY_P (c1
, c2
))
5361 not = (re_opcode_t
) *(p
- 1) == notsyntaxspec
;
5363 DEBUG_PRINT3 ("EXECUTING %ssyntaxspec %d.\n", not?"not":"", mcnt
);
5367 int offset
= PTR_TO_OFFSET (d
);
5368 int pos1
= SYNTAX_TABLE_BYTE_TO_CHAR (offset
);
5369 UPDATE_SYNTAX_TABLE (pos1
);
5375 c
= RE_STRING_CHAR_AND_LENGTH (d
, dend
- d
, len
);
5377 if ((SYNTAX (c
) != (enum syntaxcode
) mcnt
) ^ not)
5385 DEBUG_PRINT1 ("EXECUTING before_dot.\n");
5386 if (PTR_BYTE_POS (d
) >= PT_BYTE
)
5391 DEBUG_PRINT1 ("EXECUTING at_dot.\n");
5392 if (PTR_BYTE_POS (d
) != PT_BYTE
)
5397 DEBUG_PRINT1 ("EXECUTING after_dot.\n");
5398 if (PTR_BYTE_POS (d
) <= PT_BYTE
)
5403 case notcategoryspec
:
5404 not = (re_opcode_t
) *(p
- 1) == notcategoryspec
;
5406 DEBUG_PRINT3 ("EXECUTING %scategoryspec %d.\n", not?"not":"", mcnt
);
5410 c
= RE_STRING_CHAR_AND_LENGTH (d
, dend
- d
, len
);
5412 if ((!CHAR_HAS_CATEGORY (c
, mcnt
)) ^ not)
5423 continue; /* Successfully executed one pattern command; keep going. */
5426 /* We goto here if a matching operation fails. */
5429 if (!FAIL_STACK_EMPTY ())
5433 /* A restart point is known. Restore to that state. */
5434 DEBUG_PRINT1 ("\nFAIL:\n");
5435 POP_FAILURE_POINT (str
, pat
);
5436 switch (SWITCH_ENUM_CAST ((re_opcode_t
) *pat
++))
5438 case on_failure_keep_string_jump
:
5439 assert (str
== NULL
);
5440 goto continue_failure_jump
;
5442 case on_failure_jump_nastyloop
:
5443 assert ((re_opcode_t
)pat
[-2] == no_op
);
5444 PUSH_FAILURE_POINT (pat
- 2, str
);
5447 case on_failure_jump_loop
:
5448 case on_failure_jump
:
5451 continue_failure_jump
:
5452 EXTRACT_NUMBER_AND_INCR (mcnt
, pat
);
5457 /* A special frame used for nastyloops. */
5464 assert (p
>= bufp
->buffer
&& p
<= pend
);
5466 if (d
>= string1
&& d
<= end1
)
5470 break; /* Matching at this starting point really fails. */
5474 goto restore_best_regs
;
5478 return -1; /* Failure to match. */
5481 /* Subroutine definitions for re_match_2. */
5483 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
5484 bytes; nonzero otherwise. */
5487 bcmp_translate (s1
, s2
, len
, translate
, multibyte
)
5490 RE_TRANSLATE_TYPE translate
;
5491 const int multibyte
;
5493 register re_char
*p1
= s1
, *p2
= s2
;
5494 re_char
*p1_end
= s1
+ len
;
5495 re_char
*p2_end
= s2
+ len
;
5497 while (p1
!= p1_end
&& p2
!= p2_end
)
5499 int p1_charlen
, p2_charlen
;
5502 p1_ch
= RE_STRING_CHAR_AND_LENGTH (p1
, p1_end
- p1
, p1_charlen
);
5503 p2_ch
= RE_STRING_CHAR_AND_LENGTH (p2
, p2_end
- p2
, p2_charlen
);
5505 if (RE_TRANSLATE (translate
, p1_ch
)
5506 != RE_TRANSLATE (translate
, p2_ch
))
5509 p1
+= p1_charlen
, p2
+= p2_charlen
;
5512 if (p1
!= p1_end
|| p2
!= p2_end
)
5518 /* Entry points for GNU code. */
5520 /* re_compile_pattern is the GNU regular expression compiler: it
5521 compiles PATTERN (of length SIZE) and puts the result in BUFP.
5522 Returns 0 if the pattern was valid, otherwise an error string.
5524 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
5525 are set in BUFP on entry.
5527 We call regex_compile to do the actual compilation. */
5530 re_compile_pattern (pattern
, length
, bufp
)
5531 const char *pattern
;
5533 struct re_pattern_buffer
*bufp
;
5537 /* GNU code is written to assume at least RE_NREGS registers will be set
5538 (and at least one extra will be -1). */
5539 bufp
->regs_allocated
= REGS_UNALLOCATED
;
5541 /* And GNU code determines whether or not to get register information
5542 by passing null for the REGS argument to re_match, etc., not by
5546 /* Match anchors at newline. */
5547 bufp
->newline_anchor
= 1;
5549 ret
= regex_compile (pattern
, length
, re_syntax_options
, bufp
);
5553 return gettext (re_error_msgid
[(int) ret
]);
5556 /* Entry points compatible with 4.2 BSD regex library. We don't define
5557 them unless specifically requested. */
5559 #if defined (_REGEX_RE_COMP) || defined (_LIBC)
5561 /* BSD has one and only one pattern buffer. */
5562 static struct re_pattern_buffer re_comp_buf
;
5566 /* Make these definitions weak in libc, so POSIX programs can redefine
5567 these names if they don't use our functions, and still use
5568 regcomp/regexec below without link errors. */
5578 if (!re_comp_buf
.buffer
)
5579 return gettext ("No previous regular expression");
5583 if (!re_comp_buf
.buffer
)
5585 re_comp_buf
.buffer
= (unsigned char *) malloc (200);
5586 if (re_comp_buf
.buffer
== NULL
)
5587 return gettext (re_error_msgid
[(int) REG_ESPACE
]);
5588 re_comp_buf
.allocated
= 200;
5590 re_comp_buf
.fastmap
= (char *) malloc (1 << BYTEWIDTH
);
5591 if (re_comp_buf
.fastmap
== NULL
)
5592 return gettext (re_error_msgid
[(int) REG_ESPACE
]);
5595 /* Since `re_exec' always passes NULL for the `regs' argument, we
5596 don't need to initialize the pattern buffer fields which affect it. */
5598 /* Match anchors at newlines. */
5599 re_comp_buf
.newline_anchor
= 1;
5601 ret
= regex_compile (s
, strlen (s
), re_syntax_options
, &re_comp_buf
);
5606 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
5607 return (char *) gettext (re_error_msgid
[(int) ret
]);
5618 const int len
= strlen (s
);
5620 0 <= re_search (&re_comp_buf
, s
, len
, 0, len
, (struct re_registers
*) 0);
5622 #endif /* _REGEX_RE_COMP */
5624 /* POSIX.2 functions. Don't define these for Emacs. */
5628 /* regcomp takes a regular expression as a string and compiles it.
5630 PREG is a regex_t *. We do not expect any fields to be initialized,
5631 since POSIX says we shouldn't. Thus, we set
5633 `buffer' to the compiled pattern;
5634 `used' to the length of the compiled pattern;
5635 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
5636 REG_EXTENDED bit in CFLAGS is set; otherwise, to
5637 RE_SYNTAX_POSIX_BASIC;
5638 `newline_anchor' to REG_NEWLINE being set in CFLAGS;
5639 `fastmap' and `fastmap_accurate' to zero;
5640 `re_nsub' to the number of subexpressions in PATTERN.
5642 PATTERN is the address of the pattern string.
5644 CFLAGS is a series of bits which affect compilation.
5646 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
5647 use POSIX basic syntax.
5649 If REG_NEWLINE is set, then . and [^...] don't match newline.
5650 Also, regexec will try a match beginning after every newline.
5652 If REG_ICASE is set, then we considers upper- and lowercase
5653 versions of letters to be equivalent when matching.
5655 If REG_NOSUB is set, then when PREG is passed to regexec, that
5656 routine will report only success or failure, and nothing about the
5659 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
5660 the return codes and their meanings.) */
5663 regcomp (preg
, pattern
, cflags
)
5665 const char *pattern
;
5670 = (cflags
& REG_EXTENDED
) ?
5671 RE_SYNTAX_POSIX_EXTENDED
: RE_SYNTAX_POSIX_BASIC
;
5673 /* regex_compile will allocate the space for the compiled pattern. */
5675 preg
->allocated
= 0;
5678 /* Don't bother to use a fastmap when searching. This simplifies the
5679 REG_NEWLINE case: if we used a fastmap, we'd have to put all the
5680 characters after newlines into the fastmap. This way, we just try
5684 if (cflags
& REG_ICASE
)
5689 = (RE_TRANSLATE_TYPE
) malloc (CHAR_SET_SIZE
5690 * sizeof (*(RE_TRANSLATE_TYPE
)0));
5691 if (preg
->translate
== NULL
)
5692 return (int) REG_ESPACE
;
5694 /* Map uppercase characters to corresponding lowercase ones. */
5695 for (i
= 0; i
< CHAR_SET_SIZE
; i
++)
5696 preg
->translate
[i
] = ISUPPER (i
) ? tolower (i
) : i
;
5699 preg
->translate
= NULL
;
5701 /* If REG_NEWLINE is set, newlines are treated differently. */
5702 if (cflags
& REG_NEWLINE
)
5703 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
5704 syntax
&= ~RE_DOT_NEWLINE
;
5705 syntax
|= RE_HAT_LISTS_NOT_NEWLINE
;
5706 /* It also changes the matching behavior. */
5707 preg
->newline_anchor
= 1;
5710 preg
->newline_anchor
= 0;
5712 preg
->no_sub
= !!(cflags
& REG_NOSUB
);
5714 /* POSIX says a null character in the pattern terminates it, so we
5715 can use strlen here in compiling the pattern. */
5716 ret
= regex_compile (pattern
, strlen (pattern
), syntax
, preg
);
5718 /* POSIX doesn't distinguish between an unmatched open-group and an
5719 unmatched close-group: both are REG_EPAREN. */
5720 if (ret
== REG_ERPAREN
) ret
= REG_EPAREN
;
5726 /* regexec searches for a given pattern, specified by PREG, in the
5729 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
5730 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
5731 least NMATCH elements, and we set them to the offsets of the
5732 corresponding matched substrings.
5734 EFLAGS specifies `execution flags' which affect matching: if
5735 REG_NOTBOL is set, then ^ does not match at the beginning of the
5736 string; if REG_NOTEOL is set, then $ does not match at the end.
5738 We return 0 if we find a match and REG_NOMATCH if not. */
5741 regexec (preg
, string
, nmatch
, pmatch
, eflags
)
5742 const regex_t
*preg
;
5745 regmatch_t pmatch
[];
5749 struct re_registers regs
;
5750 regex_t private_preg
;
5751 int len
= strlen (string
);
5752 boolean want_reg_info
= !preg
->no_sub
&& nmatch
> 0;
5754 private_preg
= *preg
;
5756 private_preg
.not_bol
= !!(eflags
& REG_NOTBOL
);
5757 private_preg
.not_eol
= !!(eflags
& REG_NOTEOL
);
5759 /* The user has told us exactly how many registers to return
5760 information about, via `nmatch'. We have to pass that on to the
5761 matching routines. */
5762 private_preg
.regs_allocated
= REGS_FIXED
;
5766 regs
.num_regs
= nmatch
;
5767 regs
.start
= TALLOC (nmatch
, regoff_t
);
5768 regs
.end
= TALLOC (nmatch
, regoff_t
);
5769 if (regs
.start
== NULL
|| regs
.end
== NULL
)
5770 return (int) REG_NOMATCH
;
5773 /* Perform the searching operation. */
5774 ret
= re_search (&private_preg
, string
, len
,
5775 /* start: */ 0, /* range: */ len
,
5776 want_reg_info
? ®s
: (struct re_registers
*) 0);
5778 /* Copy the register information to the POSIX structure. */
5785 for (r
= 0; r
< nmatch
; r
++)
5787 pmatch
[r
].rm_so
= regs
.start
[r
];
5788 pmatch
[r
].rm_eo
= regs
.end
[r
];
5792 /* If we needed the temporary register info, free the space now. */
5797 /* We want zero return to mean success, unlike `re_search'. */
5798 return ret
>= 0 ? (int) REG_NOERROR
: (int) REG_NOMATCH
;
5802 /* Returns a message corresponding to an error code, ERRCODE, returned
5803 from either regcomp or regexec. We don't use PREG here. */
5806 regerror (errcode
, preg
, errbuf
, errbuf_size
)
5808 const regex_t
*preg
;
5816 || errcode
>= (sizeof (re_error_msgid
) / sizeof (re_error_msgid
[0])))
5817 /* Only error codes returned by the rest of the code should be passed
5818 to this routine. If we are given anything else, or if other regex
5819 code generates an invalid error code, then the program has a bug.
5820 Dump core so we can fix it. */
5823 msg
= gettext (re_error_msgid
[errcode
]);
5825 msg_size
= strlen (msg
) + 1; /* Includes the null. */
5827 if (errbuf_size
!= 0)
5829 if (msg_size
> errbuf_size
)
5831 strncpy (errbuf
, msg
, errbuf_size
- 1);
5832 errbuf
[errbuf_size
- 1] = 0;
5835 strcpy (errbuf
, msg
);
5842 /* Free dynamically allocated space used by PREG. */
5848 if (preg
->buffer
!= NULL
)
5849 free (preg
->buffer
);
5850 preg
->buffer
= NULL
;
5852 preg
->allocated
= 0;
5855 if (preg
->fastmap
!= NULL
)
5856 free (preg
->fastmap
);
5857 preg
->fastmap
= NULL
;
5858 preg
->fastmap_accurate
= 0;
5860 if (preg
->translate
!= NULL
)
5861 free (preg
->translate
);
5862 preg
->translate
= NULL
;
5865 #endif /* not emacs */