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 - use analyze_first to optimize non-empty loops
24 - optimize succeed_n and jump_n away when possible
25 - clean up multibyte issues
26 - structure the opcode space into opcode+flag.
27 - merge with glic's regex.[ch]
29 That's it for now -sm */
31 /* AIX requires this to be the first thing in the file. */
32 #if defined (_AIX) && !defined (REGEX_MALLOC)
40 /* Converts the pointer to the char to BEG-based offset from the start. */
41 #define PTR_TO_OFFSET(d) POS_AS_IN_BUFFER (POINTER_TO_OFFSET (d))
42 #define POS_AS_IN_BUFFER(p) ((p) + (NILP (re_match_object) || BUFFERP (re_match_object)))
44 #define PTR_TO_OFFSET(d) 0
51 /* We need this for `regex.h', and perhaps for the Emacs include files. */
52 #include <sys/types.h>
54 /* This is for other GNU distributions with internationalized messages. */
55 #if HAVE_LIBINTL_H || defined (_LIBC)
58 # define gettext(msgid) (msgid)
62 /* This define is so xgettext can find the internationalizable
64 #define gettext_noop(String) String
67 /* The `emacs' switch turns on certain matching commands
68 that make sense only in Emacs. */
74 /* Make syntax table lookup grant data in gl_state. */
75 #define SYNTAX_ENTRY_VIA_PROPERTY
81 #define malloc xmalloc
82 #define realloc xrealloc
85 #define RE_STRING_CHAR(p, s) \
86 (multibyte ? (STRING_CHAR (p, s)) : (*(p)))
90 /* If we are not linking with Emacs proper,
91 we can't use the relocating allocator
92 even if config.h says that we can. */
95 #if defined (STDC_HEADERS) || defined (_LIBC)
102 /* When used in Emacs's lib-src, we need to get bzero and bcopy somehow.
103 If nothing else has been done, use the method below. */
104 #ifdef INHIBIT_STRING_HEADER
105 #if !(defined (HAVE_BZERO) && defined (HAVE_BCOPY))
106 #if !defined (bzero) && !defined (bcopy)
107 #undef INHIBIT_STRING_HEADER
112 /* This is the normal way of making sure we have a bcopy and a bzero.
113 This is used in most programs--a few other programs avoid this
114 by defining INHIBIT_STRING_HEADER. */
115 #ifndef INHIBIT_STRING_HEADER
116 #if defined (HAVE_STRING_H) || defined (STDC_HEADERS) || defined (_LIBC)
119 #define bcmp(s1, s2, n) memcmp ((s1), (s2), (n))
122 #define bcopy(s, d, n) memcpy ((d), (s), (n))
125 #define bzero(s, n) memset ((s), 0, (n))
132 /* Define the syntax stuff for \<, \>, etc. */
134 /* Sword must be nonzero for the wordchar pattern commands in re_match_2. */
135 enum syntaxcode { Swhitespace = 0, Sword = 1 };
137 #ifdef SWITCH_ENUM_BUG
138 #define SWITCH_ENUM_CAST(x) ((int)(x))
140 #define SWITCH_ENUM_CAST(x) (x)
145 extern char *re_syntax_table;
147 #else /* not SYNTAX_TABLE */
149 /* How many characters in the character set. */
150 #define CHAR_SET_SIZE 256
152 static char re_syntax_table[CHAR_SET_SIZE];
163 bzero (re_syntax_table, sizeof re_syntax_table);
165 for (c = 'a'; c <= 'z'; c++)
166 re_syntax_table[c] = Sword;
168 for (c = 'A'; c <= 'Z'; c++)
169 re_syntax_table[c] = Sword;
171 for (c = '0'; c <= '9'; c++)
172 re_syntax_table[c] = Sword;
174 re_syntax_table['_'] = Sword;
179 #endif /* not SYNTAX_TABLE */
181 #define SYNTAX(c) re_syntax_table[c]
183 /* Dummy macros for non-Emacs environments. */
184 #define BASE_LEADING_CODE_P(c) (0)
185 #define CHAR_CHARSET(c) 0
186 #define CHARSET_LEADING_CODE_BASE(c) 0
187 #define WORD_BOUNDARY_P(c1, c2) (0)
188 #define CHAR_HEAD_P(p) (1)
189 #define SINGLE_BYTE_CHAR_P(c) (1)
190 #define SAME_CHARSET_P(c1, c2) (1)
191 #define MULTIBYTE_FORM_LENGTH(p, s) (1)
192 #define STRING_CHAR(p, s) (*(p))
193 #define RE_STRING_CHAR STRING_CHAR
194 #define STRING_CHAR_AND_LENGTH(p, s, actual_len) ((actual_len) = 1, *(p))
195 #define GET_CHAR_BEFORE_2(c, p, str1, end1, str2, end2) \
196 (c = ((p) == (str2) ? *((end1) - 1) : *((p) - 1)))
197 #endif /* not emacs */
200 #define RE_TRANSLATE(TBL, C) ((unsigned char)(TBL)[C])
201 #define RE_TRANSLATE_P(TBL) (TBL)
204 /* Get the interface, including the syntax bits. */
207 /* isalpha etc. are used for the character classes. */
212 /* 1 if C is an ASCII character. */
213 #define IS_REAL_ASCII(c) ((c) < 0200)
215 /* 1 if C is a unibyte character. */
216 #define ISUNIBYTE(c) (SINGLE_BYTE_CHAR_P ((c)))
218 /* The Emacs definitions should not be directly affected by locales. */
220 /* In Emacs, these are only used for single-byte characters. */
221 #define ISDIGIT(c) ((c) >= '0' && (c) <= '9')
222 #define ISCNTRL(c) ((c) < ' ')
223 #define ISXDIGIT(c) (((c) >= '0' && (c) <= '9') \
224 || ((c) >= 'a' && (c) <= 'f') \
225 || ((c) >= 'A' && (c) <= 'F'))
227 /* This is only used for single-byte characters. */
228 #define ISBLANK(c) ((c) == ' ' || (c) == '\t')
230 /* The rest must handle multibyte characters. */
232 #define ISGRAPH(c) (SINGLE_BYTE_CHAR_P (c) \
233 ? (c) > ' ' && !((c) >= 0177 && (c) <= 0237) \
236 #define ISPRINT(c) (SINGLE_BYTE_CHAR_P (c) \
237 ? (c) >= ' ' && !((c) >= 0177 && (c) <= 0237) \
240 #define ISALNUM(c) (IS_REAL_ASCII (c) \
241 ? (((c) >= 'a' && (c) <= 'z') \
242 || ((c) >= 'A' && (c) <= 'Z') \
243 || ((c) >= '0' && (c) <= '9')) \
244 : SYNTAX (c) == Sword)
246 #define ISALPHA(c) (IS_REAL_ASCII (c) \
247 ? (((c) >= 'a' && (c) <= 'z') \
248 || ((c) >= 'A' && (c) <= 'Z')) \
249 : SYNTAX (c) == Sword)
251 #define ISLOWER(c) (LOWERCASEP (c))
253 #define ISPUNCT(c) (IS_REAL_ASCII (c) \
254 ? ((c) > ' ' && (c) < 0177 \
255 && !(((c) >= 'a' && (c) <= 'z') \
256 || ((c) >= 'A' && (c) <= 'Z') \
257 || ((c) >= '0' && (c) <= '9'))) \
258 : SYNTAX (c) != Sword)
260 #define ISSPACE(c) (SYNTAX (c) == Swhitespace)
262 #define ISUPPER(c) (UPPERCASEP (c))
264 #define ISWORD(c) (SYNTAX (c) == Sword)
266 #else /* not emacs */
268 /* Jim Meyering writes:
270 "... Some ctype macros are valid only for character codes that
271 isascii says are ASCII (SGI's IRIX-4.0.5 is one such system --when
272 using /bin/cc or gcc but without giving an ansi option). So, all
273 ctype uses should be through macros like ISPRINT... If
274 STDC_HEADERS is defined, then autoconf has verified that the ctype
275 macros don't need to be guarded with references to isascii. ...
276 Defining isascii to 1 should let any compiler worth its salt
277 eliminate the && through constant folding." */
279 #if defined (STDC_HEADERS) || (!defined (isascii) && !defined (HAVE_ISASCII))
282 #define ISASCII(c) isascii(c)
285 /* 1 if C is an ASCII character. */
286 #define IS_REAL_ASCII(c) ((c) < 0200)
288 /* This distinction is not meaningful, except in Emacs. */
289 #define ISUNIBYTE(c) 1
291 #define ISDIGIT(c) (ISASCII (c) && isdigit (c))
292 #define ISCNTRL(c) (ISASCII (c) && iscntrl (c))
293 #define ISXDIGIT(c) (ISASCII (c) && isxdigit (c))
296 #define ISBLANK(c) (ISASCII (c) && isblank (c))
298 #define ISBLANK(c) ((c) == ' ' || (c) == '\t')
301 #define ISGRAPH(c) (ISASCII (c) && isgraph (c))
303 #define ISGRAPH(c) (ISASCII (c) && isprint (c) && !isspace (c))
306 #define ISPRINT(c) (ISASCII (c) && isprint (c))
307 #define ISDIGIT(c) (ISASCII (c) && isdigit (c))
308 #define ISALNUM(c) (ISASCII (c) && isalnum (c))
309 #define ISALPHA(c) (ISASCII (c) && isalpha (c))
310 #define ISCNTRL(c) (ISASCII (c) && iscntrl (c))
311 #define ISLOWER(c) (ISASCII (c) && islower (c))
312 #define ISPUNCT(c) (ISASCII (c) && ispunct (c))
313 #define ISSPACE(c) (ISASCII (c) && isspace (c))
314 #define ISUPPER(c) (ISASCII (c) && isupper (c))
315 #define ISXDIGIT(c) (ISASCII (c) && isxdigit (c))
317 #define ISWORD(c) ISALPHA(c)
319 #endif /* not emacs */
322 #define NULL (void *)0
325 /* We remove any previous definition of `SIGN_EXTEND_CHAR',
326 since ours (we hope) works properly with all combinations of
327 machines, compilers, `char' and `unsigned char' argument types.
328 (Per Bothner suggested the basic approach.) */
329 #undef SIGN_EXTEND_CHAR
331 #define SIGN_EXTEND_CHAR(c) ((signed char) (c))
332 #else /* not __STDC__ */
333 /* As in Harbison and Steele. */
334 #define SIGN_EXTEND_CHAR(c) ((((unsigned char) (c)) ^ 128) - 128)
337 /* Should we use malloc or alloca? If REGEX_MALLOC is not defined, we
338 use `alloca' instead of `malloc'. This is because using malloc in
339 re_search* or re_match* could cause memory leaks when C-g is used in
340 Emacs; also, malloc is slower and causes storage fragmentation. On
341 the other hand, malloc is more portable, and easier to debug.
343 Because we sometimes use alloca, some routines have to be macros,
344 not functions -- `alloca'-allocated space disappears at the end of the
345 function it is called in. */
349 #define REGEX_ALLOCATE malloc
350 #define REGEX_REALLOCATE(source, osize, nsize) realloc (source, nsize)
351 #define REGEX_FREE free
353 #else /* not REGEX_MALLOC */
355 /* Emacs already defines alloca, sometimes. */
358 /* Make alloca work the best possible way. */
360 #define alloca __builtin_alloca
361 #else /* not __GNUC__ */
364 #else /* not __GNUC__ or HAVE_ALLOCA_H */
365 #if 0 /* It is a bad idea to declare alloca. We always cast the result. */
366 #ifndef _AIX /* Already did AIX, up at the top. */
368 #endif /* not _AIX */
370 #endif /* not HAVE_ALLOCA_H */
371 #endif /* not __GNUC__ */
373 #endif /* not alloca */
375 #define REGEX_ALLOCATE alloca
377 /* Assumes a `char *destination' variable. */
378 #define REGEX_REALLOCATE(source, osize, nsize) \
379 (destination = (char *) alloca (nsize), \
380 bcopy (source, destination, osize), \
383 /* No need to do anything to free, after alloca. */
384 #define REGEX_FREE(arg) ((void)0) /* Do nothing! But inhibit gcc warning. */
386 #endif /* not REGEX_MALLOC */
388 /* Define how to allocate the failure stack. */
390 #if defined (REL_ALLOC) && defined (REGEX_MALLOC)
392 #define REGEX_ALLOCATE_STACK(size) \
393 r_alloc (&failure_stack_ptr, (size))
394 #define REGEX_REALLOCATE_STACK(source, osize, nsize) \
395 r_re_alloc (&failure_stack_ptr, (nsize))
396 #define REGEX_FREE_STACK(ptr) \
397 r_alloc_free (&failure_stack_ptr)
399 #else /* not using relocating allocator */
403 #define REGEX_ALLOCATE_STACK malloc
404 #define REGEX_REALLOCATE_STACK(source, osize, nsize) realloc (source, nsize)
405 #define REGEX_FREE_STACK free
407 #else /* not REGEX_MALLOC */
409 #define REGEX_ALLOCATE_STACK alloca
411 #define REGEX_REALLOCATE_STACK(source, osize, nsize) \
412 REGEX_REALLOCATE (source, osize, nsize)
413 /* No need to explicitly free anything. */
414 #define REGEX_FREE_STACK(arg)
416 #endif /* not REGEX_MALLOC */
417 #endif /* not using relocating allocator */
420 /* True if `size1' is non-NULL and PTR is pointing anywhere inside
421 `string1' or just past its end. This works if PTR is NULL, which is
423 #define FIRST_STRING_P(ptr) \
424 (size1 && string1 <= (ptr) && (ptr) <= string1 + size1)
426 /* (Re)Allocate N items of type T using malloc, or fail. */
427 #define TALLOC(n, t) ((t *) malloc ((n) * sizeof (t)))
428 #define RETALLOC(addr, n, t) ((addr) = (t *) realloc (addr, (n) * sizeof (t)))
429 #define RETALLOC_IF(addr, n, t) \
430 if (addr) RETALLOC((addr), (n), t); else (addr) = TALLOC ((n), t)
431 #define REGEX_TALLOC(n, t) ((t *) REGEX_ALLOCATE ((n) * sizeof (t)))
433 #define BYTEWIDTH 8 /* In bits. */
435 #define STREQ(s1, s2) ((strcmp (s1, s2) == 0))
439 #define MAX(a, b) ((a) > (b) ? (a) : (b))
440 #define MIN(a, b) ((a) < (b) ? (a) : (b))
442 /* Type of source-pattern and string chars. */
443 typedef const unsigned char re_char;
445 typedef char boolean;
449 static int re_match_2_internal ();
451 /* These are the command codes that appear in compiled regular
452 expressions. Some opcodes are followed by argument bytes. A
453 command code can specify any interpretation whatsoever for its
454 arguments. Zero bytes may appear in the compiled regular expression. */
460 /* Succeed right away--no more backtracking. */
463 /* Followed by one byte giving n, then by n literal bytes. */
466 /* Matches any (more or less) character. */
469 /* Matches any one char belonging to specified set. First
470 following byte is number of bitmap bytes. Then come bytes
471 for a bitmap saying which chars are in. Bits in each byte
472 are ordered low-bit-first. A character is in the set if its
473 bit is 1. A character too large to have a bit in the map is
474 automatically not in the set.
476 If the length byte has the 0x80 bit set, then that stuff
477 is followed by a range table:
478 2 bytes of flags for character sets (low 8 bits, high 8 bits)
479 See RANGE_TABLE_WORK_BITS below.
480 2 bytes, the number of pairs that follow
481 pairs, each 2 multibyte characters,
482 each multibyte character represented as 3 bytes. */
485 /* Same parameters as charset, but match any character that is
486 not one of those specified. */
489 /* Start remembering the text that is matched, for storing in a
490 register. Followed by one byte with the register number, in
491 the range 0 to one less than the pattern buffer's re_nsub
495 /* Stop remembering the text that is matched and store it in a
496 memory register. Followed by one byte with the register
497 number, in the range 0 to one less than `re_nsub' in the
501 /* Match a duplicate of something remembered. Followed by one
502 byte containing the register number. */
505 /* Fail unless at beginning of line. */
508 /* Fail unless at end of line. */
511 /* Succeeds if at beginning of buffer (if emacs) or at beginning
512 of string to be matched (if not). */
515 /* Analogously, for end of buffer/string. */
518 /* Followed by two byte relative address to which to jump. */
521 /* Followed by two-byte relative address of place to resume at
522 in case of failure. */
525 /* Like on_failure_jump, but pushes a placeholder instead of the
526 current string position when executed. */
527 on_failure_keep_string_jump,
529 /* Just like `on_failure_jump', except that it checks that we
530 don't get stuck in an infinite loop (matching an empty string
532 on_failure_jump_loop,
534 /* Just like `on_failure_jump_loop', except that it checks for
535 a different kind of loop (the kind that shows up with non-greedy
536 operators). This operation has to be immediately preceded
538 on_failure_jump_nastyloop,
540 /* A smart `on_failure_jump' used for greedy * and + operators.
541 It analyses the loop before which it is put and if the
542 loop does not require backtracking, it changes itself to
543 `on_failure_keep_string_jump' and short-circuits the loop,
544 else it just defaults to changing itself into `on_failure_jump'.
545 It assumes that it is pointing to just past a `jump'. */
546 on_failure_jump_smart,
548 /* Followed by two-byte relative address and two-byte number n.
549 After matching N times, jump to the address upon failure. */
552 /* Followed by two-byte relative address, and two-byte number n.
553 Jump to the address N times, then fail. */
556 /* Set the following two-byte relative address to the
557 subsequent two-byte number. The address *includes* the two
561 wordbeg, /* Succeeds if at word beginning. */
562 wordend, /* Succeeds if at word end. */
564 wordbound, /* Succeeds if at a word boundary. */
565 notwordbound, /* Succeeds if not at a word boundary. */
567 /* Matches any character whose syntax is specified. Followed by
568 a byte which contains a syntax code, e.g., Sword. */
571 /* Matches any character whose syntax is not that specified. */
575 ,before_dot, /* Succeeds if before point. */
576 at_dot, /* Succeeds if at point. */
577 after_dot, /* Succeeds if after point. */
579 /* Matches any character whose category-set contains the specified
580 category. The operator is followed by a byte which contains a
581 category code (mnemonic ASCII character). */
584 /* Matches any character whose category-set does not contain the
585 specified category. The operator is followed by a byte which
586 contains the category code (mnemonic ASCII character). */
591 /* Common operations on the compiled pattern. */
593 /* Store NUMBER in two contiguous bytes starting at DESTINATION. */
595 #define STORE_NUMBER(destination, number) \
597 (destination)[0] = (number) & 0377; \
598 (destination)[1] = (number) >> 8; \
601 /* Same as STORE_NUMBER, except increment DESTINATION to
602 the byte after where the number is stored. Therefore, DESTINATION
603 must be an lvalue. */
605 #define STORE_NUMBER_AND_INCR(destination, number) \
607 STORE_NUMBER (destination, number); \
608 (destination) += 2; \
611 /* Put into DESTINATION a number stored in two contiguous bytes starting
614 #define EXTRACT_NUMBER(destination, source) \
616 (destination) = *(source) & 0377; \
617 (destination) += SIGN_EXTEND_CHAR (*((source) + 1)) << 8; \
622 extract_number (dest, source)
624 unsigned char *source;
626 int temp = SIGN_EXTEND_CHAR (*(source + 1));
627 *dest = *source & 0377;
631 #ifndef EXTRACT_MACROS /* To debug the macros. */
632 #undef EXTRACT_NUMBER
633 #define EXTRACT_NUMBER(dest, src) extract_number (&dest, src)
634 #endif /* not EXTRACT_MACROS */
638 /* Same as EXTRACT_NUMBER, except increment SOURCE to after the number.
639 SOURCE must be an lvalue. */
641 #define EXTRACT_NUMBER_AND_INCR(destination, source) \
643 EXTRACT_NUMBER (destination, source); \
649 extract_number_and_incr (destination, source)
651 unsigned char **source;
653 extract_number (destination, *source);
657 #ifndef EXTRACT_MACROS
658 #undef EXTRACT_NUMBER_AND_INCR
659 #define EXTRACT_NUMBER_AND_INCR(dest, src) \
660 extract_number_and_incr (&dest, &src)
661 #endif /* not EXTRACT_MACROS */
665 /* Store a multibyte character in three contiguous bytes starting
666 DESTINATION, and increment DESTINATION to the byte after where the
667 character is stored. Therefore, DESTINATION must be an lvalue. */
669 #define STORE_CHARACTER_AND_INCR(destination, character) \
671 (destination)[0] = (character) & 0377; \
672 (destination)[1] = ((character) >> 8) & 0377; \
673 (destination)[2] = (character) >> 16; \
674 (destination) += 3; \
677 /* Put into DESTINATION a character stored in three contiguous bytes
678 starting at SOURCE. */
680 #define EXTRACT_CHARACTER(destination, source) \
682 (destination) = ((source)[0] \
683 | ((source)[1] << 8) \
684 | ((source)[2] << 16)); \
688 /* Macros for charset. */
690 /* Size of bitmap of charset P in bytes. P is a start of charset,
691 i.e. *P is (re_opcode_t) charset or (re_opcode_t) charset_not. */
692 #define CHARSET_BITMAP_SIZE(p) ((p)[1] & 0x7F)
694 /* Nonzero if charset P has range table. */
695 #define CHARSET_RANGE_TABLE_EXISTS_P(p) ((p)[1] & 0x80)
697 /* Return the address of range table of charset P. But not the start
698 of table itself, but the before where the number of ranges is
699 stored. `2 +' means to skip re_opcode_t and size of bitmap,
700 and the 2 bytes of flags at the start of the range table. */
701 #define CHARSET_RANGE_TABLE(p) (&(p)[4 + CHARSET_BITMAP_SIZE (p)])
703 /* Extract the bit flags that start a range table. */
704 #define CHARSET_RANGE_TABLE_BITS(p) \
705 ((p)[2 + CHARSET_BITMAP_SIZE (p)] \
706 + (p)[3 + CHARSET_BITMAP_SIZE (p)] * 0x100)
708 /* Test if C is listed in the bitmap of charset P. */
709 #define CHARSET_LOOKUP_BITMAP(p, c) \
710 ((c) < CHARSET_BITMAP_SIZE (p) * BYTEWIDTH \
711 && (p)[2 + (c) / BYTEWIDTH] & (1 << ((c) % BYTEWIDTH)))
713 /* Return the address of end of RANGE_TABLE. COUNT is number of
714 ranges (which is a pair of (start, end)) in the RANGE_TABLE. `* 2'
715 is start of range and end of range. `* 3' is size of each start
717 #define CHARSET_RANGE_TABLE_END(range_table, count) \
718 ((range_table) + (count) * 2 * 3)
720 /* Test if C is in RANGE_TABLE. A flag NOT is negated if C is in.
721 COUNT is number of ranges in RANGE_TABLE. */
722 #define CHARSET_LOOKUP_RANGE_TABLE_RAW(not, c, range_table, count) \
725 int range_start, range_end; \
727 unsigned char *range_table_end \
728 = CHARSET_RANGE_TABLE_END ((range_table), (count)); \
730 for (p = (range_table); p < range_table_end; p += 2 * 3) \
732 EXTRACT_CHARACTER (range_start, p); \
733 EXTRACT_CHARACTER (range_end, p + 3); \
735 if (range_start <= (c) && (c) <= range_end) \
744 /* Test if C is in range table of CHARSET. The flag NOT is negated if
745 C is listed in it. */
746 #define CHARSET_LOOKUP_RANGE_TABLE(not, c, charset) \
749 /* Number of ranges in range table. */ \
751 unsigned char *range_table = CHARSET_RANGE_TABLE (charset); \
753 EXTRACT_NUMBER_AND_INCR (count, range_table); \
754 CHARSET_LOOKUP_RANGE_TABLE_RAW ((not), (c), range_table, count); \
758 /* If DEBUG is defined, Regex prints many voluminous messages about what
759 it is doing (if the variable `debug' is nonzero). If linked with the
760 main program in `iregex.c', you can enter patterns and strings
761 interactively. And if linked with the main program in `main.c' and
762 the other test files, you can run the already-written tests. */
766 /* We use standard I/O for debugging. */
769 /* It is useful to test things that ``must'' be true when debugging. */
772 static int debug = -100000;
774 #define DEBUG_STATEMENT(e) e
775 #define DEBUG_PRINT1(x) if (debug > 0) printf (x)
776 #define DEBUG_PRINT2(x1, x2) if (debug > 0) printf (x1, x2)
777 #define DEBUG_PRINT3(x1, x2, x3) if (debug > 0) printf (x1, x2, x3)
778 #define DEBUG_PRINT4(x1, x2, x3, x4) if (debug > 0) printf (x1, x2, x3, x4)
779 #define DEBUG_PRINT_COMPILED_PATTERN(p, s, e) \
780 if (debug > 0) print_partial_compiled_pattern (s, e)
781 #define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2) \
782 if (debug > 0) print_double_string (w, s1, sz1, s2, sz2)
785 /* Print the fastmap in human-readable form. */
788 print_fastmap (fastmap)
791 unsigned was_a_range = 0;
794 while (i < (1 << BYTEWIDTH))
800 while (i < (1 << BYTEWIDTH) && fastmap[i])
816 /* Print a compiled pattern string in human-readable form, starting at
817 the START pointer into it and ending just before the pointer END. */
820 print_partial_compiled_pattern (start, end)
821 unsigned char *start;
825 unsigned char *p = start;
826 unsigned char *pend = end;
834 /* Loop over pattern commands. */
837 printf ("%d:\t", p - start);
839 switch ((re_opcode_t) *p++)
851 printf ("/exactn/%d", mcnt);
861 printf ("/start_memory/%d", *p++);
865 printf ("/stop_memory/%d", *p++);
869 printf ("/duplicate/%d", *p++);
879 register int c, last = -100;
880 register int in_range = 0;
881 int length = CHARSET_BITMAP_SIZE (p - 1);
882 int has_range_table = CHARSET_RANGE_TABLE_EXISTS_P (p - 1);
884 printf ("/charset [%s",
885 (re_opcode_t) *(p - 1) == charset_not ? "^" : "");
887 assert (p + *p < pend);
889 for (c = 0; c < 256; c++)
891 && (p[1 + (c/8)] & (1 << (c % 8))))
893 /* Are we starting a range? */
894 if (last + 1 == c && ! in_range)
899 /* Have we broken a range? */
900 else if (last + 1 != c && in_range)
922 printf ("has-range-table");
924 /* ??? Should print the range table; for now, just skip it. */
925 p += 2; /* skip range table bits */
926 EXTRACT_NUMBER_AND_INCR (count, p);
927 p = CHARSET_RANGE_TABLE_END (p, count);
940 case on_failure_jump:
941 extract_number_and_incr (&mcnt, &p);
942 printf ("/on_failure_jump to %d", p + mcnt - start);
945 case on_failure_keep_string_jump:
946 extract_number_and_incr (&mcnt, &p);
947 printf ("/on_failure_keep_string_jump to %d", p + mcnt - start);
950 case on_failure_jump_nastyloop:
951 extract_number_and_incr (&mcnt, &p);
952 printf ("/on_failure_jump_nastyloop to %d", p + mcnt - start);
955 case on_failure_jump_loop:
956 extract_number_and_incr (&mcnt, &p);
957 printf ("/on_failure_jump_loop to %d", p + mcnt - start);
960 case on_failure_jump_smart:
961 extract_number_and_incr (&mcnt, &p);
962 printf ("/on_failure_jump_smart to %d", p + mcnt - start);
966 extract_number_and_incr (&mcnt, &p);
967 printf ("/jump to %d", p + mcnt - start);
971 extract_number_and_incr (&mcnt, &p);
972 extract_number_and_incr (&mcnt2, &p);
973 printf ("/succeed_n to %d, %d times", p - 2 + mcnt - start, mcnt2);
977 extract_number_and_incr (&mcnt, &p);
978 extract_number_and_incr (&mcnt2, &p);
979 printf ("/jump_n to %d, %d times", p - 2 + mcnt - start, mcnt2);
983 extract_number_and_incr (&mcnt, &p);
984 extract_number_and_incr (&mcnt2, &p);
985 printf ("/set_number_at location %d to %d", p - 2 + mcnt - start, mcnt2);
989 printf ("/wordbound");
993 printf ("/notwordbound");
1001 printf ("/wordend");
1004 printf ("/syntaxspec");
1006 printf ("/%d", mcnt);
1010 printf ("/notsyntaxspec");
1012 printf ("/%d", mcnt);
1017 printf ("/before_dot");
1025 printf ("/after_dot");
1029 printf ("/categoryspec");
1031 printf ("/%d", mcnt);
1034 case notcategoryspec:
1035 printf ("/notcategoryspec");
1037 printf ("/%d", mcnt);
1050 printf ("?%d", *(p-1));
1056 printf ("%d:\tend of pattern.\n", p - start);
1061 print_compiled_pattern (bufp)
1062 struct re_pattern_buffer *bufp;
1064 unsigned char *buffer = bufp->buffer;
1066 print_partial_compiled_pattern (buffer, buffer + bufp->used);
1067 printf ("%ld bytes used/%ld bytes allocated.\n", bufp->used, bufp->allocated);
1069 if (bufp->fastmap_accurate && bufp->fastmap)
1071 printf ("fastmap: ");
1072 print_fastmap (bufp->fastmap);
1075 printf ("re_nsub: %d\t", bufp->re_nsub);
1076 printf ("regs_alloc: %d\t", bufp->regs_allocated);
1077 printf ("can_be_null: %d\t", bufp->can_be_null);
1078 printf ("newline_anchor: %d\n", bufp->newline_anchor);
1079 printf ("no_sub: %d\t", bufp->no_sub);
1080 printf ("not_bol: %d\t", bufp->not_bol);
1081 printf ("not_eol: %d\t", bufp->not_eol);
1082 printf ("syntax: %d\n", bufp->syntax);
1084 /* Perhaps we should print the translate table? */
1089 print_double_string (where, string1, size1, string2, size2)
1102 if (FIRST_STRING_P (where))
1104 for (this_char = where - string1; this_char < size1; this_char++)
1105 putchar (string1[this_char]);
1110 for (this_char = where - string2; this_char < size2; this_char++)
1111 putchar (string2[this_char]);
1115 #else /* not DEBUG */
1120 #define DEBUG_STATEMENT(e)
1121 #define DEBUG_PRINT1(x)
1122 #define DEBUG_PRINT2(x1, x2)
1123 #define DEBUG_PRINT3(x1, x2, x3)
1124 #define DEBUG_PRINT4(x1, x2, x3, x4)
1125 #define DEBUG_PRINT_COMPILED_PATTERN(p, s, e)
1126 #define DEBUG_PRINT_DOUBLE_STRING(w, s1, sz1, s2, sz2)
1128 #endif /* not DEBUG */
1130 /* Set by `re_set_syntax' to the current regexp syntax to recognize. Can
1131 also be assigned to arbitrarily: each pattern buffer stores its own
1132 syntax, so it can be changed between regex compilations. */
1133 /* This has no initializer because initialized variables in Emacs
1134 become read-only after dumping. */
1135 reg_syntax_t re_syntax_options;
1138 /* Specify the precise syntax of regexps for compilation. This provides
1139 for compatibility for various utilities which historically have
1140 different, incompatible syntaxes.
1142 The argument SYNTAX is a bit mask comprised of the various bits
1143 defined in regex.h. We return the old syntax. */
1146 re_set_syntax (syntax)
1147 reg_syntax_t syntax;
1149 reg_syntax_t ret = re_syntax_options;
1151 re_syntax_options = syntax;
1155 /* This table gives an error message for each of the error codes listed
1156 in regex.h. Obviously the order here has to be same as there.
1157 POSIX doesn't require that we do anything for REG_NOERROR,
1158 but why not be nice? */
1160 static const char *re_error_msgid[] =
1162 gettext_noop ("Success"), /* REG_NOERROR */
1163 gettext_noop ("No match"), /* REG_NOMATCH */
1164 gettext_noop ("Invalid regular expression"), /* REG_BADPAT */
1165 gettext_noop ("Invalid collation character"), /* REG_ECOLLATE */
1166 gettext_noop ("Invalid character class name"), /* REG_ECTYPE */
1167 gettext_noop ("Trailing backslash"), /* REG_EESCAPE */
1168 gettext_noop ("Invalid back reference"), /* REG_ESUBREG */
1169 gettext_noop ("Unmatched [ or [^"), /* REG_EBRACK */
1170 gettext_noop ("Unmatched ( or \\("), /* REG_EPAREN */
1171 gettext_noop ("Unmatched \\{"), /* REG_EBRACE */
1172 gettext_noop ("Invalid content of \\{\\}"), /* REG_BADBR */
1173 gettext_noop ("Invalid range end"), /* REG_ERANGE */
1174 gettext_noop ("Memory exhausted"), /* REG_ESPACE */
1175 gettext_noop ("Invalid preceding regular expression"), /* REG_BADRPT */
1176 gettext_noop ("Premature end of regular expression"), /* REG_EEND */
1177 gettext_noop ("Regular expression too big"), /* REG_ESIZE */
1178 gettext_noop ("Unmatched ) or \\)"), /* REG_ERPAREN */
1181 /* Avoiding alloca during matching, to placate r_alloc. */
1183 /* Define MATCH_MAY_ALLOCATE unless we need to make sure that the
1184 searching and matching functions should not call alloca. On some
1185 systems, alloca is implemented in terms of malloc, and if we're
1186 using the relocating allocator routines, then malloc could cause a
1187 relocation, which might (if the strings being searched are in the
1188 ralloc heap) shift the data out from underneath the regexp
1191 Here's another reason to avoid allocation: Emacs
1192 processes input from X in a signal handler; processing X input may
1193 call malloc; if input arrives while a matching routine is calling
1194 malloc, then we're scrod. But Emacs can't just block input while
1195 calling matching routines; then we don't notice interrupts when
1196 they come in. So, Emacs blocks input around all regexp calls
1197 except the matching calls, which it leaves unprotected, in the
1198 faith that they will not malloc. */
1200 /* Normally, this is fine. */
1201 #define MATCH_MAY_ALLOCATE
1203 /* When using GNU C, we are not REALLY using the C alloca, no matter
1204 what config.h may say. So don't take precautions for it. */
1209 /* The match routines may not allocate if (1) they would do it with malloc
1210 and (2) it's not safe for them to use malloc.
1211 Note that if REL_ALLOC is defined, matching would not use malloc for the
1212 failure stack, but we would still use it for the register vectors;
1213 so REL_ALLOC should not affect this. */
1214 #if (defined (C_ALLOCA) || defined (REGEX_MALLOC)) && defined (emacs)
1215 #undef MATCH_MAY_ALLOCATE
1219 /* Failure stack declarations and macros; both re_compile_fastmap and
1220 re_match_2 use a failure stack. These have to be macros because of
1221 REGEX_ALLOCATE_STACK. */
1224 /* Approximate number of failure points for which to initially allocate space
1225 when matching. If this number is exceeded, we allocate more
1226 space, so it is not a hard limit. */
1227 #ifndef INIT_FAILURE_ALLOC
1228 #define INIT_FAILURE_ALLOC 20
1231 /* Roughly the maximum number of failure points on the stack. Would be
1232 exactly that if always used TYPICAL_FAILURE_SIZE items each time we failed.
1233 This is a variable only so users of regex can assign to it; we never
1234 change it ourselves. */
1235 #if defined (MATCH_MAY_ALLOCATE)
1236 /* Note that 4400 is enough to cause a crash on Alpha OSF/1,
1237 whose default stack limit is 2mb. In order for a larger
1238 value to work reliably, you have to try to make it accord
1239 with the process stack limit. */
1240 int re_max_failures = 40000;
1242 int re_max_failures = 4000;
1245 union fail_stack_elt
1247 const unsigned char *pointer;
1248 unsigned int integer;
1251 typedef union fail_stack_elt fail_stack_elt_t;
1255 fail_stack_elt_t *stack;
1257 unsigned avail; /* Offset of next open position. */
1258 unsigned frame; /* Offset of the cur constructed frame. */
1261 #define PATTERN_STACK_EMPTY() (fail_stack.avail == 0)
1262 #define FAIL_STACK_EMPTY() (fail_stack.frame == 0)
1263 #define FAIL_STACK_FULL() (fail_stack.avail == fail_stack.size)
1266 /* Define macros to initialize and free the failure stack.
1267 Do `return -2' if the alloc fails. */
1269 #ifdef MATCH_MAY_ALLOCATE
1270 #define INIT_FAIL_STACK() \
1272 fail_stack.stack = (fail_stack_elt_t *) \
1273 REGEX_ALLOCATE_STACK (INIT_FAILURE_ALLOC * TYPICAL_FAILURE_SIZE \
1274 * sizeof (fail_stack_elt_t)); \
1276 if (fail_stack.stack == NULL) \
1279 fail_stack.size = INIT_FAILURE_ALLOC; \
1280 fail_stack.avail = 0; \
1281 fail_stack.frame = 0; \
1284 #define RESET_FAIL_STACK() REGEX_FREE_STACK (fail_stack.stack)
1286 #define INIT_FAIL_STACK() \
1288 fail_stack.avail = 0; \
1289 fail_stack.frame = 0; \
1292 #define RESET_FAIL_STACK()
1296 /* Double the size of FAIL_STACK, up to a limit
1297 which allows approximately `re_max_failures' items.
1299 Return 1 if succeeds, and 0 if either ran out of memory
1300 allocating space for it or it was already too large.
1302 REGEX_REALLOCATE_STACK requires `destination' be declared. */
1304 /* Factor to increase the failure stack size by
1305 when we increase it.
1306 This used to be 2, but 2 was too wasteful
1307 because the old discarded stacks added up to as much space
1308 were as ultimate, maximum-size stack. */
1309 #define FAIL_STACK_GROWTH_FACTOR 4
1311 #define GROW_FAIL_STACK(fail_stack) \
1312 (((fail_stack).size * sizeof (fail_stack_elt_t) \
1313 >= re_max_failures * TYPICAL_FAILURE_SIZE) \
1315 : ((fail_stack).stack \
1316 = (fail_stack_elt_t *) \
1317 REGEX_REALLOCATE_STACK ((fail_stack).stack, \
1318 (fail_stack).size * sizeof (fail_stack_elt_t), \
1319 MIN (re_max_failures * TYPICAL_FAILURE_SIZE, \
1320 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1321 * FAIL_STACK_GROWTH_FACTOR))), \
1323 (fail_stack).stack == NULL \
1325 : ((fail_stack).size \
1326 = (MIN (re_max_failures * TYPICAL_FAILURE_SIZE, \
1327 ((fail_stack).size * sizeof (fail_stack_elt_t) \
1328 * FAIL_STACK_GROWTH_FACTOR)) \
1329 / sizeof (fail_stack_elt_t)), \
1333 /* Push pointer POINTER on FAIL_STACK.
1334 Return 1 if was able to do so and 0 if ran out of memory allocating
1336 #define PUSH_PATTERN_OP(POINTER, FAIL_STACK) \
1337 ((FAIL_STACK_FULL () \
1338 && !GROW_FAIL_STACK (FAIL_STACK)) \
1340 : ((FAIL_STACK).stack[(FAIL_STACK).avail++].pointer = POINTER, \
1342 #define POP_PATTERN_OP() POP_FAILURE_POINTER ()
1344 /* Push a pointer value onto the failure stack.
1345 Assumes the variable `fail_stack'. Probably should only
1346 be called from within `PUSH_FAILURE_POINT'. */
1347 #define PUSH_FAILURE_POINTER(item) \
1348 fail_stack.stack[fail_stack.avail++].pointer = (unsigned char *) (item)
1350 /* This pushes an integer-valued item onto the failure stack.
1351 Assumes the variable `fail_stack'. Probably should only
1352 be called from within `PUSH_FAILURE_POINT'. */
1353 #define PUSH_FAILURE_INT(item) \
1354 fail_stack.stack[fail_stack.avail++].integer = (item)
1356 /* Push a fail_stack_elt_t value onto the failure stack.
1357 Assumes the variable `fail_stack'. Probably should only
1358 be called from within `PUSH_FAILURE_POINT'. */
1359 #define PUSH_FAILURE_ELT(item) \
1360 fail_stack.stack[fail_stack.avail++] = (item)
1362 /* These three POP... operations complement the three PUSH... operations.
1363 All assume that `fail_stack' is nonempty. */
1364 #define POP_FAILURE_POINTER() fail_stack.stack[--fail_stack.avail].pointer
1365 #define POP_FAILURE_INT() fail_stack.stack[--fail_stack.avail].integer
1366 #define POP_FAILURE_ELT() fail_stack.stack[--fail_stack.avail]
1368 /* Individual items aside from the registers. */
1369 #define NUM_NONREG_ITEMS 3
1371 /* Used to examine the stack (to detect infinite loops). */
1372 #define FAILURE_PAT(h) fail_stack.stack[(h) - 1].pointer
1373 #define FAILURE_STR(h) (fail_stack.stack[(h) - 2].pointer)
1374 #define NEXT_FAILURE_HANDLE(h) fail_stack.stack[(h) - 3].integer
1375 #define TOP_FAILURE_HANDLE() fail_stack.frame
1378 #define ENSURE_FAIL_STACK(space) \
1379 while (REMAINING_AVAIL_SLOTS <= space) { \
1380 if (!GROW_FAIL_STACK (fail_stack)) \
1382 DEBUG_PRINT2 ("\n Doubled stack; size now: %d\n", (fail_stack).size);\
1383 DEBUG_PRINT2 (" slots available: %d\n", REMAINING_AVAIL_SLOTS);\
1386 /* Push register NUM onto the stack. */
1387 #define PUSH_FAILURE_REG(num) \
1389 char *destination; \
1390 ENSURE_FAIL_STACK(3); \
1391 DEBUG_PRINT4 (" Push reg %d (spanning %p -> %p)\n", \
1392 num, regstart[num], regend[num]); \
1393 PUSH_FAILURE_POINTER (regstart[num]); \
1394 PUSH_FAILURE_POINTER (regend[num]); \
1395 PUSH_FAILURE_INT (num); \
1398 /* Pop a saved register off the stack. */
1399 #define POP_FAILURE_REG() \
1401 int reg = POP_FAILURE_INT (); \
1402 regend[reg] = POP_FAILURE_POINTER (); \
1403 regstart[reg] = POP_FAILURE_POINTER (); \
1404 DEBUG_PRINT4 (" Pop reg %d (spanning %p -> %p)\n", \
1405 reg, regstart[reg], regend[reg]); \
1408 /* Check that we are not stuck in an infinite loop. */
1409 #define CHECK_INFINITE_LOOP(pat_cur, string_place) \
1411 int failure = TOP_FAILURE_HANDLE(); \
1412 /* Check for infinite matching loops */ \
1413 while (failure > 0 && \
1414 (FAILURE_STR (failure) == string_place \
1415 || FAILURE_STR (failure) == NULL)) \
1417 assert (FAILURE_PAT (failure) >= bufp->buffer \
1418 && FAILURE_PAT (failure) <= bufp->buffer + bufp->used); \
1419 if (FAILURE_PAT (failure) == pat_cur) \
1421 DEBUG_PRINT2 (" Other pattern: %p\n", FAILURE_PAT (failure)); \
1422 failure = NEXT_FAILURE_HANDLE(failure); \
1424 DEBUG_PRINT2 (" Other string: %p\n", FAILURE_STR (failure)); \
1427 /* Push the information about the state we will need
1428 if we ever fail back to it.
1430 Requires variables fail_stack, regstart, regend and
1431 num_regs be declared. GROW_FAIL_STACK requires `destination' be
1434 Does `return FAILURE_CODE' if runs out of memory. */
1436 #define PUSH_FAILURE_POINT(pattern, string_place) \
1438 char *destination; \
1439 /* Must be int, so when we don't save any registers, the arithmetic \
1440 of 0 + -1 isn't done as unsigned. */ \
1442 DEBUG_STATEMENT (failure_id++); \
1443 DEBUG_STATEMENT (nfailure_points_pushed++); \
1444 DEBUG_PRINT2 ("\nPUSH_FAILURE_POINT #%u:\n", failure_id); \
1445 DEBUG_PRINT2 (" Before push, next avail: %d\n", (fail_stack).avail); \
1446 DEBUG_PRINT2 (" size: %d\n", (fail_stack).size);\
1448 ENSURE_FAIL_STACK (NUM_NONREG_ITEMS); \
1450 DEBUG_PRINT1 ("\n"); \
1452 DEBUG_PRINT2 (" Push frame index: %d\n", fail_stack.frame); \
1453 PUSH_FAILURE_INT (fail_stack.frame); \
1455 DEBUG_PRINT2 (" Push string %p: `", string_place); \
1456 DEBUG_PRINT_DOUBLE_STRING (string_place, string1, size1, string2, size2);\
1457 DEBUG_PRINT1 ("'\n"); \
1458 PUSH_FAILURE_POINTER (string_place); \
1460 DEBUG_PRINT2 (" Push pattern %p: ", pattern); \
1461 DEBUG_PRINT_COMPILED_PATTERN (bufp, pattern, pend); \
1462 PUSH_FAILURE_POINTER (pattern); \
1464 /* Close the frame by moving the frame pointer past it. */ \
1465 fail_stack.frame = fail_stack.avail; \
1468 /* Estimate the size of data pushed by a typical failure stack entry.
1469 An estimate is all we need, because all we use this for
1470 is to choose a limit for how big to make the failure stack. */
1472 #define TYPICAL_FAILURE_SIZE 20
1474 /* How many items can still be added to the stack without overflowing it. */
1475 #define REMAINING_AVAIL_SLOTS ((fail_stack).size - (fail_stack).avail)
1478 /* Pops what PUSH_FAIL_STACK pushes.
1480 We restore into the parameters, all of which should be lvalues:
1481 STR -- the saved data position.
1482 PAT -- the saved pattern position.
1483 REGSTART, REGEND -- arrays of string positions.
1485 Also assumes the variables `fail_stack' and (if debugging), `bufp',
1486 `pend', `string1', `size1', `string2', and `size2'. */
1488 #define POP_FAILURE_POINT(str, pat) \
1490 assert (!FAIL_STACK_EMPTY ()); \
1492 /* Remove failure points and point to how many regs pushed. */ \
1493 DEBUG_PRINT1 ("POP_FAILURE_POINT:\n"); \
1494 DEBUG_PRINT2 (" Before pop, next avail: %d\n", fail_stack.avail); \
1495 DEBUG_PRINT2 (" size: %d\n", fail_stack.size); \
1497 /* Pop the saved registers. */ \
1498 while (fail_stack.frame < fail_stack.avail) \
1499 POP_FAILURE_REG (); \
1501 pat = (unsigned char *) POP_FAILURE_POINTER (); \
1502 DEBUG_PRINT2 (" Popping pattern %p: ", pat); \
1503 DEBUG_PRINT_COMPILED_PATTERN (bufp, pat, pend); \
1505 /* If the saved string location is NULL, it came from an \
1506 on_failure_keep_string_jump opcode, and we want to throw away the \
1507 saved NULL, thus retaining our current position in the string. */ \
1508 str = (re_char *) POP_FAILURE_POINTER (); \
1509 DEBUG_PRINT2 (" Popping string %p: `", str); \
1510 DEBUG_PRINT_DOUBLE_STRING (str, string1, size1, string2, size2); \
1511 DEBUG_PRINT1 ("'\n"); \
1513 fail_stack.frame = POP_FAILURE_INT (); \
1514 DEBUG_PRINT2 (" Popping frame index: %d\n", fail_stack.frame); \
1516 assert (fail_stack.avail >= 0); \
1517 assert (fail_stack.frame <= fail_stack.avail); \
1519 DEBUG_STATEMENT (nfailure_points_popped++); \
1520 } while (0) /* POP_FAILURE_POINT */
1524 /* Registers are set to a sentinel when they haven't yet matched. */
1525 #define REG_UNSET_VALUE NULL
1526 #define REG_UNSET(e) ((e) == REG_UNSET_VALUE)
1528 /* Subroutine declarations and macros for regex_compile. */
1530 static void store_op1 _RE_ARGS((re_opcode_t op, unsigned char *loc, int arg));
1531 static void store_op2 _RE_ARGS((re_opcode_t op, unsigned char *loc,
1532 int arg1, int arg2));
1533 static void insert_op1 _RE_ARGS((re_opcode_t op, unsigned char *loc,
1534 int arg, unsigned char *end));
1535 static void insert_op2 _RE_ARGS((re_opcode_t op, unsigned char *loc,
1536 int arg1, int arg2, unsigned char *end));
1537 static boolean at_begline_loc_p _RE_ARGS((const unsigned char *pattern,
1538 const unsigned char *p,
1539 reg_syntax_t syntax));
1540 static boolean at_endline_loc_p _RE_ARGS((const unsigned char *p,
1541 const unsigned char *pend,
1542 reg_syntax_t syntax));
1543 static unsigned char *skip_one_char _RE_ARGS((unsigned char *p));
1545 /* Fetch the next character in the uncompiled pattern---translating it
1546 if necessary. Also cast from a signed character in the constant
1547 string passed to us by the user to an unsigned char that we can use
1548 as an array index (in, e.g., `translate'). */
1550 #define PATFETCH(c) \
1553 if (RE_TRANSLATE_P (translate)) c = RE_TRANSLATE (translate, c); \
1557 /* Fetch the next character in the uncompiled pattern, with no
1559 #define PATFETCH_RAW(c) \
1560 do {if (p == pend) return REG_EEND; \
1564 /* Go backwards one character in the pattern. */
1565 #define PATUNFETCH p--
1568 /* If `translate' is non-null, return translate[D], else just D. We
1569 cast the subscript to translate because some data is declared as
1570 `char *', to avoid warnings when a string constant is passed. But
1571 when we use a character as a subscript we must make it unsigned. */
1573 #define TRANSLATE(d) \
1574 (RE_TRANSLATE_P (translate) ? RE_TRANSLATE (translate, (d)) : (d))
1578 /* Macros for outputting the compiled pattern into `buffer'. */
1580 /* If the buffer isn't allocated when it comes in, use this. */
1581 #define INIT_BUF_SIZE 32
1583 /* Make sure we have at least N more bytes of space in buffer. */
1584 #define GET_BUFFER_SPACE(n) \
1585 while (b - bufp->buffer + (n) > bufp->allocated) \
1588 /* Make sure we have one more byte of buffer space and then add C to it. */
1589 #define BUF_PUSH(c) \
1591 GET_BUFFER_SPACE (1); \
1592 *b++ = (unsigned char) (c); \
1596 /* Ensure we have two more bytes of buffer space and then append C1 and C2. */
1597 #define BUF_PUSH_2(c1, c2) \
1599 GET_BUFFER_SPACE (2); \
1600 *b++ = (unsigned char) (c1); \
1601 *b++ = (unsigned char) (c2); \
1605 /* As with BUF_PUSH_2, except for three bytes. */
1606 #define BUF_PUSH_3(c1, c2, c3) \
1608 GET_BUFFER_SPACE (3); \
1609 *b++ = (unsigned char) (c1); \
1610 *b++ = (unsigned char) (c2); \
1611 *b++ = (unsigned char) (c3); \
1615 /* Store a jump with opcode OP at LOC to location TO. We store a
1616 relative address offset by the three bytes the jump itself occupies. */
1617 #define STORE_JUMP(op, loc, to) \
1618 store_op1 (op, loc, (to) - (loc) - 3)
1620 /* Likewise, for a two-argument jump. */
1621 #define STORE_JUMP2(op, loc, to, arg) \
1622 store_op2 (op, loc, (to) - (loc) - 3, arg)
1624 /* Like `STORE_JUMP', but for inserting. Assume `b' is the buffer end. */
1625 #define INSERT_JUMP(op, loc, to) \
1626 insert_op1 (op, loc, (to) - (loc) - 3, b)
1628 /* Like `STORE_JUMP2', but for inserting. Assume `b' is the buffer end. */
1629 #define INSERT_JUMP2(op, loc, to, arg) \
1630 insert_op2 (op, loc, (to) - (loc) - 3, arg, b)
1633 /* This is not an arbitrary limit: the arguments which represent offsets
1634 into the pattern are two bytes long. So if 2^16 bytes turns out to
1635 be too small, many things would have to change. */
1636 #define MAX_BUF_SIZE (1L << 16)
1639 /* Extend the buffer by twice its current size via realloc and
1640 reset the pointers that pointed into the old block to point to the
1641 correct places in the new one. If extending the buffer results in it
1642 being larger than MAX_BUF_SIZE, then flag memory exhausted. */
1643 #define EXTEND_BUFFER() \
1645 unsigned char *old_buffer = bufp->buffer; \
1646 if (bufp->allocated == MAX_BUF_SIZE) \
1648 bufp->allocated <<= 1; \
1649 if (bufp->allocated > MAX_BUF_SIZE) \
1650 bufp->allocated = MAX_BUF_SIZE; \
1651 bufp->buffer = (unsigned char *) realloc (bufp->buffer, bufp->allocated);\
1652 if (bufp->buffer == NULL) \
1653 return REG_ESPACE; \
1654 /* If the buffer moved, move all the pointers into it. */ \
1655 if (old_buffer != bufp->buffer) \
1657 b = (b - old_buffer) + bufp->buffer; \
1658 begalt = (begalt - old_buffer) + bufp->buffer; \
1659 if (fixup_alt_jump) \
1660 fixup_alt_jump = (fixup_alt_jump - old_buffer) + bufp->buffer;\
1662 laststart = (laststart - old_buffer) + bufp->buffer; \
1663 if (pending_exact) \
1664 pending_exact = (pending_exact - old_buffer) + bufp->buffer; \
1669 /* Since we have one byte reserved for the register number argument to
1670 {start,stop}_memory, the maximum number of groups we can report
1671 things about is what fits in that byte. */
1672 #define MAX_REGNUM 255
1674 /* But patterns can have more than `MAX_REGNUM' registers. We just
1675 ignore the excess. */
1676 typedef unsigned regnum_t;
1679 /* Macros for the compile stack. */
1681 /* Since offsets can go either forwards or backwards, this type needs to
1682 be able to hold values from -(MAX_BUF_SIZE - 1) to MAX_BUF_SIZE - 1. */
1683 typedef int pattern_offset_t;
1687 pattern_offset_t begalt_offset;
1688 pattern_offset_t fixup_alt_jump;
1689 pattern_offset_t laststart_offset;
1691 } compile_stack_elt_t;
1696 compile_stack_elt_t *stack;
1698 unsigned avail; /* Offset of next open position. */
1699 } compile_stack_type;
1702 #define INIT_COMPILE_STACK_SIZE 32
1704 #define COMPILE_STACK_EMPTY (compile_stack.avail == 0)
1705 #define COMPILE_STACK_FULL (compile_stack.avail == compile_stack.size)
1707 /* The next available element. */
1708 #define COMPILE_STACK_TOP (compile_stack.stack[compile_stack.avail])
1711 /* Structure to manage work area for range table. */
1712 struct range_table_work_area
1714 int *table; /* actual work area. */
1715 int allocated; /* allocated size for work area in bytes. */
1716 int used; /* actually used size in words. */
1717 int bits; /* flag to record character classes */
1720 /* Make sure that WORK_AREA can hold more N multibyte characters. */
1721 #define EXTEND_RANGE_TABLE_WORK_AREA(work_area, n) \
1723 if (((work_area).used + (n)) * sizeof (int) > (work_area).allocated) \
1725 (work_area).allocated += 16 * sizeof (int); \
1726 if ((work_area).table) \
1728 = (int *) realloc ((work_area).table, (work_area).allocated); \
1731 = (int *) malloc ((work_area).allocated); \
1732 if ((work_area).table == 0) \
1733 FREE_STACK_RETURN (REG_ESPACE); \
1737 #define SET_RANGE_TABLE_WORK_AREA_BIT(work_area, bit) \
1738 (work_area).bits |= (bit)
1740 /* These bits represent the various character classes such as [:alnum:]
1741 in a charset's range table. */
1742 #define BIT_ALNUM 0x1
1743 #define BIT_ALPHA 0x2
1744 #define BIT_WORD 0x4
1745 #define BIT_ASCII 0x8
1746 #define BIT_NONASCII 0x10
1747 #define BIT_GRAPH 0x20
1748 #define BIT_LOWER 0x40
1749 #define BIT_PRINT 0x80
1750 #define BIT_PUNCT 0x100
1751 #define BIT_SPACE 0x200
1752 #define BIT_UPPER 0x400
1753 #define BIT_UNIBYTE 0x800
1754 #define BIT_MULTIBYTE 0x1000
1756 /* Set a range (RANGE_START, RANGE_END) to WORK_AREA. */
1757 #define SET_RANGE_TABLE_WORK_AREA(work_area, range_start, range_end) \
1759 EXTEND_RANGE_TABLE_WORK_AREA ((work_area), 2); \
1760 (work_area).table[(work_area).used++] = (range_start); \
1761 (work_area).table[(work_area).used++] = (range_end); \
1764 /* Free allocated memory for WORK_AREA. */
1765 #define FREE_RANGE_TABLE_WORK_AREA(work_area) \
1767 if ((work_area).table) \
1768 free ((work_area).table); \
1771 #define CLEAR_RANGE_TABLE_WORK_USED(work_area) ((work_area).used = 0, (work_area).bits = 0)
1772 #define RANGE_TABLE_WORK_USED(work_area) ((work_area).used)
1773 #define RANGE_TABLE_WORK_BITS(work_area) ((work_area).bits)
1774 #define RANGE_TABLE_WORK_ELT(work_area, i) ((work_area).table[i])
1777 /* Set the bit for character C in a list. */
1778 #define SET_LIST_BIT(c) \
1779 (b[((unsigned char) (c)) / BYTEWIDTH] \
1780 |= 1 << (((unsigned char) c) % BYTEWIDTH))
1783 /* Get the next unsigned number in the uncompiled pattern. */
1784 #define GET_UNSIGNED_NUMBER(num) \
1785 do { if (p != pend) \
1788 while (ISDIGIT (c)) \
1792 num = num * 10 + c - '0'; \
1800 #define CHAR_CLASS_MAX_LENGTH 6 /* Namely, `xdigit'. */
1802 #define IS_CHAR_CLASS(string) \
1803 (STREQ (string, "alpha") || STREQ (string, "upper") \
1804 || STREQ (string, "lower") || STREQ (string, "digit") \
1805 || STREQ (string, "alnum") || STREQ (string, "xdigit") \
1806 || STREQ (string, "space") || STREQ (string, "print") \
1807 || STREQ (string, "punct") || STREQ (string, "graph") \
1808 || STREQ (string, "cntrl") || STREQ (string, "blank") \
1809 || STREQ (string, "word") \
1810 || STREQ (string, "ascii") || STREQ (string, "nonascii") \
1811 || STREQ (string, "unibyte") || STREQ (string, "multibyte"))
1813 /* QUIT is only used on NTemacs. */
1814 #if !defined (WINDOWSNT) || !defined (emacs)
1819 #ifndef MATCH_MAY_ALLOCATE
1821 /* If we cannot allocate large objects within re_match_2_internal,
1822 we make the fail stack and register vectors global.
1823 The fail stack, we grow to the maximum size when a regexp
1825 The register vectors, we adjust in size each time we
1826 compile a regexp, according to the number of registers it needs. */
1828 static fail_stack_type fail_stack;
1830 /* Size with which the following vectors are currently allocated.
1831 That is so we can make them bigger as needed,
1832 but never make them smaller. */
1833 static int regs_allocated_size;
1835 static re_char ** regstart, ** regend;
1836 static re_char **best_regstart, **best_regend;
1838 /* Make the register vectors big enough for NUM_REGS registers,
1839 but don't make them smaller. */
1842 regex_grow_registers (num_regs)
1845 if (num_regs > regs_allocated_size)
1847 RETALLOC_IF (regstart, num_regs, re_char *);
1848 RETALLOC_IF (regend, num_regs, re_char *);
1849 RETALLOC_IF (best_regstart, num_regs, re_char *);
1850 RETALLOC_IF (best_regend, num_regs, re_char *);
1852 regs_allocated_size = num_regs;
1856 #endif /* not MATCH_MAY_ALLOCATE */
1858 static boolean group_in_compile_stack _RE_ARGS ((compile_stack_type
1862 /* `regex_compile' compiles PATTERN (of length SIZE) according to SYNTAX.
1863 Returns one of error codes defined in `regex.h', or zero for success.
1865 Assumes the `allocated' (and perhaps `buffer') and `translate'
1866 fields are set in BUFP on entry.
1868 If it succeeds, results are put in BUFP (if it returns an error, the
1869 contents of BUFP are undefined):
1870 `buffer' is the compiled pattern;
1871 `syntax' is set to SYNTAX;
1872 `used' is set to the length of the compiled pattern;
1873 `fastmap_accurate' is zero;
1874 `re_nsub' is the number of subexpressions in PATTERN;
1875 `not_bol' and `not_eol' are zero;
1877 The `fastmap' and `newline_anchor' fields are neither
1878 examined nor set. */
1880 /* Insert the `jump' from the end of last alternative to "here".
1881 The space for the jump has already been allocated. */
1882 #define FIXUP_ALT_JUMP() \
1884 if (fixup_alt_jump) \
1885 STORE_JUMP (jump, fixup_alt_jump, b); \
1889 /* Return, freeing storage we allocated. */
1890 #define FREE_STACK_RETURN(value) \
1892 FREE_RANGE_TABLE_WORK_AREA (range_table_work); \
1893 free (compile_stack.stack); \
1897 static reg_errcode_t
1898 regex_compile (pattern, size, syntax, bufp)
1901 reg_syntax_t syntax;
1902 struct re_pattern_buffer *bufp;
1904 /* We fetch characters from PATTERN here. Even though PATTERN is
1905 `char *' (i.e., signed), we declare these variables as unsigned, so
1906 they can be reliably used as array indices. */
1907 register unsigned int c, c1;
1909 /* A random temporary spot in PATTERN. */
1912 /* Points to the end of the buffer, where we should append. */
1913 register unsigned char *b;
1915 /* Keeps track of unclosed groups. */
1916 compile_stack_type compile_stack;
1918 /* Points to the current (ending) position in the pattern. */
1920 /* `const' makes AIX compiler fail. */
1921 unsigned char *p = pattern;
1923 re_char *p = pattern;
1925 re_char *pend = pattern + size;
1927 /* How to translate the characters in the pattern. */
1928 RE_TRANSLATE_TYPE translate = bufp->translate;
1930 /* Address of the count-byte of the most recently inserted `exactn'
1931 command. This makes it possible to tell if a new exact-match
1932 character can be added to that command or if the character requires
1933 a new `exactn' command. */
1934 unsigned char *pending_exact = 0;
1936 /* Address of start of the most recently finished expression.
1937 This tells, e.g., postfix * where to find the start of its
1938 operand. Reset at the beginning of groups and alternatives. */
1939 unsigned char *laststart = 0;
1941 /* Address of beginning of regexp, or inside of last group. */
1942 unsigned char *begalt;
1944 /* Place in the uncompiled pattern (i.e., the {) to
1945 which to go back if the interval is invalid. */
1946 re_char *beg_interval;
1948 /* Address of the place where a forward jump should go to the end of
1949 the containing expression. Each alternative of an `or' -- except the
1950 last -- ends with a forward jump of this sort. */
1951 unsigned char *fixup_alt_jump = 0;
1953 /* Counts open-groups as they are encountered. Remembered for the
1954 matching close-group on the compile stack, so the same register
1955 number is put in the stop_memory as the start_memory. */
1956 regnum_t regnum = 0;
1958 /* Work area for range table of charset. */
1959 struct range_table_work_area range_table_work;
1963 DEBUG_PRINT1 ("\nCompiling pattern: ");
1966 unsigned debug_count;
1968 for (debug_count = 0; debug_count < size; debug_count++)
1969 putchar (pattern[debug_count]);
1974 /* Initialize the compile stack. */
1975 compile_stack.stack = TALLOC (INIT_COMPILE_STACK_SIZE, compile_stack_elt_t);
1976 if (compile_stack.stack == NULL)
1979 compile_stack.size = INIT_COMPILE_STACK_SIZE;
1980 compile_stack.avail = 0;
1982 range_table_work.table = 0;
1983 range_table_work.allocated = 0;
1985 /* Initialize the pattern buffer. */
1986 bufp->syntax = syntax;
1987 bufp->fastmap_accurate = 0;
1988 bufp->not_bol = bufp->not_eol = 0;
1990 /* Set `used' to zero, so that if we return an error, the pattern
1991 printer (for debugging) will think there's no pattern. We reset it
1995 /* Always count groups, whether or not bufp->no_sub is set. */
1999 /* bufp->multibyte is set before regex_compile is called, so don't alter
2001 #else /* not emacs */
2002 /* Nothing is recognized as a multibyte character. */
2003 bufp->multibyte = 0;
2006 #if !defined (emacs) && !defined (SYNTAX_TABLE)
2007 /* Initialize the syntax table. */
2008 init_syntax_once ();
2011 if (bufp->allocated == 0)
2014 { /* If zero allocated, but buffer is non-null, try to realloc
2015 enough space. This loses if buffer's address is bogus, but
2016 that is the user's responsibility. */
2017 RETALLOC (bufp->buffer, INIT_BUF_SIZE, unsigned char);
2020 { /* Caller did not allocate a buffer. Do it for them. */
2021 bufp->buffer = TALLOC (INIT_BUF_SIZE, unsigned char);
2023 if (!bufp->buffer) FREE_STACK_RETURN (REG_ESPACE);
2025 bufp->allocated = INIT_BUF_SIZE;
2028 begalt = b = bufp->buffer;
2030 /* Loop through the uncompiled pattern until we're at the end. */
2039 if ( /* If at start of pattern, it's an operator. */
2041 /* If context independent, it's an operator. */
2042 || syntax & RE_CONTEXT_INDEP_ANCHORS
2043 /* Otherwise, depends on what's come before. */
2044 || at_begline_loc_p (pattern, p, syntax))
2054 if ( /* If at end 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 next. */
2059 || at_endline_loc_p (p, pend, syntax))
2069 if ((syntax & RE_BK_PLUS_QM)
2070 || (syntax & RE_LIMITED_OPS))
2074 /* If there is no previous pattern... */
2077 if (syntax & RE_CONTEXT_INVALID_OPS)
2078 FREE_STACK_RETURN (REG_BADRPT);
2079 else if (!(syntax & RE_CONTEXT_INDEP_OPS))
2084 /* 1 means zero (many) matches is allowed. */
2085 boolean zero_times_ok = 0, many_times_ok = 0;
2088 /* If there is a sequence of repetition chars, collapse it
2089 down to just one (the right one). We can't combine
2090 interval operators with these because of, e.g., `a{2}*',
2091 which should only match an even number of `a's. */
2095 if (!(syntax & RE_ALL_GREEDY)
2096 && c == '?' && (zero_times_ok || many_times_ok))
2100 zero_times_ok |= c != '+';
2101 many_times_ok |= c != '?';
2110 || (!(syntax & RE_BK_PLUS_QM) && (c == '+' || c == '?')))
2113 else if (syntax & RE_BK_PLUS_QM && c == '\\')
2115 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2118 if (!(c1 == '+' || c1 == '?'))
2133 /* If we get here, we found another repeat character. */
2136 /* Star, etc. applied to an empty pattern is equivalent
2137 to an empty pattern. */
2138 if (!laststart || laststart == b)
2141 /* Now we know whether or not zero matches is allowed
2142 and also whether or not two or more matches is allowed. */
2147 boolean simple = skip_one_char (laststart) == b;
2148 unsigned int startoffset = 0;
2149 assert (skip_one_char (laststart) <= b);
2151 if (!zero_times_ok && simple)
2152 { /* Since simple * loops can be made faster by using
2153 on_failure_keep_string_jump, we turn simple P+
2154 into PP* if P is simple. */
2155 unsigned char *p1, *p2;
2156 startoffset = b - laststart;
2157 GET_BUFFER_SPACE (startoffset);
2158 p1 = b; p2 = laststart;
2164 GET_BUFFER_SPACE (6);
2167 STORE_JUMP (on_failure_jump_loop, b, b + 6);
2169 /* Simple * loops can use on_failure_keep_string_jump
2170 depending on what follows. But since we don't know
2171 that yet, we leave the decision up to
2172 on_failure_jump_smart. */
2173 INSERT_JUMP (simple ? on_failure_jump_smart
2174 : on_failure_jump_loop,
2175 laststart + startoffset, b + 6);
2177 STORE_JUMP (jump, b, laststart + startoffset);
2182 /* A simple ? pattern. */
2183 assert (zero_times_ok);
2184 GET_BUFFER_SPACE (3);
2185 INSERT_JUMP (on_failure_jump, laststart, b + 3);
2189 else /* not greedy */
2190 { /* I wish the greedy and non-greedy cases could be merged. */
2192 GET_BUFFER_SPACE (7); /* We might use less. */
2195 /* The non-greedy multiple match looks like a repeat..until:
2196 we only need a conditional jump at the end of the loop */
2198 STORE_JUMP (on_failure_jump_nastyloop, b, laststart);
2202 /* The repeat...until naturally matches one or more.
2203 To also match zero times, we need to first jump to
2204 the end of the loop (its conditional jump). */
2205 INSERT_JUMP (jump, laststart, b);
2211 /* non-greedy a?? */
2212 INSERT_JUMP (jump, laststart, b + 3);
2214 INSERT_JUMP (on_failure_jump, laststart, laststart + 6);
2231 CLEAR_RANGE_TABLE_WORK_USED (range_table_work);
2233 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2235 /* Ensure that we have enough space to push a charset: the
2236 opcode, the length count, and the bitset; 34 bytes in all. */
2237 GET_BUFFER_SPACE (34);
2241 /* We test `*p == '^' twice, instead of using an if
2242 statement, so we only need one BUF_PUSH. */
2243 BUF_PUSH (*p == '^' ? charset_not : charset);
2247 /* Remember the first position in the bracket expression. */
2250 /* Push the number of bytes in the bitmap. */
2251 BUF_PUSH ((1 << BYTEWIDTH) / BYTEWIDTH);
2253 /* Clear the whole map. */
2254 bzero (b, (1 << BYTEWIDTH) / BYTEWIDTH);
2256 /* charset_not matches newline according to a syntax bit. */
2257 if ((re_opcode_t) b[-2] == charset_not
2258 && (syntax & RE_HAT_LISTS_NOT_NEWLINE))
2259 SET_LIST_BIT ('\n');
2261 /* Read in characters and ranges, setting map bits. */
2265 boolean escaped_char = false;
2267 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2271 /* \ might escape characters inside [...] and [^...]. */
2272 if ((syntax & RE_BACKSLASH_ESCAPE_IN_LISTS) && c == '\\')
2274 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2277 escaped_char = true;
2281 /* Could be the end of the bracket expression. If it's
2282 not (i.e., when the bracket expression is `[]' so
2283 far), the ']' character bit gets set way below. */
2284 if (c == ']' && p != p1 + 1)
2288 /* If C indicates start of multibyte char, get the
2289 actual character code in C, and set the pattern
2290 pointer P to the next character boundary. */
2291 if (bufp->multibyte && BASE_LEADING_CODE_P (c))
2294 c = STRING_CHAR_AND_LENGTH (p, pend - p, len);
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 else if (!escaped_char &&
2305 syntax & RE_CHAR_CLASSES && c == '[' && *p == ':')
2307 /* Leave room for the null. */
2308 char str[CHAR_CLASS_MAX_LENGTH + 1];
2313 /* If pattern is `[[:'. */
2314 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2319 if (c == ':' || c == ']' || p == pend
2320 || c1 == CHAR_CLASS_MAX_LENGTH)
2326 /* If isn't a word bracketed by `[:' and `:]':
2327 undo the ending character, the letters, and
2328 leave the leading `:' and `[' (but set bits for
2330 if (c == ':' && *p == ']')
2333 boolean is_alnum = STREQ (str, "alnum");
2334 boolean is_alpha = STREQ (str, "alpha");
2335 boolean is_ascii = STREQ (str, "ascii");
2336 boolean is_blank = STREQ (str, "blank");
2337 boolean is_cntrl = STREQ (str, "cntrl");
2338 boolean is_digit = STREQ (str, "digit");
2339 boolean is_graph = STREQ (str, "graph");
2340 boolean is_lower = STREQ (str, "lower");
2341 boolean is_multibyte = STREQ (str, "multibyte");
2342 boolean is_nonascii = STREQ (str, "nonascii");
2343 boolean is_print = STREQ (str, "print");
2344 boolean is_punct = STREQ (str, "punct");
2345 boolean is_space = STREQ (str, "space");
2346 boolean is_unibyte = STREQ (str, "unibyte");
2347 boolean is_upper = STREQ (str, "upper");
2348 boolean is_word = STREQ (str, "word");
2349 boolean is_xdigit = STREQ (str, "xdigit");
2351 if (!IS_CHAR_CLASS (str))
2352 FREE_STACK_RETURN (REG_ECTYPE);
2354 /* Throw away the ] at the end of the character
2358 if (p == pend) FREE_STACK_RETURN (REG_EBRACK);
2360 /* Most character classes in a multibyte match
2361 just set a flag. Exceptions are is_blank,
2362 is_digit, is_cntrl, and is_xdigit, since
2363 they can only match ASCII characters. We
2364 don't need to handle them for multibyte. */
2366 if (bufp->multibyte)
2370 if (is_alnum) bit = BIT_ALNUM;
2371 if (is_alpha) bit = BIT_ALPHA;
2372 if (is_ascii) bit = BIT_ASCII;
2373 if (is_graph) bit = BIT_GRAPH;
2374 if (is_lower) bit = BIT_LOWER;
2375 if (is_multibyte) bit = BIT_MULTIBYTE;
2376 if (is_nonascii) bit = BIT_NONASCII;
2377 if (is_print) bit = BIT_PRINT;
2378 if (is_punct) bit = BIT_PUNCT;
2379 if (is_space) bit = BIT_SPACE;
2380 if (is_unibyte) bit = BIT_UNIBYTE;
2381 if (is_upper) bit = BIT_UPPER;
2382 if (is_word) bit = BIT_WORD;
2384 SET_RANGE_TABLE_WORK_AREA_BIT (range_table_work,
2388 /* Handle character classes for ASCII characters. */
2389 for (ch = 0; ch < 1 << BYTEWIDTH; ch++)
2391 int translated = TRANSLATE (ch);
2392 /* This was split into 3 if's to
2393 avoid an arbitrary limit in some compiler. */
2394 if ( (is_alnum && ISALNUM (ch))
2395 || (is_alpha && ISALPHA (ch))
2396 || (is_blank && ISBLANK (ch))
2397 || (is_cntrl && ISCNTRL (ch)))
2398 SET_LIST_BIT (translated);
2399 if ( (is_digit && ISDIGIT (ch))
2400 || (is_graph && ISGRAPH (ch))
2401 || (is_lower && ISLOWER (ch))
2402 || (is_print && ISPRINT (ch)))
2403 SET_LIST_BIT (translated);
2404 if ( (is_punct && ISPUNCT (ch))
2405 || (is_space && ISSPACE (ch))
2406 || (is_upper && ISUPPER (ch))
2407 || (is_xdigit && ISXDIGIT (ch)))
2408 SET_LIST_BIT (translated);
2409 if ( (is_ascii && IS_REAL_ASCII (ch))
2410 || (is_nonascii && !IS_REAL_ASCII (ch))
2411 || (is_unibyte && ISUNIBYTE (ch))
2412 || (is_multibyte && !ISUNIBYTE (ch)))
2413 SET_LIST_BIT (translated);
2415 if ( (is_word && ISWORD (ch)))
2416 SET_LIST_BIT (translated);
2419 /* Repeat the loop. */
2429 /* Because the `:' may starts the range, we
2430 can't simply set bit and repeat the loop.
2431 Instead, just set it to C and handle below. */
2436 if (p < pend && p[0] == '-' && p[1] != ']')
2439 /* Discard the `-'. */
2442 /* Fetch the character which ends the range. */
2444 if (bufp->multibyte && BASE_LEADING_CODE_P (c1))
2447 c1 = STRING_CHAR_AND_LENGTH (p, pend - p, len);
2451 if (SINGLE_BYTE_CHAR_P (c)
2452 && ! SINGLE_BYTE_CHAR_P (c1))
2454 /* Handle a range such as \177-\377 in multibyte mode.
2455 Split that into two ranges,,
2456 the low one ending at 0237, and the high one
2457 starting at ...040. */
2458 /* Unless I'm missing something,
2459 this line is useless. -sm
2460 int c1_base = (c1 & ~0177) | 040; */
2461 SET_RANGE_TABLE_WORK_AREA (range_table_work, c, c1);
2464 else if (!SAME_CHARSET_P (c, c1))
2465 FREE_STACK_RETURN (REG_ERANGE);
2468 /* Range from C to C. */
2471 /* Set the range ... */
2472 if (SINGLE_BYTE_CHAR_P (c))
2473 /* ... into bitmap. */
2476 int range_start = c, range_end = c1;
2478 /* If the start is after the end, the range is empty. */
2479 if (range_start > range_end)
2481 if (syntax & RE_NO_EMPTY_RANGES)
2482 FREE_STACK_RETURN (REG_ERANGE);
2483 /* Else, repeat the loop. */
2487 for (this_char = range_start; this_char <= range_end;
2489 SET_LIST_BIT (TRANSLATE (this_char));
2493 /* ... into range table. */
2494 SET_RANGE_TABLE_WORK_AREA (range_table_work, c, c1);
2497 /* Discard any (non)matching list bytes that are all 0 at the
2498 end of the map. Decrease the map-length byte too. */
2499 while ((int) b[-1] > 0 && b[b[-1] - 1] == 0)
2503 /* Build real range table from work area. */
2504 if (RANGE_TABLE_WORK_USED (range_table_work)
2505 || RANGE_TABLE_WORK_BITS (range_table_work))
2508 int used = RANGE_TABLE_WORK_USED (range_table_work);
2510 /* Allocate space for COUNT + RANGE_TABLE. Needs two
2511 bytes for flags, two for COUNT, and three bytes for
2513 GET_BUFFER_SPACE (4 + used * 3);
2515 /* Indicate the existence of range table. */
2516 laststart[1] |= 0x80;
2518 /* Store the character class flag bits into the range table.
2519 If not in emacs, these flag bits are always 0. */
2520 *b++ = RANGE_TABLE_WORK_BITS (range_table_work) & 0xff;
2521 *b++ = RANGE_TABLE_WORK_BITS (range_table_work) >> 8;
2523 STORE_NUMBER_AND_INCR (b, used / 2);
2524 for (i = 0; i < used; i++)
2525 STORE_CHARACTER_AND_INCR
2526 (b, RANGE_TABLE_WORK_ELT (range_table_work, i));
2533 if (syntax & RE_NO_BK_PARENS)
2540 if (syntax & RE_NO_BK_PARENS)
2547 if (syntax & RE_NEWLINE_ALT)
2554 if (syntax & RE_NO_BK_VBAR)
2561 if (syntax & RE_INTERVALS && syntax & RE_NO_BK_BRACES)
2562 goto handle_interval;
2568 if (p == pend) FREE_STACK_RETURN (REG_EESCAPE);
2570 /* Do not translate the character after the \, so that we can
2571 distinguish, e.g., \B from \b, even if we normally would
2572 translate, e.g., B to b. */
2578 if (syntax & RE_NO_BK_PARENS)
2579 goto normal_backslash;
2586 /* Look for a special (?...) construct */
2588 if ((syntax & RE_SHY_GROUPS) && c == '?')
2593 case ':': shy = 1; break;
2595 /* Only (?:...) is supported right now. */
2596 FREE_STACK_RETURN (REG_BADPAT);
2608 if (COMPILE_STACK_FULL)
2610 RETALLOC (compile_stack.stack, compile_stack.size << 1,
2611 compile_stack_elt_t);
2612 if (compile_stack.stack == NULL) return REG_ESPACE;
2614 compile_stack.size <<= 1;
2617 /* These are the values to restore when we hit end of this
2618 group. They are all relative offsets, so that if the
2619 whole pattern moves because of realloc, they will still
2621 COMPILE_STACK_TOP.begalt_offset = begalt - bufp->buffer;
2622 COMPILE_STACK_TOP.fixup_alt_jump
2623 = fixup_alt_jump ? fixup_alt_jump - bufp->buffer + 1 : 0;
2624 COMPILE_STACK_TOP.laststart_offset = b - bufp->buffer;
2625 COMPILE_STACK_TOP.regnum = shy ? -regnum : regnum;
2628 start_memory for groups beyond the last one we can
2629 represent in the compiled pattern. */
2630 if (regnum <= MAX_REGNUM && !shy)
2631 BUF_PUSH_2 (start_memory, regnum);
2633 compile_stack.avail++;
2638 /* If we've reached MAX_REGNUM groups, then this open
2639 won't actually generate any code, so we'll have to
2640 clear pending_exact explicitly. */
2646 if (syntax & RE_NO_BK_PARENS) goto normal_backslash;
2648 if (COMPILE_STACK_EMPTY)
2650 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
2651 goto normal_backslash;
2653 FREE_STACK_RETURN (REG_ERPAREN);
2659 /* See similar code for backslashed left paren above. */
2660 if (COMPILE_STACK_EMPTY)
2662 if (syntax & RE_UNMATCHED_RIGHT_PAREN_ORD)
2665 FREE_STACK_RETURN (REG_ERPAREN);
2668 /* Since we just checked for an empty stack above, this
2669 ``can't happen''. */
2670 assert (compile_stack.avail != 0);
2672 /* We don't just want to restore into `regnum', because
2673 later groups should continue to be numbered higher,
2674 as in `(ab)c(de)' -- the second group is #2. */
2675 regnum_t this_group_regnum;
2677 compile_stack.avail--;
2678 begalt = bufp->buffer + COMPILE_STACK_TOP.begalt_offset;
2680 = COMPILE_STACK_TOP.fixup_alt_jump
2681 ? bufp->buffer + COMPILE_STACK_TOP.fixup_alt_jump - 1
2683 laststart = bufp->buffer + COMPILE_STACK_TOP.laststart_offset;
2684 this_group_regnum = COMPILE_STACK_TOP.regnum;
2685 /* If we've reached MAX_REGNUM groups, then this open
2686 won't actually generate any code, so we'll have to
2687 clear pending_exact explicitly. */
2690 /* We're at the end of the group, so now we know how many
2691 groups were inside this one. */
2692 if (this_group_regnum <= MAX_REGNUM && this_group_regnum > 0)
2693 BUF_PUSH_2 (stop_memory, this_group_regnum);
2698 case '|': /* `\|'. */
2699 if (syntax & RE_LIMITED_OPS || syntax & RE_NO_BK_VBAR)
2700 goto normal_backslash;
2702 if (syntax & RE_LIMITED_OPS)
2705 /* Insert before the previous alternative a jump which
2706 jumps to this alternative if the former fails. */
2707 GET_BUFFER_SPACE (3);
2708 INSERT_JUMP (on_failure_jump, begalt, b + 6);
2712 /* The alternative before this one has a jump after it
2713 which gets executed if it gets matched. Adjust that
2714 jump so it will jump to this alternative's analogous
2715 jump (put in below, which in turn will jump to the next
2716 (if any) alternative's such jump, etc.). The last such
2717 jump jumps to the correct final destination. A picture:
2723 If we are at `b', then fixup_alt_jump right now points to a
2724 three-byte space after `a'. We'll put in the jump, set
2725 fixup_alt_jump to right after `b', and leave behind three
2726 bytes which we'll fill in when we get to after `c'. */
2730 /* Mark and leave space for a jump after this alternative,
2731 to be filled in later either by next alternative or
2732 when know we're at the end of a series of alternatives. */
2734 GET_BUFFER_SPACE (3);
2743 /* If \{ is a literal. */
2744 if (!(syntax & RE_INTERVALS)
2745 /* If we're at `\{' and it's not the open-interval
2747 || ((syntax & RE_INTERVALS) && (syntax & RE_NO_BK_BRACES))
2748 || (p - 2 == pattern && p == pend))
2749 goto normal_backslash;
2753 /* If got here, then the syntax allows intervals. */
2755 /* At least (most) this many matches must be made. */
2756 int lower_bound = 0, upper_bound = -1;
2758 beg_interval = p - 1;
2762 if (syntax & RE_NO_BK_BRACES)
2763 goto unfetch_interval;
2765 FREE_STACK_RETURN (REG_EBRACE);
2768 GET_UNSIGNED_NUMBER (lower_bound);
2772 GET_UNSIGNED_NUMBER (upper_bound);
2773 if (upper_bound < 0) upper_bound = RE_DUP_MAX;
2776 /* Interval such as `{1}' => match exactly once. */
2777 upper_bound = lower_bound;
2779 if (lower_bound < 0 || upper_bound > RE_DUP_MAX
2780 || lower_bound > upper_bound)
2782 if (syntax & RE_NO_BK_BRACES)
2783 goto unfetch_interval;
2785 FREE_STACK_RETURN (REG_BADBR);
2788 if (!(syntax & RE_NO_BK_BRACES))
2790 if (c != '\\') FREE_STACK_RETURN (REG_EBRACE);
2797 if (syntax & RE_NO_BK_BRACES)
2798 goto unfetch_interval;
2800 FREE_STACK_RETURN (REG_BADBR);
2803 /* We just parsed a valid interval. */
2805 /* If it's invalid to have no preceding re. */
2808 if (syntax & RE_CONTEXT_INVALID_OPS)
2809 FREE_STACK_RETURN (REG_BADRPT);
2810 else if (syntax & RE_CONTEXT_INDEP_OPS)
2813 goto unfetch_interval;
2816 /* If the upper bound is zero, don't want to succeed at
2817 all; jump from `laststart' to `b + 3', which will be
2818 the end of the buffer after we insert the jump. */
2819 if (upper_bound == 0)
2821 GET_BUFFER_SPACE (3);
2822 INSERT_JUMP (jump, laststart, b + 3);
2826 /* Otherwise, we have a nontrivial interval. When
2827 we're all done, the pattern will look like:
2828 set_number_at <jump count> <upper bound>
2829 set_number_at <succeed_n count> <lower bound>
2830 succeed_n <after jump addr> <succeed_n count>
2832 jump_n <succeed_n addr> <jump count>
2833 (The upper bound and `jump_n' are omitted if
2834 `upper_bound' is 1, though.) */
2836 { /* If the upper bound is > 1, we need to insert
2837 more at the end of the loop. */
2838 unsigned nbytes = 10 + (upper_bound > 1) * 10;
2840 GET_BUFFER_SPACE (nbytes);
2842 /* Initialize lower bound of the `succeed_n', even
2843 though it will be set during matching by its
2844 attendant `set_number_at' (inserted next),
2845 because `re_compile_fastmap' needs to know.
2846 Jump to the `jump_n' we might insert below. */
2847 INSERT_JUMP2 (succeed_n, laststart,
2848 b + 5 + (upper_bound > 1) * 5,
2852 /* Code to initialize the lower bound. Insert
2853 before the `succeed_n'. The `5' is the last two
2854 bytes of this `set_number_at', plus 3 bytes of
2855 the following `succeed_n'. */
2856 insert_op2 (set_number_at, laststart, 5, lower_bound, b);
2859 if (upper_bound > 1)
2860 { /* More than one repetition is allowed, so
2861 append a backward jump to the `succeed_n'
2862 that starts this interval.
2864 When we've reached this during matching,
2865 we'll have matched the interval once, so
2866 jump back only `upper_bound - 1' times. */
2867 STORE_JUMP2 (jump_n, b, laststart + 5,
2871 /* The location we want to set is the second
2872 parameter of the `jump_n'; that is `b-2' as
2873 an absolute address. `laststart' will be
2874 the `set_number_at' we're about to insert;
2875 `laststart+3' the number to set, the source
2876 for the relative address. But we are
2877 inserting into the middle of the pattern --
2878 so everything is getting moved up by 5.
2879 Conclusion: (b - 2) - (laststart + 3) + 5,
2880 i.e., b - laststart.
2882 We insert this at the beginning of the loop
2883 so that if we fail during matching, we'll
2884 reinitialize the bounds. */
2885 insert_op2 (set_number_at, laststart, b - laststart,
2886 upper_bound - 1, b);
2891 beg_interval = NULL;
2896 /* If an invalid interval, match the characters as literals. */
2897 assert (beg_interval);
2899 beg_interval = NULL;
2901 /* normal_char and normal_backslash need `c'. */
2904 if (!(syntax & RE_NO_BK_BRACES))
2906 if (p > pattern && p[-1] == '\\')
2907 goto normal_backslash;
2912 /* There is no way to specify the before_dot and after_dot
2913 operators. rms says this is ok. --karl */
2921 BUF_PUSH_2 (syntaxspec, syntax_spec_code[c]);
2927 BUF_PUSH_2 (notsyntaxspec, syntax_spec_code[c]);
2933 BUF_PUSH_2 (categoryspec, c);
2939 BUF_PUSH_2 (notcategoryspec, c);
2946 BUF_PUSH_2 (syntaxspec, Sword);
2952 BUF_PUSH_2 (notsyntaxspec, Sword);
2965 BUF_PUSH (wordbound);
2969 BUF_PUSH (notwordbound);
2980 case '1': case '2': case '3': case '4': case '5':
2981 case '6': case '7': case '8': case '9':
2982 if (syntax & RE_NO_BK_REFS)
2988 FREE_STACK_RETURN (REG_ESUBREG);
2990 /* Can't back reference to a subexpression if inside of it. */
2991 if (group_in_compile_stack (compile_stack, c1))
2995 BUF_PUSH_2 (duplicate, c1);
3001 if (syntax & RE_BK_PLUS_QM)
3004 goto normal_backslash;
3008 /* You might think it would be useful for \ to mean
3009 not to translate; but if we don't translate it
3010 it will never match anything. */
3018 /* Expects the character in `c'. */
3020 p1 = p - 1; /* P1 points the head of C. */
3022 if (bufp->multibyte)
3024 c = STRING_CHAR (p1, pend - p1);
3026 /* Set P to the next character boundary. */
3027 p += MULTIBYTE_FORM_LENGTH (p1, pend - p1) - 1;
3030 /* If no exactn currently being built. */
3033 /* If last exactn not at current position. */
3034 || pending_exact + *pending_exact + 1 != b
3036 /* We have only one byte following the exactn for the count. */
3037 || *pending_exact >= (1 << BYTEWIDTH) - (p - p1)
3039 /* If followed by a repetition operator. */
3040 || (p != pend && (*p == '*' || *p == '^'))
3041 || ((syntax & RE_BK_PLUS_QM)
3042 ? p + 1 < pend && *p == '\\' && (p[1] == '+' || p[1] == '?')
3043 : p != pend && (*p == '+' || *p == '?'))
3044 || ((syntax & RE_INTERVALS)
3045 && ((syntax & RE_NO_BK_BRACES)
3046 ? p != pend && *p == '{'
3047 : p + 1 < pend && p[0] == '\\' && p[1] == '{')))
3049 /* Start building a new exactn. */
3053 BUF_PUSH_2 (exactn, 0);
3054 pending_exact = b - 1;
3058 if (! SINGLE_BYTE_CHAR_P (c))
3060 unsigned char str[MAX_MULTIBYTE_LENGTH];
3061 int i = CHAR_STRING (c, str);
3063 for (j = 0; j < i; j++)
3077 } /* while p != pend */
3080 /* Through the pattern now. */
3084 if (!COMPILE_STACK_EMPTY)
3085 FREE_STACK_RETURN (REG_EPAREN);
3087 /* If we don't want backtracking, force success
3088 the first time we reach the end of the compiled pattern. */
3089 if (syntax & RE_NO_POSIX_BACKTRACKING)
3092 free (compile_stack.stack);
3094 /* We have succeeded; set the length of the buffer. */
3095 bufp->used = b - bufp->buffer;
3100 re_compile_fastmap (bufp);
3101 DEBUG_PRINT1 ("\nCompiled pattern: \n");
3102 print_compiled_pattern (bufp);
3107 #ifndef MATCH_MAY_ALLOCATE
3108 /* Initialize the failure stack to the largest possible stack. This
3109 isn't necessary unless we're trying to avoid calling alloca in
3110 the search and match routines. */
3112 int num_regs = bufp->re_nsub + 1;
3114 if (fail_stack.size < re_max_failures * TYPICAL_FAILURE_SIZE)
3116 fail_stack.size = re_max_failures * TYPICAL_FAILURE_SIZE;
3118 if (! fail_stack.stack)
3120 = (fail_stack_elt_t *) malloc (fail_stack.size
3121 * sizeof (fail_stack_elt_t));
3124 = (fail_stack_elt_t *) realloc (fail_stack.stack,
3126 * sizeof (fail_stack_elt_t)));
3129 regex_grow_registers (num_regs);
3131 #endif /* not MATCH_MAY_ALLOCATE */
3134 } /* regex_compile */
3136 /* Subroutines for `regex_compile'. */
3138 /* Store OP at LOC followed by two-byte integer parameter ARG. */
3141 store_op1 (op, loc, arg)
3146 *loc = (unsigned char) op;
3147 STORE_NUMBER (loc + 1, arg);
3151 /* Like `store_op1', but for two two-byte parameters ARG1 and ARG2. */
3154 store_op2 (op, loc, arg1, arg2)
3159 *loc = (unsigned char) op;
3160 STORE_NUMBER (loc + 1, arg1);
3161 STORE_NUMBER (loc + 3, arg2);
3165 /* Copy the bytes from LOC to END to open up three bytes of space at LOC
3166 for OP followed by two-byte integer parameter ARG. */
3169 insert_op1 (op, loc, arg, end)
3175 register unsigned char *pfrom = end;
3176 register unsigned char *pto = end + 3;
3178 while (pfrom != loc)
3181 store_op1 (op, loc, arg);
3185 /* Like `insert_op1', but for two two-byte parameters ARG1 and ARG2. */
3188 insert_op2 (op, loc, arg1, arg2, end)
3194 register unsigned char *pfrom = end;
3195 register unsigned char *pto = end + 5;
3197 while (pfrom != loc)
3200 store_op2 (op, loc, arg1, arg2);
3204 /* P points to just after a ^ in PATTERN. Return true if that ^ comes
3205 after an alternative or a begin-subexpression. We assume there is at
3206 least one character before the ^. */
3209 at_begline_loc_p (pattern, p, syntax)
3210 const unsigned char *pattern, *p;
3211 reg_syntax_t syntax;
3213 const unsigned char *prev = p - 2;
3214 boolean prev_prev_backslash = prev > pattern && prev[-1] == '\\';
3217 /* After a subexpression? */
3218 (*prev == '(' && (syntax & RE_NO_BK_PARENS || prev_prev_backslash))
3219 /* After an alternative? */
3220 || (*prev == '|' && (syntax & RE_NO_BK_VBAR || prev_prev_backslash));
3224 /* The dual of at_begline_loc_p. This one is for $. We assume there is
3225 at least one character after the $, i.e., `P < PEND'. */
3228 at_endline_loc_p (p, pend, syntax)
3229 const unsigned char *p, *pend;
3230 reg_syntax_t syntax;
3232 const unsigned char *next = p;
3233 boolean next_backslash = *next == '\\';
3234 const unsigned char *next_next = p + 1 < pend ? p + 1 : 0;
3237 /* Before a subexpression? */
3238 (syntax & RE_NO_BK_PARENS ? *next == ')'
3239 : next_backslash && next_next && *next_next == ')')
3240 /* Before an alternative? */
3241 || (syntax & RE_NO_BK_VBAR ? *next == '|'
3242 : next_backslash && next_next && *next_next == '|');
3246 /* Returns true if REGNUM is in one of COMPILE_STACK's elements and
3247 false if it's not. */
3250 group_in_compile_stack (compile_stack, regnum)
3251 compile_stack_type compile_stack;
3256 for (this_element = compile_stack.avail - 1;
3259 if (compile_stack.stack[this_element].regnum == regnum)
3265 /* re_compile_fastmap computes a ``fastmap'' for the compiled pattern in
3266 BUFP. A fastmap records which of the (1 << BYTEWIDTH) possible
3267 characters can start a string that matches the pattern. This fastmap
3268 is used by re_search to skip quickly over impossible starting points.
3270 Character codes above (1 << BYTEWIDTH) are not represented in the
3271 fastmap, but the leading codes are represented. Thus, the fastmap
3272 indicates which character sets could start a match.
3274 The caller must supply the address of a (1 << BYTEWIDTH)-byte data
3275 area as BUFP->fastmap.
3277 We set the `fastmap', `fastmap_accurate', and `can_be_null' fields in
3280 Returns 0 if we succeed, -2 if an internal error. */
3283 re_compile_fastmap (bufp)
3284 struct re_pattern_buffer *bufp;
3288 #ifdef MATCH_MAY_ALLOCATE
3289 fail_stack_type fail_stack;
3291 #ifndef REGEX_MALLOC
3295 register char *fastmap = bufp->fastmap;
3296 unsigned char *pattern = bufp->buffer;
3297 unsigned long size = bufp->used;
3298 unsigned char *p = pattern;
3299 register unsigned char *pend = pattern + size;
3300 const boolean multibyte = bufp->multibyte;
3302 #if defined (REL_ALLOC) && defined (REGEX_MALLOC)
3303 /* This holds the pointer to the failure stack, when
3304 it is allocated relocatably. */
3305 fail_stack_elt_t *failure_stack_ptr;
3308 /* Assume that each path through the pattern can be null until
3309 proven otherwise. We set this false at the bottom of switch
3310 statement, to which we get only if a particular path doesn't
3311 match the empty string. */
3312 boolean path_can_be_null = true;
3314 /* We aren't doing a `succeed_n' to begin with. */
3315 boolean succeed_n_p = false;
3317 /* If all elements for base leading-codes in fastmap is set, this
3318 flag is set true. */
3319 boolean match_any_multibyte_characters = false;
3321 assert (fastmap != NULL && p != NULL);
3324 bzero (fastmap, 1 << BYTEWIDTH); /* Assume nothing's valid. */
3325 bufp->fastmap_accurate = 1; /* It will be when we're done. */
3326 bufp->can_be_null = 0;
3328 /* The loop below works as follows:
3329 - It has a working-list kept in the PATTERN_STACK and which basically
3330 starts by only containing a pointer to the first operation.
3331 - If the opcode we're looking at is a match against some set of
3332 chars, then we add those chars to the fastmap and go on to the
3333 next work element from the worklist (done via `break').
3334 - If the opcode is a control operator on the other hand, we either
3335 ignore it (if it's meaningless at this point, such as `start_memory')
3336 or execute it (if it's a jump). If the jump has several destinations
3337 (i.e. `on_failure_jump'), then we push the other destination onto the
3339 We guarantee termination by ignoring backward jumps (more or less),
3340 so that `p' is monotonically increasing. More to the point, we
3341 never set `p' (or push) anything `<= p1'. */
3343 /* If can_be_null is set, then the fastmap will not be used anyway. */
3344 while (!bufp->can_be_null)
3346 /* `p1' is used as a marker of how far back a `on_failure_jump'
3347 can go without being ignored. It is normally equal to `p'
3348 (which prevents any backward `on_failure_jump') except right
3349 after a plain `jump', to allow patterns such as:
3352 10: on_failure_jump 3
3353 as used for the *? operator. */
3354 unsigned char *p1 = p;
3356 if (p == pend || *p == succeed)
3358 /* We have reached the (effective) end of pattern. */
3359 if (!PATTERN_STACK_EMPTY ())
3361 bufp->can_be_null |= path_can_be_null;
3363 /* Reset for next path. */
3364 path_can_be_null = true;
3366 p = (unsigned char*) POP_PATTERN_OP ();
3374 /* We should never be about to go beyond the end of the pattern. */
3377 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
3381 /* If the first character has to match a backreference, that means
3382 that the group was empty (since it already matched). Since this
3383 is the only case that interests us here, we can assume that the
3384 backreference must match the empty string. */
3389 /* Following are the cases which match a character. These end
3398 /* We could put all the chars except for \n (and maybe \0)
3399 but we don't bother since it is generally not worth it. */
3400 bufp->can_be_null = 1;
3405 /* Chars beyond end of bitmap are possible matches.
3406 All the single-byte codes can occur in multibyte buffers.
3407 So any that are not listed in the charset
3408 are possible matches, even in multibyte buffers. */
3409 if (!fastmap) break;
3410 for (j = CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH;
3411 j < (1 << BYTEWIDTH); j++)
3415 if (!fastmap) break;
3416 not = (re_opcode_t) *(p - 1) == charset_not;
3417 for (j = CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH - 1, p++;
3419 if (!!(p[j / BYTEWIDTH] & (1 << (j % BYTEWIDTH))) ^ not)
3422 if ((not && multibyte)
3423 /* Any character set can possibly contain a character
3424 which doesn't match the specified set of characters. */
3425 || (CHARSET_RANGE_TABLE_EXISTS_P (&p[-2])
3426 && CHARSET_RANGE_TABLE_BITS (&p[-2]) != 0))
3427 /* If we can match a character class, we can match
3428 any character set. */
3430 set_fastmap_for_multibyte_characters:
3431 if (match_any_multibyte_characters == false)
3433 for (j = 0x80; j < 0xA0; j++) /* XXX */
3434 if (BASE_LEADING_CODE_P (j))
3436 match_any_multibyte_characters = true;
3440 else if (!not && CHARSET_RANGE_TABLE_EXISTS_P (&p[-2])
3441 && match_any_multibyte_characters == false)
3443 /* Set fastmap[I] 1 where I is a base leading code of each
3444 multibyte character in the range table. */
3447 /* Make P points the range table. `+ 2' is to skip flag
3448 bits for a character class. */
3449 p += CHARSET_BITMAP_SIZE (&p[-2]) + 2;
3451 /* Extract the number of ranges in range table into COUNT. */
3452 EXTRACT_NUMBER_AND_INCR (count, p);
3453 for (; count > 0; count--, p += 2 * 3) /* XXX */
3455 /* Extract the start of each range. */
3456 EXTRACT_CHARACTER (c, p);
3457 j = CHAR_CHARSET (c);
3458 fastmap[CHARSET_LEADING_CODE_BASE (j)] = 1;
3465 if (!fastmap) break;
3467 not = (re_opcode_t)p[-1] == notsyntaxspec;
3469 for (j = 0; j < (1 << BYTEWIDTH); j++)
3470 if ((SYNTAX (j) == (enum syntaxcode) k) ^ not)
3474 /* This match depends on text properties. These end with
3475 aborting optimizations. */
3476 bufp->can_be_null = 1;
3480 case notcategoryspec:
3481 if (!fastmap) break;
3482 not = (re_opcode_t)p[-1] == notcategoryspec;
3484 for (j = 0; j < (1 << BYTEWIDTH); j++)
3485 if ((CHAR_HAS_CATEGORY (j, k)) ^ not)
3489 /* Any character set can possibly contain a character
3490 whose category is K (or not). */
3491 goto set_fastmap_for_multibyte_characters;
3494 /* All cases after this match the empty string. These end with
3515 EXTRACT_NUMBER_AND_INCR (j, p);
3517 /* Backward jumps can only go back to code that we've already
3518 visited. `re_compile' should make sure this is true. */
3521 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p))
3523 case on_failure_jump:
3524 case on_failure_keep_string_jump:
3525 case on_failure_jump_loop:
3526 case on_failure_jump_nastyloop:
3527 case on_failure_jump_smart:
3533 /* Keep `p1' to allow the `on_failure_jump' we are jumping to
3534 to jump back to "just after here". */
3537 case on_failure_jump:
3538 case on_failure_keep_string_jump:
3539 case on_failure_jump_nastyloop:
3540 case on_failure_jump_loop:
3541 case on_failure_jump_smart:
3542 handle_on_failure_jump:
3543 EXTRACT_NUMBER_AND_INCR (j, p);
3545 /* For some patterns, e.g., `(a?)?', `p+j' here points to the
3546 end of the pattern. We don't want to push such a point,
3547 since when we restore it above, entering the switch will
3548 increment `p' past the end of the pattern. We don't need
3549 to push such a point since we obviously won't find any more
3550 fastmap entries beyond `pend'. Such a pattern can match
3551 the null string, though. */
3553 /* Backward jump to be ignored. */
3555 else if (p + j < pend)
3557 if (!PUSH_PATTERN_OP (p + j, fail_stack))
3559 RESET_FAIL_STACK ();
3564 bufp->can_be_null = 1;
3568 EXTRACT_NUMBER_AND_INCR (k, p); /* Skip the n. */
3569 succeed_n_p = false;
3576 /* Get to the number of times to succeed. */
3579 /* Increment p past the n for when k != 0. */
3580 EXTRACT_NUMBER_AND_INCR (k, p);
3584 succeed_n_p = true; /* Spaghetti code alert. */
3585 goto handle_on_failure_jump;
3602 abort (); /* We have listed all the cases. */
3605 /* Getting here means we have found the possible starting
3606 characters for one path of the pattern -- and that the empty
3607 string does not match. We need not follow this path further.
3608 Instead, look at the next alternative (remembered on the
3609 stack), or quit if no more. The test at the top of the loop
3610 does these things. */
3611 path_can_be_null = false;
3615 /* Set `can_be_null' for the last path (also the first path, if the
3616 pattern is empty). */
3617 bufp->can_be_null |= path_can_be_null;
3618 RESET_FAIL_STACK ();
3620 } /* re_compile_fastmap */
3622 /* Set REGS to hold NUM_REGS registers, storing them in STARTS and
3623 ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
3624 this memory for recording register information. STARTS and ENDS
3625 must be allocated using the malloc library routine, and must each
3626 be at least NUM_REGS * sizeof (regoff_t) bytes long.
3628 If NUM_REGS == 0, then subsequent matches should allocate their own
3631 Unless this function is called, the first search or match using
3632 PATTERN_BUFFER will allocate its own register data, without
3633 freeing the old data. */
3636 re_set_registers (bufp, regs, num_regs, starts, ends)
3637 struct re_pattern_buffer *bufp;
3638 struct re_registers *regs;
3640 regoff_t *starts, *ends;
3644 bufp->regs_allocated = REGS_REALLOCATE;
3645 regs->num_regs = num_regs;
3646 regs->start = starts;
3651 bufp->regs_allocated = REGS_UNALLOCATED;
3653 regs->start = regs->end = (regoff_t *) 0;
3657 /* Searching routines. */
3659 /* Like re_search_2, below, but only one string is specified, and
3660 doesn't let you say where to stop matching. */
3663 re_search (bufp, string, size, startpos, range, regs)
3664 struct re_pattern_buffer *bufp;
3666 int size, startpos, range;
3667 struct re_registers *regs;
3669 return re_search_2 (bufp, NULL, 0, string, size, startpos, range,
3673 /* End address of virtual concatenation of string. */
3674 #define STOP_ADDR_VSTRING(P) \
3675 (((P) >= size1 ? string2 + size2 : string1 + size1))
3677 /* Address of POS in the concatenation of virtual string. */
3678 #define POS_ADDR_VSTRING(POS) \
3679 (((POS) >= size1 ? string2 - size1 : string1) + (POS))
3681 /* Using the compiled pattern in BUFP->buffer, first tries to match the
3682 virtual concatenation of STRING1 and STRING2, starting first at index
3683 STARTPOS, then at STARTPOS + 1, and so on.
3685 STRING1 and STRING2 have length SIZE1 and SIZE2, respectively.
3687 RANGE is how far to scan while trying to match. RANGE = 0 means try
3688 only at STARTPOS; in general, the last start tried is STARTPOS +
3691 In REGS, return the indices of the virtual concatenation of STRING1
3692 and STRING2 that matched the entire BUFP->buffer and its contained
3695 Do not consider matching one past the index STOP in the virtual
3696 concatenation of STRING1 and STRING2.
3698 We return either the position in the strings at which the match was
3699 found, -1 if no match, or -2 if error (such as failure
3703 re_search_2 (bufp, str1, size1, str2, size2, startpos, range, regs, stop)
3704 struct re_pattern_buffer *bufp;
3705 const char *str1, *str2;
3709 struct re_registers *regs;
3713 re_char *string1 = (re_char*) str1;
3714 re_char *string2 = (re_char*) str2;
3715 register char *fastmap = bufp->fastmap;
3716 register RE_TRANSLATE_TYPE translate = bufp->translate;
3717 int total_size = size1 + size2;
3718 int endpos = startpos + range;
3719 int anchored_start = 0;
3721 /* Nonzero if we have to concern multibyte character. */
3722 const boolean multibyte = bufp->multibyte;
3724 /* Check for out-of-range STARTPOS. */
3725 if (startpos < 0 || startpos > total_size)
3728 /* Fix up RANGE if it might eventually take us outside
3729 the virtual concatenation of STRING1 and STRING2.
3730 Make sure we won't move STARTPOS below 0 or above TOTAL_SIZE. */
3732 range = 0 - startpos;
3733 else if (endpos > total_size)
3734 range = total_size - startpos;
3736 /* If the search isn't to be a backwards one, don't waste time in a
3737 search for a pattern anchored at beginning of buffer. */
3738 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == begbuf && range > 0)
3747 /* In a forward search for something that starts with \=.
3748 don't keep searching past point. */
3749 if (bufp->used > 0 && (re_opcode_t) bufp->buffer[0] == at_dot && range > 0)
3751 range = PT_BYTE - BEGV_BYTE - startpos;
3757 /* Update the fastmap now if not correct already. */
3758 if (fastmap && !bufp->fastmap_accurate)
3759 if (re_compile_fastmap (bufp) == -2)
3762 /* See whether the pattern is anchored. */
3763 if (bufp->buffer[0] == begline)
3767 gl_state.object = re_match_object;
3769 int charpos = SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (startpos));
3771 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object, charpos, 1);
3775 /* Loop through the string, looking for a place to start matching. */
3778 /* If the pattern is anchored,
3779 skip quickly past places we cannot match.
3780 We don't bother to treat startpos == 0 specially
3781 because that case doesn't repeat. */
3782 if (anchored_start && startpos > 0)
3784 if (! (bufp->newline_anchor
3785 && ((startpos <= size1 ? string1[startpos - 1]
3786 : string2[startpos - size1 - 1])
3791 /* If a fastmap is supplied, skip quickly over characters that
3792 cannot be the start of a match. If the pattern can match the
3793 null string, however, we don't need to skip characters; we want
3794 the first null string. */
3795 if (fastmap && startpos < total_size && !bufp->can_be_null)
3797 register re_char *d;
3798 register unsigned int buf_ch;
3800 d = POS_ADDR_VSTRING (startpos);
3802 if (range > 0) /* Searching forwards. */
3804 register int lim = 0;
3807 if (startpos < size1 && startpos + range >= size1)
3808 lim = range - (size1 - startpos);
3810 /* Written out as an if-else to avoid testing `translate'
3812 if (RE_TRANSLATE_P (translate))
3819 buf_ch = STRING_CHAR_AND_LENGTH (d, range - lim,
3822 buf_ch = RE_TRANSLATE (translate, buf_ch);
3827 range -= buf_charlen;
3832 && !fastmap[RE_TRANSLATE (translate, *d)])
3839 while (range > lim && !fastmap[*d])
3845 startpos += irange - range;
3847 else /* Searching backwards. */
3849 buf_ch = STRING_CHAR (d, (startpos >= size1
3850 ? size2 + size1 - startpos
3851 : size1 - startpos));
3852 if (RE_TRANSLATE_P (translate))
3853 buf_ch = RE_TRANSLATE (translate, buf_ch);
3855 if (! (buf_ch >= 0400
3856 || fastmap[buf_ch]))
3861 /* If can't match the null string, and that's all we have left, fail. */
3862 if (range >= 0 && startpos == total_size && fastmap
3863 && !bufp->can_be_null)
3866 val = re_match_2_internal (bufp, string1, size1, string2, size2,
3867 startpos, regs, stop);
3868 #ifndef REGEX_MALLOC
3885 /* Update STARTPOS to the next character boundary. */
3888 re_char *p = POS_ADDR_VSTRING (startpos);
3889 re_char *pend = STOP_ADDR_VSTRING (startpos);
3890 int len = MULTIBYTE_FORM_LENGTH (p, pend - p);
3908 /* Update STARTPOS to the previous character boundary. */
3911 re_char *p = POS_ADDR_VSTRING (startpos);
3914 /* Find the head of multibyte form. */
3915 while (!CHAR_HEAD_P (*p))
3920 if (MULTIBYTE_FORM_LENGTH (p, len + 1) != (len + 1))
3937 /* Declarations and macros for re_match_2. */
3939 static int bcmp_translate ();
3941 /* This converts PTR, a pointer into one of the search strings `string1'
3942 and `string2' into an offset from the beginning of that string. */
3943 #define POINTER_TO_OFFSET(ptr) \
3944 (FIRST_STRING_P (ptr) \
3945 ? ((regoff_t) ((ptr) - string1)) \
3946 : ((regoff_t) ((ptr) - string2 + size1)))
3948 /* Call before fetching a character with *d. This switches over to
3949 string2 if necessary. */
3950 #define PREFETCH() \
3953 /* End of string2 => fail. */ \
3954 if (dend == end_match_2) \
3956 /* End of string1 => advance to string2. */ \
3958 dend = end_match_2; \
3962 /* Test if at very beginning or at very end of the virtual concatenation
3963 of `string1' and `string2'. If only one string, it's `string2'. */
3964 #define AT_STRINGS_BEG(d) ((d) == (size1 ? string1 : string2) || !size2)
3965 #define AT_STRINGS_END(d) ((d) == end2)
3968 /* Test if D points to a character which is word-constituent. We have
3969 two special cases to check for: if past the end of string1, look at
3970 the first character in string2; and if before the beginning of
3971 string2, look at the last character in string1. */
3972 #define WORDCHAR_P(d) \
3973 (SYNTAX ((d) == end1 ? *string2 \
3974 : (d) == string2 - 1 ? *(end1 - 1) : *(d)) \
3977 /* Disabled due to a compiler bug -- see comment at case wordbound */
3979 /* The comment at case wordbound is following one, but we don't use
3980 AT_WORD_BOUNDARY anymore to support multibyte form.
3982 The DEC Alpha C compiler 3.x generates incorrect code for the
3983 test WORDCHAR_P (d - 1) != WORDCHAR_P (d) in the expansion of
3984 AT_WORD_BOUNDARY, so this code is disabled. Expanding the
3985 macro and introducing temporary variables works around the bug. */
3988 /* Test if the character before D and the one at D differ with respect
3989 to being word-constituent. */
3990 #define AT_WORD_BOUNDARY(d) \
3991 (AT_STRINGS_BEG (d) || AT_STRINGS_END (d) \
3992 || WORDCHAR_P (d - 1) != WORDCHAR_P (d))
3995 /* Free everything we malloc. */
3996 #ifdef MATCH_MAY_ALLOCATE
3997 #define FREE_VAR(var) if (var) { REGEX_FREE (var); var = NULL; } else
3998 #define FREE_VARIABLES() \
4000 REGEX_FREE_STACK (fail_stack.stack); \
4001 FREE_VAR (regstart); \
4002 FREE_VAR (regend); \
4003 FREE_VAR (best_regstart); \
4004 FREE_VAR (best_regend); \
4007 #define FREE_VARIABLES() ((void)0) /* Do nothing! But inhibit gcc warning. */
4008 #endif /* not MATCH_MAY_ALLOCATE */
4011 /* Optimization routines. */
4013 /* If the operation is a match against one or more chars,
4014 return a pointer to the next operation, else return NULL. */
4015 static unsigned char *
4019 switch (SWITCH_ENUM_CAST (*p++))
4030 if (CHARSET_RANGE_TABLE_EXISTS_P (p - 1))
4033 p = CHARSET_RANGE_TABLE (p - 1);
4034 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4035 p = CHARSET_RANGE_TABLE_END (p, mcnt);
4038 p += 1 + CHARSET_BITMAP_SIZE (p - 1);
4045 case notcategoryspec:
4057 /* Jump over non-matching operations. */
4058 static unsigned char *
4059 skip_noops (p, pend)
4060 unsigned char *p, *pend;
4065 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p))
4074 EXTRACT_NUMBER_AND_INCR (mcnt, p);
4085 /* Non-zero if "p1 matches something" implies "p2 fails". */
4087 mutually_exclusive_p (bufp, p1, p2)
4088 struct re_pattern_buffer *bufp;
4089 unsigned char *p1, *p2;
4092 const boolean multibyte = bufp->multibyte;
4093 unsigned char *pend = bufp->buffer + bufp->used;
4095 assert (p1 >= bufp->buffer && p1 < pend
4096 && p2 >= bufp->buffer && p2 <= pend);
4098 /* Skip over open/close-group commands.
4099 If what follows this loop is a ...+ construct,
4100 look at what begins its body, since we will have to
4101 match at least one of that. */
4102 p2 = skip_noops (p2, pend);
4103 /* The same skip can be done for p1, except that this function
4104 is only used in the case where p1 is a simple match operator. */
4105 /* p1 = skip_noops (p1, pend); */
4107 assert (p1 >= bufp->buffer && p1 < pend
4108 && p2 >= bufp->buffer && p2 <= pend);
4110 op2 = p2 == pend ? succeed : *p2;
4112 switch (SWITCH_ENUM_CAST (op2))
4116 /* If we're at the end of the pattern, we can change. */
4117 if (skip_one_char (p1))
4119 DEBUG_PRINT1 (" End of pattern: fast loop.\n");
4125 if (!bufp->newline_anchor)
4130 register unsigned int c
4131 = (re_opcode_t) *p2 == endline ? '\n'
4132 : RE_STRING_CHAR(p2 + 2, pend - p2 - 2);
4134 if ((re_opcode_t) *p1 == exactn)
4136 if (c != RE_STRING_CHAR (p1 + 2, pend - p1 - 2))
4138 DEBUG_PRINT3 (" '%c' != '%c' => fast loop.\n", c, p1[2]);
4143 else if ((re_opcode_t) *p1 == charset
4144 || (re_opcode_t) *p1 == charset_not)
4146 int not = (re_opcode_t) *p1 == charset_not;
4148 /* Test if C is listed in charset (or charset_not)
4150 if (SINGLE_BYTE_CHAR_P (c))
4152 if (c < CHARSET_BITMAP_SIZE (p1) * BYTEWIDTH
4153 && p1[2 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
4156 else if (CHARSET_RANGE_TABLE_EXISTS_P (p1))
4157 CHARSET_LOOKUP_RANGE_TABLE (not, c, p1);
4159 /* `not' is equal to 1 if c would match, which means
4160 that we can't change to pop_failure_jump. */
4163 DEBUG_PRINT1 (" No match => fast loop.\n");
4167 else if ((re_opcode_t) *p1 == anychar
4170 DEBUG_PRINT1 (" . != \\n => fast loop.\n");
4179 if ((re_opcode_t) *p1 == exactn)
4180 /* Reuse the code above. */
4181 return mutually_exclusive_p (bufp, p2, p1);
4184 /* It is hard to list up all the character in charset
4185 P2 if it includes multibyte character. Give up in
4187 else if (!multibyte || !CHARSET_RANGE_TABLE_EXISTS_P (p2))
4189 /* Now, we are sure that P2 has no range table.
4190 So, for the size of bitmap in P2, `p2[1]' is
4191 enough. But P1 may have range table, so the
4192 size of bitmap table of P1 is extracted by
4193 using macro `CHARSET_BITMAP_SIZE'.
4195 Since we know that all the character listed in
4196 P2 is ASCII, it is enough to test only bitmap
4202 /* We win if the charset inside the loop
4203 has no overlap with the one after the loop. */
4206 && idx < CHARSET_BITMAP_SIZE (p1));
4208 if ((p2[2 + idx] & p1[2 + idx]) != 0)
4212 || idx == CHARSET_BITMAP_SIZE (p1))
4214 DEBUG_PRINT1 (" No match => fast loop.\n");
4218 else if ((re_opcode_t) *p1 == charset
4219 || (re_opcode_t) *p1 == charset_not)
4222 /* We win if the charset_not inside the loop lists
4223 every character listed in the charset after. */
4224 for (idx = 0; idx < (int) p2[1]; idx++)
4225 if (! (p2[2 + idx] == 0
4226 || (idx < CHARSET_BITMAP_SIZE (p1)
4227 && ((p2[2 + idx] & ~ p1[2 + idx]) == 0))))
4232 DEBUG_PRINT1 (" No match => fast loop.\n");
4241 return ((re_opcode_t) *p1 == syntaxspec
4242 && p1[1] == (op2 == wordend ? Sword : p2[1]));
4246 return ((re_opcode_t) *p1 == notsyntaxspec
4247 && p1[1] == (op2 == wordend ? Sword : p2[1]));
4250 return (((re_opcode_t) *p1 == notsyntaxspec
4251 || (re_opcode_t) *p1 == syntaxspec)
4256 return ((re_opcode_t) *p1 == notcategoryspec && p1[1] == p2[1]);
4257 case notcategoryspec:
4258 return ((re_opcode_t) *p1 == categoryspec && p1[1] == p2[1]);
4270 /* Matching routines. */
4272 #ifndef emacs /* Emacs never uses this. */
4273 /* re_match is like re_match_2 except it takes only a single string. */
4276 re_match (bufp, string, size, pos, regs)
4277 struct re_pattern_buffer *bufp;
4280 struct re_registers *regs;
4282 int result = re_match_2_internal (bufp, NULL, 0, string, size,
4287 #endif /* not emacs */
4290 /* In Emacs, this is the string or buffer in which we
4291 are matching. It is used for looking up syntax properties. */
4292 Lisp_Object re_match_object;
4295 /* re_match_2 matches the compiled pattern in BUFP against the
4296 the (virtual) concatenation of STRING1 and STRING2 (of length SIZE1
4297 and SIZE2, respectively). We start matching at POS, and stop
4300 If REGS is non-null and the `no_sub' field of BUFP is nonzero, we
4301 store offsets for the substring each group matched in REGS. See the
4302 documentation for exactly how many groups we fill.
4304 We return -1 if no match, -2 if an internal error (such as the
4305 failure stack overflowing). Otherwise, we return the length of the
4306 matched substring. */
4309 re_match_2 (bufp, string1, size1, string2, size2, pos, regs, stop)
4310 struct re_pattern_buffer *bufp;
4311 const char *string1, *string2;
4314 struct re_registers *regs;
4321 gl_state.object = re_match_object;
4322 charpos = SYNTAX_TABLE_BYTE_TO_CHAR (POS_AS_IN_BUFFER (pos));
4323 SETUP_SYNTAX_TABLE_FOR_OBJECT (re_match_object, charpos, 1);
4326 result = re_match_2_internal (bufp, string1, size1, string2, size2,
4332 /* This is a separate function so that we can force an alloca cleanup
4335 re_match_2_internal (bufp, string1, size1, string2, size2, pos, regs, stop)
4336 struct re_pattern_buffer *bufp;
4337 re_char *string1, *string2;
4340 struct re_registers *regs;
4343 /* General temporaries. */
4348 /* Just past the end of the corresponding string. */
4349 re_char *end1, *end2;
4351 /* Pointers into string1 and string2, just past the last characters in
4352 each to consider matching. */
4353 re_char *end_match_1, *end_match_2;
4355 /* Where we are in the data, and the end of the current string. */
4358 /* Used sometimes to remember where we were before starting matching
4359 an operator so that we can go back in case of failure. This "atomic"
4360 behavior of matching opcodes is indispensable to the correctness
4361 of the on_failure_keep_string_jump optimization. */
4364 /* Where we are in the pattern, and the end of the pattern. */
4365 unsigned char *p = bufp->buffer;
4366 register unsigned char *pend = p + bufp->used;
4368 /* We use this to map every character in the string. */
4369 RE_TRANSLATE_TYPE translate = bufp->translate;
4371 /* Nonzero if we have to concern multibyte character. */
4372 const boolean multibyte = bufp->multibyte;
4374 /* Failure point stack. Each place that can handle a failure further
4375 down the line pushes a failure point on this stack. It consists of
4376 regstart, and regend for all registers corresponding to
4377 the subexpressions we're currently inside, plus the number of such
4378 registers, and, finally, two char *'s. The first char * is where
4379 to resume scanning the pattern; the second one is where to resume
4380 scanning the strings. */
4381 #ifdef MATCH_MAY_ALLOCATE /* otherwise, this is global. */
4382 fail_stack_type fail_stack;
4385 static unsigned failure_id = 0;
4386 unsigned nfailure_points_pushed = 0, nfailure_points_popped = 0;
4389 #if defined (REL_ALLOC) && defined (REGEX_MALLOC)
4390 /* This holds the pointer to the failure stack, when
4391 it is allocated relocatably. */
4392 fail_stack_elt_t *failure_stack_ptr;
4395 /* We fill all the registers internally, independent of what we
4396 return, for use in backreferences. The number here includes
4397 an element for register zero. */
4398 unsigned num_regs = bufp->re_nsub + 1;
4400 /* Information on the contents of registers. These are pointers into
4401 the input strings; they record just what was matched (on this
4402 attempt) by a subexpression part of the pattern, that is, the
4403 regnum-th regstart pointer points to where in the pattern we began
4404 matching and the regnum-th regend points to right after where we
4405 stopped matching the regnum-th subexpression. (The zeroth register
4406 keeps track of what the whole pattern matches.) */
4407 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4408 re_char **regstart, **regend;
4411 /* The following record the register info as found in the above
4412 variables when we find a match better than any we've seen before.
4413 This happens as we backtrack through the failure points, which in
4414 turn happens only if we have not yet matched the entire string. */
4415 unsigned best_regs_set = false;
4416 #ifdef MATCH_MAY_ALLOCATE /* otherwise, these are global. */
4417 re_char **best_regstart, **best_regend;
4420 /* Logically, this is `best_regend[0]'. But we don't want to have to
4421 allocate space for that if we're not allocating space for anything
4422 else (see below). Also, we never need info about register 0 for
4423 any of the other register vectors, and it seems rather a kludge to
4424 treat `best_regend' differently than the rest. So we keep track of
4425 the end of the best match so far in a separate variable. We
4426 initialize this to NULL so that when we backtrack the first time
4427 and need to test it, it's not garbage. */
4428 re_char *match_end = NULL;
4431 /* Counts the total number of registers pushed. */
4432 unsigned num_regs_pushed = 0;
4435 DEBUG_PRINT1 ("\n\nEntering re_match_2.\n");
4439 #ifdef MATCH_MAY_ALLOCATE
4440 /* Do not bother to initialize all the register variables if there are
4441 no groups in the pattern, as it takes a fair amount of time. If
4442 there are groups, we include space for register 0 (the whole
4443 pattern), even though we never use it, since it simplifies the
4444 array indexing. We should fix this. */
4447 regstart = REGEX_TALLOC (num_regs, re_char *);
4448 regend = REGEX_TALLOC (num_regs, re_char *);
4449 best_regstart = REGEX_TALLOC (num_regs, re_char *);
4450 best_regend = REGEX_TALLOC (num_regs, re_char *);
4452 if (!(regstart && regend && best_regstart && best_regend))
4460 /* We must initialize all our variables to NULL, so that
4461 `FREE_VARIABLES' doesn't try to free them. */
4462 regstart = regend = best_regstart = best_regend = NULL;
4464 #endif /* MATCH_MAY_ALLOCATE */
4466 /* The starting position is bogus. */
4467 if (pos < 0 || pos > size1 + size2)
4473 /* Initialize subexpression text positions to -1 to mark ones that no
4474 start_memory/stop_memory has been seen for. Also initialize the
4475 register information struct. */
4476 for (mcnt = 1; mcnt < num_regs; mcnt++)
4477 regstart[mcnt] = regend[mcnt] = REG_UNSET_VALUE;
4479 /* Shorten strings to `stop'. */
4485 else if (stop <= size1 + size2)
4486 size2 = stop - size1;
4488 /* We move `string1' into `string2' if the latter's empty -- but not if
4489 `string1' is null. */
4490 if (size2 == 0 && string1 != NULL)
4497 end1 = string1 + size1;
4498 end2 = string2 + size2;
4500 /* Compute where to stop matching, within the two strings. */
4504 /* `p' scans through the pattern as `d' scans through the data.
4505 `dend' is the end of the input string that `d' points within. `d'
4506 is advanced into the following input string whenever necessary, but
4507 this happens before fetching; therefore, at the beginning of the
4508 loop, `d' can be pointing at the end of a string, but it cannot
4510 if (size1 > 0 && pos <= size1)
4517 d = string2 + pos - size1;
4521 DEBUG_PRINT1 ("The compiled pattern is: ");
4522 DEBUG_PRINT_COMPILED_PATTERN (bufp, p, pend);
4523 DEBUG_PRINT1 ("The string to match is: `");
4524 DEBUG_PRINT_DOUBLE_STRING (d, string1, size1, string2, size2);
4525 DEBUG_PRINT1 ("'\n");
4527 /* This loops over pattern commands. It exits by returning from the
4528 function if the match is complete, or it drops through if the match
4529 fails at this starting point in the input data. */
4532 DEBUG_PRINT2 ("\n%p: ", p);
4535 { /* End of pattern means we might have succeeded. */
4536 DEBUG_PRINT1 ("end of pattern ... ");
4538 /* If we haven't matched the entire string, and we want the
4539 longest match, try backtracking. */
4540 if (d != end_match_2)
4542 /* 1 if this match ends in the same string (string1 or string2)
4543 as the best previous match. */
4544 boolean same_str_p = (FIRST_STRING_P (match_end)
4545 == FIRST_STRING_P (d));
4546 /* 1 if this match is the best seen so far. */
4547 boolean best_match_p;
4549 /* AIX compiler got confused when this was combined
4550 with the previous declaration. */
4552 best_match_p = d > match_end;
4554 best_match_p = !FIRST_STRING_P (d);
4556 DEBUG_PRINT1 ("backtracking.\n");
4558 if (!FAIL_STACK_EMPTY ())
4559 { /* More failure points to try. */
4561 /* If exceeds best match so far, save it. */
4562 if (!best_regs_set || best_match_p)
4564 best_regs_set = true;
4567 DEBUG_PRINT1 ("\nSAVING match as best so far.\n");
4569 for (mcnt = 1; mcnt < num_regs; mcnt++)
4571 best_regstart[mcnt] = regstart[mcnt];
4572 best_regend[mcnt] = regend[mcnt];
4578 /* If no failure points, don't restore garbage. And if
4579 last match is real best match, don't restore second
4581 else if (best_regs_set && !best_match_p)
4584 /* Restore best match. It may happen that `dend ==
4585 end_match_1' while the restored d is in string2.
4586 For example, the pattern `x.*y.*z' against the
4587 strings `x-' and `y-z-', if the two strings are
4588 not consecutive in memory. */
4589 DEBUG_PRINT1 ("Restoring best registers.\n");
4592 dend = ((d >= string1 && d <= end1)
4593 ? end_match_1 : end_match_2);
4595 for (mcnt = 1; mcnt < num_regs; mcnt++)
4597 regstart[mcnt] = best_regstart[mcnt];
4598 regend[mcnt] = best_regend[mcnt];
4601 } /* d != end_match_2 */
4604 DEBUG_PRINT1 ("Accepting match.\n");
4606 /* If caller wants register contents data back, do it. */
4607 if (regs && !bufp->no_sub)
4609 /* Have the register data arrays been allocated? */
4610 if (bufp->regs_allocated == REGS_UNALLOCATED)
4611 { /* No. So allocate them with malloc. We need one
4612 extra element beyond `num_regs' for the `-1' marker
4614 regs->num_regs = MAX (RE_NREGS, num_regs + 1);
4615 regs->start = TALLOC (regs->num_regs, regoff_t);
4616 regs->end = TALLOC (regs->num_regs, regoff_t);
4617 if (regs->start == NULL || regs->end == NULL)
4622 bufp->regs_allocated = REGS_REALLOCATE;
4624 else if (bufp->regs_allocated == REGS_REALLOCATE)
4625 { /* Yes. If we need more elements than were already
4626 allocated, reallocate them. If we need fewer, just
4628 if (regs->num_regs < num_regs + 1)
4630 regs->num_regs = num_regs + 1;
4631 RETALLOC (regs->start, regs->num_regs, regoff_t);
4632 RETALLOC (regs->end, regs->num_regs, regoff_t);
4633 if (regs->start == NULL || regs->end == NULL)
4642 /* These braces fend off a "empty body in an else-statement"
4643 warning under GCC when assert expands to nothing. */
4644 assert (bufp->regs_allocated == REGS_FIXED);
4647 /* Convert the pointer data in `regstart' and `regend' to
4648 indices. Register zero has to be set differently,
4649 since we haven't kept track of any info for it. */
4650 if (regs->num_regs > 0)
4652 regs->start[0] = pos;
4653 regs->end[0] = POINTER_TO_OFFSET (d);
4656 /* Go through the first `min (num_regs, regs->num_regs)'
4657 registers, since that is all we initialized. */
4658 for (mcnt = 1; mcnt < MIN (num_regs, regs->num_regs); mcnt++)
4660 if (REG_UNSET (regstart[mcnt]) || REG_UNSET (regend[mcnt]))
4661 regs->start[mcnt] = regs->end[mcnt] = -1;
4665 = (regoff_t) POINTER_TO_OFFSET (regstart[mcnt]);
4667 = (regoff_t) POINTER_TO_OFFSET (regend[mcnt]);
4671 /* If the regs structure we return has more elements than
4672 were in the pattern, set the extra elements to -1. If
4673 we (re)allocated the registers, this is the case,
4674 because we always allocate enough to have at least one
4676 for (mcnt = num_regs; mcnt < regs->num_regs; mcnt++)
4677 regs->start[mcnt] = regs->end[mcnt] = -1;
4678 } /* regs && !bufp->no_sub */
4680 DEBUG_PRINT4 ("%u failure points pushed, %u popped (%u remain).\n",
4681 nfailure_points_pushed, nfailure_points_popped,
4682 nfailure_points_pushed - nfailure_points_popped);
4683 DEBUG_PRINT2 ("%u registers pushed.\n", num_regs_pushed);
4685 mcnt = POINTER_TO_OFFSET (d) - pos;
4687 DEBUG_PRINT2 ("Returning %d from re_match_2.\n", mcnt);
4693 /* Otherwise match next pattern command. */
4694 switch (SWITCH_ENUM_CAST ((re_opcode_t) *p++))
4696 /* Ignore these. Used to ignore the n of succeed_n's which
4697 currently have n == 0. */
4699 DEBUG_PRINT1 ("EXECUTING no_op.\n");
4703 DEBUG_PRINT1 ("EXECUTING succeed.\n");
4706 /* Match the next n pattern characters exactly. The following
4707 byte in the pattern defines n, and the n bytes after that
4708 are the characters to match. */
4711 DEBUG_PRINT2 ("EXECUTING exactn %d.\n", mcnt);
4713 /* Remember the start point to rollback upon failure. */
4716 /* This is written out as an if-else so we don't waste time
4717 testing `translate' inside the loop. */
4718 if (RE_TRANSLATE_P (translate))
4724 int pat_charlen, buf_charlen;
4725 unsigned int pat_ch, buf_ch;
4728 pat_ch = STRING_CHAR_AND_LENGTH (p, pend - p, pat_charlen);
4729 buf_ch = STRING_CHAR_AND_LENGTH (d, dend - d, buf_charlen);
4731 if (RE_TRANSLATE (translate, buf_ch)
4740 mcnt -= pat_charlen;
4744 #endif /* not emacs */
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");
4785 buf_ch = STRING_CHAR_AND_LENGTH (d, dend - d, buf_charlen);
4787 #endif /* not emacs */
4793 buf_ch = TRANSLATE (buf_ch);
4795 if ((!(bufp->syntax & RE_DOT_NEWLINE)
4797 || ((bufp->syntax & RE_DOT_NOT_NULL)
4798 && buf_ch == '\000'))
4801 DEBUG_PRINT2 (" Matched `%d'.\n", *d);
4810 register unsigned int c;
4811 boolean not = (re_opcode_t) *(p - 1) == charset_not;
4814 /* Start of actual range_table, or end of bitmap if there is no
4816 unsigned char *range_table;
4818 /* Nonzero if there is a range table. */
4819 int range_table_exists;
4821 /* Number of ranges of range table. This is not included
4822 in the initial byte-length of the command. */
4825 DEBUG_PRINT2 ("EXECUTING charset%s.\n", not ? "_not" : "");
4830 range_table_exists = CHARSET_RANGE_TABLE_EXISTS_P (&p[-1]);
4833 if (range_table_exists)
4835 range_table = CHARSET_RANGE_TABLE (&p[-1]); /* Past the bitmap. */
4836 EXTRACT_NUMBER_AND_INCR (count, range_table);
4839 if (multibyte && BASE_LEADING_CODE_P (c))
4840 c = STRING_CHAR_AND_LENGTH (d, dend - d, len);
4843 if (SINGLE_BYTE_CHAR_P (c))
4844 { /* Lookup bitmap. */
4845 c = TRANSLATE (c); /* The character to match. */
4848 /* Cast to `unsigned' instead of `unsigned char' in
4849 case the bit list is a full 32 bytes long. */
4850 if (c < (unsigned) (CHARSET_BITMAP_SIZE (&p[-1]) * BYTEWIDTH)
4851 && p[1 + c / BYTEWIDTH] & (1 << (c % BYTEWIDTH)))
4855 else if (range_table_exists)
4857 int class_bits = CHARSET_RANGE_TABLE_BITS (&p[-1]);
4859 if ( (class_bits & BIT_ALNUM && ISALNUM (c))
4860 | (class_bits & BIT_ALPHA && ISALPHA (c))
4861 | (class_bits & BIT_ASCII && IS_REAL_ASCII (c))
4862 | (class_bits & BIT_GRAPH && ISGRAPH (c))
4863 | (class_bits & BIT_LOWER && ISLOWER (c))
4864 | (class_bits & BIT_MULTIBYTE && !ISUNIBYTE (c))
4865 | (class_bits & BIT_NONASCII && !IS_REAL_ASCII (c))
4866 | (class_bits & BIT_PRINT && ISPRINT (c))
4867 | (class_bits & BIT_PUNCT && ISPUNCT (c))
4868 | (class_bits & BIT_SPACE && ISSPACE (c))
4869 | (class_bits & BIT_UNIBYTE && ISUNIBYTE (c))
4870 | (class_bits & BIT_UPPER && ISUPPER (c))
4871 | (class_bits & BIT_WORD && ISWORD (c)))
4874 CHARSET_LOOKUP_RANGE_TABLE_RAW (not, c, range_table, count);
4878 if (range_table_exists)
4879 p = CHARSET_RANGE_TABLE_END (range_table, count);
4881 p += CHARSET_BITMAP_SIZE (&p[-1]) + 1;
4883 if (!not) goto fail;
4890 /* The beginning of a group is represented by start_memory.
4891 The argument is the register number. The text
4892 matched within the group is recorded (in the internal
4893 registers data structure) under the register number. */
4895 DEBUG_PRINT2 ("EXECUTING start_memory %d:\n", *p);
4897 /* In case we need to undo this operation (via backtracking). */
4898 PUSH_FAILURE_REG ((unsigned int)*p);
4901 regend[*p] = REG_UNSET_VALUE; /* probably unnecessary. -sm */
4902 DEBUG_PRINT2 (" regstart: %d\n", POINTER_TO_OFFSET (regstart[*p]));
4904 /* Move past the register number and inner group count. */
4909 /* The stop_memory opcode represents the end of a group. Its
4910 argument is the same as start_memory's: the register number. */
4912 DEBUG_PRINT2 ("EXECUTING stop_memory %d:\n", *p);
4914 assert (!REG_UNSET (regstart[*p]));
4915 /* Strictly speaking, there should be code such as:
4917 assert (REG_UNSET (regend[*p]));
4918 PUSH_FAILURE_REGSTOP ((unsigned int)*p);
4920 But the only info to be pushed is regend[*p] and it is known to
4921 be UNSET, so there really isn't anything to push.
4922 Not pushing anything, on the other hand deprives us from the
4923 guarantee that regend[*p] is UNSET since undoing this operation
4924 will not reset its value properly. This is not important since
4925 the value will only be read on the next start_memory or at
4926 the very end and both events can only happen if this stop_memory
4930 DEBUG_PRINT2 (" regend: %d\n", POINTER_TO_OFFSET (regend[*p]));
4932 /* Move past the register number and the inner group count. */
4937 /* \<digit> has been turned into a `duplicate' command which is
4938 followed by the numeric value of <digit> as the register number. */
4941 register re_char *d2, *dend2;
4942 int regno = *p++; /* Get which register to match against. */
4943 DEBUG_PRINT2 ("EXECUTING duplicate %d.\n", regno);
4945 /* Can't back reference a group which we've never matched. */
4946 if (REG_UNSET (regstart[regno]) || REG_UNSET (regend[regno]))
4949 /* Where in input to try to start matching. */
4950 d2 = regstart[regno];
4952 /* Remember the start point to rollback upon failure. */
4955 /* Where to stop matching; if both the place to start and
4956 the place to stop matching are in the same string, then
4957 set to the place to stop, otherwise, for now have to use
4958 the end of the first string. */
4960 dend2 = ((FIRST_STRING_P (regstart[regno])
4961 == FIRST_STRING_P (regend[regno]))
4962 ? regend[regno] : end_match_1);
4965 /* If necessary, advance to next segment in register
4969 if (dend2 == end_match_2) break;
4970 if (dend2 == regend[regno]) break;
4972 /* End of string1 => advance to string2. */
4974 dend2 = regend[regno];
4976 /* At end of register contents => success */
4977 if (d2 == dend2) break;
4979 /* If necessary, advance to next segment in data. */
4982 /* How many characters left in this segment to match. */
4985 /* Want how many consecutive characters we can match in
4986 one shot, so, if necessary, adjust the count. */
4987 if (mcnt > dend2 - d2)
4990 /* Compare that many; failure if mismatch, else move
4992 if (RE_TRANSLATE_P (translate)
4993 ? bcmp_translate (d, d2, mcnt, translate)
4994 : bcmp (d, d2, mcnt))
4999 d += mcnt, d2 += mcnt;
5005 /* begline matches the empty string at the beginning of the string
5006 (unless `not_bol' is set in `bufp'), and, if
5007 `newline_anchor' is set, after newlines. */
5009 DEBUG_PRINT1 ("EXECUTING begline.\n");
5011 if (AT_STRINGS_BEG (d))
5013 if (!bufp->not_bol) break;
5015 else if (d[-1] == '\n' && bufp->newline_anchor)
5019 /* In all other cases, we fail. */
5023 /* endline is the dual of begline. */
5025 DEBUG_PRINT1 ("EXECUTING endline.\n");
5027 if (AT_STRINGS_END (d))
5029 if (!bufp->not_eol) break;
5032 /* We have to ``prefetch'' the next character. */
5033 else if ((d == end1 ? *string2 : *d) == '\n'
5034 && bufp->newline_anchor)
5041 /* Match at the very beginning of the data. */
5043 DEBUG_PRINT1 ("EXECUTING begbuf.\n");
5044 if (AT_STRINGS_BEG (d))
5049 /* Match at the very end of the data. */
5051 DEBUG_PRINT1 ("EXECUTING endbuf.\n");
5052 if (AT_STRINGS_END (d))
5057 /* on_failure_keep_string_jump is used to optimize `.*\n'. It
5058 pushes NULL as the value for the string on the stack. Then
5059 `POP_FAILURE_POINT' will keep the current value for the
5060 string, instead of restoring it. To see why, consider
5061 matching `foo\nbar' against `.*\n'. The .* matches the foo;
5062 then the . fails against the \n. But the next thing we want
5063 to do is match the \n against the \n; if we restored the
5064 string value, we would be back at the foo.
5066 Because this is used only in specific cases, we don't need to
5067 check all the things that `on_failure_jump' does, to make
5068 sure the right things get saved on the stack. Hence we don't
5069 share its code. The only reason to push anything on the
5070 stack at all is that otherwise we would have to change
5071 `anychar's code to do something besides goto fail in this
5072 case; that seems worse than this. */
5073 case on_failure_keep_string_jump:
5074 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5075 DEBUG_PRINT3 ("EXECUTING on_failure_keep_string_jump %d (to %p):\n",
5078 PUSH_FAILURE_POINT (p - 3, NULL);
5081 /* A nasty loop is introduced by the non-greedy *? and +?.
5082 With such loops, the stack only ever contains one failure point
5083 at a time, so that a plain on_failure_jump_loop kind of
5084 cycle detection cannot work. Worse yet, such a detection
5085 can not only fail to detect a cycle, but it can also wrongly
5086 detect a cycle (between different instantiations of the same
5088 So the method used for those nasty loops is a little different:
5089 We use a special cycle-detection-stack-frame which is pushed
5090 when the on_failure_jump_nastyloop failure-point is *popped*.
5091 This special frame thus marks the beginning of one iteration
5092 through the loop and we can hence easily check right here
5093 whether something matched between the beginning and the end of
5095 case on_failure_jump_nastyloop:
5096 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5097 DEBUG_PRINT3 ("EXECUTING on_failure_jump_nastyloop %d (to %p):\n",
5100 assert ((re_opcode_t)p[-4] == no_op);
5101 CHECK_INFINITE_LOOP (p - 4, d);
5102 PUSH_FAILURE_POINT (p - 3, d);
5106 /* Simple loop detecting on_failure_jump: just check on the
5107 failure stack if the same spot was already hit earlier. */
5108 case on_failure_jump_loop:
5110 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5111 DEBUG_PRINT3 ("EXECUTING on_failure_jump_loop %d (to %p):\n",
5114 CHECK_INFINITE_LOOP (p - 3, d);
5115 PUSH_FAILURE_POINT (p - 3, d);
5119 /* Uses of on_failure_jump:
5121 Each alternative starts with an on_failure_jump that points
5122 to the beginning of the next alternative. Each alternative
5123 except the last ends with a jump that in effect jumps past
5124 the rest of the alternatives. (They really jump to the
5125 ending jump of the following alternative, because tensioning
5126 these jumps is a hassle.)
5128 Repeats start with an on_failure_jump that points past both
5129 the repetition text and either the following jump or
5130 pop_failure_jump back to this on_failure_jump. */
5131 case on_failure_jump:
5133 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5134 DEBUG_PRINT3 ("EXECUTING on_failure_jump %d (to %p):\n",
5137 PUSH_FAILURE_POINT (p -3, d);
5140 /* This operation is used for greedy *.
5141 Compare the beginning of the repeat with what in the
5142 pattern follows its end. If we can establish that there
5143 is nothing that they would both match, i.e., that we
5144 would have to backtrack because of (as in, e.g., `a*a')
5145 then we can use a non-backtracking loop based on
5146 on_failure_keep_string_jump instead of on_failure_jump. */
5147 case on_failure_jump_smart:
5149 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5150 DEBUG_PRINT3 ("EXECUTING on_failure_jump_smart %d (to %p).\n",
5153 unsigned char *p1 = p; /* Next operation. */
5154 unsigned char *p2 = p + mcnt; /* Destination of the jump. */
5156 p -= 3; /* Reset so that we will re-execute the
5157 instruction once it's been changed. */
5159 EXTRACT_NUMBER (mcnt, p2 - 2);
5161 /* Ensure this is a indeed the trivial kind of loop
5162 we are expecting. */
5163 assert (skip_one_char (p1) == p2 - 3);
5164 assert ((re_opcode_t) p2[-3] == jump && p2 + mcnt == p);
5165 DEBUG_STATEMENT (debug += 2);
5166 if (mutually_exclusive_p (bufp, p1, p2))
5168 /* Use a fast `on_failure_keep_string_jump' loop. */
5169 DEBUG_PRINT1 (" smart exclusive => fast loop.\n");
5170 *p = (unsigned char) on_failure_keep_string_jump;
5171 STORE_NUMBER (p2 - 2, mcnt + 3);
5175 /* Default to a safe `on_failure_jump' loop. */
5176 DEBUG_PRINT1 (" smart default => slow loop.\n");
5177 *p = (unsigned char) on_failure_jump;
5179 DEBUG_STATEMENT (debug -= 2);
5183 /* Unconditionally jump (without popping any failure points). */
5187 EXTRACT_NUMBER_AND_INCR (mcnt, p); /* Get the amount to jump. */
5188 DEBUG_PRINT2 ("EXECUTING jump %d ", mcnt);
5189 p += mcnt; /* Do the jump. */
5190 DEBUG_PRINT2 ("(to %p).\n", p);
5194 /* Have to succeed matching what follows at least n times.
5195 After that, handle like `on_failure_jump'. */
5197 EXTRACT_NUMBER (mcnt, p + 2);
5198 DEBUG_PRINT2 ("EXECUTING succeed_n %d.\n", mcnt);
5201 /* Originally, this is how many times we HAVE to succeed. */
5206 STORE_NUMBER_AND_INCR (p, mcnt);
5207 DEBUG_PRINT3 (" Setting %p to %d.\n", p, mcnt);
5211 DEBUG_PRINT2 (" Setting two bytes from %p to no_op.\n", p+2);
5212 p[2] = (unsigned char) no_op;
5213 p[3] = (unsigned char) no_op;
5219 EXTRACT_NUMBER (mcnt, p + 2);
5220 DEBUG_PRINT2 ("EXECUTING jump_n %d.\n", mcnt);
5222 /* Originally, this is how many times we CAN jump. */
5226 STORE_NUMBER (p + 2, mcnt);
5227 goto unconditional_jump;
5229 /* If don't have to jump any more, skip over the rest of command. */
5236 DEBUG_PRINT1 ("EXECUTING set_number_at.\n");
5238 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5240 EXTRACT_NUMBER_AND_INCR (mcnt, p);
5241 DEBUG_PRINT3 (" Setting %p to %d.\n", p1, mcnt);
5242 STORE_NUMBER (p1, mcnt);
5248 not = (re_opcode_t) *(p - 1) == notwordbound;
5249 DEBUG_PRINT2 ("EXECUTING %swordbound.\n", not?"not":"");
5251 /* We SUCCEED (or FAIL) in one of the following cases: */
5253 /* Case 1: D is at the beginning or the end of string. */
5254 if (AT_STRINGS_BEG (d) || AT_STRINGS_END (d))
5258 /* C1 is the character before D, S1 is the syntax of C1, C2
5259 is the character at D, and S2 is the syntax of C2. */
5262 int charpos = SYNTAX_TABLE_BYTE_TO_CHAR (PTR_TO_OFFSET (d - 1));
5263 UPDATE_SYNTAX_TABLE (charpos);
5265 /* FIXME: This does a STRING_CHAR even for unibyte buffers. */
5266 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
5269 UPDATE_SYNTAX_TABLE_FORWARD (charpos + 1);
5272 /* FIXME: This does a STRING_CHAR even for unibyte buffers. */
5273 c2 = STRING_CHAR (d, dend - d);
5276 if (/* Case 2: Only one of S1 and S2 is Sword. */
5277 ((s1 == Sword) != (s2 == Sword))
5278 /* Case 3: Both of S1 and S2 are Sword, and macro
5279 WORD_BOUNDARY_P (C1, C2) returns nonzero. */
5280 || ((s1 == Sword) && WORD_BOUNDARY_P (c1, c2)))
5289 DEBUG_PRINT1 ("EXECUTING wordbeg.\n");
5291 /* We FAIL in one of the following cases: */
5293 /* Case 1: D is at the end of string. */
5294 if (AT_STRINGS_END (d))
5298 /* C1 is the character before D, S1 is the syntax of C1, C2
5299 is the character at D, and S2 is the syntax of C2. */
5302 int charpos = SYNTAX_TABLE_BYTE_TO_CHAR (PTR_TO_OFFSET (d));
5303 UPDATE_SYNTAX_TABLE (charpos);
5306 /* FIXME: This does a STRING_CHAR even for unibyte buffers. */
5307 c2 = STRING_CHAR (d, dend - d);
5310 /* Case 2: S2 is not Sword. */
5314 /* Case 3: D is not at the beginning of string ... */
5315 if (!AT_STRINGS_BEG (d))
5317 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
5319 UPDATE_SYNTAX_TABLE_BACKWARD (charpos - 1);
5323 /* ... and S1 is Sword, and WORD_BOUNDARY_P (C1, C2)
5325 if ((s1 == Sword) && !WORD_BOUNDARY_P (c1, c2))
5332 DEBUG_PRINT1 ("EXECUTING wordend.\n");
5334 /* We FAIL in one of the following cases: */
5336 /* Case 1: D is at the beginning of string. */
5337 if (AT_STRINGS_BEG (d))
5341 /* C1 is the character before D, S1 is the syntax of C1, C2
5342 is the character at D, and S2 is the syntax of C2. */
5345 int charpos = SYNTAX_TABLE_BYTE_TO_CHAR (PTR_TO_OFFSET (d) - 1);
5346 UPDATE_SYNTAX_TABLE (charpos);
5348 GET_CHAR_BEFORE_2 (c1, d, string1, end1, string2, end2);
5351 /* Case 2: S1 is not Sword. */
5355 /* Case 3: D is not at the end of string ... */
5356 if (!AT_STRINGS_END (d))
5359 /* FIXME: This does a STRING_CHAR even for unibyte buffers. */
5360 c2 = STRING_CHAR (d, dend - d);
5362 UPDATE_SYNTAX_TABLE_FORWARD (charpos);
5366 /* ... and S2 is Sword, and WORD_BOUNDARY_P (C1, C2)
5368 if ((s2 == Sword) && !WORD_BOUNDARY_P (c1, c2))
5376 not = (re_opcode_t) *(p - 1) == notsyntaxspec;
5378 DEBUG_PRINT3 ("EXECUTING %ssyntaxspec %d.\n", not?"not":"", mcnt);
5382 int pos1 = SYNTAX_TABLE_BYTE_TO_CHAR (PTR_TO_OFFSET (d));
5383 UPDATE_SYNTAX_TABLE (pos1);
5390 /* we must concern about multibyte form, ... */
5391 c = STRING_CHAR_AND_LENGTH (d, dend - d, len);
5393 /* everything should be handled as ASCII, even though it
5394 looks like multibyte form. */
5397 if ((SYNTAX (c) != (enum syntaxcode) mcnt) ^ not)
5405 DEBUG_PRINT1 ("EXECUTING before_dot.\n");
5406 if (PTR_BYTE_POS (d) >= PT_BYTE)
5411 DEBUG_PRINT1 ("EXECUTING at_dot.\n");
5412 if (PTR_BYTE_POS (d) != PT_BYTE)
5417 DEBUG_PRINT1 ("EXECUTING after_dot.\n");
5418 if (PTR_BYTE_POS (d) <= PT_BYTE)
5423 case notcategoryspec:
5424 not = (re_opcode_t) *(p - 1) == notcategoryspec;
5426 DEBUG_PRINT3 ("EXECUTING %scategoryspec %d.\n", not?"not":"", mcnt);
5432 c = STRING_CHAR_AND_LENGTH (d, dend - d, len);
5436 if ((!CHAR_HAS_CATEGORY (c, mcnt)) ^ not)
5447 continue; /* Successfully executed one pattern command; keep going. */
5450 /* We goto here if a matching operation fails. */
5453 if (!FAIL_STACK_EMPTY ())
5457 /* A restart point is known. Restore to that state. */
5458 DEBUG_PRINT1 ("\nFAIL:\n");
5459 POP_FAILURE_POINT (str, pat);
5460 switch (SWITCH_ENUM_CAST ((re_opcode_t) *pat++))
5462 case on_failure_keep_string_jump:
5463 assert (str == NULL);
5464 goto continue_failure_jump;
5466 case on_failure_jump_nastyloop:
5467 assert ((re_opcode_t)pat[-2] == no_op);
5468 PUSH_FAILURE_POINT (pat - 2, str);
5471 case on_failure_jump_loop:
5472 case on_failure_jump:
5475 continue_failure_jump:
5476 EXTRACT_NUMBER_AND_INCR (mcnt, pat);
5481 /* A special frame used for nastyloops. */
5488 assert (p >= bufp->buffer && p <= pend);
5490 if (d >= string1 && d <= end1)
5494 break; /* Matching at this starting point really fails. */
5498 goto restore_best_regs;
5502 return -1; /* Failure to match. */
5505 /* Subroutine definitions for re_match_2. */
5507 /* Return zero if TRANSLATE[S1] and TRANSLATE[S2] are identical for LEN
5508 bytes; nonzero otherwise. */
5511 bcmp_translate (s1, s2, len, translate)
5512 unsigned char *s1, *s2;
5514 RE_TRANSLATE_TYPE translate;
5516 register unsigned char *p1 = s1, *p2 = s2;
5517 unsigned char *p1_end = s1 + len;
5518 unsigned char *p2_end = s2 + len;
5520 while (p1 != p1_end && p2 != p2_end)
5522 int p1_charlen, p2_charlen;
5525 /* FIXME: This assumes `multibyte = true'. */
5526 p1_ch = STRING_CHAR_AND_LENGTH (p1, p1_end - p1, p1_charlen);
5527 p2_ch = STRING_CHAR_AND_LENGTH (p2, p2_end - p2, p2_charlen);
5529 if (RE_TRANSLATE (translate, p1_ch)
5530 != RE_TRANSLATE (translate, p2_ch))
5533 p1 += p1_charlen, p2 += p2_charlen;
5536 if (p1 != p1_end || p2 != p2_end)
5542 /* Entry points for GNU code. */
5544 /* re_compile_pattern is the GNU regular expression compiler: it
5545 compiles PATTERN (of length SIZE) and puts the result in BUFP.
5546 Returns 0 if the pattern was valid, otherwise an error string.
5548 Assumes the `allocated' (and perhaps `buffer') and `translate' fields
5549 are set in BUFP on entry.
5551 We call regex_compile to do the actual compilation. */
5554 re_compile_pattern (pattern, length, bufp)
5555 const char *pattern;
5557 struct re_pattern_buffer *bufp;
5561 /* GNU code is written to assume at least RE_NREGS registers will be set
5562 (and at least one extra will be -1). */
5563 bufp->regs_allocated = REGS_UNALLOCATED;
5565 /* And GNU code determines whether or not to get register information
5566 by passing null for the REGS argument to re_match, etc., not by
5570 /* Match anchors at newline. */
5571 bufp->newline_anchor = 1;
5573 ret = regex_compile (pattern, length, re_syntax_options, bufp);
5577 return gettext (re_error_msgid[(int) ret]);
5580 /* Entry points compatible with 4.2 BSD regex library. We don't define
5581 them unless specifically requested. */
5583 #if defined (_REGEX_RE_COMP) || defined (_LIBC)
5585 /* BSD has one and only one pattern buffer. */
5586 static struct re_pattern_buffer re_comp_buf;
5590 /* Make these definitions weak in libc, so POSIX programs can redefine
5591 these names if they don't use our functions, and still use
5592 regcomp/regexec below without link errors. */
5602 if (!re_comp_buf.buffer)
5603 return gettext ("No previous regular expression");
5607 if (!re_comp_buf.buffer)
5609 re_comp_buf.buffer = (unsigned char *) malloc (200);
5610 if (re_comp_buf.buffer == NULL)
5611 return gettext (re_error_msgid[(int) REG_ESPACE]);
5612 re_comp_buf.allocated = 200;
5614 re_comp_buf.fastmap = (char *) malloc (1 << BYTEWIDTH);
5615 if (re_comp_buf.fastmap == NULL)
5616 return gettext (re_error_msgid[(int) REG_ESPACE]);
5619 /* Since `re_exec' always passes NULL for the `regs' argument, we
5620 don't need to initialize the pattern buffer fields which affect it. */
5622 /* Match anchors at newlines. */
5623 re_comp_buf.newline_anchor = 1;
5625 ret = regex_compile (s, strlen (s), re_syntax_options, &re_comp_buf);
5630 /* Yes, we're discarding `const' here if !HAVE_LIBINTL. */
5631 return (char *) gettext (re_error_msgid[(int) ret]);
5642 const int len = strlen (s);
5644 0 <= re_search (&re_comp_buf, s, len, 0, len, (struct re_registers *) 0);
5646 #endif /* _REGEX_RE_COMP */
5648 /* POSIX.2 functions. Don't define these for Emacs. */
5652 /* regcomp takes a regular expression as a string and compiles it.
5654 PREG is a regex_t *. We do not expect any fields to be initialized,
5655 since POSIX says we shouldn't. Thus, we set
5657 `buffer' to the compiled pattern;
5658 `used' to the length of the compiled pattern;
5659 `syntax' to RE_SYNTAX_POSIX_EXTENDED if the
5660 REG_EXTENDED bit in CFLAGS is set; otherwise, to
5661 RE_SYNTAX_POSIX_BASIC;
5662 `newline_anchor' to REG_NEWLINE being set in CFLAGS;
5663 `fastmap' and `fastmap_accurate' to zero;
5664 `re_nsub' to the number of subexpressions in PATTERN.
5666 PATTERN is the address of the pattern string.
5668 CFLAGS is a series of bits which affect compilation.
5670 If REG_EXTENDED is set, we use POSIX extended syntax; otherwise, we
5671 use POSIX basic syntax.
5673 If REG_NEWLINE is set, then . and [^...] don't match newline.
5674 Also, regexec will try a match beginning after every newline.
5676 If REG_ICASE is set, then we considers upper- and lowercase
5677 versions of letters to be equivalent when matching.
5679 If REG_NOSUB is set, then when PREG is passed to regexec, that
5680 routine will report only success or failure, and nothing about the
5683 It returns 0 if it succeeds, nonzero if it doesn't. (See regex.h for
5684 the return codes and their meanings.) */
5687 regcomp (preg, pattern, cflags)
5689 const char *pattern;
5694 = (cflags & REG_EXTENDED) ?
5695 RE_SYNTAX_POSIX_EXTENDED : RE_SYNTAX_POSIX_BASIC;
5697 /* regex_compile will allocate the space for the compiled pattern. */
5699 preg->allocated = 0;
5702 /* Don't bother to use a fastmap when searching. This simplifies the
5703 REG_NEWLINE case: if we used a fastmap, we'd have to put all the
5704 characters after newlines into the fastmap. This way, we just try
5708 if (cflags & REG_ICASE)
5713 = (RE_TRANSLATE_TYPE) malloc (CHAR_SET_SIZE
5714 * sizeof (*(RE_TRANSLATE_TYPE)0));
5715 if (preg->translate == NULL)
5716 return (int) REG_ESPACE;
5718 /* Map uppercase characters to corresponding lowercase ones. */
5719 for (i = 0; i < CHAR_SET_SIZE; i++)
5720 preg->translate[i] = ISUPPER (i) ? tolower (i) : i;
5723 preg->translate = NULL;
5725 /* If REG_NEWLINE is set, newlines are treated differently. */
5726 if (cflags & REG_NEWLINE)
5727 { /* REG_NEWLINE implies neither . nor [^...] match newline. */
5728 syntax &= ~RE_DOT_NEWLINE;
5729 syntax |= RE_HAT_LISTS_NOT_NEWLINE;
5730 /* It also changes the matching behavior. */
5731 preg->newline_anchor = 1;
5734 preg->newline_anchor = 0;
5736 preg->no_sub = !!(cflags & REG_NOSUB);
5738 /* POSIX says a null character in the pattern terminates it, so we
5739 can use strlen here in compiling the pattern. */
5740 ret = regex_compile (pattern, strlen (pattern), syntax, preg);
5742 /* POSIX doesn't distinguish between an unmatched open-group and an
5743 unmatched close-group: both are REG_EPAREN. */
5744 if (ret == REG_ERPAREN) ret = REG_EPAREN;
5750 /* regexec searches for a given pattern, specified by PREG, in the
5753 If NMATCH is zero or REG_NOSUB was set in the cflags argument to
5754 `regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
5755 least NMATCH elements, and we set them to the offsets of the
5756 corresponding matched substrings.
5758 EFLAGS specifies `execution flags' which affect matching: if
5759 REG_NOTBOL is set, then ^ does not match at the beginning of the
5760 string; if REG_NOTEOL is set, then $ does not match at the end.
5762 We return 0 if we find a match and REG_NOMATCH if not. */
5765 regexec (preg, string, nmatch, pmatch, eflags)
5766 const regex_t *preg;
5769 regmatch_t pmatch[];
5773 struct re_registers regs;
5774 regex_t private_preg;
5775 int len = strlen (string);
5776 boolean want_reg_info = !preg->no_sub && nmatch > 0;
5778 private_preg = *preg;
5780 private_preg.not_bol = !!(eflags & REG_NOTBOL);
5781 private_preg.not_eol = !!(eflags & REG_NOTEOL);
5783 /* The user has told us exactly how many registers to return
5784 information about, via `nmatch'. We have to pass that on to the
5785 matching routines. */
5786 private_preg.regs_allocated = REGS_FIXED;
5790 regs.num_regs = nmatch;
5791 regs.start = TALLOC (nmatch, regoff_t);
5792 regs.end = TALLOC (nmatch, regoff_t);
5793 if (regs.start == NULL || regs.end == NULL)
5794 return (int) REG_NOMATCH;
5797 /* Perform the searching operation. */
5798 ret = re_search (&private_preg, string, len,
5799 /* start: */ 0, /* range: */ len,
5800 want_reg_info ? ®s : (struct re_registers *) 0);
5802 /* Copy the register information to the POSIX structure. */
5809 for (r = 0; r < nmatch; r++)
5811 pmatch[r].rm_so = regs.start[r];
5812 pmatch[r].rm_eo = regs.end[r];
5816 /* If we needed the temporary register info, free the space now. */
5821 /* We want zero return to mean success, unlike `re_search'. */
5822 return ret >= 0 ? (int) REG_NOERROR : (int) REG_NOMATCH;
5826 /* Returns a message corresponding to an error code, ERRCODE, returned
5827 from either regcomp or regexec. We don't use PREG here. */
5830 regerror (errcode, preg, errbuf, errbuf_size)
5832 const regex_t *preg;
5840 || errcode >= (sizeof (re_error_msgid) / sizeof (re_error_msgid[0])))
5841 /* Only error codes returned by the rest of the code should be passed
5842 to this routine. If we are given anything else, or if other regex
5843 code generates an invalid error code, then the program has a bug.
5844 Dump core so we can fix it. */
5847 msg = gettext (re_error_msgid[errcode]);
5849 msg_size = strlen (msg) + 1; /* Includes the null. */
5851 if (errbuf_size != 0)
5853 if (msg_size > errbuf_size)
5855 strncpy (errbuf, msg, errbuf_size - 1);
5856 errbuf[errbuf_size - 1] = 0;
5859 strcpy (errbuf, msg);
5866 /* Free dynamically allocated space used by PREG. */
5872 if (preg->buffer != NULL)
5873 free (preg->buffer);
5874 preg->buffer = NULL;
5876 preg->allocated = 0;
5879 if (preg->fastmap != NULL)
5880 free (preg->fastmap);
5881 preg->fastmap = NULL;
5882 preg->fastmap_accurate = 0;
5884 if (preg->translate != NULL)
5885 free (preg->translate);
5886 preg->translate = NULL;
5889 #endif /* not emacs */